Repository: nvaccess/nvda

Issue:
Braille fails to work when used in triggered profile after closing Windows Explorer 
### Steps to reproduce:
1. Create a triggered profile for notepad, set a braille display in it in my case Focus 40 Blue and ensure that it is active only in this profile.
2. Open Windows Explorer with Windows+e.
3. Close it with alt+f4 focus lands in notepad.
### Actual behavior:
Braille display fails to work and the following is written in the log.
Loaded braille display driver freedomScientific, current display has 40 cells.
ERROR - braille.BrailleHandler.setDisplayByName (17:55:47.686):
Error initializing display driver for kwargs {'port': u'auto'}
Traceback (most recent call last):
  File "braille.pyo", line 1680, in setDisplayByName
  File "braille.pyo", line 1962, in initialDisplay
  File "braille.pyo", line 1826, in handleGainFocus
  File "braille.pyo", line 1831, in _doNewObject
  File "braille.pyo", line 1478, in getFocusContextRegions
  File "baseObject.pyo", line 34, in __get__
  File "baseObject.pyo", line 115, in _getPropertyViaCache
  File "NVDAObjects\__init__.pyo", line 819, in _get_isPresentableFocusAncestor
  File "baseObject.pyo", line 34, in __get__
  File "baseObject.pyo", line 115, in _getPropertyViaCache
  File "NVDAObjects\UIA\__init__.pyo", line 1127, in _get_presentationType
  File "baseObject.pyo", line 34, in __get__
  File "baseObject.pyo", line 115, in _getPropertyViaCache
  File "NVDAObjects\__init__.pyo", line 637, in _get_presentationType
  File "baseObject.pyo", line 34, in __get__
  File "baseObject.pyo", line 115, in _getPropertyViaCache
  File "NVDAObjects\UIA\__init__.pyo", line 1067, in _get_states
  File "NVDAObjects\UIA\__init__.pyo", line 734, in _prefetchUIACacheForPropertyIDs
COMError: (-2147220991, 'An event was unable to invoke any of the subscribers', (None, None, None, 0, None))

### Expected behavior:
Braille should work normaly after closing Windows Explorer.

### System configuration:

#### NVDA Installed/portable/running from source:
Installed
#### NVDA version:
alpha-16183,c3ce6a38
#### Windows version:
Windows 7 x64
#### Name and version of other software in use when reproducing the issue:
Notepad, Windows Explorer
#### Other information about your system:
I've tested also with new native driver written by @bramd and the issue is present there as well. Switching to the desktop and back to notepad makes display work again.
### Other questions:

#### Does the issue still occur after restarting your PC?
Yes
#### Have you tried any other versions of NVDA?
Yes 2018.3.2 and the problem is present.



Discussion:
To clarify:
* Do you also experience this problem if you go from another program to Notepad, say from WordPad or Calculator or Paint, etc?
* Do you have this particular braille display selected in the braille profile or did you choose auto-detection?
@dkager wrote
> 
> 
> To clarify:
> 
>     * Do you also experience this problem if you go from another program to Notepad, say from WordPad or Calculator or Paint, etc?
> 
No it fails only when closing Windows Explorer and previously opened window was the app with an active braille display.

>      * Do you have this particular braille display selected in the braille profile or did you choose auto-detection?


The display in question is Focus 40 Blue, so it cannot be autodetected. The display is selected. I've tested with the new native driver and when display is selected in the profile explicitly it fails as well, but when it is set to autodetect everything is working
Further testing shows, that it is working in NVDA 2018.2 and failing in NVDA 2018.3 and later. @leonardder as an author of most braille related changes in NVDA can you please take a look.
The error in your log isn't related to braille at all, i.e. it is an UIA error.
Even if it is technically an UIA error it is happening only when braille display is connected and  it only affects  braille i.e braille no longer works after this happens until the profile with braille display is retriggeret.
I've bisected it and the result are as follows
846a998b363fd5abaf447e5148bc272fefdf161c is the first bad commit
commit 846a998b363fd5abaf447e5148bc272fefdf161c
Author: Leonard de Ruijter <leonardder@users.noreply.github.com>
Date:   Tue Jul 17 08:57:13 2018 +0200

    Add automatic background braille display detection (#7741)

    * Implement braille display auto detection. This new background mechanism can be activated by choosing the Automatic option from NVDA's braille display settings. See #1271 for an in depth di
scussion of funcionality.

    * brailliantB, use generic implementation for USB serial devices
    * Use generic check function for braille display drivers supporting bdDetect
    * Make auto detection the default
    * Set a timeout for joining the bgThread when auto detection was on
    * Poll for bluetooth devices on app switches
    * Support bluetooth HID in bdDetect

    * Use a separate thread for background scanning.

    * Make the bdDetect thread a daemon thread

    * Disable auto detection within the unit test framework. If we don't do this, detection will occur and unit tests will fail.

    * in braille.handler.handleGainFocus, check whether the focused object has an active tree interceptor. If so, focus the tree interceptor instead

    * Revert the use a separate thread for background scanning and make sure recursion does not occur when using an APC

    This reverts commit 5b97f3952348fe80db8ab06b1e9a008c105d48d0.

    * Created Detector._scanQueuedSafe which wraps changing the state of _scanQueued within a lock

    * Fix malformed VID and PID for Brailliant, add an extra check

    * NO longer filter serial ports for Brailliant

    * Updated changes.t2t

:040000 040000 29fe29d5f7367cb6d0688e66116cd7099c2656a0 c454198d7891d067a759e54e091e407bde710430 M  source
:040000 040000 3c8740f95b7a4e5abfa2f584e4435a9004687a99 55433fe8a8293f6b800c5903fb6fe8a4836046ca M  tests
:040000 040000 1d65a9f0571d0125a412c02b29c49e0e4f36488e 6ac25f866fad775e150a5e0e0b5ba6f750c3c865 M  user_docs
Mm. I will mark this as a regression and will try to reproduce this locally. Also a p2 to investigate.
I actually found the bug

Resolving patch:
diff --git a/source/braille.py b/source/braille.py
--- a/source/braille.py
+++ b/source/braille.py
@@ -1695,7 +1695,14 @@ def setDisplayByName(self, name, isFallback=False, detected=None):
 			else: # detected:
 				self._disableDetection()
 			log.info("Loaded braille display driver %s, current display has %d cells." %(name, self.displaySize))
-			self.initialDisplay()
+			try:
+				self.initialDisplay()
+			except:
+				# #8877: initialDisplay might fail because NVDA tries to focus
+				# an object for which property fetching raises an exception.
+				# We should handle this more gracefully, since this is no reason
+				# to stop a display from loading successfully.
+				log.debugWarning("Error in initial display after display load", exc_info=True)
 			return True
 		except:
 			# For auto display detection, logging an error for every failure is too obnoxious.


Test patch: