├── manifest-translated.ini.tpl ├── .gitmodules ├── msrUtil ├── log.txt ├── SConstruct ├── SConscript └── msr_util.cpp ├── manifest.ini.tpl ├── .gitignore ├── addon ├── skipTranslation.py ├── appModules │ ├── dragonbar.py │ ├── speechuxwiz.py │ └── natspeak.py ├── globalPlugins │ └── dictation │ │ ├── dictationGesture.py │ │ └── __init__.py └── installTasks.py ├── .gitattributes ├── style.css ├── README.md ├── site_scons └── site_tools │ └── gettexttool │ └── __init__.py ├── sconstruct └── COPYING.txt /manifest-translated.ini.tpl: -------------------------------------------------------------------------------- 1 | summary = "{addon_summary}" 2 | description = """{addon_description}""" 3 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "dictationbridge-core"] 2 | path = dictationbridge-core 3 | url = http://github.com/dictationbridge/dictationbridge-core 4 | -------------------------------------------------------------------------------- /msrUtil/log.txt: -------------------------------------------------------------------------------- 1 | hello 2 | r 3 | e 4 | v 5 | i 6 | e 7 | w 8 | _ 9 | c 10 | u 11 | r 12 | r 13 | e 14 | n 15 | t 16 | L 17 | i 18 | n 19 | e 20 | review_currentLine 21 | -------------------------------------------------------------------------------- /manifest.ini.tpl: -------------------------------------------------------------------------------- 1 | name = {addon_name} 2 | summary = "{addon_summary}" 3 | description = """{addon_description}""" 4 | author = "{addon_author}" 5 | url = {addon_url} 6 | version = {addon_version} 7 | docFileName = {addon_docFileName} 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | addon/doc/*.css 2 | addon/doc/en/ 3 | *_docHandler.py 4 | *.html 5 | *.ini 6 | *.mo 7 | *.pot 8 | *.pyc 9 | *.nvda-addon 10 | .sconsign.dblite 11 | *.dll 12 | *.exe 13 | *.pdb 14 | *.lib 15 | *.exp 16 | *.obj 17 | .vscode 18 | *.xml 19 | *.WSRMac 20 | -------------------------------------------------------------------------------- /msrUtil/SConstruct: -------------------------------------------------------------------------------- 1 | env = Environment(HOST_ARCH = 'x86') 2 | 3 | env.Append(CXXFLAGS=['/EHsc']) 4 | 5 | msr_util = env.Program('msr_util', 'msr_util.cpp', 6 | LIBS = 'DictationBridgeClient32', 7 | LIBPATH = '../dictationbridge-core/build/x86/client', 8 | #LINKFLAGS = "/SUBSYSTEM:WINDOWS", 9 | ) 10 | -------------------------------------------------------------------------------- /msrUtil/SConscript: -------------------------------------------------------------------------------- 1 | env = Environment(HOST_ARCH = 'x86') 2 | 3 | env.Append(CXXFLAGS=['/EHsc']) 4 | 5 | msr_util = env.Program('msr_util', 'msr_util.cpp', 6 | LIBS = 'DictationBridgeClient32', 7 | LIBPATH = '../dictationbridge-core/build/x86/client', 8 | #LINKFLAGS = "/SUBSYSTEM:WINDOWS", 9 | ) 10 | 11 | Return(['msr_util']) -------------------------------------------------------------------------------- /addon/skipTranslation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | # skipTranslation: Module to get translated texts from NVDA 3 | # Based on implementation made by Alberto Buffolino 4 | # https://github.com/nvaccess/nvda/issues/4652 5 | #Copyright (C) 2016 Noelia Ruiz Martínez 6 | # Released under GPL 2 7 | 8 | def translate(text): 9 | return _(text) 10 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set default behaviour, in case users don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Try to ensure that po files in the repo does not include 5 | # source code line numbers. 6 | # Every person expected to commit po files should change their personal config file as described here: 7 | # https://mail.gnome.org/archives/kupfer-list/2010-June/msg00002.html 8 | *.po filter=cleanpo 9 | -------------------------------------------------------------------------------- /msrUtil/msr_util.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "../dictationbridge-core/client/client.h" 4 | 5 | bool isValid(char c){ 6 | if(' ' == c) return false; 7 | if('|' == c) return true; 8 | if('_' == c) return true; 9 | return isalpha((int)c) || isdigit((int)c); 10 | } 11 | 12 | int CALLBACK WinMain(_In_ HINSTANCE hInstance, 13 | _In_ HINSTANCE hPrevInstance, 14 | _In_ LPSTR lpCmdLine, 15 | _In_ int nCmdShow) { 16 | int i=0; 17 | while(lpCmdLine[i] != '\0'){ 18 | if(!isValid(lpCmdLine[i++])) return 1; 19 | } 20 | DB_SendCommand(lpCmdLine); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /style.css: -------------------------------------------------------------------------------- 1 | @charset "utf-8"; 2 | body { 3 | font-family : Verdana, Arial, Helvetica, Sans-serif; 4 | color : #FFFFFF; 5 | background-color : #000000; 6 | line-height: 1.2em; 7 | } 8 | h1, h2 {text-align: center} 9 | dt { 10 | font-weight : bold; 11 | float : left; 12 | width: 10%; 13 | clear: left 14 | } 15 | dd { 16 | margin : 0 0 0.4em 0; 17 | float : left; 18 | width: 90%; 19 | display: block; 20 | } 21 | p { clear : both; 22 | } 23 | a { text-decoration : underline; 24 | } 25 | :active { 26 | text-decoration : none; 27 | } 28 | a:focus, a:hover {outline: solid} 29 | :link {color: #0000FF; 30 | background-color: #FFFFFF} 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DictationBridge NVDA add-on 2 | 3 | This is the NVDA add-on package for DictationBridge. It depends on the [screen-reader-independent core](https://github.com/dictationbridge/dictationbridge-core). 4 | 5 | Support for Dragon NaturallySpeaking is still under heavy development. 6 | 7 | ## Building 8 | 9 | To build the add-on, you need Python 2.7, a recent version of SCons, and Visual Studio 2015. 10 | 11 | First, fetch Git submodules with this command: 12 | 13 | git submodule update --init --recursive 14 | 15 | Then simply run SCons. 16 | 17 | ## Copyright and license 18 | 19 | Copyright 2016 3 Mouse Technology, LLC. This software is provided under the GNU General Public License, version 2. 20 | -------------------------------------------------------------------------------- /addon/appModules/dragonbar.py: -------------------------------------------------------------------------------- 1 | from appModuleHandler import AppModule 2 | import controlTypes 3 | import ui 4 | import re 5 | from comtypes import COMError 6 | 7 | class AppModule(AppModule): 8 | lastFlashRightText = None 9 | 10 | def flashRightTextChanged(self, obj): 11 | text = obj.name 12 | if not text: 13 | return 14 | if self.lastFlashRightText == text: 15 | return 16 | self.lastFlashRightText = text 17 | mOff="Dragon\'s microphone is off;" 18 | mOn="Normal mode: You can dictate and use voice" 19 | mSleep="The microphone is asleep;" 20 | if mOn in text: 21 | ui.message("Dragon mic on") 22 | elif mOff in text: 23 | ui.message("Dragon mic off") 24 | elif mSleep in text: 25 | ui.message("Dragon sleeping") 26 | 27 | def event_nameChange(self, obj, nextHandler): 28 | try: 29 | automationId = obj.UIAElement.currentAutomationID 30 | except: 31 | automationId = None 32 | if automationId == "txtFlashRight": 33 | self.flashRightTextChanged(obj) 34 | nextHandler() 35 | 36 | RE_BAD_MENU_ITEMS= re.compile(r"^mi_?("+"|".join([ 37 | "Top", 38 | "Profile", 39 | "Tools", 40 | "Vocabulary", 41 | "Audio", 42 | "Help", 43 | ])+")$") 44 | def event_NVDAObject_init(self, obj): 45 | try: 46 | automationId = obj.UIAElement.CachedAutomationID 47 | except (COMError, AttributeError): 48 | return 49 | if automationId == u'cbRecognitionMode': 50 | #Fix a combobox with no label. 51 | obj.name = obj.previous.name 52 | if self.RE_BAD_MENU_ITEMS.match(automationId): 53 | obj.role = controlTypes.ROLE_MENU 54 | -------------------------------------------------------------------------------- /site_scons/site_tools/gettexttool/__init__.py: -------------------------------------------------------------------------------- 1 | """ This tool allows generation of gettext .mo compiled files, pot files from source code files 2 | and pot files for merging. 3 | 4 | Three new builders are added into the constructed environment: 5 | 6 | - gettextMoFile: generates .mo file from .pot file using msgfmt. 7 | - gettextPotFile: Generates .pot file from source code files. 8 | - gettextMergePotFile: Creates a .pot file appropriate for merging into existing .po files. 9 | 10 | To properly configure get text, define the following variables: 11 | 12 | - gettext_package_bugs_address 13 | - gettext_package_name 14 | - gettext_package_version 15 | 16 | 17 | """ 18 | from SCons.Action import Action 19 | 20 | def exists(env): 21 | return True 22 | 23 | XGETTEXT_COMMON_ARGS = ( 24 | "--msgid-bugs-address='$gettext_package_bugs_address' " 25 | "--package-name='$gettext_package_name' " 26 | "--package-version='$gettext_package_version' " 27 | "-c -o $TARGET $SOURCES" 28 | ) 29 | 30 | def generate(env): 31 | env.SetDefault(gettext_package_bugs_address="example@example.com") 32 | env.SetDefault(gettext_package_name="") 33 | env.SetDefault(gettext_package_version="") 34 | 35 | env['BUILDERS']['gettextMoFile']=env.Builder( 36 | action=Action("msgfmt -o $TARGET $SOURCE", "Compiling translation $SOURCE"), 37 | suffix=".mo", 38 | src_suffix=".po" 39 | ) 40 | 41 | env['BUILDERS']['gettextPotFile']=env.Builder( 42 | action=Action("xgettext " + XGETTEXT_COMMON_ARGS, "Generating pot file $TARGET"), 43 | suffix=".pot") 44 | 45 | env['BUILDERS']['gettextMergePotFile']=env.Builder( 46 | action=Action("xgettext " + "--omit-header --no-location " + XGETTEXT_COMMON_ARGS, 47 | "Generating pot file $TARGET"), 48 | suffix=".pot") 49 | 50 | -------------------------------------------------------------------------------- /addon/appModules/speechuxwiz.py: -------------------------------------------------------------------------------- 1 | from appModuleHandler import AppModule 2 | import api 3 | import controlTypes 4 | import tones 5 | import ui 6 | import windowUtils 7 | from NVDAObjects.behaviors import Dialog 8 | from NVDAObjects.UIA import UIA 9 | import NVDAObjects 10 | import winUser 11 | import time 12 | from logHandler import log 13 | 14 | class Wizard(Dialog): 15 | role = controlTypes.ROLE_DIALOG 16 | 17 | class AppModule(AppModule): 18 | def chooseNVDAObjectOverlayClasses(self, obj, clsList): 19 | if obj.windowClassName == "NativeHWNDHost" and obj.role == controlTypes.ROLE_PANE: 20 | clsList.insert(0, Wizard) 21 | 22 | def event_NVDAObject_init(self, obj): 23 | #When waiting for a second or two on the headset microphone radio button, an unwanted window gains focus. 24 | if obj.role == controlTypes.ROLE_WINDOW and isinstance(obj, UIA) and obj.UIAElement.cachedClassName == u'CCRadioButton': 25 | obj.shouldAllowUIAFocusEvent = False 26 | if obj.role == controlTypes.ROLE_STATICTEXT and obj.description: 27 | obj.description = None 28 | 29 | def readTrainingText(self): 30 | window = api.getForegroundObject() 31 | for descendant in window.recursiveDescendants: 32 | if not isinstance(descendant, UIA): 33 | continue 34 | try: 35 | automationID = descendant.UIAElement.currentAutomationID 36 | except: 37 | continue 38 | if automationID == "txttrain": 39 | api.setNavigatorObject(descendant) 40 | ui.message(descendant.name) 41 | break 42 | 43 | def script_readTrainingText(self, gesture): 44 | self.readTrainingText() 45 | 46 | __gestures = { 47 | "kb:`": "readTrainingText", 48 | } 49 | 50 | def event_nameChange(self, obj, nextHandler): 51 | if obj.role == controlTypes.ROLE_STATICTEXT and obj.windowClassName == "DirectUIHWND": 52 | self.readTrainingText() 53 | nextHandler() 54 | 55 | def event_valueChange(self, obj, nextHandler): 56 | if obj.role == controlTypes.ROLE_PROGRESSBAR: 57 | self.readTrainingText() 58 | nextHandler() 59 | -------------------------------------------------------------------------------- /addon/globalPlugins/dictation/dictationGesture.py: -------------------------------------------------------------------------------- 1 | import time 2 | import functools 3 | import api 4 | import globalCommands 5 | import inputCore 6 | import scriptHandler 7 | 8 | class DictationGesture(inputCore.InputGesture): 9 | _internalID = "" 10 | _scriptCount = 1 11 | 12 | 13 | def __init__(self, action): 14 | super(DictationGesture, self).__init__() 15 | count = 1 16 | if "|" in action: 17 | action,count = action.split("|") 18 | self._internalID = action 19 | self._scriptCount = int(count) 20 | 21 | def _get_identifiers(self): 22 | return ["db:{identifier}".format(identifier=self._internalID)] 23 | 24 | def _get_displayName(self): 25 | #fix me: Wouldn't it be nice to return the proper speech? 26 | id = list(self._internalID) 27 | for index, char in enumerate(id): 28 | if char == "_": 29 | id[index] = " " 30 | continue 31 | id[index] = char.lower() 32 | return "".join(id) 33 | 34 | def _getScriptFromObject(self, obj): 35 | func = getattr(obj, "script_%s" %self._internalID, None) 36 | return func 37 | 38 | def scriptWrapper(self, script, gesture): 39 | scriptHandler._lastScriptCount = gesture._scriptCount-1 40 | script(gesture) 41 | 42 | def _get_script_hacky(self): 43 | #Workaround until DB 1.1 when I fix NVDA to not need repeated scripts. 44 | #Mostly based on scriptHandler.findScript, but no globalGestureMapness 45 | focus = api.getFocusObject() 46 | if not focus: 47 | return None 48 | 49 | ti = focus.treeInterceptor 50 | if ti: 51 | func = self._getScriptFromObject(ti) 52 | if func and (not ti.passThrough or getattr(func,"ignoreTreeInterceptorPassThrough",False)): 53 | return (func, ti) 54 | 55 | # NVDAObject level. 56 | func = self._getScriptFromObject(focus) 57 | if func: 58 | return (func, focus) 59 | for obj in reversed(api.getFocusAncestors()): 60 | func = self._getScriptFromObject(obj) 61 | if func and getattr(func, 'canPropagate', False): 62 | return (func, obj) 63 | 64 | # Global commands. 65 | func = self._getScriptFromObject(globalCommands.commands) 66 | if func: 67 | return (func, globalCommands.commands) 68 | 69 | def _get_script(self): 70 | if inputCore.manager.isInputHelpActive: 71 | #Don't send it through the hack, because there's no useful help message for it. 72 | return self.script_hacky[0] 73 | else: 74 | script = self.script_hacky 75 | if script is None: 76 | return 77 | wrappedScript = functools.partial(self.scriptWrapper, script[0]) 78 | try: 79 | wrappedScript.resumeSayAllMode = script[0].resumeSayAllMode 80 | except AttributeError: 81 | pass 82 | return wrappedScript -------------------------------------------------------------------------------- /addon/installTasks.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | from ctypes import wintypes 3 | import os 4 | import sys 5 | import _winreg 6 | import addonHandler 7 | from logHandler import log 8 | import winUser 9 | import config 10 | #Don't rely on win32con constants, they might be disappearing in NVDA soon. 11 | HWND_BROADCAST=0xffff 12 | WM_SETTINGCHANGE = 0x1a 13 | 14 | 15 | def sendMessageTimeout(hwnd, msg, wParam, lParam, flags=0, timeout=5000): 16 | dwResult = wintypes.DWORD() 17 | lResult = ctypes.windll.user32.SendMessageTimeoutW(hwnd, msg, wParam, lParam, flags, timeout, ctypes.byref(dwResult)) 18 | return lResult, dwResult 19 | 20 | def onInstall(postPathBug = False): 21 | #Add ourself to the path, so that commands when spoken can be queried to us. 22 | #Only if we are truely installing though. 23 | addons = [] 24 | if not postPathBug: 25 | addons = addonHandler.getAvailableAddons() 26 | for addon in addons: 27 | if addon.name=="DictationBridge": 28 | #Hack to work around condition where 29 | #the uninstaller removes this addon from the path 30 | #After the installer for the updator ran. 31 | #We could use version specific directories, but wsr macros Does not 32 | #play nice with refreshing the path environment after path updates, 33 | # requiring a complete reboot of wsr, or commands spontaneously break cripticly. 34 | with open(os.path.join(config.getUserDefaultConfigPath(), ".dbInstall"), 35 | "w") as fi: 36 | fi.write("dbInstall") 37 | return 38 | key = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, "Environment", 0, _winreg.KEY_READ | _winreg.KEY_WRITE) 39 | try: 40 | value, typ = _winreg.QueryValueEx(key, "Path") 41 | except: 42 | value, typ = None, _winreg.REG_EXPAND_SZ 43 | if value is None: 44 | value = "" 45 | dir = os.path.dirname(__file__) 46 | if not isinstance(dir, unicode): 47 | dir = dir.decode(sys.getfilesystemencoding()) 48 | dir = dir.replace(addonHandler.ADDON_PENDINGINSTALL_SUFFIX, "") 49 | log.info("addon directory: %r" % dir) 50 | log.info("current PATH: %r" % value) 51 | if value.lower().find(dir.lower()) == -1: 52 | if value != "": 53 | value += ";" 54 | value += dir 55 | log.info("new PATH: %r" % value) 56 | _winreg.SetValueEx(key, "Path", None, typ, value) 57 | sendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u"Environment") 58 | def onUninstall(): 59 | path = os.path.join(config.getUserDefaultConfigPath(), ".dbInstall") 60 | if os.path.exists(path): 61 | #This is an update. Bail. 62 | os.remove(path) 63 | return 64 | key = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER, "Environment", 0, _winreg.KEY_READ | _winreg.KEY_WRITE) 65 | try: 66 | value, typ = _winreg.QueryValueEx(key, "Path") 67 | except: 68 | return 69 | if value is None or value == "": 70 | return 71 | dir = os.path.dirname(__file__) 72 | if not isinstance(dir, unicode): 73 | dir = dir.decode(sys.getfilesystemencoding()) 74 | dir = dir.replace(addonHandler.DELETEDIR_SUFFIX, "") 75 | if value.find(dir) != -1: 76 | value = value.replace(";" + dir, "") 77 | value = value.replace(dir + ";", "") 78 | value = value.replace(dir, "") 79 | _winreg.SetValueEx(key, "Path", None, typ, value) 80 | sendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u"Environment") 81 | -------------------------------------------------------------------------------- /addon/appModules/natspeak.py: -------------------------------------------------------------------------------- 1 | import time 2 | import os 3 | import sys 4 | import appModuleHandler 5 | import speech 6 | import NVDAObjects 7 | import eventHandler 8 | from NVDAObjects import NVDAObject 9 | from NVDAObjects.window import Window 10 | from NVDAObjects.behaviors import ProgressBar 11 | from logHandler import log 12 | import controlTypes 13 | import colors 14 | import textInfos 15 | import ui 16 | from winUser import user32 17 | sys.path.append(os.path.dirname(os.path.dirname(__file__))) 18 | from skipTranslation import translate 19 | sys.path.remove(sys.path[-1]) 20 | 21 | 22 | class CustomList(NVDAObjects.NVDAObject): 23 | """ 24 | A display model list for the dragon vocabulary editor. 25 | """ 26 | 27 | columnNumber = 0 28 | role = controlTypes.ROLE_LIST 29 | #Translators: The name of the vocabulary items list in the vocabulary editor for Dragon. 30 | _name = _("Vocabulary Items") 31 | _addHeaderNextTime = False 32 | 33 | def _get_name(self): 34 | name = self._name 35 | name += " " 36 | name += self.columnHeaders[self.columnNumber] 37 | return name 38 | 39 | def _get_columnHeaders(self): 40 | ti = self.makeTextInfo(textInfos.POSITION_FIRST) 41 | ti.expand(textInfos.UNIT_LINE) 42 | #[Format Field, Header1, format field, column spacer, Format Field, header2.] 43 | columnInfo = ti.getTextWithFields() 44 | #second and last item. 45 | return (columnInfo[1], columnInfo[-1]) 46 | 47 | def _get_value(self): 48 | try: 49 | ti = self.parent.makeTextInfo(textInfos.POSITION_SELECTION) 50 | except LookupError: 51 | return 52 | base = "" 53 | if self._addHeaderNextTime: 54 | base = self.columnHeaders[self.columnNumber] + " " 55 | self._addHeaderNextTime= False 56 | fields = ti.getTextWithFields() 57 | #Second, and last. First is a format field. 58 | fields = fields[1], fields[-1] 59 | base += fields[self.columnNumber] 60 | return base 61 | 62 | def script_moved(self, gesture): 63 | gesture.send() 64 | #It seems to take time to refresh. 65 | time.sleep(.05) 66 | eventHandler.executeEvent("valueChange", self) 67 | 68 | def _movementHelper(self, dir): 69 | if ( 70 | (dir and self.columnNumber == 1) or 71 | (not dir and self.columnNumber==0)): 72 | ui.message(translate("Edge of table")) 73 | return 74 | if dir == 0: 75 | self.columnNumber-=1 76 | elif dir == 1: 77 | self.columnNumber+=1 78 | self._addHeaderNextTime = True 79 | eventHandler.executeEvent("valueChange", self) 80 | 81 | def script_right(self, gesture): 82 | self._movementHelper(1) 83 | 84 | def script_left(self, gesture): 85 | self._movementHelper(0) 86 | 87 | def getScript(self, gesture): 88 | #let's make quick nav single letter nav work! 89 | if len(gesture.identifiers[-1].lstrip("kb:" )) == 1: 90 | return self.script_moved 91 | return super(CustomList, self).getScript(gesture) 92 | 93 | __gestures = { 94 | "kb:upArrow" : "moved", 95 | "kb:downArrow" : "moved", 96 | "kb:pageUp" : "moved", 97 | "kb:pageDown" : "moved", 98 | "kb:home" : "moved", 99 | "kb:end" : "moved", 100 | "kb:rightArrow" : "right", 101 | "kb:leftArrow" : "left", 102 | } 103 | 104 | class AppModule(appModuleHandler.AppModule): 105 | lastMicText = None 106 | 107 | 108 | def handleMicText(self, text): 109 | if text == self.lastMicText: 110 | return 111 | mOff="Dragon\'s microphone is off;" 112 | mOn="Normal mode: You can dictate and use voice" 113 | mSleep="The microphone is asleep;" 114 | if mOn in text: 115 | self.lastMicText = text 116 | ui.message("Dragon mic on") 117 | elif mOff in text: 118 | self.lastMicText = text 119 | ui.message("Dragon mic off") 120 | elif mSleep in text: 121 | self.lastMicText = text 122 | ui.message("Dragon sleeping") 123 | 124 | def event_nameChange(self, obj, nextHandler): 125 | if obj.windowControlID == 61923 and obj.windowClassName == u"Static": 126 | text = obj.name or "" 127 | self.handleMicText(text) 128 | nextHandler() 129 | 130 | def chooseNVDAObjectOverlayClasses (self, obj, clsList): 131 | if obj.windowClassName == u'CustomListBox': 132 | clsList.insert(0, CustomList) 133 | #The setup wizard uses progress bars to indicate mic status. 134 | #This is potentially annoying, as the user is trying to speak, and hearing progress bars is distracting. 135 | try: 136 | if obj.windowClassName == u'msctls_progress32' and ( 137 | (obj.parent.parent.role == controlTypes.ROLE_LIST) or 138 | (obj.windowControlID == 1148) 139 | ): 140 | clsList.remove(ProgressBar) 141 | except ValueError: 142 | pass 143 | 144 | def event_NVDAObject_init(self, obj): 145 | if obj.role == controlTypes.ROLE_BUTTON and obj.name == "" and obj.windowClassName == u'Button': 146 | #Turnary statements aren't used because it'll break translation. 147 | if obj.windowControlID == 202: 148 | #Translators: Button title for the dictation box settings. 149 | obj.name = _("Dictation Box Settings") 150 | elif obj.windowControlID == 9: 151 | #Translators: The Dictation boxes help button label. 152 | obj.name = _("Help") 153 | -------------------------------------------------------------------------------- /sconstruct: -------------------------------------------------------------------------------- 1 | # NVDA add-on template SCONSTRUCT file 2 | #Copyright (C) 2012, 2014 Rui Batista 3 | #This file is covered by the GNU General Public License. 4 | #See the file COPYING.txt for more details. 5 | 6 | import codecs 7 | import gettext 8 | import os 9 | import os.path 10 | import zipfile 11 | 12 | import buildVars 13 | 14 | 15 | def md2html(source, dest): 16 | import markdown 17 | lang = os.path.basename(os.path.dirname(source)).replace('_', '-') 18 | title="{addonSummary} {addonVersion}".format(addonSummary=buildVars.addon_info["addon_summary"], addonVersion=buildVars.addon_info["addon_version"]) 19 | headerDic = { 20 | "[[!meta title=\"": "# ", 21 | "\"]]": " #", 22 | } 23 | with codecs.open(source, "r", "utf-8") as f: 24 | mdText = f.read() 25 | for k, v in headerDic.iteritems(): 26 | mdText = mdText.replace(k, v, 1) 27 | htmlText = markdown.markdown(mdText) 28 | with codecs.open(dest, "w", "utf-8") as f: 29 | f.write("\n" + 30 | "\n" + 32 | "\n" % (lang, lang) + 33 | "\n" + 34 | "\n" + 35 | "\n" + 36 | "%s\n" % title + 37 | "\n\n" 38 | ) 39 | f.write(htmlText) 40 | f.write("\n\n") 41 | 42 | def mdTool(env): 43 | mdAction=env.Action( 44 | lambda target,source,env: md2html(source[0].path, target[0].path), 45 | lambda target,source,env: 'Generating %s'%target[0], 46 | ) 47 | mdBuilder=env.Builder( 48 | action=mdAction, 49 | suffix='.html', 50 | src_suffix='.md', 51 | ) 52 | env['BUILDERS']['markdown']=mdBuilder 53 | 54 | vars = Variables() 55 | env = Environment(variables = vars, ENV=os.environ, tools=['gettexttool', mdTool]) 56 | 57 | env.Append(**buildVars.addon_info) 58 | 59 | addonFile = env.File("${addon_name}-${addon_version}.nvda-addon") 60 | 61 | def addonGenerator(target, source, env, for_signature): 62 | action = env.Action(lambda target, source, env : createAddonBundleFromPath(source[0].abspath, target[0].abspath) and None, 63 | lambda target, source, env : "Generating Addon %s" % target[0]) 64 | return action 65 | 66 | def manifestGenerator(target, source, env, for_signature): 67 | action = env.Action(lambda target, source, env : generateManifest(source[0].abspath, target[0].abspath) and None, 68 | lambda target, source, env : "Generating manifest %s" % target[0]) 69 | return action 70 | 71 | def translatedManifestGenerator(target, source, env, for_signature): 72 | dir = os.path.abspath(os.path.join(os.path.dirname(str(source[0])), "..")) 73 | lang = os.path.basename(dir) 74 | action = env.Action(lambda target, source, env : generateTranslatedManifest(source[1].abspath, lang, target[0].abspath) and None, 75 | lambda target, source, env : "Generating translated manifest %s" % target[0]) 76 | return action 77 | 78 | env['BUILDERS']['NVDAAddon'] = Builder(generator=addonGenerator) 79 | env['BUILDERS']['NVDAManifest'] = Builder(generator=manifestGenerator) 80 | env['BUILDERS']['NVDATranslatedManifest'] = Builder(generator=translatedManifestGenerator) 81 | 82 | def createAddonHelp(dir): 83 | docsDir = os.path.join(dir, "doc") 84 | if os.path.isfile("style.css"): 85 | cssPath = os.path.join(docsDir, "style.css") 86 | cssTarget = env.Command(cssPath, "style.css", Copy("$TARGET", "$SOURCE")) 87 | env.Depends(addon, cssTarget) 88 | if os.path.isfile("readme.md"): 89 | readmePath = os.path.join(docsDir, "en", "readme.md") 90 | readmeTarget = env.Command(readmePath, "readme.md", Copy("$TARGET", "$SOURCE")) 91 | env.Depends(addon, readmeTarget) 92 | 93 | def createAddonBundleFromPath(path, dest): 94 | """ Creates a bundle from a directory that contains an addon manifest file.""" 95 | basedir = os.path.abspath(path) 96 | with zipfile.ZipFile(dest, 'w', zipfile.ZIP_DEFLATED) as z: 97 | # FIXME: the include/exclude feature may or may not be useful. Also python files can be pre-compiled. 98 | for dir, dirnames, filenames in os.walk(basedir): 99 | relativePath = os.path.relpath(dir, basedir) 100 | for filename in filenames: 101 | pathInBundle = os.path.join(relativePath, filename) 102 | absPath = os.path.join(dir, filename) 103 | if pathInBundle not in buildVars.excludedFiles: z.write(absPath, pathInBundle) 104 | return dest 105 | 106 | def generateManifest(source, dest): 107 | with codecs.open(source, "r", "utf-8") as f: 108 | manifest_template = f.read() 109 | manifest = manifest_template.format(**buildVars.addon_info) 110 | with codecs.open(dest, "w", "utf-8") as f: 111 | f.write(manifest) 112 | 113 | def generateTranslatedManifest(source, language, out): 114 | _ = gettext.translation("nvda", localedir=os.path.join("addon", "locale"), languages=[language]).ugettext 115 | vars = {} 116 | for var in ("addon_summary", "addon_description"): 117 | vars[var] = _(buildVars.addon_info[var]) 118 | with codecs.open(source, "r", "utf-8") as f: 119 | manifest_template = f.read() 120 | result = manifest_template.format(**vars) 121 | with codecs.open(out, "w", "utf-8") as f: 122 | f.write(result) 123 | 124 | def expandGlobs(files): 125 | return [f for pattern in files for f in env.Glob(pattern)] 126 | 127 | addon = env.NVDAAddon(addonFile, env.Dir('addon')) 128 | 129 | langDirs = [f for f in env.Glob(os.path.join("addon", "locale", "*"))] 130 | 131 | #Allow all NVDA's gettext po files to be compiled in source/locale, and manifest files to be generated 132 | for dir in langDirs: 133 | poFile = dir.File(os.path.join("LC_MESSAGES", "nvda.po")) 134 | moFile=env.gettextMoFile(poFile) 135 | env.Depends(moFile, poFile) 136 | translatedManifest = env.NVDATranslatedManifest(dir.File("manifest.ini"), [moFile, os.path.join("manifest-translated.ini.tpl")]) 137 | env.Depends(translatedManifest, ["buildVars.py"]) 138 | env.Depends(addon, [translatedManifest, moFile]) 139 | 140 | pythonFiles = expandGlobs(buildVars.pythonSources) 141 | for file in pythonFiles: 142 | env.Depends(addon, file) 143 | 144 | #Convert markdown files to html 145 | createAddonHelp("addon") # We need at least doc in English and should enable the Help button for the add-on in Add-ons Manager 146 | for mdFile in env.Glob(os.path.join('addon', 'doc', '*', '*.md')): 147 | htmlFile = env.markdown(mdFile) 148 | env.Depends(htmlFile, mdFile) 149 | env.Depends(addon, htmlFile) 150 | 151 | # Pot target 152 | i18nFiles = expandGlobs(buildVars.i18nSources) 153 | gettextvars={ 154 | 'gettext_package_bugs_address' : 'nvda-translations@freelists.org', 155 | 'gettext_package_name' : buildVars.addon_info['addon_name'], 156 | 'gettext_package_version' : buildVars.addon_info['addon_version'] 157 | } 158 | 159 | pot = env.gettextPotFile("${addon_name}.pot", i18nFiles, **gettextvars) 160 | env.Alias('pot', pot) 161 | env.Depends(pot, i18nFiles) 162 | mergePot = env.gettextMergePotFile("${addon_name}-merge.pot", i18nFiles, **gettextvars) 163 | env.Alias('mergePot', mergePot) 164 | env.Depends(mergePot, i18nFiles) 165 | 166 | # Generate Manifest path 167 | manifest = env.NVDAManifest(os.path.join("addon", "manifest.ini"), os.path.join("manifest.ini.tpl")) 168 | env.Depends(manifest, env.File('buildVars.py')) 169 | 170 | env.Depends(addon, manifest) 171 | env.Default(addon) 172 | 173 | #Build and depend on the Dictationbridge core. 174 | dbCore = SConscript(['dictationbridge-core/SConstruct']) 175 | dbMSRUtil = SConscript(['MSRUtil/SConscript']) 176 | dbCoreFiles = dbCore[0]+dbCore[1]+dbCore[2] 177 | dbMSRUtilFiles = dbMSRUtil[0] 178 | env.Depends(addon, dbCoreFiles) 179 | env.Depends(addon, dbMSRUtilFiles) 180 | env.Install(env.Dir('addon'), dbCoreFiles) 181 | env.Install(env.Dir('addon'), dbMSRUtilFiles) -------------------------------------------------------------------------------- /COPYING.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Library General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License 307 | along with this program; if not, write to the Free Software 308 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 309 | 310 | 311 | Also add information on how to contact you by electronic and paper mail. 312 | 313 | If the program is interactive, make it output a short notice like this 314 | when it starts in an interactive mode: 315 | 316 | Gnomovision version 69, Copyright (C) year name of author 317 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 318 | This is free software, and you are welcome to redistribute it 319 | under certain conditions; type `show c' for details. 320 | 321 | The hypothetical commands `show w' and `show c' should show the appropriate 322 | parts of the General Public License. Of course, the commands you use may 323 | be called something other than `show w' and `show c'; they could even be 324 | mouse-clicks or menu items--whatever suits your program. 325 | 326 | You should also get your employer (if you work as a programmer) or your 327 | school, if any, to sign a "copyright disclaimer" for the program, if 328 | necessary. Here is a sample; alter the names: 329 | 330 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 331 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 332 | 333 | , 1 April 1989 334 | Ty Coon, President of Vice 335 | 336 | This General Public License does not permit incorporating your program into 337 | proprietary programs. If your program is a subroutine library, you may 338 | consider it more useful to permit linking proprietary applications with the 339 | library. If this is what you want to do, use the GNU Library General 340 | Public License instead of this License. 341 | -------------------------------------------------------------------------------- /addon/globalPlugins/dictation/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import shutil 4 | import subprocess 5 | import threading 6 | import time 7 | from ctypes import * 8 | from ctypes.wintypes import * 9 | import wx 10 | import api 11 | import braille 12 | import config 13 | import ui 14 | import controlTypes 15 | import core 16 | import eventHandler 17 | import globalCommands 18 | import gui 19 | import inputCore 20 | import keyboardHandler 21 | import queueHandler 22 | import speech 23 | import windowUtils 24 | import winInputHook 25 | import winUser 26 | from globalPluginHandler import GlobalPlugin as BaseGlobalPlugin 27 | from logHandler import log 28 | from NVDAObjects import NVDAObject 29 | from NVDAObjects.IAccessible import getNVDAObjectFromEvent 30 | from win32api import * 31 | from dictationGesture import DictationGesture 32 | import inputCore 33 | 34 | addonRootDir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) 35 | currentEntry = None 36 | autoFlushTimer = None 37 | requestedWSRShowHideEvents = False 38 | wsrAlternatesPanel = None 39 | wsrSpellingPanel = None 40 | wsrPanelHiddenFunction = None 41 | 42 | def escape(input): 43 | input = input.replace("<","<") 44 | input = input.replace(">",">") 45 | input = input.replace('"',""") 46 | input = input.replace("'","'") 47 | return input 48 | 49 | class HelpCategory(object): 50 | def __init__(self,categoryName): 51 | self.categoryName = escape(categoryName) 52 | self.rows = [] 53 | 54 | def addRow(self, command, help): 55 | self.rows.append((escape(command), escape(help))) 56 | 57 | def html(self): 58 | html = "

"+self.categoryName+"

" 59 | html += "" 66 | for row in self.rows: 67 | html+="" 68 | html += "
" 60 | #Translators: The name of the column header for what the user speaks to activate a command. 61 | html += escape(_("Say This")) 62 | html += "" 63 | #Translators: The name of a column header for the help text for what this speech will do. 64 | html += escape(_("To Do This")) 65 | html += "
"+row[0]+""+row[1]+"
" 69 | return html 70 | 71 | def dbHelp(): 72 | sys.path.append(addonRootDir) 73 | #Import this late, as we only need this here and it's a large autobuilt blob. 74 | from NVDA_helpCommands import commands 75 | sys.path.remove(sys.path[-1]) 76 | html = "

" 77 | #Translators: Description of how to Move to the next topic in the in-built help. 78 | html += escape(_('To use this help documentation, you can navigate to the next category with h, or by saying "next heading".')) 79 | #Translators: Description of how to Move through help tables in the in-built help. 80 | html += escape(_('To move by column or row, use table navigation, (You can say "Previous row/column", "prev row", "prev column", "next row", "next column" to navigate with speech).')) 81 | #Translators: Description of how to find a command in the in-built help. 82 | html += escape(_('to find specific text, say "find text", wait for the find dialog to appear, then dictate your text, then say "press enter" or "click ok".')) 83 | html += "

" 84 | #Translators: The Context sensitive help heading, telling the user what these commands are.. 85 | html +=escape(_("Currently available commands.")) 86 | html += "

" 87 | categories = {} 88 | #Translators: The name of a category in Dictationbridge for the commands help. 89 | miscName = _("Miscellaneous") 90 | categories[miscName] = HelpCategory(miscName) 91 | for command in commands: 92 | if command["identifier_for_NVDA"] in SPECIAL_COMMANDS: 93 | #All special commands get the miscelaneous category. 94 | categories[miscName].addRow(command["text"], command["helpText"]) 95 | continue 96 | #Creating a gesture is not efficient, but helps eliminate code bloat. 97 | gesture = DictationGesture(command["identifier_for_NVDA"]) 98 | scriptInfo = gesture.script_hacky 99 | if not scriptInfo: 100 | #This script is not active right now! 101 | continue 102 | doc = getattr(scriptInfo[0], "__doc__", "") 103 | category = "" 104 | try: 105 | category = scriptInfo[0].category 106 | except AttributeError: 107 | category = getattr(scriptInfo[1], "scriptCategory", miscName) 108 | if not categories.get(category): 109 | categories[cat] = HelpCategory(cat) 110 | categories[cat].addRow(command["text"], doc) 111 | for category in categories.values(): 112 | html+=category.html() 113 | ui.browseableMessage(html, 114 | #Translators: The title of the context sensitive help for Dictation Bridge NVDA Commands. 115 | _("Dictation Bridge NVDA Context Sensitive Help"), 116 | True) 117 | 118 | SPECIAL_COMMANDS = { 119 | "stopTalking" : speech.cancelSpeech, 120 | "toggleTalking" : lambda:speech.pauseSpeech(not speech.isPaused), 121 | "dbHelp" : dbHelp, 122 | } 123 | 124 | def successDialog(program): 125 | #Translators: Message shown if the commands were installed into dragon successfully. 126 | gui.messageBox(_("The {0} commands were successfully installed. Please restart your {0} profile to proceed. See the manual for details on how to do this.").format(program), 127 | #Translators: Title of the successfully installed commands dialog 128 | _("Success!")) 129 | 130 | def _onInstallDragonCommands(): 131 | si = subprocess.STARTUPINFO() 132 | si.dwFlags |= subprocess.STARTF_USESHOWWINDOW 133 | si.wShowWindow = subprocess.SW_HIDE 134 | dragonDir = r"C:\Program Files (x86)\Nuance\NaturallySpeaking15\Program" 135 | #Translators: Title of an error dialog shown in dictation bridge. 136 | DB_ERROR_TITLE = _("Dictation Bridge Error") 137 | if not os.path.exists(dragonDir): 138 | dragonDir.replace(r" (x86)", "") 139 | if not os.path.exists(dragonDir): 140 | #Translators: Message given to the user when the addon can't find an installed copy of dragon. 141 | gui.messageBox(_("Cannot find dragon installed on your machine. Please install dragon and then try this process again."), 142 | DB_ERROR_TITLE) 143 | return 144 | xml2dat = os.path.join(dragonDir, "mycmdsxml2dat.exe") 145 | nsadmin = os.path.join(dragonDir, "nsadmin.exe") 146 | 147 | #Translators: The official name of Dragon in your language, this probably should be left as Dragon. 148 | thisProgram = _("Dragon") 149 | if os.path.exists(os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat")): 150 | os.remove(os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat")) 151 | try: 152 | subprocess.check_call([ 153 | xml2dat, 154 | os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat"), 155 | os.path.join(addonRootDir, "dragon_dictationBridgeCommands.xml"), 156 | ], startupinfo=si) 157 | #Fixme: might need to get the users language, and put them there for non-english locales. 158 | d=config.execElevated(nsadmin, 159 | ["/commands", os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat"), "/overwrite=yes"], 160 | wait=True, handleAlreadyElevated=True) 161 | 162 | successDialog(thisProgram) 163 | except: 164 | #Translators: Message shown if dragon commands failed to install. 165 | gui.messageBox(_("There was an error while performing the addition of dragon commands into dragon. Are you running as an administrator? If so, please send the error in your log to the dictation bridge team as a bug report."), 166 | DB_ERROR_TITLE) 167 | raise 168 | finally: 169 | if os.path.exists(os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat")): 170 | os.remove(os.path.join(addonRootDir, "dragon_dictationBridgeCommands.dat")) 171 | 172 | def _onInstallMSRCommands(): 173 | MSRPATH = os.path.expanduser(r"~\documents\speech macros") 174 | commandsFile = os.path.join(addonRootDir, "dictationBridge.WSRMac") 175 | #Translators: Official Title of Microsoft speech Recognition in your language. 176 | thisProgram = _("Microsoft Speech Recognition") 177 | if os.path.exists(MSRPATH): 178 | shutil.copy(commandsFile, MSRPATH) 179 | successDialog(thisProgram) 180 | else: 181 | #Translators: The user doesn't have microsoft speech recognition profiles, or we can't find them. 182 | gui.messageBox(_("Failed to locate your Microsoft Speech Macros folder. Please see the troublshooting part of the documentation for more details."), 183 | #Translators: Title for the microsoft speech recognitioninstalation error dialog. 184 | _("Error installing MSR utilities")) 185 | 186 | 187 | def onInstallMSRCommands(evt): 188 | dialog = gui.IndeterminateProgressDialog(gui.mainFrame, 189 | #Translators: Title for a dialog shown when Microsoft speech recognition Commands are being installed! 190 | _("Microsoft Speech Recognition Command Installation"), 191 | #Translators: Message shown in the progress dialog for MSR command installation. 192 | _("Please wait while microsoft speech recognition commands are installed.")) 193 | try: 194 | gui.ExecAndPump(_onInstallMSRCommands) 195 | except: #Catch all, because if this fails, bad bad bad. 196 | log.error("DictationBridge commands failed to install!", exc_info=True) 197 | finally: 198 | dialog.done() 199 | 200 | def onInstallDragonCommands(evt): 201 | #Translators: Warning about having custom commands already. 202 | goAhead = gui.messageBox(_("If you are on a computer with shared commands, and you have multiple users using these commands, this will override them. Please do not proceed unless you are sure you aren't sharing commands over a network. if you are, please read \"Importing Commands Into a Shared System\" in the Dictation Bridge documentation for manual steps.\nDo you want to proceed?"), 203 | #Translators: Warning dialog title. 204 | _("Warning: Potentially Dangerous Opperation Will be Performed"), 205 | wx.YES|wx.NO) 206 | if goAhead==wx.NO: 207 | return 208 | dialog = gui.IndeterminateProgressDialog(gui.mainFrame, 209 | #Translators: Title for a dialog shown when Dragon Commands are being installed! 210 | _("Dragon Command Installation"), 211 | #Translators: Message shown in the progress dialog for dragon command installation. 212 | _("Please wait while Dragon commands are installed.")) 213 | try: 214 | gui.ExecAndPump(_onInstallDragonCommands) 215 | except: #Catch all, because if this fails, bad bad bad. 216 | log.error("DictationBridge commands failed to install!", exc_info=True) 217 | finally: 218 | dialog.done() 219 | 220 | def requestWSRShowHideEvents(fn=None): 221 | global requestedWSRShowHideEvents, hookId, eventCallback, wsrPanelHiddenFunction 222 | if fn is None: 223 | fn = wsrPanelHiddenFunction 224 | else: 225 | wsrPanelHiddenFunction = fn 226 | if requestedWSRShowHideEvents: 227 | return 228 | try: 229 | hwnd = winUser.FindWindow(u"MS:SpeechTopLevel", None) 230 | except: 231 | hwnd = None 232 | if hwnd: 233 | pid, tid = winUser.getWindowThreadProcessID(hwnd) 234 | eventHandler.requestEvents(eventName='show', processId=pid, windowClassName='#32770') 235 | eventCallback = make_callback(fn) 236 | hookId = winUser.setWinEventHook(winUser.EVENT_OBJECT_HIDE, winUser.EVENT_OBJECT_HIDE, 0, eventCallback, pid, 0, 0) 237 | requestedWSRShowHideEvents = True 238 | 239 | def make_callback(fn): 240 | @WINFUNCTYPE(None, c_int, c_int, c_int, c_int, c_int, c_int, c_int) 241 | def callback(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime): 242 | fn(hwnd) 243 | return callback 244 | 245 | def flushCurrentEntry(): 246 | global currentEntry, autoFlushTimer 247 | if autoFlushTimer is not None: 248 | autoFlushTimer.Stop() 249 | autoFlushTimer = None 250 | start, text = currentEntry 251 | text = text.replace("\r\n", "\n") 252 | text = text.replace("\r", "\n") 253 | while True: 254 | i = text.find("\n") 255 | if i == -1: 256 | break 257 | if i > 0: 258 | speech.speakText(text[:i]) 259 | if text[i:i + 2] == "\n\n": 260 | # Translators: The text which is spoken when a new paragraph is added. 261 | speech.speakText(_("new paragraph")) 262 | text = text[i + 2:] 263 | else: 264 | # Translators: The message spoken when a new line is entered. 265 | speech.speakText(_("new line")) 266 | text = text[i + 1:] 267 | if text != "": 268 | speech.speakText(text) 269 | braille.handler.handleCaretMove(api.getFocusObject()) 270 | currentEntry = None 271 | requestWSRShowHideEvents() 272 | 273 | def textInserted(hwnd, start, text): 274 | global currentEntry, autoFlushTimer 275 | log.debug("textInserted %r" % text) 276 | if currentEntry is not None: 277 | prevStart, prevText = currentEntry 278 | if (not (start == -1 and prevStart == -1)) and (start < prevStart or start > (prevStart + len(prevText))): 279 | flushCurrentEntry() 280 | if currentEntry is not None: 281 | prevStart, prevText = currentEntry 282 | if prevStart == -1 and start == -1: 283 | currentEntry = (-1, prevText + text) 284 | else: 285 | currentEntry = (prevStart, prevText[:start - prevStart] + text) 286 | else: 287 | currentEntry = (start, text) 288 | if autoFlushTimer is not None: 289 | autoFlushTimer.Stop() 290 | autoFlushTimer = None 291 | def autoFlush(*args, **kwargs): 292 | global autoFlushTimer 293 | autoFlushTimer = None 294 | flushCurrentEntry() 295 | autoFlushTimer = wx.CallLater(100, autoFlush) 296 | cTextInsertedCallback = WINFUNCTYPE(None, HWND, LONG, c_wchar_p)(textInserted) 297 | 298 | def textDeleted(hwnd, start, text): 299 | # Translators: The message spoken when a piece of text is deleted. 300 | speech.speakText(_("deleted %s" % text)) 301 | cTextDeletedCallback = WINFUNCTYPE(None, HWND, LONG, c_wchar_p)(textDeleted) 302 | 303 | def commandCallback(command): 304 | if command in SPECIAL_COMMANDS: 305 | queueHandler.queueFunction(queueHandler.eventQueue, SPECIAL_COMMANDS[command]) 306 | return 307 | inputCore.manager.executeGesture(DictationGesture(command)) 308 | cCommandCallback = WINFUNCTYPE(None, c_char_p)(commandCallback) 309 | 310 | def debugLogCallback(msg): 311 | log.debug(msg) 312 | cDebugLogCallback = WINFUNCTYPE(None, c_char_p)(debugLogCallback) 313 | 314 | lastKeyDownTime = None 315 | 316 | def patchKeyDownCallback(): 317 | originalCallback = winInputHook.keyDownCallback 318 | def callback(*args, **kwargs): 319 | global lastKeyDownTime 320 | lastKeyDownTime = time.time() 321 | return originalCallback(*args, **kwargs) 322 | winInputHook.keyDownCallback = callback 323 | 324 | masterDLL = None 325 | installMenuItem = None 326 | 327 | def initialize(): 328 | global masterDLL, installMenuItem 329 | path = os.path.join(config.getUserDefaultConfigPath(), ".dbInstall") 330 | if os.path.exists(path): 331 | #First time reinstall of old code without the bail if updating code. Remove the temp file. 332 | #Also, import install tasks, then fake an install to get around the original path bug. 333 | sys.path.append(addonRootDir) 334 | import installTasks 335 | installTasks.onInstall(postPathBug = True) 336 | sys.path.remove(sys.path[-1]) 337 | os.remove(path) 338 | dllPath = os.path.join(addonRootDir, "DictationBridgeMaster32.dll") 339 | masterDLL = windll.LoadLibrary(dllPath) 340 | masterDLL.DBMaster_SetTextInsertedCallback(cTextInsertedCallback) 341 | masterDLL.DBMaster_SetTextDeletedCallback(cTextDeletedCallback) 342 | masterDLL.DBMaster_SetCommandCallback(cCommandCallback) 343 | masterDLL.DBMaster_SetDebugLogCallback(cDebugLogCallback) 344 | if not masterDLL.DBMaster_Start(): 345 | raise WinError() 346 | patchKeyDownCallback() 347 | toolsMenu = gui.mainFrame.sysTrayIcon.toolsMenu 348 | installMenu = wx.Menu() 349 | #Translators: The Install dragon Commands for NVDA label. 350 | installDragonItem= installMenu.Append(wx.ID_ANY, _("Install Dragon Commands")) 351 | toolsMenu.Parent.Bind(wx.EVT_MENU, onInstallDragonCommands, installDragonItem) 352 | #Translators: The Install Microsoft Speech Recognition Commands for NVDA label. 353 | installMSRItem= installMenu.Append(wx.ID_ANY, _("Install Microsoft Speech Recognition Commands")) 354 | toolsMenu.Parent.Bind(wx.EVT_MENU, onInstallMSRCommands, installMSRItem) 355 | #Translators: The Install commands submenu label. 356 | installMenuItem=toolsMenu.AppendSubMenu(installMenu, _("Install commands for Dictation Bridge")) 357 | 358 | def terminate(): 359 | global masterDLL 360 | if masterDLL is not None: 361 | masterDLL.DBMaster_Stop() 362 | masterDLL = None 363 | try: 364 | gui.mainFrame.sysTrayIcon.toolsMenu.Remove(gui.mainFrame.sysTrayIcon.toolsMenu.MenuItems.index(installMenuItem)) 365 | except: 366 | pass 367 | 368 | def getCleanedWSRAlternatesPanelItemName(obj): 369 | return obj.name[2:] # strip symbol 2776 and space 370 | 371 | def speakWSRAlternatesPanelItem(obj): 372 | text = getCleanedWSRAlternatesPanelItemName(obj) 373 | speech.speakText(text) 374 | 375 | def speakAndSpellWSRAlternatesPanelItem(obj): 376 | text = getCleanedWSRAlternatesPanelItemName(obj) 377 | speech.speakText(text) 378 | speech.speakSpelling(text) 379 | 380 | def selectListItem(obj): 381 | obj.IAccessibleObject.accSelect(2, obj.IAccessibleChildID) 382 | 383 | IDOK = 1 384 | IDCANCEL = 2 385 | IDC_SPELLING_WORD = 6304 386 | 387 | class WSRAlternatesPanel(NVDAObject): 388 | def script_ok(self, gesture): 389 | buttonWindowHandle = windll.user32.GetDlgItem(self.windowHandle, IDOK) 390 | button = getNVDAObjectFromEvent(buttonWindowHandle, winUser.OBJID_CLIENT, 0) 391 | button.doAction() 392 | 393 | def script_cancel(self, gesture): 394 | buttonWindowHandle = windll.user32.GetDlgItem(self.windowHandle, IDCANCEL) 395 | button = getNVDAObjectFromEvent(buttonWindowHandle, winUser.OBJID_CLIENT, 0) 396 | button.doAction() 397 | 398 | def script_selectPreviousItem(self, gesture): 399 | for obj in self.recursiveDescendants: 400 | if obj.role != controlTypes.ROLE_LISTITEM: 401 | continue 402 | if controlTypes.STATE_SELECTED in obj.states: 403 | if obj.previous is not None and obj.previous.role == controlTypes.ROLE_LISTITEM: 404 | selectListItem(obj.previous) 405 | break 406 | 407 | def script_selectNextItem(self, gesture): 408 | firstListItem = None 409 | for obj in self.recursiveDescendants: 410 | if obj.role != controlTypes.ROLE_LISTITEM: 411 | continue 412 | if firstListItem is None: 413 | firstListItem = obj 414 | if controlTypes.STATE_SELECTED in obj.states: 415 | if obj.next is not None and obj.next.role == controlTypes.ROLE_LISTITEM: 416 | selectListItem(obj.next) 417 | break 418 | else: 419 | if firstListItem is not None: 420 | selectListItem(firstListItem) 421 | 422 | def script_selectFirstItem(self, gesture): 423 | firstListItem = None 424 | for obj in self.recursiveDescendants: 425 | if obj.role != controlTypes.ROLE_LISTITEM: 426 | continue 427 | if firstListItem is None: 428 | firstListItem = obj 429 | break 430 | if firstListItem is not None: 431 | selectListItem(firstListItem) 432 | 433 | def script_selectLastItem(self, gesture): 434 | lastListItem = None 435 | for obj in self.recursiveDescendants: 436 | if obj.role != controlTypes.ROLE_LISTITEM: 437 | continue 438 | lastListItem = obj 439 | if lastListItem is not None: 440 | selectListItem(lastListItem) 441 | 442 | __gestures = { 443 | 'kb:enter': 'ok', 444 | 'kb:escape': 'cancel', 445 | 'kb:upArrow': 'selectPreviousItem', 446 | 'kb:downArrow': 'selectNextItem', 447 | 'kb:home': 'selectFirstItem', 448 | 'kb:control+home': 'selectFirstItem', 449 | 'kb:end': 'selectLastItem', 450 | 'kb:control+end': 'selectLastItem', 451 | } 452 | 453 | class WSRSpellingPanel(NVDAObject): 454 | pollTimer = None 455 | previousWord = None 456 | 457 | def _get_word(self): 458 | wordWindowHandle = windll.user32.GetDlgItem(self.windowHandle, IDC_SPELLING_WORD) 459 | wordObject = getNVDAObjectFromEvent(wordWindowHandle, winUser.OBJID_CLIENT, 0) 460 | if controlTypes.STATE_INVISIBLE in wordObject.states: 461 | return "" 462 | return wordObject.name 463 | 464 | def poll(self, *args, **kwargs): 465 | self.pollTimer = None 466 | oldWord = self.previousWord or "" 467 | newWord = self.word or "" 468 | if newWord != oldWord: 469 | self.previousWord = newWord 470 | if len(newWord) > len(oldWord) and newWord[:len(oldWord)] == oldWord: 471 | speech.speakSpelling(newWord[len(oldWord):]) 472 | elif newWord: 473 | speech.speakText(newWord) 474 | speech.speakSpelling(newWord) 475 | elif oldWord: 476 | # Translators: The text which is spoken when the spelling dialog is cleared. 477 | speech.speakText(_("cleared")) 478 | self.schedulePoll() 479 | 480 | def cancelPoll(self): 481 | if self.pollTimer is not None: 482 | self.pollTimer.Stop() 483 | self.pollTimer = None 484 | 485 | def schedulePoll(self): 486 | self.cancelPoll() 487 | self.pollTimer = wx.CallLater(100, self.poll) 488 | 489 | def script_ok(self, gesture): 490 | buttonWindowHandle = windll.user32.GetDlgItem(self.windowHandle, IDOK) 491 | button = getNVDAObjectFromEvent(buttonWindowHandle, winUser.OBJID_CLIENT, 0) 492 | button.doAction() 493 | 494 | def script_cancel(self, gesture): 495 | buttonWindowHandle = windll.user32.GetDlgItem(self.windowHandle, IDCANCEL) 496 | button = getNVDAObjectFromEvent(buttonWindowHandle, winUser.OBJID_CLIENT, 0) 497 | button.doAction() 498 | 499 | __gestures = { 500 | 'kb:enter': 'ok', 501 | 'kb:escape': 'cancel', 502 | } 503 | 504 | def isInWSRAlternatesPanel(obj): 505 | while obj is not None: 506 | if isinstance(obj, WSRAlternatesPanel): 507 | return True 508 | obj = obj.parent 509 | return False 510 | 511 | class GlobalPlugin(BaseGlobalPlugin): 512 | def __init__(self): 513 | super(GlobalPlugin, self).__init__() 514 | initialize() 515 | requestWSRShowHideEvents(self.wsrPanelHidden) 516 | 517 | def chooseNVDAObjectOverlayClasses(self, obj, clsList): 518 | if obj.windowClassName == '#32770' and obj.name == "Alternates panel": 519 | clsList.insert(0, WSRAlternatesPanel) 520 | elif obj.windowClassName == '#32770' and obj.name == "Spelling panel": 521 | clsList.insert(0, WSRSpellingPanel) 522 | 523 | def event_show(self, obj, nextHandler): 524 | global wsrAlternatesPanel, wsrSpellingPanel 525 | #Phrases which need translated in this function: 526 | # Translators: The text for "or say," Which is telling the user that they can say the next phrase. 527 | orSay = _("Or say") 528 | if isinstance(obj, WSRAlternatesPanel): 529 | wsrAlternatesPanel = obj 530 | speech.cancelSpeech() 531 | speech.speakText(obj.name) 532 | for descendant in obj.recursiveDescendants: 533 | if controlTypes.STATE_INVISIBLE in descendant.states or controlTypes.STATE_INVISIBLE in descendant.parent.states: 534 | continue 535 | if descendant.role == controlTypes.ROLE_STATICTEXT: 536 | speech.speakText(descendant.name) 537 | elif descendant.role == controlTypes.ROLE_LINK: 538 | speech.speakText(orSay) 539 | speech.speakText(descendant.name) 540 | elif descendant.role == controlTypes.ROLE_LISTITEM: 541 | speech.speakText(str(descendant.positionInfo["indexInGroup"])) 542 | speakWSRAlternatesPanelItem(descendant) 543 | return 544 | elif isinstance(obj, WSRSpellingPanel): 545 | if wsrSpellingPanel is not None: 546 | wsrSpellingPanel.cancelPoll() 547 | wsrSpellingPanel = obj 548 | wsrSpellingPanel.schedulePoll() 549 | speech.cancelSpeech() 550 | speech.speakText(obj.name) 551 | for descendant in obj.recursiveDescendants: 552 | if controlTypes.STATE_INVISIBLE in descendant.states or controlTypes.STATE_INVISIBLE in descendant.parent.states: 553 | continue 554 | if descendant.role == controlTypes.ROLE_STATICTEXT: 555 | speech.speakText(descendant.name) 556 | elif descendant.role == controlTypes.ROLE_LINK: 557 | speech.speakText(orSay) 558 | speech.speakText(descendant.name) 559 | return 560 | nextHandler() 561 | 562 | def wsrPanelHidden(self, windowHandle): 563 | global wsrAlternatesPanel, wsrSpellingPanel 564 | if wsrAlternatesPanel is not None and windowHandle == wsrAlternatesPanel.windowHandle: 565 | if wsrSpellingPanel is None: 566 | speech.speakText("Closed alternates panel") 567 | wsrAlternatesPanel = None 568 | elif wsrSpellingPanel is not None and windowHandle == wsrSpellingPanel.windowHandle: 569 | wsrSpellingPanel.cancelPoll() 570 | speech.speakText("Closed spelling panel") 571 | wsrSpellingPanel = None 572 | 573 | def event_selection(self, obj, nextHandler): 574 | if obj.role == controlTypes.ROLE_LISTITEM and isInWSRAlternatesPanel(obj): 575 | speech.speakText(str(obj.positionInfo["indexInGroup"])) 576 | speakAndSpellWSRAlternatesPanelItem(obj) 577 | return 578 | nextHandler() 579 | 580 | def getScript(self, gesture): 581 | if wsrAlternatesPanel is not None: 582 | result = wsrAlternatesPanel.getScript(gesture) 583 | if result is not None: 584 | return result 585 | elif wsrSpellingPanel is not None: 586 | result = wsrSpellingPanel.getScript(gesture) 587 | if result is not None: 588 | return result 589 | return super(GlobalPlugin, self).getScript(gesture) 590 | 591 | def event_typedCharacter(self, obj, nextHandler, ch): 592 | if lastKeyDownTime is None or (time.time() - lastKeyDownTime) >= 0.5 and ch != "": 593 | if obj.windowClassName != "ConsoleWindowClass": 594 | log.debug("typedCharacter %r %r" % (obj.windowClassName, ch)) 595 | textInserted(obj.windowHandle, -1, ch) 596 | return 597 | nextHandler() 598 | 599 | def terminate(self): 600 | super(GlobalPlugin, self).terminate() 601 | terminate() 602 | --------------------------------------------------------------------------------