From d7b29daceb98e717aeb4828eb9e71e34e9e33b5e Mon Sep 17 00:00:00 2001 From: Sean Budd Date: Thu, 4 Jul 2024 13:12:29 +1000 Subject: [PATCH 1/4] lint scons files --- nvdaHelper/archBuild_sconscript | 2 -- nvdaHelper/detours/sconscript | 2 +- nvdaHelper/espeak/sconscript | 4 ++-- sconstruct | 14 +++++++------- source/browseMode.py | 2 +- source/comInterfaces_sconscript | 6 +++--- .../test_speechManager/speechManagerTestHarness.py | 2 +- 7 files changed, 15 insertions(+), 17 deletions(-) diff --git a/nvdaHelper/archBuild_sconscript b/nvdaHelper/archBuild_sconscript index 827c1df7308..ff81939c7b6 100644 --- a/nvdaHelper/archBuild_sconscript +++ b/nvdaHelper/archBuild_sconscript @@ -3,8 +3,6 @@ # This file may be used under the terms of the GNU General Public License, version 2 or later. # For more details see: https://www.gnu.org/licenses/gpl-2.0.html -import os -import shutil Import( 'env', diff --git a/nvdaHelper/detours/sconscript b/nvdaHelper/detours/sconscript index 74385beac5f..71f6acfa03f 100644 --- a/nvdaHelper/detours/sconscript +++ b/nvdaHelper/detours/sconscript @@ -2,7 +2,7 @@ Import([ "thirdPartyEnv" ]) -import typing +import typing # noqa: E402 thirdPartyEnv: Environment = thirdPartyEnv env: Environment = typing.cast(Environment, thirdPartyEnv.Clone()) diff --git a/nvdaHelper/espeak/sconscript b/nvdaHelper/espeak/sconscript index 76dbfd34f99..5ad0a97238a 100644 --- a/nvdaHelper/espeak/sconscript +++ b/nvdaHelper/espeak/sconscript @@ -447,7 +447,7 @@ phonemeData = env.espeak_compilePhonemeData( env.Depends(phonemeData,espeakLib) for i in phonemeData: iDir = espeakRepo.Dir('espeak-ng-data').abspath - l = len(iDir) + 1 + l = len(iDir) + 1 # noqa: E741 fileName = i.abspath[l:] env.InstallAs(os.path.join(synthDriversDir.Dir('espeak-ng-data').abspath, fileName), i) @@ -472,7 +472,7 @@ dictSourcePath: SCons.Node.FS.Dir = espeakRepo.Dir('dictsource') # Create compile commands for all languages for dictFileName, (langCode, inputFiles) in espeakDictionaryCompileList.items(): - if langCode in excludeLangs: continue + if langCode in excludeLangs: continue # noqa: E701 dictFilePath = espeakRepo.Dir('espeak-ng-data').File(dictFileName) diff --git a/sconstruct b/sconstruct index d727855ba9b..75f3d2a3f01 100755 --- a/sconstruct +++ b/sconstruct @@ -52,11 +52,11 @@ if ( ) sourceEnvPath = os.path.abspath(os.path.join(Dir('.').srcnode().path, "source")) sys.path.append(sourceEnvPath) -import sourceEnv +import sourceEnv # noqa: E402 sys.path.remove(sourceEnvPath) -import time -import importlib.util -import winreg +import time # noqa: E402 +import importlib.util # noqa: E402 +import winreg # noqa: E402 def recursiveCopy(env,targetDir,sourceDir): targets=[] @@ -73,10 +73,10 @@ def recursiveCopy(env,targetDir,sourceDir): return targets # Import NVDA's versionInfo module. -import gettext +import gettext # noqa: E402 gettext.install("nvda") sys.path.append("source") -import versionInfo +import versionInfo # noqa: E402 del sys.path[-1] makensis = os.path.abspath(os.path.join("include", "nsis", "NSIS", "makensis.exe")) @@ -356,7 +356,7 @@ def ZipArchiveAction(target, source, env): arcName = arcName.replace(".." + os.path.sep, "") return "" if arcName == "." else arcName else: - getArcName = lambda origName: "" if origName == "." else origName + getArcName = lambda origName: "" if origName == "." else origName # noqa: E731 # Nasty hack to make zipfile use best compression, since it isn't configurable. # Tried setting memlevel to 9 as well, but it made compression slightly worse. diff --git a/source/browseMode.py b/source/browseMode.py index 0445104b493..fe66b81c106 100644 --- a/source/browseMode.py +++ b/source/browseMode.py @@ -2273,7 +2273,7 @@ def _mergeIdenticalStyles( # Now merging adjacent strings result = [] for k, g in itertools.groupby(sequence, key=type): - if k == str: + if k == str: # noqa: E721 result.append("".join(g)) else: result.extend(list(g)) diff --git a/source/comInterfaces_sconscript b/source/comInterfaces_sconscript index 577aad65466..ff6baaff2a1 100755 --- a/source/comInterfaces_sconscript +++ b/source/comInterfaces_sconscript @@ -19,10 +19,10 @@ Import( 'env', ) -import importlib.util +import importlib.util # noqa: E402 # Monkeypatch comtypes to clear the importlib cache when importing a new module -import comtypes.client._generate +import comtypes.client._generate # noqa: E402 old_my_import = comtypes.client._generate._my_import def new_my_import(fullname): importlib.invalidate_caches() @@ -77,7 +77,7 @@ interfaceBuilder=env.Builder( env['BUILDERS']['comtypesInterface'] = interfaceBuilder # Force comtypes generated interfaces in to our directory -import comtypes.client +import comtypes.client # noqa: E402 comtypes.client.gen_dir=Dir('comInterfaces').abspath COM_INTERFACES = { diff --git a/tests/unit/test_speechManager/speechManagerTestHarness.py b/tests/unit/test_speechManager/speechManagerTestHarness.py index 5af106736a1..0963485aec4 100644 --- a/tests/unit/test_speechManager/speechManagerTestHarness.py +++ b/tests/unit/test_speechManager/speechManagerTestHarness.py @@ -70,7 +70,7 @@ class ExpectedProsody: ] def __eq__(self, other): - if type(self.expectedProsody) != type(other): + if type(self.expectedProsody) != type(other): # noqa: E721 return False if isinstance(other, BaseProsodyCommand): return repr(other) == repr(self.expectedProsody) From 55fb00ad342b0cd4b0a8913cfc75e0ea61b28100 Mon Sep 17 00:00:00 2001 From: Sean Budd Date: Thu, 4 Jul 2024 13:13:29 +1000 Subject: [PATCH 2/4] Add trailing commas --- appveyor/crowdinSync.py | 12 +- appveyor/mozillaSyms.py | 22 +- projectDocs/dev/developerGuide/conf.py | 4 +- site_scons/site_tools/doxygen.py | 14 +- site_scons/site_tools/gettextTool.py | 8 +- site_scons/site_tools/listModules.py | 5 +- site_scons/site_tools/md2html.py | 6 +- site_scons/site_tools/recursiveInstall.py | 8 +- source/COMRegistrationFixes/__init__.py | 2 +- source/IAccessibleHandler/__init__.py | 81 +- .../internalWinEventHandler.py | 40 +- .../orderedWinEventLimiter.py | 8 +- source/IAccessibleHandler/utils.py | 2 +- source/JABHandler.py | 11 +- source/NVDAHelper.py | 15 +- source/NVDAObjects/IAccessible/__init__.py | 41 +- source/NVDAObjects/IAccessible/chromium.py | 12 +- .../NVDAObjects/IAccessible/ia2TextMozilla.py | 12 +- source/NVDAObjects/IAccessible/ia2Web.py | 14 +- source/NVDAObjects/IAccessible/mozilla.py | 14 +- source/NVDAObjects/IAccessible/mscandui.py | 3 +- .../NVDAObjects/IAccessible/sysListView32.py | 18 +- source/NVDAObjects/IAccessible/winword.py | 28 +- source/NVDAObjects/JAB/__init__.py | 12 +- source/NVDAObjects/UIA/VisualStudio.py | 10 +- source/NVDAObjects/UIA/__init__.py | 80 +- source/NVDAObjects/UIA/chromium.py | 2 +- source/NVDAObjects/UIA/excel.py | 75 +- source/NVDAObjects/UIA/spartanEdge.py | 50 +- source/NVDAObjects/UIA/sysListView32.py | 6 +- source/NVDAObjects/UIA/web.py | 26 +- source/NVDAObjects/UIA/winConsoleUIA.py | 36 +- source/NVDAObjects/UIA/wordDocument.py | 67 +- source/NVDAObjects/__init__.py | 26 +- source/NVDAObjects/behaviors.py | 28 +- source/NVDAObjects/inputComposition.py | 2 +- source/NVDAObjects/lockscreen.py | 2 +- source/NVDAObjects/window/__init__.py | 8 +- source/NVDAObjects/window/_msOfficeChart.py | 343 +++--- source/NVDAObjects/window/edit.py | 26 +- source/NVDAObjects/window/excel.py | 196 ++-- source/NVDAObjects/window/excelCellBorder.py | 14 +- source/NVDAObjects/window/scintilla.py | 2 +- source/NVDAObjects/window/winConsole.py | 18 +- source/NVDAObjects/window/winword.py | 65 +- source/UIAHandler/__init__.py | 142 +-- source/UIAHandler/_remoteOps/builder.py | 14 +- .../_remoteOps/instructions/element.py | 2 +- source/UIAHandler/_remoteOps/localExecute.py | 8 +- source/UIAHandler/_remoteOps/lowLevel.py | 8 +- source/UIAHandler/_remoteOps/operation.py | 24 +- source/UIAHandler/_remoteOps/remoteAPI.py | 34 +- .../UIAHandler/_remoteOps/remoteAlgorithms.py | 8 +- .../_remoteOps/remoteFuncWrapper.py | 18 +- .../_remoteOps/remoteTypes/__init__.py | 154 +-- .../_remoteOps/remoteTypes/element.py | 18 +- .../_remoteOps/remoteTypes/extensionTarget.py | 18 +- .../_remoteOps/remoteTypes/intEnum.py | 6 +- .../_remoteOps/remoteTypes/textRange.py | 52 +- source/UIAHandler/browseMode.py | 42 +- source/UIAHandler/customProps.py | 2 +- source/UIAHandler/remote.py | 22 +- source/UIAHandler/types.py | 4 +- source/UIAHandler/utils.py | 17 +- source/addonAPIVersion.py | 4 +- source/addonHandler/__init__.py | 48 +- source/addonHandler/addonVersionCheck.py | 6 +- source/addonStore/dataManager.py | 6 +- source/addonStore/install.py | 12 +- source/addonStore/models/addon.py | 6 +- source/addonStore/models/status.py | 8 +- source/addonStore/models/version.py | 18 +- source/addonStore/network.py | 18 +- source/api.py | 4 +- source/appModuleHandler.py | 58 +- source/appModules/1password.py | 2 +- source/appModules/bookshelf.py | 3 +- source/appModules/calc.py | 7 +- source/appModules/calculator.py | 4 +- source/appModules/devenv.py | 10 +- source/appModules/eclipse.py | 20 +- source/appModules/explorer.py | 34 +- source/appModules/foobar2000.py | 4 +- source/appModules/kindle.py | 12 +- source/appModules/lockapp.py | 4 +- source/appModules/miranda32.py | 9 +- source/appModules/mmc.py | 2 +- source/appModules/notepad.py | 4 +- source/appModules/nvda.py | 8 +- source/appModules/outlook.py | 21 +- source/appModules/poedit.py | 20 +- source/appModules/powerpnt.py | 285 +++-- source/appModules/soffice.py | 30 +- source/appModules/systemsettings.py | 4 +- source/appModules/tween.py | 2 +- source/appModules/utorrent.py | 16 +- ...bleshell_experiences_textinput_inputapp.py | 32 +- source/appModules/winword.py | 2 +- source/appModules/wwahost.py | 2 +- source/audio/soundSplit.py | 6 +- source/audioDucking.py | 6 +- source/autoSettingsUtils/autoSettings.py | 16 +- source/autoSettingsUtils/driverSetting.py | 14 +- source/baseObject.py | 18 +- source/bdDetect.py | 58 +- source/braille.py | 117 +- .../albatross/_threading.py | 14 +- .../albatross/constants.py | 6 +- .../brailleDisplayDrivers/albatross/driver.py | 68 +- .../albatross/gestures.py | 30 +- source/brailleDisplayDrivers/alva.py | 67 +- source/brailleDisplayDrivers/baum.py | 133 ++- source/brailleDisplayDrivers/brailleNote.py | 72 +- source/brailleDisplayDrivers/brailliantB.py | 49 +- source/brailleDisplayDrivers/brltty.py | 4 +- source/brailleDisplayDrivers/ecoBraille.py | 6 +- .../eurobraille/constants.py | 4 +- .../eurobraille/driver.py | 78 +- .../eurobraille/gestures.py | 6 +- .../freedomScientific.py | 119 +- source/brailleDisplayDrivers/handyTech.py | 172 +-- .../hidBrailleStandard.py | 11 +- source/brailleDisplayDrivers/hims.py | 57 +- source/brailleDisplayDrivers/lilli.py | 4 +- source/brailleDisplayDrivers/nattiqbraille.py | 10 +- source/brailleDisplayDrivers/papenmeier.py | 8 +- .../papenmeier_serial.py | 6 +- source/brailleDisplayDrivers/seika.py | 4 +- source/brailleDisplayDrivers/seikantk.py | 16 +- source/brailleDisplayDrivers/superBrl.py | 10 +- source/brailleInput.py | 30 +- source/brailleTables.py | 8 +- source/brailleViewer/__init__.py | 2 +- source/brailleViewer/brailleViewerGui.py | 41 +- source/browseMode.py | 620 +++++----- source/buildVersion.py | 2 +- source/characterProcessing.py | 54 +- source/colors.py | 2 +- source/comHelper.py | 12 +- ...DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.py | 1026 ++++++++--------- source/compoundDocuments.py | 14 +- source/config/__init__.py | 52 +- source/config/configFlags.py | 2 +- source/config/configSpec.py | 2 +- source/config/featureFlag.py | 42 +- source/config/featureFlagEnums.py | 6 +- source/config/profileUpgradeSteps.py | 8 +- source/config/profileUpgrader.py | 2 +- source/contentRecog/__init__.py | 20 +- source/contentRecog/recogUi.py | 8 +- source/controlTypes/__init__.py | 2 +- source/controlTypes/deprecatedAliases.py | 2 +- source/controlTypes/formatFields.py | 2 +- source/controlTypes/processAndLabelStates.py | 4 +- source/core.py | 83 +- source/cursorManager.py | 11 +- source/diffHandler.py | 10 +- source/displayModel.py | 12 +- source/documentBase.py | 14 +- source/documentNavigation/paragraphHelper.py | 4 +- source/easeOfAccess.py | 8 +- source/editableText.py | 10 +- source/eventHandler.py | 44 +- source/extensionPoints/__init__.py | 2 +- source/extensionPoints/util.py | 4 +- source/fileUtils.py | 15 +- source/fonts/__init__.py | 2 +- source/garbageHandler.py | 2 +- source/globalCommands.py | 572 ++++----- source/gui/__init__.py | 55 +- source/gui/addonGui.py | 61 +- source/gui/addonStoreGui/controls/actions.py | 16 +- .../gui/addonStoreGui/controls/addonList.py | 2 +- source/gui/addonStoreGui/controls/details.py | 64 +- .../addonStoreGui/controls/messageDialogs.py | 100 +- .../gui/addonStoreGui/controls/storeDialog.py | 46 +- source/gui/addonStoreGui/viewModels/action.py | 12 +- .../gui/addonStoreGui/viewModels/addonList.py | 12 +- source/gui/addonStoreGui/viewModels/store.py | 58 +- source/gui/configProfiles.py | 104 +- source/gui/exit.py | 6 +- source/gui/guiHelper.py | 24 +- source/gui/inputGestures.py | 90 +- source/gui/installerGui.py | 96 +- source/gui/logViewer.py | 4 +- source/gui/message.py | 2 +- source/gui/nvdaControls.py | 27 +- source/gui/settingsDialogs.py | 519 +++++---- source/gui/speechDict.py | 26 +- source/gui/startupDialogs.py | 16 +- source/hidpi.py | 2 +- source/hwIo/__init__.py | 2 +- source/hwIo/base.py | 28 +- source/hwIo/hid.py | 28 +- source/hwIo/ioThread.py | 26 +- source/hwPortUtils.py | 34 +- source/inputCore.py | 23 +- source/installer.py | 85 +- source/keyboardHandler.py | 16 +- source/languageHandler.py | 4 +- source/logHandler.py | 18 +- source/mathPres/__init__.py | 6 +- source/mathPres/mathPlayer.py | 17 +- source/mathType.py | 2 +- source/mouseHandler.py | 15 +- source/nvwave.py | 44 +- source/objidl.py | 404 ++++--- source/oleTypes.py | 386 ++++--- source/pythonConsole.py | 10 +- source/review.py | 2 +- source/scriptHandler.py | 12 +- source/setup.py | 59 +- source/shellapi.py | 2 +- source/shlobj.py | 4 +- source/speech/__init__.py | 2 +- source/speech/commands.py | 12 +- source/speech/manager.py | 24 +- source/speech/sayAll.py | 10 +- source/speech/speech.py | 265 +++-- source/speech/speechWithoutPauses.py | 26 +- source/speech/types.py | 4 +- source/speechDictHandler/__init__.py | 2 +- source/speechDictHandler/dictFormatUpgrade.py | 28 +- source/speechViewer.py | 20 +- source/speechXml.py | 23 +- source/synthDriverHandler.py | 5 +- source/synthDrivers/_espeak.py | 6 +- source/synthDrivers/_sapi4.py | 78 +- source/synthDrivers/espeak.py | 2 +- source/synthDrivers/oneCore.py | 14 +- source/synthDrivers/sapi4.py | 6 +- source/synthDrivers/sapi5.py | 6 +- source/synthSettingsRing.py | 2 +- source/systemUtils.py | 14 +- source/textInfos/__init__.py | 22 +- source/textInfos/offsets.py | 10 +- source/textUtils/__init__.py | 8 +- source/textUtils/uniscribe.py | 2 +- source/tones.py | 8 +- source/touchHandler.py | 8 +- source/touchTracker.py | 4 +- source/treeInterceptorHandler.py | 2 +- source/ui.py | 16 +- source/updateCheck.py | 149 ++- source/utils/blockUntilConditionMet.py | 4 +- source/utils/caseInsensitiveCollections.py | 2 +- source/utils/schedule.py | 8 +- source/utils/security.py | 16 +- source/versionInfo.py | 5 +- source/virtualBuffers/MSHTML.py | 20 +- source/virtualBuffers/__init__.py | 32 +- source/virtualBuffers/adobeAcrobat.py | 2 +- source/virtualBuffers/gecko_ia2.py | 66 +- source/vision/util.py | 2 +- source/vision/visionHandler.py | 35 +- .../NVDAHighlighter.py | 27 +- .../_exampleProvider_autoGui.py | 12 +- .../screenCurtain.py | 30 +- source/watchdog.py | 56 +- source/winAPI/_displayTracking.py | 2 +- source/winAPI/_powerTracking.py | 2 +- source/winAPI/_wtsApi32.py | 4 +- source/winAPI/sessionTracking.py | 10 +- source/winGDI.py | 4 +- source/winKernel.py | 16 +- source/winUser.py | 52 +- source/winVersion.py | 12 +- source/wincon.py | 2 +- source/windowUtils.py | 14 +- tests/checkPot.py | 20 +- tests/system/libraries/AssertsLib.py | 26 +- tests/system/libraries/ChromeLib.py | 26 +- tests/system/libraries/NotepadLib.py | 16 +- tests/system/libraries/NvdaLib.py | 21 +- .../SystemTestSpy/blockUntilConditionMet.py | 6 +- .../libraries/SystemTestSpy/configManager.py | 18 +- .../SystemTestSpy/speechSpyGlobalPlugin.py | 26 +- .../SystemTestSpy/speechSpySynthDriver.py | 4 +- .../system/libraries/SystemTestSpy/windows.py | 12 +- tests/system/libraries/WindowsLib.py | 6 +- tests/system/robot/NVDAInstaller.py | 3 +- tests/system/robot/chromeTests.py | 354 +++--- tests/system/robot/startupShutdownNVDA.py | 24 +- .../system/robot/symbolPronunciationTests.py | 80 +- tests/unit/__init__.py | 2 +- tests/unit/contentRecog/test_contentRecog.py | 6 +- tests/unit/extensionPointTestHelpers.py | 8 +- tests/unit/test_SpeechWithoutPauses.py | 22 +- tests/unit/test_addonVersionCheck.py | 2 +- tests/unit/test_baseObject.py | 10 +- tests/unit/test_bdDetect.py | 4 +- .../test_brailleDisplayDrivers.py | 6 +- .../test_displayTextForGestureIdentifier.py | 10 +- .../test_handlerExtensionPoints.py | 6 +- tests/unit/test_brailleTables.py | 2 +- tests/unit/test_characterProcessing.py | 18 +- tests/unit/test_checkPot/__init__.py | 28 +- tests/unit/test_config.py | 58 +- tests/unit/test_controlTypes.py | 40 +- tests/unit/test_inputCore.py | 2 +- tests/unit/test_javaAccessBridge.py | 6 +- tests/unit/test_languageHandler.py | 10 +- tests/unit/test_locationHelper.py | 64 +- tests/unit/test_nvwave.py | 4 +- tests/unit/test_orderedWinEventLimiter.py | 33 +- tests/unit/test_scriptHandler.py | 2 +- tests/unit/test_speech.py | 70 +- tests/unit/test_speechManager/__init__.py | 152 +-- .../speechManagerTestHarness.py | 36 +- tests/unit/test_speechShortcutKeys.py | 2 +- tests/unit/test_speechXml.py | 49 +- tests/unit/test_synthDriverHandler.py | 4 +- tests/unit/test_synthDrivers/test_espeak.py | 24 +- tests/unit/test_textInfos.py | 2 +- tests/unit/test_textUtils.py | 12 +- tests/unit/test_tones.py | 2 +- .../test_util/test_blockUntilConditionMet.py | 8 +- tests/unit/test_util/test_schedule.py | 6 +- tests/unit/test_util/test_security.py | 52 +- .../unit/test_winAPI/test_displayTracking.py | 6 +- tests/unit/test_winAPI/test_powerTracking.py | 2 +- tests/unit/test_winVersion.py | 14 +- user_docs/keyCommandsDoc.py | 6 +- venvUtils/ensureVenv.py | 10 +- 324 files changed, 6448 insertions(+), 5513 deletions(-) diff --git a/appveyor/crowdinSync.py b/appveyor/crowdinSync.py index f1373527969..dbd799cf8d8 100644 --- a/appveyor/crowdinSync.py +++ b/appveyor/crowdinSync.py @@ -23,7 +23,7 @@ def request( path: str, method=requests.get, headers: dict[str, str] | None = None, - **kwargs + **kwargs, ) -> requests.Response: if headers is None: headers = {} @@ -31,7 +31,7 @@ def request( r = method( f"https://api.crowdin.com/api/v2/{path}", headers=headers, - **kwargs + **kwargs, ) # Convert errors to exceptions, but print the response before raising. try: @@ -54,14 +54,14 @@ def uploadSourceFile(crowdinFileID: int, localFilePath: str) -> None: "storages", method=requests.post, headers={"Crowdin-API-FileName": fn}, - data=f + data=f, ) storageID = r.json()["data"]["id"] print(f"Updating file {crowdinFileID} on Crowdin with storage ID {storageID}") r = projectRequest( f"files/{crowdinFileID}", method=requests.put, - json={"storageId": storageID} + json={"storageId": storageID}, ) revisionId = r.json()["data"]["revisionId"] print(f"Updated to revision {revisionId}") @@ -69,12 +69,12 @@ def uploadSourceFile(crowdinFileID: int, localFilePath: str) -> None: def main(): parser = argparse.ArgumentParser( - description="Syncs translations with Crowdin." + description="Syncs translations with Crowdin.", ) commands = parser.add_subparsers(dest="command", required=True) uploadCommand = commands.add_parser( "uploadSourceFile", - help="Upload a source file to Crowdin." + help="Upload a source file to Crowdin.", ) uploadCommand.add_argument("crowdinFileID", type=int, help="The Crowdin file ID.") uploadCommand.add_argument("localFilePath", help="The path to the local file.") diff --git a/appveyor/mozillaSyms.py b/appveyor/mozillaSyms.py index 365bcc19a30..5cbee390f69 100644 --- a/appveyor/mozillaSyms.py +++ b/appveyor/mozillaSyms.py @@ -27,10 +27,12 @@ "ISimpleDOM.dll", "nvdaHelperRemote.dll", ] -DLL_FILES = [f - for dll in DLL_NAMES - # We need both the 32 bit and 64 bit symbols. - for f in (os.path.join(NVDA_LIB, dll), os.path.join(NVDA_LIB64, dll))] +DLL_FILES = [ + f + for dll in DLL_NAMES + # We need both the 32 bit and 64 bit symbols. + for f in (os.path.join(NVDA_LIB, dll), os.path.join(NVDA_LIB64, dll)) +] class ProcError(Exception): def __init__(self, returncode, stderr): @@ -38,10 +40,12 @@ def __init__(self, returncode, stderr): self.stderr = stderr def check_output(command): - proc = subprocess.Popen(command, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True) + proc = subprocess.Popen( + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) stdout, stderr = proc.communicate() if proc.returncode != 0: raise ProcError(proc.returncode, stderr) @@ -91,7 +95,7 @@ def upload(): URL, files={'symbols.zip': open(ZIP_FILE, 'rb')}, headers={'Auth-Token': os.getenv('mozillaSymsAuthToken')}, - allow_redirects=False + allow_redirects=False, ) break # success except Exception as e: diff --git a/projectDocs/dev/developerGuide/conf.py b/projectDocs/dev/developerGuide/conf.py index ea8cb7a4e1b..6a9bc6093e3 100644 --- a/projectDocs/dev/developerGuide/conf.py +++ b/projectDocs/dev/developerGuide/conf.py @@ -60,7 +60,7 @@ version = versionInfo.formatVersionForGUI( versionInfo.version_year, versionInfo.version_major, - versionInfo.version_minor + versionInfo.version_minor, ) # The full version, including alpha/beta/rc tags @@ -84,7 +84,7 @@ # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [ - "_build" + "_build", ] diff --git a/site_scons/site_tools/doxygen.py b/site_scons/site_tools/doxygen.py index 09af7ebd65f..cc6827f897f 100644 --- a/site_scons/site_tools/doxygen.py +++ b/site_scons/site_tools/doxygen.py @@ -77,7 +77,7 @@ def append_data(data, key, new_data, token): elif token == "=": data[key] = list() else: - append_data( data, key, new_data, token ) + append_data( data, key, new_data, token) new_data = True last_token = token @@ -85,7 +85,7 @@ def append_data(data, key, new_data, token): if last_token == '\\' and token != '\n': new_data = False - append_data( data, key, new_data, '\\' ) + append_data( data, key, new_data, '\\') # compress lists of len 1 into single strings # Wrap items into a list, since we're mutating the dictionary @@ -204,12 +204,14 @@ def generate(env): source_scanner = doxyfile_scanner, ) - env.Append(BUILDERS = { - 'Doxygen': doxyfile_builder, - }) + env.Append( + BUILDERS = { + 'Doxygen': doxyfile_builder, + }, + ) env.AppendUnique( - DOXYGEN = fetchDoxygenPath() + DOXYGEN = fetchDoxygenPath(), ) def exists(env): diff --git a/site_scons/site_tools/gettextTool.py b/site_scons/site_tools/gettextTool.py index 9daaac33757..3e1d1521bb1 100644 --- a/site_scons/site_tools/gettextTool.py +++ b/site_scons/site_tools/gettextTool.py @@ -22,8 +22,10 @@ def exists(env): def generate(env): env['BUILDERS']['gettextMoFile']=env.Builder( - action=env.Action([[MSGFMT,"-o","$TARGET","$SOURCE"]], - lambda t,s,e: 'Compiling gettext template %s'%s[0].path), + action=env.Action( + [[MSGFMT,"-o","$TARGET","$SOURCE"]], + lambda t,s,e: 'Compiling gettext template %s'%s[0].path, + ), suffix='.mo', - src_suffix='.po' + src_suffix='.po', ) diff --git a/site_scons/site_tools/listModules.py b/site_scons/site_tools/listModules.py index 8c0950893e9..f7ef6665c2f 100644 --- a/site_scons/site_tools/listModules.py +++ b/site_scons/site_tools/listModules.py @@ -14,7 +14,7 @@ def _generateModuleList( target: list[SCons.Node.FS.File], source: list[SCons.Node.FS.Dir], - env: SCons.Environment.Environment + env: SCons.Environment.Environment, ) -> None: """ Generate a list of Python modules from compiled '.pyc' files within `library.zip` in the source folder. @@ -58,7 +58,8 @@ def _generateModuleList( def generate(env: SCons.Environment.Environment): env["BUILDERS"]["GenerateModuleList"] = SCons.Builder.Builder( - action=SCons.Action.Action(_generateModuleList)) + action=SCons.Action.Action(_generateModuleList), + ) def exists(env: SCons.Environment.Environment) -> bool: diff --git a/site_scons/site_tools/md2html.py b/site_scons/site_tools/md2html.py index 5bb71e2fce4..ccfd0168776 100644 --- a/site_scons/site_tools/md2html.py +++ b/site_scons/site_tools/md2html.py @@ -143,7 +143,7 @@ def _generateSanitizedHTML(md: str, isKeyCommands: bool = False) -> str: def md2html_actionFunc( target: list[SCons.Node.FS.File], source: list[SCons.Node.FS.File], - env: SCons.Environment.Environment + env: SCons.Environment.Environment, ): isKeyCommands = target[0].path.endswith("keyCommands.html") isUserGuide = target[0].path.endswith("userGuide.html") @@ -178,7 +178,7 @@ def md2html_actionFunc( dir="rtl" if lang in RTL_LANG_CODES else "ltr", title=title, extraStylesheet=extraStylesheet, - ) + ), ) htmlOutput = _generateSanitizedHTML(mdStr, isKeyCommands) @@ -216,5 +216,5 @@ def generate(env: SCons.Environment.Environment): env["BUILDERS"]["md2html"] = env.Builder( action=env.Action(md2html_actionFunc, lambda t, s, e: f"Converting {s[0].path} to {t[0].path}"), suffix=".html", - src_suffix=".md" + src_suffix=".md", ) diff --git a/site_scons/site_tools/recursiveInstall.py b/site_scons/site_tools/recursiveInstall.py index 386f54bb4d9..913a9ac5d14 100644 --- a/site_scons/site_tools/recursiveInstall.py +++ b/site_scons/site_tools/recursiveInstall.py @@ -31,15 +31,15 @@ import os -def recursive_install(env, path ): +def recursive_install(env, path): nodes = env.Glob \ ( os.path.join(path, '*') - , strings=False + , strings=False, ) out = [] for n in nodes: if n.isdir(): - out.extend( recursive_install(env, n.abspath )) + out.extend( recursive_install(env, n.abspath)) else: out.append(n) @@ -53,7 +53,7 @@ def RecursiveInstall(env, target, dir): l = len(dir) + 1 # noqa: E741 - relnodes = [ n.abspath[l:] for n in nodes ] + relnodes = [ n.abspath[l:] for n in nodes] for n in relnodes: t = os.path.join(target, n) diff --git a/source/COMRegistrationFixes/__init__.py b/source/COMRegistrationFixes/__init__.py index 5ccdc0a8338..cc12f44b60c 100644 --- a/source/COMRegistrationFixes/__init__.py +++ b/source/COMRegistrationFixes/__init__.py @@ -118,7 +118,7 @@ def fixCOMRegistrations() -> None: is64bit = winVer.processorArchitecture.endswith("64") log.debug( f"Fixing COM registrations for Windows {OSMajorMinor[0]}.{OSMajorMinor[1]}, " - "{} bit.".format("64" if is64bit else "32") + "{} bit.".format("64" if is64bit else "32"), ) # OLEACC (MSAA) proxies apply32bitRegistryPatch(OLEACC_REG_FILE_PATH) diff --git a/source/IAccessibleHandler/__init__.py b/source/IAccessibleHandler/__init__.py index 9c8b4f9685e..9834f841173 100644 --- a/source/IAccessibleHandler/__init__.py +++ b/source/IAccessibleHandler/__init__.py @@ -248,7 +248,7 @@ def _getStatesSetFromIAccessibleStates( - IAccessibleStates: int + IAccessibleStates: int, ) -> Set[controlTypes.State]: return set( IAccessibleStatesToNVDAStates[IAState] @@ -322,7 +322,7 @@ def NVDARoleFromAttr(accRole: Optional[str]) -> Role: def normalizeIAccessible( pacc: Union[IUnknown, IA.IAccessible, IA2.IAccessible2], - childID: int = 0 + childID: int = 0, ) -> Union[IA.IAccessible, IA2.IAccessible2]: if not isinstance(pacc, IA.IAccessible): try: @@ -352,7 +352,7 @@ def accessibleObjectFromEvent(window, objectID, childID): if isMSAADebugLoggingEnabled(): log.debugWarning( f"oleacc.AccessibleObjectFromEvent failed with {e}." - f" WinEvent: {getWinEventLogInfo(window, objectID, childID)}" + f" WinEvent: {getWinEventLogInfo(window, objectID, childID)}", ) return None return normalizeIAccessible(pacc, childID), childID @@ -519,7 +519,7 @@ def winEventToNVDAEvent( # noqa: C901 window: int, objectID: int, childID: int, - useCache: bool = True + useCache: bool = True, ) -> Optional[Tuple[str, NVDAObjects.IAccessible.IAccessible]]: """Tries to convert a win event ID to an NVDA event name, and instantiate or fetch an NVDAObject for the win event parameters. @@ -534,7 +534,7 @@ def winEventToNVDAEvent( # noqa: C901 if isMSAADebugLoggingEnabled(): log.debug( f"Creating NVDA event from winEvent: {getWinEventLogInfo(window, objectID, childID, eventID)}, " - f"use cache {useCache}" + f"use cache {useCache}", ) NVDAEventName = internalWinEventHandler.winEventIDsToNVDAEventNames.get(eventID, None) if not NVDAEventName: @@ -546,21 +546,21 @@ def winEventToNVDAEvent( # noqa: C901 if not window or not winUser.isWindow(window): if isMSAADebugLoggingEnabled(): log.debug( - f"Invalid window. Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID)}" + f"Invalid window. Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID)}", ) return None # Make sure this window does not have a ghost window if possible if NVDAObjects.window.GhostWindowFromHungWindow and NVDAObjects.window.GhostWindowFromHungWindow(window): if isMSAADebugLoggingEnabled(): log.debug( - f"Ghosted hung window. Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID)}" + f"Ghosted hung window. Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID)}", ) return None # We do not support MSAA object proxied from native UIA if UIAHandler.handler and UIAHandler.handler.isUIAWindow(window, isDebug=isMSAADebugLoggingEnabled()): if isMSAADebugLoggingEnabled(): log.debug( - f"Native UIA window. Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID)}" + f"Native UIA window. Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID)}", ) return None obj = None @@ -570,7 +570,7 @@ def winEventToNVDAEvent( # noqa: C901 if isMSAADebugLoggingEnabled() and obj: log.debug( f"Fetched existing NVDAObject {obj} from liveNVDAObjectTable" - f" for winEvent {getWinEventLogInfo(window, objectID, childID)}" + f" for winEvent {getWinEventLogInfo(window, objectID, childID)}", ) # If we don't yet have the object, then actually instanciate it. if not obj: @@ -580,7 +580,7 @@ def winEventToNVDAEvent( # noqa: C901 if isMSAADebugLoggingEnabled(): log.debug( "Could not instantiate an NVDAObject for winEvent: " - f"{getWinEventLogInfo(window, objectID, childID, eventID)}" + f"{getWinEventLogInfo(window, objectID, childID, eventID)}", ) return None # SDM MSAA objects sometimes don't contain enough information to be useful Sometimes there is a real @@ -593,7 +593,7 @@ def winEventToNVDAEvent( # noqa: C901 if isMSAADebugLoggingEnabled(): log.debug( f"Successfully created NVDA event {NVDAEventName} for {obj} " - f"from winEvent {getWinEventLogInfo(window, objectID, childID, eventID)}" + f"from winEvent {getWinEventLogInfo(window, objectID, childID, eventID)}", ) return (NVDAEventName, obj) @@ -615,7 +615,7 @@ def processGenericWinEvent(eventID, window, objectID, childID): """ if isMSAADebugLoggingEnabled(): log.debug( - f"Processing generic winEvent: {getWinEventLogInfo(window, objectID, childID, eventID)}" + f"Processing generic winEvent: {getWinEventLogInfo(window, objectID, childID, eventID)}", ) # Notify appModuleHandler of this new window appModuleHandler.update(winUser.getWindowThreadProcessID(window)[0]) @@ -623,7 +623,7 @@ def processGenericWinEvent(eventID, window, objectID, childID): focus = eventHandler.lastQueuedFocusObject if objectID == winUser.OBJID_CARET and eventID in ( winUser.EVENT_OBJECT_LOCATIONCHANGE, - winUser.EVENT_OBJECT_SHOW + winUser.EVENT_OBJECT_SHOW, ): if not isinstance(focus, NVDAObjects.IAccessible.IAccessible): # #12855: Ignore MSAA caret event on non-MSAA focus. @@ -637,13 +637,13 @@ def processGenericWinEvent(eventID, window, objectID, childID): if isMSAADebugLoggingEnabled(): log.debug( f"Ignoring MSAA caret event on focused UIA Word document" - f"winEvent {getWinEventLogInfo(window, objectID, childID)}" + f"winEvent {getWinEventLogInfo(window, objectID, childID)}", ) return False if isMSAADebugLoggingEnabled(): log.debug( "handling winEvent as caret event on focus. " - f"winEvent {getWinEventLogInfo(window, objectID, childID)}" + f"winEvent {getWinEventLogInfo(window, objectID, childID)}", ) NVDAEvent = ("caret", focus) else: @@ -665,7 +665,7 @@ def processGenericWinEvent(eventID, window, objectID, childID): if isMSAADebugLoggingEnabled(): log.debug( f"Directing winEvent to existing focus object {focus}. " - f"WinEvent {getWinEventLogInfo(window, objectID, childID)}" + f"WinEvent {getWinEventLogInfo(window, objectID, childID)}", ) NVDAEvent = (NVDAEvent[0], focus) eventHandler.queueEvent(*NVDAEvent) @@ -689,7 +689,7 @@ def processFocusWinEvent(window, objectID, childID, force=False): if isMSAADebugLoggingEnabled(): log.debug( f"Processing focus winEvent: {getWinEventLogInfo(window, objectID, childID)}, " - f"force {force}" + f"force {force}", ) windowClassName = winUser.getClassName(window) # Generally, we must ignore focus on child windows of SDM windows as we only want the SDM MSAA events. @@ -703,7 +703,7 @@ def processFocusWinEvent(window, objectID, childID, force=False): if isMSAADebugLoggingEnabled(): log.debug( f"Focus event for child window of MS Office SDM window. " - f"Dropping winEvent {getWinEventLogInfo(window, objectID, childID)}, " + f"Dropping winEvent {getWinEventLogInfo(window, objectID, childID)}, ", ) return False # Notify appModuleHandler of this new foreground window @@ -717,7 +717,7 @@ def processFocusWinEvent(window, objectID, childID, force=False): ): if isMSAADebugLoggingEnabled(): log.debug( - f"Redirecting focus to Java window. WinEvent {getWinEventLogInfo(window, objectID, childID)}" + f"Redirecting focus to Java window. WinEvent {getWinEventLogInfo(window, objectID, childID)}", ) JABHandler.event_enterJavaWindow(window) return True @@ -741,7 +741,7 @@ def processFocusWinEvent(window, objectID, childID, force=False): IAccessibleChildID=realChildID, event_windowHandle=window, event_objectID=objectID, - event_childID=realChildID + event_childID=realChildID, ) if realObj: obj = realObj @@ -776,7 +776,7 @@ def processDesktopSwitchWinEvent(window, objectID, childID): from winAPI.secureDesktop import _handleSecureDesktopChange if isMSAADebugLoggingEnabled(): log.debug( - f"Processing desktopSwitch winEvent: {getWinEventLogInfo(window, objectID, childID)}" + f"Processing desktopSwitch winEvent: {getWinEventLogInfo(window, objectID, childID)}", ) hDesk = windll.user32.OpenInputDesktop(0, False, 0) if hDesk != 0: @@ -816,14 +816,14 @@ def processForegroundWinEvent(window, objectID, childID): """ if isMSAADebugLoggingEnabled(): log.debug( - f"Processing foreground winEvent: {getWinEventLogInfo(window, objectID, childID)}" + f"Processing foreground winEvent: {getWinEventLogInfo(window, objectID, childID)}", ) # Ignore foreground events on windows that aren't the current foreground window if window != winUser.getForegroundWindow(): if isMSAADebugLoggingEnabled(): log.debug( f"Dropping foreground winEvent as it does not match GetForegroundWindow. " - f"WinEvent {getWinEventLogInfo(window, objectID, childID)}" + f"WinEvent {getWinEventLogInfo(window, objectID, childID)}", ) return False # If there is a pending gainFocus, it will handle the foreground object. @@ -836,7 +836,7 @@ def processForegroundWinEvent(window, objectID, childID): if isMSAADebugLoggingEnabled(): log.debug( f"Dropping foreground winEvent as focus is already on a descendant. " - f"WinEvent {getWinEventLogInfo(window, objectID, childID)}" + f"WinEvent {getWinEventLogInfo(window, objectID, childID)}", ) return False # If the existing focus has the same win event params as these, then ignore this event @@ -849,7 +849,7 @@ def processForegroundWinEvent(window, objectID, childID): if isMSAADebugLoggingEnabled(): log.debug( f"Dropping foreground winEvent as it is duplicate to existing focus. " - f"WinEvent {getWinEventLogInfo(window, objectID, childID)}" + f"WinEvent {getWinEventLogInfo(window, objectID, childID)}", ) return False # Notify appModuleHandler of this new foreground window @@ -860,7 +860,7 @@ def processForegroundWinEvent(window, objectID, childID): if isMSAADebugLoggingEnabled(): log.debug( f"Redirecting foreground winEvent to Java window. " - f"WinEvent {getWinEventLogInfo(window, objectID, childID)}" + f"WinEvent {getWinEventLogInfo(window, objectID, childID)}", ) return True # Convert the win event to an NVDA event @@ -869,7 +869,7 @@ def processForegroundWinEvent(window, objectID, childID): if isMSAADebugLoggingEnabled(): log.debug( f"Could not convert foreground winEvent to an NVDA event. " - f"WinEvent {getWinEventLogInfo(window, objectID, childID)}" + f"WinEvent {getWinEventLogInfo(window, objectID, childID)}", ) return False eventHandler.queueEvent(*NVDAEvent) @@ -879,7 +879,7 @@ def processForegroundWinEvent(window, objectID, childID): def processShowWinEvent(window, objectID, childID): if isMSAADebugLoggingEnabled(): log.debug( - f"Processing show winEvent: {getWinEventLogInfo(window, objectID, childID)}" + f"Processing show winEvent: {getWinEventLogInfo(window, objectID, childID)}", ) # eventHandler.shouldAcceptEvent only accepts show events for a few specific cases. # Narrow this further to only accept events for clients or custom objects. @@ -896,7 +896,7 @@ def processDestroyWinEvent(window, objectID, childID): """ if isMSAADebugLoggingEnabled(): log.debug( - f"Processing destroy winEvent: {getWinEventLogInfo(window, objectID, childID)}" + f"Processing destroy winEvent: {getWinEventLogInfo(window, objectID, childID)}", ) try: del liveNVDAObjectTable[(window, objectID, childID)] @@ -926,7 +926,7 @@ def processMenuStartWinEvent(eventID, window, objectID, childID, validFocus): if isMSAADebugLoggingEnabled(): log.debug( f"Processing menuStart winEvent: {getWinEventLogInfo(window, objectID, childID)}, " - f"validFocus {validFocus}" + f"validFocus {validFocus}", ) if validFocus: lastFocus = eventHandler.lastQueuedFocusObject @@ -947,7 +947,7 @@ def processMenuStartWinEvent(eventID, window, objectID, childID, validFocus): if isMSAADebugLoggingEnabled(): log.debug( f"Ignoring menuStart winEvent: {getWinEventLogInfo(window, objectID, childID)}, " - f"shouldAllowIAccessibleMenuStartEvent {obj.shouldAllowIAccessibleMenuStartEvent}" + f"shouldAllowIAccessibleMenuStartEvent {obj.shouldAllowIAccessibleMenuStartEvent}", ) return processFocusNVDAEvent(obj, force=True) @@ -963,7 +963,7 @@ def processFakeFocusWinEvent(eventID, window, objectID, childID): # the focus hasn't changed yet. if isMSAADebugLoggingEnabled(): log.debug( - f"Processing fake focus winEvent {getWinEventLogInfo(window, objectID, childID)}" + f"Processing fake focus winEvent {getWinEventLogInfo(window, objectID, childID)}", ) core.callLater(50, _fakeFocus, api.getFocusObject()) @@ -977,7 +977,7 @@ def _fakeFocus(oldFocus): return if isMSAADebugLoggingEnabled(): log.debug( - f"Faking focus on {focus}" + f"Faking focus on {focus}", ) processFocusNVDAEvent(focus) @@ -1017,7 +1017,7 @@ def pumpAll(): # noqa: C901 isEventOnCaret = winEvent[2] == winUser.OBJID_CARET showHideCaretEvent = focus and isEventOnCaret and winEvent[0] in [ winUser.EVENT_OBJECT_SHOW, - winUser.EVENT_OBJECT_HIDE + winUser.EVENT_OBJECT_HIDE, ] # #4001: Ideally, we'd call shouldAcceptEvent in winEventCallback, but this causes focus issues when # starting applications. #7332: If this is a show event, which would normally be dropped by @@ -1028,13 +1028,13 @@ def pumpAll(): # noqa: C901 continue elif not eventHandler.shouldAcceptEvent( internalWinEventHandler.winEventIDsToNVDAEventNames[winEvent[0]], - windowHandle=winEvent[1] + windowHandle=winEvent[1], ): continue # We want to only pass on one focus event to NVDA, but we always want to use the most recent possible one if winEvent[0] in ( winUser.EVENT_OBJECT_FOCUS, - winUser.EVENT_SYSTEM_FOREGROUND + winUser.EVENT_SYSTEM_FOREGROUND, ): focusWinEvents.append(winEvent) continue @@ -1067,7 +1067,7 @@ def pumpAll(): # noqa: C901 # Try this as a last resort. if fakeFocusEvent[0] in ( winUser.EVENT_SYSTEM_MENUSTART, - winUser.EVENT_SYSTEM_MENUPOPUPSTART + winUser.EVENT_SYSTEM_MENUPOPUPSTART, ): # menuStart needs to be handled specially and might act even if there was a valid focus event. processMenuStartWinEvent(*fakeFocusEvent, validFocus=validFocus) @@ -1189,7 +1189,7 @@ def getRecursiveTextFromIAccessibleTextObject(obj, startOffset=0, endOffset=-1): ATTRIBS_STRING_BASE64_PATTERN = re.compile( - r"(([^\\](\\\\)*);src:data\\:[^\\;]+\\;base64\\,)[A-Za-z0-9+/=]+" + r"(([^\\](\\\\)*);src:data\\:[^\\;]+\\;base64\\,)[A-Za-z0-9+/=]+", ) ATTRIBS_STRING_BASE64_REPL = r"\1" ATTRIBS_STRING_BASE64_THRESHOLD = 4096 @@ -1197,7 +1197,7 @@ def getRecursiveTextFromIAccessibleTextObject(obj, startOffset=0, endOffset=-1): # C901: splitIA2Attribs is too complex def splitIA2Attribs( # noqa: C901 - attribsString: str + attribsString: str, ) -> Dict[str, Union[str, Dict]]: """Split an IAccessible2 attributes string into a dict of attribute keys and values. An invalid attributes string does not cause an error, but strange results may be returned. @@ -1279,7 +1279,8 @@ def isMarshalledIAccessible(IAccessibleObject): raise TypeError("object should be of type IAccessible, not %s" % IAccessibleObject) buf = create_unicode_buffer(1024) addr = POINTER(c_void_p).from_address( - super(comtypes._compointer_base, IAccessibleObject).value).contents.value + super(comtypes._compointer_base, IAccessibleObject).value, + ).contents.value handle = HANDLE() windll.kernel32.GetModuleHandleExW(6, addr, byref(handle)) windll.kernel32.GetModuleFileNameW(handle, buf, 1024) diff --git a/source/IAccessibleHandler/internalWinEventHandler.py b/source/IAccessibleHandler/internalWinEventHandler.py index 6534b5e49a0..4baaf896b96 100644 --- a/source/IAccessibleHandler/internalWinEventHandler.py +++ b/source/IAccessibleHandler/internalWinEventHandler.py @@ -68,7 +68,7 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, timestamp): # noqa: C901 if isMSAADebugLoggingEnabled(): log.debug( - f"Hook received winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"Hook received winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) try: # Ignore all object IDs from alert onwards (sound, nativeom etc) as we don't support them @@ -76,7 +76,7 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times if isMSAADebugLoggingEnabled(): log.debug( f"objectID not supported. " - f"Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) return # Ignore all locationChange events except ones for the caret @@ -84,7 +84,7 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times if isMSAADebugLoggingEnabled(): log.debug( f"locationChange for something other than the caret. " - f"Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"Dropping winEvent {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) return if eventID == winUser.EVENT_OBJECT_DESTROY: @@ -96,7 +96,7 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times if isMSAADebugLoggingEnabled(): log.debug( f"Changing OBJID_WINDOW to OBJID_CLIENT " - f"for winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"for winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) # Ignore events with invalid window handles isWindow = winUser.isWindow(window) if window else 0 @@ -111,14 +111,14 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times if isMSAADebugLoggingEnabled(): log.debug( f"Changing NULL or invalid window to desktop window " - f"for winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"for winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) window = winUser.getDesktopWindow() elif not isWindow: if isMSAADebugLoggingEnabled(): log.debug( f"Invalid window. " - f"Dropping winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"Dropping winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) return @@ -132,7 +132,7 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times if windowClassName == "EXCEL7" and objectID > 0: log.debug( f"Dropping UIA proxied event for Excel7 window. " - f"WinEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"WinEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) return if windowClassName == "ConsoleWindowClass": @@ -145,7 +145,7 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times if isMSAADebugLoggingEnabled(): log.debug( f"Dropping menu event for IME window. " - f"WinEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"WinEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) return if eventID == winUser.EVENT_SYSTEM_FOREGROUND: @@ -154,7 +154,7 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times if isMSAADebugLoggingEnabled(): log.debug( f"Progman or shell_trayWnd window. " - f"Dropping winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"Dropping winEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) return # #3831: Event handling can be deferred if Windows takes a while to change the foreground window. @@ -165,7 +165,7 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times if isMSAADebugLoggingEnabled(): log.debug( f"Recording foreground defer " - f"for WinEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"for WinEvent: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) if windowClassName == "MSNHiddenWindowClass": # HACK: Events get fired by this window in Windows Live Messenger 2009 when it starts. If we send a @@ -174,7 +174,7 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times return if isMSAADebugLoggingEnabled(): log.debug( - f"Adding winEvent to limiter: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"Adding winEvent to limiter: {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) if winEventLimiter.addEvent(eventID, window, objectID, childID, threadID): core.requestPump(immediate=eventID == winUser.EVENT_OBJECT_FOCUS) @@ -189,11 +189,13 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times def initialize( - processDestroyWinEventFunc: Callable[[ - c_int, # window - c_int, # objectID - c_int, # childID - ], None] + processDestroyWinEventFunc: Callable[ + [ + c_int, # window + c_int, # objectID + c_int, # childID + ], None, + ], ): global _processDestroyWinEvent _processDestroyWinEvent = processDestroyWinEventFunc @@ -204,7 +206,7 @@ def initialize( else: log.error( f"initialize: could not register callback for" - f" event {eventType} ({winEventIDsToNVDAEventNames[eventType]})" + f" event {eventType} ({winEventIDsToNVDAEventNames[eventType]})", ) @@ -233,7 +235,7 @@ def _shouldGetEvents(): log.debugWarning( f"Foreground still {curForegroundWindow} ({curForegroundClassName}). " f"Deferring until foreground is {_deferUntilForegroundWindow} ({futureForegroundClassName}), " - f"defer count {_foregroundDefers}" + f"defer count {_foregroundDefers}", ) return False else: @@ -244,7 +246,7 @@ def _shouldGetEvents(): log.debugWarning( "Foreground took too long to change. " f"Foreground still {curForegroundWindow} ({curForegroundClassName}). " - f"Should be {_deferUntilForegroundWindow} ({futureForegroundClassName})" + f"Should be {_deferUntilForegroundWindow} ({futureForegroundClassName})", ) _deferUntilForegroundWindow = None return True diff --git a/source/IAccessibleHandler/orderedWinEventLimiter.py b/source/IAccessibleHandler/orderedWinEventLimiter.py index 54a1ca73e4f..bb81e807cc0 100644 --- a/source/IAccessibleHandler/orderedWinEventLimiter.py +++ b/source/IAccessibleHandler/orderedWinEventLimiter.py @@ -14,7 +14,7 @@ winUser.EVENT_SYSTEM_MENUSTART, winUser.EVENT_SYSTEM_MENUEND, winUser.EVENT_SYSTEM_MENUPOPUPSTART, - winUser.EVENT_SYSTEM_MENUPOPUPEND + winUser.EVENT_SYSTEM_MENUPOPUPEND, ) @@ -47,7 +47,7 @@ def addEvent( window: int, objectID: int, childID: int, - threadID: int + threadID: int, ) -> bool: """Adds a winEvent to the limiter. @param eventID: the winEvent type @@ -82,7 +82,7 @@ def addEvent( def flushEvents( self, - alwaysAllowedObjects: Optional[List[IAccessibleObjectIdentifierType]] = None + alwaysAllowedObjects: Optional[List[IAccessibleObjectIdentifierType]] = None, ) -> List: """Returns a list of winEvents that have been added. Due to limiting, it will not necessarily be all the winEvents that were originally added. @@ -123,7 +123,7 @@ def flushEvents( if isMSAADebugLoggingEnabled(): eventID, window, objectID, childID, threadID = event log.debug( - f"Emitting winEvent {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}" + f"Emitting winEvent {getWinEventLogInfo(window, objectID, childID, eventID, threadID)}", ) r.append(event[:-1]) return r diff --git a/source/IAccessibleHandler/utils.py b/source/IAccessibleHandler/utils.py index 2ede0b86f14..ad3f9075139 100644 --- a/source/IAccessibleHandler/utils.py +++ b/source/IAccessibleHandler/utils.py @@ -62,7 +62,7 @@ def getWinEventLogInfo(window, objectID, childID, eventID=None, threadID=None): messageList.append(f"{eventName}") messageList.append( f"window {window} ({windowClassName}), objectID {objectIDName}, childID {childID}, " - f"process {processID} ({processName})" + f"process {processID} ({processName})", ) if threadID is not None: messageList.append(f"thread {threadID}") diff --git a/source/JABHandler.py b/source/JABHandler.py index 2d662d22879..c8198dff662 100644 --- a/source/JABHandler.py +++ b/source/JABHandler.py @@ -26,7 +26,7 @@ CFUNCTYPE, WinError, create_string_buffer, - create_unicode_buffer + create_unicode_buffer, ) from ctypes.wintypes import BOOL, HWND, WCHAR import time @@ -339,7 +339,7 @@ def _fixBridgeFuncs(): JOBJECT64, POINTER(AccessibleTextRectInfo), jint, - errcheck=True + errcheck=True, ) _fixBridgeFunc(BOOL,'getAccessibleTextLineBounds',c_long,JOBJECT64,jint,POINTER(jint),POINTER(jint),errcheck=True) _fixBridgeFunc(BOOL,'getAccessibleTextRange',c_long,JOBJECT64,jint,jint,POINTER(c_char),c_short,errcheck=True) @@ -839,7 +839,8 @@ def initialize(): global bridgeDll, isRunning try: bridgeDll = cdll.LoadLibrary( - os.path.join(NVDAHelper.versionedLibPath, "windowsaccessbridge-32.dll")) + os.path.join(NVDAHelper.versionedLibPath, "windowsaccessbridge-32.dll"), + ) except WindowsError: raise NotImplementedError("dll not available") _fixBridgeFuncs() @@ -900,7 +901,7 @@ def terminate(): AccessibleVK.HOME: "home", AccessibleVK.END: "end", AccessibleVK.PAGE_UP: "pageup", - AccessibleVK.PAGE_DOWN: "pagedown" + AccessibleVK.PAGE_DOWN: "pagedown", } # Do not include AccessibleKeystroke.FKEY_KEYSTROKE and AccessibleKeystroke.CONTROLCODE @@ -913,7 +914,7 @@ def terminate(): AccessibleKeystroke.ALT: "alt", AccessibleKeystroke.META: "meta", AccessibleKeystroke.CONTROL: "control", - AccessibleKeystroke.SHIFT: "shift" + AccessibleKeystroke.SHIFT: "shift", } diff --git a/source/NVDAHelper.py b/source/NVDAHelper.py index d27b53108ac..390f505572e 100755 --- a/source/NVDAHelper.py +++ b/source/NVDAHelper.py @@ -146,7 +146,7 @@ def markCallable(name: str): speech.speak, speechSequence=sequence, symbolLevel=symbolLevel, - priority=priority + priority=priority, ) if not asynchronous: try: @@ -253,12 +253,12 @@ def nvdaControllerInternal_reportLiveRegion(text: str, politeness: str): Spri.NEXT if politenessValue == AriaLivePoliteness.ASSERTIVE else Spri.NORMAL - ) + ), ) queueHandler.queueFunction( queueHandler.eventQueue, braille.handler.message, - text + text, ) return 0 @@ -408,13 +408,13 @@ def nvdaControllerInternal_inputCandidateListUpdate(candidatesString,selectionIn # Translators: A mode that allows typing in the actual 'native' characters for an east-Asian input method language currently selected, rather than alpha numeric (Roman/English) characters. _("Native input"), # Translators: a mode that lets you type in alpha numeric (roman/english) characters, rather than 'native' characters for the east-Asian input method language currently selected. - _("Alpha numeric input") + _("Alpha numeric input"), ), 8:( # Translators: for East-Asian input methods, a mode that allows typing in full-shaped (full double-byte) characters, rather than the smaller half-shaped ones. _("Full shaped mode"), # Translators: for East-Asian input methods, a mode that allows typing in half-shaped (single-byte) characters, rather than the larger full-shaped (double-byte) ones. - _("Half shaped mode") + _("Half shaped mode"), ), } @@ -679,7 +679,8 @@ def initialize() -> None: # Handle VBuf_getTextInRange's BSTR out parameter so that the BSTR will be freed automatically. VBuf_getTextInRange = CFUNCTYPE(c_int, c_int, c_int, c_int, POINTER(BSTR), c_int)( # noqa: F405 ("VBuf_getTextInRange", localLib), - ((1,), (1,), (1,), (2,), (1,))) + ((1,), (1,), (1,), (2,), (1,)), + ) if config.isAppX: log.info("Remote injection disabled due to running as a Windows Store Application") return @@ -690,7 +691,7 @@ def initialize() -> None: # Using an altered search path is necessary here # As NVDAHelperRemote needs to locate dependent dlls in the same directory # such as IAccessible2proxy.dll. - winKernel.LOAD_WITH_ALTERED_SEARCH_PATH + winKernel.LOAD_WITH_ALTERED_SEARCH_PATH, ) if not h: log.critical("Error loading nvdaHelperRemote.dll: %s" % WinError()) # noqa: F405 diff --git a/source/NVDAObjects/IAccessible/__init__.py b/source/NVDAObjects/IAccessible/__init__.py index 37cf10b6d1f..6b1699e38f0 100644 --- a/source/NVDAObjects/IAccessible/__init__.py +++ b/source/NVDAObjects/IAccessible/__init__.py @@ -172,7 +172,7 @@ def _get_encoding(self): def _getOffsetFromPoint(self,x,y): if self.obj.IAccessibleTextObject.nCharacters>0: offset = self.obj.IAccessibleTextObject.OffsetAtPoint( - x, y, IA2.IA2_COORDTYPE_SCREEN_RELATIVE + x, y, IA2.IA2_COORDTYPE_SCREEN_RELATIVE, ) # IA2 specifies that a result of -1 indicates that # the point is invalid or there is no character under the point. @@ -187,9 +187,11 @@ def _getOffsetFromPoint(self,x,y): @classmethod def _getBoundingRectFromOffsetInObject(cls,obj,offset): try: - res = RectLTWH(*obj.IAccessibleTextObject.characterExtents( - offset, IA2.IA2_COORDTYPE_SCREEN_RELATIVE - )) + res = RectLTWH( + *obj.IAccessibleTextObject.characterExtents( + offset, IA2.IA2_COORDTYPE_SCREEN_RELATIVE, + ), + ) except COMError: raise NotImplementedError if not any(res[2:]): @@ -386,7 +388,7 @@ def _lineNumFromOffset(self,offset): def _iterTextWithEmbeddedObjects( self, withFields, - formatConfig=None + formatConfig=None, ) -> typing.Generator[typing.Union[textInfos.FieldCommand, str, int], None, None]: """Iterate through the text, splitting at embedded object characters. Where an embedded object character occurs, its offset is provided. @@ -543,8 +545,9 @@ def findOverlayClasses(self,clsList): windowClassName.lower().startswith('mscandui') or windowClassName in ( "Microsoft.IME.CandidateWindow.View", - "Microsoft.IME.UIManager.CandidateWindow.Host" - )): + "Microsoft.IME.UIManager.CandidateWindow.Host", + ) + ): from . import mscandui mscandui.findExtraOverlayClasses(self,clsList) elif windowClassName=="GeckoPluginWindow" and self.event_objectID==0 and self.IAccessibleChildID==0: @@ -653,7 +656,7 @@ def __init__( # noqa: C901 IAccessibleChildID: Optional[int] = None, event_windowHandle: Optional = None, event_objectID: Optional = None, - event_childID: Optional = None + event_childID: Optional = None, ): """ @param windowHandle: the window handle, if known @@ -949,7 +952,7 @@ def _get_states(self) -> typing.Set[controlTypes.State]: # noqa: C901 log.debugWarning("could not get IAccessible states",exc_info=True) else: states.update( - IAccessibleHandler.calculateNvdaStates(self.IAccessibleRole, IAccessibleStates) + IAccessibleHandler.calculateNvdaStates(self.IAccessibleRole, IAccessibleStates), ) if not isinstance(self.IAccessibleObject, IA2.IAccessible2): @@ -1171,8 +1174,10 @@ def getChild(self, index): return super(IAccessible, self).getChild(index) return None if child[0] == self.IAccessibleObject: - return IAccessible(windowHandle=self.windowHandle, IAccessibleObject=self.IAccessibleObject, IAccessibleChildID=child[1], - event_windowHandle=self.event_windowHandle, event_objectID=self.event_objectID, event_childID=child[1]) + return IAccessible( + windowHandle=self.windowHandle, IAccessibleObject=self.IAccessibleObject, IAccessibleChildID=child[1], + event_windowHandle=self.event_windowHandle, event_objectID=self.event_objectID, event_childID=child[1], + ) return self.correctAPIForRelation(IAccessible(IAccessibleObject=child[0], IAccessibleChildID=child[1])) #: Type definition for auto prop '_get_IA2Attributes' @@ -1591,7 +1596,7 @@ def _getIA2TargetsForRelationsOfType( relationType.value, # Bug in relationTargetsOfType, Chrome does not respect maxRelations param. # https://crbug.com/1399184 - maxRelations + maxRelations, ) if config.conf["debugLog"]["annotations"]: log.debug(f"Got {count} relations, given maxRelations: {maxRelations}") @@ -1604,7 +1609,7 @@ def _getIA2TargetsForRelationsOfType( def _getIA2RelationFirstTarget( self, - relationType: typing.Union[str, "IAccessibleHandler.RelationType"] + relationType: typing.Union[str, "IAccessibleHandler.RelationType"], ) -> typing.Optional["IAccessible"]: """ Get the first target for the relation of type. @param relationType: The type of relation to fetch. @@ -1625,7 +1630,7 @@ def _getIA2RelationFirstTarget( # Just take the first. return IAccessible( IAccessibleObject=ia2Object, - IAccessibleChildID=0 + IAccessibleChildID=0, ) except (NotImplementedError, COMError): log.debugWarning("Unable to use _getIA2TargetsForRelationsOfType, fallback to _IA2Relations.") @@ -1639,7 +1644,7 @@ def _getIA2RelationFirstTarget( ia2Object = IAccessibleHandler.normalizeIAccessible(target) return IAccessible( IAccessibleObject=ia2Object, - IAccessibleChildID=0 + IAccessibleChildID=0, ) except (NotImplementedError, COMError): log.debug("Unable to fetch _IA2Relations", exc_info=True) @@ -1648,7 +1653,7 @@ def _getIA2RelationFirstTarget( def _getIA2RelationTargetsOfType( self, - relationType: Union[str, IAccessibleHandler.RelationType] + relationType: Union[str, IAccessibleHandler.RelationType], ) -> typing.Iterable["IAccessible"]: """ Get the targets for the relation of type. Higher level function than _getIA2TargetsForRelationsOfType @@ -1674,7 +1679,7 @@ def _getIA2RelationTargetsOfType( ia2Object = IAccessibleHandler.normalizeIAccessible(target) ia = IAccessible( IAccessibleObject=ia2Object, - IAccessibleChildID=0 + IAccessibleChildID=0, ) yield ia # NotImplementedError is expected to occur for all targets or none. @@ -1693,7 +1698,7 @@ def _getIA2RelationTargetsOfType( ia2Object = IAccessibleHandler.normalizeIAccessible(target) yield IAccessible( IAccessibleObject=ia2Object, - IAccessibleChildID=0 + IAccessibleChildID=0, ) return except (NotImplementedError, COMError): diff --git a/source/NVDAObjects/IAccessible/chromium.py b/source/NVDAObjects/IAccessible/chromium.py index 5a78be1d513..f370d4cb050 100644 --- a/source/NVDAObjects/IAccessible/chromium.py +++ b/source/NVDAObjects/IAccessible/chromium.py @@ -103,7 +103,7 @@ class Document(ia2Web.Document): def _get_treeInterceptorClass(self) -> typing.Type["TreeInterceptor"]: shouldLoadVBufOnBusyFeatureFlag = bool( - config.conf["virtualBuffers"]["loadChromiumVBufOnBusyState"] + config.conf["virtualBuffers"]["loadChromiumVBufOnBusyState"], ) vBufUnavailableStates = { # if any of these are in states, don't return ChromeVBuf controlTypes.State.EDITABLE, @@ -111,13 +111,13 @@ def _get_treeInterceptorClass(self) -> typing.Type["TreeInterceptor"]: if not shouldLoadVBufOnBusyFeatureFlag: log.debug( f"loadChromiumVBufOnBusyState feature flag is {shouldLoadVBufOnBusyFeatureFlag}," - " vBuf WILL NOT be loaded when state of the document is busy." + " vBuf WILL NOT be loaded when state of the document is busy.", ) vBufUnavailableStates.add(controlTypes.State.BUSY) else: log.debug( f"loadChromiumVBufOnBusyState feature flag is {shouldLoadVBufOnBusyFeatureFlag}," - " vBuf WILL be loaded when state of the document is busy." + " vBuf WILL be loaded when state of the document is busy.", ) if self.states.intersection(vBufUnavailableStates): return super().treeInterceptorClass @@ -178,5 +178,7 @@ def findExtraOverlayClasses(obj, clsList): clsList.append(PresentationalList) elif obj.role == controlTypes.Role.GROUPING and obj.IA2Attributes.get("tag", "").casefold() == "figure": clsList.append(Figure) - ia2Web.findExtraOverlayClasses(obj, clsList, - documentClass=Document) + ia2Web.findExtraOverlayClasses( + obj, clsList, + documentClass=Document, + ) diff --git a/source/NVDAObjects/IAccessible/ia2TextMozilla.py b/source/NVDAObjects/IAccessible/ia2TextMozilla.py index 9ed7c673115..c6d05ecf759 100644 --- a/source/NVDAObjects/IAccessible/ia2TextMozilla.py +++ b/source/NVDAObjects/IAccessible/ia2TextMozilla.py @@ -35,7 +35,7 @@ def _getStoryLength(self): def _iterTextWithEmbeddedObjects( self, withFields, - formatConfig=None + formatConfig=None, ) -> typing.Generator[int, None, None]: yield from range(self._startOffset, self._endOffset) @@ -89,7 +89,7 @@ def _isCaretAtEndOfLine(self, caretObj: IAccessible) -> bool: # determine whether we are at this position. try: start, end, text = caretObj.IAccessibleTextObject.textAtOffset( - IA2.IA2_TEXT_OFFSET_CARET, IA2.IA2_TEXT_BOUNDARY_CHAR + IA2.IA2_TEXT_OFFSET_CARET, IA2.IA2_TEXT_BOUNDARY_CHAR, ) # If the offsets are different, this means there is a character, which # means this is not the insertion point at the end of a line. @@ -104,7 +104,7 @@ def _isCaretAtEndOfLine(self, caretObj: IAccessible) -> bool: except COMError: log.debugWarning( "Couldn't determine if caret is at end of line insertion point", - exc_info=True + exc_info=True, ) return False @@ -368,7 +368,7 @@ def _getText(self, withFields, formatConfig=None): if not ti: log.debugWarning( "_getEmbedding returned None while getting initial fields. " - "Object probably dead." + "Object probably dead.", ) return [] obj = ti.obj @@ -403,7 +403,7 @@ def _getText(self, withFields, formatConfig=None): if not ti: log.debugWarning( "_getEmbedding returned None while ascending to get more text. " - "Object probably dead." + "Object probably dead.", ) return [] obj = ti.obj @@ -443,7 +443,7 @@ def _adjustIfEndOfLine( self, expandTi: offsets.OffsetsTextInfo, unit: str, - obj: IAccessible + obj: IAccessible, ) -> None: if ( self._isEndOfLineInsertionPoint and unit != textInfos.UNIT_CHARACTER diff --git a/source/NVDAObjects/IAccessible/ia2Web.py b/source/NVDAObjects/IAccessible/ia2Web.py index df15a7875ee..d968ac940a4 100644 --- a/source/NVDAObjects/IAccessible/ia2Web.py +++ b/source/NVDAObjects/IAccessible/ia2Web.py @@ -56,7 +56,7 @@ class IA2WebAnnotation(AnnotationOrigin): def __bool__(self) -> bool: return bool( - self._originObj.IA2Attributes.get("details-roles") + self._originObj.IA2Attributes.get("details-roles"), ) @property @@ -211,7 +211,7 @@ def _get_states(self): states.discard(controlTypes.State.EDITABLE) if controlTypes.State.HASPOPUP in states: popupState = aria.ariaHaspopupValuesToNVDAStates.get( - self.IA2Attributes.get("haspopup") + self.IA2Attributes.get("haspopup"), ) if popupState: states.discard(controlTypes.State.HASPOPUP) @@ -239,7 +239,7 @@ def event_IA2AttributeChange(self): speech.speakObjectProperties( self, current=True, - reason=controlTypes.OutputReason.CHANGE + reason=controlTypes.OutputReason.CHANGE, ) # super calls event_stateChange which updates braille, so no need to # update braille here. @@ -302,7 +302,7 @@ def _getTableCellAt(self,tableID,startPos,destRow,destCol): except AttributeError: # No IAccessibleTable2, try IAccessibleTable instead. cell = table.IAccessibleTableObject.accessibleAt( - destRow - 1, destCol - 1 + destRow - 1, destCol - 1, ).QueryInterface(IA2.IAccessible2) cell = IAccessible(IAccessibleObject=cell, IAccessibleChildID=0) # If the cell we fetched is marked as hidden, raise LookupError which will instruct calling code to try an adjacent cell instead. @@ -350,8 +350,10 @@ def _get_mathMl(self): attrs = "" return "%s" % (attrs, node.innerHTML) except COMError: - log.debugWarning("Error retrieving math. " - "Not supported in this browser or ISimpleDOM COM proxy not registered.", exc_info=True) + log.debugWarning( + "Error retrieving math. " + "Not supported in this browser or ISimpleDOM COM proxy not registered.", exc_info=True, + ) raise LookupError diff --git a/source/NVDAObjects/IAccessible/mozilla.py b/source/NVDAObjects/IAccessible/mozilla.py index a03176d5eb0..5422f182c68 100755 --- a/source/NVDAObjects/IAccessible/mozilla.py +++ b/source/NVDAObjects/IAccessible/mozilla.py @@ -41,7 +41,7 @@ def role(self) -> Optional[controlTypes.Role]: # this may diverge in Firefox in the future. from .chromium import supportedAriaDetailsRoles detailsRole = IAccessibleHandler.IAccessibleRolesToNVDARoles.get( - self._target.IAccessibleRole + self._target.IAccessibleRole, ) # return a supported details role if config.conf["debugLog"]["annotations"]: @@ -69,7 +69,7 @@ def __bool__(self) -> bool: # IA2 attribute is not exposed in Firefox. # Although slower, we have to fetch the details relations instead. return bool( - self._originObj.detailsRelations + self._originObj.detailsRelations, ) @property @@ -173,14 +173,14 @@ class Document(ia2Web.Document): def _get_parent(self): res = IAccessibleHandler.accParent( - self.IAccessibleObject, self.IAccessibleChildID + self.IAccessibleObject, self.IAccessibleChildID, ) if not res: # accParent is broken in Firefox for same-process iframe documents. # Use NODE_CHILD_OF instead. res = IAccessibleHandler.accNavigate( self.IAccessibleObject, self.IAccessibleChildID, - IAccessibleHandler.NAVRELATION_NODE_CHILD_OF + IAccessibleHandler.NAVRELATION_NODE_CHILD_OF, ) if not res: return None @@ -268,8 +268,10 @@ def findExtraOverlayClasses(obj, clsList): if hasattr(parent, "IAccessibleTableObject") or hasattr(parent, "IAccessibleTable2Object"): clsList.append(RowWithFakeNavigation) - ia2Web.findExtraOverlayClasses(obj, clsList, - baseClass=Mozilla, documentClass=Document) + ia2Web.findExtraOverlayClasses( + obj, clsList, + baseClass=Mozilla, documentClass=Document, + ) #: Maps IAccessible roles to NVDAObject overlay classes. _IAccessibleRolesToOverlayClasses = { diff --git a/source/NVDAObjects/IAccessible/mscandui.py b/source/NVDAObjects/IAccessible/mscandui.py index a3cf860bb25..a7196f954a8 100755 --- a/source/NVDAObjects/IAccessible/mscandui.py +++ b/source/NVDAObjects/IAccessible/mscandui.py @@ -261,7 +261,8 @@ def findExtraOverlayClasses(obj,clsList): and ( obj.role==controlTypes.Role.BUTTON or obj.role==controlTypes.Role.LISTITEM - )): + ) + ): clsList.append(ModernCandidateUICandidateItem) elif windowClassName=="MSCandUIWindow_Candidate": if role==oleacc.ROLE_SYSTEM_CLIENT: diff --git a/source/NVDAObjects/IAccessible/sysListView32.py b/source/NVDAObjects/IAccessible/sysListView32.py index aac86117f18..b592374915b 100644 --- a/source/NVDAObjects/IAccessible/sysListView32.py +++ b/source/NVDAObjects/IAccessible/sysListView32.py @@ -242,7 +242,7 @@ def _getColumnOrderArrayRawInProc(self, columnCount: int) -> Optional[ctypes.Arr self.appModule.helperLocalBindingHandle, self.windowHandle, columnCount, - columnOrderArray + columnOrderArray, ) if res: return None @@ -268,7 +268,7 @@ def _getColumnOrderArrayRawOutProc(self, columnCount: int) -> Optional[ctypes.Ar self.windowHandle, LVM_GETCOLUMNORDERARRAY, columnCount, - internalCoa + internalCoa, ) if res: winKernel.readProcessMemory(processHandle,internalCoa,byref(coa),sizeof(coa),None) # noqa: F405 @@ -276,7 +276,7 @@ def _getColumnOrderArrayRawOutProc(self, columnCount: int) -> Optional[ctypes.Ar coa = None log.debugWarning( f"LVM_GETCOLUMNORDERARRAY failed for list. " - f"Windows Error: {ctypes.GetLastError()}, Handle: {self.windowHandle}" + f"Windows Error: {ctypes.GetLastError()}, Handle: {self.windowHandle}", ) finally: winKernel.virtualFreeEx(processHandle,internalCoa,0,winKernel.MEM_RELEASE) @@ -408,7 +408,7 @@ def _getColumnLocationRawInProc(self, index: int) -> ctypes.wintypes.RECT: self.windowHandle, item, subItem, - ctypes.byref(rect) + ctypes.byref(rect), ) != 0: return None return rect @@ -427,7 +427,7 @@ def _getColumnLocationRawOutProc(self, index: int) -> ctypes.wintypes.RECT: left=LVIR_LABEL, # According to Microsoft, top should be the one-based index of the subitem. # However, indexes coming from LVM_GETCOLUMNORDERARRAY are zero based. - top=index + top=index, ) internalRect=winKernel.virtualAllocEx(processHandle,None,sizeof(localRect),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) # noqa: F405 try: @@ -436,7 +436,7 @@ def _getColumnLocationRawOutProc(self, index: int) -> ctypes.wintypes.RECT: self.windowHandle, LVM_GETSUBITEMRECT, self.IAccessibleChildID - 1, - internalRect + internalRect, ) if res: winKernel.readProcessMemory( @@ -444,7 +444,7 @@ def _getColumnLocationRawOutProc(self, index: int) -> ctypes.wintypes.RECT: internalRect, ctypes.byref(localRect), ctypes.sizeof(localRect), - None + None, ) finally: winKernel.virtualFreeEx(processHandle,internalRect,0,winKernel.MEM_RELEASE) @@ -494,7 +494,7 @@ def _getColumnContentRawInProc(self, index: int) -> Optional[str]: self.windowHandle, item, subItem, - ctypes.byref(text) + ctypes.byref(text), ) != 0: return None return text.value @@ -594,7 +594,7 @@ def _getColumnHeaderRawInProc(self, index: int) -> Optional[str]: self.appModule.helperLocalBindingHandle, self.windowHandle, subItem, - ctypes.byref(text) + ctypes.byref(text), ) != 0: return None return text.value diff --git a/source/NVDAObjects/IAccessible/winword.py b/source/NVDAObjects/IAccessible/winword.py index c2c91c83268..2ba3b76ab58 100644 --- a/source/NVDAObjects/IAccessible/winword.py +++ b/source/NVDAObjects/IAccessible/winword.py @@ -218,9 +218,9 @@ def fetchAssociatedHeaderCellText(self,cell,columnHeader=False): # Translators: The label of a shortcut of NVDA. "Set column header. Pressing once will set this cell as the first column header for any cell lower and " "to the right of it within this table. Pressing twice will forget the current column header for this " - "cell." + "cell.", ), - category=SCRCAT_SYSTEMCARET + category=SCRCAT_SYSTEMCARET, ) def script_setColumnHeader(self,gesture): scriptCount=scriptHandler.getLastScriptRepeatCount() @@ -250,9 +250,9 @@ def script_setColumnHeader(self,gesture): description=_( # Translators: The label of a shortcut of NVDA. "Set row header. Pressing once will set this cell as the first row header for any cell lower and to the " - "right of it within this table. Pressing twice will forget the current row header for this cell." + "right of it within this table. Pressing twice will forget the current row header for this cell.", ), - category=SCRCAT_SYSTEMCARET + category=SCRCAT_SYSTEMCARET, ) def script_setRowHeader(self,gesture): scriptCount=scriptHandler.getLastScriptRepeatCount() @@ -282,8 +282,8 @@ def script_setRowHeader(self,gesture): "kb:alt+home", "kb:alt+end", "kb:alt+pageUp", - "kb:alt+pageDown" - ) + "kb:alt+pageDown", + ), ) def script_caret_moveByCell(self, gesture: inputCore.InputGesture) -> None: info = self.makeTextInfo(textInfos.POSITION_SELECTION) @@ -388,7 +388,7 @@ def _moveInTable(self,row=True,forward=True): ui.message(_("Edge of table")) return False newInfo = winWordWindowModule.WordDocumentTextInfo( - self, textInfos.POSITION_CARET, _rangeObj=foundCell + self, textInfos.POSITION_CARET, _rangeObj=foundCell, ) speech.speakTextInfo(newInfo, reason=controlTypes.OutputReason.CARET, unit=textInfos.UNIT_CELL) newInfo.collapse() @@ -396,32 +396,32 @@ def _moveInTable(self,row=True,forward=True): return True @script( - gesture="kb:control+alt+downArrow" + gesture="kb:control+alt+downArrow", ) def script_nextRow(self,gesture): self._moveInTable(row=True,forward=True) @script( - gesture="kb:control+alt+upArrow" + gesture="kb:control+alt+upArrow", ) def script_previousRow(self,gesture): self._moveInTable(row=True,forward=False) @script( - gesture="kb:control+alt+rightArrow" + gesture="kb:control+alt+rightArrow", ) def script_nextColumn(self,gesture): self._moveInTable(row=False,forward=True) @script( - gesture="kb:control+alt+leftArrow" + gesture="kb:control+alt+leftArrow", ) def script_previousColumn(self,gesture): self._moveInTable(row=False,forward=False) @script( gesture="kb:control+downArrow", - resumeSayAllMode=sayAll.CURSOR.CARET + resumeSayAllMode=sayAll.CURSOR.CARET, ) def script_nextParagraph(self,gesture): info=self.makeTextInfo(textInfos.POSITION_CARET) @@ -432,7 +432,7 @@ def script_nextParagraph(self,gesture): @script( gesture="kb:control+upArrow", - resumeSayAllMode=sayAll.CURSOR.CARET + resumeSayAllMode=sayAll.CURSOR.CARET, ) def script_previousParagraph(self,gesture): info=self.makeTextInfo(textInfos.POSITION_CARET) @@ -448,7 +448,7 @@ def script_previousParagraph(self,gesture): "kb:control+y", "kb:control+z", "kb:alt+backspace", - ) + ), ) def script_updateBrailleAndReviewPosition(self, gesture: inputCore.InputGesture) -> None: """Helper script to update braille and review position. diff --git a/source/NVDAObjects/JAB/__init__.py b/source/NVDAObjects/JAB/__init__.py index 60aaaaa51c9..70bdcf074bf 100644 --- a/source/NVDAObjects/JAB/__init__.py +++ b/source/NVDAObjects/JAB/__init__.py @@ -361,7 +361,7 @@ def _get_value(self): self.role not in [ controlTypes.Role.TOGGLEBUTTON, controlTypes.Role.CHECKBOX, controlTypes.Role.MENU, controlTypes.Role.MENUITEM, - controlTypes.Role.RADIOBUTTON, controlTypes.Role.BUTTON + controlTypes.Role.RADIOBUTTON, controlTypes.Role.BUTTON, ] and self._JABAccContextInfo.accessibleValue and not self._JABAccContextInfo.accessibleText @@ -409,7 +409,7 @@ def _get_positionInfo(self): and self.role in ( controlTypes.Role.TREEVIEWITEM, controlTypes.Role.LISTITEM, - controlTypes.Role.TAB + controlTypes.Role.TAB, ) ): index=self._JABAccContextInfo.indexInParent+1 @@ -573,9 +573,11 @@ def doAction(self, index=None): if index is None: index = self.defaultActionIndex try: - JABHandler.bridgeDll.doAccessibleActions(self.jabContext.vmID, self.jabContext.accContext, - JABHandler.AccessibleActionsToDo(actionsCount=1, actions=(self._actions[index],)), - JABHandler.jint()) + JABHandler.bridgeDll.doAccessibleActions( + self.jabContext.vmID, self.jabContext.accContext, + JABHandler.AccessibleActionsToDo(actionsCount=1, actions=(self._actions[index],)), + JABHandler.jint(), + ) except (IndexError, RuntimeError): raise NotImplementedError diff --git a/source/NVDAObjects/UIA/VisualStudio.py b/source/NVDAObjects/UIA/VisualStudio.py index 352c253b5ae..caf24288b43 100644 --- a/source/NVDAObjects/UIA/VisualStudio.py +++ b/source/NVDAObjects/UIA/VisualStudio.py @@ -28,9 +28,11 @@ def event_UIA_elementSelected(self): if api.setNavigatorObject(self, isFocus=True): self.reportFocus() # Display results as flash messages. - braille.handler.message(braille.getPropertiesBraille( - name=self.name, role=self.role, positionInfo=self.positionInfo, description=self.description - )) + braille.handler.message( + braille.getPropertiesBraille( + name=self.name, role=self.role, positionInfo=self.positionInfo, description=self.description, + ), + ) class IntelliSenseList(UIA): @@ -50,7 +52,7 @@ class IntelliSenseLiveRegion(UIA): _INTELLISENSE_LIST_AUTOMATION_IDS = { "listBoxCompletions", - "CompletionList" + "CompletionList", } diff --git a/source/NVDAObjects/UIA/__init__.py b/source/NVDAObjects/UIA/__init__.py index 49ef29c542f..4514c804376 100644 --- a/source/NVDAObjects/UIA/__init__.py +++ b/source/NVDAObjects/UIA/__init__.py @@ -32,7 +32,7 @@ import textInfos from logHandler import log from UIAHandler.types import ( - IUIAutomationTextRangeT + IUIAutomationTextRangeT, ) from UIAHandler.utils import ( BulkUIATextRangeAttributeValueFetcher, @@ -58,7 +58,7 @@ Dialog, Notification, EditableTextWithSuggestions, - ToolTip + ToolTip, ) import braille import locationHelper @@ -145,7 +145,7 @@ def _get__controlFieldUIACacheRequest(self): UIAFormatUnits=[ UIAHandler.TextUnit_Format, UIAHandler.TextUnit_Word, - UIAHandler.TextUnit_Character + UIAHandler.TextUnit_Character, ] def find(self,text,caseSensitive=False,reverse=False): @@ -212,12 +212,12 @@ def _getFormatFieldAtRange( # noqa: C901 UIAHandler.UIA_FontWeightAttributeId, UIAHandler.UIA_IsItalicAttributeId, UIAHandler.UIA_UnderlineStyleAttributeId, - UIAHandler.UIA_StrikethroughStyleAttributeId + UIAHandler.UIA_StrikethroughStyleAttributeId, }) if formatConfig["reportSuperscriptsAndSubscripts"]: IDs.update({ UIAHandler.UIA_IsSuperscriptAttributeId, - UIAHandler.UIA_IsSubscriptAttributeId + UIAHandler.UIA_IsSubscriptAttributeId, }) if formatConfig["reportParagraphIndentation"]: IDs.update(set(paragraphIndentIDs)) @@ -417,7 +417,7 @@ def __init__( # noqa: C901 self, obj: NVDAObject, position: str, - _rangeObj: Optional[IUIAutomationTextRangeT] = None + _rangeObj: Optional[IUIAutomationTextRangeT] = None, ): super(UIATextInfo,self).__init__(obj,position) if _rangeObj: @@ -517,7 +517,7 @@ def _get_bookmark(self): UIAHandler.UIA_MenuItemControlTypeId, UIAHandler.UIA_TabItemControlTypeId, UIAHandler.UIA_TextControlTypeId, - UIAHandler.UIA_SplitButtonControlTypeId + UIAHandler.UIA_SplitButtonControlTypeId, } def _getControlFieldForUIAObject( @@ -525,7 +525,7 @@ def _getControlFieldForUIAObject( obj: "UIA", isEmbedded=False, startOfNode=False, - endOfNode=False + endOfNode=False, ) -> textInfos.ControlField: """ Fetch control field information for the given UIA NVDAObject. @@ -585,7 +585,7 @@ def _getTextWithFields_text( self, textRange: IUIAutomationTextRangeT, formatConfig: Dict, - UIAFormatUnits: Optional[List[int]] = None + UIAFormatUnits: Optional[List[int]] = None, ) -> Generator[textInfos.FieldCommand, None, None]: """ Yields format fields and text for the given UI Automation text range, split up by the first available UI Automation text unit that does not result in mixed attribute values. @@ -610,7 +610,7 @@ def _getTextWithFields_text( if debug: log.debug( f"Walking by unit {unit}, " - f"with further units of: {furtherUIAFormatUnits}" + f"with further units of: {furtherUIAFormatUnits}", ) rangeIter=iterUIARangeByUnit(textRange,unit) if unit is not None else [textRange] for tempRange in rangeIter: @@ -731,7 +731,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 obj, isEmbedded=objIsEmbedded, startOfNode=startOfNode, - endOfNode=endOfNode + endOfNode=endOfNode, ) except LookupError: if debug: @@ -792,7 +792,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 if childRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_End, textRange, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ) <= 0: if debug: log.debug("Child completely before textRange. Skipping") @@ -800,7 +800,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 if childRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_Start, textRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) >= 0: if debug: log.debug("Child at or past end of textRange. Breaking") @@ -808,18 +808,18 @@ def _getTextWithFieldsForUIARange( # noqa: C901 lastChildEndDelta = childRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_End, textRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) if lastChildEndDelta > 0: if debug: log.debug( "textRange ended part way through the child. " - "Crop end of childRange to fit" + "Crop end of childRange to fit", ) childRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_End, textRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) clippedEnd = True childStartDelta=childRange.CompareEndpoints(UIAHandler.TextPatternRangeEndpoint_Start,tempRange,UIAHandler.TextPatternRangeEndpoint_End) @@ -834,7 +834,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 if debug: log.debug( "textRange started part way through child. " - "Cropping Start of child range to fit" + "Cropping Start of child range to fit", ) childRange.MoveEndpointByRange(UIAHandler.TextPatternRangeEndpoint_Start,tempRange,UIAHandler.TextPatternRangeEndpoint_End) clippedStart=True @@ -1096,7 +1096,7 @@ def findOverlayClasses(self, clsList): # NOQA: C901 # changes the controlType to document and self.role in ( controlTypes.Role.PANE, - controlTypes.Role.DOCUMENT + controlTypes.Role.DOCUMENT, ) and self.parent and ( @@ -1205,7 +1205,7 @@ def findOverlayClasses(self, clsList): # NOQA: C901 # #10329: 2019 Windows Search results require special handling due to UI redesign. parentElement = UIAHandler.handler.baseTreeWalker.GetParentElementBuildCache( self.UIAElement, - UIAHandler.handler.baseCacheRequest + UIAHandler.handler.baseCacheRequest, ) # Sometimes, fetching parent (list control) via base tree walker fails, # especially when dealing with suggestions in Windows10 Start menu. @@ -1289,13 +1289,13 @@ def kwargsFromSuper(cls, kwargs, relation=None, ignoreNonNativeElementsWithFocus if UIAHandler._isDebug(): log.debug( f"kwargsFromSuper: given coordinates {relation}, " - f"fetched element {UIAHandler.handler.getUIAElementDebugString(UIAElement)}" + f"fetched element {UIAHandler.handler.getUIAElementDebugString(UIAElement)}", ) # Ignore this object if it is non native. if not UIAHandler.handler.isNativeUIAElement(UIAElement): if UIAHandler._isDebug(): log.debug( - f"kwargsFromSuper: ignoring non native element at coordinates {relation}" + f"kwargsFromSuper: ignoring non native element at coordinates {relation}", ) return False # This object may be in a different window, so we need to recalculate the window handle. @@ -1303,7 +1303,7 @@ def kwargsFromSuper(cls, kwargs, relation=None, ignoreNonNativeElementsWithFocus elif relation=="focus": try: UIAElement = UIAHandler.handler.clientObject.getFocusedElementBuildCache( - UIAHandler.handler.baseCacheRequest + UIAHandler.handler.baseCacheRequest, ) except COMError: log.debugWarning("getFocusedElement failed", exc_info=True) @@ -1311,13 +1311,13 @@ def kwargsFromSuper(cls, kwargs, relation=None, ignoreNonNativeElementsWithFocus if UIAHandler._isDebug(): log.debug( f"kwargsFromSuper: fetched focused element " - f"{UIAHandler.handler.getUIAElementDebugString(UIAElement)}" + f"{UIAHandler.handler.getUIAElementDebugString(UIAElement)}", ) # Ignore this object if it is non native. if ignoreNonNativeElementsWithFocus and not UIAHandler.handler.isNativeUIAElement(UIAElement): if UIAHandler._isDebug(): log.debug( - "kwargsFromSuper: ignoring non native element with focus" + "kwargsFromSuper: ignoring non native element with focus", ) return False # This object may be in a different window, so we need to recalculate the window handle. @@ -1356,7 +1356,7 @@ def __init__(self,windowHandle=None,UIAElement=None,initialUIACachedPropertyIDs= if UIAHandler._isDebug(): log.debug( "No windowHandle for UIA NvDAObject. " - "Searching UIA element ancestry for nearest windowHandle" + "Searching UIA element ancestry for nearest windowHandle", ) windowHandle=UIAHandler.handler.getNearestWindowHandle(UIAElement) if not windowHandle: @@ -1420,14 +1420,14 @@ def _get_UIAGridPattern(self): def _get_UIARangeValuePattern(self): self.UIARangeValuePattern = self._getUIAPattern( UIAHandler.UIA_RangeValuePatternId, - UIAHandler.IUIAutomationRangeValuePattern + UIAHandler.IUIAutomationRangeValuePattern, ) return self.UIARangeValuePattern def _get_UIAValuePattern(self): self.UIAValuePattern = self._getUIAPattern( UIAHandler.UIA_ValuePatternId, - UIAHandler.IUIAutomationValuePattern + UIAHandler.IUIAutomationValuePattern, ) return self.UIAValuePattern @@ -1442,7 +1442,7 @@ def _get_UIASelectionItemPattern(self): def _get_UIASelectionPattern(self): self.UIASelectionPattern = self._getUIAPattern( UIAHandler.UIA_SelectionPatternId, - UIAHandler.IUIAutomationSelectionPattern + UIAHandler.IUIAutomationSelectionPattern, ) return self.UIASelectionPattern @@ -1450,7 +1450,7 @@ def _get_UIASelectionPattern2(self): try: self.UIASelectionPattern2 = self._getUIAPattern( UIAHandler.UIA_SelectionPattern2Id, - UIAHandler.IUIAutomationSelectionPattern2 + UIAHandler.IUIAutomationSelectionPattern2, ) except COMError: # SelectionPattern2 is not available on older Operating Systems such as Windows 7 @@ -1503,7 +1503,7 @@ def _get_UIATextPattern(self): self.UIATextPattern = self._getUIAPattern( UIAHandler.UIA_TextPatternId, UIAHandler.IUIAutomationTextPattern, - cache=False + cache=False, ) return self.UIATextPattern @@ -1511,7 +1511,7 @@ def _get_UIATableItemPattern(self): self.UIATableItemPattern = self._getUIAPattern( UIAHandler.UIA_TableItemPatternId, UIAHandler.IUIAutomationTableItemPattern, - cache=False + cache=False, ) return self.UIATableItemPattern @@ -1613,7 +1613,7 @@ def _get_liveRegionPoliteness(self): try: return UIAHandler.UIALiveSettingtoNVDAAriaLivePoliteness.get( self._getUIACacheablePropertyValue(UIAHandler.UIA.UIA_LiveSettingPropertyId), - super().liveRegionPoliteness + super().liveRegionPoliteness, ) except COMError: return super().liveRegionPoliteness @@ -1907,7 +1907,7 @@ def _get_rowSpan(self): def _getTextFromHeaderElement(self, element: UIAHandler.IUIAutomationElement) -> typing.Optional[str]: obj = UIA( windowHandle=self.windowHandle, - UIAElement=element.buildUpdatedCache(UIAHandler.handler.baseCacheRequest) + UIAElement=element.buildUpdatedCache(UIAHandler.handler.baseCacheRequest), ) if not obj: return None @@ -2098,7 +2098,7 @@ def isDescendantOf(self, obj: "NVDAObjects.NVDAObject") -> bool: objIDArray = array.array("l", objID) UIACondition = UIAHandler.handler.clientObject.createPropertyCondition( UIAHandler.UIA_RuntimeIdPropertyId, - objIDArray + objIDArray, ) UIAWalker = UIAHandler.handler.clientObject.createTreeWalker(UIACondition) try: @@ -2163,7 +2163,7 @@ def event_UIA_notification( notificationKind: Optional[int] = None, notificationProcessing: Optional[int] = UIAHandler.NotificationProcessing_CurrentThenMostRecent, displayString: Optional[str] = None, - activityId: Optional[str] = None + activityId: Optional[str] = None, ): """ Introduced in Windows 10 Fall Creators Update (build 16299). @@ -2192,7 +2192,7 @@ def event_UIA_dropTargetEffect(self): # UIA drop target effect property was introduced in Windows 8. try: dropTargetEffect = self._getUIACacheablePropertyValue( - UIAHandler.UIA_DropTargetDropTargetEffectPropertyId + UIAHandler.UIA_DropTargetDropTargetEffectPropertyId, ) except COMError: dropTargetEffect = "" @@ -2203,7 +2203,7 @@ def event_UIA_dropTargetEffect(self): continue try: dropTargetEffect = element._getUIACacheablePropertyValue( - UIAHandler.UIA_DropTargetDropTargetEffectPropertyId + UIAHandler.UIA_DropTargetDropTargetEffectPropertyId, ) except COMError: dropTargetEffect = "" @@ -2362,8 +2362,10 @@ def event_stateChange(self): if not self.hasFocus: parent = self.parent focus=api.getFocusObject() - if parent and parent==focus and (isinstance(parent, ComboBoxWithoutValuePattern) - or (parent._getUIACacheablePropertyValue(UIAHandler.UIA_IsValuePatternAvailablePropertyId) and parent.windowClassName.startswith("Windows.UI.Core"))): + if parent and parent==focus and ( + isinstance(parent, ComboBoxWithoutValuePattern) + or (parent._getUIACacheablePropertyValue(UIAHandler.UIA_IsValuePatternAvailablePropertyId) and parent.windowClassName.startswith("Windows.UI.Core")) + ): # #6337: This is an item in a combo box without the Value pattern or does not raise value change event. # This item has been selected, so notify the combo box that its value has changed. focus.event_valueChange() diff --git a/source/NVDAObjects/UIA/chromium.py b/source/NVDAObjects/UIA/chromium.py index fbb1673cfaa..c449d8d6af0 100644 --- a/source/NVDAObjects/UIA/chromium.py +++ b/source/NVDAObjects/UIA/chromium.py @@ -41,7 +41,7 @@ def _getControlFieldForUIAObject(self, obj, isEmbedded=False, startOfNode=False, obj, isEmbedded=isEmbedded, startOfNode=startOfNode, - endOfNode=endOfNode + endOfNode=endOfNode, ) # use the value of comboboxes as content. if obj.role == controlTypes.Role.COMBOBOX: diff --git a/source/NVDAObjects/UIA/excel.py b/source/NVDAObjects/UIA/excel.py index bd93627813e..cbcfa32b2d8 100644 --- a/source/NVDAObjects/UIA/excel.py +++ b/source/NVDAObjects/UIA/excel.py @@ -194,7 +194,7 @@ def _get_cellSize(self) -> locationHelper.Point: "excel-UIA", # Translators: the description of a script "Shows a browseable message Listing information about a cell's " - "appearance such as outline and fill colors, rotation and size" + "appearance such as outline and fill colors, rotation and size", ), gestures=["kb:NVDA+o"], ) @@ -203,31 +203,33 @@ def script_showCellAppearanceInfo(self, gesture): tmpl = pgettext( "excel-UIA", # Translators: The width of the cell in points - "Cell width: {0.x:.1f} pt" + "Cell width: {0.x:.1f} pt", ) infoList.append(tmpl.format(self.cellSize)) tmpl = pgettext( "excel-UIA", # Translators: The height of the cell in points - "Cell height: {0.y:.1f} pt" + "Cell height: {0.y:.1f} pt", ) infoList.append(tmpl.format(self.cellSize)) if self.rotation is not None: - infoList.append(npgettext( - "excel-UIA", - # Translators: The rotation in degrees of an Excel cell - "Rotation: {0} degree", - "Rotation: {0} degrees", - self.rotation, - ).format(self.rotation)) + infoList.append( + npgettext( + "excel-UIA", + # Translators: The rotation in degrees of an Excel cell + "Rotation: {0} degree", + "Rotation: {0} degrees", + self.rotation, + ).format(self.rotation), + ) if self.outlineColor is not None: tmpl = pgettext( "excel-UIA", # Translators: The outline (border) colors of an Excel cell. - "Outline color: top={0.name}, bottom={1.name}, left={2.name}, right={3.name}" + "Outline color: top={0.name}, bottom={1.name}, left={2.name}, right={3.name}", ) infoList.append(tmpl.format(*self.outlineColor)) @@ -235,7 +237,7 @@ def script_showCellAppearanceInfo(self, gesture): tmpl = pgettext( "excel-UIA", # Translators: The outline (border) thickness values of an Excel cell. - "Outline thickness: top={0}, bottom={1}, left={2}, right={3}" + "Outline thickness: top={0}, bottom={1}, left={2}, right={3}", ) infoList.append(tmpl.format(*self.outlineThickness)) @@ -243,7 +245,7 @@ def script_showCellAppearanceInfo(self, gesture): tmpl = pgettext( "excel-UIA", # Translators: The fill color of an Excel cell - "Fill color: {0.name}" + "Fill color: {0.name}", ) infoList.append(tmpl.format(self.fillColor)) @@ -251,32 +253,32 @@ def script_showCellAppearanceInfo(self, gesture): tmpl = pgettext( "excel-UIA", # Translators: The fill type (pattern, gradient etc) of an Excel Cell - "Fill type: {0}" + "Fill type: {0}", ) infoList.append(tmpl.format(UIAHandler.constants.FillTypeLabels[self.fillType])) numberFormat = self._getUIACacheablePropertyValue( - self._UIAExcelCustomProps.cellNumberFormat.id + self._UIAExcelCustomProps.cellNumberFormat.id, ) if numberFormat: # Translators: the number format of an Excel cell tmpl = _("Number format: {0}") infoList.append(tmpl.format(numberFormat)) hasDataValidation = self._getUIACacheablePropertyValue( - self._UIAExcelCustomProps.hasDataValidation.id + self._UIAExcelCustomProps.hasDataValidation.id, ) if hasDataValidation: # Translators: If an excel cell has data validation set tmpl = _("Has data validation") infoList.append(tmpl) dataValidationPrompt = self._getUIACacheablePropertyValue( - self._UIAExcelCustomProps.dataValidationPrompt.id + self._UIAExcelCustomProps.dataValidationPrompt.id, ) if dataValidationPrompt: # Translators: the data validation prompt (input message) for an Excel cell tmpl = _("Data validation prompt: {0}") infoList.append(tmpl.format(dataValidationPrompt)) hasConditionalFormatting = self._getUIACacheablePropertyValue( - self._UIAExcelCustomProps.hasConditionalFormatting.id + self._UIAExcelCustomProps.hasConditionalFormatting.id, ) if hasConditionalFormatting: # Translators: If an excel cell has conditional formatting @@ -292,8 +294,8 @@ def script_showCellAppearanceInfo(self, gesture): title=pgettext( "excel-UIA", # Translators: Title for a browsable message that describes the appearance of a cell in Excel - "Cell Appearance" - ) + "Cell Appearance", + ), ) def _hasSelection(self): @@ -325,7 +327,7 @@ def _get_description(self): # Translators: an error message on a cell in Microsoft Excel descriptionList.append( # Translators: an error message on a cell in Microsoft Excel. - _("Error: {errorText}").format(errorText=self.errorText) + _("Error: {errorText}").format(errorText=self.errorText), ) presence = self.UIAAnnotationObjects.get(UIAHandler.AnnotationType_Author) if presence: @@ -333,8 +335,8 @@ def _get_description(self): descriptionList.append( # Translators: a mesage when another author is editing a cell in a shared Excel spreadsheet. _("{author} is editing").format( - author=author - ) + author=author, + ), ) baseDescription = super().description if baseDescription: @@ -427,43 +429,43 @@ def _getNumberRepresentationForColumn(column: str) -> int: def _get_cellCoordsText(self): if self._hasSelection(): sc = self._getUIACacheablePropertyValue( - UIAHandler.UIA_SelectionItemSelectionContainerPropertyId + UIAHandler.UIA_SelectionItemSelectionContainerPropertyId, ).QueryInterface(UIAHandler.IUIAutomationElement) firstSelected = sc.GetCurrentPropertyValue( - UIAHandler.UIA_Selection2FirstSelectedItemPropertyId + UIAHandler.UIA_Selection2FirstSelectedItemPropertyId, ).QueryInterface(UIAHandler.IUIAutomationElement) firstAddress = firstSelected.GetCurrentPropertyValue( - UIAHandler.UIA_NamePropertyId + UIAHandler.UIA_NamePropertyId, ).replace('"', '').replace(' ', '') firstValue = firstSelected.GetCurrentPropertyValue( - UIAHandler.UIA_ValueValuePropertyId + UIAHandler.UIA_ValueValuePropertyId, ) lastSelected = sc.GetCurrentPropertyValue( - UIAHandler.UIA_Selection2LastSelectedItemPropertyId + UIAHandler.UIA_Selection2LastSelectedItemPropertyId, ).QueryInterface(UIAHandler.IUIAutomationElement) lastAddress = lastSelected.GetCurrentPropertyValue( - UIAHandler.UIA_NamePropertyId + UIAHandler.UIA_NamePropertyId, ).replace('"', '').replace(' ', '') lastValue = lastSelected.GetCurrentPropertyValue( - UIAHandler.UIA_ValueValuePropertyId + UIAHandler.UIA_ValueValuePropertyId, ) cellCoordsTemplate = pgettext( "excel-UIA", # Translators: Excel, report selected range of cell coordinates - "{firstAddress} {firstValue} through {lastAddress} {lastValue}" + "{firstAddress} {firstValue} through {lastAddress} {lastValue}", ) return cellCoordsTemplate.format( firstAddress=firstAddress, firstValue=firstValue, lastAddress=lastAddress, - lastValue=lastValue + lastValue=lastValue, ) else: name = super().name @@ -478,14 +480,14 @@ def _get_cellCoordsText(self): firstColumn, firstRow = self._coordinateRegEx.match(firstAddress).groups() firstRow = int(firstRow) lastColumn = firstColumn if self.columnSpan == 1 else self._getColumnRepresentationForNumber( - self._getNumberRepresentationForColumn(firstColumn) + (self.columnSpan - 1) + self._getNumberRepresentationForColumn(firstColumn) + (self.columnSpan - 1), ) lastRow = firstRow + (self.rowSpan - 1) lastAddress = f"{lastColumn}{lastRow}" cellCoordsTemplate = pgettext( "excel-UIA", # Translators: Excel, report merged range of cell coordinates - "{firstAddress} through {lastAddress}" + "{firstAddress} through {lastAddress}", ) return cellCoordsTemplate.format( firstAddress=firstAddress, @@ -496,7 +498,8 @@ def _get_cellCoordsText(self): @script( # Translators: the description for a script for Excel description=_("Reports the note or comment thread on the current cell"), - gesture="kb:NVDA+alt+c") + gesture="kb:NVDA+alt+c", + ) def script_reportComment(self, gesture): if winVersion.getWinVer() >= winVersion.WIN11: noteElement = self.UIAAnnotationObjects.get(self._UIAExcelCustomAnnotationTypes.note.id) @@ -518,7 +521,7 @@ def script_reportComment(self, gesture): # Translators: a comment on a cell in Microsoft excel. text = _("Comment thread: {comment} by {author}").format( comment=comment, - author=author + author=author, ) else: text = ngettext( diff --git a/source/NVDAObjects/UIA/spartanEdge.py b/source/NVDAObjects/UIA/spartanEdge.py index 1d1b666b992..f7e0bc67598 100644 --- a/source/NVDAObjects/UIA/spartanEdge.py +++ b/source/NVDAObjects/UIA/spartanEdge.py @@ -49,7 +49,7 @@ def move(self, unit, direction, endPoint=None, skipReplacedContent=True): if not endPoint: if direction > 0 and unit in ( textInfos.UNIT_LINE, - textInfos.UNIT_PARAGRAPH + textInfos.UNIT_PARAGRAPH, ): return self._collapsedMove(unit, direction, skipReplacedContent) elif direction > 0: @@ -107,7 +107,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 includeRoot=True, recurseChildren=True, alwaysWalkAncestors=True, - _rootElementClipped=(True, True) + _rootElementClipped=(True, True), ): # Edge zooms into its children at the start. # Thus you are already in the deepest first child. @@ -124,7 +124,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 includeRoot=includeRoot, alwaysWalkAncestors=True, recurseChildren=False, - _rootElementClipped=_rootElementClipped + _rootElementClipped=_rootElementClipped, ): yield field return @@ -136,11 +136,11 @@ def _getTextWithFieldsForUIARange( # noqa: C901 startRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_End, startRange, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ) enclosingElement = getEnclosingElementWithCacheFromUIATextRange( startRange, - self._controlFieldUIACacheRequest + self._controlFieldUIACacheRequest, ) if not enclosingElement: log.debug("No enclosingElement. Returning") @@ -154,23 +154,23 @@ def _getTextWithFieldsForUIARange( # noqa: C901 startRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_End, enclosingRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) if 0 < startRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_End, textRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ): startRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_End, textRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) # Ensure we don't now have a collapsed range if 0 >= startRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_End, startRange, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ): log.debug("Collapsed range. Returning") return @@ -180,7 +180,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 childElements.length == 1 and UIAHandler.handler.clientObject.compareElements( rootElement, - childElements.getElement(0) + childElements.getElement(0), ) ): log.debug("Using single embedded child as enclosingElement") @@ -191,7 +191,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 _rootElementClipped=_rootElementClipped, includeRoot=includeRoot, alwaysWalkAncestors=False, - recurseChildren=False + recurseChildren=False, ): yield field return @@ -212,7 +212,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 obj = UIA( windowHandle=self.obj.windowHandle, UIAElement=parentElement, - initialUIACachedPropertyIDs=self._controlFieldUIACachedPropertyIDs + initialUIACachedPropertyIDs=self._controlFieldUIACachedPropertyIDs, ) field = self._getControlFieldForUIAObject(obj) except LookupError: @@ -229,7 +229,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 log.debug("Fetching next parentElement") parentElement = UIAHandler.handler.baseTreeWalker.getParentElementBuildCache( parentElement, - self._controlFieldUIACacheRequest + self._controlFieldUIACacheRequest, ) log.debug("Done generating parents") log.debug("Yielding parents in reverse order") @@ -241,12 +241,12 @@ def _getTextWithFieldsForUIARange( # noqa: C901 clippedStart = 0 > enclosingRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_Start, startRange, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ) clippedEnd = 0 < enclosingRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_End, startRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) for field in super(EdgeTextInfo, self)._getTextWithFieldsForUIARange( enclosingElement, @@ -255,7 +255,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 _rootElementClipped=(clippedStart, clippedEnd), includeRoot=includeRoot or hasAncestors, alwaysWalkAncestors=False, - recurseChildren=True + recurseChildren=True, ): yield field tempRange = startRange.clone() @@ -266,24 +266,24 @@ def _getTextWithFieldsForUIARange( # noqa: C901 tempRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_Start, tempRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) parentRange = self.obj.getNormalizedUIATextRangeFromElement(parentElement) if parentRange: tempRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_End, parentRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) if 0 < tempRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_End, textRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ): tempRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_End, textRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) clippedEnd = True else: @@ -292,14 +292,14 @@ def _getTextWithFieldsForUIARange( # noqa: C901 clippedStart = 0 > parentRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_Start, textRange, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ) field['_startOfNode'] = not clippedStart field['_endOfNode'] = not clippedEnd if 0 < tempRange.CompareEndpoints( UIAHandler.TextPatternRangeEndpoint_End, tempRange, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ): log.debug("Recursing endRange") for endField in self._getTextWithFieldsForUIARange( @@ -309,7 +309,7 @@ def _getTextWithFieldsForUIARange( # noqa: C901 _rootElementClipped=(clippedStart, clippedEnd), includeRoot=False, alwaysWalkAncestors=True, - recurseChildren=True + recurseChildren=True, ): yield endField log.debug("Done recursing endRange") @@ -336,7 +336,7 @@ def getNormalizedUIATextRangeFromElement(self, UIAElement): lastCharInfo = EdgeTextInfo_preGapRemoval( obj=self, position=None, - _rangeObj=textRange + _rangeObj=textRange, ) lastCharInfo._rangeObj = textRange charInfo = lastCharInfo.copy() @@ -346,7 +346,7 @@ def getNormalizedUIATextRangeFromElement(self, UIAElement): # EdgeTextInfo_preGapRemoval.move? while 0 != super(EdgeTextInfo, charInfo).move( textInfos.UNIT_CHARACTER, - 1 + 1, ): charInfo.setEndPoint(lastCharInfo, "startToStart") if charInfo.text or charInfo._hasEmbedded(): diff --git a/source/NVDAObjects/UIA/sysListView32.py b/source/NVDAObjects/UIA/sysListView32.py index 1273c1bdcc9..1247da1885f 100644 --- a/source/NVDAObjects/UIA/sysListView32.py +++ b/source/NVDAObjects/UIA/sysListView32.py @@ -61,7 +61,7 @@ def _get_name(self) -> str: try: columnHeaderItems = e.getCachedPropertyValueEx( UIAHandler.UIA.UIA_TableItemColumnHeaderItemsPropertyId, - False + False, ) except COMError: log.debugWarning("Couldn't fetch column header items", exc_info=True) @@ -89,11 +89,11 @@ def _get_indexInParent(self) -> Optional[int]: childCacheRequest.addProperty(UIAHandler.UIA.UIA_GridItemRowPropertyId) element = UIAHandler.handler.baseTreeWalker.GetFirstChildElementBuildCache( self.UIAElement, - childCacheRequest + childCacheRequest, ) val = element.getCachedPropertyValueEx( UIAHandler.UIA.UIA_GridItemRowPropertyId, - True + True, ) if val == UIAHandler.handler.reservedNotSupportedValue: return super().indexInParent diff --git a/source/NVDAObjects/UIA/web.py b/source/NVDAObjects/UIA/web.py index 9459c307c06..34168746cca 100644 --- a/source/NVDAObjects/UIA/web.py +++ b/source/NVDAObjects/UIA/web.py @@ -89,26 +89,26 @@ def _get_UIAElementAtStartWithReplacedContent(self): element = self.UIAElementAtStart condition = createUIAMultiPropertyCondition( { - UIAHandler.UIA_ControlTypePropertyId: self.UIAControlTypesWhereNameIsContent + UIAHandler.UIA_ControlTypePropertyId: self.UIAControlTypesWhereNameIsContent, }, { UIAHandler.UIA_ControlTypePropertyId: UIAHandler.UIA_ListControlTypeId, UIAHandler.UIA_IsKeyboardFocusablePropertyId: True, - } + }, ) # A part from the condition given, we must always match on the root of the document # so we know when to stop walking runtimeID = VARIANT() self.obj.UIAElement._IUIAutomationElement__com_GetCurrentPropertyValue( UIAHandler.UIA_RuntimeIdPropertyId, - byref(runtimeID) + byref(runtimeID), ) condition = UIAHandler.handler.clientObject.createOrCondition( UIAHandler.handler.clientObject.createPropertyCondition( UIAHandler.UIA_RuntimeIdPropertyId, - runtimeID + runtimeID, ), - condition + condition, ) walker = UIAHandler.handler.clientObject.createTreeWalker(condition) cacheRequest = UIAHandler.handler.clientObject.createCacheRequest() @@ -156,14 +156,14 @@ def _moveToEdgeOfReplacedContent(self, back=False): textRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_Start, textRange, - UIAHandler.TextPatternRangeEndpoint_End + UIAHandler.TextPatternRangeEndpoint_End, ) textRange.move(UIAHandler.TextUnit_Character, -1) else: textRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_End, textRange, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ) self._rangeObj = textRange @@ -200,7 +200,7 @@ def _getControlFieldForUIAObject(self, obj, isEmbedded=False, startOfNode=False, obj, isEmbedded=isEmbedded, startOfNode=startOfNode, - endOfNode=endOfNode + endOfNode=endOfNode, ) field['embedded'] = isEmbedded role = field.get('role') @@ -216,7 +216,7 @@ def _getControlFieldForUIAObject(self, obj, isEmbedded=False, startOfNode=False, ): field['isBlock'] = True ariaProperties = splitUIAElementAttribs( - obj._getUIACacheablePropertyValue(UIAHandler.UIA_AriaPropertiesPropertyId) + obj._getUIACacheablePropertyValue(UIAHandler.UIA_AriaPropertiesPropertyId), ) # ARIA roledescription and landmarks field['roleText'] = ariaProperties.get('roledescription') @@ -269,7 +269,7 @@ def _getControlFieldForUIAObject(self, obj, isEmbedded=False, startOfNode=False, # and move logic out into smaller helper functions. def getTextWithFields( # noqa: C901 self, - formatConfig: Optional[Dict] = None + formatConfig: Optional[Dict] = None, ) -> textInfos.TextInfo.TextWithFieldsT: # We don't want fields for collapsed ranges. # This would normally be a general rule, but MS Word currently needs fields for collapsed ranges, @@ -398,7 +398,7 @@ def _get_isCurrent(self) -> controlTypes.IsCurrent: return controlTypes.IsCurrent(valueOfAriaCurrent) except ValueError: log.debugWarning( - f"Unknown aria-current value: {valueOfAriaCurrent}, ariaProperties: {ariaProperties}" + f"Unknown aria-current value: {valueOfAriaCurrent}, ariaProperties: {ariaProperties}", ) return controlTypes.IsCurrent.NO @@ -473,11 +473,11 @@ def HeadingControlQuicknavIterator(itemType, document, position, direction="next levels = list(range(1, 7)) condition = createUIAMultiPropertyCondition({ UIAHandler.UIA_ControlTypePropertyId: UIAHandler.UIA_TextControlTypeId, - UIAHandler.UIA_LevelPropertyId: levels + UIAHandler.UIA_LevelPropertyId: levels, }) levelString = itemType[7:] itemIter = UIAControlQuicknavIterator( - itemType, document, position, condition, direction=direction, itemClass=HeadingControlQuickNavItem + itemType, document, position, condition, direction=direction, itemClass=HeadingControlQuickNavItem, ) for item in itemIter: # Verify this is the correct heading level via text attributes diff --git a/source/NVDAObjects/UIA/winConsoleUIA.py b/source/NVDAObjects/UIA/winConsoleUIA.py index dcca4fbce89..49a13beb40f 100644 --- a/source/NVDAObjects/UIA/winConsoleUIA.py +++ b/source/NVDAObjects/UIA/winConsoleUIA.py @@ -38,7 +38,7 @@ def __init__(self, obj, position, _rangeObj=None): if not _rangeObj and position in ( textInfos.POSITION_FIRST, textInfos.POSITION_LAST, - textInfos.POSITION_ALL + textInfos.POSITION_ALL, ): try: _rangeObj, collapseToEnd = self._getBoundingRange(obj, position) @@ -66,7 +66,7 @@ def _getBoundingRange(self, obj, position): _rangeObj.MoveEndpointByUnit( UIAHandler.TextPatternRangeEndpoint_End, UIAHandler.NVDAUnitsToUIAUnits['character'], - -1 + -1, ) collapseToEnd = True return (_rangeObj, collapseToEnd) @@ -165,7 +165,7 @@ def collapse(self, end=False): self._rangeObj.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_Start, oldInfo._rangeObj, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ) def compareEndPoints(self, other, which): @@ -206,19 +206,19 @@ def expand(self, unit): start, end = self._getWordOffsetsInThisLine(offset, lineInfo) wordEndPoints = ( (offset - start) * -1, - end - offset - 1 + end - offset - 1, ) if wordEndPoints[0]: self._rangeObj.MoveEndpointByUnit( UIAHandler.TextPatternRangeEndpoint_Start, UIAHandler.NVDAUnitsToUIAUnits[textInfos.UNIT_CHARACTER], - wordEndPoints[0] + wordEndPoints[0], ) if wordEndPoints[1]: self._rangeObj.MoveEndpointByUnit( UIAHandler.TextPatternRangeEndpoint_End, UIAHandler.NVDAUnitsToUIAUnits[textInfos.UNIT_CHARACTER], - wordEndPoints[1] + wordEndPoints[1], ) else: return super(ConsoleUIATextInfo, self).expand(unit) @@ -239,7 +239,7 @@ def _move(self, unit, direction, endPoint=None): res = self.move( textInfos.UNIT_CHARACTER, end - offset, - endPoint=endPoint + endPoint=endPoint, ) else: # Moving backwards @@ -250,7 +250,7 @@ def _move(self, unit, direction, endPoint=None): self.move( textInfos.UNIT_CHARACTER, wordStartDistance, - endPoint=endPoint + endPoint=endPoint, ) offset += wordStartDistance # Try to move one character back before the start of the word. @@ -274,7 +274,7 @@ def _move(self, unit, direction, endPoint=None): self.move( textInfos.UNIT_CHARACTER, wordStartDistance, - endPoint=endPoint + endPoint=endPoint, ) else: # moving by a unit other than word res = super(ConsoleUIATextInfo, self).move(unit, direction, endPoint) @@ -316,11 +316,11 @@ def _getWordOffsetsInThisLine(self, offset, lineInfo): lineTextLen, offset, ctypes.byref(start), - ctypes.byref(end) + ctypes.byref(end), ) return ( start.value, - min(end.value, max(1, lineTextLen - 2)) + min(end.value, max(1, lineTextLen - 2)), ) def _isCollapsed(self): @@ -416,10 +416,12 @@ def detectPossibleSelectionChange(self): # microsoft/terminal#5399: when attempting to compare text ranges # from the standard and alt mode buffers, E_FAIL is returned. # Downgrade this to a debugWarning. - log.debugWarning(( - "Exception raised when comparing selections, " - "probably due to a switch to/from the alt buffer." - ), exc_info=True) + log.debugWarning( + ( + "Exception raised when comparing selections, " + "probably due to a switch to/from the alt buffer." + ), exc_info=True, + ) def event_UIA_notification(self, **kwargs): """ @@ -467,7 +469,7 @@ def event_UIA_notification( notificationKind: Optional[int] = None, notificationProcessing: Optional[int] = UIAHandler.NotificationProcessing_CurrentThenMostRecent, displayString: Optional[str] = None, - activityId: Optional[str] = None + activityId: Optional[str] = None, ): # Do not announce output from background terminals. if self.appModule != api.getFocusObject().appModule: @@ -488,7 +490,7 @@ def __getattr__(attrName: str) -> Any: if attrName == "WinTerminalUIA" and NVDAState._allowDeprecatedAPI(): log.warning( "WinTerminalUIA is deprecated. " - "Instead use _DiffBasedWinTerminalUIA or _NotificationsBasedWinTerminalUIA" + "Instead use _DiffBasedWinTerminalUIA or _NotificationsBasedWinTerminalUIA", ) return ( _NotificationsBasedWinTerminalUIA diff --git a/source/NVDAObjects/UIA/wordDocument.py b/source/NVDAObjects/UIA/wordDocument.py index aae0b43f694..3e765f774c8 100644 --- a/source/NVDAObjects/UIA/wordDocument.py +++ b/source/NVDAObjects/UIA/wordDocument.py @@ -27,12 +27,12 @@ UIABrowseModeDocument, UIADocumentWithTableNavigation, UIATextAttributeQuicknavIterator, - TextAttribUIATextInfoQuickNavItem + TextAttribUIATextInfoQuickNavItem, ) from . import UIA, UIATextInfo from NVDAObjects.window.winword import ( WordDocument as WordDocumentBase, - WordDocumentTextInfo as LegacyWordDocumentTextInfo + WordDocumentTextInfo as LegacyWordDocumentTextInfo, ) from NVDAObjects import NVDAObject from scriptHandler import script @@ -56,14 +56,15 @@ class UIACustomAttributeID(enum.IntEnum): class ElementsListDialog(browseMode.ElementsListDialog): - ELEMENT_TYPES=(browseMode.ElementsListDialog.ELEMENT_TYPES[0],browseMode.ElementsListDialog.ELEMENT_TYPES[1], - # Translators: The label of a radio button to select the type of element - # in the browse mode Elements List dialog. - ("annotation", _("&Annotations")), - # Translators: The label of a radio button to select the type of element - # in the browse mode Elements List dialog. - ("error", _("&Errors")), - ) + ELEMENT_TYPES=( + browseMode.ElementsListDialog.ELEMENT_TYPES[0],browseMode.ElementsListDialog.ELEMENT_TYPES[1], + # Translators: The label of a radio button to select the type of element + # in the browse mode Elements List dialog. + ("annotation", _("&Annotations")), + # Translators: The label of a radio button to select the type of element + # in the browse mode Elements List dialog. + ("error", _("&Errors")), + ) class RevisionUIATextInfoQuickNavItem(TextAttribUIATextInfoQuickNavItem): attribID=UIAHandler.UIA_AnnotationTypesAttributeId @@ -113,7 +114,7 @@ def getCommentInfoFromPosition(position): not obj.parent # Because the name of this object is language sensetive check if it has UIA Annotation Pattern or not obj.parent.UIAElement.getCurrentPropertyValue( - UIAHandler.UIA_IsAnnotationPatternAvailablePropertyId + UIAHandler.UIA_IsAnnotationPatternAvailablePropertyId, ) ): continue @@ -137,7 +138,7 @@ def getPresentableCommentInfoFromPosition(commentInfo): class CommentUIATextInfoQuickNavItem(TextAttribUIATextInfoQuickNavItem): attribID=UIAHandler.UIA_AnnotationTypesAttributeId - wantedAttribValues={UIAHandler.AnnotationType_Comment,} + wantedAttribValues={UIAHandler.AnnotationType_Comment} @property def label(self): @@ -207,7 +208,7 @@ def _getControlFieldForUIAObject(self, obj, isEmbedded=False, startOfNode=False, obj, isEmbedded=isEmbedded, startOfNode=startOfNode, - endOfNode=endOfNode + endOfNode=endOfNode, ) if automationId.startswith('UIA_AutomationId_Word_Page_'): field['page-number'] = automationId.rsplit('_', 1)[-1] @@ -293,7 +294,7 @@ def expand(self,unit): # and move logic out into smaller helper functions. def getTextWithFields( # noqa: C901 self, - formatConfig: Optional[Dict] = None + formatConfig: Optional[Dict] = None, ) -> textInfos.TextInfo.TextWithFieldsT: fields = None # #11043: when a non-collapsed text range is positioned within a blank table cell @@ -429,13 +430,13 @@ def _getFormatFieldAtRange(self, textRange, formatConfig, ignoreMixedValues=Fals docElement = self.obj.UIAElement if formatConfig['reportLineNumber']: lineNumber = UIARemote.msWord_getCustomAttributeValue( - docElement, textRange, UIACustomAttributeID.LINE_NUMBER + docElement, textRange, UIACustomAttributeID.LINE_NUMBER, ) if isinstance(lineNumber, int): formatField.field['line-number'] = lineNumber if formatConfig['reportPage']: sectionNumber = UIARemote.msWord_getCustomAttributeValue( - docElement, textRange, UIACustomAttributeID.SECTION_NUMBER + docElement, textRange, UIACustomAttributeID.SECTION_NUMBER, ) if isinstance(sectionNumber, int): formatField.field['section-number'] = sectionNumber @@ -444,7 +445,7 @@ def _getFormatFieldAtRange(self, textRange, formatConfig, ignoreMixedValues=Fals # as it causes Microsoft Word 16.0.1493 and newer to crash!! # This should only be reenabled for versions identified not to crash. textColumnNumber = UIARemote.msWord_getCustomAttributeValue( - docElement, textRange, UIACustomAttributeID.COLUMN_NUMBER + docElement, textRange, UIACustomAttributeID.COLUMN_NUMBER, ) if isinstance(textColumnNumber, int): formatField.field['text-column-number'] = textColumnNumber @@ -519,10 +520,10 @@ def _iterTextStyle( self, kind: str, direction: documentBase._Movement = documentBase._Movement.NEXT, - pos: textInfos.TextInfo | None = None + pos: textInfos.TextInfo | None = None, ) -> Generator[browseMode.TextInfoQuickNavItem, None, None]: raise NotImplementedError( - "word textInfos are not supported due to multiple issues with them - #16569" + "word textInfos are not supported due to multiple issues with them - #16569", ) @@ -627,18 +628,22 @@ def script_reportCurrentComment(self,gesture): @script(gesture="kb:NVDA+shift+c") def script_setColumnHeader(self, gesture): - ui.message(_( - # Translators: The message reported in Microsoft Word for document types not supporting setting custom - # headers. - "Command not supported in this type of document. " - "The tables have their first row cells automatically set as column headers." - )) + ui.message( + _( + # Translators: The message reported in Microsoft Word for document types not supporting setting custom + # headers. + "Command not supported in this type of document. " + "The tables have their first row cells automatically set as column headers.", + ), + ) @script(gesture="kb:NVDA+shift+r") def script_setRowHeader(self, gesture): - ui.message(_( - # Translators: The message reported in Microsoft Word for document types not supporting setting custom - # headers. - "Command not supported in this type of document. " - "The tables have their first column cells automatically set as row headers." - )) + ui.message( + _( + # Translators: The message reported in Microsoft Word for document types not supporting setting custom + # headers. + "Command not supported in this type of document. " + "The tables have their first column cells automatically set as row headers.", + ), + ) diff --git a/source/NVDAObjects/__init__.py b/source/NVDAObjects/__init__.py index d5b8edeafbd..394470646e5 100644 --- a/source/NVDAObjects/__init__.py +++ b/source/NVDAObjects/__init__.py @@ -67,7 +67,7 @@ def _getStoryLength(self): def _get_boundingRects(self): if self.obj.hasIrrelevantLocation: raise LookupError("Object is off screen, invisible or has no location") - return [self.obj.location,] + return [self.obj.location] class InvalidNVDAObject(RuntimeError): """Raised by NVDAObjects during construction to inform that this object is invalid. @@ -525,7 +525,7 @@ def _get_descriptionFrom(self) -> controlTypes.DescriptionFrom: def _get_annotations(self) -> typing.Optional[AnnotationOrigin]: if config.conf["debugLog"]["annotations"]: log.debugWarning( - f"Fetching annotations not supported on: {self.__class__.__qualname__}" + f"Fetching annotations not supported on: {self.__class__.__qualname__}", ) return None @@ -538,7 +538,7 @@ def _get_annotations(self) -> typing.Optional[AnnotationOrigin]: def _get_detailsSummary(self) -> typing.Optional[str]: log.warning( "NVDAObject.detailsSummary is deprecated. Use NVDAObject.annotations instead.", - stack_info=True + stack_info=True, ) return None @@ -549,7 +549,7 @@ def hasDetails(self) -> bool: """ log.warning( "NVDAObject.hasDetails is deprecated. Use NVDAObject.annotations instead.", - stack_info=True + stack_info=True, ) return bool(self.annotations) @@ -561,7 +561,7 @@ def hasDetails(self) -> bool: def _get_detailsRole(self) -> typing.Optional[controlTypes.Role]: log.warning( "NVDAObject.detailsRole is deprecated. Use NVDAObject.annotations instead.", - stack_info=True + stack_info=True, ) if config.conf["debugLog"]["annotations"]: log.debugWarning(f"Fetching details summary not supported on: {self.__class__.__qualname__}") @@ -704,7 +704,7 @@ def _get_children(self): """ log.debugWarning( "Base implementation used." - " Relies on child.next which is error prone in many IA2 implementations." + " Relies on child.next which is error prone in many IA2 implementations.", ) children=[] child=self.firstChild @@ -908,7 +908,7 @@ def _get_presentationType(self): controlTypes.Role.TITLEBAR, controlTypes.Role.LABEL, controlTypes.Role.WHITESPACE, - controlTypes.Role.BORDER + controlTypes.Role.BORDER, ): return self.presType_layout name = self.name @@ -1202,7 +1202,7 @@ def event_liveRegionChange(self): speech.priorities.Spri.NEXT if politeness == aria.AriaLivePoliteness.ASSERTIVE else speech.priorities.Spri.NORMAL - ) + ), ) def event_typedCharacter(self,ch): @@ -1270,9 +1270,11 @@ def event_selection(self): if api.setNavigatorObject(self, isFocus=True): self.reportFocus() # Display results as flash messages. - braille.handler.message(braille.getPropertiesBraille( - name=self.name, role=self.role, positionInfo=self.positionInfo - )) + braille.handler.message( + braille.getPropertiesBraille( + name=self.name, role=self.role, positionInfo=self.positionInfo, + ), + ) self.event_stateChange() def event_stateChange(self): @@ -1334,7 +1336,7 @@ def event_becomeNavigatorObject(self, isFocus=False): if not (braille.handler.shouldAutoTether and isFocus): braille.handler.handleReviewMove(shouldAutoTether=not isFocus) vision.handler.handleReviewMove( - context=vision.constants.Context.FOCUS if isFocus else vision.constants.Context.NAVIGATOR + context=vision.constants.Context.FOCUS if isFocus else vision.constants.Context.NAVIGATOR, ) def event_valueChange(self): diff --git a/source/NVDAObjects/behaviors.py b/source/NVDAObjects/behaviors.py index aa7c2db3ef9..82bfe1574a9 100755 --- a/source/NVDAObjects/behaviors.py +++ b/source/NVDAObjects/behaviors.py @@ -104,7 +104,7 @@ def getDialogText(cls,obj,allowFocusedDescendants=True): controlTypes.Role.PARAGRAPH, controlTypes.Role.SECTION, controlTypes.Role.TEXTFRAME, - controlTypes.Role.UNKNOWN + controlTypes.Role.UNKNOWN, ): #Grab text from descendants, but not for a child which inherits from Dialog and has focusable descendants #Stops double reporting when focus is in a property page in a dialog @@ -537,14 +537,16 @@ def event_textChange(self): self._dispatchQueue() super().event_textChange() - @script(gestures=[ - "kb:enter", - "kb:numpadEnter", - "kb:tab", - "kb:control+c", - "kb:control+d", - "kb:control+pause" - ]) + @script( + gestures=[ + "kb:enter", + "kb:numpadEnter", + "kb:tab", + "kb:control+c", + "kb:control+d", + "kb:control+pause", + ], + ) def script_flush_queuedChars(self, gesture): """ Flushes the typed word buffer and queue of typedCharacter events if present. @@ -735,7 +737,7 @@ def script_moveToPreviousRow(self, gesture): @script( description=_( # Translators: The description of an NVDA command. - "Moves the navigator object to the first column" + "Moves the navigator object to the first column", ), gesture="kb:Control+Alt+Home", canPropagate=True, @@ -749,7 +751,7 @@ def script_moveToFirstColumn(self, gesture): @script( description=_( # Translators: The description of an NVDA command. - "Moves the navigator object to the last column" + "Moves the navigator object to the last column", ), gesture="kb:Control+Alt+End", canPropagate=True, @@ -766,7 +768,7 @@ def script_moveToLastColumn(self, gesture): @script( description=_( # Translators: The description of an NVDA command. - "Moves the navigator object and focus to the first row" + "Moves the navigator object and focus to the first row", ), gesture="kb:Control+Alt+PageUp", canPropagate=True, @@ -777,7 +779,7 @@ def script_moveToFirstRow(self, gesture): @script( description=_( # Translators: The description of an NVDA command. - "Moves the navigator object and focus to the last row" + "Moves the navigator object and focus to the last row", ), gesture="kb:Control+Alt+PageDown", canPropagate=True, diff --git a/source/NVDAObjects/inputComposition.py b/source/NVDAObjects/inputComposition.py index 7e7c7bdfbbf..e67011c721b 100644 --- a/source/NVDAObjects/inputComposition.py +++ b/source/NVDAObjects/inputComposition.py @@ -76,7 +76,7 @@ def reportNewText(self,oldString,newString): queueHandler.eventQueue, speech.speakText, newText, - symbolLevel=characterProcessing.SymbolLevel.ALL + symbolLevel=characterProcessing.SymbolLevel.ALL, ) def compositionUpdate(self,compositionString,selectionStart,selectionEnd,isReading,announce=True): diff --git a/source/NVDAObjects/lockscreen.py b/source/NVDAObjects/lockscreen.py index db98940b959..e6553bf29e5 100644 --- a/source/NVDAObjects/lockscreen.py +++ b/source/NVDAObjects/lockscreen.py @@ -4,7 +4,7 @@ # Copyright (C) 2022 NV Access Limited from typing import ( - Optional + Optional, ) from NVDAObjects import NVDAObject diff --git a/source/NVDAObjects/window/__init__.py b/source/NVDAObjects/window/__init__.py index 8fa94347e2d..e04dcae51be 100644 --- a/source/NVDAObjects/window/__init__.py +++ b/source/NVDAObjects/window/__init__.py @@ -206,9 +206,11 @@ def redraw(self): """ left, top, width, height = self.location left, top = winUser.ScreenToClient(self.windowHandle, left, top) - winUser.RedrawWindow(self.windowHandle, - winUser.RECT(left, top, left + width, top + height), None, - winUser.RDW_INVALIDATE | winUser.RDW_UPDATENOW) + winUser.RedrawWindow( + self.windowHandle, + winUser.RECT(left, top, left + width, top + height), None, + winUser.RDW_INVALIDATE | winUser.RDW_UPDATENOW, + ) def _get_windowText(self): textLength=watchdog.cancellableSendMessage(self.windowHandle,winUser.WM_GETTEXTLENGTH,0,0) diff --git a/source/NVDAObjects/window/_msOfficeChart.py b/source/NVDAObjects/window/_msOfficeChart.py index be5afe38e70..7f6e7e23460 100644 --- a/source/NVDAObjects/window/_msOfficeChart.py +++ b/source/NVDAObjects/window/_msOfficeChart.py @@ -136,223 +136,223 @@ chartTypeDict = { # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DArea : _( "3D Area" ), + xl3DArea : _( "3D Area"), # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DAreaStacked : _( "3D Stacked Area" ), + xl3DAreaStacked : _( "3D Stacked Area"), # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DAreaStacked100 : _( "100 percent Stacked Area" ) , + xl3DAreaStacked100 : _( "100 percent Stacked Area") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DBarClustered : _( "3D Clustered Bar" ) , + xl3DBarClustered : _( "3D Clustered Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DBarStacked : _( "3D Stacked Bar" ) , + xl3DBarStacked : _( "3D Stacked Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DBarStacked100 : _( "3D 100 percent Stacked Bar" ) , + xl3DBarStacked100 : _( "3D 100 percent Stacked Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DColumn : _( "3D Column" ) , + xl3DColumn : _( "3D Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DColumnClustered : _( "3D Clustered Column" ), + xl3DColumnClustered : _( "3D Clustered Column"), # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DColumnStacked : _( "3D Stacked Column" ) , + xl3DColumnStacked : _( "3D Stacked Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DColumnStacked100 : _( "3D 100 percent Stacked Column" ) , + xl3DColumnStacked100 : _( "3D 100 percent Stacked Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DLine : _( "3D Line" ) , + xl3DLine : _( "3D Line") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DPie : _( "3D Pie" ) , + xl3DPie : _( "3D Pie") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xl3DPieExploded : _( "Exploded 3D Pie" ) , + xl3DPieExploded : _( "Exploded 3D Pie") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlArea : _( "Area" ) , + xlArea : _( "Area") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlAreaStacked : _( "Stacked Area" ) , + xlAreaStacked : _( "Stacked Area") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlAreaStacked100 : _( "100 percent Stacked Area" ) , + xlAreaStacked100 : _( "100 percent Stacked Area") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlBarClustered : _( "Clustered Bar" ) , + xlBarClustered : _( "Clustered Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlBarOfPie : _( "Bar of Pie" ) , + xlBarOfPie : _( "Bar of Pie") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlBarStacked : _( "Stacked Bar" ) , + xlBarStacked : _( "Stacked Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlBarStacked100 : _( "100 percent Stacked Bar" ) , + xlBarStacked100 : _( "100 percent Stacked Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlBubble : _( "Bubble" ) , + xlBubble : _( "Bubble") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlBubble3DEffect : _( "Bubble with 3D effects" ) , + xlBubble3DEffect : _( "Bubble with 3D effects") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlColumnClustered : _( "Clustered Column" ) , + xlColumnClustered : _( "Clustered Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlColumnStacked : _( "Stacked Column" ) , + xlColumnStacked : _( "Stacked Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlColumnStacked100 : _( "100 percent Stacked Column" ) , + xlColumnStacked100 : _( "100 percent Stacked Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlConeBarClustered : _( "Clustered Cone Bar" ) , + xlConeBarClustered : _( "Clustered Cone Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlConeBarStacked : _( "Stacked Cone Bar" ) , + xlConeBarStacked : _( "Stacked Cone Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlConeBarStacked100 : _( "100 percent Stacked Cone Bar" ) , + xlConeBarStacked100 : _( "100 percent Stacked Cone Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlConeCol : _( "3D Cone Column" ) , + xlConeCol : _( "3D Cone Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlConeColClustered : _( "Clustered Cone Column" ) , + xlConeColClustered : _( "Clustered Cone Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlConeColStacked : _( "Stacked Cone Column" ), + xlConeColStacked : _( "Stacked Cone Column"), # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlConeColStacked100 : _( "100 percent Stacked Cone Column" ) , + xlConeColStacked100 : _( "100 percent Stacked Cone Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlCylinderBarClustered : _( "Clustered Cylinder Bar" ) , + xlCylinderBarClustered : _( "Clustered Cylinder Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlCylinderBarStacked : _( "Stacked Cylinder Bar" ) , + xlCylinderBarStacked : _( "Stacked Cylinder Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlCylinderBarStacked100 : _( "100 percent Stacked Cylinder Bar" ) , + xlCylinderBarStacked100 : _( "100 percent Stacked Cylinder Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlCylinderCol : _( "3D Cylinder Column" ) , + xlCylinderCol : _( "3D Cylinder Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlCylinderColClustered : _( "Clustered Cone Column" ) , + xlCylinderColClustered : _( "Clustered Cone Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlCylinderColStacked : _( "Stacked Cone Column" ) , + xlCylinderColStacked : _( "Stacked Cone Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlCylinderColStacked100 : _( "100 percent Stacked Cylinder Column" ) , + xlCylinderColStacked100 : _( "100 percent Stacked Cylinder Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlDoughnut : _( "Doughnut" ) , + xlDoughnut : _( "Doughnut") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlDoughnutExploded : _( "Exploded Doughnut" ) , + xlDoughnutExploded : _( "Exploded Doughnut") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlLine : _( "Line" ) , + xlLine : _( "Line") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlLineMarkers : _( "Line with Markers" ) , + xlLineMarkers : _( "Line with Markers") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlLineMarkersStacked : _( "Stacked Line with Markers" ) , + xlLineMarkersStacked : _( "Stacked Line with Markers") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlLineMarkersStacked100 : _( "100 percent Stacked Line with Markers" ) , + xlLineMarkersStacked100 : _( "100 percent Stacked Line with Markers") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlLineStacked : _( "Stacked Line" ) , + xlLineStacked : _( "Stacked Line") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlLineStacked100 : _( "100 percent Stacked Line" ) , + xlLineStacked100 : _( "100 percent Stacked Line") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlPie : _( "Pie" ) , + xlPie : _( "Pie") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlPieExploded : _( "Exploded Pie" ) , + xlPieExploded : _( "Exploded Pie") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlPieOfPie : _( "Pie of Pie" ) , + xlPieOfPie : _( "Pie of Pie") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlPyramidBarClustered : _( "Clustered Pyramid Bar" ) , + xlPyramidBarClustered : _( "Clustered Pyramid Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlPyramidBarStacked : _( "Stacked Pyramid Bar" ) , + xlPyramidBarStacked : _( "Stacked Pyramid Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlPyramidBarStacked100 : _( "100 percent Stacked Pyramid Bar" ) , + xlPyramidBarStacked100 : _( "100 percent Stacked Pyramid Bar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlPyramidCol : _( "3D Pyramid Column" ) , + xlPyramidCol : _( "3D Pyramid Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlPyramidColClustered : _( "Clustered Pyramid Column" ) , + xlPyramidColClustered : _( "Clustered Pyramid Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlPyramidColStacked : _( "Stacked Pyramid Column" ) , + xlPyramidColStacked : _( "Stacked Pyramid Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-b22a8bb9-a673-4d7f-b481-aa747c48eb3d - xlPyramidColStacked100 : _( "100 percent Stacked Pyramid Column" ) , + xlPyramidColStacked100 : _( "100 percent Stacked Pyramid Column") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlRadar : _( "Radar" ) , + xlRadar : _( "Radar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlRadarFilled : _( "Filled Radar" ) , + xlRadarFilled : _( "Filled Radar") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlRadarMarkers : _( "Radar with Data Markers" ) , + xlRadarMarkers : _( "Radar with Data Markers") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlStockHLC : _( "High-Low-Close" ) , + xlStockHLC : _( "High-Low-Close") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlStockOHLC : _( "Open-High-Low-Close" ) , + xlStockOHLC : _( "Open-High-Low-Close") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlStockVHLC : _( "Volume-High-Low-Close" ) , + xlStockVHLC : _( "Volume-High-Low-Close") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlStockVOHLC : _( "Volume-Open-High-Low-Close" ) , + xlStockVOHLC : _( "Volume-Open-High-Low-Close") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlSurface : _( "3D Surface" ) , + xlSurface : _( "3D Surface") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlSurfaceTopView : _( "Surface (Top View)" ) , + xlSurfaceTopView : _( "Surface (Top View)") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlSurfaceTopViewWireframe : _( "Surface (Top View wireframe)" ) , + xlSurfaceTopViewWireframe : _( "Surface (Top View wireframe)") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlSurfaceWireframe : _( "3D Surface (wireframe)" ) , + xlSurfaceWireframe : _( "3D Surface (wireframe)") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlXYScatter : _( "Scatter" ) , + xlXYScatter : _( "Scatter") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlXYScatterLines : _( "Scatter with Lines" ) , + xlXYScatterLines : _( "Scatter with Lines") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlXYScatterLinesNoMarkers : _( "Scatter with Lines and No Data Markers" ) , + xlXYScatterLinesNoMarkers : _( "Scatter with Lines and No Data Markers") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlXYScatterSmooth : _( "Scatter with Smoothed Lines" ) , + xlXYScatterSmooth : _( "Scatter with Smoothed Lines") , # Translators: A type of chart in Microsoft Office. # See https://support.office.com/en-in/article/Available-chart-types-a019c053-ba7f-4c46-a09a-82e17f3ee5be - xlXYScatterSmoothNoMarkers : _( "Scatter with Smoothed Lines and No Data Markers") + xlXYScatterSmoothNoMarkers : _( "Scatter with Smoothed Lines and No Data Markers"), } # Axis types in chart @@ -377,7 +377,7 @@ class OfficeChartElementBase(Window): #used for deciding whether to report extra information for chart or plot areas reportExtraInfo = False - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): self.officeChartObject = officeChartObject self.elementID = elementID self.arg1 = arg1 @@ -404,19 +404,19 @@ def _get_role(self): return controlTypes.Role.UNKNOWN def _get_name(self): - return self._getChartElementText(self.elementID , self.arg1 , self.arg2 , self.reportExtraInfo ) + return self._getChartElementText(self.elementID , self.arg1 , self.arg2 , self.reportExtraInfo) def select(self): """used to activate specific element in the office application""" raise NotImplementedError def script_reportCurrentChartElementWithExtraInfo(self,gesture): - ui.message( self._getChartElementText(self.elementID , self.arg1 , self.arg2 , True ) ) + ui.message( self._getChartElementText(self.elementID , self.arg1 , self.arg2 , True)) def script_reportCurrentChartElementColor(self,gesture): if self.elementID == xlSeries: if self.arg2 == -1: - ui.message ( _( "Series color: {colorName} ").format(colorName=colors.RGB.fromCOLORREF(int( self.officeChartObject.SeriesCollection( self.arg1 ).Interior.Color ) ).name ) ) + ui.message ( _( "Series color: {colorName} ").format(colorName=colors.RGB.fromCOLORREF(int( self.officeChartObject.SeriesCollection( self.arg1).Interior.Color)).name)) ELEMENT_IDS = { # Translators: A type of element in a Microsoft Office chart. @@ -462,7 +462,7 @@ def script_reportCurrentChartElementColor(self,gesture): # Translators: A type of element in a Microsoft Office chart. xlShape: _("Shape"), } - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): return self.ELEMENT_IDS[ElementID] __gestures = { @@ -472,11 +472,11 @@ def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): class OfficeChartElementList(Window): - def __init__(self, windowHandle , officeChartObject , elementID=None , arg1=None , arg2=None ): + def __init__(self, windowHandle , officeChartObject , elementID=None , arg1=None , arg2=None): self.officeChartObject = officeChartObject self.elementList = [] self.activeElement = None - super(OfficeChartElementList,self).__init__(windowHandle=windowHandle ) + super(OfficeChartElementList,self).__init__(windowHandle=windowHandle) def addElement(self , element , parent): element.parent = parent @@ -484,8 +484,8 @@ def addElement(self , element , parent): elementCount = len(self.elementList) if( elementCount > 1): - self.elementList[ elementCount - 2 ].next= self.elementList[ elementCount -1] - self.elementList[ elementCount -1].previous= self.elementList[ elementCount - 2 ] + self.elementList[ elementCount - 2].next= self.elementList[ elementCount -1] + self.elementList[ elementCount -1].previous= self.elementList[ elementCount - 2] self.elementList[0].previous = self.elementList[ elementCount -1] self.elementList[ elementCount -1].next = self.elementList[0] @@ -521,7 +521,7 @@ class OfficeChart(OfficeChartElementList): role=controlTypes.Role.CHART def __init__(self,windowHandle, officeApplicationObject, officeChartObject, initialDocument , keyIndex=0): - super(OfficeChart,self).__init__(windowHandle=windowHandle , officeChartObject = officeChartObject ) + super(OfficeChart,self).__init__(windowHandle=windowHandle , officeChartObject = officeChartObject) self.initialDocument = initialDocument self.parent=initialDocument self.officeApplicationObject=officeApplicationObject @@ -531,9 +531,9 @@ def __init__(self,windowHandle, officeApplicationObject, officeChartObject, init seriesCount=None if seriesCount: for i in range(seriesCount): - self.addElement( OfficeChartElementSeries(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject , elementID = xlSeries , arg1 = i +1 ) , self) + self.addElement( OfficeChartElementSeries(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject , elementID = xlSeries , arg1 = i +1) , self) - self.addElement( OfficeChartElementCollection(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject ) , self ) + self.addElement( OfficeChartElementCollection(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject) , self) try: self.officeChartObject.Select() except: # noqa: E722 @@ -546,9 +546,11 @@ def _get_name(self): name=self.officeChartObject.Name #find the type of the chart chartType = self.officeChartObject.ChartType - chartTypeText = chartTypeDict.get(chartType, - # Translators: Reported when the type of a chart is not known. - _("unknown")) + chartTypeText = chartTypeDict.get( + chartType, + # Translators: Reported when the type of a chart is not known. + _("unknown"), + ) # Translators: Message reporting the title and type of a chart. text=_("Chart title: {chartTitle}, type: {chartType}").format(chartTitle=name, chartType=chartTypeText) return text @@ -580,10 +582,10 @@ def _get_description(self): "Toggles between browse mode and focus mode." " When in focus mode, keys will pass straight through to the application, " "allowing you to interact directly with a control. " - "When in browse mode, you can navigate the document with the cursor, quick navigation keys, etc." + "When in browse mode, you can navigate the document with the cursor, quick navigation keys, etc.", ), category=inputCore.SCRCAT_BROWSEMODE, - gestures=("kb:enter", "kb(desktop):numpadEnter", "kb:space") + gestures=("kb:enter", "kb(desktop):numpadEnter", "kb:space"), ) def script_activatePosition(self, gesture): # Toggle browse mode pass-through. @@ -607,33 +609,33 @@ class OfficeChartElementCollection(OfficeChartElementList): role=controlTypes.Role.CHARTELEMENT description=None - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): - super( OfficeChartElementCollection ,self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): + super( OfficeChartElementCollection ,self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) if officeChartObject.HasTitle: - self.addElement(OfficeChartElementChartTitle(windowHandle = windowHandle, officeChartObject = officeChartObject ) , self ) + self.addElement(OfficeChartElementChartTitle(windowHandle = windowHandle, officeChartObject = officeChartObject) , self) - axisAndAxisTitles = OfficeChartElementAxis.getAvailableAxisAndAxisTitle(windowHandle, officeChartObject ) + axisAndAxisTitles = OfficeChartElementAxis.getAvailableAxisAndAxisTitle(windowHandle, officeChartObject) for item in axisAndAxisTitles: self.addElement( item , self) - chartAreaObject = OfficeChartElementChartArea(windowHandle=self.windowHandle, officeChartObject = officeChartObject ) + chartAreaObject = OfficeChartElementChartArea(windowHandle=self.windowHandle, officeChartObject = officeChartObject) chartAreaObject.reportExtraInfo = True - self.addElement( chartAreaObject , self ) - plotAreaObject = OfficeChartElementPlotArea(windowHandle=self.windowHandle, officeChartObject = officeChartObject ) + self.addElement( chartAreaObject , self) + plotAreaObject = OfficeChartElementPlotArea(windowHandle=self.windowHandle, officeChartObject = officeChartObject) plotAreaObject.reportExtraInfo = True - self.addElement( plotAreaObject , self ) + self.addElement( plotAreaObject , self) if officeChartObject.HasLegend: - self.addElement(OfficeChartElementLegend(windowHandle=self.windowHandle, officeChartObject = officeChartObject ) , self ) + self.addElement(OfficeChartElementLegend(windowHandle=self.windowHandle, officeChartObject = officeChartObject) , self) self.legendEntryCount = self.officeChartObject.Legend.LegendEntries().Count - for legendEntryIndex in range( 1 , self.legendEntryCount + 1 ) : - legendEntry = OfficeChartElementLegendEntry(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject , elementID= xlLegendEntry , arg1 = legendEntryIndex , arg2 = self.legendEntryCount ) + for legendEntryIndex in range( 1 , self.legendEntryCount + 1) : + legendEntry = OfficeChartElementLegendEntry(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject , elementID= xlLegendEntry , arg1 = legendEntryIndex , arg2 = self.legendEntryCount) legendEntry.eventDriven = False - self.addElement ( legendEntry , self ) + self.addElement ( legendEntry , self) if officeChartObject.HasDataTable: - self.addElement(OfficeChartElementDataTable(windowHandle=self.windowHandle, officeChartObject = officeChartObject ) , self ) + self.addElement(OfficeChartElementDataTable(windowHandle=self.windowHandle, officeChartObject = officeChartObject) , self) def _get_name(self): #Translators: Speak text chart elements when virtual row of chart elements is reached while navigation @@ -647,8 +649,8 @@ class OfficeChartElementSeries(OfficeChartElementList): description=None role=controlTypes.Role.CHARTELEMENT - def __init__(self,windowHandle, officeChartObject , elementID , arg1 = None , arg2= None ): - super(OfficeChartElementSeries,self).__init__( windowHandle=windowHandle , officeChartObject = officeChartObject ) + def __init__(self,windowHandle, officeChartObject , elementID , arg1 = None , arg2= None): + super(OfficeChartElementSeries,self).__init__( windowHandle=windowHandle , officeChartObject = officeChartObject) self.elementID=elementID self.seriesIndex=arg1 self.currentPointIndex=arg2 @@ -657,16 +659,16 @@ def __init__(self,windowHandle, officeChartObject , elementID , arg1 = None , ar self.pointsCount=self.pointsCollection.Count for pointIndex in range(1,self.pointsCount +1) : - self.addElement ( OfficeChartElementPoint(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject , elementID= xlSeries, arg1 =self.seriesIndex, arg2 =pointIndex) , self ) + self.addElement ( OfficeChartElementPoint(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject , elementID= xlSeries, arg1 =self.seriesIndex, arg2 =pointIndex) , self) self.trendlinesCount = self.officeChartObject.SeriesCollection(self.seriesIndex).Trendlines().Count - for trendlineIndex in range( 1 , self.trendlinesCount + 1 ) : - self.addElement ( OfficeChartElementTrendline(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject , elementID= xlTrendline , arg1 = self.seriesIndex , arg2 = trendlineIndex ) , self ) + for trendlineIndex in range( 1 , self.trendlinesCount + 1) : + self.addElement ( OfficeChartElementTrendline(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject , elementID= xlTrendline , arg1 = self.seriesIndex , arg2 = trendlineIndex) , self) def _get_name(self): currentSeries=self.officeChartObject.SeriesCollection(self.seriesIndex) # noqa: F841 # Translators: Details about a series in a chart. For example, this might report "foo series 1 of 2" - seriesText=_("{seriesName} series {seriesIndex} of {seriesCount}").format( seriesName = self.officeChartObject.SeriesCollection(self.seriesIndex).Name , seriesIndex = self.seriesIndex , seriesCount = self.seriesCount ) + seriesText=_("{seriesName} series {seriesIndex} of {seriesCount}").format( seriesName = self.officeChartObject.SeriesCollection(self.seriesIndex).Name , seriesIndex = self.seriesIndex , seriesCount = self.seriesCount) return seriesText def select(self): @@ -675,10 +677,10 @@ def select(self): def script_reportColor(self, gesture): if self.officeChartObject.ChartType in (xlPie, xlPieExploded, xlPieOfPie): #Translators: Message to be spoken to report Slice Color in Pie Chart - ui.message ( _( "Slice color: {colorName} ").format(colorName=colors.RGB.fromCOLORREF(int( self.officeChartObject.SeriesCollection( self.seriesIndex ).Points(self.currentPointIndex).Format.Fill.ForeColor.RGB) ).name ) ) + ui.message ( _( "Slice color: {colorName} ").format(colorName=colors.RGB.fromCOLORREF(int( self.officeChartObject.SeriesCollection( self.seriesIndex).Points(self.currentPointIndex).Format.Fill.ForeColor.RGB)).name)) else: #Translators: Message to be spoken to report Series Color - ui.message ( _( "Series color: {colorName} ").format(colorName=colors.RGB.fromCOLORREF(int( self.officeChartObject.SeriesCollection( self.seriesIndex ).Interior.Color ) ).name ) ) + ui.message ( _( "Series color: {colorName} ").format(colorName=colors.RGB.fromCOLORREF(int( self.officeChartObject.SeriesCollection( self.seriesIndex).Interior.Color)).name)) __gestures = { "kb:NVDA+5": "reportColor", @@ -686,21 +688,21 @@ def script_reportColor(self, gesture): class OfficeChartElementPoint(OfficeChartElementBase): - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): - super(OfficeChartElementPoint ,self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): + super(OfficeChartElementPoint ,self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): if ElementID == xlSeries: if arg2 == -1: # Translators: Details about a series in a chart. # For example, this might report "foo series 1 of 2" - return _( "{seriesName} series {seriesIndex} of {seriesCount}").format( seriesName = self.officeChartObject.SeriesCollection(arg1).Name , seriesIndex = arg1 , seriesCount = self.officeChartObject.SeriesCollection().Count ) + return _( "{seriesName} series {seriesIndex} of {seriesCount}").format( seriesName = self.officeChartObject.SeriesCollection(arg1).Name , seriesIndex = arg1 , seriesCount = self.officeChartObject.SeriesCollection().Count) else: if self.officeChartObject.Application.name == "Microsoft Excel": # get the formula string and split it on comma separator to obtain range. # the formula should be in the form SERIES(name_ref, categories, values, plot_order listSeparator = self.officeChartObject.Application.International(xlListSeparator) - formulas = self.officeChartObject.SeriesCollection(arg1).Formula.split(listSeparator ) + formulas = self.officeChartObject.SeriesCollection(arg1).Formula.split(listSeparator) if len(formulas) == 4: chartSeriesXValue = self.officeChartObject.Application.Range(formulas[1]).Rows[arg2].Text else: @@ -733,11 +735,11 @@ def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): # Translators: Specifies the category of a data point. # {categoryAxisTitle} will be replaced with the title of the category axis; e.g. "Month". # {categoryAxisData} will be replaced with the category itself; e.g. "January". - output += _( "{categoryAxisTitle} {categoryAxisData}: ").format( categoryAxisTitle = self.officeChartObject.Axes(xlCategory).AxisTitle.Text , categoryAxisData = chartSeriesXValue ) + output += _( "{categoryAxisTitle} {categoryAxisData}: ").format( categoryAxisTitle = self.officeChartObject.Axes(xlCategory).AxisTitle.Text , categoryAxisData = chartSeriesXValue) else: # Translators: Specifies the category of a data point. # {categoryAxisData} will be replaced with the category itself; e.g. "January". - output += _( "Category {categoryAxisData}: ").format( categoryAxisData = chartSeriesXValue ) + output += _( "Category {categoryAxisData}: ").format( categoryAxisData = chartSeriesXValue) if self.officeChartObject.HasAxis(xlValue) and self.officeChartObject.Axes(xlValue).HasTitle: # Translators: Specifies the value of a data point. @@ -750,14 +752,14 @@ def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): output += _( "value {valueAxisData}").format( valueAxisData = self.officeChartObject.SeriesCollection(arg1).Values[arg2-1]) if self.officeChartObject.ChartType in (xlPie, xlPieExploded, xlPieOfPie): - total = math.fsum( self.officeChartObject.SeriesCollection(arg1).Values ) + total = math.fsum( self.officeChartObject.SeriesCollection(arg1).Values) # Translators: Details about a slice of a pie chart. # For example, this might report "fraction 25.25 percent slice 1 of 5" - output += _( " fraction {fractionValue:.2f} Percent slice {pointIndex} of {pointCount}").format( fractionValue = self.officeChartObject.SeriesCollection(arg1).Values[arg2-1] / total *100.00 , pointIndex = arg2 , pointCount = len( self.officeChartObject.SeriesCollection(arg1).Values ) ) + output += _( " fraction {fractionValue:.2f} Percent slice {pointIndex} of {pointCount}").format( fractionValue = self.officeChartObject.SeriesCollection(arg1).Values[arg2-1] / total *100.00 , pointIndex = arg2 , pointCount = len( self.officeChartObject.SeriesCollection(arg1).Values)) else: # Translators: Details about a segment of a chart. # For example, this might report "column 1 of 5" - output += _( " {segmentType} {pointIndex} of {pointCount}").format( segmentType = self.GetChartSegment() , pointIndex = arg2 , pointCount = len( self.officeChartObject.SeriesCollection(arg1).Values ) ) + output += _( " {segmentType} {pointIndex} of {pointCount}").format( segmentType = self.GetChartSegment() , pointIndex = arg2 , pointCount = len( self.officeChartObject.SeriesCollection(arg1).Values)) return output @@ -772,21 +774,24 @@ class OfficeChartElementAxis(OfficeChartElementBase): # Translators: Indicates Primary Category Axis xlPrimary: _("Primary Category Axis"), # Translators: Indicates Secondary Category Axis - xlSecondary: _("Secondary Category Axis")}, + xlSecondary: _("Secondary Category Axis"), + }, xlValue: { # Translators: Indicates Primary Value Axis xlPrimary: _("Primary Value Axis"), # Translators: Indicates Secondary Value Axis - xlSecondary: _("Secondary Value Axis")}, + xlSecondary: _("Secondary Value Axis"), + }, xlSeriesAxis: { # Translators: Indicates Primary Series Axis xlPrimary: _("Primary Series Axis"), # Translators: Indicates Secondary Series Axis - xlSecondary: _("Secondary Series Axis")} + xlSecondary: _("Secondary Series Axis"), + }, } @classmethod - def getAvailableAxisAndAxisTitle( cls , windowHandle , tempChartObject ): + def getAvailableAxisAndAxisTitle( cls , windowHandle , tempChartObject): listOfChartAxis = [] for axisType in [xlCategory, xlValue, xlSeriesAxis]: for axisGroup in [xlPrimary, xlSecondary]: @@ -796,32 +801,32 @@ def getAvailableAxisAndAxisTitle( cls , windowHandle , tempChartObject ): listOfChartAxis.append(OfficeChartElementAxisTitle(windowHandle = windowHandle , officeChartObject = tempChartObject , elementID = xlAxisTitle , arg1 = axisType , arg2 = axisGroup)) return listOfChartAxis - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): self.axisGroup = arg1 self.axisType = arg2 - super( OfficeChartElementAxis , self ).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + super( OfficeChartElementAxis , self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): return self._axisMap[self.axisType][self.axisGroup] def select(self): - self.officeChartObject.Axes( self.axisType , self.axisGroup ).Select() + self.officeChartObject.Axes( self.axisType , self.axisGroup).Select() -class OfficeChartElementAxisTitle( OfficeChartElementAxis ): +class OfficeChartElementAxisTitle( OfficeChartElementAxis): - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): - super( OfficeChartElementAxisTitle , self ).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): + super( OfficeChartElementAxisTitle , self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): # Translators: Indicates a chart axis title in Microsoft Office. - axisTitle = super(OfficeChartElementAxisTitle , self)._getChartElementText(ElementID , arg1 , arg2 ) - if self.officeChartObject.HasAxis( arg2 , arg1 ) and self.officeChartObject.Axes( arg2 , arg1 ).HasTitle: + axisTitle = super(OfficeChartElementAxisTitle , self)._getChartElementText(ElementID , arg1 , arg2) + if self.officeChartObject.HasAxis( arg2 , arg1) and self.officeChartObject.Axes( arg2 , arg1).HasTitle: # Translators: the title of a chart axis axisTitle += _(" title: {axisTitle}").format( axisTitle = self.officeChartObject.Axes(self.axisType, self.axisGroup).AxisTitle.Text) return axisTitle def select(self): - self.officeChartObject.Axes( self.axisType , self.axisGroup ).AxisTitle.Select() + self.officeChartObject.Axes( self.axisType , self.axisGroup).AxisTitle.Select() class OfficeChartElementTrendline( OfficeChartElementBase): @@ -837,20 +842,20 @@ class OfficeChartElementTrendline( OfficeChartElementBase): # Translators: Indicates that trendline type is Polynomial xlPolynomial: _("Polynomial"), # Translators: Indicates that trendline type is Power - xlPower: _("Power") + xlPower: _("Power"), } - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): self.seriesIndex = arg1 self.trendlineIndex = arg2 self.currentTrendline = officeChartObject.SeriesCollection(self.seriesIndex).Trendlines(self.trendlineIndex) - super( OfficeChartElementTrendline , self ).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + super( OfficeChartElementTrendline , self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): if self.currentTrendline.DisplayEquation or self.currentTrendline.DisplayRSquared: label=self.currentTrendline.DataLabel.Text #Translators: Substitute superscript two by square for R square value - label=label.replace(u"²", _( " square " )) + label=label.replace(u"²", _( " square ")) label=re.sub(r'([a-zA-Z]+)([2])',r'\1 square', label) label=re.sub(r'([a-zA-Z]+)([3])',r'\1 cube', label) label=re.sub(r'([a-zA-Z]+)([-]*[04-9][0-9]*)',r'\1 to the power \2', label) @@ -868,26 +873,26 @@ def select(self): class OfficeChartElementChartTitle( OfficeChartElementBase): - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): - super( OfficeChartElementChartTitle , self ).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): + super( OfficeChartElementChartTitle , self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): if self.officeChartObject.HasTitle: # Translators: Details about a chart title in Microsoft Office. - return _( "Chart title: {chartTitle}").format ( chartTitle = self.officeChartObject.ChartTitle.Text ) + return _( "Chart title: {chartTitle}").format ( chartTitle = self.officeChartObject.ChartTitle.Text) else: # Translators: Indicates an untitled chart in Microsoft Office. - return _( "Untitled chart" ) + return _( "Untitled chart") def select(self): self.officeChartObject.ChartTitle.Select() class OfficeChartElementChartArea( OfficeChartElementBase): - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): - super( OfficeChartElementChartArea , self ).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): + super( OfficeChartElementChartArea , self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): if reportExtraInfo: # Translators: Details about the chart area in a Microsoft Office chart. return _( "Chart area, height: {chartAreaHeight}, width: {chartAreaWidth}, top: {chartAreaTop}, left: {chartAreaLeft}").format ( chartAreaHeight = self.officeChartObject.ChartArea.Height , chartAreaWidth = self.officeChartObject.ChartArea.Width , chartAreaTop = self.officeChartObject.ChartArea.Top , chartAreaLeft = self.officeChartObject.ChartArea.Left) @@ -900,28 +905,28 @@ def select(self): class OfficeChartElementPlotArea( OfficeChartElementBase): - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): - super( OfficeChartElementPlotArea , self ).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): + super( OfficeChartElementPlotArea , self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): if reportExtraInfo: # useing {:.0f} to remove fractions # Translators: Details about the plot area of a Microsoft Office chart. - return _( "Plot area, inside height: {plotAreaInsideHeight:.0f}, inside width: {plotAreaInsideWidth:.0f}, inside top: {plotAreaInsideTop:.0f}, inside left: {plotAreaInsideLeft:.0f}").format ( plotAreaInsideHeight = self.officeChartObject.PlotArea.InsideHeight , plotAreaInsideWidth = self.officeChartObject.PlotArea.InsideWidth , plotAreaInsideTop = self.officeChartObject.PlotArea.InsideTop , plotAreaInsideLeft = self.officeChartObject.PlotArea.InsideLeft ) + return _( "Plot area, inside height: {plotAreaInsideHeight:.0f}, inside width: {plotAreaInsideWidth:.0f}, inside top: {plotAreaInsideTop:.0f}, inside left: {plotAreaInsideLeft:.0f}").format ( plotAreaInsideHeight = self.officeChartObject.PlotArea.InsideHeight , plotAreaInsideWidth = self.officeChartObject.PlotArea.InsideWidth , plotAreaInsideTop = self.officeChartObject.PlotArea.InsideTop , plotAreaInsideLeft = self.officeChartObject.PlotArea.InsideLeft) else: # Translators: Indicates the plot area of a Microsoft Office chart. - return _( "Plot area " ) + return _( "Plot area ") def select(self): self.officeChartObject.PlotArea.Select() class OfficeChartElementLegend( OfficeChartElementBase): - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): self.chartLegend = officeChartObject.Legend - super( OfficeChartElementLegend , self ).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + super( OfficeChartElementLegend , self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): return self.chartLegend.Name def select(self): @@ -931,20 +936,20 @@ class OfficeChartElementLegendEntry( OfficeChartElementBase): eventDriven = True - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): if self.eventDriven: self.legendEntry = officeChartObject.Legend.LegendEntries(arg1) - super( OfficeChartElementLegendEntry , self ).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + super( OfficeChartElementLegendEntry , self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): # Translators: Details about a legend entry for a series in a Microsoft Office chart. # For example, this might report "Legend entry for series Temperature 1 of 2" if self.eventDriven: # Translators: a message for the legend entry of a chart in MS Office - return _( "Legend entry for series {seriesName} {seriesIndex} of {seriesCount}").format( seriesName = self.officeChartObject.SeriesCollection(arg1).Name , seriesIndex = arg1 , seriesCount = self.officeChartObject.SeriesCollection().Count ) + return _( "Legend entry for series {seriesName} {seriesIndex} of {seriesCount}").format( seriesName = self.officeChartObject.SeriesCollection(arg1).Name , seriesIndex = arg1 , seriesCount = self.officeChartObject.SeriesCollection().Count) else: # Translators: the legend entry for a chart in Microsoft Office - return _( "Legend entry {legendEntryIndex} of {legendEntryCount}").format( legendEntryIndex = arg1 , legendEntryCount = arg2 ) + return _( "Legend entry {legendEntryIndex} of {legendEntryCount}").format( legendEntryIndex = arg1 , legendEntryCount = arg2) def select(self): if self.eventDriven: @@ -952,29 +957,29 @@ def select(self): class OfficeChartElementLegendKey( OfficeChartElementBase): - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): - super( OfficeChartElementLegendKey , self ).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2 ) + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): + super( OfficeChartElementLegendKey , self).__init__( windowHandle=windowHandle , officeChartObject=officeChartObject , elementID=elementID , arg1=arg1 , arg2=arg2) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): if ElementID == xlLegendKey: # Translators: Details about a legend key for a series in a Microsoft office chart. # For example, this might report "Legend key for series Temperature 1 of 2" # See https://support.office.com/en-us/article/Excel-Glossary-53b6ce43-1a9f-4ac2-a33c-d6f64ea2d1fc?CorrelationId=44f003e6-453a-4b14-a9a6-3fb5287109c7&ui=en-US&rs=en-US&ad=US - return _( "Legend key for Series {seriesName} {seriesIndex} of {seriesCount}").format( seriesName = self.officeChartObject.SeriesCollection(arg1).Name , seriesIndex = arg1 , seriesCount = self.officeChartObject.SeriesCollection().Count ) + return _( "Legend key for Series {seriesName} {seriesIndex} of {seriesCount}").format( seriesName = self.officeChartObject.SeriesCollection(arg1).Name , seriesIndex = arg1 , seriesCount = self.officeChartObject.SeriesCollection().Count) class OfficeChartElementDataTable( OfficeChartElementBase): - def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None ): + def __init__(self, windowHandle=None , officeChartObject=None , elementID=None , arg1=None , arg2=None): super().__init__( windowHandle=windowHandle, officeChartObject=officeChartObject, elementID=elementID, arg1=arg1, - arg2=arg2 + arg2=arg2, ) - def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False ): + def _getChartElementText(self, ElementID ,arg1,arg2 , reportExtraInfo=False): #Translators: Data Table will be spoken when chart element Data Table is selected return _("Data Table") diff --git a/source/NVDAObjects/window/edit.py b/source/NVDAObjects/window/edit.py index 5e0a897c416..84823645543 100644 --- a/source/NVDAObjects/window/edit.py +++ b/source/NVDAObjects/window/edit.py @@ -61,7 +61,7 @@ class PointLStruct(ctypes.Structure): _fields_=[ ('x',ctypes.c_long), ('y',ctypes.c_long), - ] + ] class CharRangeStruct(ctypes.Structure): _fields_=[ @@ -182,8 +182,10 @@ def _getPointFromOffset(self,offset): # If the specified index is greater than the index of the last character in the control, # the control returns -1. if point.x <0 or point.y <0: - raise LookupError("Point with client coordinates x=%d, y=%d not within client area of object" % - (point.x, point.y)) + raise LookupError( + "Point with client coordinates x=%d, y=%d not within client area of object" % + (point.x, point.y), + ) return point.toScreen(self.obj.windowHandle) @@ -295,7 +297,7 @@ def _getFormatFieldAndOffsets(self, offset, formatConfig, calculateOffsets=True) def _setFormatFieldColor( self, charFormat: Union[CharFormat2AStruct, CharFormat2WStruct], - formatField: textInfos.FormatField + formatField: textInfos.FormatField, ) -> None: if charFormat.dwEffects & CFE_AUTOCOLOR: rgb = GetSysColor(SysColorIndex.WINDOW_TEXT) @@ -581,7 +583,7 @@ def _getFormatFieldAtRange(self, textRange, formatConfig): # noqa: C901 def _setFormatFieldColor( self, fontObj, - formatField: textInfos.FormatField + formatField: textInfos.FormatField, ) -> None: fgColor = fontObj.foreColor if fgColor == comInterfaces.tom.tomAutoColor: @@ -744,18 +746,20 @@ def getTextWithFields(self, formatConfig: Optional[Dict] = None) -> textInfos.Te return [ textInfos.FieldCommand( "formatChange", - self._getFormatFieldAtRange(textRange, formatConfig) + self._getFormatFieldAtRange(textRange, formatConfig), ), - self._getTextAtRange(self._rangeObj) + self._getTextAtRange(self._rangeObj), ] commandList=[] endLimit=self._rangeObj.end while textRange.end Any: XlVAlign.BOTTOM.value: "botom", XlVAlign.TOP.value: "top", 1: "default", - } + }, } if attrName in _deprecatedConstantsMap and NVDAState._allowDeprecatedAPI(): replacementSymbol = _deprecatedConstantsMap[attrName] @@ -281,7 +281,7 @@ def __getattr__(attrName: str) -> Any: xlPatternLinearGradient:_("linear gradient"), # Translators: A type of background pattern in Microsoft Excel. xlPatternRectangularGradient:_("rectangular gradient"), - } +} from .excelCellBorder import getCellBorderStyleDescription # noqa: E402 @@ -290,10 +290,10 @@ def __getattr__(attrName: str) -> Any: class ExcelQuickNavItem(browseMode.QuickNavItem): - def __init__( self , nodeType , document , itemObject , itemCollection ): + def __init__( self , nodeType , document , itemObject , itemCollection): self.excelItemObject = itemObject self.excelItemCollection = itemCollection - super( ExcelQuickNavItem ,self).__init__( nodeType , document ) + super( ExcelQuickNavItem ,self).__init__( nodeType , document) def activate(self): pass @@ -319,7 +319,7 @@ def __init__(self, nodeType, document, chartObject, chartCollection): nodeType, document, chartObject, - chartCollection + chartCollection, ) def __lt__(self,other): @@ -375,8 +375,8 @@ def isAfterSelection(self): activeCell.row, activeCell.column, self.excelItemObject.row, - self.excelItemObject.column - ) + self.excelItemObject.column, + ), ) if self.excelItemObject.row == activeCell.row: @@ -388,16 +388,16 @@ def isAfterSelection(self): class ExcelCommentQuickNavItem(ExcelRangeBasedQuickNavItem): - def __init__( self , nodeType , document , commentObject , commentCollection ): + def __init__( self , nodeType , document , commentObject , commentCollection): self.comment=commentObject.comment self.label = commentObject.address(False,False,1,False) + " " + (self.comment.Text() if self.comment else "") - super( ExcelCommentQuickNavItem , self).__init__( nodeType , document , commentObject , commentCollection ) + super( ExcelCommentQuickNavItem , self).__init__( nodeType , document , commentObject , commentCollection) class ExcelFormulaQuickNavItem(ExcelRangeBasedQuickNavItem): - def __init__( self , nodeType , document , formulaObject , formulaCollection ): + def __init__( self , nodeType , document , formulaObject , formulaCollection): self.label = formulaObject.address(False, False, 1, False) + " " + formulaObject.FormulaLocal - super( ExcelFormulaQuickNavItem , self).__init__( nodeType , document , formulaObject , formulaCollection ) + super( ExcelFormulaQuickNavItem , self).__init__( nodeType , document , formulaObject , formulaCollection) class ExcelQuicknavIterator(object): """ @@ -444,21 +444,21 @@ def iterate(self): if self.direction=="previous": items=reversed(items) for collectionItem in items: - item=self.quickNavItemClass(self.itemType,self.document,collectionItem , items ) + item=self.quickNavItemClass(self.itemType,self.document,collectionItem , items) if not self.filter(collectionItem): continue yield item class ChartExcelCollectionQuicknavIterator(ExcelQuicknavIterator): quickNavItemClass=ExcelChartQuickNavItem#: the QuickNavItem class that should be instanciated and emitted. - def collectionFromWorksheet( self , worksheetObject ): + def collectionFromWorksheet( self , worksheetObject): return worksheetObject.ChartObjects() class CommentExcelCollectionQuicknavIterator(ExcelQuicknavIterator): quickNavItemClass=ExcelCommentQuickNavItem#: the QuickNavItem class that should be instanciated and emitted. - def collectionFromWorksheet( self , worksheetObject ): + def collectionFromWorksheet( self , worksheetObject): try: - return worksheetObject.cells.SpecialCells( xlCellTypeComments ) + return worksheetObject.cells.SpecialCells( xlCellTypeComments) except(COMError): return None @@ -467,20 +467,20 @@ def filter(self,item): class FormulaExcelCollectionQuicknavIterator(ExcelQuicknavIterator): quickNavItemClass=ExcelFormulaQuickNavItem#: the QuickNavItem class that should be instanciated and emitted. - def collectionFromWorksheet( self , worksheetObject ): + def collectionFromWorksheet( self , worksheetObject): try: - return worksheetObject.cells.SpecialCells( xlCellTypeFormulas ) + return worksheetObject.cells.SpecialCells( xlCellTypeFormulas) except(COMError): return None class ExcelSheetQuickNavItem(ExcelQuickNavItem): - def __init__( self , nodeType , document , sheetObject , sheetCollection ): + def __init__( self , nodeType , document , sheetObject , sheetCollection): self.label = sheetObject.Name self.sheetIndex = sheetObject.Index self.sheetObject = sheetObject - super( ExcelSheetQuickNavItem , self).__init__( nodeType , document , sheetObject , sheetCollection ) + super( ExcelSheetQuickNavItem , self).__init__( nodeType , document , sheetObject , sheetCollection) def __lt__(self,other): return self.sheetIndex < other.sheetIndex @@ -511,7 +511,7 @@ class SheetsExcelCollectionQuicknavIterator(ExcelQuicknavIterator): Allows iterating over an MS excel Sheets collection emitting L{QuickNavItem} object. """ quickNavItemClass=ExcelSheetQuickNavItem#: the QuickNavItem class that should be instantiated and emitted. - def collectionFromWorksheet( self , worksheetObject ): + def collectionFromWorksheet( self , worksheetObject): try: return worksheetObject.Application.ActiveWorkbook.sheets except(COMError): @@ -636,15 +636,15 @@ def _get_ElementsListDialog(self): def _iterNodesByType(self,nodeType,direction="next",pos=None): if nodeType=="chart": - return ChartExcelCollectionQuicknavIterator( nodeType , self.rootNVDAObject.excelWorksheetObject , direction , None ).iterate() + return ChartExcelCollectionQuicknavIterator( nodeType , self.rootNVDAObject.excelWorksheetObject , direction , None).iterate() elif nodeType=="comment": - return CommentExcelCellInfoQuicknavIterator( nodeType , self.rootNVDAObject, direction , None ).iterate() + return CommentExcelCellInfoQuicknavIterator( nodeType , self.rootNVDAObject, direction , None).iterate() elif nodeType=="formula": - return FormulaExcelCellInfoQuicknavIterator( nodeType , self.rootNVDAObject, direction , None ).iterate() + return FormulaExcelCellInfoQuicknavIterator( nodeType , self.rootNVDAObject, direction , None).iterate() elif nodeType=="sheet": - return SheetsExcelCollectionQuicknavIterator( nodeType , self.rootNVDAObject.excelWorksheetObject , direction , None ).iterate() + return SheetsExcelCollectionQuicknavIterator( nodeType , self.rootNVDAObject.excelWorksheetObject , direction , None).iterate() elif nodeType=="formField": - return ExcelFormControlQuicknavIterator( nodeType , self.rootNVDAObject.excelWorksheetObject , direction , None,self ).iterate(pos) + return ExcelFormControlQuicknavIterator( nodeType , self.rootNVDAObject.excelWorksheetObject , direction , None,self).iterate(pos) else: raise NotImplementedError @@ -804,7 +804,7 @@ def _get_excelApplicationObject(self): # .ab34 r'(\.(?P[a-zA-Z]+[0-9]+)?(\.(?P[a-zA-Z]+[0-9]+)?' # Optionally followed by a period (.) and extra random data (sometimes produced by other screen readers) - r'(\..*)*)?)?$' + r'(\..*)*)?)?$', ) def populateHeaderCellTrackerFromNames(self,headerCellTracker): @@ -972,57 +972,59 @@ def _get_states(self): states.add(controlTypes.State.PROTECTED) return states - @scriptHandler.script(gestures=( - "kb:tab", - "kb:shift+tab", - "kb:enter", - "kb:numpadEnter", - "kb:shift+enter", - "kb:shift+numpadEnter", - "kb:upArrow", - "kb:downArrow", - "kb:leftArrow", - "kb:rightArrow", - "kb:control+upArrow", - "kb:control+downArrow", - "kb:control+leftArrow", - "kb:control+rightArrow", - "kb:home", - "kb:end", - "kb:control+home", - "kb:control+end", - "kb:shift+upArrow", - "kb:shift+downArrow", - "kb:shift+leftArrow", - "kb:shift+rightArrow", - "kb:shift+control+upArrow", - "kb:shift+control+downArrow", - "kb:shift+control+leftArrow", - "kb:shift+control+rightArrow", - "kb:shift+home", - "kb:shift+end", - "kb:shift+control+home", - "kb:shift+control+end", - "kb:shift+space", - "kb:control+space", - "kb:pageUp", - "kb:pageDown", - "kb:shift+pageUp", - "kb:shift+pageDown", - "kb:alt+pageUp", - "kb:alt+pageDown", - "kb:alt+shift+pageUp", - "kb:alt+shift+pageDown", - "kb:control+shift+8", - "kb:control+pageUp", - "kb:control+pageDown", - "kb:control+a", - "kb:control+v", - "kb:shift+f11", - "kb:control+y", - "kb:control+z", - "kb:alt+backspace", - ), canPropagate=True) + @scriptHandler.script( + gestures=( + "kb:tab", + "kb:shift+tab", + "kb:enter", + "kb:numpadEnter", + "kb:shift+enter", + "kb:shift+numpadEnter", + "kb:upArrow", + "kb:downArrow", + "kb:leftArrow", + "kb:rightArrow", + "kb:control+upArrow", + "kb:control+downArrow", + "kb:control+leftArrow", + "kb:control+rightArrow", + "kb:home", + "kb:end", + "kb:control+home", + "kb:control+end", + "kb:shift+upArrow", + "kb:shift+downArrow", + "kb:shift+leftArrow", + "kb:shift+rightArrow", + "kb:shift+control+upArrow", + "kb:shift+control+downArrow", + "kb:shift+control+leftArrow", + "kb:shift+control+rightArrow", + "kb:shift+home", + "kb:shift+end", + "kb:shift+control+home", + "kb:shift+control+end", + "kb:shift+space", + "kb:control+space", + "kb:pageUp", + "kb:pageDown", + "kb:shift+pageUp", + "kb:shift+pageDown", + "kb:alt+pageUp", + "kb:alt+pageDown", + "kb:alt+shift+pageUp", + "kb:alt+shift+pageDown", + "kb:control+shift+8", + "kb:control+pageUp", + "kb:control+pageDown", + "kb:control+a", + "kb:control+v", + "kb:shift+f11", + "kb:control+y", + "kb:control+z", + "kb:alt+backspace", + ), canPropagate=True, + ) def script_changeSelection(self,gesture): oldSelection = self._getSelection() @@ -1091,7 +1093,7 @@ def _toggleBooleanAttribute(self, gesture, getStateFun, msgOff, msgOn): return enabled = self._WaitForValueChangeForAction( action=lambda: gesture.send(), - fetcher=lambda: getStateFun(selObj) + fetcher=lambda: getStateFun(selObj), ) if enabled: ui.message(msgOn) @@ -1309,7 +1311,7 @@ class ExcelCellInfoQuickNavItem(browseMode.QuickNavItem): def __init__( self , parentIterator, cellInfo): self.excelCellInfo = cellInfo self.parentIterator=parentIterator - super( ExcelCellInfoQuickNavItem ,self).__init__( parentIterator.itemType , parentIterator.document ) + super( ExcelCellInfoQuickNavItem ,self).__init__( parentIterator.itemType , parentIterator.document) def activate(self): pass @@ -1463,10 +1465,10 @@ def script_openDropdown(self,gesture): # Translators: the description for a script for Excel "Sets the current cell as start of column header. Pressing once will set this cell as the first column " "header for any cell lower and to the right of it within this region. Pressing twice will forget the " - "current column header for this cell." + "current column header for this cell.", ), gesture="kb:NVDA+shift+c", - category=SCRCAT_SYSTEMCARET + category=SCRCAT_SYSTEMCARET, ) def script_setColumnHeader(self,gesture): scriptCount=scriptHandler.getLastScriptRepeatCount() @@ -1490,10 +1492,10 @@ def script_setColumnHeader(self,gesture): # Translators: the description for a script for Excel "Sets the current cell as start of row headers. Pressing once will set this cell as the first row header " "for any cell lower and to the right of it within this region. Pressing twice will forget the current " - "row header for this cell." + "row header for this cell.", ), gesture="kb:NVDA+shift+r", - category=SCRCAT_SYSTEMCARET + category=SCRCAT_SYSTEMCARET, ) def script_setRowHeader(self,gesture): scriptCount=scriptHandler.getLastScriptRepeatCount() @@ -1551,7 +1553,7 @@ def _isEqual(self,other): False, # relative row False, # relative column xlA1, # 'a1' format - True # include book / sheet name + True, # include book / sheet name ) try: thisAddr=self.excelCellObject.address(*addressArgs) @@ -1621,7 +1623,7 @@ def _get_states(self): if nvCellStates & possibleCellState.value: states.add( # intentionally use indexing operator so an error is raised for a missing key - _nvCellStatesToStates[possibleCellState] + _nvCellStatesToStates[possibleCellState], ) return states @@ -1695,7 +1697,7 @@ def script_reportComment(self,gesture): # Translators: the description for a script for Excel description=_("Opens the note editing dialog"), gesture="kb:shift+f2", - category=SCRCAT_SYSTEMCARET + category=SCRCAT_SYSTEMCARET, ) def script_editComment(self,gesture): commentObj=self.excelCellObject.comment @@ -1706,7 +1708,8 @@ def script_editComment(self,gesture): # Translators: Title for the note editing dialog _("Note"), value=commentObj.text() if commentObj else u"", - style=wx.TE_MULTILINE|wx.OK|wx.CANCEL) + style=wx.TE_MULTILINE|wx.OK|wx.CANCEL, + ) def callback(result): if result == wx.ID_OK: if commentObj: @@ -1730,7 +1733,7 @@ def reportFocus(self): sequence = speech.getFormatFieldSpeech( formatField, attrsCache=self.parent._formatFieldSpeechCache, - formatConfig=formatConfig + formatConfig=formatConfig, ) speech.speak(sequence) super(ExcelCell,self).reportFocus() @@ -1759,7 +1762,7 @@ def _get_name(self): firstAddress=self.getCellAddress(firstCell), firstContent=firstCell.Text, lastAddress=self.getCellAddress(lastCell), - lastContent=lastCell.Text + lastContent=lastCell.Text, ) def _get_parent(self): @@ -1812,7 +1815,7 @@ def _get_treeInterceptor(self): return self.parent.treeInterceptor def _get_positionInfo(self): - return {'indexInGroup':self.index+1,'similarItemsInGroup':self.parent.childCount,} + return {'indexInGroup':self.index+1,'similarItemsInGroup':self.parent.childCount} class ExcelDropdown(Window): @@ -1861,7 +1864,8 @@ def _get_selection(self): @script( gestures=("kb:downArrow", "kb:upArrow", "kb:leftArrow", "kb:rightArrow", "kb:home", "kb:end"), - canPropagate=True) + canPropagate=True, + ) def script_selectionChange(self,gesture): gesture.send() newFocus=self.selection or self @@ -2014,8 +2018,8 @@ def doAction(self): class ExcelFormControlQuickNavItem(ExcelQuickNavItem): - def __init__( self , nodeType , document , formControlObject , formControlCollection, treeInterceptorObj ): - super( ExcelFormControlQuickNavItem ,self).__init__( nodeType , document , formControlObject , formControlCollection ) + def __init__( self , nodeType , document , formControlObject , formControlCollection, treeInterceptorObj): + super( ExcelFormControlQuickNavItem ,self).__init__( nodeType , document , formControlObject , formControlCollection) self.formControlObjectIndex = formControlObject.ZOrderPosition self.treeInterceptorObj=treeInterceptorObj @@ -2074,7 +2078,7 @@ def __init__(self, itemType , document , direction , includeCurrent,treeIntercep super(ExcelFormControlQuicknavIterator,self).__init__(itemType , document , direction , includeCurrent) self.treeInterceptorObj=treeInterceptorObj - def collectionFromWorksheet( self , worksheetObject ): + def collectionFromWorksheet( self , worksheetObject): try: return worksheetObject.Shapes except(COMError): @@ -2110,12 +2114,12 @@ def topLeftCellRow(item): for collectionItem in reversed(items): itemRow=collectionItem._comobj.excelRow if (itemRow= 1: if newRng.InlineShapes[1].Type==wdInlineShapeChart: - return eventHandler.queueEvent('gainFocus',_msOfficeChart.OfficeChart(windowHandle= self.obj.windowHandle, officeApplicationObject=self.obj.WinwordDocumentObject.Application, officeChartObject=newRng.InlineShapes[1].Chart , initialDocument = self.obj )) + return eventHandler.queueEvent('gainFocus',_msOfficeChart.OfficeChart(windowHandle= self.obj.windowHandle, officeApplicationObject=self.obj.WinwordDocumentObject.Application, officeChartObject=newRng.InlineShapes[1].Chart , initialDocument = self.obj)) # Handle activating links. # It is necessary to expand to word to get a link as the link's first character is never actually in the link! tempRange=self._rangeObj.duplicate @@ -719,7 +720,7 @@ def activate(self): # text will be something like ' REF _Ref457210120 \\h ' fieldText = field.code.text.strip().split(' ') # the \\h field indicates that the field is a link - if not any( fieldText[i] == '\\h' for i in range(2, len(fieldText)) ): + if not any( fieldText[i] == '\\h' for i in range(2, len(fieldText))): log.debugWarning("no \\h for field xref: %s" % field.code.text) continue bookmarkKey = fieldText[1] # we want the _Ref12345 part @@ -783,7 +784,7 @@ def __init__(self,obj,position,_rangeObj=None): # and move logic out into smaller helper functions. def getTextWithFields( # noqa: C901 self, - formatConfig: Optional[Dict] = None + formatConfig: Optional[Dict] = None, ) -> textInfos.TextInfo.TextWithFieldsT: if self.isCollapsed: return [] # noqa: E701 if self.obj.ignoreFormatting: @@ -916,7 +917,7 @@ def _normalizeFormatField(self,field,extraDetail=False): field['line-spacing'] = pgettext( 'line spacing value', # Translators: line spacing of exactly x point - "exactly {space:.1f} pt" + "exactly {space:.1f} pt", ).format(space=float(lineSpacingVal)) elif lineSpacingRule==wdLineSpaceAtLeast: # Translators: line spacing of at least x point @@ -1076,10 +1077,11 @@ def _move(self,unit,direction,endPoint=None,_rangeObj=None): #units higher than character and word expand to contain the last text plus the insertion point offset in the document #However move from a character before will incorrectly move to this offset which makes move/expand contridictory to each other #Make sure that move fails if it lands on the final offset but the unit is bigger than character/word - if (direction>0 and endPoint!="end" - and unit not in (wdCharacter,wdWord) # moving by units of line or more - and (_rangeObj.start+1) == self.obj.WinwordDocumentObject.range().end # character after the range start is the end of the document range - ): + if ( + direction>0 and endPoint!="end" + and unit not in (wdCharacter,wdWord) # moving by units of line or more + and (_rangeObj.start+1) == self.obj.WinwordDocumentObject.range().end # character after the range start is the end of the document range + ): return 0 return res @@ -1256,10 +1258,10 @@ def _iterTextStyle( self, kind: str, direction: documentBase._Movement = documentBase._Movement.NEXT, - pos: textInfos.TextInfo | None = None + pos: textInfos.TextInfo | None = None, ) -> Generator[browseMode.TextInfoQuickNavItem, None, None]: raise NotImplementedError( - "word textInfos are not supported due to multiple issues with them - #16569" + "word textInfos are not supported due to multiple issues with them - #16569", ) __gestures={ @@ -1428,7 +1430,7 @@ def script_changeParagraphLeftIndent(self, gesture): margin = self.WinwordDocumentObject.PageSetup.LeftMargin val = self._WaitForValueChangeForAction( lambda: gesture.send(), - lambda: self.WinwordSelectionObject.paragraphFormat.LeftIndent + lambda: self.WinwordSelectionObject.paragraphFormat.LeftIndent, ) msg = self.getLocalizedMeasurementTextForPointSize(margin + val) ui.message(msg) @@ -1512,7 +1514,7 @@ def script_toggleDisplayNonprintingCharacters(self, gesture): return gesture.send() val = self._WaitForValueChangeForAction( lambda: gesture.send(), - lambda: self.WinwordWindowObject.ActivePane.View.ShowAll + lambda: self.WinwordWindowObject.ActivePane.View.ShowAll, ) if val: # Translators: a message when toggling Display Nonprinting Characters in Microsoft word @@ -1636,8 +1638,8 @@ def initOverlayClass(self): if isinstance(self, EditableTextWithoutAutoSelectDetection): self.bindGesture("kb:alt+shift+home", "caret_changeSelection") self.bindGesture("kb:alt+shift+end", "caret_changeSelection") - self.bindGesture("kb:alt+shift+pageUp", "caret_changeSelection",) - self.bindGesture("kb:alt+shift+pageDown", "caret_changeSelection",) + self.bindGesture("kb:alt+shift+pageUp", "caret_changeSelection") + self.bindGesture("kb:alt+shift+pageDown", "caret_changeSelection") __gestures = { "kb:control+[":"increaseDecreaseFontSize", @@ -1693,14 +1695,15 @@ def _get_WinwordWindowObject(self): class ElementsListDialog(browseMode.ElementsListDialog): - ELEMENT_TYPES=(browseMode.ElementsListDialog.ELEMENT_TYPES[0],browseMode.ElementsListDialog.ELEMENT_TYPES[1], - # Translators: The label of a radio button to select the type of element - # in the browse mode Elements List dialog. - ("annotation", _("&Annotations")), - # Translators: The label of a radio button to select the type of element - # in the browse mode Elements List dialog. - ("chart", _("&Charts")), - # Translators: The label of a radio button to select the type of element - # in the browse mode Elements List dialog. - ("error", _("&Errors")), - ) + ELEMENT_TYPES=( + browseMode.ElementsListDialog.ELEMENT_TYPES[0],browseMode.ElementsListDialog.ELEMENT_TYPES[1], + # Translators: The label of a radio button to select the type of element + # in the browse mode Elements List dialog. + ("annotation", _("&Annotations")), + # Translators: The label of a radio button to select the type of element + # in the browse mode Elements List dialog. + ("chart", _("&Charts")), + # Translators: The label of a radio button to select the type of element + # in the browse mode Elements List dialog. + ("error", _("&Errors")), + ) diff --git a/source/UIAHandler/__init__.py b/source/UIAHandler/__init__.py index af4fe506308..209c0515609 100644 --- a/source/UIAHandler/__init__.py +++ b/source/UIAHandler/__init__.py @@ -454,8 +454,8 @@ def terminate(self): windll.kernel32.OpenThread( winKernel.SYNCHRONIZE, False, - self.MTAThread.ident - ) + self.MTAThread.ident, + ), ) self.MTAThreadQueue.put_nowait(None) # Wait for the MTA thread to die (while still message pumping) @@ -471,7 +471,7 @@ def MTAThreadFunc(self): UIA.CUIAutomation8._reg_clsid_, # Minimum interface is IUIAutomation3 (Windows 8.1). interface=UIA.CUIAutomation8._com_interfaces_[1], - clsctx=CLSCTX_INPROC_SERVER + clsctx=CLSCTX_INPROC_SERVER, ) # #7345: Instruct UIA to never map MSAA winEvents to UIA propertyChange events. # These events are not needed by NVDA, and they can cause the UI Automation client library to become unresponsive if an application firing winEvents has a slow message pump. @@ -527,7 +527,7 @@ def MTAThreadFunc(self): handler = self._rateLimitedEventHandler = POINTER(IUnknown)() NVDAHelper.localLib.rateLimitedUIAEventHandler_create( self._com_pointers_[IUnknown._iid_], - byref(self._rateLimitedEventHandler) + byref(self._rateLimitedEventHandler), ) else: handler = self @@ -570,8 +570,8 @@ def _registerGlobalEventHandlers(self, handler: "UIAHandler"): *self.clientObject.IntSafeArrayToNativeArray( globalEventHandlerGroupUIAPropertyIds if utils._shouldSelectivelyRegister() - else UIAPropertyIdsToNVDAEventNames - ) + else UIAPropertyIdsToNVDAEventNames, + ), ) for eventId in ( globalEventHandlerGroupUIAEventIds @@ -582,7 +582,7 @@ def _registerGlobalEventHandlers(self, handler: "UIAHandler"): eventId, UIA.TreeScope_Subtree, self.baseCacheRequest, - handler + handler, ) if ( not utils._shouldSelectivelyRegister() @@ -593,20 +593,20 @@ def _registerGlobalEventHandlers(self, handler: "UIAHandler"): UIA.UIA_Text_TextChangedEventId, UIA.TreeScope_Subtree, self.baseCacheRequest, - handler + handler, ) # #7984: add support for notification event (IUIAutomation5, part of Windows 10 build 16299 and later). if isinstance(self.clientObject, UIA.IUIAutomation5): self.globalEventHandlerGroup.AddNotificationEventHandler( UIA.TreeScope_Subtree, self.baseCacheRequest, - handler + handler, ) if isinstance(self.clientObject, UIA.IUIAutomation6): self.globalEventHandlerGroup.AddActiveTextPositionChangedEventHandler( UIA.TreeScope_Subtree, self.baseCacheRequest, - handler + handler, ) self.addEventHandlerGroup(self.rootElement, self.globalEventHandlerGroup) @@ -621,32 +621,32 @@ def _createLocalEventHandlerGroup(self, handler: "UIAHandler"): UIA.TreeScope_Ancestors | UIA.TreeScope_Element, self.baseCacheRequest, handler, - *self.clientObject.IntSafeArrayToNativeArray(localEventHandlerGroupUIAPropertyIds) + *self.clientObject.IntSafeArrayToNativeArray(localEventHandlerGroupUIAPropertyIds), ) self.localEventHandlerGroupWithTextChanges.AddPropertyChangedEventHandler( UIA.TreeScope_Ancestors | UIA.TreeScope_Element, self.baseCacheRequest, handler, - *self.clientObject.IntSafeArrayToNativeArray(localEventHandlerGroupUIAPropertyIds) + *self.clientObject.IntSafeArrayToNativeArray(localEventHandlerGroupUIAPropertyIds), ) for eventId in localEventHandlerGroupUIAEventIds: self.localEventHandlerGroup.AddAutomationEventHandler( eventId, UIA.TreeScope_Ancestors | UIA.TreeScope_Element, self.baseCacheRequest, - handler + handler, ) self.localEventHandlerGroupWithTextChanges.AddAutomationEventHandler( eventId, UIA.TreeScope_Ancestors | UIA.TreeScope_Element, self.baseCacheRequest, - handler + handler, ) self.localEventHandlerGroupWithTextChanges.AddAutomationEventHandler( UIA.UIA_Text_TextChangedEventId, UIA.TreeScope_Ancestors | UIA.TreeScope_Element, self.baseCacheRequest, - handler + handler, ) def addEventHandlerGroup(self, element, eventHandlerGroup): @@ -696,7 +696,7 @@ def func(): log.debugWarning( f"{logPrefix} registering for textChange events from UIA element " f"with class name {repr(element.currentClassName)} " - f"and automation ID {repr(element.CachedAutomationID)}" + f"and automation ID {repr(element.CachedAutomationID)}", ) self.addEventHandlerGroup(element, group) except COMError: @@ -724,7 +724,7 @@ def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if _isDebug(): log.debug( f"handleAutomationEvent called with event {self.getUIAEventIDDebugString(eventID)} " - f"for element {self.getUIAElementDebugString(sender)}" + f"for element {self.getUIAElementDebugString(sender)}", ) if not self.MTAThreadInitEvent.is_set(): # UIAHandler hasn't finished initialising yet, so just ignore this event. @@ -751,7 +751,7 @@ def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if _isDebug(): log.debugWarning( "HandleAutomationEvent: Dropping textChange event " - f"from element {self.getUIAElementDebugString(sender)}" + f"from element {self.getUIAElementDebugString(sender)}", ) return else: @@ -770,13 +770,13 @@ def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if _isDebug(): log.debug( "handleAutomationEvent: element matches focus. " - f"Redirecting event to focus NVDAObject {focus}" + f"Redirecting event to focus NVDAObject {focus}", ) obj = focus elif not self.isNativeUIAElement(sender): if _isDebug(): log.debug( - f"HandleAutomationEvent: Ignoring event {NVDAEventName} for non native element" + f"HandleAutomationEvent: Ignoring event {NVDAEventName} for non native element", ) return window = obj.windowHandle if obj else self.getNearestWindowHandle(sender) @@ -784,12 +784,12 @@ def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if _isDebug(): log.debug( f"Checking if should accept NVDA event {NVDAEventName} " - f"with window {self.getWindowHandleDebugString(window)}" + f"with window {self.getWindowHandleDebugString(window)}", ) if not eventHandler.shouldAcceptEvent(NVDAEventName, windowHandle=window): if _isDebug(): log.debug( - f"HandleAutomationEvent: Ignoring event {NVDAEventName} for shouldAcceptEvent=False" + f"HandleAutomationEvent: Ignoring event {NVDAEventName} for shouldAcceptEvent=False", ) return if not obj: @@ -799,7 +799,7 @@ def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if _isDebug(): log.debugWarning( f"HandleAutomationEvent: Exception while creating object for event {NVDAEventName}", - exc_info=True + exc_info=True, ) return if not obj: @@ -808,7 +808,7 @@ def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): return if _isDebug(): log.debug( - f"handleAutomationEvent: created object {obj} " + f"handleAutomationEvent: created object {obj} ", ) if ( (NVDAEventName == "gainFocus" and not obj.shouldAllowUIAFocusEvent) @@ -817,13 +817,13 @@ def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if _isDebug(): log.debug( "HandleAutomationEvent: " - f"Ignoring event {NVDAEventName} because ignored by object itself" + f"Ignoring event {NVDAEventName} because ignored by object itself", ) return if _isDebug(): log.debug( f"handleAutomationEvent: queuing NVDA event {NVDAEventName} " - f"for NVDAObject {obj} " + f"for NVDAObject {obj} ", ) eventHandler.queueEvent(NVDAEventName,obj) @@ -867,20 +867,20 @@ def IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent(self,sender): ): if _isDebug(): log.debugWarning( - "HandleFocusChangedEvent: Ignoring duplicate focus event " + "HandleFocusChangedEvent: Ignoring duplicate focus event ", ) return except COMError: if _isDebug(): log.debugWarning( "HandleFocusChangedEvent: Couldn't check for duplicate focus event ", - exc_info=True + exc_info=True, ) window = self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent("gainFocus", windowHandle=window): if _isDebug(): log.debug( - "HandleFocusChangedEvent: Ignoring for shouldAcceptEvent=False" + "HandleFocusChangedEvent: Ignoring for shouldAcceptEvent=False", ) return try: @@ -889,13 +889,13 @@ def IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent(self,sender): if _isDebug(): log.debugWarning( "HandleFocusChangedEvent: Exception while creating NVDAObject ", - exc_info=True + exc_info=True, ) obj = None if not obj: if _isDebug(): log.debug( - "handleFocusChangedEvent: Could not create an NVDAObject " + "handleFocusChangedEvent: Could not create an NVDAObject ", ) return if _isDebug(): @@ -903,13 +903,13 @@ def IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent(self,sender): if not obj.shouldAllowUIAFocusEvent: if _isDebug(): log.debug( - "HandleFocusChangedEvent: NVDAObject chose to ignore event " + "HandleFocusChangedEvent: NVDAObject chose to ignore event ", ) return if _isDebug(): log.debug( "handleFocusChangedEvent: Queuing NVDA gainFocus event " - f"for obj {obj} " + f"for obj {obj} ", ) eventHandler.queueEvent("gainFocus",obj) @@ -918,7 +918,7 @@ def IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self,sen log.debug( f"handlePropertyChangeEvent called with property {self.getUIAPropertyIDDebugString(propertyId)}, " f"value {str(newValue.value)[:50]} " - f"for element {self.getUIAElementDebugString(sender)}" + f"for element {self.getUIAElementDebugString(sender)}", ) # #3867: For now manually force this VARIANT type to empty to get around a nasty double free in comtypes/ctypes. # We also don't use the value in this callback. @@ -938,7 +938,7 @@ def IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self,sen if _isDebug(): log.debug( f"handlePropertyChangeEvent: dropping property {self.getUIAPropertyIDDebugString(propertyId)} " - f"at request of appModule {appMod.appName}" + f"at request of appModule {appMod.appName}", ) return NVDAEventName=UIAPropertyIdsToNVDAEventNames.get(propertyId,None) @@ -956,13 +956,13 @@ def IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self,sen if _isDebug(): log.debug( "propertyChange event is for focus. " - f"Redirecting event to focus NVDAObject {focus}" + f"Redirecting event to focus NVDAObject {focus}", ) obj = focus elif not self.isNativeUIAElement(sender): if _isDebug(): log.debug( - f"HandlePropertyChangedEvent: Ignoring event {NVDAEventName} for non native element" + f"HandlePropertyChangedEvent: Ignoring event {NVDAEventName} for non native element", ) return window = obj.windowHandle if obj else self.getNearestWindowHandle(sender) @@ -970,12 +970,12 @@ def IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self,sen if _isDebug(): log.debug( f"Checking if should accept NVDA event {NVDAEventName} " - f"with window {self.getWindowHandleDebugString(window)}" + f"with window {self.getWindowHandleDebugString(window)}", ) if not eventHandler.shouldAcceptEvent(NVDAEventName, windowHandle=window): if _isDebug(): log.debug( - f"HandlePropertyChangedEvent: Ignoring event {NVDAEventName} for shouldAcceptEvent=False" + f"HandlePropertyChangedEvent: Ignoring event {NVDAEventName} for shouldAcceptEvent=False", ) return if not obj: @@ -985,7 +985,7 @@ def IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self,sen if _isDebug(): log.debugWarning( f"HandlePropertyChangedEvent: Exception while creating object for event {NVDAEventName}", - exc_info=True + exc_info=True, ) return if not obj: @@ -994,12 +994,12 @@ def IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self,sen return if _isDebug(): log.debug( - f"handlePropertyChangeEvent: created object {obj} " + f"handlePropertyChangeEvent: created object {obj} ", ) if _isDebug(): log.debug( f"handlePropertyChangeEvent: queuing NVDA {NVDAEventName} event " - f"for NVDAObject {obj} " + f"for NVDAObject {obj} ", ) eventHandler.queueEvent(NVDAEventName,obj) @@ -1009,7 +1009,7 @@ def IUIAutomationNotificationEventHandler_HandleNotificationEvent( NotificationKind, NotificationProcessing, displayString, - activityId + activityId, ): if _isDebug(): log.debug( @@ -1018,7 +1018,7 @@ def IUIAutomationNotificationEventHandler_HandleNotificationEvent( f"notificationProcessing {self.getUIANotificationProcessingValueDebugString(NotificationProcessing)}, " f"displayString {str(displayString)[:50]}, " f"activityID {activityId}, " - f"for element {self.getUIAElementDebugString(sender)}" + f"for element {self.getUIAElementDebugString(sender)}", ) if not self.MTAThreadInitEvent.is_set(): # UIAHandler hasn't finished initialising yet, so just ignore this event. @@ -1035,7 +1035,7 @@ def IUIAutomationNotificationEventHandler_HandleNotificationEvent( f"NotificationProcessing={NotificationProcessing} " f"displayString={displayString} " f"activityId={activityId}", - exc_info=True + exc_info=True, ) return if not obj: @@ -1046,24 +1046,24 @@ def IUIAutomationNotificationEventHandler_HandleNotificationEvent( "HandleNotificationEvent: Ignoring because no object: " f"NotificationProcessing={NotificationProcessing} " f"displayString={displayString} " - f"activityId={activityId}" + f"activityId={activityId}", ) return if _isDebug(): log.debug( "Queuing UIA_notification NVDA event " - f"for NVDAObject {obj}" + f"for NVDAObject {obj}", ) eventHandler.queueEvent("UIA_notification",obj, notificationKind=NotificationKind, notificationProcessing=NotificationProcessing, displayString=displayString, activityId=activityId) def IUIAutomationActiveTextPositionChangedEventHandler_HandleActiveTextPositionChangedEvent( self, sender, - textRange + textRange, ): if _isDebug(): log.debug( - f"HandleActiveTextPositionChangedEvent called for element {self.getUIAElementDebugString(sender)}" + f"HandleActiveTextPositionChangedEvent called for element {self.getUIAElementDebugString(sender)}", ) if not self.MTAThreadInitEvent.is_set(): # UIAHandler hasn't finished initialising yet, so just ignore this event. @@ -1077,19 +1077,19 @@ def IUIAutomationActiveTextPositionChangedEventHandler_HandleActiveTextPositionC if _isDebug(): log.debugWarning( "HandleActiveTextPositionChangedEvent: Exception while creating object: ", - exc_info=True + exc_info=True, ) return if not obj: if _isDebug(): log.debug( - "HandleActiveTextPositionchangedEvent: Ignoring because no object: " + "HandleActiveTextPositionchangedEvent: Ignoring because no object: ", ) return if _isDebug(): log.debug( "handleActiveTextPositionChange: Queuing UIA_activeTextPositionChanged NVDA event " - f"for NVDAObject {obj}" + f"for NVDAObject {obj}", ) eventHandler.queueEvent("UIA_activeTextPositionChanged", obj, textRange=textRange) @@ -1119,7 +1119,7 @@ def _isUIAWindowHelper(self, hwnd: int, isDebug=False) -> bool: # noqa: C901 if appModule and appModule.isGoodUIAWindow(hwnd): if isDebug: log.debug( - f"appModule {appModule.appName} says to treat window as UIA" + f"appModule {appModule.appName} says to treat window as UIA", ) return True # There are certain window classes that just had bad UIA implementations @@ -1131,7 +1131,7 @@ def _isUIAWindowHelper(self, hwnd: int, isDebug=False) -> bool: # noqa: C901 if appModule and appModule.isBadUIAWindow(hwnd): if isDebug: log.debug( - f"appModule {appModule.appName} says to not treat window as UIA" + f"appModule {appModule.appName} says to not treat window as UIA", ) return False if windowClass == "NetUIHWND" and appModule: @@ -1151,14 +1151,14 @@ def _isUIAWindowHelper(self, hwnd: int, isDebug=False) -> bool: # noqa: C901 # this is not necessarily an office app, or an app with version information, for example geekbench 6. log.debugWarning( "Failed parsing productName / productVersion, version information likely missing", - exc_info=True + exc_info=True, ) isOfficeApp = False isOffice2013OrOlder = False if isOfficeApp and isOffice2013OrOlder: parentHwnd = winUser.getAncestor(hwnd, winUser.GA_PARENT) while parentHwnd: - if winUser.getClassName(parentHwnd) in ("Net UI Tool Window", "MsoCommandBar",): + if winUser.getClassName(parentHwnd) in ("Net UI Tool Window", "MsoCommandBar"): if isDebug: log.debug("Office 2013 ribon or older. Treating as non-UIA") return False @@ -1251,7 +1251,7 @@ def isUIAWindow(self, hwnd: int, isDebug: bool = False) -> bool: if not v or (now-v[1])>0.5: v = ( self._isUIAWindowHelper(hwnd, isDebug=isDebug), - now + now, ) self.UIAWindowHandleCache[hwnd]=v elif isDebug: @@ -1266,13 +1266,13 @@ def getNearestWindowHandle(self, UIAElement): log.debug( "Got previously cached nearest windowHandle " f"of {self.getWindowHandleDebugString(windowHandle)} " - f"for element {self.getUIAElementDebugString(UIAElement)}" + f"for element {self.getUIAElementDebugString(UIAElement)}", ) return windowHandle if _isDebug(): log.debug( "Locating nearest ancestor windowHandle " - f"for element {self.getUIAElementDebugString(UIAElement)}" + f"for element {self.getUIAElementDebugString(UIAElement)}", ) try: processID = UIAElement.cachedProcessID @@ -1292,17 +1292,17 @@ def getNearestWindowHandle(self, UIAElement): ): if _isDebug(): log.debug( - f"using active WDAG local window {self.getWindowHandleDebugString(gi.hwndActive)}" + f"using active WDAG local window {self.getWindowHandleDebugString(gi.hwndActive)}", ) return gi.hwndActive else: if _isDebug(): log.debug( - f"Active window is not WDAG or is wrong instance: {self.getWindowHandleDebugString(gi.hwndActive)}" + f"Active window is not WDAG or is wrong instance: {self.getWindowHandleDebugString(gi.hwndActive)}", ) return None condition = utils.createUIAMultiPropertyCondition( - {UIA.UIA_ClassNamePropertyId: ['ApplicationFrameWindow', 'CabinetWClass']} + {UIA.UIA_ClassNamePropertyId: ['ApplicationFrameWindow', 'CabinetWClass']}, ) walker = self.clientObject.createTreeWalker(condition) else: @@ -1316,7 +1316,7 @@ def getNearestWindowHandle(self, UIAElement): new = walker.NormalizeElementBuildCache(UIAElement, cacheRequest) except COMError: log.debugWarning( - "error walking up to an element with a valid windowHandle", exc_info=True + "error walking up to an element with a valid windowHandle", exc_info=True, ) return None try: @@ -1324,13 +1324,13 @@ def getNearestWindowHandle(self, UIAElement): except COMError: if _isDebug(): log.debugWarning( - "Unable to get cachedNativeWindowHandle from found ancestor element", exc_info=True + "Unable to get cachedNativeWindowHandle from found ancestor element", exc_info=True, ) return None if _isDebug(): log.debug( "Found ancestor element " - f"with valid windowHandle {self.getWindowHandleDebugString(window)}" + f"with valid windowHandle {self.getWindowHandleDebugString(window)}", ) # Cache for future use to improve performance. UIAElement._nearestWindowHandle = window @@ -1352,7 +1352,7 @@ def _isNetUIEmbeddedInWordDoc(self, element: UIA.IUIAutomationElement) -> bool: return False condition = utils.createUIAMultiPropertyCondition( {UIA.UIA_ClassNamePropertyId: 'NetUIHWNDElement'}, - {UIA.UIA_NativeWindowHandlePropertyId: windowHandle} + {UIA.UIA_NativeWindowHandlePropertyId: windowHandle}, ) walker = self.clientObject.createTreeWalker(condition) cacheRequest = self.clientObject.createCacheRequest() @@ -1382,7 +1382,7 @@ def _emitMSAAFocusForWordDocIfNecessary(self, element: UIA.IUIAutomationElement) and not self.isUIAWindow(oldFocus.windowHandle) ): IAccessibleHandler.internalWinEventHandler.winEventLimiter.addEvent( - winUser.EVENT_OBJECT_FOCUS, oldFocus.windowHandle, winUser.OBJID_CLIENT, 0, oldFocus.windowThreadID + winUser.EVENT_OBJECT_FOCUS, oldFocus.windowHandle, winUser.OBJID_CLIENT, 0, oldFocus.windowThreadID, ) def isNativeUIAElement(self,UIAElement): @@ -1401,7 +1401,7 @@ def isNativeUIAElement(self,UIAElement): if _isDebug(): log.debug( "element is local to NVDA, " - "treating as non-native." + "treating as non-native.", ) return False # Whether this is a native element depends on whether its window natively supports UIA. @@ -1411,7 +1411,7 @@ def isNativeUIAElement(self,UIAElement): if _isDebug(): log.debug( "treating element as native due to " - f"windowHandle {self.getWindowHandleDebugString(windowHandle)}. " + f"windowHandle {self.getWindowHandleDebugString(windowHandle)}. ", ) return True # #12982: although NVDA by default may not treat this element's window as native UIA, @@ -1423,7 +1423,7 @@ def isNativeUIAElement(self,UIAElement): if self._isNetUIEmbeddedInWordDoc(UIAElement): if _isDebug(): log.debug( - "treating as native as is a netUI embedded in word doc. " + "treating as native as is a netUI embedded in word doc. ", ) return True if winUser.getClassName(windowHandle)=="DirectUIHWND" and "IEFRAME.dll" in UIAElement.cachedProviderDescription and UIAElement.currentClassName in ("DownloadBox", "accessiblebutton", "DUIToolbarButton", "PushButton"): @@ -1435,7 +1435,7 @@ def isNativeUIAElement(self,UIAElement): # Therefore, we must use UIA here. if _isDebug(): log.debug( - "treating as native as is in IE9 downloads list. " + "treating as native as is in IE9 downloads list. ", ) return True if _isDebug(): diff --git a/source/UIAHandler/_remoteOps/builder.py b/source/UIAHandler/_remoteOps/builder.py index 0c966057db2..e019b07a3d5 100644 --- a/source/UIAHandler/_remoteOps/builder.py +++ b/source/UIAHandler/_remoteOps/builder.py @@ -10,14 +10,14 @@ Self, ClassVar, Any, - Iterable + Iterable, ) import ctypes from ctypes import ( _SimpleCData, c_char, c_long, - c_wchar + c_wchar, ) import enum from dataclasses import dataclass @@ -154,7 +154,7 @@ class GenericInstruction(InstructionBase): def __init__( self, opCode: lowLevel.InstructionType, - **kwargs: Operand | _SimpleCData | ctypes.Array | ctypes.Structure + **kwargs: Operand | _SimpleCData | ctypes.Array | ctypes.Structure, ): self.opCode = opCode self._params = kwargs @@ -273,9 +273,11 @@ def overrideDefaultSection(self, section: str): self._defaultSection = oldDefaultSection def getAllInstructions(self) -> list[InstructionBase]: - return list(itertools.chain.from_iterable( - instructionList._instructions for instructionList in self._instructionListBySection.values() - )) + return list( + itertools.chain.from_iterable( + instructionList._instructions for instructionList in self._instructionListBySection.values() + ), + ) def getByteCode(self) -> bytes: byteCode = self._versionBytes diff --git a/source/UIAHandler/_remoteOps/instructions/element.py b/source/UIAHandler/_remoteOps/instructions/element.py index e94e34cf51b..c5e6afa9ad3 100644 --- a/source/UIAHandler/_remoteOps/instructions/element.py +++ b/source/UIAHandler/_remoteOps/instructions/element.py @@ -30,7 +30,7 @@ class IsElement(_TypedInstruction): def localExecute(self, registers: dict[lowLevel.OperandId, object]): registers[self.result.operandId] = isinstance( - registers[self.target.operandId], POINTER(UIA.IUIAutomationElement) + registers[self.target.operandId], POINTER(UIA.IUIAutomationElement), ) diff --git a/source/UIAHandler/_remoteOps/localExecute.py b/source/UIAHandler/_remoteOps/localExecute.py index d2b629fbce8..57a30f4905f 100644 --- a/source/UIAHandler/_remoteOps/localExecute.py +++ b/source/UIAHandler/_remoteOps/localExecute.py @@ -110,7 +110,7 @@ def _execute_NewLoopBlock(self, instruction: instructions.NewLoopBlock): self._instructionLoop( stopInstruction=instructions.EndLoopBlock, breakAddress=breakAddress, - continueAddress=continueAddress + continueAddress=continueAddress, ) def _execute_NewTryBlock(self, instruction: instructions.NewTryBlock): @@ -136,7 +136,7 @@ def _executeInstruction( self, instruction: builder.InstructionBase, breakAddress: int | None = None, - continueAddress: int | None = None + continueAddress: int | None = None, ): match instruction: case instructions.Halt(): @@ -166,7 +166,7 @@ def _instructionLoop( stopInstruction: Type[builder.InstructionBase] | None = None, breakAddress: int | None = None, continueAddress: int | None = None, - catchAddress: int | None = None + catchAddress: int | None = None, ): self._instructionLoopDepth += 1 try: @@ -224,5 +224,5 @@ def execute(self) -> LocalExecutionResult: results={k: v for k, v in self._registers.items() if k in self._requestedResults}, status=status, errorLocation=self._ip, - extendedError=self._operationStatus + extendedError=self._operationStatus, ) diff --git a/source/UIAHandler/_remoteOps/lowLevel.py b/source/UIAHandler/_remoteOps/lowLevel.py index effa9524189..c6fe08c488d 100644 --- a/source/UIAHandler/_remoteOps/lowLevel.py +++ b/source/UIAHandler/_remoteOps/lowLevel.py @@ -10,7 +10,7 @@ c_void_p, c_long, c_ulong, - c_bool + c_bool, ) from comtypes.automation import VARIANT import os @@ -361,16 +361,16 @@ class TextPatternRangeEndpoint(enum.IntEnum): PropertyId = enum.IntEnum( "PropertyId", - {k[4:-10]: v for k, v in vars(UIA).items() if k.endswith("PropertyId")} + {k[4:-10]: v for k, v in vars(UIA).items() if k.endswith("PropertyId")}, ) AttributeId = enum.IntEnum( "AttributeId", - {k[4:-11]: v for k, v in vars(UIA).items() if k.endswith("AttributeId")} + {k[4:-11]: v for k, v in vars(UIA).items() if k.endswith("AttributeId")}, ) StyleId = enum.IntEnum( "StyleId", - {k[8:]: v for k, v in vars(UIA).items() if k.startswith("StyleId")} + {k[8:]: v for k, v in vars(UIA).items() if k.startswith("StyleId")}, ) diff --git a/source/UIAHandler/_remoteOps/operation.py b/source/UIAHandler/_remoteOps/operation.py index ecb52fcfcec..c4477203008 100644 --- a/source/UIAHandler/_remoteOps/operation.py +++ b/source/UIAHandler/_remoteOps/operation.py @@ -143,7 +143,7 @@ def execute(self) -> ExecutionResult: status=resultSet.status, errorLocation=resultSet.errorLocation, extendedError=resultSet.extendedError, - resultSet=resultSet + resultSet=resultSet, ) @@ -166,7 +166,7 @@ def __init__( self, enableCompiletimeLogging: bool = False, enableRuntimeLogging: bool = False, - localMode: bool = False + localMode: bool = False, ): self._compiletimeLoggingEnabled = enableCompiletimeLogging self._runtimeLoggingEnabled = enableRuntimeLogging @@ -183,26 +183,26 @@ def __init__( def importElement( self, element: UIA.IUIAutomationElement, - operandId: lowLevel.OperandId | None = None + operandId: lowLevel.OperandId | None = None, ) -> remoteAPI.RemoteElement: if operandId is None: operandId = self._rob.requestNewOperandId() self._importedElements[operandId] = element self._rob.getDefaultInstructionList().addMetaCommand( - f"importElement into {operandId}, value {element}" + f"importElement into {operandId}, value {element}", ) return remoteAPI.RemoteElement(self._rob, operandId) def importTextRange( self, textRange: UIA.IUIAutomationTextRange, - operandId: lowLevel.OperandId | None = None + operandId: lowLevel.OperandId | None = None, ) -> remoteAPI.RemoteTextRange: if operandId is None: operandId = self._rob.requestNewOperandId() self._importedTextRanges[operandId] = textRange self._rob.getDefaultInstructionList().addMetaCommand( - f"importTextRange into {operandId}, value {textRange}" + f"importTextRange into {operandId}, value {textRange}", ) return remoteAPI.RemoteTextRange(self._rob, operandId) @@ -249,7 +249,7 @@ def buildContext(self): def buildFunction( self, - func: Callable[[remoteAPI.RemoteAPI], None] + func: Callable[[remoteAPI.RemoteAPI], None], ) -> Operation: with self.buildContext() as ra: self._returnIdOperand = ra.newInt(-1) @@ -259,7 +259,7 @@ def buildFunction( def buildIterableFunction( self, - func: Callable[[remoteAPI.RemoteAPI], None] + func: Callable[[remoteAPI.RemoteAPI], None], ) -> Operation: with self.buildContext() as ra: self._yieldListOperand = ra.newArray() @@ -295,7 +295,7 @@ def _dumpRemoteLog(self): f"Remote log for execution {self._executionCount}\n" "--- Begin ---\n" f"{logOutput}" - "--- end ---" + "--- end ---", ) def _dumpCompiletimeLog(self): @@ -303,7 +303,7 @@ def _dumpCompiletimeLog(self): "Dumping instructions:\n" "--- Begin ---\n" f"{self._rob.dumpInstructions()}" - "--- End ---" + "--- End ---", ) def _executeUntilSuccess(self, maxTries: int) -> Generator[ExecutionResult, None, None]: @@ -326,13 +326,13 @@ def _executeUntilSuccess(self, maxTries: int) -> Generator[ExecutionResult, None break except Exception as e: e.add_note( - f"Error occured on execution try {self._executionCount}" + f"Error occured on execution try {self._executionCount}", ) e.add_note( "Dumping instructions:\n" "--- Begin ---\n" f"{self._rob.dumpInstructions()}" - "--- End ---" + "--- End ---", ) raise diff --git a/source/UIAHandler/_remoteOps/remoteAPI.py b/source/UIAHandler/_remoteOps/remoteAPI.py index 260605c7ff2..00c191f2aed 100644 --- a/source/UIAHandler/_remoteOps/remoteAPI.py +++ b/source/UIAHandler/_remoteOps/remoteAPI.py @@ -11,18 +11,18 @@ Callable, Generator, TypeVar, - cast + cast, ) import contextlib from comtypes import ( - GUID + GUID, ) from UIAHandler import UIA from .lowLevel import RelativeOffset from . import instructions from . import builder from .remoteFuncWrapper import ( - remoteContextManager + remoteContextManager, ) from . import operation from .remoteTypes import ( @@ -58,7 +58,7 @@ def Return(self, *values: RemoteBaseObject | int | float | str | bool | None): else: remoteValue = self.newArray() self.addCompiletimeComment( - f"Created {remoteValue} for returning values {remoteValues}" + f"Created {remoteValue} for returning values {remoteValues}", ) for value in remoteValues: remoteValue.append(value) @@ -66,7 +66,7 @@ def Return(self, *values: RemoteBaseObject | int | float | str | bool | None): raise RuntimeError("ReturnIdOperand not set not created") self._op.addToResults(remoteValue) self.addCompiletimeComment( - f"Returning {remoteValue}" + f"Returning {remoteValue}", ) self._op._returnIdOperand.set(remoteValue.operandId.value) self.halt() @@ -79,7 +79,7 @@ def Yield(self, *values: RemoteBaseObject | int | float | str | bool | None): else: remoteValue = self.newArray() self.addCompiletimeComment( - f"Created {remoteValue} for yielding values {remoteValues}" + f"Created {remoteValue} for yielding values {remoteValues}", ) for value in remoteValues: remoteValue.append(value) @@ -95,7 +95,7 @@ def _newObject( self, RemoteType: Type[_newObject_RemoteType], value: Any, - static: bool = False + static: bool = False, ) -> _newObject_RemoteType: section = "static" if static else "main" with self.rob.overrideDefaultSection(section): @@ -137,7 +137,7 @@ def newArray(self) -> RemoteArray: def newElement( self, value: UIA.IUIAutomationElement | None = None, - static: bool = False + static: bool = False, ) -> RemoteElement: section = "static" if static else "main" with self.rob.overrideDefaultSection(section): @@ -152,7 +152,7 @@ def newElement( def newTextRange( self, value: UIA.IUIAutomationTextRange | None = None, - static: bool = False + static: bool = False, ) -> RemoteTextRange: section = "static" if static else "main" with self.rob.overrideDefaultSection(section): @@ -170,8 +170,8 @@ def getOperationStatus(self) -> RemoteInt: result = RemoteInt(self.rob, self.rob.requestNewOperandId()) instructionList.addInstruction( instructions.GetOperationStatus( - result=result - ) + result=result, + ), ) return result @@ -179,8 +179,8 @@ def setOperationStatus(self, status: RemoteInt | int): instructionList = self.rob.getDefaultInstructionList() instructionList.addInstruction( instructions.SetOperationStatus( - status=RemoteInt.ensureRemote(self.rob, status) - ) + status=RemoteInt.ensureRemote(self.rob, status), + ), ) _scopeInstructionJustExited: instructions.InstructionBase | None = None @@ -240,7 +240,7 @@ def whileBlock(self, conditionBuilderFunc: Callable[[], RemoteBool], silent: boo # Add a new loop block instruction to start the while loop loopBlockInstruction = instructions.NewLoopBlock( breakBranch=RelativeOffset(1), # offset updated after yield - continueBranch=RelativeOffset(1) + continueBranch=RelativeOffset(1), ) loopBlockInstructionIndex = instructionList.addInstruction(loopBlockInstruction) # generate the loop condition. @@ -270,7 +270,7 @@ def forEachNumInRange( self, start: _range_intTypeVar | int, stop: _range_intTypeVar | int, - step: _range_intTypeVar | int = 1 + step: _range_intTypeVar | int = 1, ) -> Generator[RemoteIntBase, None, None]: RemoteType: Type[RemoteIntBase] = RemoteInt for arg in (start, stop, step): @@ -288,7 +288,7 @@ def forEachNumInRange( @remoteContextManager def forEachItemInArray( self, - array: RemoteArray + array: RemoteArray, ) -> Generator[RemoteVariant, None, None]: with self.forEachNumInRange(0, array.size()) as index: yield array[index] @@ -324,7 +324,7 @@ def catchBlock(self, silent: bool = False): if not silent: instructionList.addComment("Jump over catch block") jumpCatchInstruction = instructions.Fork( - jumpTo=RelativeOffset(1) # offset updated after yield + jumpTo=RelativeOffset(1), # offset updated after yield ) jumpCatchInstructionIndex = instructionList.addInstruction(jumpCatchInstruction) # increment the catch offset of the previous try block to take the new jump instruction into account. diff --git a/source/UIAHandler/_remoteOps/remoteAlgorithms.py b/source/UIAHandler/_remoteOps/remoteAlgorithms.py index 2af9e16eb4b..289468defec 100644 --- a/source/UIAHandler/_remoteOps/remoteAlgorithms.py +++ b/source/UIAHandler/_remoteOps/remoteAlgorithms.py @@ -6,15 +6,15 @@ from __future__ import annotations from collections.abc import Generator from .remoteFuncWrapper import ( - remoteContextManager + remoteContextManager, ) from .remoteAPI import RemoteAPI from .remoteTypes import ( RemoteIntEnum, - RemoteTextRange + RemoteTextRange, ) from .lowLevel import ( - TextUnit + TextUnit, ) @@ -23,7 +23,7 @@ def remote_forEachUnitInTextRange( ra: RemoteAPI, textRange: RemoteTextRange, unit: RemoteIntEnum[TextUnit] | TextUnit, - reverse: bool = False + reverse: bool = False, ) -> Generator[RemoteTextRange, None, None]: logicalTextRange = textRange.getLogicalAdapter(reverse) logicalTempRange = logicalTextRange.clone() diff --git a/source/UIAHandler/_remoteOps/remoteFuncWrapper.py b/source/UIAHandler/_remoteOps/remoteFuncWrapper.py index 54a3c09abe5..a47cf594143 100644 --- a/source/UIAHandler/_remoteOps/remoteFuncWrapper.py +++ b/source/UIAHandler/_remoteOps/remoteFuncWrapper.py @@ -11,7 +11,7 @@ Callable, Concatenate, ParamSpec, - TypeVar + TypeVar, ) import functools import contextlib @@ -35,11 +35,11 @@ def _execRawFunc( func: Callable[Concatenate[_remoteFunc_self, _remoteFunc_paramSpec], _remoteFunc_return], funcSelf: _remoteFunc_self, *args: _remoteFunc_paramSpec.args, - **kwargs: _remoteFunc_paramSpec.kwargs + **kwargs: _remoteFunc_paramSpec.kwargs, ) -> _remoteFunc_return: main = funcSelf.rob.getInstructionList('main') main.addComment( - f"Entering {func.__qualname__}{self.generateArgsKwargsString(*args, **kwargs)}" + f"Entering {func.__qualname__}{self.generateArgsKwargsString(*args, **kwargs)}", ) res = func(funcSelf, *args, **kwargs) main.addComment(f"Exiting {func.__qualname__}") @@ -53,7 +53,7 @@ def __call__( def wrapper( funcSelf: _remoteFunc_self, *args: _remoteFunc_paramSpec.args, - **kwargs: _remoteFunc_paramSpec.kwargs + **kwargs: _remoteFunc_paramSpec.kwargs, ) -> _remoteFunc_return: return self._execRawFunc(func, funcSelf, *args, **kwargs) return wrapper @@ -71,7 +71,7 @@ def _execRawFunc( func: Callable[Concatenate[_remoteFunc_self, _remoteFunc_paramSpec], _remoteFunc_return], funcSelf: _remoteFunc_self, *args: _remoteFunc_paramSpec.args, - **kwargs: _remoteFunc_paramSpec.kwargs + **kwargs: _remoteFunc_paramSpec.kwargs, ) -> _remoteFunc_return: if self._mutable and not funcSelf._mutable: raise RuntimeError(f"{funcSelf.__class__.__name__} is not mutable") @@ -83,8 +83,8 @@ class RemoteContextManager(_BaseRemoteFuncWrapper): def __call__( self, func: Callable[ - Concatenate[_remoteFunc_self, _remoteFunc_paramSpec], Generator[_remoteFunc_return, None, None] - ] + Concatenate[_remoteFunc_self, _remoteFunc_paramSpec], Generator[_remoteFunc_return, None, None], + ], ) -> Callable[Concatenate[_remoteFunc_self, _remoteFunc_paramSpec], ContextManager[_remoteFunc_return]]: contextFunc = contextlib.contextmanager(func) return super().__call__(contextFunc) @@ -95,11 +95,11 @@ def _execRawFunc( func: Callable[Concatenate[_remoteFunc_self, _remoteFunc_paramSpec], ContextManager[_remoteFunc_return]], funcSelf: _remoteFunc_self, *args: _remoteFunc_paramSpec.args, - **kwargs: _remoteFunc_paramSpec.kwargs + **kwargs: _remoteFunc_paramSpec.kwargs, ) -> Generator[_remoteFunc_return, None, None]: main = funcSelf.rob.getInstructionList('main') main.addComment( - f"Entering context manager {func.__qualname__}{self.generateArgsKwargsString(*args, **kwargs)}" + f"Entering context manager {func.__qualname__}{self.generateArgsKwargsString(*args, **kwargs)}", ) with func(funcSelf, *args, **kwargs) as val: main.addComment("Yielding to outer scope") diff --git a/source/UIAHandler/_remoteOps/remoteTypes/__init__.py b/source/UIAHandler/_remoteOps/remoteTypes/__init__.py index e9d666bfa3b..eaccfcb9034 100644 --- a/source/UIAHandler/_remoteOps/remoteTypes/__init__.py +++ b/source/UIAHandler/_remoteOps/remoteTypes/__init__.py @@ -13,7 +13,7 @@ Iterable, Generic, TypeVar, - cast + cast, ) from types import NoneType import ctypes @@ -26,7 +26,7 @@ from comtypes import ( GUID, IUnknown, - COMError + COMError, ) import enum from UIAHandler import UIA @@ -35,7 +35,7 @@ from .. import builder from ..remoteFuncWrapper import ( remoteMethod, - remoteMethod_mutable + remoteMethod_mutable, ) from .. import operation @@ -76,7 +76,7 @@ def _initOperand(self, initialValue: LocalTypeVar | None = None, const: bool =Fa if not isinstance(initialValue, self.LocalType): raise TypeError( f"initialValue must be of type {self.LocalType.__name__} " - f"not {type(initialValue).__name__}" + f"not {type(initialValue).__name__}", ) self._initialValue = initialValue self._mutable = not const @@ -90,7 +90,7 @@ def createNew( rob: builder.RemoteOperationBuilder, initialValue: LocalTypeVar | None = None, operandId: lowLevel.OperandId | None = None, - const: bool = False + const: bool = False, ) -> Self: if operandId is None: operandId = rob.requestNewOperandId() @@ -113,7 +113,7 @@ def ensureRemote(cls, rob: builder.RemoteOperationBuilder, obj: Self | LocalType if not issubclass(RemoteType, cls): raise TypeError( f"The RemoteType of {type(obj).__name__} is {RemoteType.__name__} " - f"which is not a subclass of {cls.__name__}" + f"which is not a subclass of {cls.__name__}", ) cacheKey = (RemoteType, obj) cachedRemoteObj = rob._remotedArgCache.get(cacheKey) @@ -121,13 +121,13 @@ def ensureRemote(cls, rob: builder.RemoteOperationBuilder, obj: Self | LocalType if not isinstance(cachedRemoteObj, RemoteType): raise RuntimeError(f"Cache entry for {cacheKey} is not of type {RemoteType.__name__}") rob.getDefaultInstructionList().addComment( - f"Using cached {cachedRemoteObj} for constant value {repr(obj)}" + f"Using cached {cachedRemoteObj} for constant value {repr(obj)}", ) return cast(RemoteType, cachedRemoteObj) with rob.overrideDefaultSection('const'): remoteObj = RemoteType.createNew(rob, obj, const=True) rob.getDefaultInstructionList().addComment( - f"Using cached {remoteObj} for constant value {repr(obj)}" + f"Using cached {remoteObj} for constant value {repr(obj)}", ) rob._remotedArgCache[cacheKey] = remoteObj return remoteObj @@ -154,8 +154,8 @@ def set(self, other: Self | LocalTypeVar): self.rob.getDefaultInstructionList().addInstruction( instructions.Set( target=self, - value=type(self).ensureRemote(self.rob, other) - ) + value=type(self).ensureRemote(self.rob, other), + ), ) @remoteMethod @@ -164,8 +164,8 @@ def copy(self) -> Self: self.rob.getDefaultInstructionList().addInstruction( instructions.Set( target=copy, - value=self - ) + value=self, + ), ) return copy @@ -176,8 +176,8 @@ def _doCompare(self, comparisonType: lowLevel.ComparisonType, other: Self | Loca result=result, left=self, right=type(self).ensureRemote(self.rob, other), - comparisonType=comparisonType - ) + comparisonType=comparisonType, + ), ) return result @@ -195,8 +195,8 @@ def stringify(self) -> RemoteString: self.rob.getDefaultInstructionList().addInstruction( instructions.Stringify( result=result, - target=self - ) + target=self, + ), ) return result @@ -205,7 +205,7 @@ class RemoteVariant(RemoteBaseObject): def _generateInitInstructions(self) -> Iterable[instructions.InstructionBase]: yield instructions.NewNull( - result=self + result=self, ) def _isType(self, RemoteClass: Type[RemoteBaseObject]) -> RemoteBool: @@ -215,8 +215,8 @@ def _isType(self, RemoteClass: Type[RemoteBaseObject]) -> RemoteBool: self.rob.getDefaultInstructionList().addInstruction( RemoteClass._IsTypeInstruction( result=result, - target=self - ) + target=self, + ), ) return result @@ -265,9 +265,9 @@ def asType(self, remoteClass: Type[_TV_asType]) -> _TV_asType: class RemoteNull(RemoteBaseObject): _IsTypeInstruction = instructions.IsNull - def _generateInitInstructions(self,) -> Iterable[instructions.InstructionBase]: + def _generateInitInstructions(self) -> Iterable[instructions.InstructionBase]: yield instructions.NewNull( - result=self + result=self, ) @@ -279,7 +279,7 @@ class RemoteIntegral(RemoteBaseObject[LocalTypeVar], Generic[LocalTypeVar]): def _generateInitInstructions(self) -> Iterable[instructions.InstructionBase]: yield self._NewInstruction( result=self, - value=self._ctype(self.initialValue) + value=self._ctype(self.initialValue), ) @@ -296,8 +296,8 @@ def inverse(self) -> RemoteBool: self.rob.getDefaultInstructionList().addInstruction( instructions.BoolNot( result=result, - target=self - ) + target=self, + ), ) return result @@ -308,8 +308,8 @@ def __and__(self, other: Self | bool) -> RemoteBool: instructions.BoolAnd( result=result, left=self, - right=RemoteBool.ensureRemote(self.rob, other) - ) + right=RemoteBool.ensureRemote(self.rob, other), + ), ) return result @@ -320,8 +320,8 @@ def __rand__(self, other: Self | bool) -> RemoteBool: instructions.BoolAnd( result=result, left=self, - right=RemoteBool.ensureRemote(self.rob, other) - ) + right=RemoteBool.ensureRemote(self.rob, other), + ), ) return result @@ -332,8 +332,8 @@ def __or__(self, other: Self | bool) -> RemoteBool: instructions.BoolOr( result=result, left=self, - right=RemoteBool.ensureRemote(self.rob, other) - ) + right=RemoteBool.ensureRemote(self.rob, other), + ), ) return result @@ -344,8 +344,8 @@ def __ror__(self, other: Self | bool) -> RemoteBool: instructions.BoolOr( result=result, left=self, - right=RemoteBool.ensureRemote(self.rob, other) - ) + right=RemoteBool.ensureRemote(self.rob, other), + ), ) return result @@ -375,8 +375,8 @@ def __add__(self, other: Self | LocalTypeVar) -> Self: instructions.BinaryAdd( result=result, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return result @@ -387,8 +387,8 @@ def __sub__(self, other: Self | LocalTypeVar) -> Self: instructions.BinarySubtract( result=result, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return result @@ -399,8 +399,8 @@ def __mul__(self, other: Self | LocalTypeVar) -> Self: instructions.BinaryMultiply( result=result, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return result @@ -411,8 +411,8 @@ def __truediv__(self, other: Self | LocalTypeVar) -> Self: instructions.BinaryDivide( result=result, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return result @@ -427,8 +427,8 @@ def __radd__(self, other: Self | LocalTypeVar) -> Self: instructions.BinaryAdd( result=result, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return result @@ -439,8 +439,8 @@ def __rsub__(self, other: Self | LocalTypeVar) -> Self: instructions.BinarySubtract( result=result, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return result @@ -451,8 +451,8 @@ def __rmul__(self, other: Self | LocalTypeVar) -> Self: instructions.BinaryMultiply( result=result, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return result @@ -463,8 +463,8 @@ def __rtruediv__(self, other: Self | LocalTypeVar) -> Self: instructions.BinaryDivide( result=result, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return result @@ -477,8 +477,8 @@ def __iadd__(self, other: Self | LocalTypeVar) -> Self: self.rob.getDefaultInstructionList().addInstruction( instructions.InplaceAdd( target=self, - value=type(self).ensureRemote(self.rob, other) - ) + value=type(self).ensureRemote(self.rob, other), + ), ) return self @@ -487,8 +487,8 @@ def __isub__(self, other: Self | LocalTypeVar) -> Self: self.rob.getDefaultInstructionList().addInstruction( instructions.InplaceSubtract( target=self, - value=type(self).ensureRemote(self.rob, other) - ) + value=type(self).ensureRemote(self.rob, other), + ), ) return self @@ -497,8 +497,8 @@ def __imul__(self, other: Self | LocalTypeVar) -> Self: self.rob.getDefaultInstructionList().addInstruction( instructions.InplaceMultiply( target=self, - value=type(self).ensureRemote(self.rob, other) - ) + value=type(self).ensureRemote(self.rob, other), + ), ) return self @@ -507,8 +507,8 @@ def __itruediv__(self, other: Self | LocalTypeVar) -> Self: self.rob.getDefaultInstructionList().addInstruction( instructions.InplaceDivide( target=self, - value=type(self).ensureRemote(self.rob, other) - ) + value=type(self).ensureRemote(self.rob, other), + ), ) return self @@ -560,7 +560,7 @@ def _generateInitInstructions(self) -> Iterable[instructions.InstructionBase]: yield instructions.NewString( result=self, length=c_ulong(stringLen), - value=stringVal + value=stringVal, ) def _concat(self, other: Self | str) -> Self: @@ -569,8 +569,8 @@ def _concat(self, other: Self | str) -> Self: instructions.StringConcat( result=result, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return result @@ -588,8 +588,8 @@ def __iadd__(self, other: Self | str) -> Self: instructions.StringConcat( result=self, left=self, - right=type(self).ensureRemote(self.rob, other) - ) + right=type(self).ensureRemote(self.rob, other), + ), ) return self @@ -599,8 +599,8 @@ def set(self, other: Self | str): instructions.NewString( result=self, length=c_ulong(1), - value=ctypes.create_unicode_buffer("") - ) + value=ctypes.create_unicode_buffer(""), + ), ) self += other @@ -615,7 +615,7 @@ class RemoteArray(RemoteBaseObject): _LOCAL_COM_INTERFACES = [ UIA.IUIAutomationElement, - UIA.IUIAutomationTextRange + UIA.IUIAutomationTextRange, ] def _correctCOMPointers(self, *items: object) -> list: @@ -640,7 +640,7 @@ def localValue(self) -> list: def _generateInitInstructions(self) -> Iterable[instructions.InstructionBase]: yield instructions.NewArray( - result=self + result=self, ) @remoteMethod @@ -650,8 +650,8 @@ def __getitem__(self, index: RemoteIntBase | int) -> RemoteVariant: instructions.ArrayGetAt( result=result, target=self, - index=RemoteIntBase.ensureRemote(self.rob, index) - ) + index=RemoteIntBase.ensureRemote(self.rob, index), + ), ) return result @@ -661,8 +661,8 @@ def size(self) -> RemoteUint: self.rob.getDefaultInstructionList().addInstruction( instructions.ArraySize( result=result, - target=self - ) + target=self, + ), ) return result @@ -671,22 +671,22 @@ def append(self, value: RemoteBaseObject | int | float | str) -> None: self.rob.getDefaultInstructionList().addInstruction( instructions.ArrayAppend( target=self, - value=RemoteBaseObject.ensureRemote(self.rob, value) - ) + value=RemoteBaseObject.ensureRemote(self.rob, value), + ), ) @remoteMethod_mutable def __setitem__( self, index: RemoteIntBase | int, - value: RemoteBaseObject | int | float | str + value: RemoteBaseObject | int | float | str, ) -> None: self.rob.getDefaultInstructionList().addInstruction( instructions.ArraySetAt( target=self, index=RemoteIntBase.ensureRemote(self.rob, index), - value=RemoteBaseObject.ensureRemote(self.rob, value) - ) + value=RemoteBaseObject.ensureRemote(self.rob, value), + ), ) @remoteMethod_mutable @@ -694,8 +694,8 @@ def remove(self, index: RemoteIntBase | int) -> None: self.rob.getDefaultInstructionList().addInstruction( instructions.ArrayRemoveAt( target=self, - index=RemoteIntBase.ensureRemote(self.rob, index) - ) + index=RemoteIntBase.ensureRemote(self.rob, index), + ), ) @@ -710,7 +710,7 @@ def _defaultInitialValue(self) -> GUID: def _generateInitInstructions(self) -> Iterable[instructions.InstructionBase]: yield instructions.NewGuid( result=self, - value=self.initialValue + value=self.initialValue, ) diff --git a/source/UIAHandler/_remoteOps/remoteTypes/element.py b/source/UIAHandler/_remoteOps/remoteTypes/element.py index ccd60f75785..51b3c9c4a6d 100644 --- a/source/UIAHandler/_remoteOps/remoteTypes/element.py +++ b/source/UIAHandler/_remoteOps/remoteTypes/element.py @@ -6,22 +6,22 @@ from __future__ import annotations from typing import ( - cast + cast, ) from ctypes import ( - POINTER + POINTER, ) from UIAHandler import UIA from .. import lowLevel from .. import instructions from ..remoteFuncWrapper import ( - remoteMethod + remoteMethod, ) from . import ( RemoteExtensionTarget, RemoteIntEnum, RemoteBool, - RemoteVariant + RemoteVariant, ) @@ -50,7 +50,7 @@ def localValue(self) -> UIA.IUIAutomationElement: def getPropertyValue( self, propertyId: RemoteIntEnum[lowLevel.PropertyId] | lowLevel.PropertyId, - ignoreDefault: RemoteBool | bool = False + ignoreDefault: RemoteBool | bool = False, ) -> RemoteVariant: result = RemoteVariant(self.rob, self.rob.requestNewOperandId()) self.rob.getDefaultInstructionList().addInstruction( @@ -58,8 +58,8 @@ def getPropertyValue( result=result, target=self, propertyId=RemoteIntEnum.ensureRemote(self.rob, propertyId), - ignoreDefault=RemoteBool.ensureRemote(self.rob, ignoreDefault) - ) + ignoreDefault=RemoteBool.ensureRemote(self.rob, ignoreDefault), + ), ) return result @@ -69,8 +69,8 @@ def _navigate(self, navigationDirection: lowLevel.NavigationDirection) -> Remote instructions.ElementNavigate( result=result, target=self, - direction=RemoteIntEnum.ensureRemote(self.rob, navigationDirection) - ) + direction=RemoteIntEnum.ensureRemote(self.rob, navigationDirection), + ), ) return result diff --git a/source/UIAHandler/_remoteOps/remoteTypes/extensionTarget.py b/source/UIAHandler/_remoteOps/remoteTypes/extensionTarget.py index 21cec7d7d3b..8ca086379f9 100644 --- a/source/UIAHandler/_remoteOps/remoteTypes/extensionTarget.py +++ b/source/UIAHandler/_remoteOps/remoteTypes/extensionTarget.py @@ -7,18 +7,18 @@ from __future__ import annotations from typing import ( Iterable, - Generic + Generic, ) from ctypes import ( c_ulong, ) from comtypes import ( - GUID + GUID, ) from .. import instructions from ..remoteFuncWrapper import ( remoteMethod, - remoteMethod_mutable + remoteMethod_mutable, ) from . import ( LocalTypeVar, @@ -38,7 +38,7 @@ class RemoteExtensionTarget(RemoteBaseObject[LocalTypeVar], Generic[LocalTypeVar def _generateInitInstructions(self) -> Iterable[instructions.InstructionBase]: yield instructions.NewNull( - result=self + result=self, ) @remoteMethod @@ -53,8 +53,8 @@ def isExtensionSupported(self, extensionId: RemoteGuid | GUID) -> RemoteBool: instructions.IsExtensionSupported( result=result, target=self, - extensionId=RemoteGuid.ensureRemote(self.rob, extensionId) - ) + extensionId=RemoteGuid.ensureRemote(self.rob, extensionId), + ), ) return result @@ -62,13 +62,13 @@ def isExtensionSupported(self, extensionId: RemoteGuid | GUID) -> RemoteBool: def callExtension( self, extensionId: RemoteGuid | GUID, - *params: RemoteBaseObject | int | float | str + *params: RemoteBaseObject | int | float | str, ) -> None: self.rob.getDefaultInstructionList().addInstruction( instructions.CallExtension( target=self, extensionId=RemoteGuid.ensureRemote(self.rob, extensionId), argCount=c_ulong(len(params)), - arguments=[RemoteBaseObject.ensureRemote(self.rob, param) for param in params] - ) + arguments=[RemoteBaseObject.ensureRemote(self.rob, param) for param in params], + ), ) diff --git a/source/UIAHandler/_remoteOps/remoteTypes/intEnum.py b/source/UIAHandler/_remoteOps/remoteTypes/intEnum.py index 091324166aa..34754370907 100644 --- a/source/UIAHandler/_remoteOps/remoteTypes/intEnum.py +++ b/source/UIAHandler/_remoteOps/remoteTypes/intEnum.py @@ -15,13 +15,13 @@ ) from ctypes import ( _SimpleCData, - c_long + c_long, ) import enum from .. import builder from . import ( RemoteInt, - remoteMethod + remoteMethod, ) @@ -85,7 +85,7 @@ def _initOperand(self, initialValue: _RemoteIntEnum_LocalTypeVar, const: bool = def ensureRemote( cls, rob: builder.RemoteOperationBuilder, - obj: RemoteIntEnum[_RemoteIntEnum_LocalTypeVar] | _RemoteIntEnum_LocalTypeVar + obj: RemoteIntEnum[_RemoteIntEnum_LocalTypeVar] | _RemoteIntEnum_LocalTypeVar, ) -> RemoteIntEnum[_RemoteIntEnum_LocalTypeVar]: remoteObj = super().ensureRemote(rob, cast(Any, obj)) return cast(RemoteIntEnum[_RemoteIntEnum_LocalTypeVar], remoteObj) diff --git a/source/UIAHandler/_remoteOps/remoteTypes/textRange.py b/source/UIAHandler/_remoteOps/remoteTypes/textRange.py index 2f18f1a89e2..a8c4bf92161 100644 --- a/source/UIAHandler/_remoteOps/remoteTypes/textRange.py +++ b/source/UIAHandler/_remoteOps/remoteTypes/textRange.py @@ -6,10 +6,10 @@ from __future__ import annotations from typing import ( - cast + cast, ) from ctypes import ( - POINTER + POINTER, ) from UIAHandler import UIA from .. import lowLevel @@ -17,7 +17,7 @@ from .. import builder from ..remoteFuncWrapper import ( remoteMethod, - remoteMethod_mutable + remoteMethod_mutable, ) from . import ( RemoteVariant, @@ -55,8 +55,8 @@ def clone(self) -> RemoteTextRange: self.rob.getDefaultInstructionList().addInstruction( instructions.TextRangeClone( result=result, - target=self - ) + target=self, + ), ) return result @@ -66,8 +66,8 @@ def getEnclosingElement(self) -> RemoteElement: self.rob.getDefaultInstructionList().addInstruction( instructions.TextRangeGetEnclosingElement( result=result, - target=self - ) + target=self, + ), ) return result @@ -78,8 +78,8 @@ def getText(self, maxLength: RemoteInt | int) -> RemoteString: instructions.TextRangeGetText( result=result, target=self, - maxLength=RemoteInt.ensureRemote(self.rob, maxLength) - ) + maxLength=RemoteInt.ensureRemote(self.rob, maxLength), + ), ) return result @@ -88,8 +88,8 @@ def expandToEnclosingUnit(self, unit: RemoteIntEnum[lowLevel.TextUnit] | lowLeve self.rob.getDefaultInstructionList().addInstruction( instructions.TextRangeExpandToEnclosingUnit( target=self, - unit=RemoteIntEnum.ensureRemote(self.rob, unit) - ) + unit=RemoteIntEnum.ensureRemote(self.rob, unit), + ), ) @remoteMethod_mutable @@ -97,7 +97,7 @@ def moveEndpointByUnit( self, endpoint: RemoteIntEnum[lowLevel.TextPatternRangeEndpoint] | lowLevel.TextPatternRangeEndpoint, unit: RemoteIntEnum[lowLevel.TextUnit] | lowLevel.TextUnit, - count: RemoteInt | int + count: RemoteInt | int, ) -> RemoteInt: result = RemoteInt(self.rob, self.rob.requestNewOperandId()) self.rob.getDefaultInstructionList().addInstruction( @@ -106,8 +106,8 @@ def moveEndpointByUnit( target=self, endpoint=RemoteIntEnum.ensureRemote(self.rob, endpoint), unit=RemoteIntEnum.ensureRemote(self.rob, unit), - count=RemoteInt.ensureRemote(self.rob, count) - ) + count=RemoteInt.ensureRemote(self.rob, count), + ), ) return result @@ -116,29 +116,29 @@ def moveEndpointByRange( self, srcEndpoint: RemoteIntEnum[lowLevel.TextPatternRangeEndpoint] | lowLevel.TextPatternRangeEndpoint, otherRange: RemoteTextRange, - otherEndpoint: RemoteIntEnum[lowLevel.TextPatternRangeEndpoint] | lowLevel.TextPatternRangeEndpoint + otherEndpoint: RemoteIntEnum[lowLevel.TextPatternRangeEndpoint] | lowLevel.TextPatternRangeEndpoint, ): self.rob.getDefaultInstructionList().addInstruction( instructions.TextRangeMoveEndpointByRange( target=self, srcEndpoint=RemoteIntEnum.ensureRemote(self.rob, srcEndpoint), otherRange=otherRange, - otherEndpoint=RemoteIntEnum.ensureRemote(self.rob, otherEndpoint) - ) + otherEndpoint=RemoteIntEnum.ensureRemote(self.rob, otherEndpoint), + ), ) @remoteMethod def getAttributeValue( self, - attributeId: RemoteIntEnum[lowLevel.AttributeId] | lowLevel.AttributeId + attributeId: RemoteIntEnum[lowLevel.AttributeId] | lowLevel.AttributeId, ) -> RemoteVariant: result = RemoteVariant(self.rob, self.rob.requestNewOperandId()) self.rob.getDefaultInstructionList().addInstruction( instructions.TextRangeGetAttributeValue( result=result, target=self, - attributeId=RemoteIntEnum.ensureRemote(self.rob, attributeId) - ) + attributeId=RemoteIntEnum.ensureRemote(self.rob, attributeId), + ), ) return result @@ -147,7 +147,7 @@ def compareEndpoints( self, thisEndpoint: RemoteIntEnum[lowLevel.TextPatternRangeEndpoint] | lowLevel.TextPatternRangeEndpoint, otherRange: RemoteTextRange, - otherEndpoint: RemoteIntEnum[lowLevel.TextPatternRangeEndpoint] | lowLevel.TextPatternRangeEndpoint + otherEndpoint: RemoteIntEnum[lowLevel.TextPatternRangeEndpoint] | lowLevel.TextPatternRangeEndpoint, ) -> RemoteInt: result = RemoteInt(self.rob, self.rob.requestNewOperandId()) self.rob.getDefaultInstructionList().addInstruction( @@ -156,8 +156,8 @@ def compareEndpoints( target=self, thisEndpoint=RemoteIntEnum.ensureRemote(self.rob, thisEndpoint), otherRange=otherRange, - otherEndpoint=RemoteIntEnum.ensureRemote(self.rob, otherEndpoint) - ) + otherEndpoint=RemoteIntEnum.ensureRemote(self.rob, otherEndpoint), + ), ) return result @@ -172,7 +172,7 @@ def __init__( self, rob: builder.RemoteOperationBuilder, textRangeLA: RemoteTextRangeLogicalAdapter, - isStart: bool + isStart: bool, ): super().__init__(rob) self._la = textRangeLA @@ -206,7 +206,7 @@ def moveTo(self, other: _RemoteTextRangeEndpoint): def moveByUnit( self, unit: RemoteIntEnum[lowLevel.TextUnit] | lowLevel.TextUnit, - count: RemoteInt | int + count: RemoteInt | int, ) -> RemoteInt: realCount = (count * -1) if self.isReversed else count res = self.textRange.moveEndpointByUnit(self.endpoint, unit, realCount) @@ -237,7 +237,7 @@ def __init__( self, rob: builder.RemoteOperationBuilder, textRange: RemoteTextRange, - reverse: bool = False + reverse: bool = False, ): super().__init__(rob) self._textRange = textRange diff --git a/source/UIAHandler/browseMode.py b/source/UIAHandler/browseMode.py index 351e9b23954..a147dd90932 100644 --- a/source/UIAHandler/browseMode.py +++ b/source/UIAHandler/browseMode.py @@ -150,7 +150,7 @@ def __init__( document: UIA, position: UIATextInfo, label: str | None = None, - level: int = 0 + level: int = 0, ): super(HeadingUIATextInfoQuickNavItem,self).__init__(itemType,document,position) self.level=level @@ -170,7 +170,7 @@ def UIAHeadingQuicknavIterator( itemType: str, document: "UIABrowseModeDocument", position: Optional["UIABrowseModeDocumentTextInfo"], - direction: str = "next" + direction: str = "next", ): reverse = bool(direction == "previous") itemTypeBaseLen = len('heading') @@ -449,18 +449,18 @@ def _iterNodesByType(self,nodeType,direction="next",pos=None): condition = createUIAMultiPropertyCondition( { UIAHandler.UIA.UIA_ControlTypePropertyId: UIAHandler.UIA.UIA_ListControlTypeId, - UIAHandler.UIA.UIA_IsKeyboardFocusablePropertyId: False + UIAHandler.UIA.UIA_IsKeyboardFocusablePropertyId: False, }, { UIAHandler.UIA.UIA_ControlTypePropertyId: [ UIAHandler.UIA.UIA_TableControlTypeId, - UIAHandler.UIA.UIA_DataGridControlTypeId - ] + UIAHandler.UIA.UIA_DataGridControlTypeId, + ], }, { UIAHandler.UIA_ControlTypePropertyId: UIAHandler.UIA.UIA_GroupControlTypeId, - UIAHandler.UIA_AriaRolePropertyId: ["article"] - } + UIAHandler.UIA_AriaRolePropertyId: ["article"], + }, ) return UIAControlQuicknavIterator(nodeType,self,pos,condition,direction) elif nodeType=="edit": @@ -470,11 +470,11 @@ def _iterNodesByType(self,nodeType,direction="next",pos=None): condition = createUIAMultiPropertyCondition( { UIAHandler.UIA_ControlTypePropertyId: UIAHandler.UIA_EditControlTypeId, - UIAHandler.UIA_ValueIsReadOnlyPropertyId: False + UIAHandler.UIA_ValueIsReadOnlyPropertyId: False, }, { UIAHandler.UIA_ControlTypePropertyId: UIAHandler.UIA_ListControlTypeId, - UIAHandler.UIA_IsKeyboardFocusablePropertyId: True + UIAHandler.UIA_IsKeyboardFocusablePropertyId: True, }, { UIAHandler.UIA_ControlTypePropertyId: [ @@ -483,7 +483,7 @@ def _iterNodesByType(self,nodeType,direction="next",pos=None): UIAHandler.UIA_ComboBoxControlTypeId, UIAHandler.UIA_RadioButtonControlTypeId, UIAHandler.UIA_TabItemControlTypeId, - ] + ], }, ) return UIAControlQuicknavIterator(nodeType, self, pos, condition, direction) @@ -491,39 +491,39 @@ def _iterNodesByType(self,nodeType,direction="next",pos=None): condition = UIAHandler.handler.clientObject.createNotCondition( UIAHandler.handler.clientObject.createPropertyCondition( UIAHandler.UIA.UIA_LandmarkTypePropertyId, - 0 - ) + 0, + ), ) return UIAControlQuicknavIterator(nodeType, self, pos, condition, direction) elif nodeType == "article": condition = createUIAMultiPropertyCondition({ UIAHandler.UIA_ControlTypePropertyId: UIAHandler.UIA.UIA_GroupControlTypeId, - UIAHandler.UIA_AriaRolePropertyId: ["article"] + UIAHandler.UIA_AriaRolePropertyId: ["article"], }) return UIAControlQuicknavIterator(nodeType, self, pos, condition, direction) elif nodeType == "grouping": condition = UIAHandler.handler.clientObject.CreateAndConditionFromArray([ UIAHandler.handler.clientObject.createPropertyCondition( UIAHandler.UIA.UIA_ControlTypePropertyId, - UIAHandler.UIA.UIA_GroupControlTypeId + UIAHandler.UIA.UIA_GroupControlTypeId, ), UIAHandler.handler.clientObject.createNotCondition( UIAHandler.handler.clientObject.createPropertyCondition( UIAHandler.UIA.UIA_NamePropertyId, - "" - ) - ) + "", + ), + ), ]) return UIAControlQuicknavIterator(nodeType, self, pos, condition, direction) elif nodeType == "tab": condition = UIAHandler.handler.clientObject.createPropertyCondition( - UIAHandler.UIA_ControlTypePropertyId, UIAHandler.UIA_TabItemControlTypeId + UIAHandler.UIA_ControlTypePropertyId, UIAHandler.UIA_TabItemControlTypeId, ) return UIAControlQuicknavIterator(nodeType, self, pos, condition, direction) elif nodeType == "progressBar": condition = UIAHandler.handler.clientObject.createPropertyCondition( UIAHandler.UIA_ControlTypePropertyId, - UIAHandler.UIA_ProgressBarControlTypeId + UIAHandler.UIA_ProgressBarControlTypeId, ) return UIAControlQuicknavIterator(nodeType, self, pos, condition, direction) @@ -551,13 +551,13 @@ def __contains__(self,obj): runtimeID=VARIANT() try: self.rootNVDAObject.UIAElement._IUIAutomationElement__com_GetCurrentPropertyValue( - UIAHandler.UIA_RuntimeIdPropertyId, byref(runtimeID) + UIAHandler.UIA_RuntimeIdPropertyId, byref(runtimeID), ) except COMError: runtimeID = VARIANT() if runtimeID.vt == VT_EMPTY: log.debugWarning( - "Could not get runtimeID of document. Most likely document is dead." + "Could not get runtimeID of document. Most likely document is dead.", ) return False UIACondition=UIAHandler.handler.clientObject.createPropertyCondition(UIAHandler.UIA_RuntimeIdPropertyId,runtimeID) diff --git a/source/UIAHandler/customProps.py b/source/UIAHandler/customProps.py index b8a13c1fa38..4eb4a66d4de 100644 --- a/source/UIAHandler/customProps.py +++ b/source/UIAHandler/customProps.py @@ -55,7 +55,7 @@ def _registerCustomProperty(self) -> int: return NVDAHelper.localLib.registerUIAProperty( byref(self.guid), self.programmaticName, - self.uiaType + self.uiaType, ) @property diff --git a/source/UIAHandler/remote.py b/source/UIAHandler/remote.py index bdef43ee98f..34798507c26 100644 --- a/source/UIAHandler/remote.py +++ b/source/UIAHandler/remote.py @@ -8,7 +8,7 @@ Optional, Any, Generator, - cast + cast, ) from comtypes import GUID from comInterfaces import UIAutomationClient as UIA @@ -17,14 +17,14 @@ from ._remoteOps import remoteAlgorithms from ._remoteOps.remoteTypes import ( RemoteExtensionTarget, - RemoteInt + RemoteInt, ) from ._remoteOps import operation from ._remoteOps import remoteAPI from ._remoteOps.lowLevel import ( TextUnit, AttributeId, - StyleId + StyleId, ) @@ -59,7 +59,7 @@ def terminate(): def msWord_getCustomAttributeValue( docElement: UIA.IUIAutomationElement, textRange: UIA.IUIAutomationTextRange, - customAttribID: int + customAttribID: int, ) -> Optional[Any]: guid_msWord_extendedTextRangePattern = GUID("{93514122-FF04-4B2C-A4AD-4AB04587C129}") guid_msWord_getCustomAttributeValue = GUID("{081ACA91-32F2-46F0-9FB9-017038BC45F8}") @@ -79,7 +79,7 @@ def code(ra: remoteAPI.RemoteAPI): ra.logRuntimeMessage("doing callExtension for extendedTextRangePattern") remoteDocElement.callExtension( guid_msWord_extendedTextRangePattern, - remoteResult + remoteResult, ) with ra.ifBlock(remoteResult.isNull()): ra.logRuntimeMessage("extendedTextRangePattern is null") @@ -96,7 +96,7 @@ def code(ra: remoteAPI.RemoteAPI): guid_msWord_getCustomAttributeValue, remoteTextRange, customAttribID, - remoteCustomAttribValue + remoteCustomAttribValue, ) ra.logRuntimeMessage("got customAttribValue of ", remoteCustomAttribValue) ra.Return(remoteCustomAttribValue) @@ -109,7 +109,7 @@ def code(ra: remoteAPI.RemoteAPI): def collectAllHeadingsInTextRange( - textRange: UIA.IUIAutomationTextRange + textRange: UIA.IUIAutomationTextRange, ) -> Generator[tuple[int, str, UIA.IUIAutomationElement], None, None]: op = operation.Operation() @@ -117,7 +117,7 @@ def collectAllHeadingsInTextRange( def code(ra: remoteAPI.RemoteAPI): remoteTextRange = ra.newTextRange(textRange, static=True) with remoteAlgorithms.remote_forEachUnitInTextRange( - ra, remoteTextRange, TextUnit.Paragraph + ra, remoteTextRange, TextUnit.Paragraph, ) as paragraphRange: val = paragraphRange.getAttributeValue(AttributeId.StyleId) with ra.ifBlock(val.isInt()): @@ -134,7 +134,7 @@ def code(ra: remoteAPI.RemoteAPI): def findFirstHeadingInTextRange( textRange: UIA.IUIAutomationTextRange, wantedLevel: int | None = None, - reverse: bool = False + reverse: bool = False, ) -> tuple[int, str, UIA.IUIAutomationElement] | None: op = operation.Operation() @@ -149,7 +149,7 @@ def code(ra: remoteAPI.RemoteAPI): ra.logRuntimeMessage("Doing initial move") remoteTextRange.getLogicalAdapter(reverse).start.moveByUnit(TextUnit.Paragraph, 1) with remoteAlgorithms.remote_forEachUnitInTextRange( - ra, remoteTextRange, TextUnit.Paragraph, reverse=reverse + ra, remoteTextRange, TextUnit.Paragraph, reverse=reverse, ) as paragraphRange: val = paragraphRange.getAttributeValue(AttributeId.StyleId) with ra.ifBlock(val.isInt()): @@ -168,5 +168,5 @@ def code(ra: remoteAPI.RemoteAPI): return ( cast(int, level), cast(str, label), - cast(UIA.IUIAutomationTextRange, paragraphRange) + cast(UIA.IUIAutomationTextRange, paragraphRange), ) diff --git a/source/UIAHandler/types.py b/source/UIAHandler/types.py index 26052c170a9..5fe92ce94b0 100644 --- a/source/UIAHandler/types.py +++ b/source/UIAHandler/types.py @@ -26,7 +26,7 @@ def CompareEndpoints( self, source: int, rangeObject: "IUIAutomationTextRangeT", - target: int + target: int, ) -> int: ... @@ -49,7 +49,7 @@ def MoveEndpointByRange( self, source: int, rangeObject: "IUIAutomationTextRangeT", - target: int + target: int, ) -> None: ... diff --git a/source/UIAHandler/utils.py b/source/UIAHandler/utils.py index 7255fcf4323..716abca7a76 100644 --- a/source/UIAHandler/utils.py +++ b/source/UIAHandler/utils.py @@ -206,10 +206,11 @@ def isTextRangeOffscreen(textRange, visiRanges): lastVisiRange = visiRanges.GetElement(visiLength - 1) return textRange.CompareEndPoints( UIAHandler.TextPatternRangeEndpoint_Start, firstVisiRange, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ) < 0 or textRange.CompareEndPoints( UIAHandler.TextPatternRangeEndpoint_Start, lastVisiRange, - UIAHandler.TextPatternRangeEndpoint_End) >= 0 + UIAHandler.TextPatternRangeEndpoint_End, + ) >= 0 else: # Visible textRanges not available. raise RuntimeError("Visible textRanges array is empty or invalid.") @@ -328,19 +329,19 @@ def _getConhostAPILevel(hwnd: int) -> WinConsoleAPILevel: # Therefore, if exactly one range is returned, it is almost definitely an IMPROVED console. try: UIAElement = UIAHandler.handler.clientObject.ElementFromHandleBuildCache( - hwnd, UIAHandler.handler.baseCacheRequest + hwnd, UIAHandler.handler.baseCacheRequest, ) textAreaCacheRequest = UIAHandler.handler.baseCacheRequest.clone() textAreaCacheRequest.TreeScope = UIAHandler.TreeScope_Children textAreaCacheRequest.treeFilter = UIAHandler.handler.clientObject.createPropertyCondition( UIAHandler.UIA_AutomationIdPropertyId, - "Text Area" + "Text Area", ) textArea = UIAElement.buildUpdatedCache( - textAreaCacheRequest + textAreaCacheRequest, ).getCachedChildren().GetElement(0) UIATextPattern = textArea.GetCurrentPattern( - UIAHandler.UIA_TextPatternId + UIAHandler.UIA_TextPatternId, ).QueryInterface(UIAHandler.IUIAutomationTextPattern) visiRanges = UIATextPattern.GetVisibleRanges() if visiRanges.length == 1: @@ -348,7 +349,7 @@ def _getConhostAPILevel(hwnd: int) -> WinConsoleAPILevel: # information to UIA. if isinstance( visiRanges.GetElement(0).GetAttributeValue(UIAHandler.UIA_FontNameAttributeId), - str + str, ): return WinConsoleAPILevel.FORMATTED else: @@ -383,7 +384,7 @@ def _isFrameworkIdWinForm(hwnd: int) -> bool: """ try: UIAElement = UIAHandler.handler.clientObject.ElementFromHandleBuildCache( - hwnd, UIAHandler.handler.baseCacheRequest + hwnd, UIAHandler.handler.baseCacheRequest, ) return UIAElement.cachedFrameworkID == "WinForm" except COMError: diff --git a/source/addonAPIVersion.py b/source/addonAPIVersion.py index f01f3c4b3a3..b7be2c79857 100644 --- a/source/addonAPIVersion.py +++ b/source/addonAPIVersion.py @@ -21,7 +21,7 @@ CURRENT: AddonApiVersionT = ( buildVersion.version_year, buildVersion.version_major, - buildVersion.version_minor + buildVersion.version_minor, ) BACK_COMPAT_TO: AddonApiVersionT = (2024, 1, 0) @@ -78,7 +78,7 @@ def formatForGUI(versionTuple: AddonApiVersionT) -> str: return buildVersion.formatVersionForGUI(year, major, minor) except ( ValueError, # Too few/many values to unpack - TypeError # versionTuple is None or some other incorrect type + TypeError, # versionTuple is None or some other incorrect type ): # This path should never be hit. But the appearance of "unknown" in the GUI is a better outcome # than an exception and unusable dialog. diff --git a/source/addonHandler/__init__.py b/source/addonHandler/__init__.py index 6902654b434..c1e0995f1f5 100644 --- a/source/addonHandler/__init__.py +++ b/source/addonHandler/__init__.py @@ -116,7 +116,7 @@ def setDefaultStateValues(self) -> None: def fromPickledDict( self, - pickledState: Dict[str, Union[Set[str], addonAPIVersion.AddonApiVersionT, MajorMinorPatch]] + pickledState: Dict[str, Union[Set[str], addonAPIVersion.AddonApiVersionT, MajorMinorPatch]], ) -> None: # Load from pickledState if "backCompatToAPIVersion" in pickledState: @@ -155,7 +155,7 @@ def load(self) -> None: if self.manualOverridesAPIVersion != addonAPIVersion.BACK_COMPAT_TO: log.debug( "BACK_COMPAT_TO API version for manual compatibility overrides has changed. " - f"NVDA API has been upgraded: from {self.manualOverridesAPIVersion} to {addonAPIVersion.BACK_COMPAT_TO}" + f"NVDA API has been upgraded: from {self.manualOverridesAPIVersion} to {addonAPIVersion.BACK_COMPAT_TO}", ) if self.manualOverridesAPIVersion < addonAPIVersion.BACK_COMPAT_TO: # Reset compatibility overrides as the API version has upgraded. @@ -213,8 +213,8 @@ def _cleanupCompatibleAddonsFromDowngrade(self) -> None: installedAddons = addonDataManager._installedAddonsCache.installedAddons for blockedAddon in CaseInsensitiveSet( self[AddonStateCategory.BLOCKED].union( - self[AddonStateCategory.OVERRIDE_COMPATIBILITY] - ) + self[AddonStateCategory.OVERRIDE_COMPATIBILITY], + ), ): # Iterate over copy of set to prevent updating the set while iterating over it. if blockedAddon not in installedAddons and blockedAddon not in self[AddonStateCategory.PENDING_INSTALL]: @@ -238,7 +238,7 @@ def getRunningAddons() -> "AddonHandlerModelGeneratorT": def getIncompatibleAddons( currentAPIVersion=addonAPIVersion.CURRENT, - backCompatToAPIVersion=addonAPIVersion.BACK_COMPAT_TO + backCompatToAPIVersion=addonAPIVersion.BACK_COMPAT_TO, ) -> "AddonHandlerModelGeneratorT": """ Returns a generator of the add-ons that are not compatible. """ @@ -247,7 +247,7 @@ def getIncompatibleAddons( not isAddonCompatible( addon, currentAPIVersion=currentAPIVersion, - backwardsCompatToVersion=backCompatToAPIVersion + backwardsCompatToVersion=backCompatToAPIVersion, ) and ( # Add-ons that override incompatibility are not considered incompatible. @@ -256,7 +256,7 @@ def getIncompatibleAddons( # then the add-on compatibility override will be reset or backCompatToAPIVersion > addonAPIVersion.BACK_COMPAT_TO ) - ) + ), ) @@ -295,7 +295,7 @@ def initialize(): if missingPendingInstalls := state[AddonStateCategory.PENDING_INSTALL] - _failedPendingInstalls: log.error( "The following add-ons should be installed, " - f"but are no longer present on disk: {', '.join(missingPendingInstalls)}" + f"but are no longer present on disk: {', '.join(missingPendingInstalls)}", ) state[AddonStateCategory.PENDING_INSTALL] -= missingPendingInstalls if missingPendingOverrideCompat := ( @@ -303,7 +303,7 @@ def initialize(): ): log.error( "The following add-ons which were marked as compatible are no longer installed: " - f"{', '.join(missingPendingOverrideCompat)}" + f"{', '.join(missingPendingOverrideCompat)}", ) state[AddonStateCategory.PENDING_OVERRIDE_COMPATIBILITY] -= missingPendingOverrideCompat if NVDAState.shouldWriteToDisk(): @@ -328,7 +328,7 @@ def _getDefaultAddonPaths() -> list[str]: def _getAvailableAddonsFromPath( path: str, - isFirstLoad: bool = False + isFirstLoad: bool = False, ) -> "AddonHandlerModelGeneratorT": """ Gets available add-ons from path. An addon is only considered available if the manifest file is loaded with no errors. @@ -384,8 +384,9 @@ def _getAvailableAddonsFromPath( " Requires API: {a.minimumNVDAVersion}." " Last-tested API: {a.lastTestedNVDAVersion}".format( name=name, - a=a - )) + a=a, + ), + ) if a.isDisabled: log.debug("Disabling add-on %s", name) if not ( @@ -404,7 +405,7 @@ def _getAvailableAddonsFromPath( def getAvailableAddons( refresh: bool = False, filterFunc: Optional[Callable[["Addon"], bool]] = None, - isFirstLoad: bool = False + isFirstLoad: bool = False, ) -> "AddonHandlerModelGeneratorT": """ Gets all available addons on the system. @param refresh: Whether or not to query the file system for available add-ons. @@ -640,8 +641,8 @@ def enable(self, shouldEnable: bool) -> None: self.manifest['minimumNVDAVersion'], self.manifest['lastTestedNVDAVersion'], addonAPIVersion.CURRENT, - addonAPIVersion.BACK_COMPAT_TO - ) + addonAPIVersion.BACK_COMPAT_TO, + ), ) if self.name in state[AddonStateCategory.PENDING_DISABLE]: # Undoing a pending disable. @@ -735,7 +736,7 @@ def runInstallTask( self, taskName: Literal["onInstall", "onUninstall"], *args, - **kwargs + **kwargs, ) -> None: """ Executes the function having the given taskName with the given args and kwargs, @@ -846,7 +847,7 @@ def initTranslation(): translations.gettext: "_", translations.ngettext: "ngettext", translations.pgettext: "pgettext", - translations.npgettext: "npgettext" + translations.npgettext: "npgettext", } # Point _ to the translation object in the globals namespace of the caller frame try: @@ -897,7 +898,7 @@ def __init__(self, bundlePath: str): # ZipFile.open opens every file in binary mode. # decoding is handled by configobj. z.open(MANIFEST_FILENAME, 'r'), - translatedInput=translatedInput + translatedInput=translatedInput, ) if self.manifest.errors is not None: _report_manifest_errors(self.manifest) @@ -964,8 +965,9 @@ def _report_manifest_errors(manifest): class AddonManifest(ConfigObj): """ Add-on manifest file. It contains metadata about an NVDA add-on package. """ - configspec = ConfigObj(StringIO( - """ + configspec = ConfigObj( + StringIO( + """ # NVDA Add-on Manifest configuration specification # Add-on unique name # Suggested convention is lowerCamelCase. @@ -1014,7 +1016,9 @@ class AddonManifest(ConfigObj): # "0.0.0" is also valid. # The final integer can be left out, and in that case will default to 0. E.g. 2019.1 -""")) +""", + ), + ) def __init__(self, input, translatedInput=None): """ Constructs an L{AddonManifest} instance from manifest string data @@ -1032,7 +1036,7 @@ def __init__(self, input, translatedInput=None): elif True != self._validateApiVersionRange(): # noqa: E712 self._errors = "Constraint not met: minimumNVDAVersion ({}) <= lastTestedNVDAVersion ({})".format( self.get("minimumNVDAVersion"), - self.get("lastTestedNVDAVersion") + self.get("lastTestedNVDAVersion"), ) self._translatedConfig = None if translatedInput is not None: diff --git a/source/addonHandler/addonVersionCheck.py b/source/addonHandler/addonVersionCheck.py index 649eec145bc..0ad57198d23 100644 --- a/source/addonHandler/addonVersionCheck.py +++ b/source/addonHandler/addonVersionCheck.py @@ -14,7 +14,7 @@ def hasAddonGotRequiredSupport( addon: "SupportsVersionCheck", - currentAPIVersion: addonAPIVersion.AddonApiVersionT = addonAPIVersion.CURRENT + currentAPIVersion: addonAPIVersion.AddonApiVersionT = addonAPIVersion.CURRENT, ) -> bool: """True if NVDA provides the add-on with an API version high enough to meet the add-on's minimum requirements """ @@ -24,7 +24,7 @@ def hasAddonGotRequiredSupport( def isAddonTested( addon: "SupportsVersionCheck", - backwardsCompatToVersion: addonAPIVersion.AddonApiVersionT = addonAPIVersion.BACK_COMPAT_TO + backwardsCompatToVersion: addonAPIVersion.AddonApiVersionT = addonAPIVersion.BACK_COMPAT_TO, ) -> bool: """True if this add-on is tested for the given API version. By default, the current version of NVDA is evaluated. @@ -35,7 +35,7 @@ def isAddonTested( def isAddonCompatible( addon: "SupportsVersionCheck", currentAPIVersion: addonAPIVersion.AddonApiVersionT = addonAPIVersion.CURRENT, - backwardsCompatToVersion: addonAPIVersion.AddonApiVersionT = addonAPIVersion.BACK_COMPAT_TO + backwardsCompatToVersion: addonAPIVersion.AddonApiVersionT = addonAPIVersion.BACK_COMPAT_TO, ) -> bool: """Tests if the addon is compatible. The compatibility is defined by having the required features in NVDA, and by having been tested / built against diff --git a/source/addonStore/dataManager.py b/source/addonStore/dataManager.py index 30963dd992a..74c525e47af 100644 --- a/source/addonStore/dataManager.py +++ b/source/addonStore/dataManager.py @@ -122,7 +122,7 @@ def _getLatestAddonsDataForVersion(self, apiVersion: str) -> Optional[bytes]: if response.status_code != requests.codes.OK: log.error( f"Unable to get data from API ({url})," - f" response ({response.status_code}): {response.content}" + f" response ({response.status_code}): {response.content}", ) return None return response.content @@ -138,7 +138,7 @@ def _getCacheHash(self) -> Optional[str]: if response.status_code != requests.codes.OK: log.error( f"Unable to get data from API ({url})," - f" response ({response.status_code}): {response.content}" + f" response ({response.status_code}): {response.content}", ) return None cacheHash = response.json() @@ -273,7 +273,7 @@ def getLatestAddons( displayableError = DisplayableError( # Translators: A message shown when fetching add-on data from the store fails pgettext("addonStore", "Unable to fetch latest add-on data for incompatible add-ons."), - self._updateFailureMessage + self._updateFailureMessage, ) callLater(delay=0, callable=onDisplayableError.notify, displayableError=displayableError) diff --git a/source/addonStore/install.py b/source/addonStore/install.py index f98942815bd..21e69df12d0 100644 --- a/source/addonStore/install.py +++ b/source/addonStore/install.py @@ -41,8 +41,8 @@ def _getAddonBundleToInstallIfValid(addonPath: str) -> "AddonBundle": "addonStore", # Translators: The message displayed when an error occurs when opening an add-on package for adding. # The %s will be replaced with the path to the add-on that could not be opened. - "Failed to open add-on package file at {filePath} - missing file or invalid file format" - ).format(filePath=addonPath) + "Failed to open add-on package file at {filePath} - missing file or invalid file format", + ).format(filePath=addonPath), ) if not bundle.isCompatible and not ( @@ -55,8 +55,8 @@ def _getAddonBundleToInstallIfValid(addonPath: str) -> "AddonBundle": "addonStore", # Translators: The message displayed when an add-on is not supported by this version of NVDA. # The %s will be replaced with the path to the add-on that is not supported. - "Add-on not supported %s" - ) % addonPath + "Add-on not supported %s", + ) % addonPath, ) return bundle @@ -94,8 +94,8 @@ def installAddon(addonPath: PathLike) -> None: "addonStore", # Translators: The message displayed when an error occurs when installing an add-on package. # The %s will be replaced with the path to the add-on that could not be installed. - "Failed to install add-on from %s" - ) % addonPath + "Failed to install add-on from %s", + ) % addonPath, ) finally: if addonObj is not None: diff --git a/source/addonStore/models/addon.py b/source/addonStore/models/addon.py index a1a4d6982ca..b1db320de4f 100644 --- a/source/addonStore/models/addon.py +++ b/source/addonStore/models/addon.py @@ -131,7 +131,7 @@ def tempDownloadPath(self) -> str: """ return os.path.join( WritePaths.addonStoreDownloadDir, - f"{self.name}.download" + f"{self.name}.download", ) @property @@ -143,7 +143,7 @@ def cachedDownloadPath(self) -> str: """ return os.path.join( WritePaths.addonStoreDownloadDir, - f"{self.name}-{self.addonVersionName}.nvda-addon" + f"{self.name}-{self.addonVersionName}.nvda-addon", ) @property @@ -155,7 +155,7 @@ def isPendingInstall(self) -> bool: lambda m: m[0].model.name == self.name, # add-ons which have been downloaded but # have not been installed yet - addonDataManager._downloadsPendingInstall + addonDataManager._downloadsPendingInstall, ) return ( super().isPendingInstall diff --git a/source/addonStore/models/status.py b/source/addonStore/models/status.py index 67692434fac..0b247043c3e 100644 --- a/source/addonStore/models/status.py +++ b/source/addonStore/models/status.py @@ -335,8 +335,8 @@ def getStatus(model: "_AddonGUIModel", context: _StatusFilterKey) -> AvailableAd _addonStoreStateToAddonHandlerState: OrderedDict[ AvailableAddonStatus, - Set[AddonStateCategory] - ] = OrderedDict({ + Set[AddonStateCategory], +] = OrderedDict({ # Pending states must be first as the pending state may be altering another state. AvailableAddonStatus.PENDING_INCOMPATIBLE_DISABLED: { AddonStateCategory.BLOCKED, @@ -448,14 +448,14 @@ def pendingInstallPath(self) -> str: from addonHandler import ADDON_PENDINGINSTALL_SUFFIX return os.path.join( WritePaths.addonsDir, - self.name + ADDON_PENDINGINSTALL_SUFFIX + self.name + ADDON_PENDINGINSTALL_SUFFIX, ) @property def installPath(self) -> str: return os.path.join( WritePaths.addonsDir, - self.name + self.name, ) @property diff --git a/source/addonStore/models/version.py b/source/addonStore/models/version.py index 05a61d662ef..0033ea719d5 100644 --- a/source/addonStore/models/version.py +++ b/source/addonStore/models/version.py @@ -29,7 +29,7 @@ def _parseVersionFromVersionStr(cls, version: str) -> "MajorMinorPatch": return cls( int(versionParts[0]), int(versionParts[1]), - 0 if len(versionParts) == 2 else int(versionParts[2]) + 0 if len(versionParts) == 2 else int(versionParts[2]), ) @@ -111,9 +111,9 @@ def getIncompatibleReason( # A more recent version of NVDA is required for the add-on to work. # The placeholder will be replaced with Year.Major.Minor (e.g. 2019.1). "An updated version of NVDA is required. " - "NVDA version {nvdaVersion} or later." - ).format( - nvdaVersion=addonAPIVersion.formatForGUI(self.minimumNVDAVersion) + "NVDA version {nvdaVersion} or later.", + ).format( + nvdaVersion=addonAPIVersion.formatForGUI(self.minimumNVDAVersion), ) elif not isAddonTested(self, backwardsCompatToVersion): return pgettext( @@ -124,11 +124,11 @@ def getIncompatibleReason( "An updated version of this add-on is required. " "This add-on was last tested with {lastTestedNVDAVersion}. " "NVDA requires this add-on to be tested with NVDA {nvdaVersion} or higher. " - "You can enable this add-on at your own risk. " - ).format( + "You can enable this add-on at your own risk. ", + ).format( nvdaVersion=addonAPIVersion.formatForGUI(backwardsCompatToVersion), lastTestedNVDAVersion=addonAPIVersion.formatForGUI(self.lastTestedNVDAVersion), - ) + ) else: return None @@ -141,7 +141,7 @@ def getAddonCompatibilityMessage() -> str: "Your NVDA configuration contains add-ons that are incompatible with this version of NVDA. " "These add-ons will be disabled after installation. " "After installation, you will be able to manually re-enable these add-ons at your own risk. " - "If you rely on these add-ons, please review the list to decide whether to continue with the installation. " + "If you rely on these add-ons, please review the list to decide whether to continue with the installation. ", ) @@ -151,5 +151,5 @@ def getAddonCompatibilityConfirmationMessage() -> str: # Translators: A message to confirm that the user understands that incompatible add-ons # will be disabled after installation, and can be manually re-enabled. "I understand that incompatible add-ons will be disabled " - "and can be manually re-enabled at my own risk after installation." + "and can be manually re-enabled at my own risk after installation.", ) diff --git a/source/addonStore/network.py b/source/addonStore/network.py index c12588b86d6..3652867a959 100644 --- a/source/addonStore/network.py +++ b/source/addonStore/network.py @@ -64,7 +64,7 @@ def _getCacheHashURL() -> str: class AddonFileDownloader: OnCompleteT = Callable[ ["AddonListItemVM[_AddonStoreModel]", Optional[os.PathLike]], - None + None, ] def __init__(self): @@ -74,13 +74,13 @@ def __init__(self): Tuple[ "AddonListItemVM[_AddonStoreModel]", AddonFileDownloader.OnCompleteT, - "DisplayableError.OnDisplayableErrorT" - ] + "DisplayableError.OnDisplayableErrorT", + ], ] = {} self.complete: Dict[ "AddonListItemVM[_AddonStoreModel]", # Path to downloaded file - Optional[os.PathLike] + Optional[os.PathLike], ] = {} self._executor = ThreadPoolExecutor( max_workers=10, @@ -138,7 +138,7 @@ def _done(self, downloadAddonFuture: Future[Optional[os.PathLike]]): callLater( delay=0, callable=onDisplayableError.notify, - displayableError=downloadAddonFutureException + displayableError=downloadAddonFutureException, ) else: cacheFilePath = downloadAddonFuture.result() @@ -165,7 +165,7 @@ def cancelAll(self): def _downloadAddonToPath( self, addonData: "AddonListItemVM[_AddonStoreModel]", - downloadFilePath: str + downloadFilePath: str, ) -> bool: """ @return: True if the add-on is downloaded successfully, @@ -221,7 +221,7 @@ def _download(self, listItem: "AddonListItemVM[_AddonStoreModel]") -> Optional[o pgettext( "addonStore", # Translators: A message to the user if an add-on download fails - "Unable to download add-on: {name}" + "Unable to download add-on: {name}", ).format(name=addonData.displayName), _addonDownloadFailureMessageTitle, ) @@ -231,7 +231,7 @@ def _download(self, listItem: "AddonListItemVM[_AddonStoreModel]") -> Optional[o pgettext( "addonStore", # Translators: A message to the user if an add-on download fails - "Unable to save add-on as a file: {name}" + "Unable to save add-on as a file: {name}", ).format(name=addonData.displayName), _addonDownloadFailureMessageTitle, ) @@ -242,7 +242,7 @@ def _download(self, listItem: "AddonListItemVM[_AddonStoreModel]") -> Optional[o pgettext( "addonStore", # Translators: A message to the user if an add-on download is not safe - "Add-on download not safe: checksum failed for {name}" + "Add-on download not safe: checksum failed for {name}", ).format(name=addonData.displayName), _addonDownloadFailureMessageTitle, ) diff --git a/source/api.py b/source/api.py index 88e610f9256..250a9bb482f 100644 --- a/source/api.py +++ b/source/api.py @@ -116,7 +116,7 @@ def setFocusObject(obj: NVDAObjects.NVDAObject) -> bool: # noqa: C901 "Never ending focus ancestry:" f" last object: {tempObj.name}, {controlTypes.Role(tempObj.role).displayString}," f" window class {tempObj.windowClassName if isinstance(tempObj, Window) else type(tempObj)}, " - f"application name {tempObj.appModule.appName}" + f"application name {tempObj.appModule.appName}", ) except: # noqa: E722 pass @@ -492,7 +492,7 @@ def isObjectInActiveTreeInterceptor(obj: NVDAObjects.NVDAObject) -> bool: return bool( isinstance(obj, NVDAObjects.NVDAObject) and obj.treeInterceptor - and not obj.treeInterceptor.passThrough + and not obj.treeInterceptor.passThrough, ) diff --git a/source/appModuleHandler.py b/source/appModuleHandler.py index c66c914b255..3af742e8fcd 100644 --- a/source/appModuleHandler.py +++ b/source/appModuleHandler.py @@ -74,7 +74,7 @@ class processEntry32W(ctypes.Structure): ("th32ParentProcessID",ctypes.wintypes.DWORD), ("pcPriClassBase",ctypes.c_long), ("dwFlags",ctypes.wintypes.DWORD), - ("szExeFile", ctypes.c_wchar * 260) + ("szExeFile", ctypes.c_wchar * 260), ] @@ -82,7 +82,7 @@ class _PROCESS_MACHINE_INFORMATION(ctypes.Structure): _fields_ = [ ("ProcessMachine", ctypes.wintypes.USHORT), ("Res0", ctypes.wintypes.USHORT), - ("MachineAttributes", ctypes.wintypes.DWORD) + ("MachineAttributes", ctypes.wintypes.DWORD), ] @@ -133,7 +133,7 @@ def _getPossibleAppModuleNamesForExecutable(executableName: str) -> Tuple[str, . # For new App Modules consider adding an alias to `appModule.EXECUTABLE_NAMES_TO_APP_MODS` # rather than rely on the fact that dots are replaced. executableName.replace(".", "_"), - appModules.EXECUTABLE_NAMES_TO_APP_MODS.get(executableName) + appModules.EXECUTABLE_NAMES_TO_APP_MODS.get(executableName), ) if aliasName is not None ) @@ -160,7 +160,7 @@ def _importAppModuleForExecutable(executableName: str) -> Optional[ModuleType]: if doesAppModuleExist(possibleModName): return importlib.import_module( f"appModules.{possibleModName}", - package="appModules" + package="appModules", ) return None # Module not found @@ -281,7 +281,7 @@ def fetchAppModule(processID: int, appName: str) -> AppModule: # Translators: This is presented when errors are found in an appModule # (example output: error in appModule explorer). _("Error in appModule %s") % modName, - speechPriority=speech.priorities.Spri.NOW + speechPriority=speech.priorities.Spri.NOW, ) # Use the base AppModule. @@ -296,15 +296,18 @@ def reloadAppModules(): global appModules state = [] for mod in runningTable.values(): - state.append({key: getattr(mod, key) for key in ("processID", - # #2892: We must save nvdaHelperRemote handles, as we can't reinitialize without a foreground/focus event. - # Also, if there is an active context handle such as a loaded buffer, - # nvdaHelperRemote can't reinit until that handle dies. - "helperLocalBindingHandle", "_inprocRegistrationHandle", - # #5380: We must save config profile triggers so they can be cleaned up correctly. - # Otherwise, they'll remain active forever. - "_configProfileTrigger", - ) if hasattr(mod, key)}) + state.append({ + key: getattr(mod, key) for key in ( + "processID", + # #2892: We must save nvdaHelperRemote handles, as we can't reinitialize without a foreground/focus event. + # Also, if there is an active context handle such as a loaded buffer, + # nvdaHelperRemote can't reinit until that handle dies. + "helperLocalBindingHandle", "_inprocRegistrationHandle", + # #5380: We must save config profile triggers so they can be cleaned up correctly. + # Otherwise, they'll remain active forever. + "_configProfileTrigger", + ) if hasattr(mod, key) + }) # #2892: Don't disconnect from nvdaHelperRemote during termination. mod._helperPreventDisconnect = True terminate() @@ -473,7 +476,7 @@ def _getExecutableFileInfo(self): exeFileName = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH) length = ctypes.wintypes.DWORD(ctypes.wintypes.MAX_PATH) if not ctypes.windll.Kernel32.QueryFullProcessImageNameW( - self.processHandle, 0, exeFileName, ctypes.byref(length) + self.processHandle, 0, exeFileName, ctypes.byref(length), ): raise ctypes.WinError() fileName = exeFileName.value @@ -490,7 +493,7 @@ def _getImmersivePackageInfo(self): ctypes.windll.kernel32.GetPackageFullName(self.processHandle, ctypes.byref(length), None) packageFullName = ctypes.create_unicode_buffer(length.value) if ctypes.windll.kernel32.GetPackageFullName( - self.processHandle, ctypes.byref(length), packageFullName + self.processHandle, ctypes.byref(length), packageFullName, ) == 0: return packageFullName.value else: @@ -591,8 +594,10 @@ def _get_is64BitProcess(self) -> bool: try: # We need IsWow64Process2 to detect WOW64 on ARM64. processMachine = ctypes.wintypes.USHORT() - if ctypes.windll.kernel32.IsWow64Process2(self.processHandle, - ctypes.byref(processMachine), None) == 0: + if ctypes.windll.kernel32.IsWow64Process2( + self.processHandle, + ctypes.byref(processMachine), None, + ) == 0: self.is64BitProcess = False return False # IMAGE_FILE_MACHINE_UNKNOWN if not a WOW64 process. @@ -667,7 +672,7 @@ def _get_appArchitecture(self) -> str: self.processHandle, ProcessMachineTypeInfo, ctypes.byref(processMachineInfo), - ctypes.sizeof(_PROCESS_MACHINE_INFORMATION) + ctypes.sizeof(_PROCESS_MACHINE_INFORMATION), ): self.appArchitecture = "unknown" else: @@ -725,10 +730,13 @@ def dumpOnCrash(self): """Request that this process writes a minidump when it crashes for debugging. This should only be called if instructed by a developer. """ - path = os.path.join(tempfile.gettempdir(), - "nvda_crash_%s_%d.dmp" % (self.appName, self.processID)) + path = os.path.join( + tempfile.gettempdir(), + "nvda_crash_%s_%d.dmp" % (self.appName, self.processID), + ) NVDAHelper.localLib.nvdaInProcUtils_dumpOnCrash( - self.helperLocalBindingHandle, path) + self.helperLocalBindingHandle, path, + ) print("Dump path: %s" % path) def _get_statusBar(self): @@ -809,8 +817,10 @@ def getWmiProcessInfo(processId): """ try: wmi = comtypes.client.CoGetObject(r"winmgmts:root\cimv2", dynamic=True) - results = wmi.ExecQuery("select * from Win32_Process " - "where ProcessId = %d" % processId) + results = wmi.ExecQuery( + "select * from Win32_Process " + "where ProcessId = %d" % processId, + ) for result in results: return result except: # noqa: E722 diff --git a/source/appModules/1password.py b/source/appModules/1password.py index 2b3282464c4..cd3acf774e4 100644 --- a/source/appModules/1password.py +++ b/source/appModules/1password.py @@ -14,7 +14,7 @@ def shouldProcessUIAPropertyChangedEvent(self, sender, propertyId): if propertyId in ( UIAHandler.UIA_NamePropertyId, UIAHandler.UIA_ItemStatusPropertyId, - UIAHandler.UIA_IsEnabledPropertyId + UIAHandler.UIA_IsEnabledPropertyId, ): # #10508: 1Password floods property change events, resulting in very poor # performance. Just drop them. diff --git a/source/appModules/bookshelf.py b/source/appModules/bookshelf.py index 0b66069a83c..2e291e1afe5 100644 --- a/source/appModules/bookshelf.py +++ b/source/appModules/bookshelf.py @@ -17,7 +17,8 @@ def getDocument(): try: document = NVDAObjects.IAccessible.getNVDAObjectFromEvent( windowUtils.findDescendantWindow(api.getForegroundObject().windowHandle, className="Internet Explorer_Server"), - winUser.OBJID_CLIENT, 0) + winUser.OBJID_CLIENT, 0, + ) return document except LookupError: return None diff --git a/source/appModules/calc.py b/source/appModules/calc.py index 6a470d98430..126c46250d8 100644 --- a/source/appModules/calc.py +++ b/source/appModules/calc.py @@ -16,9 +16,10 @@ class AppModule(appModuleHandler.AppModule): def chooseNVDAObjectOverlayClasses(self, obj, clsList): windowClassName=obj.windowClassName windowControlID=obj.windowControlID - if ((windowClassName=="Edit" and windowControlID==403) - or (windowClassName=="Static" and windowControlID==150) - ): + if ( + (windowClassName=="Edit" and windowControlID==403) + or (windowClassName=="Static" and windowControlID==150) + ): clsList.insert(0, Display) diff --git a/source/appModules/calculator.py b/source/appModules/calculator.py index 1676faa13a1..f4d14f58bf7 100644 --- a/source/appModules/calculator.py +++ b/source/appModules/calculator.py @@ -132,7 +132,7 @@ def event_UIA_notification(self, obj, nextHandler, displayString=None, activityI "kb:numpadEnter", "kb:escape", "kb:delete", - "kb:numpadDelete" + "kb:numpadDelete", ) @scriptHandler.script(gestures=_calculatorResultGestures) @@ -163,7 +163,7 @@ def script_calculatorResult(self, gesture): # Handle both number row and numpad with num lock on. @scriptHandler.script( gestures=[f"kb:{i}" for i in range(10)] - + [f"kb:numLockNumpad{i}" for i in range(10)] + + [f"kb:numLockNumpad{i}" for i in range(10)], ) def script_doNotAnnounceCalculatorResults(self, gesture): gesture.send() diff --git a/source/appModules/devenv.py b/source/appModules/devenv.py index 0a2f5993837..c1d45ba50ee 100644 --- a/source/appModules/devenv.py +++ b/source/appModules/devenv.py @@ -96,7 +96,7 @@ def _getLineNumberString(self, textRange): lineNumberRange.MoveEndpointByRange( UIAHandler.TextPatternRangeEndpoint_End, lineNumberRange, - UIAHandler.TextPatternRangeEndpoint_Start + UIAHandler.TextPatternRangeEndpoint_Start, ) return lineNumberRange.GetText(-1) @@ -111,7 +111,7 @@ def _getFormatFieldAtRange(self, textRange, formatConfig, ignoreMixedValues=Fals except ValueError: log.debugWarning( f"Couldn't parse {lineNumberStr} as integer to report a line number", - exc_info=True + exc_info=True, ) return formatField @@ -199,7 +199,7 @@ def _get_TextInfo(self): return VsTextEditPaneTextInfo else: log.debugWarning( - f"Retrieved Visual Studio window object, but unknown type: {self._window.Type}" + f"Retrieved Visual Studio window object, but unknown type: {self._window.Type}", ) except Exception: log.debugWarning("Couldn't retrieve Visual Studio window object", exc_info=True) @@ -214,7 +214,7 @@ def _get_location(self): self._window.Left, self._window.Top, self._window.Width, - self._window.Height + self._window.Height, ) return super().location @@ -239,5 +239,5 @@ def _get_focusRedirect(self): def _get_positionInfo(self): return { - "level": int(self.IAccessibleObject.accValue(self.IAccessibleChildID)) + "level": int(self.IAccessibleObject.accValue(self.IAccessibleChildID)), } diff --git a/source/appModules/eclipse.py b/source/appModules/eclipse.py index 811dc67f664..7bf62cecc47 100644 --- a/source/appModules/eclipse.py +++ b/source/appModules/eclipse.py @@ -43,7 +43,7 @@ def event_caret(self): pass @script( - gestures = ["kb:enter", "kb:escape"] + gestures = ["kb:enter", "kb:escape"], ) def script_closeAutocompleter(self, gesture): gesture.send() @@ -56,7 +56,7 @@ def script_closeAutocompleter(self, gesture): # Translators: Input help mode message for the 'read documentation script description=_("Tries to read documentation for the selected autocompletion item."), gesture="kb:nvda+d", - category=SCRCAT_ECLIPSE + category=SCRCAT_ECLIPSE, ) def script_readDocumentation(self, gesture): rootDocumentationWindow = None @@ -115,7 +115,7 @@ def script_readDocumentation(self, gesture): ui.message(_("Can't find the documentation window.")) @script( - gesture="kb:tab" + gesture="kb:tab", ) def script_completeInstruction(self, gesture): """ @@ -152,11 +152,13 @@ def event_selection(self): # Simply calling `reportFocus` doesn't output the text in braille # and reporting with `ui.message` needs an extra translation string when reporting position info - braille.handler.message(braille.getPropertiesBraille( - name=self.name, - role=self.role, - positionInfo=self.positionInfo - )) + braille.handler.message( + braille.getPropertiesBraille( + name=self.name, + role=self.role, + positionInfo=self.positionInfo, + ), + ) class AppModule(appModuleHandler.AppModule): LIST_VIEW_CLASS = "SysListView32" @@ -190,7 +192,7 @@ def chooseNVDAObjectOverlayClasses(self, obj, clsList): ) and obj.parent.parent.parent.parent.simpleNext.role in ( controlTypes.Role.BUTTON, - controlTypes.Role.TOGGLEBUTTON + controlTypes.Role.TOGGLEBUTTON, ) ): clsList.insert(0, AutocompletionListItem) diff --git a/source/appModules/explorer.py b/source/appModules/explorer.py index 550e1473c27..d390c1e9824 100644 --- a/source/appModules/explorer.py +++ b/source/appModules/explorer.py @@ -374,7 +374,7 @@ def _get_statusBar(self): clientObject = UIAHandler.handler.clientObject condition = clientObject.createPropertyCondition( UIAHandler.UIA_ControlTypePropertyId, - UIAHandler.UIA_StatusBarControlTypeId + UIAHandler.UIA_StatusBarControlTypeId, ) walker = clientObject.createTreeWalker(condition) try: @@ -413,20 +413,24 @@ def _getStatusBarText(obj: NVDAObject) -> str: iter( grandChild for grandChild in child.children if controlTypes.State.CHECKED in grandChild.states - ), None + ), None, ) if selected is not None: - parts.append(" ".join( - [child.name] - + ([selected.name] if selected is not None else []) - )) + parts.append( + " ".join( + [child.name] + + ([selected.name] if selected is not None else []), + ), + ) else: # Unexpected child, try to retrieve something useful. - parts.append(" ".join( - chunk - for chunk in (child.name, child.value) - if chunk and isinstance(chunk, str) and not chunk.isspace() - )) + parts.append( + " ".join( + chunk + for chunk in (child.name, child.value) + if chunk and isinstance(chunk, str) and not chunk.isspace() + ), + ) if not parts: # We couldn't retrieve anything. Resort to standard behavior. raise NotImplementedError @@ -464,7 +468,7 @@ def event_NVDAObject_init(self, obj: NVDAObject) -> None: if ( windowClass == "msctls_progress32" and winUser.getClassName( - winUser.getAncestor(obj.windowHandle, winUser.GA_PARENT) + winUser.getAncestor(obj.windowHandle, winUser.GA_PARENT), ) == "Address Band Root" ): obj.presentationType = obj.presType_layout @@ -536,7 +540,7 @@ def event_UIA_window_windowOpen(self, obj, nextHandler): # 19H2 and earlier "windowsinternal_composableshell_experiences_textinput_inputapp", # 20H1 and later - "textinputhost" + "textinputhost", ) if inputPanelWindow and inputPanelWindow.appModule.appName in inputPanelAppName: eventHandler.executeEvent("UIA_window_windowOpen", inputPanelWindow) @@ -558,7 +562,7 @@ def event_UIA_elementSelected(self, obj: NVDAObject, nextHandler: Callable[[], N name=obj.name, role=obj.role, states=obj.states, - positionInfo=obj.positionInfo - ) + positionInfo=obj.positionInfo, + ), ) nextHandler() diff --git a/source/appModules/foobar2000.py b/source/appModules/foobar2000.py index 56ceb0f8976..43f082caaae 100644 --- a/source/appModules/foobar2000.py +++ b/source/appModules/foobar2000.py @@ -83,7 +83,7 @@ def _parseTimeStrToTimeDelta(timeStr: str) -> Optional[timedelta]: try: parsedTime = datetime.strptime( timeStr, - _timeOutputToParsingFormats[outputFormat] + _timeOutputToParsingFormats[outputFormat], ) except ValueError: # Note if D > 31, strptime does not recognise that value for d. @@ -97,7 +97,7 @@ def _parseTimeStrToTimeDelta(timeStr: str) -> Optional[timedelta]: days=parsedDay, hours=parsedTime.hour, minutes=parsedTime.minute, - seconds=parsedTime.second + seconds=parsedTime.second, ) diff --git a/source/appModules/kindle.py b/source/appModules/kindle.py index 24fa4af6483..0e01e5b9b07 100644 --- a/source/appModules/kindle.py +++ b/source/appModules/kindle.py @@ -82,7 +82,7 @@ def _getTableCellAt(self,tableID,startPos,destRow,destCol): table = obj.table try: cell = table.IAccessibleTable2Object.cellAt( - destRow - 1, destCol - 1 + destRow - 1, destCol - 1, ).QueryInterface(IA2.IAccessible2) cell = IAccessible(IAccessibleObject=cell, IAccessibleChildID=0) # If the cell we fetched is marked as hidden, raise LookupError which will instruct calling code to try an adjacent cell instead. @@ -271,8 +271,10 @@ def getTextWithFields(self, formatConfig: Optional[Dict] = None) -> textInfos.Te if isinstance(item, textInfos.FieldCommand) and item.command == "formatChange": if formatConfig['reportPage']: item.field['page-number'] = self.obj.pageNumber - elif (isinstance(item, textInfos.FieldCommand) and item.command == "controlStart" - and item.field.get("mathMl")): + elif ( + isinstance(item, textInfos.FieldCommand) and item.command == "controlStart" + and item.field.get("mathMl") + ): # We have MathML, so don't report alt text (if any) as content. item.field.pop("content", None) return items @@ -285,7 +287,7 @@ def getFormatFieldSpeech( reason: Optional[OutputReason] = None, unit: Optional[str] = None, extraDetail: bool = False, - initialFormat: bool = False + initialFormat: bool = False, ) -> SpeechSequence: out: SpeechSequence = [] comment = attrs.get("kindle-user-note") @@ -322,7 +324,7 @@ def getFormatFieldSpeech( reason=reason, unit=unit, extraDetail=extraDetail, - initialFormat=initialFormat + initialFormat=initialFormat, ) out.extend(superSpeech) textInfos._logBadSequenceTypes(out) diff --git a/source/appModules/lockapp.py b/source/appModules/lockapp.py index 15fe3698f33..1ab63db7952 100644 --- a/source/appModules/lockapp.py +++ b/source/appModules/lockapp.py @@ -64,7 +64,7 @@ def chooseNVDAObjectOverlayClasses( log.debugWarning( "LockApp is being initialized but NVDA does not expect Windows to be locked. " "DynamicNVDAObjectType may have failed to apply LockScreenObject. " - "This means session lock state tracking has failed. " + "This means session lock state tracking has failed. ", ) clsList.insert(0, LockScreenObject) @@ -83,7 +83,7 @@ def _inputCaptor(self, gesture: inputCore.InputGesture) -> bool: if not scriptShouldRun: log.error( "scriptHandler failed to block script when Windows is locked. " - "This means session lock state tracking has failed. " + "This means session lock state tracking has failed. ", ) return scriptShouldRun diff --git a/source/appModules/miranda32.py b/source/appModules/miranda32.py index d5824dd3873..fdb84013504 100644 --- a/source/appModules/miranda32.py +++ b/source/appModules/miranda32.py @@ -256,9 +256,10 @@ def _get_shouldAllowIAccessibleFocusEvent(self): focus = api.getFocusObject() focusRole = focus.role focusStates = focus.states - if (self == focus or - (focusRole == controlTypes.Role.MENUITEM and controlTypes.State.FOCUSED in focusStates) or - (focusRole == controlTypes.Role.POPUPMENU and controlTypes.State.INVISIBLE not in focusStates) - ): + if ( + self == focus or + (focusRole == controlTypes.Role.MENUITEM and controlTypes.State.FOCUSED in focusStates) or + (focusRole == controlTypes.Role.POPUPMENU and controlTypes.State.INVISIBLE not in focusStates) + ): return False return super(DuplicateFocusListBox, self).shouldAllowIAccessibleFocusEvent diff --git a/source/appModules/mmc.py b/source/appModules/mmc.py index 30e30431057..a5502c1597d 100644 --- a/source/appModules/mmc.py +++ b/source/appModules/mmc.py @@ -61,7 +61,7 @@ def chooseNVDAObjectOverlayClasses(self, obj, clsList): clsList.insert(0, MMCTable) elif obj.role in ( controlTypes.Role.TABLECELL, - controlTypes.Role.TABLEROWHEADER + controlTypes.Role.TABLEROWHEADER, ): clsList.insert(0, MMCTableCell) if obj.windowClassName == "tooltips_class32" and obj.name is None: diff --git a/source/appModules/notepad.py b/source/appModules/notepad.py index f5dd89e6d8c..7d9bcdc60ef 100644 --- a/source/appModules/notepad.py +++ b/source/appModules/notepad.py @@ -37,8 +37,8 @@ def event_UIA_elementSelected(self, obj: NVDAObject, nextHandler: Callable[[], N name=obj.name, role=obj.role, states=obj.states, - positionInfo=obj.positionInfo - ) + positionInfo=obj.positionInfo, + ), ) nextHandler() diff --git a/source/appModules/nvda.py b/source/appModules/nvda.py index 89915995426..23542b81be0 100755 --- a/source/appModules/nvda.py +++ b/source/appModules/nvda.py @@ -86,7 +86,7 @@ class NvdaPythonConsoleUIOutputCtrl(ScriptableObject): gesture="kb:alt+downArrow", # Translators: Description of a command to move to the next result in the Python Console output pane description=_("Move to the next result"), - category=SCRCAT_PYTHON_CONSOLE + category=SCRCAT_PYTHON_CONSOLE, ) def script_moveToNextResult(self, gesture: "inputCore.InputGesture"): self._resultNavHelper(direction="next", select=False) @@ -96,7 +96,7 @@ def script_moveToNextResult(self, gesture: "inputCore.InputGesture"): # Translators: Description of a command to move to the previous result # in the Python Console output pane description=_("Move to the previous result"), - category=SCRCAT_PYTHON_CONSOLE + category=SCRCAT_PYTHON_CONSOLE, ) def script_moveToPrevResult(self, gesture: "inputCore.InputGesture"): self._resultNavHelper(direction="previous", select=False) @@ -106,7 +106,7 @@ def script_moveToPrevResult(self, gesture: "inputCore.InputGesture"): # Translators: Description of a command to select from the current caret position to the end # of the current result in the Python Console output pane description=_("Select until the end of the current result"), - category=SCRCAT_PYTHON_CONSOLE + category=SCRCAT_PYTHON_CONSOLE, ) def script_selectToResultEnd(self, gesture: "inputCore.InputGesture"): self._resultNavHelper(direction="next", select=True) @@ -116,7 +116,7 @@ def script_selectToResultEnd(self, gesture: "inputCore.InputGesture"): # Translators: Description of a command to select from the current caret position to the start # of the current result in the Python Console output pane description=_("Select until the start of the current result"), - category=SCRCAT_PYTHON_CONSOLE + category=SCRCAT_PYTHON_CONSOLE, ) def script_selectToResultStart(self, gesture: "inputCore.InputGesture"): self._resultNavHelper(direction="previous", select=True) diff --git a/source/appModules/outlook.py b/source/appModules/outlook.py index 7648377d556..0326c7cfa09 100644 --- a/source/appModules/outlook.py +++ b/source/appModules/outlook.py @@ -326,9 +326,10 @@ def _generateTimeRangeText(self,startTime,endTime): startText="%s %s"%(startDateText,startText) CalendarView._lastStartDate=startDate if endDate!=startDate: - if ((startTime.hour, startTime.minute, startTime.second) == (0, 0, 0) and - (endDate - startDate).total_seconds()==SECONDS_PER_DAY - ): + if ( + (startTime.hour, startTime.minute, startTime.second) == (0, 0, 0) and + (endDate - startDate).total_seconds()==SECONDS_PER_DAY + ): # Translators: a message reporting the date of a all day Outlook calendar entry return _("{date} (all day)").format(date=startDateText) endText="%s %s"%(winKernel.GetDateFormatEx(winKernel.LOCALE_NAME_USER_DEFAULT, winKernel.DATE_LONGDATE, endTime, None),endText) @@ -349,7 +350,7 @@ def _generateCategoriesText(appointment): languageHandler.LOCALE_USER_DEFAULT, languageHandler.LOCALE.SLIST, separatorBuf, - bufLength + bufLength, ) == 0: raise ctypes.WinError() categoriesCount = len(categories.split(f"{separatorBuf.value} ")) @@ -401,25 +402,25 @@ def reportFocus(self): winKernel.LOCALE_NAME_USER_DEFAULT, winKernel.DATE_LONGDATE, selectedStartTime, - None + None, ) startTime = winKernel.GetTimeFormatEx( winKernel.LOCALE_NAME_USER_DEFAULT, winKernel.TIME_NOSECONDS, selectedStartTime, - None + None, ) endDate = winKernel.GetDateFormatEx( winKernel.LOCALE_NAME_USER_DEFAULT, winKernel.DATE_LONGDATE, selectedEndTime, - None + None, ) endTime = winKernel.GetTimeFormatEx( winKernel.LOCALE_NAME_USER_DEFAULT, winKernel.TIME_NOSECONDS, selectedEndTime, - None + None, ) query = f'[Start] < "{endDate} {endTime}" And [End] > "{startDate} {startTime}"' i=e.currentFolder.items @@ -467,7 +468,7 @@ def _get_name(self): self.windowThreadID, mapiObject, PR_LAST_VERB_EXECUTED, - ctypes.byref(v) + ctypes.byref(v), ) if res==S_OK: verbLabel=executedVerbLabels.get(v.value,None) @@ -610,7 +611,7 @@ def _iterTextStyle( self, kind: str, direction: documentBase._Movement = documentBase._Movement.NEXT, - pos: textInfos.TextInfo | None = None + pos: textInfos.TextInfo | None = None, ) -> Generator[browseMode.TextInfoQuickNavItem, None, None]: raise NotImplementedError("Outlook is not supported due to performance - #16408") diff --git a/source/appModules/poedit.py b/source/appModules/poedit.py index 0d30a2e8cbe..e06559d4adf 100644 --- a/source/appModules/poedit.py +++ b/source/appModules/poedit.py @@ -112,20 +112,20 @@ def _get__sidebarControlId(self) -> int | None: def _get__isPro(self) -> bool: """Returns whether this instance of Poedit is a pro version.""" obj = self._getNVDAObjectForWindowControlIdOffsetFromDataView( - _WindowControlIdOffsetFromDataView.PRO_IDENTIFIER + _WindowControlIdOffsetFromDataView.PRO_IDENTIFIER, ) return obj is None def _getNVDAObjectForWindowControlIdOffsetFromDataView( self, - windowControlIdOffset: _WindowControlIdOffsetFromDataView + windowControlIdOffset: _WindowControlIdOffsetFromDataView, ) -> Window | None: fg = api.getForegroundObject() return _findDescendantObject(fg.windowHandle, self._dataViewControlId + windowControlIdOffset) def _getNVDAObjectForWindowControlIdOffsetFromSidebar( self, - windowControlIdOffset: _WindowControlIdOffsetFromSidebar + windowControlIdOffset: _WindowControlIdOffsetFromSidebar, ) -> Window | None: fg = api.getForegroundObject() sidebarControlId = self._sidebarControlId @@ -142,7 +142,7 @@ def _getNVDAObjectForWindowControlIdOffsetFromSidebar( def _get__translatorNotesObj(self) -> Window | None: return self._getNVDAObjectForWindowControlIdOffsetFromSidebar( - _WindowControlIdOffsetFromSidebar.TRANSLATOR_NOTES + _WindowControlIdOffsetFromSidebar.TRANSLATOR_NOTES, ) def _reportControlScriptHelper(self, obj: Window, description: str): @@ -160,14 +160,14 @@ def _reportControlScriptHelper(self, obj: Window, description: str): # to be presented to the user in Poedit. # {description} is replaced by the description of the window to be reported, # e.g. translator notes - pgettext("poedit", "No {description}").format(description=description) + pgettext("poedit", "No {description}").format(description=description), ) else: ui.message( # Translators: this message is reported when NVDA is unable to find # a requested window in Poedit. # {description} is replaced by the description of the window to be reported, e.g. translator notes - pgettext("poedit", "Could not find {description} window.").format(description=description) + pgettext("poedit", "Could not find {description} window.").format(description=description), ) @script( @@ -193,7 +193,7 @@ def script_reportAutoCommentsWindow(self, gesture): def _get__commentObj(self) -> Window | None: return self._getNVDAObjectForWindowControlIdOffsetFromSidebar( - _WindowControlIdOffsetFromSidebar.COMMENT + _WindowControlIdOffsetFromSidebar.COMMENT, ) @script( @@ -220,7 +220,7 @@ def script_reportCommentsWindow(self, gesture): def _get__oldSourceTextObj(self) -> Window | None: return self._getNVDAObjectForWindowControlIdOffsetFromSidebar( - _WindowControlIdOffsetFromSidebar.OLD_SOURCE_TEXT + _WindowControlIdOffsetFromSidebar.OLD_SOURCE_TEXT, ) @script( @@ -246,7 +246,7 @@ def script_reportOldSourceText(self, gesture): def _get__translationWarningObj(self) -> Window | None: return self._getNVDAObjectForWindowControlIdOffsetFromDataView( - _WindowControlIdOffsetFromDataView.TRANSLATION_WARNING + _WindowControlIdOffsetFromDataView.TRANSLATION_WARNING, ) @script( @@ -272,7 +272,7 @@ def script_reportTranslationWarning(self, gesture): def _get__needsWorkObj(self) -> Window | None: obj = self._getNVDAObjectForWindowControlIdOffsetFromDataView( - _WindowControlIdOffsetFromDataView.NEEDS_WORK_SWITCH + _WindowControlIdOffsetFromDataView.NEEDS_WORK_SWITCH, ) if obj and obj.role == controlTypes.Role.CHECKBOX: return obj diff --git a/source/appModules/powerpnt.py b/source/appModules/powerpnt.py index e0008af9f0e..adb7d2d4680 100644 --- a/source/appModules/powerpnt.py +++ b/source/appModules/powerpnt.py @@ -53,10 +53,14 @@ class EApplication(IDispatch): _iid_=comtypes.GUID('{914934C2-5A91-11CF-8700-00AA0060263B}') _methods_=[] _disp_methods_=[ - comtypes.DISPMETHOD([comtypes.dispid(2001)],None,"WindowSelectionChange", - (['in'],ctypes.POINTER(IDispatch),'sel'),), - comtypes.DISPMETHOD([comtypes.dispid(2013)],None,"SlideShowNextSlide", - (['in'],ctypes.POINTER(IDispatch),'slideShowWindow'),), + comtypes.DISPMETHOD( + [comtypes.dispid(2001)],None,"WindowSelectionChange", + (['in'],ctypes.POINTER(IDispatch),'sel'), + ), + comtypes.DISPMETHOD( + [comtypes.dispid(2013)],None,"SlideShowNextSlide", + (['in'],ctypes.POINTER(IDispatch),'slideShowWindow'), + ), ] #Our implementation of the EApplication COM interface to receive application events @@ -434,15 +438,17 @@ def script_selectionChange(self,gesture): self.handleSelectionChange() script_selectionChange.canPropagate=True - __gestures={k:"selectionChange" for k in ( - "kb:tab","kb:shift+tab", - "kb:leftArrow","kb:rightArrow","kb:upArrow","kb:downArrow", - "kb:shift+leftArrow","kb:shift+rightArrow","kb:shift+upArrow","kb:shift+downArrow", - "kb:pageUp","kb:pageDown", - "kb:home","kb:control+home","kb:end","kb:control+end", - "kb:shift+home","kb:shift+control+home","kb:shift+end","kb:shift+control+end", - "kb:delete","kb:backspace", - )} + __gestures={ + k:"selectionChange" for k in ( + "kb:tab","kb:shift+tab", + "kb:leftArrow","kb:rightArrow","kb:upArrow","kb:downArrow", + "kb:shift+leftArrow","kb:shift+rightArrow","kb:shift+upArrow","kb:shift+downArrow", + "kb:pageUp","kb:pageDown", + "kb:home","kb:control+home","kb:end","kb:control+end", + "kb:shift+home","kb:shift+control+home","kb:shift+end","kb:shift+control+end", + "kb:delete","kb:backspace", + ) + } class OutlinePane(EditableTextWithoutAutoSelectDetection,PaneClassDC): TextInfo=EditableTextDisplayModelTextInfo @@ -588,70 +594,86 @@ def _getOverlapText(self): if overlapsOtherLeftBy>0: total=False if otherIsBehind: - textList.append(ngettext( - # Translators: A message when a shape is in front of another shape on a PowerPoint slide - "covers left of {otherShape} by {distance:.3g} point", - "covers left of {otherShape} by {distance:.3g} points", - overlapsOtherLeftBy, - ).format(otherShape=otherLabel, distance=overlapsOtherLeftBy)) + textList.append( + ngettext( + # Translators: A message when a shape is in front of another shape on a PowerPoint slide + "covers left of {otherShape} by {distance:.3g} point", + "covers left of {otherShape} by {distance:.3g} points", + overlapsOtherLeftBy, + ).format(otherShape=otherLabel, distance=overlapsOtherLeftBy), + ) else: - textList.append(ngettext( - # Translators: A message when a shape is behind another shape on a PowerPoint slide - "behind left of {otherShape} by {distance:.3g} point", - "behind left of {otherShape} by {distance:.3g} points", - overlapsOtherLeftBy, - ).format(otherShape=otherLabel, distance=overlapsOtherLeftBy)) + textList.append( + ngettext( + # Translators: A message when a shape is behind another shape on a PowerPoint slide + "behind left of {otherShape} by {distance:.3g} point", + "behind left of {otherShape} by {distance:.3g} points", + overlapsOtherLeftBy, + ).format(otherShape=otherLabel, distance=overlapsOtherLeftBy), + ) overlapsOtherTopBy=otherInfo['overlapsOtherTopBy'] if overlapsOtherTopBy>0: total=False if otherIsBehind: - textList.append(ngettext( - # Translators: A message when a shape is in front of another shape on a PowerPoint slide - "covers top of {otherShape} by {distance:.3g} point", - "covers top of {otherShape} by {distance:.3g} points", - overlapsOtherTopBy, - ).format(otherShape=otherLabel, distance=overlapsOtherTopBy)) + textList.append( + ngettext( + # Translators: A message when a shape is in front of another shape on a PowerPoint slide + "covers top of {otherShape} by {distance:.3g} point", + "covers top of {otherShape} by {distance:.3g} points", + overlapsOtherTopBy, + ).format(otherShape=otherLabel, distance=overlapsOtherTopBy), + ) else: - textList.append(ngettext( - # Translators: A message when a shape is behind another shape on a PowerPoint slide - "behind top of {otherShape} by {distance:.3g} point", - "behind top of {otherShape} by {distance:.3g} points", - overlapsOtherTopBy, - ).format(otherShape=otherLabel, distance=overlapsOtherTopBy)) + textList.append( + ngettext( + # Translators: A message when a shape is behind another shape on a PowerPoint slide + "behind top of {otherShape} by {distance:.3g} point", + "behind top of {otherShape} by {distance:.3g} points", + overlapsOtherTopBy, + ).format(otherShape=otherLabel, distance=overlapsOtherTopBy), + ) overlapsOtherRightBy=otherInfo['overlapsOtherRightBy'] if overlapsOtherRightBy>0: total=False if otherIsBehind: - textList.append(ngettext( - # Translators: A message when a shape is in front of another shape on a PowerPoint slide - "covers right of {otherShape} by {distance:.3g} point", - "covers right of {otherShape} by {distance:.3g} points", - overlapsOtherRightBy, - ).format(otherShape=otherLabel, distance=overlapsOtherRightBy)) + textList.append( + ngettext( + # Translators: A message when a shape is in front of another shape on a PowerPoint slide + "covers right of {otherShape} by {distance:.3g} point", + "covers right of {otherShape} by {distance:.3g} points", + overlapsOtherRightBy, + ).format(otherShape=otherLabel, distance=overlapsOtherRightBy), + ) else: - textList.append(ngettext( - # Translators: A message when a shape is behind another shape on a PowerPoint slide - "behind right of {otherShape} by {distance:.3g} point", - "behind right of {otherShape} by {distance:.3g} points", - overlapsOtherRightBy, - ).format(otherShape=otherLabel, distance=overlapsOtherRightBy)) + textList.append( + ngettext( + # Translators: A message when a shape is behind another shape on a PowerPoint slide + "behind right of {otherShape} by {distance:.3g} point", + "behind right of {otherShape} by {distance:.3g} points", + overlapsOtherRightBy, + ).format(otherShape=otherLabel, distance=overlapsOtherRightBy), + ) overlapsOtherBottomBy=otherInfo['overlapsOtherBottomBy'] if overlapsOtherBottomBy>0: total=False if otherIsBehind: - textList.append(ngettext( - # Translators: A message when a shape is in front of another shape on a PowerPoint slide - "covers bottom of {otherShape} by {distance:.3g} point", - "covers bottom of {otherShape} by {distance:.3g} points", - overlapsOtherBottomBy, - ).format(otherShape=otherLabel, distance=overlapsOtherBottomBy)) + textList.append( + ngettext( + # Translators: A message when a shape is in front of another shape on a PowerPoint slide + "covers bottom of {otherShape} by {distance:.3g} point", + "covers bottom of {otherShape} by {distance:.3g} points", + overlapsOtherBottomBy, + ).format(otherShape=otherLabel, distance=overlapsOtherBottomBy), + ) else: - textList.append(ngettext( - # Translators: A message when a shape is behind another shape on a PowerPoint slide - "behind bottom of {otherShape} by {distance:.3g} point", - "behind bottom of {otherShape} by {distance:.3g} points", - overlapsOtherBottomBy, - ).format(otherShape=otherLabel, distance=overlapsOtherBottomBy)) + textList.append( + ngettext( + # Translators: A message when a shape is behind another shape on a PowerPoint slide + "behind bottom of {otherShape} by {distance:.3g} point", + "behind bottom of {otherShape} by {distance:.3g} points", + overlapsOtherBottomBy, + ).format(otherShape=otherLabel, distance=overlapsOtherBottomBy), + ) if total: if otherIsBehind: # Translators: A message when a shape is in front of another shape on a PowerPoint slide @@ -677,72 +699,88 @@ def _getShapeLocationText(self,left=False,top=False,right=False,bottom=False): onSlideList=[] if left: if leftDistance>=0: - onSlideList.append(ngettext( - # Translators: For a shape within a PowerPoint Slide, this is the distance in points from the shape's - # left edge to the slide's left edge - "{distance:.3g} point from left slide edge", - "{distance:.3g} points from left slide edge", - leftDistance, - ).format(distance=leftDistance)) + onSlideList.append( + ngettext( + # Translators: For a shape within a PowerPoint Slide, this is the distance in points from the shape's + # left edge to the slide's left edge + "{distance:.3g} point from left slide edge", + "{distance:.3g} points from left slide edge", + leftDistance, + ).format(distance=leftDistance), + ) else: - offSlideList.append(ngettext( - # Translators: For a shape too far off the left edge of a PowerPoint Slide, this is the distance in - # points from the shape's left edge (off the slide) to the slide's left edge (where the slide starts) - "Off left slide edge by {distance:.3g} point", - "Off left slide edge by {distance:.3g} points", - -leftDistance, - ).format(distance=-leftDistance)) + offSlideList.append( + ngettext( + # Translators: For a shape too far off the left edge of a PowerPoint Slide, this is the distance in + # points from the shape's left edge (off the slide) to the slide's left edge (where the slide starts) + "Off left slide edge by {distance:.3g} point", + "Off left slide edge by {distance:.3g} points", + -leftDistance, + ).format(distance=-leftDistance), + ) if top: if topDistance>=0: - onSlideList.append(ngettext( - # Translators: For a shape within a PowerPoint Slide, this is the distance in points from the shape's - # top edge to the slide's top edge - "{distance:.3g} point from top slide edge", - "{distance:.3g} points from top slide edge", - topDistance, - ).format(distance=topDistance)) + onSlideList.append( + ngettext( + # Translators: For a shape within a PowerPoint Slide, this is the distance in points from the shape's + # top edge to the slide's top edge + "{distance:.3g} point from top slide edge", + "{distance:.3g} points from top slide edge", + topDistance, + ).format(distance=topDistance), + ) else: - offSlideList.append(ngettext( - # Translators: For a shape too far off the top edge of a PowerPoint Slide, this is the distance in - # points from the shape's top edge (off the slide) to the slide's top edge (where the slide starts) - "Off top slide edge by {distance:.3g} point", - "Off top slide edge by {distance:.3g} points", - -topDistance, - ).format(distance=-topDistance)) + offSlideList.append( + ngettext( + # Translators: For a shape too far off the top edge of a PowerPoint Slide, this is the distance in + # points from the shape's top edge (off the slide) to the slide's top edge (where the slide starts) + "Off top slide edge by {distance:.3g} point", + "Off top slide edge by {distance:.3g} points", + -topDistance, + ).format(distance=-topDistance), + ) if right: if rightDistance>=0: - onSlideList.append(ngettext( - # Translators: For a shape within a PowerPoint Slide, this is the distance in points from the shape's - # right edge to the slide's right edge - "{distance:.3g} point from right slide edge", - "{distance:.3g} points from right slide edge", - rightDistance, - ).format(distance=rightDistance)) + onSlideList.append( + ngettext( + # Translators: For a shape within a PowerPoint Slide, this is the distance in points from the shape's + # right edge to the slide's right edge + "{distance:.3g} point from right slide edge", + "{distance:.3g} points from right slide edge", + rightDistance, + ).format(distance=rightDistance), + ) else: - offSlideList.append(ngettext( - # Translators: For a shape too far off the right edge of a PowerPoint Slide, this is the distance in - # points from the shape's right edge (off the slide) to the slide's right edge (where the slide starts) - "Off right slide edge by {distance:.3g} point", - "Off right slide edge by {distance:.3g} points", - -rightDistance, - ).format(distance=-rightDistance)) + offSlideList.append( + ngettext( + # Translators: For a shape too far off the right edge of a PowerPoint Slide, this is the distance in + # points from the shape's right edge (off the slide) to the slide's right edge (where the slide starts) + "Off right slide edge by {distance:.3g} point", + "Off right slide edge by {distance:.3g} points", + -rightDistance, + ).format(distance=-rightDistance), + ) if bottom: if bottomDistance>=0: - onSlideList.append(ngettext( - # Translators: For a shape within a PowerPoint Slide, this is the distance in points from the shape's - # bottom edge to the slide's bottom edge - "{distance:.3g} point from bottom slide edge", - "{distance:.3g} points from bottom slide edge", - bottomDistance, - ).format(distance=bottomDistance)) + onSlideList.append( + ngettext( + # Translators: For a shape within a PowerPoint Slide, this is the distance in points from the shape's + # bottom edge to the slide's bottom edge + "{distance:.3g} point from bottom slide edge", + "{distance:.3g} points from bottom slide edge", + bottomDistance, + ).format(distance=bottomDistance), + ) else: - offSlideList.append(ngettext( - # Translators: For a shape too far off the bottom edge of a PowerPoint Slide, this is the distance in - # points from the shape's bottom edge (off the slide) to the slide's bottom edge (where the slide starts) - "Off bottom slide edge by {distance:.3g} point", - "Off bottom slide edge by {distance:.3g} points", - -bottomDistance - ).format(distance=-bottomDistance)) + offSlideList.append( + ngettext( + # Translators: For a shape too far off the bottom edge of a PowerPoint Slide, this is the distance in + # points from the shape's bottom edge (off the slide) to the slide's bottom edge (where the slide starts) + "Off bottom slide edge by {distance:.3g} point", + "Off bottom slide edge by {distance:.3g} points", + -bottomDistance, + ).format(distance=-bottomDistance), + ) return ", ".join(offSlideList+onSlideList) def _get_locationText(self): @@ -924,7 +962,7 @@ def _get_name(self): role=controlTypes.Role.CHART def _get_chart(self): - return OfficeChart(windowHandle=self.windowHandle , officeApplicationObject = self.ppObject.Application , officeChartObject = self.ppObject.chart, initialDocument=self ) + return OfficeChart(windowHandle=self.windowHandle , officeApplicationObject = self.ppObject.Application , officeChartObject = self.ppObject.chart, initialDocument=self) def focusOnActiveDocument(self,chart): self.ppObject.select() @@ -1123,7 +1161,8 @@ def getTextWithFields(self, formatConfig: Optional[Dict] = None) -> textInfos.Te out.extend(( # Copy the field so the original isn't modified. textInfos.FieldCommand("controlStart", textInfos.ControlField(field)), - u" ", textInfos.FieldCommand("controlEnd", None))) + u" ", textInfos.FieldCommand("controlEnd", None), + )) textOffset = fieldOffset + 1 # Output any text after all fields in this range. chunk = text[textOffset:self._endOffset] @@ -1184,7 +1223,7 @@ def reportNewSlide(self): description=_( # Translators: The description for a script "Toggles between reporting the speaker notes or the actual slide content. This does not change" - " what is visible on-screen, but only what the user can read with NVDA" + " what is visible on-screen, but only what the user can read with NVDA", ), category=SCRCAT_POWERPOINT, ) @@ -1257,8 +1296,10 @@ def _getShapeText(self,shape,cellShape=False): if shapeType==msoEmbeddedOLEObject: oleFormat=shape.OLEFormat if oleFormat.ProgID.startswith(MATHTYPE_PROGID): - yield textInfos.ControlField(role=controlTypes.Role.MATH, - oleFormat=oleFormat, _startOfNode=True) + yield textInfos.ControlField( + role=controlTypes.Role.MATH, + oleFormat=oleFormat, _startOfNode=True, + ) return label=shape.alternativeText if not label: diff --git a/source/appModules/soffice.py b/source/appModules/soffice.py index 6ce27cfbd0d..88e9eec058b 100755 --- a/source/appModules/soffice.py +++ b/source/appModules/soffice.py @@ -5,7 +5,7 @@ from typing import ( Optional, - Union + Union, ) from comtypes import COMError @@ -41,7 +41,7 @@ class SymphonyTextInfo(IA2TextTextInfo): def _getFormatFieldFromLegacyAttributesString( # noqa: C901 self, attribsString: str, - offset: int + offset: int, ) -> textInfos.FormatField: """Get format field with information retrieved from a text @@ -124,7 +124,7 @@ def _getFormatFieldAndOffsetsFromAttributes( self, offset: int, formatConfig: Optional[dict], - calculateOffsets: bool + calculateOffsets: bool, ) -> tuple[textInfos.FormatField, tuple[int, int]]: """Get format field and offset information from either attributes according to the IAccessible2 specification @@ -155,13 +155,13 @@ def _getFormatFieldAndOffsetsFromAttributes( if attribsString and attribsString.startswith('Version:1;'): formatField = self._getFormatFieldFromLegacyAttributesString( attribsString, - offset + offset, ) else: formatField, (startOffset, endOffset) = super()._getFormatFieldAndOffsets( offset, formatConfig, - calculateOffsets + calculateOffsets, ) return formatField, (startOffset, endOffset) @@ -170,19 +170,19 @@ def _getFormatFieldAndOffsets( self, offset: int, formatConfig: Optional[dict], - calculateOffsets: bool = True + calculateOffsets: bool = True, ) -> tuple[textInfos.FormatField, tuple[int, int]]: formatField, (startOffset, endOffset) = self._getFormatFieldAndOffsetsFromAttributes( offset, formatConfig, - calculateOffsets + calculateOffsets, ) obj = self.obj # optimisation: Assume a hyperlink occupies a full attribute run. try: if obj.IAccessibleTextObject.QueryInterface( - IA2.IAccessibleHypertext + IA2.IAccessibleHypertext, ).hyperlinkIndex(offset) != -1: formatField["link"] = True except COMError: @@ -291,7 +291,7 @@ def announceSelectionChange(self): self, states=True, cellCoordsText=True, - reason=controlTypes.OutputReason.CHANGE + reason=controlTypes.OutputReason.CHANGE, ) braille.handler.handleUpdate(self) vision.handler.handleUpdate(self, property="states") @@ -327,12 +327,12 @@ def _get_cellCoordsText(self): firstAddress=firstAddress, firstValue=firstValue, lastAddress=lastAddress, - lastValue=lastValue + lastValue=lastValue, ) elif self.rowSpan > 1 or self.columnSpan > 1: lastSelected = ( (self.rowNumber - 1) + (self.rowSpan - 1), - (self.columnNumber - 1) + (self.columnSpan - 1) + (self.columnNumber - 1) + (self.columnSpan - 1), ) lastCellUnknown = self.table.IAccessibleTable2Object.cellAt(*lastSelected) lastAccessible = lastCellUnknown.QueryInterface(IA2.IAccessible2) @@ -340,7 +340,7 @@ def _get_cellCoordsText(self): # Translators: LibreOffice, report range of cell coordinates return _("{firstAddress} through {lastAddress}").format( firstAddress=self._get_name(), - lastAddress=lastAddress + lastAddress=lastAddress, ) return super().cellCoordsText @@ -427,7 +427,7 @@ def _get_locationText(self): verticalDistanceText = getDistanceTextForTwips(verticalPos) return _( # Translators: LibreOffice, report cursor position in the current page - "cursor positioned {horizontalDistance} from left edge of page, {verticalDistance} from top edge of page" + "cursor positioned {horizontalDistance} from left edge of page, {verticalDistance} from top edge of page", ).format(horizontalDistance=horizontalDistanceText, verticalDistance=verticalDistanceText) except (AttributeError, KeyError): return super(SymphonyDocumentTextInfo, self)._get_locationText() @@ -495,7 +495,7 @@ def _backspaceScriptHelper(self, unit: str, gesture: inputCore.InputGesture): "kb:control+r", # justified "kb:control+j", - ] + ], ) def script_toggleTextAttribute(self, gesture: inputCore.InputGesture): """Reset time and enable announcement of toggled toolbar buttons. @@ -548,7 +548,7 @@ def searchStatusBar(self, obj: NVDAObject, max_depth: int = 5) -> Optional[NVDAO controlTypes.Role.FRAME, controlTypes.Role.OPTIONPANE, controlTypes.Role.ROOTPANE, - controlTypes.Role.WINDOW + controlTypes.Role.WINDOW, }: return None for child in obj.children: diff --git a/source/appModules/systemsettings.py b/source/appModules/systemsettings.py index f273eb172e0..40acb724d54 100644 --- a/source/appModules/systemsettings.py +++ b/source/appModules/systemsettings.py @@ -20,10 +20,10 @@ def chooseNVDAObjectOverlayClasses(self, obj, clsList): try: if ( obj.next.UIAAutomationId.startswith( - "SystemSettings_Audio_Output_VolumeValue_" + "SystemSettings_Audio_Output_VolumeValue_", ) or obj.simplePrevious.UIAAutomationId.startswith( - "SystemSettings_Audio_Input_VolumeValue_" + "SystemSettings_Audio_Input_VolumeValue_", ) ): try: diff --git a/source/appModules/tween.py b/source/appModules/tween.py index f7b3255b78f..edfaaa7c690 100644 --- a/source/appModules/tween.py +++ b/source/appModules/tween.py @@ -46,7 +46,7 @@ def _getColumnContentRaw(self, index: int) -> Optional[str]: left, top, width, height = self._getColumnLocationRaw(index) content = displayModel.DisplayModelTextInfo( self, - locationHelper.RectLTRB(left, top, left + width, top + height) + locationHelper.RectLTRB(left, top, left + width, top + height), ).text if content: return content diff --git a/source/appModules/utorrent.py b/source/appModules/utorrent.py index 5bb8f10c97a..9d97afcec26 100644 --- a/source/appModules/utorrent.py +++ b/source/appModules/utorrent.py @@ -27,10 +27,11 @@ def _get_shouldAllowIAccessibleFocusEvent(self): focus = api.getFocusObject() focusRole = focus.role focusStates = focus.states - if (self == focus or - (focusRole == controlTypes.Role.MENUITEM and controlTypes.State.FOCUSED in focusStates) or - (focusRole == controlTypes.Role.POPUPMENU and controlTypes.State.INVISIBLE not in focusStates) - ): + if ( + self == focus or + (focusRole == controlTypes.Role.MENUITEM and controlTypes.State.FOCUSED in focusStates) or + (focusRole == controlTypes.Role.POPUPMENU and controlTypes.State.INVISIBLE not in focusStates) + ): return False return super(DuplicateFocusListView, self).shouldAllowIAccessibleFocusEvent @@ -46,8 +47,11 @@ def _getColumnContent(self, column): # We need to use the display model to retrieve the Name column. try: left, top, width, height = self._getColumnLocation(column) - return displayModel.DisplayModelTextInfo(self, locationHelper.RectLTRB( - left, top, left + width, top + height)).text + return displayModel.DisplayModelTextInfo( + self, locationHelper.RectLTRB( + left, top, left + width, top + height, + ), + ).text except: # noqa: E722 log.debugWarning("Error retrieving name using display model", exc_info=True) return superContent diff --git a/source/appModules/windowsinternal_composableshell_experiences_textinput_inputapp.py b/source/appModules/windowsinternal_composableshell_experiences_textinput_inputapp.py index bd194af8131..0ae839166c4 100644 --- a/source/appModules/windowsinternal_composableshell_experiences_textinput_inputapp.py +++ b/source/appModules/windowsinternal_composableshell_experiences_textinput_inputapp.py @@ -177,8 +177,8 @@ def event_UIA_elementSelected(self, obj, nextHandler): if isinstance( obj, ( ImeCandidateItem, # IME candidate items - NavigationMenuItem # Windows 11 emoji panel navigation menu items - ) + NavigationMenuItem, # Windows 11 emoji panel navigation menu items + ), ): return nextHandler() # #7273: When this is fired on categories, @@ -216,11 +216,13 @@ def event_UIA_elementSelected(self, obj, nextHandler): obj = candidate.firstChild if obj is not None and api.setNavigatorObject(obj): obj.reportFocus() - braille.handler.message(braille.getPropertiesBraille( - name=obj.name, - role=obj.role, - positionInfo=obj.positionInfo - )) + braille.handler.message( + braille.getPropertiesBraille( + name=obj.name, + role=obj.role, + positionInfo=obj.positionInfo, + ), + ) # Cache selected item. self._recentlySelected = obj.name else: @@ -232,7 +234,7 @@ def event_UIA_elementSelected(self, obj, nextHandler): # Emoji panel for build 16299 and 17134. _classicEmojiPanelAutomationIds = ( "TEMPLATE_PART_ExpressiveInputFullViewFuntionBarItemControl", - "TEMPLATE_PART_ExpressiveInputFullViewFuntionBarCloseButton" + "TEMPLATE_PART_ExpressiveInputFullViewFuntionBarCloseButton", ) def event_UIA_window_windowOpen(self, obj, nextHandler): @@ -320,10 +322,12 @@ def event_nameChange(self, obj, nextHandler): (obj.UIAElement.cachedClassName in ("CRootKey", "GridViewItem")) # Just ignore useless clipboard status. # Also top emoji search result must be announced for better user experience. - or (obj.UIAAutomationId in ( - "TEMPLATE_PART_ClipboardItemsList", - "TEMPLATE_PART_Search_TextBlock" - )) + or ( + obj.UIAAutomationId in ( + "TEMPLATE_PART_ClipboardItemsList", + "TEMPLATE_PART_Search_TextBlock", + ) + ) # And no, emoji entries should not be announced here. or (self._recentlySelected is not None and self._recentlySelected in obj.name) ): @@ -352,7 +356,7 @@ def event_nameChange(self, obj, nextHandler): obj.UIAAutomationId not in ( "TEMPLATE_PART_ExpressionFullViewItemsGrid", "TEMPLATE_PART_ClipboardItemIndex", - "CandidateWindowControl" + "CandidateWindowControl", ) ): ui.message(obj.name) @@ -364,7 +368,7 @@ def event_UIA_notification( nextHandler: Callable[[], None], displayString: str | None = None, activityId: str | None = None, - **kwargs + **kwargs, ): # #16009: Windows 11 modern keyboard uses UIA notification event to announce things. # These include voice typing availability message and appearance of Suggested Actions diff --git a/source/appModules/winword.py b/source/appModules/winword.py index 2e26fbffe0d..e33bfb07ce9 100644 --- a/source/appModules/winword.py +++ b/source/appModules/winword.py @@ -34,7 +34,7 @@ def script_toggleChangeTracking(self, gesture): return gesture.send() val = self._WaitForValueChangeForAction( lambda: gesture.send(), - lambda: self.WinwordDocumentObject.TrackRevisions + lambda: self.WinwordDocumentObject.TrackRevisions, ) if val: # Translators: a message when toggling change tracking in Microsoft word diff --git a/source/appModules/wwahost.py b/source/appModules/wwahost.py index 4232d34f77e..4ad6eca4564 100644 --- a/source/appModules/wwahost.py +++ b/source/appModules/wwahost.py @@ -18,7 +18,7 @@ def getAppNameFromHost(processId): # Some apps that come with Windows 8 and 8.1 are hosted by wwahost.exe. # App modules for these are named after the hosted app name. processHandle = winKernel.openProcess( - winKernel.SYNCHRONIZE | winKernel.PROCESS_QUERY_INFORMATION, False, processId + winKernel.SYNCHRONIZE | winKernel.PROCESS_QUERY_INFORMATION, False, processId, ) length = ctypes.c_uint() winKernel.kernel32.GetApplicationUserModelId(processHandle, ctypes.byref(length), None) diff --git a/source/audio/soundSplit.py b/source/audio/soundSplit.py index d20e0667a6c..3267f9a39cf 100644 --- a/source/audio/soundSplit.py +++ b/source/audio/soundSplit.py @@ -211,7 +211,7 @@ def _toggleSoundSplitState() -> None: message = _( # Translators: error message when wasapi is turned off. "Sound split cannot be used. " - "Please enable WASAPI in the Advanced category in NVDA Settings to use it." + "Please enable WASAPI in the Advanced category in NVDA Settings to use it.", ) ui.message(message) return @@ -232,7 +232,7 @@ def _toggleSoundSplitState() -> None: # Translators: warning message when sound split trigger wasn't successful due to one of audio sessions # had number of channels other than 2 . "Warning: couldn't set volumes for sound split: " - "one of audio sessions is either mono, or has more than 2 audio channels." + "one of audio sessions is either mono, or has more than 2 audio channels.", ) ui.message(msg) @@ -254,7 +254,7 @@ def restoreVolume(self): channelCount = channelVolume.GetChannelCount() if channelCount != 2: log.warning( - f"Audio session for pid {self.pid} has {channelCount} channels instead of 2 - cannot set volume!" + f"Audio session for pid {self.pid} has {channelCount} channels instead of 2 - cannot set volume!", ) return channelVolume.SetChannelVolume(0, 1.0, None) diff --git a/source/audioDucking.py b/source/audioDucking.py index 4448d3c66db..10408de238c 100644 --- a/source/audioDucking.py +++ b/source/audioDucking.py @@ -76,14 +76,14 @@ def _setDuckingState(switch): oledll.oleacc.AccSetRunningUtilityState( ATWindow, ANRUSDucking.AUDIO_ACTIVE | ANRUSDucking.AUDIO_ACTIVE_NODUCK, - ANRUSDucking.AUDIO_ACTIVE | ANRUSDucking.AUDIO_ACTIVE_NODUCK + ANRUSDucking.AUDIO_ACTIVE | ANRUSDucking.AUDIO_ACTIVE_NODUCK, ) _lastDuckedTime=time.time() else: oledll.oleacc.AccSetRunningUtilityState( ATWindow, ANRUSDucking.AUDIO_ACTIVE | ANRUSDucking.AUDIO_ACTIVE_NODUCK, - ANRUSDucking.AUDIO_ACTIVE_NODUCK + ANRUSDucking.AUDIO_ACTIVE_NODUCK, ) except WindowsError as e: # When the NVDA build is not signed, audio ducking fails with access denied. @@ -99,7 +99,7 @@ def _setDuckingState(switch): # we want developers to hear the "error sound", and to halt, so still raise the exception. log.error( "Unknown error when setting ducking state: Error number: {:#010X}".format(errorCode), - exc_info=True + exc_info=True, ) raise e diff --git a/source/autoSettingsUtils/autoSettings.py b/source/autoSettingsUtils/autoSettings.py index 000e91071e2..68ab5eb778a 100644 --- a/source/autoSettingsUtils/autoSettings.py +++ b/source/autoSettingsUtils/autoSettings.py @@ -79,7 +79,7 @@ def _getConfigSection(cls) -> str: def _initSpecificSettings( cls, clsOrInst: Any, - settings: SupportedSettingType + settings: SupportedSettingType, ) -> None: section = cls._getConfigSection() settingsId = cls.getId() @@ -89,7 +89,7 @@ def _initSpecificSettings( config.conf[section][settingsId] = {} # Make sure the config spec is up to date, so the config validator does its work. config.conf[section][settingsId].spec.update( - cls._getConfigSpecForSettings(settings) + cls._getConfigSpecForSettings(settings), ) # Make sure the clsOrInst has attributes for every setting for setting in settings: @@ -128,7 +128,7 @@ def isSupported(self, settingID) -> bool: @classmethod def _getConfigSpecForSettings( cls, - settings: SupportedSettingType + settings: SupportedSettingType, ) -> Dict: section = cls._getConfigSection() spec = deepcopy(config.confspec[section]["__many__"]) @@ -145,7 +145,7 @@ def getConfigSpec(self): def _saveSpecificSettings( cls, clsOrInst: Any, - settings: SupportedSettingType + settings: SupportedSettingType, ) -> None: """ Save values for settings to config. @@ -164,7 +164,7 @@ def _saveSpecificSettings( except UnsupportedConfigParameterError: log.debugWarning( f"Unsupported setting {setting.id!r}; ignoring", - exc_info=True + exc_info=True, ) continue if settings: @@ -183,7 +183,7 @@ def _loadSpecificSettings( cls, clsOrInst: Any, settings: SupportedSettingType, - onlyChanged: bool = False + onlyChanged: bool = False, ) -> None: """ Load settings from config, set them on `clsOrInst`. @@ -208,14 +208,14 @@ def _loadSpecificSettings( except UnsupportedConfigParameterError: log.debugWarning( f"Unsupported setting {setting.id!r}; ignoring", - exc_info=True + exc_info=True, ) continue if settings: log.debug( f"Loaded changed settings for {cls.__qualname__}" if onlyChanged else - f"Loaded settings for {cls.__qualname__}" + f"Loaded settings for {cls.__qualname__}", ) def loadSettings(self, onlyChanged: bool = False): diff --git a/source/autoSettingsUtils/driverSetting.py b/source/autoSettingsUtils/driverSetting.py index 8a3cc9dbbcf..d8815c87b1b 100644 --- a/source/autoSettingsUtils/driverSetting.py +++ b/source/autoSettingsUtils/driverSetting.py @@ -44,7 +44,7 @@ def __init__( availableInSettingsRing: bool = False, defaultVal: object = None, displayName: Optional[str] = None, - useConfig: bool = True + useConfig: bool = True, ): """ @param id: internal identifier of the setting @@ -76,7 +76,8 @@ class NumericDriverSetting(DriverSetting): def _get_configSpec(self): return "integer(default={defaultVal},min={minVal},max={maxVal})".format( - defaultVal=self.defaultVal, minVal=self.minVal, maxVal=self.maxVal) + defaultVal=self.defaultVal, minVal=self.minVal, maxVal=self.maxVal, + ) def __init__( self, @@ -90,7 +91,8 @@ def __init__( normalStep: int = 5, largeStep: int = 10, displayName: Optional[str] = None, - useConfig: bool = True): + useConfig: bool = True, + ): """ @param defaultVal: Specifies the default value for a numeric driver setting. @param minVal: Specifies the minimum valid value for a numeric driver setting. @@ -109,7 +111,7 @@ def __init__( availableInSettingsRing=availableInSettingsRing, defaultVal=defaultVal, displayName=displayName, - useConfig=useConfig + useConfig=useConfig, ) self.minVal = minVal self.maxVal = max(maxVal, self.defaultVal) @@ -131,7 +133,7 @@ def __init__( availableInSettingsRing: bool = False, displayName: Optional[str] = None, defaultVal: bool = False, - useConfig: bool = True + useConfig: bool = True, ): """ @param defaultVal: Specifies the default value for a boolean driver setting. @@ -142,7 +144,7 @@ def __init__( availableInSettingsRing=availableInSettingsRing, defaultVal=defaultVal, displayName=displayName, - useConfig=useConfig + useConfig=useConfig, ) def _get_configSpec(self): diff --git a/source/baseObject.py b/source/baseObject.py index 6cefa9b7cc8..c5b17dc936c 100755 --- a/source/baseObject.py +++ b/source/baseObject.py @@ -251,9 +251,11 @@ def bindGesture(self, gestureIdentifier, scriptName): # and instance methods are meant to be generated on retrieval anyway. func = getattr(self.__class__, scriptAttrName, None) if not func: - raise LookupError("No such script on class {className}. Couldn't find attribute: {scriptAttrName}".format( - className=self.__class__.__name__, scriptAttrName=scriptAttrName - )) + raise LookupError( + "No such script on class {className}. Couldn't find attribute: {scriptAttrName}".format( + className=self.__class__.__name__, scriptAttrName=scriptAttrName, + ), + ) # Import late to avoid circular import. import inputCore self._gestureMap[inputCore.normalizeGestureIdentifier(gestureIdentifier)] = func @@ -307,10 +309,12 @@ def getScript(self,gesture): except KeyError: continue except AttributeError: - log.exception(( - "Base class may not have been initialized." - f"\nMRO={self.__class__.__mro__}" - ) if not hasattr(self, "_gestureMap") else None) + log.exception( + ( + "Base class may not have been initialized." + f"\nMRO={self.__class__.__mro__}" + ) if not hasattr(self, "_gestureMap") else None, + ) return None else: return None diff --git a/source/bdDetect.py b/source/bdDetect.py index c040fd81d43..4a1e491bfcd 100644 --- a/source/bdDetect.py +++ b/source/bdDetect.py @@ -80,7 +80,7 @@ def __getattr__(attrName: str) -> Any: replacementSymbol = _deprecatedConstantsMap[attrName] log.warning( f"{attrName} is deprecated. " - f"Use bdDetect.DeviceType.{replacementSymbol.name} instead. " + f"Use bdDetect.DeviceType.{replacementSymbol.name} instead. ", ) return replacementSymbol raise AttributeError(f"module {repr(__name__)} has no attribute {repr(attrName)}") @@ -130,7 +130,7 @@ def _isDebug(): def getDriversForConnectedUsbDevices( - limitToDevices: Optional[List[str]] = None + limitToDevices: Optional[List[str]] = None, ) -> Iterator[Tuple[str, DeviceMatch]]: """Get any matching drivers for connected USB devices. Looks for (and yields) custom drivers first, then considers if the device is may be compatible with the @@ -199,7 +199,7 @@ def _isHIDBrailleMatch(match: DeviceMatch) -> bool: def getDriversForPossibleBluetoothDevices( - limitToDevices: Optional[List[str]] = None + limitToDevices: Optional[List[str]] = None, ) -> Iterator[Tuple[str, DeviceMatch]]: """Get any matching drivers for possible Bluetooth devices. Looks for (and yields) custom drivers first, then considers if the device is may be compatible with the @@ -289,10 +289,12 @@ def _get_usbComPorts(self) -> list[dict[str, str]]: for port in self.comPorts: if (usbId := port.get("usbID")) is None: continue - if (usbDict := next( - (d for d in self.usbDevices if d.get("usbID") == usbId), - None - )) is not None: + if ( + usbDict := next( + (d for d in self.usbDevices if d.get("usbID") == usbId), + None, + ) + ) is not None: comPorts.append(port | usbDict) return comPorts @@ -328,7 +330,7 @@ def _queueBgScan( self, usb: bool = False, bluetooth: bool = False, - limitToDevices: Optional[List[str]] = None + limitToDevices: Optional[List[str]] = None, ): """Queues a scan for devices. If a scan is already in progress, a new scan will be queued after the current scan. @@ -399,7 +401,7 @@ def _bgScan( self, usb: bool, bluetooth: bool, - limitToDevices: Optional[List[str]] + limitToDevices: Optional[List[str]], ): """Performs the actual background scan. this function should be run on a background thread. @@ -486,7 +488,7 @@ def getConnectedUsbDevicesForDriver(driver: str) -> Iterator[DeviceMatch]: ( DeviceMatch(DeviceType.SERIAL, port["usbID"], port["port"], port) for port in deviceInfoFetcher.usbComPorts - ) + ), ) fallbackMatches: list[DeviceMatch] = [] @@ -545,10 +547,14 @@ def driverHasPossibleDevices(driver: str) -> bool: @return: C{True} if there are possible devices, C{False} otherwise. @raise LookupError: If there is no detection data for this driver. """ - return bool(next(itertools.chain( - getConnectedUsbDevicesForDriver(driver), - getPossibleBluetoothDevicesForDriver(driver) - ), None)) + return bool( + next( + itertools.chain( + getConnectedUsbDevicesForDriver(driver), + getPossibleBluetoothDevicesForDriver(driver), + ), None, + ), + ) def driverSupportsAutoDetection(driver: str) -> bool: @@ -572,16 +578,18 @@ def driverIsEnabledForAutoDetection(driver: str) -> bool: def getSupportedBrailleDisplayDrivers( - onlyEnabled: bool = False + onlyEnabled: bool = False, ) -> Generator[Type["braille.BrailleDisplayDriver"], Any, Any]: - return braille.getDisplayDrivers(lambda d: ( - d.isThreadSafe - and d.supportsAutomaticDetection - and ( - not onlyEnabled - or d.name not in config.conf["braille"]["auto"]["excludedDisplays"] - ) - )) + return braille.getDisplayDrivers( + lambda d: ( + d.isThreadSafe + and d.supportsAutomaticDetection + and ( + not onlyEnabled + or d.name not in config.conf["braille"]["auto"]["excludedDisplays"] + ) + ), + ) def getBrailleDisplayDriversEnabledForDetection() -> Generator[str, Any, Any]: @@ -652,7 +660,7 @@ def addUsbDevices(self, type: DeviceType, ids: set[str], useAsFallBack: bool = F if malformedIds: raise ValueError( f"Invalid IDs provided for driver {self._driver!r}, type {type!r}: " - f"{', '.join(malformedIds)}" + f"{', '.join(malformedIds)}", ) if useAsFallBack: fallBackDevices.update((self._driver, type, id) for id in ids) @@ -673,7 +681,7 @@ def addBluetoothDevices(self, matchFunc: MatchFuncT): def addDeviceScanner( self, scanFunc: Callable[..., Iterable[Tuple[str, DeviceMatch]]], - moveToStart: bool = False + moveToStart: bool = False, ): """Register a callable to scan devices. This adds a handler to L{scanForDevices}. diff --git a/source/braille.py b/source/braille.py index b9fc9df004c..b285d1cabe4 100644 --- a/source/braille.py +++ b/source/braille.py @@ -517,7 +517,7 @@ def update(self): textToTranslate, typeform=textToTranslateTypeforms, mode=mode, - cursorPos=cursorPos + cursorPos=cursorPos, ) if converter: @@ -579,14 +579,14 @@ def __init__(self, text): def _getAnnotationProperty( - propertyValues: Dict[str, Any] + propertyValues: Dict[str, Any], ) -> str: # Translators: Braille when there are further details/annotations that can be fetched manually. genericDetailsRole = _("details") detailsRoles: _AnnotationRolesT = propertyValues.get("detailsRoles", tuple()) if not detailsRoles: log.debugWarning( - "There should always be detailsRoles (at least a single None value) when hasDetails is true." + "There should always be detailsRoles (at least a single None value) when hasDetails is true.", ) return genericDetailsRole else: @@ -655,8 +655,8 @@ def getPropertiesBraille(**propertyValues) -> str: # noqa: C901 states, None, positiveStateLabels, - negativeStateLabels - ) + negativeStateLabels, + ), ) if roleText: textList.append(roleText) @@ -789,7 +789,8 @@ def update(self): if mathPres.brailleProvider: try: text += TEXT_SEPARATOR + mathPres.brailleProvider.getBrailleForMathMl( - obj.mathMl) + obj.mathMl, + ) except (NotImplementedError, LookupError): pass self.rawText = text + self.appendText @@ -820,7 +821,7 @@ def getControlFieldBraille( field: textInfos.Field, ancestors: typing.List[textInfos.Field], reportStart: bool, - formatConfig: config.AggregatedSection + formatConfig: config.AggregatedSection, ) -> Optional[str]: presCat = field.getPresentationCategory(ancestors, formatConfig) # Cache this for later use. @@ -912,16 +913,18 @@ def getControlFieldBraille( value=value, roleText=roleText, placeholder=placeholder, - errorMessage=errorMessage + errorMessage=errorMessage, ) else: # Translators: Displayed in braille at the end of a control field such as a list or table. # %s is replaced with the control's role. - return (_("%s end") % getPropertiesBraille( - role=role, - roleText=roleText - )) + return ( + _("%s end") % getPropertiesBraille( + role=role, + roleText=roleText, + ) + ) def _getControlFieldForLayoutPresentation( @@ -1036,7 +1039,8 @@ def _getControlFieldForReportStart( if text: text += TEXT_SEPARATOR text += mathPres.brailleProvider.getBrailleForMathMl( - info.getMathMl(field)) + info.getMathMl(field), + ) except (NotImplementedError, LookupError): pass return text @@ -1657,7 +1661,7 @@ def bufferPositionsToRawText(self, startPos, endPos): f"(startPos-endPos): {startPos}-{endPos}, " f"for rawText: {self.rawText}, " f"with brailleToRawPos: {brailleToRawPos}", - exc_info=True + exc_info=True, ) return "" @@ -1676,8 +1680,10 @@ def _get_windowEndPos(self): try: # Try not to split words across windows. # To do this, break after the furthest possible space. - return min(rindex(self.brailleCells, 0, self.windowStartPos, endPos) + 1, - endPos) + return min( + rindex(self.brailleCells, 0, self.windowStartPos, endPos) + 1, + endPos, + ) except ValueError: pass return endPos @@ -1978,7 +1984,7 @@ def getFocusRegions( obj = obj.rootNVDAObject region = (ReviewNVDAObjectRegion if review else NVDAObjectRegion)( obj, - appendText=TEXT_SEPARATOR if region2 else "" + appendText=TEXT_SEPARATOR if region2 else "", ) region.update() yield region @@ -2000,7 +2006,8 @@ def formatCellsForLog(cells: List[int]) -> str: return TEXT_SEPARATOR.join([ "".join([str(dot + 1) for dot in range(8) if cell & (1 << dot)]) if cell else "-" - for cell in cells]) + for cell in cells + ]) pre_writeCells = extensionPoints.Action() @@ -2238,7 +2245,7 @@ def _set_displaySize(self, value): Consider registering a handler to L{filter_displaySize} instead. """ raise AttributeError( - f"Can't set displaySize to {value}, consider registering a handler to filter_displaySize" + f"Can't set displaySize to {value}, consider registering a handler to filter_displaySize", ) enabled: bool @@ -2263,7 +2270,7 @@ def _get_enabled(self): def _set_enabled(self, value): raise AttributeError( - f"Can't set enabled to {value}, consider registering a handler to decide_enabled or filter_displaySize" + f"Can't set enabled to {value}, consider registering a handler to decide_enabled or filter_displaySize", ) def _handleEnabledDecisionFalse(self): @@ -2328,7 +2335,7 @@ def _switchDisplay( self, oldDisplay: Optional["BrailleDisplayDriver"], newDisplayClass: Type["BrailleDisplayDriver"], - **kwargs + **kwargs, ) -> "BrailleDisplayDriver": sameDisplayReInit = newDisplayClass == oldDisplay.__class__ if sameDisplayReInit: @@ -2371,7 +2378,7 @@ def _setDisplay( newDisplay = self._switchDisplay(oldDisplay, newDisplayClass, **kwargs) self.display = newDisplay log.info( - f"Loaded braille display driver {newDisplay.name!r}, current display has {newDisplay.numCells} cells." + f"Loaded braille display driver {newDisplay.name!r}, current display has {newDisplay.numCells} cells.", ) displayChanged.notify(display=newDisplay, isFallback=isFallback, detected=detected) queueHandler.queueFunction(queueHandler.eventQueue, self.initialDisplay) @@ -2411,7 +2418,7 @@ def _writeCells(self, cells: List[int]): # There are more cells than the connected display could take. log.warning( f"Connected display {self.display.name!r} has {displayCellCount} cells, " - f"while braille handler is using {handlerCellCount} cells" + f"while braille handler is using {handlerCellCount} cells", ) cells = cells[:displayCellCount] elif cellCountDif > 0: @@ -2584,7 +2591,7 @@ def _doNewObject(self, regions): def handleCaretMove( self, obj: "NVDAObject", - shouldAutoTether: bool = True + shouldAutoTether: bool = True, ) -> None: if not self.enabled or config.conf["braille"]["mode"] == BrailleMode.SPEECH_OUTPUT.value: return @@ -2621,7 +2628,7 @@ def _handlePendingUpdate(self): except Exception: log.debugWarning( f"Region update failed for {region}, object probably died", - exc_info=True + exc_info=True, ) continue if isinstance(region, TextInfoRegion) and region.pendingCaretUpdate: @@ -2765,7 +2772,7 @@ def handlePostConfigProfileSwitch(self): except LookupError: log.error( f"Invalid translation table ({tableName}), " - f"falling back to default ({FALLBACK_TABLE})." + f"falling back to default ({FALLBACK_TABLE}).", ) self._table = brailleTables.getTable(FALLBACK_TABLE) @@ -2787,7 +2794,7 @@ def _enableDetection( self, usb: bool = True, bluetooth: bool = True, - limitToDevices: Optional[List[str]] = None + limitToDevices: Optional[List[str]] = None, ): """Enables automatic detection of braille displays. When auto detection is already active, this will force a rescan for devices. @@ -2844,7 +2851,7 @@ def _bgThreadExecutor(self, param: int): # Wait twice the display driver timeout for acknowledgement packets # Note: timeout is in seconds whereas setWaitableTimer expects milliseconds int(self.display.timeout * 2 * SECOND_TO_MS), - self._ackTimeoutResetter + self._ackTimeoutResetter, ) def _ackTimeoutResetter(self, param: int): @@ -3109,7 +3116,7 @@ def getManualPorts(cls) -> typing.Iterator[typing.Tuple[str, str]]: @classmethod def _getTryPorts( - cls, port: Union[str, bdDetect.DeviceMatch] + cls, port: Union[str, bdDetect.DeviceMatch], ) -> typing.Iterator[bdDetect.DeviceMatch]: """Returns the ports for this driver to which a connection attempt should be made. This generator function is usually used in L{__init__} to connect to the desired display. @@ -3132,7 +3139,7 @@ def _getTryPorts( bdDetect.DeviceType.SERIAL, portInfo["bluetoothName" if "bluetoothName" in portInfo else "friendlyName"], portInfo["port"], - portInfo + portInfo, ) else: for match in cls._getAutoPorts(usb=isUsb, bluetooth=isBluetooth): @@ -3155,14 +3162,16 @@ def _getModifierGestures(cls, model=None): globalMaps = [inputCore.manager.userGestureMap] if cls.gestureMap: globalMaps.append(cls.gestureMap) - prefixes=["br({source})".format(source=cls.name),] + prefixes=["br({source})".format(source=cls.name)] if model: prefixes.insert(0,"br({source}.{model})".format(source=cls.name, model=model)) for globalMap in globalMaps: for scriptCls, gesture, scriptName in globalMap.getScriptsForAllGestures(): - if (any(gesture.startswith(prefix.lower()) for prefix in prefixes) - and scriptCls is globalCommands.GlobalCommands - and scriptName and scriptName.startswith("kb")): + if ( + any(gesture.startswith(prefix.lower()) for prefix in prefixes) + and scriptCls is globalCommands.GlobalCommands + and scriptName and scriptName.startswith("kb") + ): emuGesture = keyboardHandler.KeyboardInputGesture.fromName(scriptName.split(":")[1]) if emuGesture.isModifier: yield set(gesture.split(":")[1].split("+")), set(emuGesture._keyNamesInDisplayOrder) @@ -3186,7 +3195,7 @@ def DotFirmnessSetting(cls,defaultVal,minVal,maxVal,useConfig=False): defaultVal=defaultVal, minVal=minVal, maxVal=maxVal, - useConfig=useConfig + useConfig=useConfig, ) @classmethod @@ -3196,7 +3205,7 @@ def BrailleInputSetting(cls, useConfig=True): "brailleInput", # Translators: Label for a setting in braille settings dialog. _("Braille inp&ut"), - useConfig=useConfig + useConfig=useConfig, ) @classmethod @@ -3206,7 +3215,7 @@ def HIDInputSetting(cls, useConfig): "hidKeyboardInput", # Translators: Label for a setting in braille settings dialog. _("&HID keyboard input simulation"), - useConfig=useConfig + useConfig=useConfig, ) class BrailleDisplayGesture(inputCore.InputGesture): @@ -3304,7 +3313,7 @@ def _get_script(self): if gestureKeys != set(self.keyNames): # Find a script for L{gestureKeys}. id = "+".join(gestureKeys) - fakeGestureIds = [u"br({source}):{id}".format(source=self.source, id=id),] + fakeGestureIds = [u"br({source}):{id}".format(source=self.source, id=id)] if self.model: fakeGestureIds.insert(0,u"br({source}.{model}):{id}".format(source=self.source, model=self.model, id=id)) scriptNames = [] @@ -3318,12 +3327,12 @@ def _get_script(self): # We can't bother about multiple scripts for a gesture, we will just use the first one combinedScriptName = "kb:{modifiers}+{keys}".format( modifiers="+".join(gestureModifiers), - keys=scriptNames[0].split(":")[1] + keys=scriptNames[0].split(":")[1], ) elif script and scriptName: combinedScriptName = "kb:{modifiers}+{keys}".format( modifiers="+".join(gestureModifiers), - keys=scriptName.split(":")[1] + keys=scriptName.split(":")[1], ) else: return None @@ -3373,7 +3382,7 @@ def getDisplayTextForIdentifier(cls, identifier): description = unknownDisplayDescription if modelName: # The identifier contains a model name return description, "{modelName}: {key}".format( - modelName=modelName, key=key + modelName=modelName, key=key, ) else: return description, key @@ -3393,20 +3402,24 @@ def getSerialPorts(filterFunc=None) -> typing.Iterator[typing.Tuple[str, str]]: if filterFunc and not filterFunc(info): continue if "bluetoothName" in info: - yield (info["port"], - # Translators: Name of a Bluetooth serial communications port. - _("Bluetooth Serial: {port} ({deviceName})").format( - port=info["port"], - deviceName=info["bluetoothName"] - )) + yield ( + info["port"], + # Translators: Name of a Bluetooth serial communications port. + _("Bluetooth Serial: {port} ({deviceName})").format( + port=info["port"], + deviceName=info["bluetoothName"], + ), + ) else: - yield (info["port"], - # Translators: Name of a serial communications port. - _("Serial: {portName}").format(portName=info["friendlyName"])) + yield ( + info["port"], + # Translators: Name of a serial communications port. + _("Serial: {portName}").format(portName=info["friendlyName"]), + ) def getDisplayDrivers( - filterFunc: Optional[Callable[[Type[BrailleDisplayDriver]], bool]] = None + filterFunc: Optional[Callable[[Type[BrailleDisplayDriver]], bool]] = None, ) -> Generator[Type[BrailleDisplayDriver], Any, Any]: """Gets an iterator of braille display drivers meeting the given filter callable. @param filterFunc: an optional callable that receives a driver as its only argument and returns @@ -3421,7 +3434,7 @@ def getDisplayDrivers( except Exception: log.error( f"Error while importing braille display driver {name}", - exc_info=True + exc_info=True, ) continue if not filterFunc or filterFunc(display): diff --git a/source/brailleDisplayDrivers/albatross/_threading.py b/source/brailleDisplayDrivers/albatross/_threading.py index 0fa434b27a8..75c54735326 100644 --- a/source/brailleDisplayDrivers/albatross/_threading.py +++ b/source/brailleDisplayDrivers/albatross/_threading.py @@ -45,7 +45,7 @@ def __init__( event: Event, dev: serial.Serial, *args, - **kwargs + **kwargs, ): """Constructor. @param readFunction: Handles read operations and reconnection. @@ -68,18 +68,18 @@ def run(self): # But if port is not present, just wait and continue if not self._portPresent(): log.debug( - f"Sleepin {KC_INTERVAL} seconds, port {self._dev.name} not present" + f"Sleepin {KC_INTERVAL} seconds, port {self._dev.name} not present", ) self._event.wait(KC_INTERVAL) continue log.debug( f"Port {self._dev.name} present, calling {self._readFunction.__name__} " - "to open it" + "to open it", ) self._readFunction() if not self._dev.is_open: log.debug( - f"Sleepin {KC_INTERVAL} seconds, port {self._dev.name} not open" + f"Sleepin {KC_INTERVAL} seconds, port {self._dev.name} not open", ) self._event.wait(KC_INTERVAL) continue @@ -95,7 +95,7 @@ def run(self): result = ctypes.windll.kernel32.WaitCommEvent( self._dev._port_handle, byref(dwEvtMask), - byref(self._dev._overlapped_read) + byref(self._dev._overlapped_read), ) if not result and GetLastError() != ERROR_IO_PENDING: if self._event.is_set(): @@ -107,7 +107,7 @@ def run(self): self._dev._port_handle, byref(self._dev._overlapped_read), byref(data), - True + True, ) if result: log.debug(f"Calling function {self._readFunction.__name__} for read") @@ -147,7 +147,7 @@ class RepeatedTimer: def __init__( self, interval: float, - feedFunction: Callable[[], None] + feedFunction: Callable[[], None], ): """Constructor. @param interval: Checking frequency diff --git a/source/brailleDisplayDrivers/albatross/constants.py b/source/brailleDisplayDrivers/albatross/constants.py index 17e6ad34245..cda9b9f2457 100644 --- a/source/brailleDisplayDrivers/albatross/constants.py +++ b/source/brailleDisplayDrivers/albatross/constants.py @@ -156,7 +156,7 @@ class Keys(IntEnum): Keys.end2, Keys.eCursor2, Keys.cursor2, - } + }, ) """Ctrl keys which may start key combination.""" @@ -233,8 +233,8 @@ class RoutingKeyRange: RoutingKeyRange("routing", 2, 41, indexOffset=2), RoutingKeyRange("secondRouting", 43, 82, indexOffset=43), RoutingKeyRange("routing", 111, 150, indexOffset=71), - RoutingKeyRange("secondRouting", 152, 191, indexOffset=112) - } + RoutingKeyRange("secondRouting", 152, 191, indexOffset=112), + }, ) """Defines routing key ranges. See L{RoutingKeyRange}.""" diff --git a/source/brailleDisplayDrivers/albatross/driver.py b/source/brailleDisplayDrivers/albatross/driver.py index ae148ededf0..28b8474f768 100644 --- a/source/brailleDisplayDrivers/albatross/driver.py +++ b/source/brailleDisplayDrivers/albatross/driver.py @@ -84,9 +84,11 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver): @classmethod def registerAutomaticDetection(cls, driverRegistrar: DriverRegistrar): - driverRegistrar.addUsbDevices(DeviceType.SERIAL, { - "VID_0403&PID_6001", # Caiku Albatross 46/80 - }) + driverRegistrar.addUsbDevices( + DeviceType.SERIAL, { + "VID_0403&PID_6001", # Caiku Albatross 46/80 + }, + ) @classmethod def getManualPorts(cls): @@ -183,7 +185,7 @@ def _searchPorts(self, originalPort: str): self._oldCells.append(0) self._kc = _threading.RepeatedTimer( KC_INTERVAL, - self._keepConnected + self._keepConnected, ) self._handleRead = _threading.ReadThread( self._readHandling, @@ -191,12 +193,12 @@ def _searchPorts(self, originalPort: str): self._exitEvent, self._dev, name="albatross_read", - daemon=True + daemon=True, ) self._handleRead.start() log.info( f"Connected to Caiku Albatross {self.numCells} on {portType} port {port} " - f"at {self._baudRate} bps." + f"at {self._baudRate} bps.", ) break # This device initialization failed. @@ -206,7 +208,7 @@ def _searchPorts(self, originalPort: str): self._dev = None log.info( f"Connection to {self.description} display on {portType} port {port} " - f"at {self._baudRate} bps failed." + f"at {self._baudRate} bps failed.", ) if self.numCells: break @@ -241,7 +243,7 @@ def _initConnection(self) -> bool: self._tryToConnect = False else: log.debug( - f"Sleeping {SLEEP_TIMEOUT} seconds before try {i + 1} / {MAX_INIT_RETRIES}" + f"Sleeping {SLEEP_TIMEOUT} seconds before try {i + 1} / {MAX_INIT_RETRIES}", ) time.sleep(SLEEP_TIMEOUT) if not self._readInitByte(): @@ -262,14 +264,14 @@ def _initPort(self, i: int = MAX_INIT_RETRIES - 1) -> bool: stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE, timeout=READ_TIMEOUT, - writeTimeout=WRITE_TIMEOUT + writeTimeout=WRITE_TIMEOUT, ) log.debug(f"Port {self._currentPort} initialized") if not self._resetBuffers(): if i == MAX_INIT_RETRIES - 1: return False log( - f"sleeping {SLEEP_TIMEOUT} seconds before try {i + 2} / {MAX_INIT_RETRIES}" + f"sleeping {SLEEP_TIMEOUT} seconds before try {i + 2} / {MAX_INIT_RETRIES}", ) time.sleep(SLEEP_TIMEOUT) return False @@ -287,7 +289,7 @@ def _openPort(self, i: int = MAX_INIT_RETRIES - 1) -> bool: if i == MAX_INIT_RETRIES - 1: return False log( - f"sleeping {SLEEP_TIMEOUT} seconds before try {i + 2} / {MAX_INIT_RETRIES}" + f"sleeping {SLEEP_TIMEOUT} seconds before try {i + 2} / {MAX_INIT_RETRIES}", ) time.sleep(SLEEP_TIMEOUT) return False @@ -299,7 +301,7 @@ def _openPort(self, i: int = MAX_INIT_RETRIES - 1) -> bool: log.debug( f"Port {self._currentPort} not opened, sleeping {SLEEP_TIMEOUT} seconds " f"before try {i + 2} / {MAX_INIT_RETRIES}", - exc_info=True + exc_info=True, ) time.sleep(SLEEP_TIMEOUT) return False @@ -336,7 +338,7 @@ def _readInitByte(self) -> bool: log.debug( f"INIT_START_BYTE {INIT_START_BYTE} read failed, " "trying to reconnect", - exc_info=True + exc_info=True, ) return False @@ -377,7 +379,7 @@ def _resetBuffers(self) -> bool: for j in range(RESET_COUNT): PurgeComm( self._dev._port_handle, - PURGE_RXCLEAR | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_TXABORT + PURGE_RXCLEAR | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_TXABORT, ) time.sleep(RESET_SLEEP) log.debug("I/O buffers reset done") @@ -387,7 +389,7 @@ def _resetBuffers(self) -> bool: # might raise. except (IOError, AttributeError): log.debug( - f"I/O buffer reset failed on port {self._currentPort}", exc_info=True + f"I/O buffer reset failed on port {self._currentPort}", exc_info=True, ) if self._dev.is_open: self._dev.close() @@ -445,7 +447,7 @@ def _somethingToRead(self) -> Optional[bytes]: return None data = self._dev.read(self._dev.in_waiting) log.debug( - f"Read: {data}, length {len(data)}, in_waiting {self._dev.in_waiting}" + f"Read: {data}, length {len(data)}, in_waiting {self._dev.in_waiting}", ) return data # Considering situation where "albatross_read" thread is about to read @@ -485,8 +487,8 @@ def _skipRedundantInitPackets(self, data: bytes) -> bool: "To use Albatross with NVDA: " "change number of status cells in Albatross internal menu at most " f"to {MAX_STATUS_CELLS_ALLOWED}, and if needed, restart Albatross " - "and NVDA." - ) + "and NVDA.", + ), ) self._disableConnection() return False @@ -529,7 +531,7 @@ def _somethingToWrite(self): def _handleReadQueue(self): """Handles data read in L{_readHandling}.""" log.debug( - f"_ReadQueue is: {self._readQueue}, length {len(self._readQueue)}" + f"_ReadQueue is: {self._readQueue}, length {len(self._readQueue)}", ) while len(self._readQueue): try: @@ -568,7 +570,7 @@ def _handleInitPackets(self, data: bytes): self._waitingSettingsByte = True log.debug( "Read: _readQueue is empty, waiting for settings byte", - exc_info=True + exc_info=True, ) return self._writeQueue.appendleft(ESTABLISHED) @@ -583,7 +585,7 @@ def _handleInitPackets(self, data: bytes): self._clearOldCells() braille.handler._displayWithCursor() log.debug( - "Updated display content after reconnection or display menu exit" + "Updated display content after reconnection or display menu exit", ) if self._waitingSettingsByte: self._waitingSettingsByte = False @@ -635,7 +637,7 @@ def _handleSettingsByte(self, data: bytes): self._keyLayout = ord(data) >> 4 & KEY_LAYOUT_MASK log.debug( f"Current settings: number of cells {self.numCells}, " - f"key layout {KeyLayout(self._keyLayout).name}" + f"key layout {KeyLayout(self._keyLayout).name}", ) self._disabledConnection = False @@ -670,7 +672,7 @@ def _handleKeyPresses(self, data: bytes): log.debug( f"Read: Ctrl key packet {data} dequeued partially, " "_readQueue is empty", - exc_info=True + exc_info=True, ) return if len(data) > MAX_COMBINATION_KEYS and data[len(data) - 1] != data[0]: @@ -681,14 +683,14 @@ def _handleKeyPresses(self, data: bytes): if self._keyLayout != KeyLayout.normal: # Using custom key layout data = self._changeKeyValues( - bytearray(data) + bytearray(data), ) log.debug(f"Keys for key press: {data}") pressedKeys = set(data) log.debug(f"Forwarding keys {pressedKeys}") try: inputCore.manager.executeGesture( - gestures.InputGestureKeys(pressedKeys, self.name) + gestures.InputGestureKeys(pressedKeys, self.name), ) # Attribute error which rarely occurs here is something strange. except (inputCore.NoInputGestureAction, AttributeError): @@ -708,10 +710,10 @@ def _changeKeyValues(self, data: bytearray) -> bytes: data[i] = LEFT_RIGHT_KEY_CODES[key] elif key in LEFT_RIGHT_KEY_CODES.values(): j = list( - LEFT_RIGHT_KEY_CODES.values() + LEFT_RIGHT_KEY_CODES.values(), ).index(key) data[i] = list( - LEFT_RIGHT_KEY_CODES.keys() + LEFT_RIGHT_KEY_CODES.keys(), )[j] continue if self._keyLayout == KeyLayout.bothSidesAsRight: @@ -721,10 +723,10 @@ def _changeKeyValues(self, data: bytearray) -> bytes: if self._keyLayout == KeyLayout.bothSidesAsLeft: if key in LEFT_RIGHT_KEY_CODES.values(): j = list( - LEFT_RIGHT_KEY_CODES.values() + LEFT_RIGHT_KEY_CODES.values(), ).index(key) data[i] = list( - LEFT_RIGHT_KEY_CODES.keys() + LEFT_RIGHT_KEY_CODES.keys(), )[j] return bytes(data) @@ -751,7 +753,7 @@ def display(self, cells: List[int]): # Using lock because called also indirectly manually when display is # switched back on or exited from internal menu. with self._displayLock: - writeBytes: List[bytes] = [START_BYTE, ] + writeBytes: List[bytes] = [START_BYTE] # Only changed content is sent (cell index and data). for i, cell in enumerate(cells): if cell != self._oldCells[i]: @@ -761,11 +763,11 @@ def display(self, cells: List[int]): # Bits have to be reversed. writeBytes.append( int( - '{:08b}'.format(cell)[::-1], 2 + '{:08b}'.format(cell)[::-1], 2, ) .to_bytes( - 1, 'big' - ) + 1, 'big', + ), ) writeBytes.append(END_BYTE) if writeBytes == [START_BYTE, END_BYTE]: # No updated cell content diff --git a/source/brailleDisplayDrivers/albatross/gestures.py b/source/brailleDisplayDrivers/albatross/gestures.py index 452a4c765c2..a7fb0523f9a 100644 --- a/source/brailleDisplayDrivers/albatross/gestures.py +++ b/source/brailleDisplayDrivers/albatross/gestures.py @@ -21,16 +21,16 @@ ) _gestureMap = inputCore.GlobalGestureMap({ "globalCommands.GlobalCommands": { - "review_top": ("br(albatross):home1", "br(albatross):home2",), - "review_bottom": ("br(albatross):end1", "br(albatross):end2",), - "navigatorObject_toFocus": ("br(albatross):eCursor1", "br(albatross):eCursor2",), - "braille_toFocus": ("br(albatross):cursor1", "br(albatross):cursor2",), + "review_top": ("br(albatross):home1", "br(albatross):home2"), + "review_bottom": ("br(albatross):end1", "br(albatross):end2"), + "navigatorObject_toFocus": ("br(albatross):eCursor1", "br(albatross):eCursor2"), + "braille_toFocus": ("br(albatross):cursor1", "br(albatross):cursor2"), "moveMouseToNavigatorObject": ("br(albatross):home1+home2",), "moveNavigatorObjectToMouse": ("br(albatross):end1+end2",), "navigatorObject_moveFocus": ("br(albatross):eCursor1+eCursor2",), "braille_toggleTether": ("br(albatross):cursor1+cursor2",), - "braille_previousLine": ("br(albatross):up1", "br(albatross):up2", "br(albatross):up3",), - "braille_nextLine": ("br(albatross):down1", "br(albatross):down2", "br(albatross):down3",), + "braille_previousLine": ("br(albatross):up1", "br(albatross):up2", "br(albatross):up3"), + "braille_nextLine": ("br(albatross):down1", "br(albatross):down2", "br(albatross):down3"), "braille_scrollBack": ( "br(albatross):left", "br(albatross):lWheelLeft", @@ -53,13 +53,13 @@ "navigatorObject_next": ("br(albatross):f6",), "navigatorObject_current": ("br(albatross):f7",), "navigatorObject_currentDimensions": ("br(albatross):f8",), - "activateBrailleSettingsDialog": ("br(albatross):f1+home1", "br(albatross):f9+home2",), - "reviewCursorToStatusLine": ("br(albatross):f1+end1", "br(albatross):f9+end2",), - "braille_cycleCursorShape": ("br(albatross):f1+eCursor1", "br(albatross):f9+eCursor2",), - "braille_toggleShowCursor": ("br(albatross):f1+cursor1", "br(albatross):f9+cursor2",), - "braille_cycleShowMessages": ("br(albatross):f1+f2", "br(albatross):f9+f10",), - "braille_cycleShowSelection": ("br(albatross):f1+f5", "br(albatross):f9+f14",), - "braille_cycleReviewRoutingMovesSystemCaret": ("br(albatross):f1+f3", "br(albatross):f9+f11",), + "activateBrailleSettingsDialog": ("br(albatross):f1+home1", "br(albatross):f9+home2"), + "reviewCursorToStatusLine": ("br(albatross):f1+end1", "br(albatross):f9+end2"), + "braille_cycleCursorShape": ("br(albatross):f1+eCursor1", "br(albatross):f9+eCursor2"), + "braille_toggleShowCursor": ("br(albatross):f1+cursor1", "br(albatross):f9+cursor2"), + "braille_cycleShowMessages": ("br(albatross):f1+f2", "br(albatross):f9+f10"), + "braille_cycleShowSelection": ("br(albatross):f1+f5", "br(albatross):f9+f14"), + "braille_cycleReviewRoutingMovesSystemCaret": ("br(albatross):f1+f3", "br(albatross):f9+f11"), "review_activate": ("br(albatross):f7+f8",), "dateTime": ("br(albatross):f9",), "say_battery_status": ("br(albatross):f10",), @@ -70,8 +70,8 @@ "review_currentCharacter": ("br(albatross):f15",), "review_currentLine": ("br(albatross):f16",), "review_currentWord": ("br(albatross):f15+f16",), - "review_previousLine": ("br(albatross):lWheelUp", "br(albatross):rWheelUp",), - "review_nextLine": ("br(albatross):lWheelDown", "br(albatross):rWheelDown",), + "review_previousLine": ("br(albatross):lWheelUp", "br(albatross):rWheelUp"), + "review_nextLine": ("br(albatross):lWheelDown", "br(albatross):rWheelDown"), "kb:windows+d": ("br(albatross):attribute1"), "kb:windows+e": ("br(albatross):attribute2"), "kb:windows+b": ("br(albatross):attribute3"), diff --git a/source/brailleDisplayDrivers/alva.py b/source/brailleDisplayDrivers/alva.py index 8a17d82174f..fab597b730f 100644 --- a/source/brailleDisplayDrivers/alva.py +++ b/source/brailleDisplayDrivers/alva.py @@ -82,24 +82,30 @@ DOUBLED_KEY_COUNTS = { ALVA_THUMB_GROUP: 5, - ALVA_SP_GROUP: 9 + ALVA_SP_GROUP: 9, } ALVA_KEYS = { # Thumb keys (FRONT_GROUP) - ALVA_THUMB_GROUP: ("t1", "t2", "t3", "t4", "t5", - # Only for BC680 - "t1", "t2", "t3", "t4", "t5"), + ALVA_THUMB_GROUP: ( + "t1", "t2", "t3", "t4", "t5", + # Only for BC680 + "t1", "t2", "t3", "t4", "t5", + ), # eTouch keys (ETOUCH_GROUP) ALVA_ETOUCH_GROUP: ("etouch1", "etouch2", "etouch3", "etouch4"), # Smartpad keys (PDA_GROUP) - ALVA_SP_GROUP: ("sp1", "sp2", "spLeft", "spEnter", "spUp", "spDown", "spRight", "sp3", "sp4", - # Only for BC680 - "sp1", "sp2", "spLeft", "spEnter", "spUp", "spDown", "spRight", "sp3", "sp4"), + ALVA_SP_GROUP: ( + "sp1", "sp2", "spLeft", "spEnter", "spUp", "spDown", "spRight", "sp3", "sp4", + # Only for BC680 + "sp1", "sp2", "spLeft", "spEnter", "spUp", "spDown", "spRight", "sp3", "sp4", + ), # Feature pack keys. # Numbers start at 0x01, therefore the first string is an empty placeholder. - ALVA_FEATURE_PACK_GROUP: ("", "dot1", "dot2", "dot3", "dot4", "dot5", "dot6", "dot7", "dot8", - "control", "windows", "space", "alt", "enter"), + ALVA_FEATURE_PACK_GROUP: ( + "", "dot1", "dot2", "dot3", "dot4", "dot5", "dot6", "dot7", "dot8", + "control", "windows", "space", "alt", "enter", + ), } class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): @@ -116,11 +122,13 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): @classmethod def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): - driverRegistrar.addUsbDevices(bdDetect.DeviceType.HID, { - "VID_0798&PID_0640", # BC640 - "VID_0798&PID_0680", # BC680 - "VID_0798&PID_0699", # USB protocol converter - }) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.HID, { + "VID_0798&PID_0640", # BC640 + "VID_0798&PID_0680", # BC680 + "VID_0798&PID_0699", # USB protocol converter + }, + ) driverRegistrar.addBluetoothDevices(lambda m: m.id.startswith("ALVA ")) @@ -192,8 +200,11 @@ def __init__(self, port="auto"): self._updateSettings() if self.numCells: # A display responded. - log.info("Found display with {cells} cells connected via {type} ({port})".format( - cells=self.numCells, type=portType, port=port)) + log.info( + "Found display with {cells} cells connected via {type} ({port})".format( + cells=self.numCells, type=portType, port=port, + ), + ) break self._dev.close() @@ -247,7 +258,7 @@ def _hidOnReceive(self, data: bytes): if reportID == ALVA_KEY_REPORT: self._handleInput( data[ALVA_KEY_REPORT_KEY_GROUP_POS], - data[ALVA_KEY_REPORT_KEY_POS] + data[ALVA_KEY_REPORT_KEY_POS], ) def _handleInput(self, group: int, number: int) -> None: @@ -283,7 +294,7 @@ def _hidDisplay(self, cellBytes: bytes) -> None: ALVA_BRAILLE_OUTPUT_REPORT, intToByte(offset), intToByte(len(cellsToWrite)), - cellsToWrite + cellsToWrite, ]) self._dev.write(data) @@ -293,7 +304,7 @@ def _ser6Display(self, cellBytes: bytes) -> None: value = b"".join([ b"\x00", intToByte(len(cellBytes)), - cellBytes + cellBytes, ]) self._ser6SendMessage(b"B", value) @@ -320,7 +331,7 @@ def _handleTime(self, time: bytes): day=time[3], hour=time[4], minute=time[5], - second=time[6] + second=time[6], ) except ValueError: log.debugWarning("Invalid time/date of ALVA display: %r" % time) @@ -340,7 +351,7 @@ def _syncTime(self, dt: datetime.datetime): dt.day, dt.hour, dt.minute, - dt.second + dt.second, ] if self.isHid: self._dev.setFeature(ALVA_RTC_REPORT + bytes(timeList)) @@ -355,7 +366,7 @@ def _set_hidKeyboardInput(self, state): if self.isHid: # Make sure the device settings are up to date. keySettings: int = self._dev.getFeature( - ALVA_KEY_SETTINGS_REPORT + ALVA_KEY_SETTINGS_REPORT, )[ALVA_KEY_SETTINGS_POS] # Try to update the state if rawState: @@ -368,14 +379,14 @@ def _set_hidKeyboardInput(self, state): # Check whether the state has been changed successfully. # If not, this device does not support this feature. keySettings: int = self._dev.getFeature( - ALVA_KEY_SETTINGS_REPORT + ALVA_KEY_SETTINGS_REPORT, )[ALVA_KEY_SETTINGS_POS] # Save the new state self._rawKeyboardInput = bool(keySettings & ALVA_KEY_RAW_INPUT_MASK) else: self._ser6SendMessage( cmd=b"r", - value=boolToByte(rawState) + value=boolToByte(rawState), ) self._ser6SendMessage(b"r", b"?") for i in range(3): @@ -420,26 +431,26 @@ def script_toggleHidKeyboardInput(self, gesture): "title": ("br(alva):etouch2",), "reportStatusLine": ("br(alva):etouch4",), "kb:shift+tab": ("br(alva):sp1",), - "kb:alt": ("br(alva):sp2","br(alva):alt",), + "kb:alt": ("br(alva):sp2","br(alva):alt"), "kb:escape": ("br(alva):sp3",), "kb:tab": ("br(alva):sp4",), "kb:upArrow": ("br(alva):spUp",), "kb:downArrow": ("br(alva):spDown",), "kb:leftArrow": ("br(alva):spLeft",), "kb:rightArrow": ("br(alva):spRight",), - "kb:enter": ("br(alva):spEnter","br(alva):enter",), + "kb:enter": ("br(alva):spEnter","br(alva):enter"), "dateTime": ("br(alva):sp2+sp3",), "showGui": ("br(alva):sp1+sp3",), "kb:windows+d": ("br(alva):sp1+sp4",), "kb:windows+b": ("br(alva):sp3+sp4",), - "kb:windows": ("br(alva):sp1+sp2","br(alva):windows",), + "kb:windows": ("br(alva):sp1+sp2","br(alva):windows"), "kb:alt+tab": ("br(alva):sp2+sp4",), "kb:control+home": ("br(alva):t3+spUp",), "kb:control+end": ("br(alva):t3+spDown",), "kb:home": ("br(alva):t3+spLeft",), "kb:end": ("br(alva):t3+spRight",), "kb:control": ("br(alva):control",), - } + }, }) class InputGesture(braille.BrailleDisplayGesture, brailleInput.BrailleInputGesture): diff --git a/source/brailleDisplayDrivers/baum.py b/source/brailleDisplayDrivers/baum.py index 35c20410ac2..c7dc2d7eaaa 100644 --- a/source/brailleDisplayDrivers/baum.py +++ b/source/brailleDisplayDrivers/baum.py @@ -51,8 +51,10 @@ BAUM_ROUTING_KEYS: None, BAUM_ROUTING_KEY: None, BAUM_DISPLAY_KEYS: ("d1", "d2", "d3", "d4", "d5", "d6"), - BAUM_BRAILLE_KEYS: ("b9", "b10", "b11", None, "c1", "c2", "c3", "c4", # byte 1 - "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8"), # byte 2 + BAUM_BRAILLE_KEYS: ( + "b9", "b10", "b11", None, "c1", "c2", "c3", "c4", # byte 1 + "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", + ), # byte 2 BAUM_JOYSTICK_KEYS: ("up", "left", "down", "right", "select"), } @@ -66,63 +68,71 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver): @classmethod def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): - driverRegistrar.addUsbDevices(bdDetect.DeviceType.HID, { - "VID_0904&PID_3001", # RefreshaBraille 18 - "VID_0904&PID_6101", # VarioUltra 20 - "VID_0904&PID_6103", # VarioUltra 32 - "VID_0904&PID_6102", # VarioUltra 40 - "VID_0904&PID_4004", # Pronto! 18 V3 - "VID_0904&PID_4005", # Pronto! 40 V3 - "VID_0904&PID_4007", # Pronto! 18 V4 - "VID_0904&PID_4008", # Pronto! 40 V4 - "VID_0904&PID_6001", # SuperVario2 40 - "VID_0904&PID_6002", # SuperVario2 24 - "VID_0904&PID_6003", # SuperVario2 32 - "VID_0904&PID_6004", # SuperVario2 64 - "VID_0904&PID_6005", # SuperVario2 80 - "VID_0904&PID_6006", # Brailliant2 40 - "VID_0904&PID_6007", # Brailliant2 24 - "VID_0904&PID_6008", # Brailliant2 32 - "VID_0904&PID_6009", # Brailliant2 64 - "VID_0904&PID_600A", # Brailliant2 80 - "VID_0904&PID_6201", # Vario 340 - "VID_0483&PID_A1D3", # Orbit Reader 20 - "VID_0904&PID_6301", # Vario 4 - }) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.HID, { + "VID_0904&PID_3001", # RefreshaBraille 18 + "VID_0904&PID_6101", # VarioUltra 20 + "VID_0904&PID_6103", # VarioUltra 32 + "VID_0904&PID_6102", # VarioUltra 40 + "VID_0904&PID_4004", # Pronto! 18 V3 + "VID_0904&PID_4005", # Pronto! 40 V3 + "VID_0904&PID_4007", # Pronto! 18 V4 + "VID_0904&PID_4008", # Pronto! 40 V4 + "VID_0904&PID_6001", # SuperVario2 40 + "VID_0904&PID_6002", # SuperVario2 24 + "VID_0904&PID_6003", # SuperVario2 32 + "VID_0904&PID_6004", # SuperVario2 64 + "VID_0904&PID_6005", # SuperVario2 80 + "VID_0904&PID_6006", # Brailliant2 40 + "VID_0904&PID_6007", # Brailliant2 24 + "VID_0904&PID_6008", # Brailliant2 32 + "VID_0904&PID_6009", # Brailliant2 64 + "VID_0904&PID_600A", # Brailliant2 80 + "VID_0904&PID_6201", # Vario 340 + "VID_0483&PID_A1D3", # Orbit Reader 20 + "VID_0904&PID_6301", # Vario 4 + }, + ) - driverRegistrar.addUsbDevices(bdDetect.DeviceType.SERIAL, { - "VID_0403&PID_FE70", # Vario 40 - "VID_0403&PID_FE71", # PocketVario - "VID_0403&PID_FE72", # SuperVario/Brailliant 40 - "VID_0403&PID_FE73", # SuperVario/Brailliant 32 - "VID_0403&PID_FE74", # SuperVario/Brailliant 64 - "VID_0403&PID_FE75", # SuperVario/Brailliant 80 - "VID_0904&PID_2001", # EcoVario 24 - "VID_0904&PID_2002", # EcoVario 40 - "VID_0904&PID_2007", # VarioConnect/BrailleConnect 40 - "VID_0904&PID_2008", # VarioConnect/BrailleConnect 32 - "VID_0904&PID_2009", # VarioConnect/BrailleConnect 24 - "VID_0904&PID_2010", # VarioConnect/BrailleConnect 64 - "VID_0904&PID_2011", # VarioConnect/BrailleConnect 80 - "VID_0904&PID_2014", # EcoVario 32 - "VID_0904&PID_2015", # EcoVario 64 - "VID_0904&PID_2016", # EcoVario 80 - "VID_0904&PID_3000", # RefreshaBraille 18 - }) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.SERIAL, { + "VID_0403&PID_FE70", # Vario 40 + "VID_0403&PID_FE71", # PocketVario + "VID_0403&PID_FE72", # SuperVario/Brailliant 40 + "VID_0403&PID_FE73", # SuperVario/Brailliant 32 + "VID_0403&PID_FE74", # SuperVario/Brailliant 64 + "VID_0403&PID_FE75", # SuperVario/Brailliant 80 + "VID_0904&PID_2001", # EcoVario 24 + "VID_0904&PID_2002", # EcoVario 40 + "VID_0904&PID_2007", # VarioConnect/BrailleConnect 40 + "VID_0904&PID_2008", # VarioConnect/BrailleConnect 32 + "VID_0904&PID_2009", # VarioConnect/BrailleConnect 24 + "VID_0904&PID_2010", # VarioConnect/BrailleConnect 64 + "VID_0904&PID_2011", # VarioConnect/BrailleConnect 80 + "VID_0904&PID_2014", # EcoVario 32 + "VID_0904&PID_2015", # EcoVario 64 + "VID_0904&PID_2016", # EcoVario 80 + "VID_0904&PID_3000", # RefreshaBraille 18 + }, + ) - driverRegistrar.addBluetoothDevices(lambda m: any(m.id.startswith(prefix) for prefix in ( - "Baum SuperVario", - "Baum PocketVario", - "Baum SVario", - "HWG Brailliant", - "Refreshabraille", - "VarioConnect", - "BrailleConnect", - "Pronto!", - "VarioUltra", - "Orbit Reader 20", - "Vario 4", - ))) + driverRegistrar.addBluetoothDevices( + lambda m: any( + m.id.startswith(prefix) for prefix in ( + "Baum SuperVario", + "Baum PocketVario", + "Baum SVario", + "HWG Brailliant", + "Refreshabraille", + "VarioConnect", + "BrailleConnect", + "Pronto!", + "VarioUltra", + "Orbit Reader 20", + "Vario 4", + ) + ), + ) @classmethod def getManualPorts(cls): @@ -170,8 +180,11 @@ def __init__(self, port="auto"): break if self.numCells: # A display responded. - log.info("Found {device} connected via {type} ({port})".format( - device=self._deviceID, type=portType, port=port)) + log.info( + "Found {device} connected via {type} ({port})".format( + device=self._deviceID, type=portType, port=port, + ), + ) break self._dev.close() @@ -218,7 +231,7 @@ def _sendRequest(self, command: bytes, arg: Union[bytes, bool, int] = b""): data = b"".join([ ESCAPE, command, - arg + arg, ]) self._dev.write(data) diff --git a/source/brailleDisplayDrivers/brailleNote.py b/source/brailleDisplayDrivers/brailleNote.py index 2183f748df6..74900438dce 100644 --- a/source/brailleDisplayDrivers/brailleNote.py +++ b/source/brailleDisplayDrivers/brailleNote.py @@ -74,7 +74,7 @@ THUMB_BACK : "tback", THUMB_ADVANCE : "tadvance", THUMB_NEXT : "tnext", - 0 : "space" + 0 : "space", } # Scroll wheel components (Apex BT) @@ -92,7 +92,7 @@ QT_FN : "function", QT_SHIFT : "shift", QT_CTRL : "ctrl", - QT_READ : "read" + QT_READ : "read", } # QT uses various ASCII characters for special keys, akin to scancodes. @@ -129,18 +129,22 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver): @classmethod def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): - driverRegistrar.addUsbDevices(bdDetect.DeviceType.SERIAL, { - "VID_1C71&PID_C004", # Apex - }) - driverRegistrar.addBluetoothDevices(lambda m: ( - any( - first <= m.deviceInfo.get("bluetoothAddress", 0) <= last - for first, last in ( - (0x0025EC000000, 0x0025EC01869F), # Apex - ) - ) - or m.id.startswith("Braillenote") - )) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.SERIAL, { + "VID_1C71&PID_C004", # Apex + }, + ) + driverRegistrar.addBluetoothDevices( + lambda m: ( + any( + first <= m.deviceInfo.get("bluetoothAddress", 0) <= last + for first, last in ( + (0x0025EC000000, 0x0025EC01869F), # Apex + ) + ) + or m.id.startswith("Braillenote") + ), + ) @classmethod def getManualPorts(cls): @@ -206,7 +210,7 @@ def _dispatch( self, command: int, arg: int, - arg2: Optional[str] = None + arg2: Optional[str] = None, ): space = False if command == THUMB_KEYS_TAG: @@ -248,24 +252,24 @@ def display(self, cells: List[int]): "braille_nextLine": ("br(braillenote):tnext",), "braille_routeTo": ("br(braillenote):routing",), "braille_toggleTether": ("br(braillenote):tprevious+tnext",), - "kb:upArrow": ("br(braillenote):space+d1", "br(braillenote):wUp", "br(braillenote):upArrow",), - "kb:downArrow": ("br(braillenote):space+d4", "br(braillenote):wDown","br(braillenote):downArrow",), - "kb:leftArrow": ("br(braillenote):space+d3","br(braillenote):wLeft","br(braillenote):leftArrow",), - "kb:rightArrow": ("br(braillenote):space+d6","br(braillenote):wRight","br(braillenote):rightArrow",), - "kb:pageup": ("br(braillenote):space+d1+d3","br(braillenote):function+upArrow",), - "kb:pagedown": ("br(braillenote):space+d4+d6","br(braillenote):function+downArrow",), - "kb:home": ("br(braillenote):space+d1+d2","br(braillenote):function+leftArrow",), - "kb:end": ("br(braillenote):space+d4+d5","br(braillenote):function+rightArrow",), - "kb:control+home": ("br(braillenote):space+d1+d2+d3","br(braillenote):read+T",), - "kb:control+end": ("br(braillenote):space+d4+d5+d6","br(braillenote):read+B",), - "braille_enter": ("br(braillenote):space+d8","br(braillenote):wCenter","br(braillenote):enter",), - "kb:shift+tab": ("br(braillenote):space+d1+d2+d5+d6","br(braillenote):wCounterclockwise","br(braillenote):shift+tab",), - "kb:tab": ("br(braillenote):space+d2+d3+d4+d5","br(braillenote):wClockwise","br(braillenote):tab",), - "braille_eraseLastCell": ("br(braillenote):space+d7","br(braillenote):backspace",), - "showGui": ("br(braillenote):space+d1+d3+d4+d5","br(braillenote):read+N",), - "kb:windows": ("br(braillenote):space+d2+d4+d5+d6","br(braillenote):read+W",), - "kb:alt": ("br(braillenote):space+d1+d3+d4","br(braillenote):read+M",), - "toggleInputHelp": ("br(braillenote):space+d2+d3+d6","br(braillenote):read+1",), + "kb:upArrow": ("br(braillenote):space+d1", "br(braillenote):wUp", "br(braillenote):upArrow"), + "kb:downArrow": ("br(braillenote):space+d4", "br(braillenote):wDown","br(braillenote):downArrow"), + "kb:leftArrow": ("br(braillenote):space+d3","br(braillenote):wLeft","br(braillenote):leftArrow"), + "kb:rightArrow": ("br(braillenote):space+d6","br(braillenote):wRight","br(braillenote):rightArrow"), + "kb:pageup": ("br(braillenote):space+d1+d3","br(braillenote):function+upArrow"), + "kb:pagedown": ("br(braillenote):space+d4+d6","br(braillenote):function+downArrow"), + "kb:home": ("br(braillenote):space+d1+d2","br(braillenote):function+leftArrow"), + "kb:end": ("br(braillenote):space+d4+d5","br(braillenote):function+rightArrow"), + "kb:control+home": ("br(braillenote):space+d1+d2+d3","br(braillenote):read+T"), + "kb:control+end": ("br(braillenote):space+d4+d5+d6","br(braillenote):read+B"), + "braille_enter": ("br(braillenote):space+d8","br(braillenote):wCenter","br(braillenote):enter"), + "kb:shift+tab": ("br(braillenote):space+d1+d2+d5+d6","br(braillenote):wCounterclockwise","br(braillenote):shift+tab"), + "kb:tab": ("br(braillenote):space+d2+d3+d4+d5","br(braillenote):wClockwise","br(braillenote):tab"), + "braille_eraseLastCell": ("br(braillenote):space+d7","br(braillenote):backspace"), + "showGui": ("br(braillenote):space+d1+d3+d4+d5","br(braillenote):read+N"), + "kb:windows": ("br(braillenote):space+d2+d4+d5+d6","br(braillenote):read+W"), + "kb:alt": ("br(braillenote):space+d1+d3+d4","br(braillenote):read+M"), + "toggleInputHelp": ("br(braillenote):space+d2+d3+d6","br(braillenote):read+1"), }, }) @@ -280,7 +284,7 @@ def __init__( routing: Optional[int] = None, wheel: Optional[int] = None, qtMod: Optional[int] = None, - qtData:Optional[str] = None + qtData:Optional[str] = None, ): super(braille.BrailleDisplayGesture, self).__init__() # Denotes if we're dealing with a QT model. diff --git a/source/brailleDisplayDrivers/brailliantB.py b/source/brailleDisplayDrivers/brailliantB.py index 617b81228a3..41667d85393 100644 --- a/source/brailleDisplayDrivers/brailliantB.py +++ b/source/brailleDisplayDrivers/brailliantB.py @@ -87,22 +87,26 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver): @classmethod def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): - driverRegistrar.addUsbDevices(bdDetect.DeviceType.HID, { - "VID_1C71&PID_C111", # Mantis Q 40 - "VID_1C71&PID_C101", # Chameleon 20 - "VID_1C71&PID_C121", # Humanware BrailleOne 20 HID - "VID_1C71&PID_CE01", # NLS eReader 20 HID - "VID_1C71&PID_C006", # Brailliant BI 32, 40 and 80 - "VID_1C71&PID_C022", # Brailliant BI 14 - "VID_1C71&PID_C131", # Brailliant BI 40X - "VID_1C71&PID_C141", # Brailliant BI 20X - "VID_1C71&PID_C00A", # BrailleNote Touch - "VID_1C71&PID_C00E", # BrailleNote Touch v2 - }) - driverRegistrar.addUsbDevices(bdDetect.DeviceType.SERIAL, { - "VID_1C71&PID_C005", # Brailliant BI 32, 40 and 80 - "VID_1C71&PID_C021", # Brailliant BI 14 - }) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.HID, { + "VID_1C71&PID_C111", # Mantis Q 40 + "VID_1C71&PID_C101", # Chameleon 20 + "VID_1C71&PID_C121", # Humanware BrailleOne 20 HID + "VID_1C71&PID_CE01", # NLS eReader 20 HID + "VID_1C71&PID_C006", # Brailliant BI 32, 40 and 80 + "VID_1C71&PID_C022", # Brailliant BI 14 + "VID_1C71&PID_C131", # Brailliant BI 40X + "VID_1C71&PID_C141", # Brailliant BI 20X + "VID_1C71&PID_C00A", # BrailleNote Touch + "VID_1C71&PID_C00E", # BrailleNote Touch v2 + }, + ) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.SERIAL, { + "VID_1C71&PID_C005", # Brailliant BI 32, 40 and 80 + "VID_1C71&PID_C021", # Brailliant BI 14 + }, + ) driverRegistrar.addBluetoothDevices( lambda m: ( m.type == bdDetect.DeviceType.SERIAL @@ -125,7 +129,7 @@ def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): "Brailliant BI 40X", "Brailliant BI 20X", ) - ) + ), ) @classmethod @@ -158,8 +162,11 @@ def __init__(self, port="auto"): break # Success! if self.numCells: # A display responded. - log.info("Found display with {cells} cells connected via {type} ({port})".format( - cells=self.numCells, type=portType, port=port)) + log.info( + "Found display with {cells} cells connected via {type} ({port})".format( + cells=self.numCells, type=portType, port=port, + ), + ) break # This device can't be initialized. Move on to the next (if any). self._dev.close() @@ -203,7 +210,7 @@ def _serSendMessage(self, msgId: bytes, payload: Union[bytes, int, bool] = b""): HEADER, msgId, intToByte(len(payload)), - payload + payload, ]) self._dev.write(data) @@ -275,7 +282,7 @@ def display(self, cells: List[int]): HR_BRAILLE, # id b"\x01\x00", # Module 1, offset 0 intToByte(self.numCells), # length - cellBytes + cellBytes, ]) #: Humanware HID devices require the use of HidD_SetOutputReport when # sending data to the device via HID, as WriteFile seems to block forever diff --git a/source/brailleDisplayDrivers/brltty.py b/source/brailleDisplayDrivers/brltty.py index ea6b50a6c9d..f4bba4d07d0 100644 --- a/source/brailleDisplayDrivers/brltty.py +++ b/source/brailleDisplayDrivers/brltty.py @@ -114,7 +114,7 @@ def _onKeyPress(self, key): if keyType == brlapi.KEY_TYPE_CMD: try: inputCore.manager.executeGesture( - InputGesture(self.driverName, command, argument) + InputGesture(self.driverName, command, argument), ) except inputCore.NoInputGestureAction: pass @@ -133,7 +133,7 @@ def _onKeyPress(self, key): "dateTime": ("br(brltty):time",), "review_currentLine": ("br(brltty):say_line",), "review_sayAll": ("br(brltty):say_below",), - } + }, }) class InputGesture(braille.BrailleDisplayGesture): diff --git a/source/brailleDisplayDrivers/ecoBraille.py b/source/brailleDisplayDrivers/ecoBraille.py index a29fff991f2..f108d26840f 100644 --- a/source/brailleDisplayDrivers/ecoBraille.py +++ b/source/brailleDisplayDrivers/ecoBraille.py @@ -58,7 +58,7 @@ ECO_KEY_DOWN: "T5", ECO_KEY_RIGHT: "T4", ECO_KEY_POINT: "T3", - ECO_KEY_LEFT: "T2" + ECO_KEY_LEFT: "T2", } class ecoTypes: @@ -143,7 +143,7 @@ def eco_in(dev: serial.Serial) -> int: 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC, 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD, 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE, - 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF + 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF, ] @@ -259,7 +259,7 @@ def _handleResponse(self, command: int): "navigatorObject_moveFocus": "br(ecoBraille):F9", "navigatorObject_currentDimensions": "br(ecoBraille):F0", "braille_toggleTether": "br(ecoBraille):A", - } + }, }) diff --git a/source/brailleDisplayDrivers/eurobraille/constants.py b/source/brailleDisplayDrivers/eurobraille/constants.py index 2001ee78a97..205573670e5 100644 --- a/source/brailleDisplayDrivers/eurobraille/constants.py +++ b/source/brailleDisplayDrivers/eurobraille/constants.py @@ -56,7 +56,7 @@ 0x2000000: "joystick2Down", 0x4000000: "joystick2Right", 0x8000000: "joystick2Left", - 0x10000000: "joystick2Center" + 0x10000000: "joystick2Center", }) KEYS_ESYS: Dict[int, str] = OrderedDict({ 0x01: "switch1Right", @@ -124,5 +124,5 @@ 0x12: "bnote", 0x13: "bnote 2", 0x14: "bbook", - 0x15: "bbook 2" + 0x15: "bbook 2", } diff --git a/source/brailleDisplayDrivers/eurobraille/driver.py b/source/brailleDisplayDrivers/eurobraille/driver.py index b46686ec18a..3ede7823e6a 100644 --- a/source/brailleDisplayDrivers/eurobraille/driver.py +++ b/source/brailleDisplayDrivers/eurobraille/driver.py @@ -46,31 +46,35 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): @classmethod def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): - driverRegistrar.addUsbDevices(bdDetect.DeviceType.HID, { - "VID_C251&PID_1122", # Esys (version < 3.0, no SD card - "VID_C251&PID_1123", # Esys (version >= 3.0, with HID keyboard, no SD card - "VID_C251&PID_1124", # Esys (version < 3.0, with SD card - "VID_C251&PID_1125", # Esys (version >= 3.0, with HID keyboard, with SD card - "VID_C251&PID_1126", # Esys (version >= 3.0, no SD card - "VID_C251&PID_1127", # Reserved - "VID_C251&PID_1128", # Esys (version >= 3.0, with SD card - "VID_C251&PID_1129", # Reserved - "VID_C251&PID_112A", # Reserved - "VID_C251&PID_112B", # Reserved - "VID_C251&PID_112C", # Reserved - "VID_C251&PID_112D", # Reserved - "VID_C251&PID_112E", # Reserved - "VID_C251&PID_112F", # Reserved - "VID_C251&PID_1130", # Esytime - "VID_C251&PID_1131", # Reserved - "VID_C251&PID_1132", # Reserved - }) - driverRegistrar.addUsbDevices(bdDetect.DeviceType.SERIAL, { - "VID_28AC&PID_0012", # b.note - "VID_28AC&PID_0013", # b.note 2 - "VID_28AC&PID_0020", # b.book internal - "VID_28AC&PID_0021", # b.book external - }) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.HID, { + "VID_C251&PID_1122", # Esys (version < 3.0, no SD card + "VID_C251&PID_1123", # Esys (version >= 3.0, with HID keyboard, no SD card + "VID_C251&PID_1124", # Esys (version < 3.0, with SD card + "VID_C251&PID_1125", # Esys (version >= 3.0, with HID keyboard, with SD card + "VID_C251&PID_1126", # Esys (version >= 3.0, no SD card + "VID_C251&PID_1127", # Reserved + "VID_C251&PID_1128", # Esys (version >= 3.0, with SD card + "VID_C251&PID_1129", # Reserved + "VID_C251&PID_112A", # Reserved + "VID_C251&PID_112B", # Reserved + "VID_C251&PID_112C", # Reserved + "VID_C251&PID_112D", # Reserved + "VID_C251&PID_112E", # Reserved + "VID_C251&PID_112F", # Reserved + "VID_C251&PID_1130", # Esytime + "VID_C251&PID_1131", # Reserved + "VID_C251&PID_1132", # Reserved + }, + ) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.SERIAL, { + "VID_28AC&PID_0012", # b.note + "VID_28AC&PID_0013", # b.note 2 + "VID_28AC&PID_0020", # b.book internal + "VID_28AC&PID_0021", # b.book external + }, + ) driverRegistrar.addBluetoothDevices(lambda m: m.id.startswith("Esys")) @@ -100,7 +104,7 @@ def __init__(self, port="Auto"): port, onReceive=self._onReceive, # Eurobraille wants us not to block other application's access to this handle. - exclusive=False + exclusive=False, ) else: self._dev = hwIo.Serial( @@ -111,7 +115,7 @@ def __init__(self, port="Auto"): stopbits=serial.STOPBITS_ONE, timeout=self.timeout, writeTimeout=self.timeout, - onReceive=self._onReceive + onReceive=self._onReceive, ) except EnvironmentError: log.debugWarning(f"Error while connecting to port {port}", exc_info=True) @@ -130,8 +134,11 @@ def __init__(self, port="Auto"): break if self.numCells and self.deviceType: # A display responded. - log.info("Found {device} connected via {type} ({port})".format( - device=self.deviceType, type=portType, port=port)) + log.info( + "Found {device} connected via {type} ({port})".format( + device=self.deviceType, type=portType, port=port, + ), + ) if self.deviceType.startswith(("bnote", "bbook")): # send identifier to bnote / bbook with current COM port comportNumber = f'{int(re.match(".*?([0-9]+)$", port).group(1)):02d}' @@ -163,7 +170,7 @@ def terminate(self): def _prepFirstByteStreamAndData( self, - data: bytes + data: bytes, ) -> (bytes, Union[BytesIO, hwIo.IoBase], bytes): if self.isHid: # data contains the entire packet. @@ -303,8 +310,9 @@ def _sendPacket(self, packetType: bytes, packetSubType: bytes, packetData: bytes packetType, packetSubType, packetData, - constants.ETX - ])) + constants.ETX, + ]), + ) if self.receivesAckPackets: with self._frameLock: frame = self._frame @@ -328,7 +336,7 @@ def _sendHidPacket(self, packet: bytes): hidPacket = b"".join([ b"\x00", bytesToWrite, - b"\x55" * (blockSize - len(bytesToWrite)) # padding + b"\x55" * (blockSize - len(bytesToWrite)), # padding ]) self._dev.write(hidPacket) @@ -337,7 +345,7 @@ def display(self, cells: List[int]): self._sendPacket( packetType=constants.EB_BRAILLE_DISPLAY, packetSubType=constants.EB_BRAILLE_DISPLAY_STATIC, - packetData=bytes(cells) + packetData=bytes(cells), ) def _get_hidKeyboardInput(self): @@ -347,7 +355,7 @@ def _set_hidKeyboardInput(self, state: bool): self._sendPacket( packetType=constants.EB_KEY, packetSubType=constants.EB_KEY_USB_HID_MODE, - packetData=constants.EB_TRUE if state else constants.EB_FALSE + packetData=constants.EB_TRUE if state else constants.EB_FALSE, ) for i in range(3): self._dev.waitForRead(self.timeout) diff --git a/source/brailleDisplayDrivers/eurobraille/gestures.py b/source/brailleDisplayDrivers/eurobraille/gestures.py index 099c19826de..9aab9fe1067 100644 --- a/source/brailleDisplayDrivers/eurobraille/gestures.py +++ b/source/brailleDisplayDrivers/eurobraille/gestures.py @@ -113,8 +113,8 @@ "kb:f11": ("br(eurobraille):dot1+dot3+backspace",), "kb:f12": ("br(eurobraille):dot1+dot2+dot3+backspace",), "kb:windows": ("br(eurobraille):dot1+dot2+dot4+dot5+dot6+space",), - "kb:capsLock": ("br(eurobraille):dot7+backspace", "br(eurobraille):dot8+backspace",), - "kb:numLock": ("br(eurobraille):dot3+backspace", "br(eurobraille):dot6+backspace",), + "kb:capsLock": ("br(eurobraille):dot7+backspace", "br(eurobraille):dot8+backspace"), + "kb:numLock": ("br(eurobraille):dot3+backspace", "br(eurobraille):dot6+backspace"), "braille_toggleShift": ( "br(eurobraille):dot1+dot7+space", "br(eurobraille):dot4+dot7+space", @@ -130,7 +130,7 @@ "braille_toggleAlt": ( "br(eurobraille):dot1+dot8+space", "br(eurobraille):dot4+dot8+space", - "br(eurobraille):l6" + "br(eurobraille):l6", ), "kb:alt": ("br(eurobraille):dot8+space"), "braille_toggleNVDAKey": ("br(eurobraille):l7", "br(eurobraille):dot3+dot5+space"), diff --git a/source/brailleDisplayDrivers/freedomScientific.py b/source/brailleDisplayDrivers/freedomScientific.py index b300cd4967c..f10d4649785 100755 --- a/source/brailleDisplayDrivers/freedomScientific.py +++ b/source/brailleDisplayDrivers/freedomScientific.py @@ -43,7 +43,7 @@ # beginning/end of the display are used as status cells, and an extra blank cell to separate status # from normal cells. These devices require a special translation table: L{FOCUS_1_TRANSLATION_TABLE} # This line of displays is known as the first generation Focus displays. -FOCUS_1_CELL_COUNTS = (44, 70, 84,) +FOCUS_1_CELL_COUNTS = (44, 70, 84) # Packet types #: Query the display for information such as manufacturer, model and firmware version @@ -148,7 +148,7 @@ def _translate(cells, translationTable): #: Dots table used by first generation Focus displays FOCUS_1_DOTS_TABLE = [ - 0X01, 0X02, 0X04, 0X10, 0X20, 0X40, 0X08, 0X80 + 0X01, 0X02, 0X04, 0X10, 0X20, 0X40, 0X08, 0X80, ] #: Braille translation table used by first generation Focus displays @@ -170,32 +170,40 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): wizWheelActions = [ # Translators: The name of a key on a braille display, that scrolls the display # to show previous/next part of a long line. - (_("display scroll"), ("globalCommands", "GlobalCommands", "braille_scrollBack"), - ("globalCommands", "GlobalCommands", "braille_scrollForward")), + ( + _("display scroll"), ("globalCommands", "GlobalCommands", "braille_scrollBack"), + ("globalCommands", "GlobalCommands", "braille_scrollForward"), + ), # Translators: The name of a key on a braille display, that scrolls the display to show the next/previous line. - (_("line scroll"), ("globalCommands", "GlobalCommands", "braille_previousLine"), - ("globalCommands", "GlobalCommands", "braille_nextLine")), + ( + _("line scroll"), ("globalCommands", "GlobalCommands", "braille_previousLine"), + ("globalCommands", "GlobalCommands", "braille_nextLine"), + ), ] @classmethod def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): - driverRegistrar.addUsbDevices(bdDetect.DeviceType.CUSTOM, { - "VID_0F4E&PID_0100", # Focus 1 - "VID_0F4E&PID_0111", # PAC Mate - "VID_0F4E&PID_0112", # Focus 2 - "VID_0F4E&PID_0114", # Focus Blue - }) - - driverRegistrar.addBluetoothDevices(lambda m: ( - any( - m.id.startswith(prefix) - for prefix in ( - "F14", "Focus 14 BT", - "Focus 40 BT", - "Focus 80 BT", - ) - ) - )) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.CUSTOM, { + "VID_0F4E&PID_0100", # Focus 1 + "VID_0F4E&PID_0111", # PAC Mate + "VID_0F4E&PID_0112", # Focus 2 + "VID_0F4E&PID_0114", # Focus Blue + }, + ) + + driverRegistrar.addBluetoothDevices( + lambda m: ( + any( + m.id.startswith(prefix) + for prefix in ( + "F14", "Focus 14 BT", + "Focus 40 BT", + "Focus 80 BT", + ) + ) + ), + ) def __init__(self, port="auto"): self.numCells = 0 @@ -228,7 +236,7 @@ def __init__(self, port="auto"): epOut=0, onReceive=self._onReceive, onReceiveSize=56, - onReadError=self._handleReadError + onReadError=self._handleReadError, ) else: self._dev = hwIo.Serial( @@ -237,7 +245,7 @@ def __init__(self, port="auto"): parity=PARITY, timeout=self.timeout, writeTimeout=self.timeout, - onReceive=self._onReceive + onReceive=self._onReceive, ) except EnvironmentError: log.debugWarning("", exc_info=True) @@ -252,8 +260,11 @@ def __init__(self, port="auto"): if self.numCells and self._model: # A display responded. - log.info("Found {device} connected via {type} ({port})".format( - device=self._model, type=portType, port=port)) + log.info( + "Found {device} connected via {type} ({port})".format( + device=self._model, type=portType, port=port, + ), + ) break self._dev.close() @@ -261,10 +272,14 @@ def __init__(self, port="auto"): raise RuntimeError("No Freedom Scientific display found") self._configureDisplay() - self.gestureMap.add("br(freedomScientific):topRouting1", - "globalCommands", "GlobalCommands", "braille_scrollBack") - self.gestureMap.add("br(freedomScientific):topRouting%d" % self.numCells, - "globalCommands", "GlobalCommands", "braille_scrollForward") + self.gestureMap.add( + "br(freedomScientific):topRouting1", + "globalCommands", "GlobalCommands", "braille_scrollBack", + ) + self.gestureMap.add( + "br(freedomScientific):topRouting%d" % self.numCells, + "globalCommands", "GlobalCommands", "braille_scrollForward", + ) self._restarting = False def terminate(self): @@ -281,7 +296,7 @@ def _sendPacket( arg1: bytes = FS_BYTE_NULL, arg2: bytes = FS_BYTE_NULL, arg3: bytes = FS_BYTE_NULL, - data: bytes = FS_DATA_EMPTY + data: bytes = FS_DATA_EMPTY, ): """Send a packet to the display @param packetType: Type of packet (first byte), use one of the FS_PKT constants @@ -330,7 +345,7 @@ def _onReceive(self, data: bytes): payload: bytes = data.read(length) checksum: int = ord(data.read(1)) calculatedChecksum = BrailleDisplayDriver._calculateChecksum( - packetType + arg1 + arg2 + arg3 + payload + packetType + arg1 + arg2 + arg3 + payload, ) assert calculatedChecksum == checksum, "Checksum mismatch, expected %s but got %s" % (checksum, payload[-1]) else: @@ -350,7 +365,7 @@ def _handleReadError(self, error: int) -> bool: return False def _handlePacket( - self, packetType: bytes, arg1: bytes, arg2: bytes, arg3: bytes, payload: bytes + self, packetType: bytes, arg1: bytes, arg2: bytes, arg3: bytes, payload: bytes, ): """Handle a packet from the device" @@ -386,15 +401,15 @@ def _handlePacket( self._handleAck() elif packetType == FS_PKT_INFO: manuBytes = payload[INFO_MANU_START:INFO_MANU_END].replace( - FS_BYTE_NULL, b"" + FS_BYTE_NULL, b"", ) self._manufacturer = manuBytes.decode() modelBytes = payload[INFO_MODEL_START:INFO_MODEL_END].replace( - FS_BYTE_NULL, b"" + FS_BYTE_NULL, b"", ) self._model = modelBytes.decode() firmwareBytes = payload[INFO_VERSION_START:INFO_VERSION_END].replace( - FS_BYTE_NULL, b"" + FS_BYTE_NULL, b"", ) self._firmwareVersion = firmwareBytes.decode() self.numCells = MODELS.get(self._model, 0) @@ -403,7 +418,7 @@ def _handlePacket( self.translationTable = FOCUS_1_TRANSLATION_TABLE log.debug( "Device info: manufacturer: %s model: %s, version: %s", - self._manufacturer, self._model, self._firmwareVersion + self._manufacturer, self._model, self._firmwareVersion, ) elif packetType == FS_PKT_WHEEL: threeLeastSigBitsMask = 0x7 @@ -416,7 +431,7 @@ def _handlePacket( (False, False), (True, False), (True, True), - (False, True) + (False, True), ][wheelNumber] except IndexError: log.debugWarning("wheelNumber unknown") @@ -529,7 +544,7 @@ def display(self, cells: List[int]): intToByte(self.numCells), FS_BYTE_NULL, FS_BYTE_NULL, - bytes(cells) + bytes(cells), ) self._pendingCells = [] else: @@ -541,8 +556,10 @@ def _configureDisplay(self): return if self._model.startswith("Focus") and ord(self._firmwareVersion[0]) >= ord("3"): # Focus 2 or later. Make sure extended keys support is enabled. - log.debug("Activating extended keys on freedom Scientific display. Display name: %s, firmware version: %s.", - self._model, self._firmwareVersion) + log.debug( + "Activating extended keys on freedom Scientific display. Display name: %s, firmware version: %s.", + self._model, self._firmwareVersion, + ) self._sendPacket(FS_PKT_CONFIG, FS_CFG_EXTKEY) def script_toggleLeftWizWheelAction(self, _gesture): @@ -569,13 +586,17 @@ def script_toggleRightWizWheelAction(self, _gesture): gestureMap = inputCore.GlobalGestureMap({ "globalCommands.GlobalCommands": { "braille_routeTo": ("br(freedomScientific):routing",), - "braille_scrollBack": ("br(freedomScientific):leftAdvanceBar", - "br(freedomScientific):leftBumperBarUp", "br(freedomScientific):rightBumperBarUp",), - "braille_scrollForward": ("br(freedomScientific):rightAdvanceBar", - "br(freedomScientific):leftBumperBarDown", "br(freedomScientific):rightBumperBarDown",), + "braille_scrollBack": ( + "br(freedomScientific):leftAdvanceBar", + "br(freedomScientific):leftBumperBarUp", "br(freedomScientific):rightBumperBarUp", + ), + "braille_scrollForward": ( + "br(freedomScientific):rightAdvanceBar", + "br(freedomScientific):leftBumperBarDown", "br(freedomScientific):rightBumperBarDown", + ), "braille_previousLine": - ("br(freedomScientific):leftRockerBarUp", "br(freedomScientific):rightRockerBarUp",), - "braille_nextLine": ("br(freedomScientific):leftRockerBarDown", "br(freedomScientific):rightRockerBarDown",), + ("br(freedomScientific):leftRockerBarUp", "br(freedomScientific):rightRockerBarUp"), + "braille_nextLine": ("br(freedomScientific):leftRockerBarDown", "br(freedomScientific):rightRockerBarDown"), "kb:shift+tab": ("br(freedomScientific):dot1+dot2+brailleSpaceBar",), "kb:tab": ("br(freedomScientific):dot4+dot5+brailleSpaceBar",), "kb:upArrow": ("br(freedomScientific):dot1+brailleSpaceBar",), @@ -610,7 +631,7 @@ def script_toggleRightWizWheelAction(self, _gesture): "braille_toggleNVDAKeyShift": ("br(freedomscientific):dot5+dot7+dot8+brailleSpaceBar",), "braille_toggleControlAlt": ("br(freedomscientific):dot3+dot6+dot8+brailleSpaceBar",), "braille_toggleControlAltShift": ("br(freedomscientific):dot3+dot6+dot7+dot8+brailleSpaceBar",), - } + }, }) # pylint: disable=abstract-method diff --git a/source/brailleDisplayDrivers/handyTech.py b/source/brailleDisplayDrivers/handyTech.py index 28aa7964c6a..bcc6356bb60 100644 --- a/source/brailleDisplayDrivers/handyTech.py +++ b/source/brailleDisplayDrivers/handyTech.py @@ -55,13 +55,13 @@ def windowProc(self, hwnd: int, msg: int, wParam: int, lParam: int): instanceCount = len(BrailleDisplayDriver._instances) if instanceCount == 0: log.error( - "Received Handy_Tech_Server window message while no driver instances are alive" + "Received Handy_Tech_Server window message while no driver instances are alive", ) wx.CallAfter(BrailleDisplayDriver.destroyMessageWindow) elif wParam == self.HT_SLEEP: if instanceCount > 1: log.error( - "Received Handy_Tech_Server window message while multiple driver instances are alive" + "Received Handy_Tech_Server window message while multiple driver instances are alive", ) driver = next(d for d in BrailleDisplayDriver._instances) if lParam == self.HT_INCREMENT: @@ -142,7 +142,7 @@ def windowProc(self, hwnd: int, msg: int, wParam: int, lParam: int): } # Considered spaces in braille input mode -KEY_SPACES = (KEY_LEFT_SPACE, KEY_RIGHT_SPACE,) +KEY_SPACES = (KEY_LEFT_SPACE, KEY_RIGHT_SPACE) class Model(AutoPropertyObject): @@ -238,7 +238,7 @@ def display(self, cells: List[int]): cellBytes: bytes = bytes(cells) self._display.sendExtendedPacket( HT_EXTPKT_BRAILLE, - cellBytes + cellBytes, ) class OldProtocolMixin(object): @@ -284,7 +284,7 @@ def handleTime(self, timeBytes: bytes): day=timeBytes[3], hour=timeBytes[4], minute=timeBytes[5], - second=timeBytes[6] + second=timeBytes[6], ) except ValueError: log.debugWarning("Invalid time/date of Handy Tech display: %r" % timeBytes) @@ -302,7 +302,7 @@ def syncTime(self, dt: datetime.datetime): timeList: List[int] = [ dt.year & 0xFF, dt.year >> 8, dt.month, dt.day, - dt.hour, dt.minute, dt.second + dt.hour, dt.minute, dt.second, ] timeBytes = bytes(timeList) self._display.sendExtendedPacket(HT_EXTPKT_SET_RTC, timeBytes) @@ -476,10 +476,12 @@ def _get_name(self): def basicBrailleFactory(numCells, deviceId): - return type("BasicBraille{cells}".format(cells=numCells), (BasicBraille,), { - "deviceId": deviceId, - "numCells": numCells, - }) + return type( + "BasicBraille{cells}".format(cells=numCells), (BasicBraille,), { + "deviceId": deviceId, + "numCells": numCells, + }, + ) BasicBraille16 = basicBrailleFactory(16, MODEL_BASIC_BRAILLE_16) BasicBraille20 = basicBrailleFactory(20, MODEL_BASIC_BRAILLE_20) @@ -493,10 +495,12 @@ def basicBrailleFactory(numCells, deviceId): def basicBraillePlusFactory(numCells, deviceId): - return type("BasicBraillePlus{cells}".format(cells=numCells), (BasicBraillePlus,), { - "deviceId": deviceId, - "numCells": numCells, - }) + return type( + "BasicBraillePlus{cells}".format(cells=numCells), (BasicBraillePlus,), { + "deviceId": deviceId, + "numCells": numCells, + }, + ) BasicBraillePlus32 = basicBraillePlusFactory(32, MODEL_BASIC_BRAILLE_PLUS_32) @@ -548,7 +552,7 @@ class Activator( AtcMixin, JoystickMixin, TripleActionKeysMixin, - Model + Model, ): deviceId = MODEL_ACTIVATOR numCells = 40 @@ -568,7 +572,7 @@ class ActivatorPro( TimeSyncFirmnessMixin, AtcMixin, TripleActionKeysMixin, - Model + Model, ): genericName = 'Activator Pro' @@ -603,8 +607,10 @@ def _allSubclasses(cls): @type cls: class @rtype: [class] """ - return cls.__subclasses__() + [g for s in cls.__subclasses__() - for g in _allSubclasses(s)] + return cls.__subclasses__() + [ + g for s in cls.__subclasses__() + for g in _allSubclasses(s) + ] # Model dict for easy lookup MODELS = { @@ -665,52 +671,62 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver, ScriptableObject): @classmethod def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): - driverRegistrar.addUsbDevices(bdDetect.DeviceType.SERIAL, { - "VID_0403&PID_6001", # FTDI chip - "VID_0921&PID_1200", # GoHubs chip - }) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.SERIAL, { + "VID_0403&PID_6001", # FTDI chip + "VID_0921&PID_1200", # GoHubs chip + }, + ) # Newer Handy Tech displays have a native HID processor - driverRegistrar.addUsbDevices(bdDetect.DeviceType.HID, { - "VID_1FE4&PID_0054", # Active Braille - "VID_1FE4&PID_0055", # Connect Braille - "VID_1FE4&PID_0061", # Actilino - "VID_1FE4&PID_0064", # Active Star 40 - "VID_1FE4&PID_0081", # Basic Braille 16 - "VID_1FE4&PID_0082", # Basic Braille 20 - "VID_1FE4&PID_0083", # Basic Braille 32 - "VID_1FE4&PID_0084", # Basic Braille 40 - "VID_1FE4&PID_008A", # Basic Braille 48 - "VID_1FE4&PID_0086", # Basic Braille 64 - "VID_1FE4&PID_0087", # Basic Braille 80 - "VID_1FE4&PID_008B", # Basic Braille 160 - "VID_1FE4&PID_008C", # Basic Braille 84 - "VID_1FE4&PID_0093", # Basic Braille Plus 32 - "VID_1FE4&PID_0094", # Basic Braille Plus 40 - "VID_1FE4&PID_00A4", # Activator - "VID_1FE4&PID_00A6", # Activator Pro 64 - "VID_1FE4&PID_00A8", # Activator Pro 80 - }) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.HID, { + "VID_1FE4&PID_0054", # Active Braille + "VID_1FE4&PID_0055", # Connect Braille + "VID_1FE4&PID_0061", # Actilino + "VID_1FE4&PID_0064", # Active Star 40 + "VID_1FE4&PID_0081", # Basic Braille 16 + "VID_1FE4&PID_0082", # Basic Braille 20 + "VID_1FE4&PID_0083", # Basic Braille 32 + "VID_1FE4&PID_0084", # Basic Braille 40 + "VID_1FE4&PID_008A", # Basic Braille 48 + "VID_1FE4&PID_0086", # Basic Braille 64 + "VID_1FE4&PID_0087", # Basic Braille 80 + "VID_1FE4&PID_008B", # Basic Braille 160 + "VID_1FE4&PID_008C", # Basic Braille 84 + "VID_1FE4&PID_0093", # Basic Braille Plus 32 + "VID_1FE4&PID_0094", # Basic Braille Plus 40 + "VID_1FE4&PID_00A4", # Activator + "VID_1FE4&PID_00A6", # Activator Pro 64 + "VID_1FE4&PID_00A8", # Activator Pro 80 + }, + ) # Some older HT displays use a HID converter and an internal serial interface - driverRegistrar.addUsbDevices(bdDetect.DeviceType.HID, { - "VID_1FE4&PID_0003", # USB-HID adapter - "VID_1FE4&PID_0074", # Braille Star 40 - "VID_1FE4&PID_0044", # Easy Braille - }) - - driverRegistrar.addBluetoothDevices(lambda m: any(m.id.startswith(prefix) for prefix in ( - "Actilino AL", - "Active Braille AB", - "Active Star AS", - "Basic Braille BB", - "Basic Braille Plus BP", - "Braille Star 40 BS", - "Braillino BL", - "Braille Wave BW", - "Easy Braille EBR", - "Activator", - ))) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.HID, { + "VID_1FE4&PID_0003", # USB-HID adapter + "VID_1FE4&PID_0074", # Braille Star 40 + "VID_1FE4&PID_0044", # Easy Braille + }, + ) + + driverRegistrar.addBluetoothDevices( + lambda m: any( + m.id.startswith(prefix) for prefix in ( + "Actilino AL", + "Active Braille AB", + "Active Star AS", + "Basic Braille BB", + "Basic Braille Plus BP", + "Braille Star 40 BS", + "Braillino BL", + "Braille Wave BW", + "Easy Braille EBR", + "Activator", + ) + ), + ) @classmethod def getManualPorts(cls): @@ -750,8 +766,10 @@ def __init__(self, port="auto"): elif self.isHid: self._dev = hwIo.Hid(port, onReceive=self._hidOnReceive) else: - self._dev = hwIo.Serial(port, baudrate=BAUD_RATE, parity=PARITY, - timeout=self.timeout, writeTimeout=self.timeout, onReceive=self._serialOnReceive) + self._dev = hwIo.Serial( + port, baudrate=BAUD_RATE, parity=PARITY, + timeout=self.timeout, writeTimeout=self.timeout, onReceive=self._serialOnReceive, + ) except EnvironmentError: log.debugWarning("", exc_info=True) continue @@ -769,8 +787,11 @@ def __init__(self, port="auto"): self.sendExtendedPacket(HT_EXTPKT_GET_PROTOCOL_PROPERTIES) self._dev.waitForRead(self.timeout) self._model.postInit() - log.info("Found {device} connected via {type} ({port})".format( - device=self._model.name, type=portType, port=port)) + log.info( + "Found {device} connected via {type} ({port})".format( + device=self._model.name, type=portType, port=port, + ), + ) # Create the message window on the ui thread. wx.CallAfter(self.createMessageWindow) break @@ -828,8 +849,10 @@ def wakeUp(self): elif self.isHid: self._dev = hwIo.Hid(self.port, onReceive=self._hidOnReceive) else: - self._dev = hwIo.Serial(self.port, baudrate=BAUD_RATE, parity=PARITY, - timeout=self.timeout, writeTimeout=self.timeout, onReceive=self._serialOnReceive) + self._dev = hwIo.Serial( + self.port, baudrate=BAUD_RATE, parity=PARITY, + timeout=self.timeout, writeTimeout=self.timeout, onReceive=self._serialOnReceive, + ) def terminate(self): try: @@ -899,7 +922,7 @@ def sendExtendedPacket(self, packetType: bytes, data: bytes = b""): intToByte(len(data) + len(packetType)), packetType, data, - b"\x16" + b"\x16", ]) if self._model: packetBytes = self._model.deviceId + packetBytes @@ -922,7 +945,8 @@ def _handleKeyRelease(self): # The first key released executes the key combination. try: inputCore.manager.executeGesture( - InputGesture(self._model, self._keysDown, self.brailleInput)) + InputGesture(self._model, self._keysDown, self.brailleInput), + ) except inputCore.NoInputGestureAction: pass # Any further releases are just the rest of the keys in the combination @@ -985,7 +1009,8 @@ def _handleInputStream(self, htPacketType: bytes, stream): if modelId not in MODELS: log.debugWarning("Unknown model: %r" % modelId) raise RuntimeError( - "The model with ID %r is not supported by this driver" % modelId) + "The model with ID %r is not supported by this driver" % modelId, + ) self._model = MODELS.get(modelId)(self) if htPacketType == HT_PKT_OK_WITH_LENGTH: self.numCells = ord(stream.read(1)) @@ -1029,8 +1054,10 @@ def _handleInputStream(self, htPacketType: bytes, stream): self._dotFirmness = packet[1] else: # Unknown extended packet, log it - log.debugWarning("Unhandled extended packet of type %r: %r" % - (extPacketType, packet)) + log.debugWarning( + "Unhandled extended packet of type %r: %r" % + (extPacketType, packet), + ) else: serPacketOrd = ord(htPacketType) if isinstance(self._model, OldProtocolMixin) and serPacketOrd&~KEY_RELEASE_MASK < ord(HT_PKT_EXTENDED): @@ -1085,7 +1112,8 @@ def script_toggleBrailleInput(self, _gesture): "braille_routeTo": ("br(handyTech):routing",), "braille_scrollBack": ( "br(handytech):leftSpace", "br(handytech):leftTakTop", - "br(handytech):rightTakTop", "br(handytech):b3", "br(handytech):left",), + "br(handytech):rightTakTop", "br(handytech):b3", "br(handytech):left", + ), "braille_previousLine": ("br(handytech):b4",), "braille_nextLine": ("br(handytech):b5",), "braille_scrollForward": ( diff --git a/source/brailleDisplayDrivers/hidBrailleStandard.py b/source/brailleDisplayDrivers/hidBrailleStandard.py index 4808289b9fa..c80ae653110 100644 --- a/source/brailleDisplayDrivers/hidBrailleStandard.py +++ b/source/brailleDisplayDrivers/hidBrailleStandard.py @@ -109,8 +109,11 @@ def __init__(self, port="auto"): self._cellValueCaps = cellValueCaps self.numCells = cellValueCaps.ReportCount # A display responded. - log.info("Found display with {cells} cells connected via {type} ({port})".format( - cells=self.numCells, type=portType, port=port)) + log.info( + "Found display with {cells} cells connected via {type} ({port})".format( + cells=self.numCells, type=portType, port=port, + ), + ) break # This device can't be initialized. Move on to the next (if any). self._dev.close() @@ -127,7 +130,7 @@ def _findCellValueCaps(self) -> Optional[hidpi.HIDP_VALUE_CAPS]: and valueCaps.LinkUsage == BraillePageUsageID.BRAILLE_ROW and valueCaps.u1.NotRange.Usage in ( BraillePageUsageID.EIGHT_DOT_BRAILLE_CELL, - BraillePageUsageID.SIX_DOT_BRAILLE_CELL + BraillePageUsageID.SIX_DOT_BRAILLE_CELL, ) and valueCaps.ReportCount > 0 ): @@ -201,7 +204,7 @@ def display(self, cells: List[int]): HID_USAGE_PAGE_BRAILLE, self._cellValueCaps.LinkCollection, self._cellValueCaps.u1.NotRange.Usage, - cellBytes + cellBytes, ) self._dev.write(report.data) diff --git a/source/brailleDisplayDrivers/hims.py b/source/brailleDisplayDrivers/hims.py index 14f49344624..5b060af2db2 100644 --- a/source/brailleDisplayDrivers/hims.py +++ b/source/brailleDisplayDrivers/hims.py @@ -250,34 +250,38 @@ def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): deviceTypes = { bdDetect.DeviceType.HID: ( { - "VID_045E&PID_940A" # Braille Edge3S 40 + "VID_045E&PID_940A", # Braille Edge3S 40 }, - True + True, ), bdDetect.DeviceType.CUSTOM: ( { "VID_045E&PID_930A", # Braille Sense & Smart Beetle - "VID_045E&PID_930B" # Braille EDGE 40 + "VID_045E&PID_930B", # Braille EDGE 40 }, - False + False, ), bdDetect.DeviceType.SERIAL: ( { "VID_0403&PID_6001", - "VID_1A86&PID_55D3" # Braille Edge2S 40 + "VID_1A86&PID_55D3", # Braille Edge2S 40 }, - False - ) + False, + ), } for deviceType, (ids, useAsFallback) in deviceTypes.items(): driverRegistrar.addUsbDevices(deviceType, ids, useAsFallback) - driverRegistrar.addBluetoothDevices(lambda m: any(m.id.startswith(prefix) for prefix in ( - "BrailleSense", - "BrailleEDGE", - "SmartBeetle", - ))) + driverRegistrar.addBluetoothDevices( + lambda m: any( + m.id.startswith(prefix) for prefix in ( + "BrailleSense", + "BrailleEDGE", + "SmartBeetle", + ) + ), + ) @classmethod def getManualPorts(cls) -> Iterator[tuple[str, str]]: @@ -308,7 +312,7 @@ def __init__(self, port="auto"): parity=PARITY, timeout=self.timeout, writeTimeout=self.timeout, - onReceive=self._onReceive + onReceive=self._onReceive, ) case _: log.error(f"No matching case for portType found: {portType}") @@ -335,8 +339,11 @@ def __init__(self, port="auto"): self._sendIdentificationRequests(match) if self._model: # A display responded. - log.info("Found {device} connected via {type} ({port})".format( - device=self._model.name, type=portType, port=port)) + log.info( + "Found {device} connected via {type} ({port})".format( + device=self._model.name, type=portType, port=port, + ), + ) break self._dev.close() @@ -349,7 +356,7 @@ def display(self, cells: List[int]): if self.isHID: outputReport: bytes = b"".join([ intToByte(self.numCells), # length - cellBytes + cellBytes, ]) self._dev.setOutputReport(outputReport) @@ -401,11 +408,13 @@ def _sendIdentificationRequests(self, match: bdDetect.DeviceMatch): for modelId, cls in matchedModelsMap: log.debug("Sending request for id %r" % modelId) - self._dev.write(b"".join([ - b"\x1c", - modelId, - b"\x1f" - ])) + self._dev.write( + b"".join([ + b"\x1c", + modelId, + b"\x1f", + ]), + ) self._dev.waitForRead(self.timeout) if self._model: log.debug("%s model has been set"%self._model.name) @@ -561,7 +570,7 @@ def _sendPacket( packetType: bytes, mode: bytes, data1: bytes, - data2: bytes = b"" + data2: bytes = b"", ): d1Len = len(data1) d2Len = len(data2) @@ -628,7 +637,7 @@ def terminate(self): "globalCommands.GlobalCommands": { "braille_routeTo": ( "br(hims):routing", - ), + ), "braille_scrollBack": ( "br(hims):leftSideScrollUp", "br(hims):rightSideScrollUp", @@ -832,7 +841,7 @@ def terminate(self): "kb:alt+insert": ( "br(hims.smartbeetle):f3+rightSideScroll", ), - } + }, }) class KeyInputGesture(braille.BrailleDisplayGesture, brailleInput.BrailleInputGesture): diff --git a/source/brailleDisplayDrivers/lilli.py b/source/brailleDisplayDrivers/lilli.py index fd578ed3cad..a0acaf37236 100644 --- a/source/brailleDisplayDrivers/lilli.py +++ b/source/brailleDisplayDrivers/lilli.py @@ -26,7 +26,7 @@ "", "SF1", "SF2", "SF3", "SF4", "SF5", "SF6", "SF7", "SF8", "SF9", "SF10", "SLF", "SUP", "SRG", "SDN", "", "", "LF1", "LF2", "LF3", "LF4", "LF5", "LF6", "LF7", "LF8", "LF9", "LF10", "LLF", "LUP", "LRG", "LDN", "", "", "SLF1", "SLF2", "SLF3", "SLF4", "SLF5", "SLF6", "SLF7", "SLF8", "SLF9", "SLF10", "SLLF", "SLUP", "SLRG", "SLDN", "SFDN", "SFUP", - "route" + "route", ] ROUTE_COMMAND = "route" @@ -113,7 +113,7 @@ def display(self, cells: List[int]): "kb:tab": ("br(lilli):SRG",), "kb:alt+tab": ("br(lilli):SDN",), "kb:alt+shift+tab": ("br(lilli):SUP",), - } + }, }) class InputGesture(braille.BrailleDisplayGesture): diff --git a/source/brailleDisplayDrivers/nattiqbraille.py b/source/brailleDisplayDrivers/nattiqbraille.py index ed65c09b366..857b49bf5e3 100644 --- a/source/brailleDisplayDrivers/nattiqbraille.py +++ b/source/brailleDisplayDrivers/nattiqbraille.py @@ -38,9 +38,11 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver): @classmethod def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): - driverRegistrar.addUsbDevices(bdDetect.DeviceType.SERIAL, { - "VID_2341&PID_8036", # Atmel-based USB Serial for Nattiq nBraille - }) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.SERIAL, { + "VID_2341&PID_8036", # Atmel-based USB Serial for Nattiq nBraille + }, + ) @classmethod def getManualPorts(cls): @@ -54,7 +56,7 @@ def __init__(self, port="auto"): try: self._serial = hwIo.Serial( port, baudrate=BAUD_RATE, timeout=self.timeout, writeTimeout=self.timeout, - parity=serial.PARITY_NONE, onReceive=self._onReceive + parity=serial.PARITY_NONE, onReceive=self._onReceive, ) except EnvironmentError: log.debugWarning("", exc_info=True) diff --git a/source/brailleDisplayDrivers/papenmeier.py b/source/brailleDisplayDrivers/papenmeier.py index 10e72d96f16..6e31cc6bd50 100644 --- a/source/brailleDisplayDrivers/papenmeier.py +++ b/source/brailleDisplayDrivers/papenmeier.py @@ -48,7 +48,7 @@ def brl_auto_id() -> bytes: """send auto id command to braille display""" # device will respond with a message that allows identification of the display return bytes([ - STX, AUTOID, 0x50, 0x50, ETX + STX, AUTOID, 0x50, 0x50, ETX, ]) def _swapDotBits(d: int) -> List[int]: @@ -394,10 +394,10 @@ def _handleKeyPresses(self): "kb:control+escape": ("br(papenmeier):space+d1+d2+d3+d4+d5+d6",), "kb:control+alt+delete": ("br(papenmeier):space+d1+d2+d3+d4+d5+d6+d7+d8",), - "kb:enter": ("br(papenmeier):space+d8", "br(papenmeier):d8",), + "kb:enter": ("br(papenmeier):space+d8", "br(papenmeier):d8"), "kb:pageup": ("br(papenmeier):space+d3",), "kb:pagedown": ("br(papenmeier):space+d6",), - "kb:backspace": ("br(papenmeier):space+d6+d8", "br(papenmeier):d7",), + "kb:backspace": ("br(papenmeier):space+d6+d8", "br(papenmeier):d7"), "kb:home": ("br(papenmeier):space+d1+d2",), "kb:end": ("br(papenmeier):space+d4+d5",), "kb:delete": ("br(papenmeier):space+d5+d6",), @@ -440,7 +440,7 @@ def _handleKeyPresses(self): "kb:control+x": ("br(papenmeier):d1+d3+d4+d6+d7+d8",), "kb:control+y": ("br(papenmeier):d1+d3+d4+d5+d6+d7+d8",), "kb:control+z": ("br(papenmeier):d1+d3+d5+d6+d7+d8",), - } + }, }) def brl_decode_trio(keys: bytes)->List[int]: diff --git a/source/brailleDisplayDrivers/papenmeier_serial.py b/source/brailleDisplayDrivers/papenmeier_serial.py index 4bd9ecf9af1..e3751a37651 100644 --- a/source/brailleDisplayDrivers/papenmeier_serial.py +++ b/source/brailleDisplayDrivers/papenmeier_serial.py @@ -38,7 +38,7 @@ def brl_out(offset: int, data: List[int]) -> bytes: d2 = len(data)+7 ret = bytearray([ STX, - ord(b'S') + ord(b'S'), ]) ret.extend(offset.to_bytes(2, "big", signed=False)) ret.extend(d2.to_bytes(2, "big", signed=False)) @@ -217,7 +217,7 @@ def _handleKeyPresses(self): #called by the keycheck timer "title": ("br(papenmeier_serial):l1,up",), "reportStatusLine": ("br(papenmeier_serial):l2,dn",), - } + }, }) def brl_keyname2(keys: int) -> str: @@ -257,7 +257,7 @@ def __init__( keyindex: Optional[int], pressed: Optional[int], keys: Optional[int], - driver: BrailleDisplayDriver + driver: BrailleDisplayDriver, ): super(InputGesture, self).__init__() self.id = '' diff --git a/source/brailleDisplayDrivers/seika.py b/source/brailleDisplayDrivers/seika.py index 9da545f5118..a1537074545 100644 --- a/source/brailleDisplayDrivers/seika.py +++ b/source/brailleDisplayDrivers/seika.py @@ -51,7 +51,7 @@ def __init__(self): writeTimeout=TIMEOUT, parity=serial.PARITY_ODD, bytesize=serial.EIGHTBITS, - stopbits=serial.STOPBITS_ONE + stopbits=serial.STOPBITS_ONE, ) except serial.SerialException: continue @@ -94,7 +94,7 @@ def __init__(self): log.debug(f"receive {versionS}") if versionS.startswith(( b'\x00\x05(\x08v5.0\x01\x01\x01\x01', - b'\x00\x05(\x08seika\x00' + b'\x00\x05(\x08seika\x00', )): log.info(f"Found Seika3 old Version connected via {port} Version {versionS}") self.numCells = 40 diff --git a/source/brailleDisplayDrivers/seikantk.py b/source/brailleDisplayDrivers/seikantk.py index 215e59528d8..f25674d26b1 100644 --- a/source/brailleDisplayDrivers/seikantk.py +++ b/source/brailleDisplayDrivers/seikantk.py @@ -107,9 +107,11 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver): @classmethod def registerAutomaticDetection(cls, driverRegistrar: DriverRegistrar): - driverRegistrar.addUsbDevices(DeviceType.HID, { - vidpid, # Seika Notetaker - }) + driverRegistrar.addUsbDevices( + DeviceType.HID, { + vidpid, # Seika Notetaker + }, + ) driverRegistrar.addBluetoothDevices(isSeikaBluetoothDeviceMatch) @@ -140,7 +142,7 @@ def __init__(self, port: typing.Union[None, str, DeviceMatch]): log.info("Trying Seika notetaker on USB-HID") self._dev = dev = hwIo.Hid( path=match.port, # for a Hid match type 'port' is actually 'path'. - onReceive=self._onReceiveHID + onReceive=self._onReceiveHID, ) dev.setFeature(SEIKA_HID_FEATURES) # baud rate, stop bit usw dev.setFeature(SEIKA_CMD_ON) # device on @@ -178,7 +180,7 @@ def __init__(self, port: typing.Union[None, str, DeviceMatch]): log.info( f"Seika notetaker," f" Cells {self.numCells}" - f" Buttons {self.numBtns}" + f" Buttons {self.numBtns}", ) def _getDeviceInfo(self, dev: hwIo.IoBase) -> bool: @@ -347,7 +349,7 @@ def _handleKeysRouting(self, arg: bytes): "kb:shift+rightArrow": ("br(seikantk):SPACE+RJ_RIGHT", "br(seikantk):BACKSPACE+RJ_RIGHT"), "kb:escape": ("br(seikantk):SPACE+RJ_CENTER",), "kb:windows": ("br(seikantk):BACKSPACE+RJ_CENTER",), - "kb:space": ("br(seikantk):BACKSPACE", "br(seikantk):SPACE",), + "kb:space": ("br(seikantk):BACKSPACE", "br(seikantk):SPACE"), "kb:backspace": ("br(seikantk):d7",), "kb:pageup": ("br(seikantk):SPACE+LJ_RIGHT",), "kb:pagedown": ("br(seikantk):SPACE+LJ_LEFT",), @@ -379,7 +381,7 @@ def _getRoutingIndexes(routingKeyBytes: bytes) -> Set[int]: bitsPerByte = 8 # Convert bytes into a single bitset int combinedRoutingKeysBitSet = sum( - [value << (bitsPerByte * bitIndex) for bitIndex, value in enumerate(routingKeyBytes)] + [value << (bitsPerByte * bitIndex) for bitIndex, value in enumerate(routingKeyBytes)], ) numRoutingKeys = len(routingKeyBytes) * bitsPerByte return {i for i in range(numRoutingKeys) if (1 << i) & combinedRoutingKeysBitSet} diff --git a/source/brailleDisplayDrivers/superBrl.py b/source/brailleDisplayDrivers/superBrl.py index 16645ac8027..f86484cbee5 100644 --- a/source/brailleDisplayDrivers/superBrl.py +++ b/source/brailleDisplayDrivers/superBrl.py @@ -32,9 +32,11 @@ class BrailleDisplayDriver(braille.BrailleDisplayDriver): @classmethod def registerAutomaticDetection(cls, driverRegistrar: bdDetect.DriverRegistrar): - driverRegistrar.addUsbDevices(bdDetect.DeviceType.SERIAL, { - "VID_10C4&PID_EA60", # SuperBraille 3.2 - }) + driverRegistrar.addUsbDevices( + bdDetect.DeviceType.SERIAL, { + "VID_10C4&PID_EA60", # SuperBraille 3.2 + }, + ) @classmethod def getManualPorts(cls): @@ -84,7 +86,7 @@ def _onReceive(self, data: bytes): self.version=self._dev.read(8) def display(self, cells: List[int]): - writeBytes: List[bytes] = [DISPLAY_TAG, ] + writeBytes: List[bytes] = [DISPLAY_TAG] for cell in cells: writeBytes.append(b"\x00") writeBytes.append(intToByte(cell)) diff --git a/source/brailleInput.py b/source/brailleInput.py index 578e79f888d..482c3e6edb1 100644 --- a/source/brailleInput.py +++ b/source/brailleInput.py @@ -127,7 +127,8 @@ def _translate(self, endWord: bool) -> bool: mode |= louis.partialTrans self.bufferText = louis.backTranslate( [self._table.fileName, "braille-patterns.cti"], - data, mode=mode)[0] + data, mode=mode, + )[0] newText = self.bufferText[oldTextLen:] if newText: # New text was generated by the cells just entered. @@ -176,7 +177,8 @@ def _translateForReportContractedCell(self, pos): oldText = self.bufferText text = louis.backTranslate( [self._table.fileName, "braille-patterns.cti"], - data, mode=louis.dotsIO | louis.noUndefinedDots | louis.partialTrans)[0] + data, mode=louis.dotsIO | louis.noUndefinedDots | louis.partialTrans, + )[0] self.bufferText = text return oldText @@ -257,7 +259,8 @@ def toggleModifiers(self, modifiers: List[str]): # Check modifier validity validModifiers: bool = all( keyboardHandler.KeyboardInputGesture.fromName(m).isModifier - for m in modifiers) + for m in modifiers + ) if not validModifiers: raise ValueError("%r contains unknown modifiers" % modifiers) @@ -274,9 +277,11 @@ def toggleModifiers(self, modifiers: List[str]): speech.speakMessage(keyLabels.getKeyCombinationLabel(modifier)) for modifier in removed: # Translators: Reported when a braille input modifier is released. - speech.speakMessage(_("{modifier} released").format( - modifier=keyLabels.getKeyCombinationLabel(modifier) - )) + speech.speakMessage( + _("{modifier} released").format( + modifier=keyLabels.getKeyCombinationLabel(modifier), + ), + ) def enter(self): """Translates any braille input and presses the enter key. @@ -322,9 +327,10 @@ def eraseLastCell(self): char = self.bufferText[-1] self.bufferText = self.bufferText[:-1] region = braille.handler.mainBuffer.regions[-1] if braille.handler.mainBuffer.regions else None - if (not isinstance(region, braille.TextInfoRegion) or region.cursorPos is None - or region.rawText[region.cursorPos - 1] != char - ): + if ( + not isinstance(region, braille.TextInfoRegion) or region.cursorPos is None + or region.rawText[region.cursorPos - 1] != char + ): # The character before the cursor isn't the character we expected to erase. # The cursor must have moved between typing and erasing. # Thus, the buffer is now invalid. @@ -392,7 +398,9 @@ def sendChars(self, chars: str): inputs = [] chars = ''.join( ch if ord(ch) <= 0xffff else ''.join( - chr(x) for x in struct.unpack(">2H", ch.encode("utf-16be"))) for ch in chars) + chr(x) for x in struct.unpack(">2H", ch.encode("utf-16be")) + ) for ch in chars + ) for ch in chars: for direction in (0,winUser.KEYEVENTF_KEYUP): input = winUser.Input() @@ -449,7 +457,7 @@ def handlePostConfigProfileSwitch(self): except LookupError: log.error( f"Invalid input table ({tableName}), " - f"falling back to default ({FALLBACK_TABLE})." + f"falling back to default ({FALLBACK_TABLE}).", ) self._table = brailleTables.getTable(FALLBACK_TABLE) diff --git a/source/brailleTables.py b/source/brailleTables.py index 014e8fa670e..2613649c708 100644 --- a/source/brailleTables.py +++ b/source/brailleTables.py @@ -31,7 +31,7 @@ class TableSource(StrEnum): _tablesDirs = collections.ChainMap({ - TableSource.BUILTIN: TABLES_DIR + TableSource.BUILTIN: TABLES_DIR, }) """Chainmap of directories for braille tables lookup, including custom tables.""" @@ -75,7 +75,7 @@ def addTable( contracted: bool = False, output: bool = True, input: bool = True, - source: str = TableSource.BUILTIN + source: str = TableSource.BUILTIN, ): """Register a braille translation table. At least one of C{input} or C{output} must be C{True}. @@ -106,7 +106,7 @@ def listTables() -> list[BrailleTable]: """ return sorted( _tables.values(), - key=lambda table: (table.source != TableSource.BUILTIN, strxfrm(table.displayName)) + key=lambda table: (table.source != TableSource.BUILTIN, strxfrm(table.displayName)), ) @@ -778,7 +778,7 @@ def initialize(): except Exception: log.exception( "Error while applying custom braille tables config from scratchpad manifest: " - f"{manifestPath}" + f"{manifestPath}", ) diff --git a/source/brailleViewer/__init__.py b/source/brailleViewer/__init__.py index 21bf0f8c732..57284a96817 100644 --- a/source/brailleViewer/__init__.py +++ b/source/brailleViewer/__init__.py @@ -108,7 +108,7 @@ def createBrailleViewerTool(): _brailleGui = BrailleViewerFrame( braille.handler.displaySize, - _onGuiDestroyed + _onGuiDestroyed, ) braille.pre_writeCells.register(_brailleGui.updateBrailleDisplayed) postBrailleViewerToolToggledAction.notify(created=True) diff --git a/source/brailleViewer/brailleViewerGui.py b/source/brailleViewer/brailleViewerGui.py index 18cb15c5caa..831439a802f 100644 --- a/source/brailleViewer/brailleViewerGui.py +++ b/source/brailleViewer/brailleViewerGui.py @@ -42,7 +42,7 @@ def _getCharIndexUnderMouse(ctrl: wx.TextCtrl) -> Optional[int]: # Above: mouseY is less than windowY I.E. when 'toClient.y' < 0 # Before: mouseX is less than windowX I.E. when 'toClient.x' < 0 result, index = ctrl.HitTestPos( - toClient + toClient, ) if result == wx.TE_HT_ON_TEXT and toClient.y > 0 and toClient.x > 0: return index @@ -95,11 +95,13 @@ def update(self): # [0..1] proportion accumulatedElapsedTime is through totalTime normalisedElapsed = min(1.0, max(0.0, (0.001 + accumulatedElapsedTime) / self._durationSeconds)) colourTransitionValue = self._startValue + normalisedElapsed * (1 - self._startValue) - currentColorTuple = tuple(int(c) for c in _linearInterpolate( - colourTransitionValue, - self._originColor.Get(includeAlpha=False), - self._destColor.Get(includeAlpha=False) - )) + currentColorTuple = tuple( + int(c) for c in _linearInterpolate( + colourTransitionValue, + self._originColor.Get(includeAlpha=False), + self._destColor.Get(includeAlpha=False), + ) + ) currentStyle = createBackgroundColorTextAttr(wx.Colour(*currentColorTuple)) index = self._textCellIndex length = len(self._textCtrl.GetValue()) @@ -159,7 +161,7 @@ def startPendingHover(self, index): startValue=0.2, originColor=self._normalBGColor, destColor=wx.Colour(255, 205, 60), # orange-yellow - durationSeconds=self._secondsOfHoverToActivate + durationSeconds=self._secondsOfHoverToActivate, ) def _setPostActivateStyle(self): @@ -169,7 +171,7 @@ def _setPostActivateStyle(self): startValue=0.0, originColor=wx.Colour(81, 215, 81), # green destColor=self._normalBGColor, - durationSeconds=self._secondsOfPostActivate + durationSeconds=self._secondsOfPostActivate, ) def doHoverTracking(self): @@ -221,7 +223,7 @@ def _updateHoverStage(self): def _activateRouteToCell(self): from .brailleViewerInputGesture import BrailleViewerGesture_RouteTo inputCore.manager.executeGesture( - BrailleViewerGesture_RouteTo(self._charIndex) + BrailleViewerGesture_RouteTo(self._charIndex), ) @@ -253,7 +255,7 @@ def _setBrailleFont(fontName: str, textCtrl: wx.Control) -> wx.Font: # may start at the same time) class BrailleViewerFrame( gui.contextHelp.ContextHelpMixin, - wx.Frame # wxPython does not seem to call base class initializer, put last in MRO + wx.Frame, # wxPython does not seem to call base class initializer, put last in MRO ): helpId = "BrailleViewer" @@ -285,7 +287,7 @@ def __init__(self, numCells: int, onDestroyed: Callable[[], None]): gui.mainFrame, title=self._title, pos=dialogPos, - style=wx.CAPTION | wx.CLOSE_BOX | wx.STAY_ON_TOP + style=wx.CAPTION | wx.CLOSE_BOX | wx.STAY_ON_TOP, ) post_sessionLockStateChanged.register(self.onSessionLockStateChange) self.Bind(wx.EVT_CLOSE, self._onClose) @@ -339,7 +341,7 @@ def _createBrailleTextSizeTestCtrl(self, sizer, parent): # Use the same font so the size is accurate. _setBrailleFont( "FreeMono-FixedBraille", - self._brailleSizeTest + self._brailleSizeTest, ) # Keep the label hidden since it provides no information. @@ -365,11 +367,11 @@ def _createControls(self, sizer: wx.Sizer, parent: wx.Control) -> None: parent, value=self._brailleOutputLastSet, style=wx.TE_RICH | wx.TE_READONLY, - size=wx.Size(labelSize.x, -1) + size=wx.Size(labelSize.x, -1), ) _setBrailleFont( "FreeMono-FixedBraille", - self._brailleOutput + self._brailleOutput, ) log.debug(f"Font for braille: {self._brailleOutput.GetFont().GetNativeFontInfoUserDesc()}") sizer.Add(self._brailleOutput, flag=wx.EXPAND, proportion=1) @@ -379,11 +381,11 @@ def _createControls(self, sizer: wx.Sizer, parent: wx.Control) -> None: self._rawTextOutput = wx.TextCtrl( parent, value=self._rawTextOutputLastSet, - style=wx.TE_RICH2 | wx.TE_READONLY + style=wx.TE_RICH2 | wx.TE_READONLY, ) _setBrailleFont( "FreeMono-FixedBraille", - self._rawTextOutput + self._rawTextOutput, ) log.debug(f"Font for raw text: {self._rawTextOutput.Font.GetNativeFontInfoUserDesc()}") sizer.Add(self._rawTextOutput, flag=wx.EXPAND, proportion=1) @@ -394,7 +396,8 @@ def _createControls(self, sizer: wx.Sizer, parent: wx.Control) -> None: showOnStartupCheckboxLabel = _("&Show Braille Viewer on Startup") self._shouldShowOnStartupCheckBox = wx.CheckBox( parent=parent, - label=showOnStartupCheckboxLabel) + label=showOnStartupCheckboxLabel, + ) self._shouldShowOnStartupCheckBox.SetValue(config.conf["brailleViewer"]["showBrailleViewerAtStartup"]) self._shouldShowOnStartupCheckBox.Bind(wx.EVT_CHECKBOX, self._onShouldShowOnStartupChanged) optionsSizer.Add(self._shouldShowOnStartupCheckBox) @@ -406,7 +409,7 @@ def _createControls(self, sizer: wx.Sizer, parent: wx.Control) -> None: hoverRoutesCellText = _("&Hover for cell routing") self._shouldHoverRouteToCellCheckBox = wx.CheckBox( parent=parent, - label=hoverRoutesCellText + label=hoverRoutesCellText, ) self._shouldHoverRouteToCellCheckBox.Bind(wx.EVT_CHECKBOX, self._onShouldHoverRouteToCellCheckBoxChanged) self._shouldHoverRouteToCellCheckBox.SetValue(_shouldDoHover()) @@ -501,7 +504,7 @@ def _updateGui(self): newSize = self._brailleOutput.GetSize() log.debug( f"Updating brailleViewer cell count to: {self._newCellCount}" - f", braille label size {oldSize} -> {newSize}" + f", braille label size {oldSize} -> {newSize}", ) # Ensure that any variation in the number of characters displayed is still shown by calling `Fit`. # This should really only happen when an external display with a different cell count is connected. diff --git a/source/browseMode.py b/source/browseMode.py index fe66b81c106..3fe13d81a76 100644 --- a/source/browseMode.py +++ b/source/browseMode.py @@ -278,7 +278,7 @@ def _getLabelForProperties(self, labelPropertyGetter: Callable[[str], Optional[A controlTypes.Role.SPLITBUTTON, controlTypes.Role.MENUBUTTON, controlTypes.Role.DROPDOWNBUTTONGRID, - controlTypes.Role.TREEVIEWBUTTON + controlTypes.Role.TREEVIEWBUTTON, ): # Example output: Mute; toggle button; pressed labelParts = (content or name or unlabeled, roleText, labeledStates) @@ -328,7 +328,7 @@ def event_treeInterceptor_gainFocus(self): controlTypes.Role.TABLECELL, controlTypes.Role.TABLEROWHEADER, controlTypes.Role.TABLECOLUMNHEADER, - }) + }) SWITCH_TO_PASS_THROUGH_ON_FOCUS_ROLES = frozenset({ controlTypes.Role.LISTITEM, @@ -337,14 +337,14 @@ def event_treeInterceptor_gainFocus(self): controlTypes.Role.MENUITEM, controlTypes.Role.RADIOMENUITEM, controlTypes.Role.CHECKMENUITEM, - }) + }) IGNORE_DISABLE_PASS_THROUGH_WHEN_FOCUSED_ROLES = frozenset({ controlTypes.Role.MENUITEM, controlTypes.Role.RADIOMENUITEM, controlTypes.Role.CHECKMENUITEM, controlTypes.Role.TABLECELL, - }) + }) def shouldPassThrough(self, obj, reason: Optional[OutputReason] = None): """Determine whether pass through mode should be enabled (focus mode) or disabled (browse mode) for a given object. @@ -384,7 +384,7 @@ def shouldPassThrough(self, obj, reason: Optional[OutputReason] = None): # #5118: read-only ARIA grids should also be allowed (focusable table cells, rows and headers). if role not in ( controlTypes.Role.EDITABLETEXT, controlTypes.Role.COMBOBOX, controlTypes.Role.TABLEROW, - controlTypes.Role.TABLECELL, controlTypes.Role.TABLEROWHEADER, controlTypes.Role.TABLECOLUMNHEADER + controlTypes.Role.TABLECELL, controlTypes.Role.TABLEROWHEADER, controlTypes.Role.TABLECOLUMNHEADER, ): return False # Any roles or states for which we always switch to passThrough @@ -536,7 +536,7 @@ def addQuickNav( nextError: str, prevDoc: str, prevError: str, - readUnit: Optional[str] = None + readUnit: Optional[str] = None, ): """Adds a script for the given quick nav item. @param itemType: The type of item, I.E. "heading" "Link" ... @@ -723,264 +723,320 @@ def _get_disableAutoPassThrough(self): # Add quick navigation scripts. qn = BrowseModeTreeInterceptor.addQuickNav -qn("heading", key="h", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next heading"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next heading"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous heading"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous heading")) -qn("heading1", key="1", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next heading at level 1"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next heading at level 1"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous heading at level 1"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous heading at level 1")) -qn("heading2", key="2", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next heading at level 2"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next heading at level 2"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous heading at level 2"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous heading at level 2")) -qn("heading3", key="3", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next heading at level 3"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next heading at level 3"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous heading at level 3"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous heading at level 3")) -qn("heading4", key="4", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next heading at level 4"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next heading at level 4"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous heading at level 4"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous heading at level 4")) -qn("heading5", key="5", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next heading at level 5"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next heading at level 5"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous heading at level 5"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous heading at level 5")) -qn("heading6", key="6", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next heading at level 6"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next heading at level 6"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous heading at level 6"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous heading at level 6")) -qn("table", key="t", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next table"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next table"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous table"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous table"), - readUnit=textInfos.UNIT_LINE) -qn("link", key="k", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next link"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next link"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous link"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous link")) -qn("visitedLink", key="v", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next visited link"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next visited link"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous visited link"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous visited link")) -qn("unvisitedLink", key="u", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next unvisited link"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next unvisited link"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous unvisited link"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous unvisited link")) -qn("formField", key="f", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next form field"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next form field"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous form field"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous form field")) -qn("list", key="l", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next list"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next list"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous list"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous list"), - readUnit=textInfos.UNIT_LINE) -qn("listItem", key="i", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next list item"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next list item"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous list item"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous list item")) -qn("button", key="b", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next button"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next button"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous button"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous button")) -qn("edit", key="e", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next edit field"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next edit field"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous edit field"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous edit field"), - readUnit=textInfos.UNIT_LINE) -qn("frame", key="m", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next frame"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next frame"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous frame"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous frame"), - readUnit=textInfos.UNIT_LINE) -qn("separator", key="s", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next separator"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next separator"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous separator"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous separator")) -qn("radioButton", key="r", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next radio button"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next radio button"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous radio button"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous radio button")) -qn("comboBox", key="c", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next combo box"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next combo box"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous combo box"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous combo box")) -qn("checkBox", key="x", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next check box"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next check box"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous check box"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous check box")) -qn("graphic", key="g", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next graphic"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next graphic"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous graphic"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous graphic")) -qn("blockQuote", key="q", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next block quote"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next block quote"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous block quote"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous block quote")) -qn("notLinkBlock", key="n", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("skips forward past a block of links"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no more text after a block of links"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("skips backward past a block of links"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no more text before a block of links"), - readUnit=textInfos.UNIT_LINE) -qn("landmark", key="d", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next landmark"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next landmark"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous landmark"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous landmark"), - readUnit=textInfos.UNIT_LINE) -qn("embeddedObject", key="o", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next embedded object"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next embedded object"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous embedded object"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous embedded object")) -qn("annotation", key="a", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next annotation"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next annotation"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous annotation"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous annotation")) -qn("error", key="w", - # Translators: Input help message for a quick navigation command in browse mode. - nextDoc=_("moves to the next error"), - # Translators: Message presented when the browse mode element is not found. - nextError=_("no next error"), - # Translators: Input help message for a quick navigation command in browse mode. - prevDoc=_("moves to the previous error"), - # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous error")) +qn( + "heading", key="h", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next heading"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next heading"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous heading"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous heading"), +) +qn( + "heading1", key="1", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next heading at level 1"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next heading at level 1"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous heading at level 1"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous heading at level 1"), +) +qn( + "heading2", key="2", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next heading at level 2"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next heading at level 2"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous heading at level 2"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous heading at level 2"), +) +qn( + "heading3", key="3", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next heading at level 3"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next heading at level 3"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous heading at level 3"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous heading at level 3"), +) +qn( + "heading4", key="4", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next heading at level 4"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next heading at level 4"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous heading at level 4"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous heading at level 4"), +) +qn( + "heading5", key="5", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next heading at level 5"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next heading at level 5"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous heading at level 5"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous heading at level 5"), +) +qn( + "heading6", key="6", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next heading at level 6"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next heading at level 6"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous heading at level 6"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous heading at level 6"), +) +qn( + "table", key="t", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next table"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next table"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous table"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous table"), + readUnit=textInfos.UNIT_LINE, +) +qn( + "link", key="k", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next link"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next link"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous link"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous link"), +) +qn( + "visitedLink", key="v", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next visited link"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next visited link"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous visited link"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous visited link"), +) +qn( + "unvisitedLink", key="u", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next unvisited link"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next unvisited link"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous unvisited link"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous unvisited link"), +) +qn( + "formField", key="f", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next form field"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next form field"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous form field"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous form field"), +) +qn( + "list", key="l", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next list"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next list"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous list"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous list"), + readUnit=textInfos.UNIT_LINE, +) +qn( + "listItem", key="i", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next list item"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next list item"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous list item"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous list item"), +) +qn( + "button", key="b", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next button"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next button"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous button"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous button"), +) +qn( + "edit", key="e", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next edit field"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next edit field"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous edit field"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous edit field"), + readUnit=textInfos.UNIT_LINE, +) +qn( + "frame", key="m", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next frame"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next frame"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous frame"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous frame"), + readUnit=textInfos.UNIT_LINE, +) +qn( + "separator", key="s", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next separator"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next separator"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous separator"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous separator"), +) +qn( + "radioButton", key="r", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next radio button"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next radio button"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous radio button"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous radio button"), +) +qn( + "comboBox", key="c", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next combo box"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next combo box"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous combo box"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous combo box"), +) +qn( + "checkBox", key="x", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next check box"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next check box"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous check box"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous check box"), +) +qn( + "graphic", key="g", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next graphic"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next graphic"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous graphic"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous graphic"), +) +qn( + "blockQuote", key="q", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next block quote"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next block quote"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous block quote"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous block quote"), +) +qn( + "notLinkBlock", key="n", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("skips forward past a block of links"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no more text after a block of links"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("skips backward past a block of links"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no more text before a block of links"), + readUnit=textInfos.UNIT_LINE, +) +qn( + "landmark", key="d", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next landmark"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next landmark"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous landmark"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous landmark"), + readUnit=textInfos.UNIT_LINE, +) +qn( + "embeddedObject", key="o", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next embedded object"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next embedded object"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous embedded object"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous embedded object"), +) +qn( + "annotation", key="a", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next annotation"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next annotation"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous annotation"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous annotation"), +) +qn( + "error", key="w", + # Translators: Input help message for a quick navigation command in browse mode. + nextDoc=_("moves to the next error"), + # Translators: Message presented when the browse mode element is not found. + nextError=_("no next error"), + # Translators: Input help message for a quick navigation command in browse mode. + prevDoc=_("moves to the previous error"), + # Translators: Message presented when the browse mode element is not found. + prevError=_("no previous error"), +) qn( "article", key=None, # Translators: Input help message for a quick navigation command in browse mode. @@ -990,7 +1046,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous article"), # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous article") + prevError=_("no previous article"), ) qn( "grouping", key=None, @@ -1001,7 +1057,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous grouping"), # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous grouping") + prevError=_("no previous grouping"), ) qn( "tab", key=None, @@ -1012,7 +1068,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous tab"), # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous tab") + prevError=_("no previous tab"), ) qn( "figure", key=None, @@ -1023,7 +1079,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous figure"), # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous figure") + prevError=_("no previous figure"), ) qn( "menuItem", @@ -1035,7 +1091,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous menu item"), # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous menu item") + prevError=_("no previous menu item"), ) qn( "toggleButton", @@ -1047,7 +1103,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous toggle button"), # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous toggle button") + prevError=_("no previous toggle button"), ) qn( "progressBar", @@ -1059,7 +1115,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous progress bar"), # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous progress bar") + prevError=_("no previous progress bar"), ) qn( "math", @@ -1071,7 +1127,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous math formula"), # Translators: Message presented when the browse mode element is not found. - prevError=_("no previous math formula") + prevError=_("no previous math formula"), ) qn( "textParagraph", @@ -1109,7 +1165,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous same style text"), # Translators: Message presented when the browse mode element is not found. - prevError=_("No previous same style text") + prevError=_("No previous same style text"), ) qn( "differentStyle", @@ -1121,7 +1177,7 @@ def _get_disableAutoPassThrough(self): # Translators: Input help message for a quick navigation command in browse mode. prevDoc=_("moves to the previous different style text"), # Translators: Message presented when the browse mode element is not found. - prevError=_("No previous different style text") + prevError=_("No previous different style text"), ) del qn @@ -1129,7 +1185,7 @@ def _get_disableAutoPassThrough(self): class ElementsListDialog( DpiScalingHelperMixinWithoutInit, gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): helpId = "ElementsList" ELEMENT_TYPES = ( @@ -1158,7 +1214,7 @@ def __init__(self, document): super().__init__( parent=gui.mainFrame, # Translators: The title of the browse mode Elements List dialog. - title=_("Elements List") + title=_("Elements List"), ) self.document = document mainSizer = wx.BoxSizer(wx.VERTICAL) @@ -1175,7 +1231,7 @@ def __init__(self, document): self.tree = wx.TreeCtrl( self, size=self.scaleSize((500, 300)), # height is chosen to ensure the dialog will fit on an 800x600 screen - style=wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT | wx.TR_LINES_AT_ROOT | wx.TR_SINGLE | wx.TR_EDIT_LABELS + style=wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT | wx.TR_LINES_AT_ROOT | wx.TR_SINGLE | wx.TR_EDIT_LABELS, ) self.tree.Bind(wx.EVT_SET_FOCUS, self.onTreeSetFocus) self.tree.Bind(wx.EVT_CHAR, self.onTreeChar) @@ -1834,7 +1890,7 @@ def event_gainFocus(self, obj, nextHandler): except Exception: log.debugWarning( "Error fetching states when checking for defunct object. Treating object as defunct anyway.", - exc_info=True + exc_info=True, ) previousFocusObjIsDefunct = True @@ -1928,7 +1984,7 @@ def event_gainFocus(self, obj, nextHandler): # changes. speech.speakObject( objPendingFocusBeforeActivate, - OutputReason.CHANGE + OutputReason.CHANGE, ) else: self._replayFocusEnteredEvents() @@ -2296,7 +2352,7 @@ def _expandStyle( paragraphInfo.expand(textInfos.UNIT_PARAGRAPH) compareResult = textRange.compareEndPoints( paragraphInfo, - "endToEnd" if direction == documentBase._Movement.NEXT else "startToStart" + "endToEnd" if direction == documentBase._Movement.NEXT else "startToStart", ) if compareResult != 0: # initial text range is not even touching end of paragraph in the desired direction, @@ -2367,7 +2423,7 @@ def _iterTextStyle( self, kind: str, direction: documentBase._Movement = documentBase._Movement.NEXT, - pos: textInfos.TextInfo | None = None + pos: textInfos.TextInfo | None = None, ) -> Generator[TextInfoQuickNavItem, None, None]: if direction not in [ documentBase._Movement.NEXT, @@ -2479,7 +2535,7 @@ def _iterTextStyle( @script( description=_( # Translators: the description for the toggleScreenLayout script. - "Toggles on and off if the screen layout is preserved while rendering the document content" + "Toggles on and off if the screen layout is preserved while rendering the document content", ), gesture="kb:NVDA+v", ) diff --git a/source/buildVersion.py b/source/buildVersion.py index 263ad290d64..9bca9bcc1e8 100644 --- a/source/buildVersion.py +++ b/source/buildVersion.py @@ -54,7 +54,7 @@ def formatVersionForGUI(year, major, minor): """ if None in (year, major, minor): raise ValueError( - "Three values must be provided. Got year={}, major={}, minor={}".format(year, major, minor) + "Three values must be provided. Got year={}, major={}, minor={}".format(year, major, minor), ) if minor == 0: return "{y}.{M}".format(y=year, M=major) diff --git a/source/characterProcessing.py b/source/characterProcessing.py index 0e9b0a270f1..db44c059fb9 100644 --- a/source/characterProcessing.py +++ b/source/characterProcessing.py @@ -33,7 +33,7 @@ class LocaleDataMap(Generic[_LocaleDataT], object): def __init__( self, - localeDataFactory: Callable[[str], _LocaleDataT] + localeDataFactory: Callable[[str], _LocaleDataT], ): """ @param localeDataFactory: the factory to create data objects for the requested locale. @@ -198,8 +198,11 @@ def __init__(self, identifier, pattern=None, replacement=None, level=None, prese def __repr__(self): attrs = [] for attr in self.__slots__: - attrs.append("{name}={val!r}".format( - name=attr, val=getattr(self, attr))) + attrs.append( + "{name}={val!r}".format( + name=attr, val=getattr(self, attr), + ), + ) return "SpeechSymbol(%s)" % ", ".join(attrs) class SpeechSymbols(object): @@ -241,8 +244,11 @@ def load(self, fileName: str, allowComplexSymbols: bool = True) -> None: else: raise ValueError except ValueError: - log.warning(u"Invalid line in file {file}: {line}".format( - file=fileName, line=line)) + log.warning( + u"Invalid line in file {file}: {line}".format( + file=fileName, line=line, + ), + ) def _loadComplexSymbol(self, line: str) -> None: try: @@ -358,14 +364,16 @@ def _saveSymbol(self, symbol): identifier = symbol.identifier try: identifier = u"\\%s%s" % ( - self.IDENTIFIER_ESCAPES_OUTPUT[identifier[0]], identifier[1:]) + self.IDENTIFIER_ESCAPES_OUTPUT[identifier[0]], identifier[1:], + ) except KeyError: pass - fields = [identifier, - self._saveSymbolField(symbol.replacement), - self._saveSymbolField(symbol.level, self.LEVEL_OUTPUT), - self._saveSymbolField(symbol.preserve, self.PRESERVE_OUTPUT) - ] + fields = [ + identifier, + self._saveSymbolField(symbol.replacement), + self._saveSymbolField(symbol.level, self.LEVEL_OUTPUT), + self._saveSymbolField(symbol.preserve, self.PRESERVE_OUTPUT), + ] # Strip optional fields with default values. for field in reversed(fields[2:]): if field == "-": @@ -396,7 +404,7 @@ def _getSpeechSymbolsForLocale(locale: str) -> Tuple[SpeechSymbols, SpeechSymbol try: builtin.load( os.path.join(globalVars.appDir, "locale", locale, "cldr.dic"), - allowComplexSymbols=False + allowComplexSymbols=False, ) builtinDataImported = True except IOError: @@ -500,8 +508,11 @@ def __init__(self, locale): for symbol in list(symbols.values()): if symbol.replacement is None: # Symbols without a replacement specified are useless. - log.warning(u"Replacement not defined in locale {locale} for symbol: {symbol}".format( - symbol=symbol.identifier, locale=self.locale)) + log.warning( + u"Replacement not defined in locale {locale} for symbol: {symbol}".format( + symbol=symbol.identifier, locale=self.locale, + ), + ) del symbols[symbol.identifier] try: if len(symbol.identifier) == 1: @@ -533,20 +544,23 @@ def __init__(self, locale): # Each complex symbol has its own named group so we know which symbol matched. patterns.extend( u"(?P{pattern})".format(index=index, pattern=symbol.pattern) - for index, symbol in enumerate(complexSymbolsList)) + for index, symbol in enumerate(complexSymbolsList) + ) patterns.extend([ # Strip repeated spaces from the end of the line to stop them from being picked up by repeated. r"(?P +$)", # Repeated characters: more than 3 repeats. - r"(?P(?P%s)(?P=repTmp){3,})" % characters + r"(?P(?P%s)(?P=repTmp){3,})" % characters, ]) # Simple symbols. # These are all handled in one named group. # Because the symbols are just text, we know which symbol matched just by looking at the matched text. - patterns.append(r"(?P{multiChars}|{singleChars})".format( - multiChars="|".join(re.escape(identifier) for identifier in multiChars), - singleChars=characters - )) + patterns.append( + r"(?P{multiChars}|{singleChars})".format( + multiChars="|".join(re.escape(identifier) for identifier in multiChars), + singleChars=characters, + ), + ) pattern = "|".join(patterns) try: self._regexp = re.compile(pattern, re.UNICODE) diff --git a/source/colors.py b/source/colors.py index 0babe762bcb..9c143c24a28 100644 --- a/source/colors.py +++ b/source/colors.py @@ -161,7 +161,7 @@ def _calcColorName(red: int, green: int, blue: int, alpha: int, reportTransparen 'color variation', # Translators: a transparent color, {colorDescription} replaced with the full description of the color e.g. # "transparent bright orange-yellow" - 'transparent {colorDescription}' + 'transparent {colorDescription}', ).format(colorDescription=closestName) return closestName diff --git a/source/comHelper.py b/source/comHelper.py index 597fac89ff0..e238f50db0d 100644 --- a/source/comHelper.py +++ b/source/comHelper.py @@ -49,15 +49,19 @@ def getActiveObject(progid, dynamic=False,appModule=None): if e.winerror not in (MK_E_UNAVAILABLE, CO_E_CLASSSTRING): # This isn't related to privileges. raise - p = subprocess.Popen((config.SLAVE_FILENAME, "comGetActiveObject", progid, "%d" % dynamic), - stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + p = subprocess.Popen( + (config.SLAVE_FILENAME, "comGetActiveObject", progid, "%d" % dynamic), + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + ) try: try: lres = int(p.stdout.readline()) except ValueError: raise RuntimeError("Helper process unable to get object; see log for details") - o = oleacc.ObjectFromLresult(lres, 0, - IDispatch if dynamic else IUnknown) + o = oleacc.ObjectFromLresult( + lres, 0, + IDispatch if dynamic else IUnknown, + ) if dynamic: o = comtypes.client.dynamic.Dispatch(o) return o diff --git a/source/comInterfaces/_944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.py b/source/comInterfaces/_944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.py index a34a8efc307..828b204e79e 100644 --- a/source/comInterfaces/_944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.py +++ b/source/comInterfaces/_944DE083_8FB8_45CF_BCB7_C477ACB2F897_0_1_0.py @@ -3,7 +3,7 @@ from ctypes import * import comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0 from comtypes import ( - _check_version, BSTR, CoClass, COMMETHOD, dispid, GUID, IUnknown + _check_version, BSTR, CoClass, COMMETHOD, dispid, GUID, IUnknown, ) from comtypes.automation import _midlSAFEARRAY, IDispatch, VARIANT from ctypes import HRESULT @@ -64,7 +64,7 @@ class IUIAutomationElement(comtypes.gen._00020430_0000_0000_C000_000000000046_0_ 'HandleTextEditTextChangedEvent', (['in'], POINTER(IUIAutomationElement), 'sender'), (['in'], TextEditChangeType, 'TextEditChangeType'), - (['in'], _midlSAFEARRAY(BSTR), 'eventStrings') + (['in'], _midlSAFEARRAY(BSTR), 'eventStrings'), ), ] @@ -96,14 +96,14 @@ class IUIAutomationElementArray(comtypes.gen._00020430_0000_0000_C000_0000000000 ['propget'], HRESULT, 'Length', - (['out', 'retval'], POINTER(c_int), 'Length') + (['out', 'retval'], POINTER(c_int), 'Length'), ), COMMETHOD( [], HRESULT, 'GetElement', (['in'], c_int, 'index'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), ] @@ -132,7 +132,7 @@ class IUIAutomationAndCondition(IUIAutomationCondition): ['propget'], HRESULT, 'ChildCount', - (['out', 'retval'], POINTER(c_int), 'ChildCount') + (['out', 'retval'], POINTER(c_int), 'ChildCount'), ), COMMETHOD( [], @@ -143,7 +143,7 @@ class IUIAutomationAndCondition(IUIAutomationCondition): POINTER(POINTER(POINTER(IUIAutomationCondition))), 'childArray', ), - (['out'], POINTER(c_int), 'childArrayCount') + (['out'], POINTER(c_int), 'childArrayCount'), ), COMMETHOD( [], @@ -153,7 +153,7 @@ class IUIAutomationAndCondition(IUIAutomationCondition): ['out', 'retval'], POINTER(_midlSAFEARRAY(POINTER(IUIAutomationCondition))), 'childArray', - ) + ), ), ] @@ -186,7 +186,7 @@ class IUIAutomationFocusChangedEventHandler(comtypes.gen._00020430_0000_0000_C00 [], HRESULT, 'HandleFocusChangedEvent', - (['in'], POINTER(IUIAutomationElement), 'sender') + (['in'], POINTER(IUIAutomationElement), 'sender'), ), ] @@ -211,7 +211,7 @@ class IUIAutomationOrCondition(IUIAutomationCondition): ['propget'], HRESULT, 'ChildCount', - (['out', 'retval'], POINTER(c_int), 'ChildCount') + (['out', 'retval'], POINTER(c_int), 'ChildCount'), ), COMMETHOD( [], @@ -222,7 +222,7 @@ class IUIAutomationOrCondition(IUIAutomationCondition): POINTER(POINTER(POINTER(IUIAutomationCondition))), 'childArray', ), - (['out'], POINTER(c_int), 'childArrayCount') + (['out'], POINTER(c_int), 'childArrayCount'), ), COMMETHOD( [], @@ -232,7 +232,7 @@ class IUIAutomationOrCondition(IUIAutomationCondition): ['out', 'retval'], POINTER(_midlSAFEARRAY(POINTER(IUIAutomationCondition))), 'childArray', - ) + ), ), ] @@ -272,7 +272,7 @@ class IUIAutomationNotCondition(IUIAutomationCondition): ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'condition', - ) + ), ), ] @@ -302,7 +302,7 @@ class UiaChangeInfo(Structure): 'HandleChangesEvent', (['in'], POINTER(IUIAutomationElement), 'sender'), (['in'], POINTER(UiaChangeInfo), 'uiaChanges'), - (['in'], c_int, 'changesCount') + (['in'], c_int, 'changesCount'), ), ] @@ -360,35 +360,35 @@ class IUIAutomationCacheRequest(comtypes.gen._00020430_0000_0000_C000_0000000000 HRESULT, 'GetParentElement', (['in'], POINTER(IUIAutomationElement), 'element'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'parent') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'parent'), ), COMMETHOD( [], HRESULT, 'GetFirstChildElement', (['in'], POINTER(IUIAutomationElement), 'element'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'first') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'first'), ), COMMETHOD( [], HRESULT, 'GetLastChildElement', (['in'], POINTER(IUIAutomationElement), 'element'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'last') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'last'), ), COMMETHOD( [], HRESULT, 'GetNextSiblingElement', (['in'], POINTER(IUIAutomationElement), 'element'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'next') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'next'), ), COMMETHOD( [], HRESULT, 'GetPreviousSiblingElement', (['in'], POINTER(IUIAutomationElement), 'element'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'previous') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'previous'), ), COMMETHOD( [], @@ -399,7 +399,7 @@ class IUIAutomationCacheRequest(comtypes.gen._00020430_0000_0000_C000_0000000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'normalized', - ) + ), ), COMMETHOD( [], @@ -407,7 +407,7 @@ class IUIAutomationCacheRequest(comtypes.gen._00020430_0000_0000_C000_0000000000 'GetParentElementBuildCache', (['in'], POINTER(IUIAutomationElement), 'element'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'parent') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'parent'), ), COMMETHOD( [], @@ -415,7 +415,7 @@ class IUIAutomationCacheRequest(comtypes.gen._00020430_0000_0000_C000_0000000000 'GetFirstChildElementBuildCache', (['in'], POINTER(IUIAutomationElement), 'element'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'first') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'first'), ), COMMETHOD( [], @@ -423,7 +423,7 @@ class IUIAutomationCacheRequest(comtypes.gen._00020430_0000_0000_C000_0000000000 'GetLastChildElementBuildCache', (['in'], POINTER(IUIAutomationElement), 'element'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'last') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'last'), ), COMMETHOD( [], @@ -431,7 +431,7 @@ class IUIAutomationCacheRequest(comtypes.gen._00020430_0000_0000_C000_0000000000 'GetNextSiblingElementBuildCache', (['in'], POINTER(IUIAutomationElement), 'element'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'next') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'next'), ), COMMETHOD( [], @@ -439,7 +439,7 @@ class IUIAutomationCacheRequest(comtypes.gen._00020430_0000_0000_C000_0000000000 'GetPreviousSiblingElementBuildCache', (['in'], POINTER(IUIAutomationElement), 'element'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'previous') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'previous'), ), COMMETHOD( [], @@ -451,7 +451,7 @@ class IUIAutomationCacheRequest(comtypes.gen._00020430_0000_0000_C000_0000000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'normalized', - ) + ), ), COMMETHOD( ['propget'], @@ -461,7 +461,7 @@ class IUIAutomationCacheRequest(comtypes.gen._00020430_0000_0000_C000_0000000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'condition', - ) + ), ), ] @@ -556,7 +556,7 @@ class IUIAutomationNotificationEventHandler(comtypes.gen._00020430_0000_0000_C00 ([], NotificationKind, 'NotificationKind'), ([], NotificationProcessing, 'NotificationProcessing'), (['in'], BSTR, 'displayString'), - (['in'], BSTR, 'activityId') + (['in'], BSTR, 'activityId'), ), ] @@ -622,37 +622,37 @@ class IUIAutomationMultipleViewPattern(comtypes.gen._00020430_0000_0000_C000_000 HRESULT, 'GetViewName', (['in'], c_int, 'view'), - (['out', 'retval'], POINTER(BSTR), 'name') + (['out', 'retval'], POINTER(BSTR), 'name'), ), COMMETHOD( [], HRESULT, 'SetCurrentView', - (['in'], c_int, 'view') + (['in'], c_int, 'view'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCurrentView', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( [], HRESULT, 'GetCurrentSupportedViews', - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedCurrentView', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( [], HRESULT, 'GetCachedSupportedViews', - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal'), ), ] @@ -705,7 +705,7 @@ class IUIAutomationSpreadsheetPattern(comtypes.gen._00020430_0000_0000_C000_0000 HRESULT, 'GetItemByName', (['in'], BSTR, 'name'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), ] @@ -735,13 +735,13 @@ class IUIAutomationTextRange(comtypes.gen._00020430_0000_0000_C000_000000000046_ ['propget'], HRESULT, 'TextContainer', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'container') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'container'), ), COMMETHOD( ['propget'], HRESULT, 'TextRange', - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range'), ), ] @@ -797,7 +797,7 @@ class IUIAutomationTableItemPattern(comtypes.gen._00020430_0000_0000_C000_000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( [], @@ -807,7 +807,7 @@ class IUIAutomationTableItemPattern(comtypes.gen._00020430_0000_0000_C000_000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( [], @@ -817,7 +817,7 @@ class IUIAutomationTableItemPattern(comtypes.gen._00020430_0000_0000_C000_000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( [], @@ -827,7 +827,7 @@ class IUIAutomationTableItemPattern(comtypes.gen._00020430_0000_0000_C000_000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), ] @@ -870,99 +870,99 @@ class IUIAutomationStylesPattern(comtypes.gen._00020430_0000_0000_C000_000000000 ['propget'], HRESULT, 'CurrentStyleId', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentStyleName', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentFillColor', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentFillPatternStyle', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentShape', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentFillPatternColor', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentExtendedProperties', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( [], HRESULT, 'GetCurrentExtendedPropertiesAsArray', (['out'], POINTER(POINTER(ExtendedProperty)), 'propertyArray'), - (['out'], POINTER(c_int), 'propertyCount') + (['out'], POINTER(c_int), 'propertyCount'), ), COMMETHOD( ['propget'], HRESULT, 'CachedStyleId', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedStyleName', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedFillColor', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedFillPatternStyle', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedShape', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedFillPatternColor', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedExtendedProperties', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( [], HRESULT, 'GetCachedExtendedPropertiesAsArray', (['out'], POINTER(POINTER(ExtendedProperty)), 'propertyArray'), - (['out'], POINTER(c_int), 'propertyCount') + (['out'], POINTER(c_int), 'propertyCount'), ), ] @@ -1074,13 +1074,13 @@ class IUIAutomationTogglePattern(comtypes.gen._00020430_0000_0000_C000_000000000 ['propget'], HRESULT, 'CurrentToggleState', - (['out', 'retval'], POINTER(ToggleState), 'retVal') + (['out', 'retval'], POINTER(ToggleState), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedToggleState', - (['out', 'retval'], POINTER(ToggleState), 'retVal') + (['out', 'retval'], POINTER(ToggleState), 'retVal'), ), ] @@ -1114,62 +1114,62 @@ class IAccessible(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDisp [dispid(-5000), 'hidden', 'propget'], HRESULT, 'accParent', - (['out', 'retval'], POINTER(POINTER(IDispatch)), 'ppdispParent') + (['out', 'retval'], POINTER(POINTER(IDispatch)), 'ppdispParent'), ), COMMETHOD( [dispid(-5001), 'hidden', 'propget'], HRESULT, 'accChildCount', - (['out', 'retval'], POINTER(c_int), 'pcountChildren') + (['out', 'retval'], POINTER(c_int), 'pcountChildren'), ), COMMETHOD( [dispid(-5002), 'hidden', 'propget'], HRESULT, 'accChild', (['in'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(POINTER(IDispatch)), 'ppdispChild') + (['out', 'retval'], POINTER(POINTER(IDispatch)), 'ppdispChild'), ), COMMETHOD( [dispid(-5003), 'hidden', 'propget'], HRESULT, 'accName', (['in', 'optional'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(BSTR), 'pszName') + (['out', 'retval'], POINTER(BSTR), 'pszName'), ), COMMETHOD( [dispid(-5004), 'hidden', 'propget'], HRESULT, 'accValue', (['in', 'optional'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(BSTR), 'pszValue') + (['out', 'retval'], POINTER(BSTR), 'pszValue'), ), COMMETHOD( [dispid(-5005), 'hidden', 'propget'], HRESULT, 'accDescription', (['in', 'optional'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(BSTR), 'pszDescription') + (['out', 'retval'], POINTER(BSTR), 'pszDescription'), ), COMMETHOD( [dispid(-5006), 'hidden', 'propget'], HRESULT, 'accRole', (['in', 'optional'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(VARIANT), 'pvarRole') + (['out', 'retval'], POINTER(VARIANT), 'pvarRole'), ), COMMETHOD( [dispid(-5007), 'hidden', 'propget'], HRESULT, 'accState', (['in', 'optional'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(VARIANT), 'pvarState') + (['out', 'retval'], POINTER(VARIANT), 'pvarState'), ), COMMETHOD( [dispid(-5008), 'hidden', 'propget'], HRESULT, 'accHelp', (['in', 'optional'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(BSTR), 'pszHelp') + (['out', 'retval'], POINTER(BSTR), 'pszHelp'), ), COMMETHOD( [dispid(-5009), 'hidden', 'propget'], @@ -1177,40 +1177,40 @@ class IAccessible(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDisp 'accHelpTopic', (['out'], POINTER(BSTR), 'pszHelpFile'), (['in', 'optional'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(c_int), 'pidTopic') + (['out', 'retval'], POINTER(c_int), 'pidTopic'), ), COMMETHOD( [dispid(-5010), 'hidden', 'propget'], HRESULT, 'accKeyboardShortcut', (['in', 'optional'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(BSTR), 'pszKeyboardShortcut') + (['out', 'retval'], POINTER(BSTR), 'pszKeyboardShortcut'), ), COMMETHOD( [dispid(-5011), 'hidden', 'propget'], HRESULT, 'accFocus', - (['out', 'retval'], POINTER(VARIANT), 'pvarChild') + (['out', 'retval'], POINTER(VARIANT), 'pvarChild'), ), COMMETHOD( [dispid(-5012), 'hidden', 'propget'], HRESULT, 'accSelection', - (['out', 'retval'], POINTER(VARIANT), 'pvarChildren') + (['out', 'retval'], POINTER(VARIANT), 'pvarChildren'), ), COMMETHOD( [dispid(-5013), 'hidden', 'propget'], HRESULT, 'accDefaultAction', (['in', 'optional'], VARIANT, 'varChild'), - (['out', 'retval'], POINTER(BSTR), 'pszDefaultAction') + (['out', 'retval'], POINTER(BSTR), 'pszDefaultAction'), ), COMMETHOD( [dispid(-5014), 'hidden'], HRESULT, 'accSelect', (['in'], c_int, 'flagsSelect'), - (['in', 'optional'], VARIANT, 'varChild') + (['in', 'optional'], VARIANT, 'varChild'), ), COMMETHOD( [dispid(-5015), 'hidden'], @@ -1220,7 +1220,7 @@ class IAccessible(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDisp (['out'], POINTER(c_int), 'pyTop'), (['out'], POINTER(c_int), 'pcxWidth'), (['out'], POINTER(c_int), 'pcyHeight'), - (['in', 'optional'], VARIANT, 'varChild') + (['in', 'optional'], VARIANT, 'varChild'), ), COMMETHOD( [dispid(-5016), 'hidden'], @@ -1228,7 +1228,7 @@ class IAccessible(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDisp 'accNavigate', (['in'], c_int, 'navDir'), (['in', 'optional'], VARIANT, 'varStart'), - (['out', 'retval'], POINTER(VARIANT), 'pvarEndUpAt') + (['out', 'retval'], POINTER(VARIANT), 'pvarEndUpAt'), ), COMMETHOD( [dispid(-5017), 'hidden'], @@ -1236,27 +1236,27 @@ class IAccessible(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.IDisp 'accHitTest', (['in'], c_int, 'xLeft'), (['in'], c_int, 'yTop'), - (['out', 'retval'], POINTER(VARIANT), 'pvarChild') + (['out', 'retval'], POINTER(VARIANT), 'pvarChild'), ), COMMETHOD( [dispid(-5018), 'hidden'], HRESULT, 'accDoDefaultAction', - (['in', 'optional'], VARIANT, 'varChild') + (['in', 'optional'], VARIANT, 'varChild'), ), COMMETHOD( [dispid(-5003), 'hidden', 'propput'], HRESULT, 'accName', (['in', 'optional'], VARIANT, 'varChild'), - (['in'], BSTR, 'pszName') + (['in'], BSTR, 'pszName'), ), COMMETHOD( [dispid(-5004), 'hidden', 'propput'], HRESULT, 'accValue', (['in', 'optional'], VARIANT, 'varChild'), - (['in'], BSTR, 'pszValue') + (['in'], BSTR, 'pszValue'), ), ] @@ -1388,37 +1388,37 @@ class IUIAutomationDragPattern(comtypes.gen._00020430_0000_0000_C000_00000000004 ['propget'], HRESULT, 'CurrentIsGrabbed', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsGrabbed', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentDropEffect', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedDropEffect', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentDropEffects', - (['out', 'retval'], POINTER(_midlSAFEARRAY(BSTR)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(BSTR)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedDropEffects', - (['out', 'retval'], POINTER(_midlSAFEARRAY(BSTR)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(BSTR)), 'retVal'), ), COMMETHOD( [], @@ -1428,7 +1428,7 @@ class IUIAutomationDragPattern(comtypes.gen._00020430_0000_0000_C000_00000000004 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( [], @@ -1438,7 +1438,7 @@ class IUIAutomationDragPattern(comtypes.gen._00020430_0000_0000_C000_00000000004 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), ] @@ -1497,56 +1497,56 @@ class IUIAutomationTransformPattern(comtypes.gen._00020430_0000_0000_C000_000000 HRESULT, 'Move', (['in'], c_double, 'x'), - (['in'], c_double, 'y') + (['in'], c_double, 'y'), ), COMMETHOD( [], HRESULT, 'Resize', (['in'], c_double, 'width'), - (['in'], c_double, 'height') + (['in'], c_double, 'height'), ), COMMETHOD( [], HRESULT, 'Rotate', - (['in'], c_double, 'degrees') + (['in'], c_double, 'degrees'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCanMove', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCanResize', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCanRotate', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedCanMove', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedCanResize', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedCanRotate', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -1666,7 +1666,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'CompareElements', (['in'], POINTER(IUIAutomationElement), 'el1'), (['in'], POINTER(IUIAutomationElement), 'el2'), - (['out', 'retval'], POINTER(c_int), 'areSame') + (['out', 'retval'], POINTER(c_int), 'areSame'), ), COMMETHOD( [], @@ -1674,40 +1674,40 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'CompareRuntimeIds', (['in'], _midlSAFEARRAY(c_int), 'runtimeId1'), (['in'], _midlSAFEARRAY(c_int), 'runtimeId2'), - (['out', 'retval'], POINTER(c_int), 'areSame') + (['out', 'retval'], POINTER(c_int), 'areSame'), ), COMMETHOD( [], HRESULT, 'GetRootElement', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'root') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'root'), ), COMMETHOD( [], HRESULT, 'ElementFromHandle', (['in'], c_void_p, 'hwnd'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), COMMETHOD( [], HRESULT, 'ElementFromPoint', (['in'], tagPOINT, 'pt'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), COMMETHOD( [], HRESULT, 'GetFocusedElement', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), COMMETHOD( [], HRESULT, 'GetRootElementBuildCache', (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'root') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'root'), ), COMMETHOD( [], @@ -1715,7 +1715,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'ElementFromHandleBuildCache', (['in'], c_void_p, 'hwnd'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), COMMETHOD( [], @@ -1723,39 +1723,39 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'ElementFromPointBuildCache', (['in'], tagPOINT, 'pt'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), COMMETHOD( [], HRESULT, 'GetFocusedElementBuildCache', (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), COMMETHOD( [], HRESULT, 'CreateTreeWalker', (['in'], POINTER(IUIAutomationCondition), 'pCondition'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationTreeWalker)), 'walker') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTreeWalker)), 'walker'), ), COMMETHOD( ['propget'], HRESULT, 'ControlViewWalker', - (['out', 'retval'], POINTER(POINTER(IUIAutomationTreeWalker)), 'walker') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTreeWalker)), 'walker'), ), COMMETHOD( ['propget'], HRESULT, 'ContentViewWalker', - (['out', 'retval'], POINTER(POINTER(IUIAutomationTreeWalker)), 'walker') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTreeWalker)), 'walker'), ), COMMETHOD( ['propget'], HRESULT, 'RawViewWalker', - (['out', 'retval'], POINTER(POINTER(IUIAutomationTreeWalker)), 'walker') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTreeWalker)), 'walker'), ), COMMETHOD( ['propget'], @@ -1765,7 +1765,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'condition', - ) + ), ), COMMETHOD( ['propget'], @@ -1775,7 +1775,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'condition', - ) + ), ), COMMETHOD( ['propget'], @@ -1785,7 +1785,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'condition', - ) + ), ), COMMETHOD( [], @@ -1795,7 +1795,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCacheRequest)), 'cacheRequest', - ) + ), ), COMMETHOD( [], @@ -1805,7 +1805,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1815,7 +1815,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1827,7 +1827,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1840,7 +1840,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1852,7 +1852,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1863,7 +1863,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1875,7 +1875,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1887,7 +1887,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1898,7 +1898,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1910,7 +1910,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1921,7 +1921,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'newCondition', - ) + ), ), COMMETHOD( [], @@ -1931,7 +1931,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 (['in'], POINTER(IUIAutomationElement), 'element'), (['in'], TreeScope, 'scope'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['in'], POINTER(IUIAutomationEventHandler), 'handler') + (['in'], POINTER(IUIAutomationEventHandler), 'handler'), ), COMMETHOD( [], @@ -1939,7 +1939,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'RemoveAutomationEventHandler', (['in'], c_int, 'eventId'), (['in'], POINTER(IUIAutomationElement), 'element'), - (['in'], POINTER(IUIAutomationEventHandler), 'handler') + (['in'], POINTER(IUIAutomationEventHandler), 'handler'), ), COMMETHOD( [], @@ -1950,7 +1950,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), (['in'], POINTER(IUIAutomationPropertyChangedEventHandler), 'handler'), (['in'], POINTER(c_int), 'propertyArray'), - (['in'], c_int, 'propertyCount') + (['in'], c_int, 'propertyCount'), ), COMMETHOD( [], @@ -1960,14 +1960,14 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 (['in'], TreeScope, 'scope'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), (['in'], POINTER(IUIAutomationPropertyChangedEventHandler), 'handler'), - (['in'], _midlSAFEARRAY(c_int), 'propertyArray') + (['in'], _midlSAFEARRAY(c_int), 'propertyArray'), ), COMMETHOD( [], HRESULT, 'RemovePropertyChangedEventHandler', (['in'], POINTER(IUIAutomationElement), 'element'), - (['in'], POINTER(IUIAutomationPropertyChangedEventHandler), 'handler') + (['in'], POINTER(IUIAutomationPropertyChangedEventHandler), 'handler'), ), COMMETHOD( [], @@ -1976,27 +1976,27 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 (['in'], POINTER(IUIAutomationElement), 'element'), (['in'], TreeScope, 'scope'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['in'], POINTER(IUIAutomationStructureChangedEventHandler), 'handler') + (['in'], POINTER(IUIAutomationStructureChangedEventHandler), 'handler'), ), COMMETHOD( [], HRESULT, 'RemoveStructureChangedEventHandler', (['in'], POINTER(IUIAutomationElement), 'element'), - (['in'], POINTER(IUIAutomationStructureChangedEventHandler), 'handler') + (['in'], POINTER(IUIAutomationStructureChangedEventHandler), 'handler'), ), COMMETHOD( [], HRESULT, 'AddFocusChangedEventHandler', (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['in'], POINTER(IUIAutomationFocusChangedEventHandler), 'handler') + (['in'], POINTER(IUIAutomationFocusChangedEventHandler), 'handler'), ), COMMETHOD( [], HRESULT, 'RemoveFocusChangedEventHandler', - (['in'], POINTER(IUIAutomationFocusChangedEventHandler), 'handler') + (['in'], POINTER(IUIAutomationFocusChangedEventHandler), 'handler'), ), COMMETHOD([], HRESULT, 'RemoveAllEventHandlers'), COMMETHOD( @@ -2005,7 +2005,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'IntNativeArrayToSafeArray', (['in'], POINTER(c_int), 'array'), (['in'], c_int, 'arrayCount'), - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'safeArray') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'safeArray'), ), COMMETHOD( [], @@ -2013,21 +2013,21 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'IntSafeArrayToNativeArray', (['in'], _midlSAFEARRAY(c_int), 'intArray'), (['out'], POINTER(POINTER(c_int)), 'array'), - (['out', 'retval'], POINTER(c_int), 'arrayCount') + (['out', 'retval'], POINTER(c_int), 'arrayCount'), ), COMMETHOD( [], HRESULT, 'RectToVariant', (['in'], tagRECT, 'rc'), - (['out', 'retval'], POINTER(VARIANT), 'var') + (['out', 'retval'], POINTER(VARIANT), 'var'), ), COMMETHOD( [], HRESULT, 'VariantToRect', (['in'], VARIANT, 'var'), - (['out', 'retval'], POINTER(tagRECT), 'rc') + (['out', 'retval'], POINTER(tagRECT), 'rc'), ), COMMETHOD( [], @@ -2035,7 +2035,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'SafeArrayToRectNativeArray', (['in'], _midlSAFEARRAY(c_double), 'rects'), (['out'], POINTER(POINTER(tagRECT)), 'rectArray'), - (['out', 'retval'], POINTER(c_int), 'rectArrayCount') + (['out', 'retval'], POINTER(c_int), 'rectArrayCount'), ), COMMETHOD( [], @@ -2046,7 +2046,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationProxyFactoryEntry)), 'factoryEntry', - ) + ), ), COMMETHOD( ['propget'], @@ -2056,21 +2056,21 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['out', 'retval'], POINTER(POINTER(IUIAutomationProxyFactoryMapping)), 'factoryMapping', - ) + ), ), COMMETHOD( [], HRESULT, 'GetPropertyProgrammaticName', (['in'], c_int, 'property'), - (['out', 'retval'], POINTER(BSTR), 'name') + (['out', 'retval'], POINTER(BSTR), 'name'), ), COMMETHOD( [], HRESULT, 'GetPatternProgrammaticName', (['in'], c_int, 'pattern'), - (['out', 'retval'], POINTER(BSTR), 'name') + (['out', 'retval'], POINTER(BSTR), 'name'), ), COMMETHOD( [], @@ -2078,7 +2078,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'PollForPotentialSupportedPatterns', (['in'], POINTER(IUIAutomationElement), 'pElement'), (['out'], POINTER(_midlSAFEARRAY(c_int)), 'patternIds'), - (['out'], POINTER(_midlSAFEARRAY(BSTR)), 'patternNames') + (['out'], POINTER(_midlSAFEARRAY(BSTR)), 'patternNames'), ), COMMETHOD( [], @@ -2086,26 +2086,26 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'PollForPotentialSupportedProperties', (['in'], POINTER(IUIAutomationElement), 'pElement'), (['out'], POINTER(_midlSAFEARRAY(c_int)), 'propertyIds'), - (['out'], POINTER(_midlSAFEARRAY(BSTR)), 'propertyNames') + (['out'], POINTER(_midlSAFEARRAY(BSTR)), 'propertyNames'), ), COMMETHOD( [], HRESULT, 'CheckNotSupported', (['in'], VARIANT, 'value'), - (['out', 'retval'], POINTER(c_int), 'isNotSupported') + (['out', 'retval'], POINTER(c_int), 'isNotSupported'), ), COMMETHOD( ['propget'], HRESULT, 'ReservedNotSupportedValue', - (['out', 'retval'], POINTER(POINTER(IUnknown)), 'notSupportedValue') + (['out', 'retval'], POINTER(POINTER(IUnknown)), 'notSupportedValue'), ), COMMETHOD( ['propget'], HRESULT, 'ReservedMixedAttributeValue', - (['out', 'retval'], POINTER(POINTER(IUnknown)), 'mixedAttributeValue') + (['out', 'retval'], POINTER(POINTER(IUnknown)), 'mixedAttributeValue'), ), COMMETHOD( [], @@ -2113,7 +2113,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 'ElementFromIAccessible', (['in'], POINTER(IAccessible), 'accessible'), (['in'], c_int, 'childId'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), COMMETHOD( [], @@ -2122,7 +2122,7 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 (['in'], POINTER(IAccessible), 'accessible'), (['in'], c_int, 'childId'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), ] @@ -2364,37 +2364,37 @@ class IUIAutomationProxyFactoryMapping(comtypes.gen._00020430_0000_0000_C000_000 ['propget'], HRESULT, 'AutoSetFocus', - (['out', 'retval'], POINTER(c_int), 'AutoSetFocus') + (['out', 'retval'], POINTER(c_int), 'AutoSetFocus'), ), COMMETHOD( ['propput'], HRESULT, 'AutoSetFocus', - (['in'], c_int, 'AutoSetFocus') + (['in'], c_int, 'AutoSetFocus'), ), COMMETHOD( ['propget'], HRESULT, 'ConnectionTimeout', - (['out', 'retval'], POINTER(c_ulong), 'timeout') + (['out', 'retval'], POINTER(c_ulong), 'timeout'), ), COMMETHOD( ['propput'], HRESULT, 'ConnectionTimeout', - (['in'], c_ulong, 'timeout') + (['in'], c_ulong, 'timeout'), ), COMMETHOD( ['propget'], HRESULT, 'TransactionTimeout', - (['out', 'retval'], POINTER(c_ulong), 'timeout') + (['out', 'retval'], POINTER(c_ulong), 'timeout'), ), COMMETHOD( ['propput'], HRESULT, 'TransactionTimeout', - (['in'], c_ulong, 'timeout') + (['in'], c_ulong, 'timeout'), ), ] @@ -2489,31 +2489,31 @@ class IUIAutomationValuePattern(comtypes.gen._00020430_0000_0000_C000_0000000000 [], HRESULT, 'SetValue', - (['in'], BSTR, 'val') + (['in'], BSTR, 'val'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentValue', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsReadOnly', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedValue', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsReadOnly', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -2564,7 +2564,7 @@ class IUIAutomationSpreadsheetItemPattern(comtypes.gen._00020430_0000_0000_C000_ ['propget'], HRESULT, 'CurrentFormula', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( [], @@ -2574,19 +2574,19 @@ class IUIAutomationSpreadsheetItemPattern(comtypes.gen._00020430_0000_0000_C000_ ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( [], HRESULT, 'GetCurrentAnnotationTypes', - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedFormula', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( [], @@ -2596,13 +2596,13 @@ class IUIAutomationSpreadsheetItemPattern(comtypes.gen._00020430_0000_0000_C000_ ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( [], HRESULT, 'GetCachedAnnotationTypes', - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal'), ), ] @@ -2644,7 +2644,7 @@ class IUIAutomationSpreadsheetItemPattern(comtypes.gen._00020430_0000_0000_C000_ ['propget'], HRESULT, 'count', - (['out', 'retval'], POINTER(c_uint), 'count') + (['out', 'retval'], POINTER(c_uint), 'count'), ), COMMETHOD( [], @@ -2654,7 +2654,7 @@ class IUIAutomationSpreadsheetItemPattern(comtypes.gen._00020430_0000_0000_C000_ ['out', 'retval'], POINTER(_midlSAFEARRAY(POINTER(IUIAutomationProxyFactoryEntry))), 'table', - ) + ), ), COMMETHOD( [], @@ -2665,7 +2665,7 @@ class IUIAutomationSpreadsheetItemPattern(comtypes.gen._00020430_0000_0000_C000_ ['out', 'retval'], POINTER(POINTER(IUIAutomationProxyFactoryEntry)), 'entry', - ) + ), ), COMMETHOD( [], @@ -2675,7 +2675,7 @@ class IUIAutomationSpreadsheetItemPattern(comtypes.gen._00020430_0000_0000_C000_ ['in'], _midlSAFEARRAY(POINTER(IUIAutomationProxyFactoryEntry)), 'factoryList', - ) + ), ), COMMETHOD( [], @@ -2686,20 +2686,20 @@ class IUIAutomationSpreadsheetItemPattern(comtypes.gen._00020430_0000_0000_C000_ ['in'], _midlSAFEARRAY(POINTER(IUIAutomationProxyFactoryEntry)), 'factoryList', - ) + ), ), COMMETHOD( [], HRESULT, 'InsertEntry', (['in'], c_uint, 'before'), - (['in'], POINTER(IUIAutomationProxyFactoryEntry), 'factory') + (['in'], POINTER(IUIAutomationProxyFactoryEntry), 'factory'), ), COMMETHOD( [], HRESULT, 'RemoveEntry', - (['in'], c_uint, 'index') + (['in'], c_uint, 'index'), ), COMMETHOD([], HRESULT, 'ClearTable'), COMMETHOD([], HRESULT, 'RestoreDefaultTable'), @@ -2775,7 +2775,7 @@ class IUIAutomationElement3(IUIAutomationElement2): [], HRESULT, 'GetRuntimeId', - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'runtimeId') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'runtimeId'), ), COMMETHOD( [], @@ -2783,7 +2783,7 @@ class IUIAutomationElement3(IUIAutomationElement2): 'FindFirst', (['in'], TreeScope, 'scope'), (['in'], POINTER(IUIAutomationCondition), 'condition'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'found') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'found'), ), COMMETHOD( [], @@ -2795,7 +2795,7 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'found', - ) + ), ), COMMETHOD( [], @@ -2804,7 +2804,7 @@ class IUIAutomationElement3(IUIAutomationElement2): (['in'], TreeScope, 'scope'), (['in'], POINTER(IUIAutomationCondition), 'condition'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'found') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'found'), ), COMMETHOD( [], @@ -2817,7 +2817,7 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'found', - ) + ), ), COMMETHOD( [], @@ -2828,14 +2828,14 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'updatedElement', - ) + ), ), COMMETHOD( [], HRESULT, 'GetCurrentPropertyValue', (['in'], c_int, 'propertyId'), - (['out', 'retval'], POINTER(VARIANT), 'retVal') + (['out', 'retval'], POINTER(VARIANT), 'retVal'), ), COMMETHOD( [], @@ -2843,14 +2843,14 @@ class IUIAutomationElement3(IUIAutomationElement2): 'GetCurrentPropertyValueEx', (['in'], c_int, 'propertyId'), (['in'], c_int, 'ignoreDefaultValue'), - (['out', 'retval'], POINTER(VARIANT), 'retVal') + (['out', 'retval'], POINTER(VARIANT), 'retVal'), ), COMMETHOD( [], HRESULT, 'GetCachedPropertyValue', (['in'], c_int, 'propertyId'), - (['out', 'retval'], POINTER(VARIANT), 'retVal') + (['out', 'retval'], POINTER(VARIANT), 'retVal'), ), COMMETHOD( [], @@ -2858,7 +2858,7 @@ class IUIAutomationElement3(IUIAutomationElement2): 'GetCachedPropertyValueEx', (['in'], c_int, 'propertyId'), (['in'], c_int, 'ignoreDefaultValue'), - (['out', 'retval'], POINTER(VARIANT), 'retVal') + (['out', 'retval'], POINTER(VARIANT), 'retVal'), ), COMMETHOD( [], @@ -2870,7 +2870,7 @@ class IUIAutomationElement3(IUIAutomationElement2): POINTER(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.GUID), 'riid', ), - (['out', 'retval'], POINTER(c_void_p), 'patternObject') + (['out', 'retval'], POINTER(c_void_p), 'patternObject'), ), COMMETHOD( [], @@ -2882,27 +2882,27 @@ class IUIAutomationElement3(IUIAutomationElement2): POINTER(comtypes.gen._00020430_0000_0000_C000_000000000046_0_2_0.GUID), 'riid', ), - (['out', 'retval'], POINTER(c_void_p), 'patternObject') + (['out', 'retval'], POINTER(c_void_p), 'patternObject'), ), COMMETHOD( [], HRESULT, 'GetCurrentPattern', (['in'], c_int, 'patternId'), - (['out', 'retval'], POINTER(POINTER(IUnknown)), 'patternObject') + (['out', 'retval'], POINTER(POINTER(IUnknown)), 'patternObject'), ), COMMETHOD( [], HRESULT, 'GetCachedPattern', (['in'], c_int, 'patternId'), - (['out', 'retval'], POINTER(POINTER(IUnknown)), 'patternObject') + (['out', 'retval'], POINTER(POINTER(IUnknown)), 'patternObject'), ), COMMETHOD( [], HRESULT, 'GetCachedParent', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'parent') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'parent'), ), COMMETHOD( [], @@ -2912,175 +2912,175 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'children', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CurrentProcessId', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentControlType', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentLocalizedControlType', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentName', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentAcceleratorKey', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentAccessKey', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentHasKeyboardFocus', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsKeyboardFocusable', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsEnabled', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentAutomationId', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentClassName', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentHelpText', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCulture', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsControlElement', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsContentElement', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsPassword', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentNativeWindowHandle', - (['out', 'retval'], POINTER(c_void_p), 'retVal') + (['out', 'retval'], POINTER(c_void_p), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentItemType', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsOffscreen', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentOrientation', - (['out', 'retval'], POINTER(OrientationType), 'retVal') + (['out', 'retval'], POINTER(OrientationType), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentFrameworkId', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsRequiredForForm', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentItemStatus', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentBoundingRectangle', - (['out', 'retval'], POINTER(tagRECT), 'retVal') + (['out', 'retval'], POINTER(tagRECT), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentLabeledBy', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentAriaRole', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentAriaProperties', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsDataValidForForm', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], @@ -3090,7 +3090,7 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], @@ -3100,7 +3100,7 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], @@ -3110,181 +3110,181 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CurrentProviderDescription', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedProcessId', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedControlType', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedLocalizedControlType', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedName', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedAcceleratorKey', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedAccessKey', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedHasKeyboardFocus', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsKeyboardFocusable', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsEnabled', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedAutomationId', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedClassName', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedHelpText', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedCulture', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsControlElement', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsContentElement', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsPassword', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedNativeWindowHandle', - (['out', 'retval'], POINTER(c_void_p), 'retVal') + (['out', 'retval'], POINTER(c_void_p), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedItemType', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsOffscreen', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedOrientation', - (['out', 'retval'], POINTER(OrientationType), 'retVal') + (['out', 'retval'], POINTER(OrientationType), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedFrameworkId', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsRequiredForForm', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedItemStatus', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedBoundingRectangle', - (['out', 'retval'], POINTER(tagRECT), 'retVal') + (['out', 'retval'], POINTER(tagRECT), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedLabeledBy', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedAriaRole', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedAriaProperties', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsDataValidForForm', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], @@ -3294,7 +3294,7 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], @@ -3304,7 +3304,7 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], @@ -3314,20 +3314,20 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CachedProviderDescription', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( [], HRESULT, 'GetClickablePoint', (['out'], POINTER(tagPOINT), 'clickable'), - (['out', 'retval'], POINTER(c_int), 'gotClickable') + (['out', 'retval'], POINTER(c_int), 'gotClickable'), ), ] @@ -3737,25 +3737,25 @@ class IUIAutomationElement3(IUIAutomationElement2): ['propget'], HRESULT, 'CurrentOptimizeForVisualContent', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedOptimizeForVisualContent', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentLiveSetting', - (['out', 'retval'], POINTER(LiveSetting), 'retVal') + (['out', 'retval'], POINTER(LiveSetting), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedLiveSetting', - (['out', 'retval'], POINTER(LiveSetting), 'retVal') + (['out', 'retval'], POINTER(LiveSetting), 'retVal'), ), COMMETHOD( ['propget'], @@ -3765,7 +3765,7 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], @@ -3775,7 +3775,7 @@ class IUIAutomationElement3(IUIAutomationElement2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), ] @@ -3819,13 +3819,13 @@ class IUIAutomationElement3(IUIAutomationElement2): ['propget'], HRESULT, 'CurrentIsPeripheral', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsPeripheral', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -3876,7 +3876,7 @@ class IUIAutomation4(IUIAutomation3): ['in'], POINTER(IUIAutomationTextEditTextChangedEventHandler), 'handler', - ) + ), ), COMMETHOD( [], @@ -3887,7 +3887,7 @@ class IUIAutomation4(IUIAutomation3): ['in'], POINTER(IUIAutomationTextEditTextChangedEventHandler), 'handler', - ) + ), ), ] @@ -3913,14 +3913,14 @@ class IUIAutomation4(IUIAutomation3): (['in'], POINTER(c_int), 'changeTypes'), (['in'], c_int, 'changesCount'), (['in'], POINTER(IUIAutomationCacheRequest), 'pCacheRequest'), - (['in'], POINTER(IUIAutomationChangesEventHandler), 'handler') + (['in'], POINTER(IUIAutomationChangesEventHandler), 'handler'), ), COMMETHOD( [], HRESULT, 'RemoveChangesEventHandler', (['in'], POINTER(IUIAutomationElement), 'element'), - (['in'], POINTER(IUIAutomationChangesEventHandler), 'handler') + (['in'], POINTER(IUIAutomationChangesEventHandler), 'handler'), ), ] @@ -3956,25 +3956,25 @@ class IUIAutomationElement4(IUIAutomationElement3): ['propget'], HRESULT, 'CurrentPositionInSet', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentSizeOfSet', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentLevel', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentAnnotationTypes', - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal'), ), COMMETHOD( ['propget'], @@ -3984,31 +3984,31 @@ class IUIAutomationElement4(IUIAutomationElement3): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CachedPositionInSet', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedSizeOfSet', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedLevel', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedAnnotationTypes', - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_int)), 'retVal'), ), COMMETHOD( ['propget'], @@ -4018,7 +4018,7 @@ class IUIAutomationElement4(IUIAutomationElement3): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), ] @@ -4108,85 +4108,85 @@ class IUIAutomationWindowPattern(comtypes.gen._00020430_0000_0000_C000_000000000 HRESULT, 'WaitForInputIdle', (['in'], c_int, 'milliseconds'), - (['out', 'retval'], POINTER(c_int), 'success') + (['out', 'retval'], POINTER(c_int), 'success'), ), COMMETHOD( [], HRESULT, 'SetWindowVisualState', - (['in'], WindowVisualState, 'state') + (['in'], WindowVisualState, 'state'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCanMaximize', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCanMinimize', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsModal', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsTopmost', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentWindowVisualState', - (['out', 'retval'], POINTER(WindowVisualState), 'retVal') + (['out', 'retval'], POINTER(WindowVisualState), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentWindowInteractionState', - (['out', 'retval'], POINTER(WindowInteractionState), 'retVal') + (['out', 'retval'], POINTER(WindowInteractionState), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedCanMaximize', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedCanMinimize', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsModal', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsTopmost', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedWindowVisualState', - (['out', 'retval'], POINTER(WindowVisualState), 'retVal') + (['out', 'retval'], POINTER(WindowVisualState), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedWindowInteractionState', - (['out', 'retval'], POINTER(WindowInteractionState), 'retVal') + (['out', 'retval'], POINTER(WindowInteractionState), 'retVal'), ), ] @@ -4287,25 +4287,25 @@ class IUIAutomationElement6(IUIAutomationElement5): ['propget'], HRESULT, 'CurrentLandmarkType', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentLocalizedLandmarkType', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedLandmarkType', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedLocalizedLandmarkType', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), ] @@ -4338,13 +4338,13 @@ class IUIAutomationElement6(IUIAutomationElement5): ['propget'], HRESULT, 'CurrentFullDescription', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedFullDescription', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), ] @@ -4390,86 +4390,86 @@ class IUIAutomationScrollPattern(comtypes.gen._00020430_0000_0000_C000_000000000 HRESULT, 'Scroll', (['in'], ScrollAmount, 'horizontalAmount'), - (['in'], ScrollAmount, 'verticalAmount') + (['in'], ScrollAmount, 'verticalAmount'), ), COMMETHOD( [], HRESULT, 'SetScrollPercent', (['in'], c_double, 'horizontalPercent'), - (['in'], c_double, 'verticalPercent') + (['in'], c_double, 'verticalPercent'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentHorizontalScrollPercent', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentVerticalScrollPercent', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentHorizontalViewSize', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentVerticalViewSize', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentHorizontallyScrollable', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentVerticallyScrollable', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedHorizontalScrollPercent', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedVerticalScrollPercent', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedHorizontalViewSize', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedVerticalViewSize', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedHorizontallyScrollable', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedVerticallyScrollable', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -4569,7 +4569,7 @@ class IUIAutomationElement7(IUIAutomationElement6): (['in'], POINTER(IUIAutomationCondition), 'condition'), (['in'], TreeTraversalOptions, 'traversalOptions'), (['in'], POINTER(IUIAutomationElement), 'root'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'found') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'found'), ), COMMETHOD( [], @@ -4583,7 +4583,7 @@ class IUIAutomationElement7(IUIAutomationElement6): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'found', - ) + ), ), COMMETHOD( [], @@ -4594,7 +4594,7 @@ class IUIAutomationElement7(IUIAutomationElement6): (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), (['in'], TreeTraversalOptions, 'traversalOptions'), (['in'], POINTER(IUIAutomationElement), 'root'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'found') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'found'), ), COMMETHOD( [], @@ -4609,7 +4609,7 @@ class IUIAutomationElement7(IUIAutomationElement6): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'found', - ) + ), ), COMMETHOD( [], @@ -4617,7 +4617,7 @@ class IUIAutomationElement7(IUIAutomationElement6): 'GetCurrentMetadataValue', (['in'], c_int, 'targetId'), (['in'], c_int, 'metadataId'), - (['out', 'retval'], POINTER(VARIANT), 'returnVal') + (['out', 'retval'], POINTER(VARIANT), 'returnVal'), ), ] @@ -4666,61 +4666,61 @@ class IUIAutomationTransformPattern2(IUIAutomationTransformPattern): [], HRESULT, 'Zoom', - (['in'], c_double, 'zoomValue') + (['in'], c_double, 'zoomValue'), ), COMMETHOD( [], HRESULT, 'ZoomByUnit', - (['in'], ZoomUnit, 'ZoomUnit') + (['in'], ZoomUnit, 'ZoomUnit'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCanZoom', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedCanZoom', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentZoomLevel', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedZoomLevel', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentZoomMinimum', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedZoomMinimum', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentZoomMaximum', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedZoomMaximum', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), ] @@ -4797,14 +4797,14 @@ class IUIAutomation5(IUIAutomation4): (['in'], POINTER(IUIAutomationElement), 'element'), (['in'], TreeScope, 'scope'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['in'], POINTER(IUIAutomationNotificationEventHandler), 'handler') + (['in'], POINTER(IUIAutomationNotificationEventHandler), 'handler'), ), COMMETHOD( [], HRESULT, 'RemoveNotificationEventHandler', (['in'], POINTER(IUIAutomationElement), 'element'), - (['in'], POINTER(IUIAutomationNotificationEventHandler), 'handler') + (['in'], POINTER(IUIAutomationNotificationEventHandler), 'handler'), ), ] @@ -4851,14 +4851,14 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): ['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'clonedRange', - ) + ), ), COMMETHOD( [], HRESULT, 'Compare', (['in'], POINTER(IUIAutomationTextRange), 'range'), - (['out', 'retval'], POINTER(c_int), 'areSame') + (['out', 'retval'], POINTER(c_int), 'areSame'), ), COMMETHOD( [], @@ -4867,13 +4867,13 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): (['in'], TextPatternRangeEndpoint, 'srcEndPoint'), (['in'], POINTER(IUIAutomationTextRange), 'range'), (['in'], TextPatternRangeEndpoint, 'targetEndPoint'), - (['out', 'retval'], POINTER(c_int), 'compValue') + (['out', 'retval'], POINTER(c_int), 'compValue'), ), COMMETHOD( [], HRESULT, 'ExpandToEnclosingUnit', - (['in'], TextUnit, 'TextUnit') + (['in'], TextUnit, 'TextUnit'), ), COMMETHOD( [], @@ -4882,7 +4882,7 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): (['in'], c_int, 'attr'), (['in'], VARIANT, 'val'), (['in'], c_int, 'backward'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'found') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'found'), ), COMMETHOD( [], @@ -4891,20 +4891,20 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): (['in'], BSTR, 'text'), (['in'], c_int, 'backward'), (['in'], c_int, 'ignoreCase'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'found') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'found'), ), COMMETHOD( [], HRESULT, 'GetAttributeValue', (['in'], c_int, 'attr'), - (['out', 'retval'], POINTER(VARIANT), 'value') + (['out', 'retval'], POINTER(VARIANT), 'value'), ), COMMETHOD( [], HRESULT, 'GetBoundingRectangles', - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_double)), 'boundingRects') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_double)), 'boundingRects'), ), COMMETHOD( [], @@ -4914,14 +4914,14 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): ['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'enclosingElement', - ) + ), ), COMMETHOD( [], HRESULT, 'GetText', (['in'], c_int, 'maxLength'), - (['out', 'retval'], POINTER(BSTR), 'text') + (['out', 'retval'], POINTER(BSTR), 'text'), ), COMMETHOD( [], @@ -4929,7 +4929,7 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): 'Move', (['in'], TextUnit, 'unit'), (['in'], c_int, 'count'), - (['out', 'retval'], POINTER(c_int), 'moved') + (['out', 'retval'], POINTER(c_int), 'moved'), ), COMMETHOD( [], @@ -4938,7 +4938,7 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): (['in'], TextPatternRangeEndpoint, 'endpoint'), (['in'], TextUnit, 'unit'), (['in'], c_int, 'count'), - (['out', 'retval'], POINTER(c_int), 'moved') + (['out', 'retval'], POINTER(c_int), 'moved'), ), COMMETHOD( [], @@ -4946,7 +4946,7 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): 'MoveEndpointByRange', (['in'], TextPatternRangeEndpoint, 'srcEndPoint'), (['in'], POINTER(IUIAutomationTextRange), 'range'), - (['in'], TextPatternRangeEndpoint, 'targetEndPoint') + (['in'], TextPatternRangeEndpoint, 'targetEndPoint'), ), COMMETHOD([], HRESULT, 'Select'), COMMETHOD([], HRESULT, 'AddToSelection'), @@ -4955,7 +4955,7 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): [], HRESULT, 'ScrollIntoView', - (['in'], c_int, 'alignToTop') + (['in'], c_int, 'alignToTop'), ), COMMETHOD( [], @@ -4965,7 +4965,7 @@ class IUIAutomationTextRange2(IUIAutomationTextRange): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'children', - ) + ), ), ] @@ -5082,7 +5082,7 @@ class IUIAutomationActiveTextPositionChangedEventHandler(comtypes.gen._00020430_ ['in'], POINTER(IUIAutomationActiveTextPositionChangedEventHandler), 'handler', - ) + ), ), COMMETHOD( [], @@ -5091,7 +5091,7 @@ class IUIAutomationActiveTextPositionChangedEventHandler(comtypes.gen._00020430_ (['in'], c_int, 'eventId'), (['in'], TreeScope, 'scope'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['in'], POINTER(IUIAutomationEventHandler), 'handler') + (['in'], POINTER(IUIAutomationEventHandler), 'handler'), ), COMMETHOD( [], @@ -5101,7 +5101,7 @@ class IUIAutomationActiveTextPositionChangedEventHandler(comtypes.gen._00020430_ (['in'], POINTER(c_int), 'changeTypes'), (['in'], c_int, 'changesCount'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['in'], POINTER(IUIAutomationChangesEventHandler), 'handler') + (['in'], POINTER(IUIAutomationChangesEventHandler), 'handler'), ), COMMETHOD( [], @@ -5109,7 +5109,7 @@ class IUIAutomationActiveTextPositionChangedEventHandler(comtypes.gen._00020430_ 'AddNotificationEventHandler', (['in'], TreeScope, 'scope'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['in'], POINTER(IUIAutomationNotificationEventHandler), 'handler') + (['in'], POINTER(IUIAutomationNotificationEventHandler), 'handler'), ), COMMETHOD( [], @@ -5119,7 +5119,7 @@ class IUIAutomationActiveTextPositionChangedEventHandler(comtypes.gen._00020430_ (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), (['in'], POINTER(IUIAutomationPropertyChangedEventHandler), 'handler'), (['in'], POINTER(c_int), 'propertyArray'), - (['in'], c_int, 'propertyCount') + (['in'], c_int, 'propertyCount'), ), COMMETHOD( [], @@ -5127,7 +5127,7 @@ class IUIAutomationActiveTextPositionChangedEventHandler(comtypes.gen._00020430_ 'AddStructureChangedEventHandler', (['in'], TreeScope, 'scope'), (['in'], POINTER(IUIAutomationCacheRequest), 'cacheRequest'), - (['in'], POINTER(IUIAutomationStructureChangedEventHandler), 'handler') + (['in'], POINTER(IUIAutomationStructureChangedEventHandler), 'handler'), ), COMMETHOD( [], @@ -5140,7 +5140,7 @@ class IUIAutomationActiveTextPositionChangedEventHandler(comtypes.gen._00020430_ ['in'], POINTER(IUIAutomationTextEditTextChangedEventHandler), 'handler', - ) + ), ), ] @@ -5194,7 +5194,7 @@ class IUIAutomationTextRange3(IUIAutomationTextRange2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'enclosingElement', - ) + ), ), COMMETHOD( [], @@ -5205,7 +5205,7 @@ class IUIAutomationTextRange3(IUIAutomationTextRange2): ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'children', - ) + ), ), COMMETHOD( [], @@ -5213,7 +5213,7 @@ class IUIAutomationTextRange3(IUIAutomationTextRange2): 'GetAttributeValues', (['in'], POINTER(c_int), 'attributeIds'), (['in'], c_int, 'attributeIdCount'), - (['out', 'retval'], POINTER(_midlSAFEARRAY(VARIANT)), 'attributeValues') + (['out', 'retval'], POINTER(_midlSAFEARRAY(VARIANT)), 'attributeValues'), ), ] @@ -5245,14 +5245,14 @@ class IUIAutomationTextRangeArray(comtypes.gen._00020430_0000_0000_C000_00000000 ['propget'], HRESULT, 'Length', - (['out', 'retval'], POINTER(c_int), 'Length') + (['out', 'retval'], POINTER(c_int), 'Length'), ), COMMETHOD( [], HRESULT, 'GetElement', (['in'], c_int, 'index'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'element'), ), ] @@ -5288,14 +5288,14 @@ class IUIAutomationTextPattern(comtypes.gen._00020430_0000_0000_C000_00000000004 HRESULT, 'RangeFromPoint', (['in'], tagPOINT, 'pt'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range'), ), COMMETHOD( [], HRESULT, 'RangeFromChild', (['in'], POINTER(IUIAutomationElement), 'child'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range'), ), COMMETHOD( [], @@ -5305,7 +5305,7 @@ class IUIAutomationTextPattern(comtypes.gen._00020430_0000_0000_C000_00000000004 ['out', 'retval'], POINTER(POINTER(IUIAutomationTextRangeArray)), 'ranges', - ) + ), ), COMMETHOD( [], @@ -5315,13 +5315,13 @@ class IUIAutomationTextPattern(comtypes.gen._00020430_0000_0000_C000_00000000004 ['out', 'retval'], POINTER(POINTER(IUIAutomationTextRangeArray)), 'ranges', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'DocumentRange', - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range'), ), COMMETHOD( ['propget'], @@ -5331,7 +5331,7 @@ class IUIAutomationTextPattern(comtypes.gen._00020430_0000_0000_C000_00000000004 ['out', 'retval'], POINTER(SupportedTextSelection), 'SupportedTextSelection', - ) + ), ), ] @@ -5377,7 +5377,7 @@ class IUIAutomationObjectModelPattern(comtypes.gen._00020430_0000_0000_C000_0000 [], HRESULT, 'GetUnderlyingObjectModel', - (['out', 'retval'], POINTER(POINTER(IUnknown)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUnknown)), 'retVal'), ), ] @@ -5401,79 +5401,79 @@ class IUIAutomationRangeValuePattern(comtypes.gen._00020430_0000_0000_C000_00000 [], HRESULT, 'SetValue', - (['in'], c_double, 'val') + (['in'], c_double, 'val'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentValue', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsReadOnly', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentMaximum', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentMinimum', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentLargeChange', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentSmallChange', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedValue', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsReadOnly', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedMaximum', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedMinimum', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedLargeChange', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedSmallChange', - (['out', 'retval'], POINTER(c_double), 'retVal') + (['out', 'retval'], POINTER(c_double), 'retVal'), ), ] @@ -5558,14 +5558,14 @@ class IUIAutomationTextPattern2(IUIAutomationTextPattern): HRESULT, 'RangeFromAnnotation', (['in'], POINTER(IUIAutomationElement), 'annotation'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range'), ), COMMETHOD( [], HRESULT, 'GetCaretRange', (['out'], POINTER(c_int), 'isActive'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range'), ), ] @@ -5593,13 +5593,13 @@ class IUIAutomationTextEditPattern(IUIAutomationTextPattern): [], HRESULT, 'GetActiveComposition', - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range'), ), COMMETHOD( [], HRESULT, 'GetConversionTarget', - (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range') + (['out', 'retval'], POINTER(POINTER(IUIAutomationTextRange)), 'range'), ), ] @@ -5630,7 +5630,7 @@ class IUIAutomationItemContainerPattern(comtypes.gen._00020430_0000_0000_C000_00 (['in'], POINTER(IUIAutomationElement), 'pStartAfter'), (['in'], c_int, 'propertyId'), (['in'], VARIANT, 'value'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'pFound') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'pFound'), ), ] @@ -5682,19 +5682,19 @@ class IUIAutomationDockPattern(comtypes.gen._00020430_0000_0000_C000_00000000004 [], HRESULT, 'SetDockPosition', - (['in'], DockPosition, 'dockPos') + (['in'], DockPosition, 'dockPos'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentDockPosition', - (['out', 'retval'], POINTER(DockPosition), 'retVal') + (['out', 'retval'], POINTER(DockPosition), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedDockPosition', - (['out', 'retval'], POINTER(DockPosition), 'retVal') + (['out', 'retval'], POINTER(DockPosition), 'retVal'), ), ] @@ -5751,19 +5751,19 @@ class IUIAutomationSelectionPattern(comtypes.gen._00020430_0000_0000_C000_000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCanSelectMultiple', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentIsSelectionRequired', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( [], @@ -5773,19 +5773,19 @@ class IUIAutomationSelectionPattern(comtypes.gen._00020430_0000_0000_C000_000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CachedCanSelectMultiple', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsSelectionRequired', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -5842,13 +5842,13 @@ class IUIAutomationExpandCollapsePattern(comtypes.gen._00020430_0000_0000_C000_0 ['propget'], HRESULT, 'CurrentExpandCollapseState', - (['out', 'retval'], POINTER(ExpandCollapseState), 'retVal') + (['out', 'retval'], POINTER(ExpandCollapseState), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedExpandCollapseState', - (['out', 'retval'], POINTER(ExpandCollapseState), 'retVal') + (['out', 'retval'], POINTER(ExpandCollapseState), 'retVal'), ), ] @@ -5902,31 +5902,31 @@ class IUIAutomationGridPattern(comtypes.gen._00020430_0000_0000_C000_00000000004 'GetItem', (['in'], c_int, 'row'), (['in'], c_int, 'column'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'element'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentRowCount', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentColumnCount', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedRowCount', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedColumnCount', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -5978,49 +5978,49 @@ class IUIAutomationSelectionPattern2(IUIAutomationSelectionPattern): ['propget'], HRESULT, 'CurrentFirstSelectedItem', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentLastSelectedItem', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentCurrentSelectedItem', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentItemCount', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedFirstSelectedItem', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedLastSelectedItem', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedCurrentSelectedItem', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedItemCount', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -6087,61 +6087,61 @@ class IUIAutomationGridItemPattern(comtypes.gen._00020430_0000_0000_C000_0000000 ['propget'], HRESULT, 'CurrentContainingGrid', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentRow', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentColumn', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentRowSpan', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentColumnSpan', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedContainingGrid', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedRow', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedColumn', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedRowSpan', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedColumnSpan', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -6225,21 +6225,21 @@ class IUIAutomation6(IUIAutomation5): ['out'], POINTER(POINTER(IUIAutomationEventHandlerGroup)), 'handlerGroup', - ) + ), ), COMMETHOD( [], HRESULT, 'AddEventHandlerGroup', (['in'], POINTER(IUIAutomationElement), 'element'), - (['in'], POINTER(IUIAutomationEventHandlerGroup), 'handlerGroup') + (['in'], POINTER(IUIAutomationEventHandlerGroup), 'handlerGroup'), ), COMMETHOD( [], HRESULT, 'RemoveEventHandlerGroup', (['in'], POINTER(IUIAutomationElement), 'element'), - (['in'], POINTER(IUIAutomationEventHandlerGroup), 'handlerGroup') + (['in'], POINTER(IUIAutomationEventHandlerGroup), 'handlerGroup'), ), COMMETHOD( ['propget'], @@ -6249,7 +6249,7 @@ class IUIAutomation6(IUIAutomation5): ['out', 'retval'], POINTER(ConnectionRecoveryBehaviorOptions), 'ConnectionRecoveryBehaviorOptions', - ) + ), ), COMMETHOD( ['propput'], @@ -6259,7 +6259,7 @@ class IUIAutomation6(IUIAutomation5): ['in'], ConnectionRecoveryBehaviorOptions, 'ConnectionRecoveryBehaviorOptions', - ) + ), ), COMMETHOD( ['propget'], @@ -6269,13 +6269,13 @@ class IUIAutomation6(IUIAutomation5): ['out', 'retval'], POINTER(CoalesceEventsOptions), 'CoalesceEventsOptions', - ) + ), ), COMMETHOD( ['propput'], HRESULT, 'CoalesceEvents', - (['in'], CoalesceEventsOptions, 'CoalesceEventsOptions') + (['in'], CoalesceEventsOptions, 'CoalesceEventsOptions'), ), COMMETHOD( [], @@ -6288,7 +6288,7 @@ class IUIAutomation6(IUIAutomation5): ['in'], POINTER(IUIAutomationActiveTextPositionChangedEventHandler), 'handler', - ) + ), ), COMMETHOD( [], @@ -6299,7 +6299,7 @@ class IUIAutomation6(IUIAutomation5): ['in'], POINTER(IUIAutomationActiveTextPositionChangedEventHandler), 'handler', - ) + ), ), ] @@ -6430,61 +6430,61 @@ class IUIAutomationAnnotationPattern(comtypes.gen._00020430_0000_0000_C000_00000 ['propget'], HRESULT, 'CurrentAnnotationTypeId', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentAnnotationTypeName', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentAuthor', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentDateTime', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentTarget', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedAnnotationTypeId', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedAnnotationTypeName', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedAuthor', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedDateTime', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedTarget', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), ] @@ -6566,25 +6566,25 @@ class IUIAutomationDropTargetPattern(comtypes.gen._00020430_0000_0000_C000_00000 ['propget'], HRESULT, 'CurrentDropTargetEffect', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedDropTargetEffect', - (['out', 'retval'], POINTER(BSTR), 'retVal') + (['out', 'retval'], POINTER(BSTR), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentDropTargetEffects', - (['out', 'retval'], POINTER(_midlSAFEARRAY(BSTR)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(BSTR)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedDropTargetEffects', - (['out', 'retval'], POINTER(_midlSAFEARRAY(BSTR)), 'retVal') + (['out', 'retval'], POINTER(_midlSAFEARRAY(BSTR)), 'retVal'), ), ] @@ -6639,13 +6639,13 @@ class IUIAutomationElement8(IUIAutomationElement7): ['propget'], HRESULT, 'CurrentHeadingLevel', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedHeadingLevel', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -6688,7 +6688,7 @@ class IUIAutomationElement8(IUIAutomationElement7): HRESULT, 'HandleAutomationEvent', (['in'], POINTER(IUIAutomationElement), 'sender'), - (['in'], c_int, 'eventId') + (['in'], c_int, 'eventId'), ), ] @@ -6712,13 +6712,13 @@ class IUIAutomationElement9(IUIAutomationElement8): ['propget'], HRESULT, 'CurrentIsDialog', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsDialog', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), ] @@ -6743,7 +6743,7 @@ class IUIAutomationElement9(IUIAutomationElement8): 'HandlePropertyChangedEvent', (['in'], POINTER(IUIAutomationElement), 'sender'), (['in'], c_int, 'propertyId'), - (['in'], VARIANT, 'newValue') + (['in'], VARIANT, 'newValue'), ), ] @@ -6774,13 +6774,13 @@ class IRawElementProviderSimple(comtypes.gen._00020430_0000_0000_C000_0000000000 ['out', 'retval'], POINTER(POINTER(IRawElementProviderSimple)), 'provider', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'ProxyFactoryId', - (['out', 'retval'], POINTER(BSTR), 'factoryId') + (['out', 'retval'], POINTER(BSTR), 'factoryId'), ), ] @@ -6804,7 +6804,7 @@ class IRawElementProviderSimple(comtypes.gen._00020430_0000_0000_C000_0000000000 'HandleStructureChangedEvent', (['in'], POINTER(IUIAutomationElement), 'sender'), (['in'], StructureChangeType, 'changeType'), - (['in'], _midlSAFEARRAY(c_int), 'runtimeId') + (['in'], _midlSAFEARRAY(c_int), 'runtimeId'), ), ] @@ -6838,7 +6838,7 @@ class IUIAutomationCustomNavigationPattern(comtypes.gen._00020430_0000_0000_C000 HRESULT, 'Navigate', (['in'], NavigateDirection, 'direction'), - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'pRetVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'pRetVal'), ), ] @@ -6856,7 +6856,7 @@ class IUIAutomationCustomNavigationPattern(comtypes.gen._00020430_0000_0000_C000 HRESULT, 'HandleActiveTextPositionChangedEvent', (['in'], POINTER(IUIAutomationElement), 'sender'), - (['in'], POINTER(IUIAutomationTextRange), 'range') + (['in'], POINTER(IUIAutomationTextRange), 'range'), ), ] @@ -6884,21 +6884,21 @@ class IUIAutomationCustomNavigationPattern(comtypes.gen._00020430_0000_0000_C000 ['propget'], HRESULT, 'ProviderOptions', - (['out', 'retval'], POINTER(ProviderOptions), 'pRetVal') + (['out', 'retval'], POINTER(ProviderOptions), 'pRetVal'), ), COMMETHOD( [], HRESULT, 'GetPatternProvider', (['in'], c_int, 'patternId'), - (['out', 'retval'], POINTER(POINTER(IUnknown)), 'pRetVal') + (['out', 'retval'], POINTER(POINTER(IUnknown)), 'pRetVal'), ), COMMETHOD( [], HRESULT, 'GetPropertyValue', (['in'], c_int, 'propertyId'), - (['out', 'retval'], POINTER(VARIANT), 'pRetVal') + (['out', 'retval'], POINTER(VARIANT), 'pRetVal'), ), COMMETHOD( ['propget'], @@ -6908,7 +6908,7 @@ class IUIAutomationCustomNavigationPattern(comtypes.gen._00020430_0000_0000_C000 ['out', 'retval'], POINTER(POINTER(IRawElementProviderSimple)), 'pRetVal', - ) + ), ), ] @@ -6950,25 +6950,25 @@ class IUIAutomationSelectionItemPattern(comtypes.gen._00020430_0000_0000_C000_00 ['propget'], HRESULT, 'CurrentIsSelected', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentSelectionContainer', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedIsSelected', - (['out', 'retval'], POINTER(c_int), 'retVal') + (['out', 'retval'], POINTER(c_int), 'retVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedSelectionContainer', - (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal') + (['out', 'retval'], POINTER(POINTER(IUIAutomationElement)), 'retVal'), ), ] @@ -7030,62 +7030,62 @@ class IUIAutomationLegacyIAccessiblePattern(comtypes.gen._00020430_0000_0000_C00 [], HRESULT, 'Select', - ([], c_int, 'flagsSelect') + ([], c_int, 'flagsSelect'), ), COMMETHOD([], HRESULT, 'DoDefaultAction'), COMMETHOD( [], HRESULT, 'SetValue', - ([], WSTRING, 'szValue') + ([], WSTRING, 'szValue'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentChildId', - (['out', 'retval'], POINTER(c_int), 'pRetVal') + (['out', 'retval'], POINTER(c_int), 'pRetVal'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentName', - (['out', 'retval'], POINTER(BSTR), 'pszName') + (['out', 'retval'], POINTER(BSTR), 'pszName'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentValue', - (['out', 'retval'], POINTER(BSTR), 'pszValue') + (['out', 'retval'], POINTER(BSTR), 'pszValue'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentDescription', - (['out', 'retval'], POINTER(BSTR), 'pszDescription') + (['out', 'retval'], POINTER(BSTR), 'pszDescription'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentRole', - (['out', 'retval'], POINTER(c_ulong), 'pdwRole') + (['out', 'retval'], POINTER(c_ulong), 'pdwRole'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentState', - (['out', 'retval'], POINTER(c_ulong), 'pdwState') + (['out', 'retval'], POINTER(c_ulong), 'pdwState'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentHelp', - (['out', 'retval'], POINTER(BSTR), 'pszHelp') + (['out', 'retval'], POINTER(BSTR), 'pszHelp'), ), COMMETHOD( ['propget'], HRESULT, 'CurrentKeyboardShortcut', - (['out', 'retval'], POINTER(BSTR), 'pszKeyboardShortcut') + (['out', 'retval'], POINTER(BSTR), 'pszKeyboardShortcut'), ), COMMETHOD( [], @@ -7095,61 +7095,61 @@ class IUIAutomationLegacyIAccessiblePattern(comtypes.gen._00020430_0000_0000_C00 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'pvarSelectedChildren', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CurrentDefaultAction', - (['out', 'retval'], POINTER(BSTR), 'pszDefaultAction') + (['out', 'retval'], POINTER(BSTR), 'pszDefaultAction'), ), COMMETHOD( ['propget'], HRESULT, 'CachedChildId', - (['out', 'retval'], POINTER(c_int), 'pRetVal') + (['out', 'retval'], POINTER(c_int), 'pRetVal'), ), COMMETHOD( ['propget'], HRESULT, 'CachedName', - (['out', 'retval'], POINTER(BSTR), 'pszName') + (['out', 'retval'], POINTER(BSTR), 'pszName'), ), COMMETHOD( ['propget'], HRESULT, 'CachedValue', - (['out', 'retval'], POINTER(BSTR), 'pszValue') + (['out', 'retval'], POINTER(BSTR), 'pszValue'), ), COMMETHOD( ['propget'], HRESULT, 'CachedDescription', - (['out', 'retval'], POINTER(BSTR), 'pszDescription') + (['out', 'retval'], POINTER(BSTR), 'pszDescription'), ), COMMETHOD( ['propget'], HRESULT, 'CachedRole', - (['out', 'retval'], POINTER(c_ulong), 'pdwRole') + (['out', 'retval'], POINTER(c_ulong), 'pdwRole'), ), COMMETHOD( ['propget'], HRESULT, 'CachedState', - (['out', 'retval'], POINTER(c_ulong), 'pdwState') + (['out', 'retval'], POINTER(c_ulong), 'pdwState'), ), COMMETHOD( ['propget'], HRESULT, 'CachedHelp', - (['out', 'retval'], POINTER(BSTR), 'pszHelp') + (['out', 'retval'], POINTER(BSTR), 'pszHelp'), ), COMMETHOD( ['propget'], HRESULT, 'CachedKeyboardShortcut', - (['out', 'retval'], POINTER(BSTR), 'pszKeyboardShortcut') + (['out', 'retval'], POINTER(BSTR), 'pszKeyboardShortcut'), ), COMMETHOD( [], @@ -7159,19 +7159,19 @@ class IUIAutomationLegacyIAccessiblePattern(comtypes.gen._00020430_0000_0000_C00 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'pvarSelectedChildren', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CachedDefaultAction', - (['out', 'retval'], POINTER(BSTR), 'pszDefaultAction') + (['out', 'retval'], POINTER(BSTR), 'pszDefaultAction'), ), COMMETHOD( [], HRESULT, 'GetIAccessible', - (['out', 'retval'], POINTER(POINTER(IAccessible)), 'ppAccessible') + (['out', 'retval'], POINTER(POINTER(IAccessible)), 'ppAccessible'), ), ] @@ -7327,7 +7327,7 @@ class IUIAutomationSynchronizedInputPattern(comtypes.gen._00020430_0000_0000_C00 [], HRESULT, 'StartListening', - (['in'], SynchronizedInputType, 'inputType') + (['in'], SynchronizedInputType, 'inputType'), ), COMMETHOD([], HRESULT, 'Cancel'), ] @@ -7367,7 +7367,7 @@ class IUIAutomationTablePattern(comtypes.gen._00020430_0000_0000_C000_0000000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( [], @@ -7377,13 +7377,13 @@ class IUIAutomationTablePattern(comtypes.gen._00020430_0000_0000_C000_0000000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CurrentRowOrColumnMajor', - (['out', 'retval'], POINTER(RowOrColumnMajor), 'retVal') + (['out', 'retval'], POINTER(RowOrColumnMajor), 'retVal'), ), COMMETHOD( [], @@ -7393,7 +7393,7 @@ class IUIAutomationTablePattern(comtypes.gen._00020430_0000_0000_C000_0000000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( [], @@ -7403,13 +7403,13 @@ class IUIAutomationTablePattern(comtypes.gen._00020430_0000_0000_C000_0000000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationElementArray)), 'retVal', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'CachedRowOrColumnMajor', - (['out', 'retval'], POINTER(RowOrColumnMajor), 'retVal') + (['out', 'retval'], POINTER(RowOrColumnMajor), 'retVal'), ), ] @@ -7455,67 +7455,67 @@ class IUIAutomationTablePattern(comtypes.gen._00020430_0000_0000_C000_0000000000 ['out', 'retval'], POINTER(POINTER(IUIAutomationProxyFactory)), 'factory', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'ClassName', - (['out', 'retval'], POINTER(BSTR), 'ClassName') + (['out', 'retval'], POINTER(BSTR), 'ClassName'), ), COMMETHOD( ['propget'], HRESULT, 'ImageName', - (['out', 'retval'], POINTER(BSTR), 'ImageName') + (['out', 'retval'], POINTER(BSTR), 'ImageName'), ), COMMETHOD( ['propget'], HRESULT, 'AllowSubstringMatch', - (['out', 'retval'], POINTER(c_int), 'AllowSubstringMatch') + (['out', 'retval'], POINTER(c_int), 'AllowSubstringMatch'), ), COMMETHOD( ['propget'], HRESULT, 'CanCheckBaseClass', - (['out', 'retval'], POINTER(c_int), 'CanCheckBaseClass') + (['out', 'retval'], POINTER(c_int), 'CanCheckBaseClass'), ), COMMETHOD( ['propget'], HRESULT, 'NeedsAdviseEvents', - (['out', 'retval'], POINTER(c_int), 'adviseEvents') + (['out', 'retval'], POINTER(c_int), 'adviseEvents'), ), COMMETHOD( ['propput'], HRESULT, 'ClassName', - (['in'], WSTRING, 'ClassName') + (['in'], WSTRING, 'ClassName'), ), COMMETHOD( ['propput'], HRESULT, 'ImageName', - (['in'], WSTRING, 'ImageName') + (['in'], WSTRING, 'ImageName'), ), COMMETHOD( ['propput'], HRESULT, 'AllowSubstringMatch', - (['in'], c_int, 'AllowSubstringMatch') + (['in'], c_int, 'AllowSubstringMatch'), ), COMMETHOD( ['propput'], HRESULT, 'CanCheckBaseClass', - (['in'], c_int, 'CanCheckBaseClass') + (['in'], c_int, 'CanCheckBaseClass'), ), COMMETHOD( ['propput'], HRESULT, 'NeedsAdviseEvents', - (['in'], c_int, 'adviseEvents') + (['in'], c_int, 'adviseEvents'), ), COMMETHOD( [], @@ -7523,7 +7523,7 @@ class IUIAutomationTablePattern(comtypes.gen._00020430_0000_0000_C000_0000000000 'SetWinEventsForAutomationEvent', (['in'], c_int, 'eventId'), (['in'], c_int, 'propertyId'), - (['in'], _midlSAFEARRAY(c_uint), 'winEvents') + (['in'], _midlSAFEARRAY(c_uint), 'winEvents'), ), COMMETHOD( [], @@ -7531,7 +7531,7 @@ class IUIAutomationTablePattern(comtypes.gen._00020430_0000_0000_C000_0000000000 'GetWinEventsForAutomationEvent', (['in'], c_int, 'eventId'), (['in'], c_int, 'propertyId'), - (['out', 'retval'], POINTER(_midlSAFEARRAY(c_uint)), 'winEvents') + (['out', 'retval'], POINTER(_midlSAFEARRAY(c_uint)), 'winEvents'), ), ] @@ -7599,19 +7599,19 @@ class IUIAutomationPropertyCondition(IUIAutomationCondition): ['propget'], HRESULT, 'propertyId', - (['out', 'retval'], POINTER(c_int), 'propertyId') + (['out', 'retval'], POINTER(c_int), 'propertyId'), ), COMMETHOD( ['propget'], HRESULT, 'PropertyValue', - (['out', 'retval'], POINTER(VARIANT), 'PropertyValue') + (['out', 'retval'], POINTER(VARIANT), 'PropertyValue'), ), COMMETHOD( ['propget'], HRESULT, 'PropertyConditionFlags', - (['out', 'retval'], POINTER(PropertyConditionFlags), 'flags') + (['out', 'retval'], POINTER(PropertyConditionFlags), 'flags'), ), ] @@ -7646,7 +7646,7 @@ class IUIAutomationBoolCondition(IUIAutomationCondition): ['propget'], HRESULT, 'BooleanValue', - (['out', 'retval'], POINTER(c_int), 'boolVal') + (['out', 'retval'], POINTER(c_int), 'boolVal'), ), ] @@ -7675,13 +7675,13 @@ class IUIAutomationBoolCondition(IUIAutomationCondition): [], HRESULT, 'AddProperty', - (['in'], c_int, 'propertyId') + (['in'], c_int, 'propertyId'), ), COMMETHOD( [], HRESULT, 'AddPattern', - (['in'], c_int, 'patternId') + (['in'], c_int, 'patternId'), ), COMMETHOD( [], @@ -7691,43 +7691,43 @@ class IUIAutomationBoolCondition(IUIAutomationCondition): ['out', 'retval'], POINTER(POINTER(IUIAutomationCacheRequest)), 'clonedRequest', - ) + ), ), COMMETHOD( ['propget'], HRESULT, 'TreeScope', - (['out', 'retval'], POINTER(TreeScope), 'scope') + (['out', 'retval'], POINTER(TreeScope), 'scope'), ), COMMETHOD( ['propput'], HRESULT, 'TreeScope', - (['in'], TreeScope, 'scope') + (['in'], TreeScope, 'scope'), ), COMMETHOD( ['propget'], HRESULT, 'TreeFilter', - (['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'filter') + (['out', 'retval'], POINTER(POINTER(IUIAutomationCondition)), 'filter'), ), COMMETHOD( ['propput'], HRESULT, 'TreeFilter', - (['in'], POINTER(IUIAutomationCondition), 'filter') + (['in'], POINTER(IUIAutomationCondition), 'filter'), ), COMMETHOD( ['propget'], HRESULT, 'AutomationElementMode', - (['out', 'retval'], POINTER(AutomationElementMode), 'mode') + (['out', 'retval'], POINTER(AutomationElementMode), 'mode'), ), COMMETHOD( ['propput'], HRESULT, 'AutomationElementMode', - (['in'], AutomationElementMode, 'mode') + (['in'], AutomationElementMode, 'mode'), ), ] @@ -8174,7 +8174,7 @@ class CUIAutomation(CoClass): 'IUIAutomationFocusChangedEventHandler', 'UIA_IsActiveAttributeId', 'CoalesceEventsOptions_Enabled', 'UIA_IndentationLeadingAttributeId', 'UIA_SelectionItemPatternId', - 'RowOrColumnMajor_ColumnMajor' + 'RowOrColumnMajor_ColumnMajor', ] _check_version('1.2.0', 1691570609.765831) diff --git a/source/compoundDocuments.py b/source/compoundDocuments.py index 8e10b37f3ce..f23eae95c53 100644 --- a/source/compoundDocuments.py +++ b/source/compoundDocuments.py @@ -30,8 +30,10 @@ def _makeRawTextInfo(self, obj, position): return obj.makeTextInfo(position) def _normalizeStartAndEnd(self): - if (self._start.isCollapsed and self._startObj != self._endObj - and self._start.compareEndPoints(self._makeRawTextInfo(self._startObj, textInfos.POSITION_ALL), "endToEnd") == 0): + if ( + self._start.isCollapsed and self._startObj != self._endObj + and self._start.compareEndPoints(self._makeRawTextInfo(self._startObj, textInfos.POSITION_ALL), "endToEnd") == 0 + ): # Start it is at the end of its object. # This is equivalent to the start of the next content. # Aside from being pointless, we don't want a collapsed start object, as this will cause bogus control fields to be emitted. @@ -40,8 +42,10 @@ def _normalizeStartAndEnd(self): except LookupError: pass - if (self._end.isCollapsed and self._endObj != self._startObj - and self._end.compareEndPoints(self._makeRawTextInfo(self._endObj, textInfos.POSITION_FIRST), "startToStart") == 0): + if ( + self._end.isCollapsed and self._endObj != self._startObj + and self._end.compareEndPoints(self._makeRawTextInfo(self._endObj, textInfos.POSITION_FIRST), "startToStart") == 0 + ): # End is at the start of its object. # This is equivalent to the end of the previous content. # Aside from being pointless, we don't want a collapsed end object, as this will cause bogus control fields to be emitted. @@ -320,7 +324,7 @@ def getTextWithFields(self, formatConfig: Optional[Dict] = None) -> textInfos.Te fields.extend(( textInfos.FieldCommand("controlStart", controlField), textUtils.OBJ_REPLACEMENT_CHAR, - textInfos.FieldCommand("controlEnd", None) + textInfos.FieldCommand("controlEnd", None), )) else: # str or fieldCommand if not isinstance(textWithEmbeddedObjectsItem, (str, textInfos.FieldCommand)): diff --git a/source/config/__init__.py b/source/config/__init__.py index c0df546106d..725ab880884 100644 --- a/source/config/__init__.py +++ b/source/config/__init__.py @@ -88,7 +88,7 @@ def __getattr__(attrName: str) -> Any: if attrName == "addConfigDirsToPythonPackagePath" and NVDAState._allowDeprecatedAPI(): log.warning( "addConfigDirsToPythonPackagePath is deprecated, " - "use addonHandler.packaging.addDirsToPythonPackagePath instead." + "use addonHandler.packaging.addDirsToPythonPackagePath instead.", ) from addonHandler.packaging import addDirsToPythonPackagePath return addDirsToPythonPackagePath @@ -147,18 +147,18 @@ def isInstalledCopy() -> bool: try: k = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, - RegistryKey.INSTALLED_COPY.value + RegistryKey.INSTALLED_COPY.value, ) except FileNotFoundError: log.debug( f"Unable to find isInstalledCopy registry key {RegistryKey.INSTALLED_COPY}" - "- this is not an installed copy." + "- this is not an installed copy.", ) return False except WindowsError: log.error( f"Unable to open isInstalledCopy registry key {RegistryKey.INSTALLED_COPY}", - exc_info=True + exc_info=True, ) return False @@ -167,7 +167,7 @@ def isInstalledCopy() -> bool: except FileNotFoundError: log.debug( f"Unable to find UninstallDirectory value for {RegistryKey.INSTALLED_COPY}" - "- this may not be an installed copy." + "- this may not be an installed copy.", ) return False except WindowsError: @@ -181,7 +181,7 @@ def isInstalledCopy() -> bool: log.error( "Failed to access the installed NVDA directory," "or, a portable copy failed to access the current NVDA app directory", - exc_info=True + exc_info=True, ) return False @@ -299,13 +299,13 @@ def getStartAfterLogon() -> bool: except FileNotFoundError: log.debugWarning( f"Unable to find run registry key {RegistryKey.RUN}", - exc_info=True + exc_info=True, ) return False except WindowsError: log.error( f"Unable to open run registry key {RegistryKey.RUN}", - exc_info=True + exc_info=True, ) return False @@ -323,7 +323,7 @@ def getStartAfterLogon() -> bool: except WindowsError: log.error( "Failed to access the start after logon directory.", - exc_info=True + exc_info=True, ) return False @@ -335,7 +335,7 @@ def getStartAfterLogon() -> bool: except WindowsError: log.error( "Failed to access the current running NVDA directory.", - exc_info=True + exc_info=True, ) return False @@ -364,7 +364,7 @@ def setStartAfterLogon(enable: bool) -> None: except FileNotFoundError: log.debug( "The run registry key is not set for setStartAfterLogon." - "This is expected since ease of access is used" + "This is expected since ease of access is used", ) return try: @@ -372,7 +372,7 @@ def setStartAfterLogon(enable: bool) -> None: except WindowsError: log.error( "Couldn't unset registry key for nvda to start after logon.", - exc_info=True + exc_info=True, ) @@ -476,7 +476,7 @@ def setStartOnLogonScreen(enable: bool) -> None: if systemUtils.execElevated( SLAVE_FILENAME, ("config_setStartOnLogonScreen", "%d" % enable), - wait=True + wait=True, ) != 0: raise RuntimeError("Slave failed to set startOnLogonScreen") @@ -527,7 +527,7 @@ def __init__(self): #: Whether profile triggers are enabled (read-only). self.profileTriggersEnabled: bool = True self.validator: Validator = Validator({ - "_featureFlag": _validateConfig_featureFlag + "_featureFlag": _validateConfig_featureFlag, }) self.rootSection: Optional[AggregatedSection] = None self._shouldHandleProfileSwitch: bool = True @@ -785,8 +785,10 @@ def deleteProfile(self, name): # Remove any triggers associated with this profile. allTriggers = self.triggersToProfiles # You can't delete from a dict while iterating through it. - delTrigs = [trigSpec for trigSpec, trigProfile in allTriggers.items() - if trigProfile == name] + delTrigs = [ + trigSpec for trigSpec, trigProfile in allTriggers.items() + if trigProfile == name + ] if delTrigs: for trigSpec in delTrigs: del allTriggers[trigSpec] @@ -1069,7 +1071,7 @@ def __init__( manager: ConfigManager, path: Tuple[str], spec: ConfigObj, - profiles: List[ConfigObj] + profiles: List[ConfigObj], ): self.manager = manager self.path = path @@ -1086,7 +1088,7 @@ def _isSection(val: Any) -> bool: def __getitem__( self, key: aggregatedSection._cacheKeyT, - checkValidity: bool = True + checkValidity: bool = True, ): # Try the cache first. try: @@ -1228,7 +1230,7 @@ def dict(self): def __setitem__( self, key: aggregatedSection._cacheKeyT, - val: aggregatedSection._cacheValueT + val: aggregatedSection._cacheValueT, ): spec = self._spec.get(key) if self.spec else None if self._isSection(spec) and not self._isSection(val): @@ -1359,8 +1361,10 @@ def enter(self): try: conf._triggerProfileEnter(self) except: # noqa: E722 - log.error("Error entering trigger %s, profile %s" - % (self.spec, self.profileName), exc_info=True) + log.error( + "Error entering trigger %s, profile %s" + % (self.spec, self.profileName), exc_info=True, + ) __enter__ = enter def exit(self): @@ -1372,8 +1376,10 @@ def exit(self): try: conf._triggerProfileExit(self) except: # noqa: E722 - log.error("Error exiting trigger %s, profile %s" - % (self.spec, self.profileName), exc_info=True) + log.error( + "Error exiting trigger %s, profile %s" + % (self.spec, self.profileName), exc_info=True, + ) def __exit__(self, excType, excVal, traceback): self.exit() diff --git a/source/config/configFlags.py b/source/config/configFlags.py index 58fdda21994..5037c362984 100644 --- a/source/config/configFlags.py +++ b/source/config/configFlags.py @@ -112,7 +112,7 @@ def _displayStringLabels(self) -> dict["BrailleMode", str]: # Translators: The label for a braille mode BrailleMode.FOLLOW_CURSORS: _("follow cursors"), # Translators: The label for a braille mode - BrailleMode.SPEECH_OUTPUT: _("display speech output") + BrailleMode.SPEECH_OUTPUT: _("display speech output"), } diff --git a/source/config/configSpec.py b/source/config/configSpec.py index d50eed49a3d..73531ec31ca 100644 --- a/source/config/configSpec.py +++ b/source/config/configSpec.py @@ -330,5 +330,5 @@ #: The configuration specification #: @type: ConfigObj -confspec = ConfigObj(StringIO( configSpecString ), list_values=False, encoding="UTF-8") +confspec = ConfigObj(StringIO( configSpecString), list_values=False, encoding="UTF-8") confspec.newlines = "\r\n" diff --git a/source/config/featureFlag.py b/source/config/featureFlag.py index 95b6e488dbb..b47f6ae5e30 100644 --- a/source/config/featureFlag.py +++ b/source/config/featureFlag.py @@ -40,7 +40,7 @@ class FeatureFlag: def __init__( self, value: FlagValueEnum, - behaviorOfDefault: FlagValueEnum + behaviorOfDefault: FlagValueEnum, ): self.value = value self.enumClassType: typing.Type[FlagValueEnum] = type(value) @@ -51,7 +51,7 @@ def __init__( def __bool__(self) -> bool: if not isinstance(self.value, BoolFlag): raise NotImplementedError( - "Only BoolFlag supported. For other types use explicit checks" + "Only BoolFlag supported. For other types use explicit checks", ) if self.isDefault(): return bool(self.behaviorOfDefault) @@ -81,7 +81,7 @@ def __str__(self) -> str: def _validateConfig_featureFlag( value: Union[str, FeatureFlag, None], optionsEnum: str, - behaviorOfDefault: str + behaviorOfDefault: str, ) -> FeatureFlag: """ Used in conjunction with configObj.Validator param value: The value to be validated / converted to a FeatureFlag object. @@ -91,33 +91,33 @@ def _validateConfig_featureFlag( log.debug( f"Validating feature flag: {value}" f", optionsEnum: {optionsEnum}" - f", behaviorOfDefault: {behaviorOfDefault}" + f", behaviorOfDefault: {behaviorOfDefault}", ) if not isinstance(optionsEnum, str): raise ValidateError( 'Spec Error: optionsEnum must be specified as a string' - f" (got type {type(optionsEnum)} with value: {optionsEnum})" + f" (got type {type(optionsEnum)} with value: {optionsEnum})", ) try: OptionsEnumClass = dict(featureFlagEnums.getAvailableEnums())[optionsEnum] except KeyError: raise ValidateError( "Spec Error: optionsEnum must be an enum defined in the config.featureFlagEnums module." - f" (got {optionsEnum})" + f" (got {optionsEnum})", ) if not isinstance(behaviorOfDefault, str): raise ValidateError( 'Spec Error: behaviorOfDefault must be specified as a valid' f' {OptionsEnumClass.__qualname__} member string' - f" (got type {type(behaviorOfDefault)} with value: {behaviorOfDefault})" + f" (got type {type(behaviorOfDefault)} with value: {behaviorOfDefault})", ) try: behaviorOfDefault = OptionsEnumClass[behaviorOfDefault.upper()] except KeyError: raise ValidateError( "Spec Error: behaviorOfDefault must be specified as a valid enum member string for enum class " - f"{OptionsEnumClass.__qualname__} (got {behaviorOfDefault})" + f"{OptionsEnumClass.__qualname__} (got {behaviorOfDefault})", ) if behaviorOfDefault == OptionsEnumClass.DEFAULT: raise ValidateError("Spec Error: behaviorOfDefault must not be 'default'/'DEFAULT'") @@ -128,7 +128,7 @@ def _validateConfig_featureFlag( if not isinstance(value, str): raise ValidateError( 'Expected a featureFlag value in the form of a string. EG "disabled", "enabled", or "default".' - f" Got {type(value)} with value: {value} instead." + f" Got {type(value)} with value: {value} instead.", ) try: @@ -136,7 +136,7 @@ def _validateConfig_featureFlag( except KeyError: raise ValidateError( "FeatureFlag value must be specified as a valid enum member string for enum class " - f"{OptionsEnumClass.__qualname__} (got {value})" + f"{OptionsEnumClass.__qualname__} (got {value})", ) return FeatureFlag(value, behaviorOfDefault) @@ -158,22 +158,23 @@ def _transformSpec_AddFeatureFlagDefault(specString: str, **kwargs) -> str: if "default=" in specString: raise VdtParamError( name_or_msg=f"Param 'default' not expected. {usage}", - value=specString + value=specString, ) optionsEnumKey = "optionsEnum" if optionsEnumKey not in kwargs: raise VdtParamError( name_or_msg=f"Param '{optionsEnumKey}' missing. {usage}", - value=specString + value=specString, ) optionsEnumVal = kwargs[optionsEnumKey] if not isinstance(optionsEnumVal, str): raise VdtParamError( name_or_msg=( f"Param '{optionsEnumKey}' should have a string value" - f" but got {type(optionsEnumVal)}. {usage}"), - value=specString + f" but got {type(optionsEnumVal)}. {usage}" + ), + value=specString, ) availableEnums = dict(featureFlagEnums.getAvailableEnums()) if optionsEnumVal not in availableEnums: @@ -182,22 +183,23 @@ def _transformSpec_AddFeatureFlagDefault(specString: str, **kwargs) -> str: f"Param '{optionsEnumKey}' should be an enum defined in featureFlagEnums," f" but was {optionsEnumVal}. Currently available: {availableEnums.keys()} " ), - value=specString + value=specString, ) OptionsEnumClass: enum.EnumMeta = availableEnums[optionsEnumVal] behaviorOfDefaultKey = "behaviorOfDefault" if behaviorOfDefaultKey not in kwargs: raise VdtParamError( name_or_msg=f"Param '{behaviorOfDefaultKey}' missing. {usage}", - value=specString + value=specString, ) behaviorOfDefaultVal = kwargs[behaviorOfDefaultKey] if not isinstance(behaviorOfDefaultVal, str): raise VdtParamError( name_or_msg=( f"Param '{behaviorOfDefaultKey}' should have a string value" - f" but got {type(behaviorOfDefaultVal)}. {usage}"), - value=specString + f" but got {type(behaviorOfDefaultVal)}. {usage}" + ), + value=specString, ) behaviorOfDefaultVal = behaviorOfDefaultVal.upper() try: @@ -208,7 +210,7 @@ def _transformSpec_AddFeatureFlagDefault(specString: str, **kwargs) -> str: f"Param '{behaviorOfDefaultKey}' should be one of: {[o.name for o in OptionsEnumClass]}" f" but was {behaviorOfDefaultVal}. {usage}" ), - value=specString + value=specString, ) if len(kwargs) != 2: raise VdtParamError( @@ -216,7 +218,7 @@ def _transformSpec_AddFeatureFlagDefault(specString: str, **kwargs) -> str: "Unexpected number of params." f" Got {kwargs}. {usage}" ), - value=specString + value=specString, ) # ensure there is the expected default retString = ( diff --git a/source/config/featureFlagEnums.py b/source/config/featureFlagEnums.py index b6ea0e6c15f..bf87fd14396 100644 --- a/source/config/featureFlagEnums.py +++ b/source/config/featureFlagEnums.py @@ -59,7 +59,7 @@ def __bool__(self): if self == BoolFlag.DEFAULT: raise ValueError( "Only ENABLED or DISABLED are valid bool values" - ", DEFAULT must be combined with a 'behavior for default' to be Truthy or Falsy" + ", DEFAULT must be combined with a 'behavior for default' to be Truthy or Falsy", ) return self == BoolFlag.ENABLED @@ -73,7 +73,7 @@ def _displayStringLabels(self): # Translators: Label for a paragraph style in NVDA settings. self.SINGLE_LINE_BREAK: _("Single line break"), # Translators: Label for a paragraph style in NVDA settings. - self.MULTI_LINE_BREAK: _("Multi line break") + self.MULTI_LINE_BREAK: _("Multi line break"), } DEFAULT = enum.auto() @@ -91,7 +91,7 @@ def _displayStringLabels(self): # Translators: Label for setting to move the system caret when routing review cursor with braille. self.ONLY_WHEN_AUTO_TETHERED: _("Only when tethered automatically"), # Translators: Label for setting to move the system caret when routing review cursor with braille. - self.ALWAYS: _("Always") + self.ALWAYS: _("Always"), } DEFAULT = enum.auto() diff --git a/source/config/profileUpgradeSteps.py b/source/config/profileUpgradeSteps.py index d2271e28765..af0bf0e0099 100644 --- a/source/config/profileUpgradeSteps.py +++ b/source/config/profileUpgradeSteps.py @@ -249,7 +249,7 @@ def _upgradeConfigFrom_8_to_9_showMessages(profile: ConfigObj) -> None: # So we fix it with ShowMessages.DISABLED but also issue a warning. log.debugWarning( "Invalid config found: noMessageTimeout=True and messageTimeout=0." - " Fixing it with setting showMessages on DISABLE." + " Fixing it with setting showMessages on DISABLE.", ) else: if noMessageTimeoutVal: @@ -286,7 +286,7 @@ def _upgradeConfigFrom_8_to_9_tetherTo(profile: ConfigObj) -> None: # "Review") and the current profile has this option set to "Focus". # In this case, tetherTo keeps the same value. log.debug( - "autoTether not present in config but tetherTo present, no action taken (keeping tetherTo value)." + "autoTether not present in config but tetherTo present, no action taken (keeping tetherTo value).", ) elif isTetherToMissing: if autoTetherVal: @@ -345,7 +345,7 @@ def upgradeConfigFrom_9_to_10(profile: ConfigObj) -> None: # Thus we consider case 1 which is the only use case reachable by the user via NVDA's GUI. log.debug( "No True value for any of 'use*AsNVDAModifierKey'," - " restore caps lock (only possible case via NVDA's GUI)." + " restore caps lock (only possible case via NVDA's GUI).", ) val = NVDAKey.CAPS_LOCK.value profile['keyboard']['NVDAModifierKeys'] = val @@ -374,5 +374,5 @@ def upgradeConfigFrom_10_to_11(profile: ConfigObj) -> None: profile['braille']['auto']['excludedDisplays'] += ["hidBrailleStandard"] log.debug( "hidBrailleStandard added to braille display auto detection excluded displays. " - f"List is now: {profile['braille']['auto']['excludedDisplays']}" + f"List is now: {profile['braille']['auto']['excludedDisplays']}", ) diff --git a/source/config/profileUpgrader.py b/source/config/profileUpgrader.py index 3a1efc6e342..15a8423e70e 100644 --- a/source/config/profileUpgrader.py +++ b/source/config/profileUpgrader.py @@ -59,7 +59,7 @@ def _doValidation(profile, validator): u"Unable to validate config file after upgrade: Key {0} : {1}\n" + "Full result: (value of false means the key was not present)\n" + "{2}" - ).format(key, value, flatResult) + ).format(key, value, flatResult) raise ValueError(errorString) def _ensureVersionProperty(profile): diff --git a/source/contentRecog/__init__.py b/source/contentRecog/__init__.py index 4e3ab1e97b9..751d9f93d21 100644 --- a/source/contentRecog/__init__.py +++ b/source/contentRecog/__init__.py @@ -113,7 +113,7 @@ def __init__( screenTop: int, screenWidth: int, screenHeight: int, - resizeFactor: Union[int, float] + resizeFactor: Union[int, float], ): """ @param screenLeft: The x screen coordinate of the upper-left corner of the image. @@ -143,7 +143,7 @@ def createFromRecognizer( screenTop: int, screenWidth: int, screenHeight: int, - recognizer: ContentRecognizer + recognizer: ContentRecognizer, ): """Convenience method to construct an instance using a L{ContentRecognizer}. The resize factor is obtained by calling L{ContentRecognizer.getResizeFactor}. @@ -242,13 +242,15 @@ def _parseData(self): # Separate with a space. self._textList.append(" ") self.textLen += 1 - self.words.append(LwrWord( - self.textLen, - self.imageInfo.convertXToScreen(word["x"]), - self.imageInfo.convertYToScreen(word["y"]), - self.imageInfo.convertWidthToScreen(word["width"]), - self.imageInfo.convertHeightToScreen(word["height"])) - ) + self.words.append( + LwrWord( + self.textLen, + self.imageInfo.convertXToScreen(word["x"]), + self.imageInfo.convertYToScreen(word["y"]), + self.imageInfo.convertWidthToScreen(word["width"]), + self.imageInfo.convertHeightToScreen(word["height"]), + ), + ) text = word["text"] self._textList.append(text) self.textLen += len(text) diff --git a/source/contentRecog/recogUi.py b/source/contentRecog/recogUi.py index 63679e76fa9..38eb3c48d33 100644 --- a/source/contentRecog/recogUi.py +++ b/source/contentRecog/recogUi.py @@ -114,7 +114,7 @@ def __init__( self, recognizer: ContentRecognizer, imageInfo: RecogImageInfo, - obj: Optional[NVDAObjects.NVDAObject] = None + obj: Optional[NVDAObjects.NVDAObject] = None, ): self.recognizer = recognizer self.imageInfo = imageInfo @@ -131,7 +131,7 @@ def _recognize(self, onResult: onRecognizeResultCallbackT): sb = screenBitmap.ScreenBitmap(imgInfo.recogWidth, imgInfo.recogHeight) pixels = sb.captureImage( imgInfo.screenLeft, imgInfo.screenTop, - imgInfo.screenWidth, imgInfo.screenHeight + imgInfo.screenWidth, imgInfo.screenHeight, ) self.recognizer.recognize(pixels, self.imageInfo, onResult) @@ -145,7 +145,7 @@ def _onFirstResult(self, result: Union[RecognitionResult, Exception]): queueHandler.eventQueue, ui.message, # Translators: Reported when recognition (e.g. OCR) fails. - _("Recognition failed") + _("Recognition failed"), ) return self.result = result @@ -168,7 +168,7 @@ def _onResult(self, result: Union[RecognitionResult, Exception]): queueHandler.eventQueue, ui.message, # Translators: Reported when recognition (e.g. OCR) fails during automatic refresh. - _("Automatic refresh of recognition result failed") + _("Automatic refresh of recognition result failed"), ) self.stopMonitoring() return diff --git a/source/controlTypes/__init__.py b/source/controlTypes/__init__.py index ea2bf417687..a7897d026d5 100644 --- a/source/controlTypes/__init__.py +++ b/source/controlTypes/__init__.py @@ -35,5 +35,5 @@ "TextPosition", "transformRoleStates", "VerticalTextAlign", - *deprecatedAliases.__all__ + *deprecatedAliases.__all__, ] diff --git a/source/controlTypes/deprecatedAliases.py b/source/controlTypes/deprecatedAliases.py index 3de9e39a45b..8919ea9460a 100644 --- a/source/controlTypes/deprecatedAliases.py +++ b/source/controlTypes/deprecatedAliases.py @@ -23,7 +23,7 @@ ) from .processAndLabelStates import ( _processNegativeStates, - _processPositiveStates + _processPositiveStates, ) # Do not extend diff --git a/source/controlTypes/formatFields.py b/source/controlTypes/formatFields.py index e0e90da2adf..f8b84e8576d 100644 --- a/source/controlTypes/formatFields.py +++ b/source/controlTypes/formatFields.py @@ -74,7 +74,7 @@ class FontSize: # Translators: A measurement unit of font size. "larger": pgettext("font size", "larger"), # Translators: A measurement unit of font size. - "smaller": pgettext("font size", "smaller") + "smaller": pgettext("font size", "smaller"), } _measurementRe = re.compile(r"([0-9\.]+)(px|em|ex|rem|pt|%)") diff --git a/source/controlTypes/processAndLabelStates.py b/source/controlTypes/processAndLabelStates.py index 7ccb6a5402e..0cf1f113807 100644 --- a/source/controlTypes/processAndLabelStates.py +++ b/source/controlTypes/processAndLabelStates.py @@ -14,7 +14,7 @@ def _processPositiveStates( role: Role, states: Set[State], reason: OutputReason, - positiveStates: Optional[Set[State]] = None + positiveStates: Optional[Set[State]] = None, ) -> Set[State]: """Processes the states for an object and returns the positive states to output for a specified reason. For example, if C{State.CHECKED} is in the returned states, it means that the processed object is checked. @@ -81,7 +81,7 @@ def _processNegativeStates( role: Role, states: Set[State], reason: OutputReason, - negativeStates: Optional[Set[State]] = None + negativeStates: Optional[Set[State]] = None, ) -> Set[State]: """Processes the states for an object and returns the negative states to output for a specified reason. For example, if C{State.CHECKED} is in the returned states, it means that the processed object is not diff --git a/source/core.py b/source/core.py index dd778fb1a71..d79252b7cb8 100644 --- a/source/core.py +++ b/source/core.py @@ -43,7 +43,7 @@ def __getattr__(attrName: str) -> Any: from winAPI.messageWindow import pre_handleWindowMessage log.warning( "core.post_windowMessageReceipt is deprecated, " - "use winAPI.messageWindow.pre_handleWindowMessage instead." + "use winAPI.messageWindow.pre_handleWindowMessage instead.", ) return pre_handleWindowMessage raise AttributeError(f"module {repr(__name__)} has no attribute {repr(attrName)}") @@ -84,8 +84,8 @@ def _showAddonsErrors() -> None: # Translators: Shown when one or more add-ons failed to update. "The following add-on failed to update: {}.", "The following add-ons failed to update: {}.", - len(failedUpdates) - ).format(", ".join(failedUpdates)) + len(failedUpdates), + ).format(", ".join(failedUpdates)), ) if failedRemovals: addonFailureMessages.append( @@ -93,8 +93,8 @@ def _showAddonsErrors() -> None: # Translators: Shown when one or more add-ons failed to be uninstalled. "The following add-on failed to uninstall: {}.", "The following add-ons failed to uninstall: {}.", - len(failedRemovals) - ).format(", ".join(failedRemovals)) + len(failedRemovals), + ).format(", ".join(failedRemovals)), ) if failedInstalls: addonFailureMessages.append( @@ -102,8 +102,8 @@ def _showAddonsErrors() -> None: # Translators: Shown when one or more add-ons failed to be installed. "The following add-on failed to be installed: {}.", "The following add-ons failed to be installed: {}.", - len(failedInstalls) - ).format(", ".join(failedInstalls)) + len(failedInstalls), + ).format(", ".join(failedInstalls)), ) if addonFailureMessages: @@ -112,11 +112,11 @@ def _showAddonsErrors() -> None: gui.messageBox( _( # Translators: Shown when one or more actions on add-ons failed. - "Some operations on add-ons failed. See the log file for more details.\n{}" + "Some operations on add-ons failed. See the log file for more details.\n{}", ).format("\n".join(addonFailureMessages)), # Translators: Title of message shown when requested action on add-ons failed. _("Error"), - wx.ICON_ERROR | wx.OK + wx.ICON_ERROR | wx.OK, ) @@ -143,23 +143,26 @@ def handleReplaceCLIArg(cliArgument: str) -> bool: gui.messageBox( # Translators: Shown when NVDA has been started with unknown command line parameters. _("The following command line parameters are unknown to NVDA: {params}").format( - params=", ".join(unknownCLIParams) + params=", ".join(unknownCLIParams), ), # Translators: Title of the dialog letting user know # that command line parameters they provided are unknown. _("Unknown command line parameters"), - wx.OK | wx.ICON_ERROR + wx.OK | wx.ICON_ERROR, ) if config.conf.baseConfigError: import wx gui.messageBox( # Translators: A message informing the user that there are errors in the configuration file. - _("Your configuration file contains errors. " - "Your configuration has been reset to factory defaults.\n" - "More details about the errors can be found in the log file."), + _( + "Your configuration file contains errors. " + "Your configuration has been reset to factory defaults.\n" + "More details about the errors can be found in the log file.", + ), # Translators: The title of the dialog to tell users that there are errors in the configuration file. _("Configuration File Error"), - wx.OK | wx.ICON_EXCLAMATION) + wx.OK | wx.ICON_EXCLAMATION, + ) if config.conf["general"]["showWelcomeDialogAtStartup"]: from gui.startupDialogs import WelcomeDialog WelcomeDialog.run() @@ -170,9 +173,13 @@ def handleReplaceCLIArg(cliArgument: str) -> bool: import inputCore if inputCore.manager.userGestureMap.lastUpdateContainedError: import wx - gui.messageBox(_("Your gesture map file contains errors.\n" - "More details about the errors can be found in the log file."), - _("gesture map File Error"), wx.OK|wx.ICON_EXCLAMATION) + gui.messageBox( + _( + "Your gesture map file contains errors.\n" + "More details about the errors can be found in the log file.", + ), + _("gesture map File Error"), wx.OK|wx.ICON_EXCLAMATION, + ) try: import updateCheck except RuntimeError: @@ -226,11 +233,13 @@ def restartUnsafely(): options = [] if NVDAState.isRunningAsSource(): options.append(os.path.basename(sys.argv[0])) - _startNewInstance(NewNVDAInstance( - sys.executable, - subprocess.list2cmdline(options + sys.argv[1:]), - globalVars.appDir - )) + _startNewInstance( + NewNVDAInstance( + sys.executable, + subprocess.list2cmdline(options + sys.argv[1:]), + globalVars.appDir, + ), + ) def restart(disableAddons=False, debugLogging=False): @@ -242,7 +251,7 @@ def restart(disableAddons=False, debugLogging=False): return import subprocess for paramToRemove in ( - "--disable-addons", "--debug-logging", "--ease-of-access" + "--disable-addons", "--debug-logging", "--ease-of-access", ) + languageHandler.getLanguageCliArgs(): try: sys.argv.remove(paramToRemove) @@ -256,11 +265,13 @@ def restart(disableAddons=False, debugLogging=False): if debugLogging: options.append('--debug-logging') - if not triggerNVDAExit(NewNVDAInstance( - sys.executable, - subprocess.list2cmdline(options + sys.argv[1:]), - globalVars.appDir - )): + if not triggerNVDAExit( + NewNVDAInstance( + sys.executable, + subprocess.list2cmdline(options + sys.argv[1:]), + globalVars.appDir, + ), + ): log.error("NVDA already in process of exiting, this indicates a logic error.") @@ -396,7 +407,7 @@ def _startNewInstance(newNVDA: NewNVDAInstance): parameters=newNVDA.parameters, directory=newNVDA.directory, # #4475: ensure that the first window of the new process is not hidden by providing SW_SHOWNORMAL - showCmd=SW_SHOWNORMAL + showCmd=SW_SHOWNORMAL, ) @@ -454,7 +465,7 @@ def _closeAllWindows(): if state is _SettingsDialog.DialogState.DESTROYED: log.debugWarning( "Destroyed but not deleted instance of gui.SettingsDialog exists" - f": {instance.title} - {instance.__class__.__qualname__} - {instance}" + f": {instance.title} - {instance.__class__.__qualname__} - {instance}", ) else: log.debug("Exiting NVDA with an open settings dialog: {!r}".format(instance)) @@ -593,7 +604,7 @@ def onEndSession(evt): try: nvwave.playWaveFile( os.path.join(globalVars.appDir, "waves", "exit.wav"), - asynchronous=False + asynchronous=False, ) except Exception: log.exception("Error playing exit sound") @@ -630,7 +641,7 @@ def main(): ) ): WritePaths.configDir = config.getUserDefaultConfigPath( - useInstalledPathIfExists=globalVars.appArgs.launcher + useInstalledPathIfExists=globalVars.appArgs.launcher, ) #Initialize the config path (make sure it exists) config.initConfigPath() @@ -802,7 +813,7 @@ def main(): wx.CallAfter( gui.installerGui.doSilentInstall, copyPortableConfig=globalVars.appArgs.copyPortableConfig, - startAfterInstall=not globalVars.appArgs.installSilent + startAfterInstall=not globalVars.appArgs.installSilent, ) elif globalVars.appArgs.portablePath and (globalVars.appArgs.createPortable or globalVars.appArgs.createPortableSilent): import gui.installerGui @@ -934,7 +945,7 @@ def _doPostNvdaStartupAction(): if triggerNVDAExit(): log.debug( "NVDA not already exiting, hit catch-all exit trigger." - " This likely indicates NVDA is exiting due to WM_QUIT." + " This likely indicates NVDA is exiting due to WM_QUIT.", ) queueHandler.pumpAll() _terminate(gui) @@ -983,7 +994,7 @@ def _doPostNvdaStartupAction(): try: nvwave.playWaveFile( os.path.join(globalVars.appDir, "waves", "exit.wav"), - asynchronous=False + asynchronous=False, ) except: # noqa: E722 pass diff --git a/source/cursorManager.py b/source/cursorManager.py index ec8b3f083e5..1f8184d7862 100644 --- a/source/cursorManager.py +++ b/source/cursorManager.py @@ -78,7 +78,7 @@ def onOk(self, evt): self.activeCursorManager.doFindText, text, caseSensitive=caseSensitive, - reverse=self.reverse + reverse=self.reverse, ) self.Destroy() @@ -193,7 +193,7 @@ def doFindText(self, text, reverse=False, caseSensitive=False, willSayAllResume= # Translators: message dialog title displayed to the user when # searching text and no text is found. _("0 matches"), - wx.OK | wx.ICON_INFORMATION + wx.OK | wx.ICON_INFORMATION, ) CursorManager._lastFindText=text CursorManager._lastCaseSensitivity=caseSensitive @@ -212,7 +212,7 @@ def run(): @script( description=_( # Translators: Input help message for find next command. - "find the next occurrence of the previously entered text string from the current cursor's position" + "find the next occurrence of the previously entered text string from the current cursor's position", ), gesture="kb:NVDA+f3", resumeSayAllMode=sayAll.CURSOR.CARET, @@ -230,7 +230,7 @@ def script_findNext(self,gesture): @script( description=_( # Translators: Input help message for find previous command. - "find the previous occurrence of the previously entered text string from the current cursor's position" + "find the previous occurrence of the previously entered text string from the current cursor's position", ), gesture="kb:NVDA+shift+f3", resumeSayAllMode=sayAll.CURSOR.CARET, @@ -296,7 +296,8 @@ def _handleParagraphNavigation(self, gesture: InputGesture, nextParagraph: bool) passKey, moved = moveToMultiLineBreakParagraph( nextParagraph=nextParagraph, speakNew=not willSayAllResume(gesture), - ti=ti) + ti=ti, + ) if moved: self.selection = ti elif passKey: diff --git a/source/diffHandler.py b/source/diffHandler.py index 6dc6e858de1..ecc3561bb60 100644 --- a/source/diffHandler.py +++ b/source/diffHandler.py @@ -46,9 +46,11 @@ def _initialize(self): if not DiffMatchPatch._proc: log.debug("Starting diff-match-patch proxy") if NVDAState.isRunningAsSource(): - dmp_path = (sys.executable, os.path.join( - globalVars.appDir, "..", "include", "nvda_dmp", "nvda_dmp.py" - )) + dmp_path = ( + sys.executable, os.path.join( + globalVars.appDir, "..", "include", "nvda_dmp", "nvda_dmp.py", + ), + ) else: dmp_path = (os.path.join(globalVars.appDir, "nvda_dmp.exe"),) DiffMatchPatch._proc = subprocess.Popen( @@ -56,7 +58,7 @@ def _initialize(self): creationflags=subprocess.CREATE_NO_WINDOW, bufsize=0, stdin=subprocess.PIPE, - stdout=subprocess.PIPE + stdout=subprocess.PIPE, ) def _getText(self, ti: TextInfo) -> str: diff --git a/source/displayModel.py b/source/displayModel.py index 569ae8e111a..6ccfde4fd05 100644 --- a/source/displayModel.py +++ b/source/displayModel.py @@ -27,7 +27,7 @@ List, Tuple, Optional, - Dict + Dict, ) #: A text info unit constant for a single chunk in a display model @@ -186,7 +186,7 @@ def getCaretRect(obj): ctypes.byref(left), ctypes.byref(top), ctypes.byref(right), - ctypes.byref(bottom) + ctypes.byref(bottom), ) if res != 0: raise RuntimeError(f"displayModel_getCaretRect failed with res {res}") @@ -194,7 +194,7 @@ def getCaretRect(obj): left.value, top.value, right.value, - bottom.value + bottom.value, ) def getWindowTextInRect(bindingHandle, windowHandle, left, top, right, bottom,minHorizontalWhitespace,minVerticalWhitespace,stripOuterWhitespace=True,includeDescendantWindows=True): @@ -209,7 +209,7 @@ def getWindowTextInRect(bindingHandle, windowHandle, left, top, right, bottom,mi wcharToInt(cp), wcharToInt(next(cpBufIt)), wcharToInt(next(cpBufIt)), - wcharToInt(next(cpBufIt)) + wcharToInt(next(cpBufIt)), ) if right < left: left, right = right, left @@ -302,7 +302,7 @@ def _get__storyFieldsAndRects(self) -> Tuple[ List[textInfos.TextInfo.TextOrFieldsT], List[RectLTRB], List[int], - List[int] + List[int], ]: # All returned coordinates are logical coordinates. if self._location: @@ -590,7 +590,7 @@ def _findCaretOffsetFromLocation( self, caretRect: RectLTRB, validateBaseline: bool = True, - validateDirection: bool = True + validateDirection: bool = True, ): # Accepts logical coordinates. for charOffset, ((charLeft, charTop, charRight, charBottom),charBaseline,charDirection) in enumerate(self._getStoryOffsetLocations()): diff --git a/source/documentBase.py b/source/documentBase.py index 6f79df3822d..143c3e0d507 100644 --- a/source/documentBase.py +++ b/source/documentBase.py @@ -289,7 +289,7 @@ def _getFirstOrLastTableCell( startPos: textInfos.TextInfo, cell: _TableCell, movement: _Movement, - axis: _Axis + axis: _Axis, ) -> textInfos.TextInfo: """ Locates the first or last cell in current row or column given coordinates of current cell. @@ -366,7 +366,7 @@ def _tableFindNewCell( self.selection, cell, movement, - axis + axis, ) elif movement is None: info = self._getTableCellAt(cell.tableID, self.selection, cell.row, cell.col) @@ -399,7 +399,7 @@ def _tableFindNewCell( def _tableMovementScriptHelper( self, movement: _Movement = _Movement.NEXT, - axis: Optional[_Axis] = None + axis: Optional[_Axis] = None, ): # documentBase is a core module and should not depend on these UI modules and so they are imported # at run-time. (#12404) @@ -510,7 +510,7 @@ def script_sayAllRow(self, gesture): self._tableSayAll(_Movement.NEXT, _Axis.COLUMN) script_sayAllRow.__doc__ = _( # Translators: the description for the sayAll row command - "Reads the row horizontally from the current cell rightwards to the last cell in the row." + "Reads the row horizontally from the current cell rightwards to the last cell in the row.", ) script_sayAllRow.speakOnDemand = True @@ -519,7 +519,7 @@ def script_sayAllColumn(self, gesture): self._tableSayAll(_Movement.NEXT, _Axis.ROW) script_sayAllColumn.__doc__ = _( # Translators: the description for the sayAll row command - "Reads the column vertically from the current cell downwards to the last cell in the column." + "Reads the column vertically from the current cell downwards to the last cell in the column.", ) script_sayAllColumn.speakOnDemand = True @@ -528,7 +528,7 @@ def script_speakRow(self, gesture): script_speakRow.__doc__ = _( # Translators: the description for the speak row command "Reads the current row horizontally from left to right " - "without moving the system caret." + "without moving the system caret.", ) script_speakRow.speakOnDemand = True @@ -537,7 +537,7 @@ def script_speakColumn(self, gesture): script_speakColumn.__doc__ = _( # Translators: the description for the speak column command "Reads the current column vertically from top to bottom " - "without moving the system caret." + "without moving the system caret.", ) script_speakColumn.speakOnDemand = True diff --git a/source/documentNavigation/paragraphHelper.py b/source/documentNavigation/paragraphHelper.py index b68f4c978a0..a85b82c86cf 100644 --- a/source/documentNavigation/paragraphHelper.py +++ b/source/documentNavigation/paragraphHelper.py @@ -179,7 +179,7 @@ def _moveTextInfoToSingleLineBreakParagraph(nextParagraph: bool, ti: textInfos.T def moveToSingleLineBreakParagraph( nextParagraph: bool, speakNew: bool, - ti: textInfos.TextInfo = None + ti: textInfos.TextInfo = None, ) -> Tuple[bool, bool]: """ Moves to the previous or next paragraph which is delimited by a single line break. @@ -268,7 +268,7 @@ def _moveTextInfoToMultiLineBreakParagraph(nextParagraph: bool, ti: textInfos.Te def moveToMultiLineBreakParagraph( nextParagraph: bool, speakNew: bool, - ti: textInfos.TextInfo = None + ti: textInfos.TextInfo = None, ) -> Tuple[bool, bool]: """ Moves to the previous or next paragraph delineated by one or more blank lines. diff --git a/source/easeOfAccess.py b/source/easeOfAccess.py index cf6aa04b076..f53328a9b02 100644 --- a/source/easeOfAccess.py +++ b/source/easeOfAccess.py @@ -53,7 +53,7 @@ def isRegistered() -> bool: winreg.HKEY_LOCAL_MACHINE, RegistryKey.APP.value, 0, - winreg.KEY_READ | winreg.KEY_WOW64_64KEY + winreg.KEY_READ | winreg.KEY_WOW64_64KEY, ) return True except FileNotFoundError: @@ -115,7 +115,7 @@ def _getAutoStartConfiguration(autoStartContext: AutoStartContext) -> List[str]: autoStartContext.value, RegistryKey.ROOT.value, 0, - winreg.KEY_READ | winreg.KEY_WOW64_64KEY + winreg.KEY_READ | winreg.KEY_WOW64_64KEY, ) except FileNotFoundError: log.debug(f"Unable to find existing {autoStartContext} {RegistryKey.ROOT}") @@ -164,12 +164,12 @@ def setAutoStart(autoStartContext: AutoStartContext, enable: bool) -> None: autoStartContext.value, RegistryKey.ROOT.value, 0, - winreg.KEY_READ | winreg.KEY_WRITE | winreg.KEY_WOW64_64KEY + winreg.KEY_READ | winreg.KEY_WRITE | winreg.KEY_WOW64_64KEY, ) winreg.SetValueEx( k, "Configuration", None, winreg.REG_SZ, - ",".join(conf) + ",".join(conf), ) diff --git a/source/editableText.py b/source/editableText.py index 7d0d1afa222..1eb196c2afe 100755 --- a/source/editableText.py +++ b/source/editableText.py @@ -96,7 +96,7 @@ def _hasCaretMoved(self, bookmark, retryInterval=0.01, timeout=None, origWord=No ): log.debug( "Caret move detected using event. Elapsed %g sec, retries %d" - % (elapsed, retries) + % (elapsed, retries), ) # We must fetch the caret here rather than above the isPendingEvents check # to avoid a race condition where an event is queued from a background @@ -123,7 +123,7 @@ def _hasCaretMoved(self, bookmark, retryInterval=0.01, timeout=None, origWord=No if newBookmark and newBookmark!=bookmark: log.debug( "Caret move detected using bookmarks. Elapsed %g sec, retries %d" - % (elapsed, retries) + % (elapsed, retries), ) return (True, newInfo) if origWord is not None and newInfo and elapsed >= self._hasCaretMoved_minWordTimeoutSec: @@ -224,7 +224,7 @@ def script_caret_newLine(self,gesture): unit=textInfos.UNIT_LINE, reason=controlTypes.OutputReason.CARET, onlyInitialFields=onlyInitial, - suppressBlanks=True + suppressBlanks=True, ) def _caretMoveBySentenceHelper(self, gesture, direction): @@ -327,7 +327,7 @@ def _handleParagraphNavigation(self, gesture: InputGesture, nextParagraph: bool) from documentNavigation.paragraphHelper import moveToSingleLineBreakParagraph passKey, moved = moveToSingleLineBreakParagraph( nextParagraph=nextParagraph, - speakNew=not willSayAllResume(gesture) + speakNew=not willSayAllResume(gesture), ) if passKey: self.script_caret_moveByParagraph(gesture) @@ -335,7 +335,7 @@ def _handleParagraphNavigation(self, gesture: InputGesture, nextParagraph: bool) from documentNavigation.paragraphHelper import moveToMultiLineBreakParagraph passKey, moved = moveToMultiLineBreakParagraph( nextParagraph=nextParagraph, - speakNew=not willSayAllResume(gesture) + speakNew=not willSayAllResume(gesture), ) if passKey: self.script_caret_moveByParagraph(gesture) diff --git a/source/eventHandler.py b/source/eventHandler.py index 8111ccb2df1..2a51153cd8a 100755 --- a/source/eventHandler.py +++ b/source/eventHandler.py @@ -61,7 +61,7 @@ def queueEvent(eventName,obj,**kwargs): eventName, obj, kwargs, - _immediate=eventName == "gainFocus" + _immediate=eventName == "gainFocus", ) @@ -124,11 +124,13 @@ def next(self): try: return func(*args, **self.kwargs) except TypeError: - log.warning("Could not execute function {func} defined in {module} module; kwargs: {kwargs}".format( - func=func.__name__, - module=func.__module__ or "unknown", - kwargs=self.kwargs - ), exc_info=True) + log.warning( + "Could not execute function {func} defined in {module} module; kwargs: {kwargs}".format( + func=func.__name__, + module=func.__module__ or "unknown", + kwargs=self.kwargs, + ), exc_info=True, + ) return extensionPoints.callWithSupportedKwargs(func, *args, **self.kwargs) def gen(self, eventName, obj): @@ -265,7 +267,7 @@ def isMenuItemOfCurrentFocus(self) -> bool: and self._obj.IAccessibleRole in ( oleacc.ROLE_SYSTEM_MENUITEM, IA2.IA2_ROLE_CHECK_MENU_ITEM, - IA2.IA2_ROLE_RADIO_MENU_ITEM + IA2.IA2_ROLE_RADIO_MENU_ITEM, ) and lastFocus.IAccessibleRole == oleacc.ROLE_SYSTEM_MENUPOPUP and self._obj.parent @@ -279,7 +281,7 @@ def isMenuItemOfCurrentFocus(self) -> bool: log.debugWarning( "This ancestor menu was not announced properly, and should have been focused before the submenu item.\n" f"Object info: {self._obj.devInfo}\n" - f"Ancestor info: {ancestor.devInfo}" + f"Ancestor info: {ancestor.devInfo}", ) return True @@ -290,7 +292,7 @@ def isMenuItemOfCurrentFocus(self) -> bool: def _getFocusLossCancellableSpeechCommand( obj, - reason: controlTypes.OutputReason + reason: controlTypes.OutputReason, ) -> Optional[_CancellableSpeechCommand]: if reason != controlTypes.OutputReason.FOCUS or not speech.manager._shouldCancelExpiredFocusEvents(): return None @@ -469,9 +471,11 @@ def shouldAcceptEvent(eventName, windowHandle=None): # We can't filter without a window handle. return True wClass = winUser.getClassName(windowHandle) - key = (eventName, - winUser.getWindowThreadProcessID(windowHandle)[0], - wClass) + key = ( + eventName, + winUser.getWindowThreadProcessID(windowHandle)[0], + wClass, + ) if key in _acceptEvents: return True if eventName == "valueChange" and config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"]: @@ -515,13 +519,17 @@ def shouldAcceptEvent(eventName, windowHandle=None): == winUser.getAncestor(fg, winUser.GA_ROOTOWNER) ): return True - if (winUser.isDescendantWindow(fg, windowHandle) - # #3899, #3905: Covers cases such as the Firefox Page Bookmarked window and OpenOffice/LibreOffice context menus. - or winUser.isDescendantWindow(fg, winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER))): + if ( + winUser.isDescendantWindow(fg, windowHandle) + # #3899, #3905: Covers cases such as the Firefox Page Bookmarked window and OpenOffice/LibreOffice context menus. + or winUser.isDescendantWindow(fg, winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER)) + ): # This is for the foreground application. return True - if (winUser.user32.GetWindowLongW(windowHandle, winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST - or winUser.user32.GetWindowLongW(winUser.getAncestor(windowHandle, winUser.GA_ROOT), winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST): + if ( + winUser.user32.GetWindowLongW(windowHandle, winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST + or winUser.user32.GetWindowLongW(winUser.getAncestor(windowHandle, winUser.GA_ROOT), winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST + ): # This window or its root is a topmost window. # This includes menus, combo box pop-ups and the task switching list. return True @@ -541,7 +549,7 @@ def shouldAcceptEvent(eventName, windowHandle=None): log.debugWarning("Could not create UIA element for root of Chromium document", exc_info=True) else: condition = UIAHandler.handler.clientObject.CreatePropertyCondition( - UIAHandler.UIA_NativeWindowHandlePropertyId, gi.hwndFocus + UIAHandler.UIA_NativeWindowHandlePropertyId, gi.hwndFocus, ) try: walker = UIAHandler.handler.clientObject.CreateTreeWalker(condition) diff --git a/source/extensionPoints/__init__.py b/source/extensionPoints/__init__.py index 3b249241891..eabb20fc60c 100644 --- a/source/extensionPoints/__init__.py +++ b/source/extensionPoints/__init__.py @@ -75,7 +75,7 @@ def notifyOnce(self, **kwargs): class Filter( HandlerRegistrar[Union[Callable[..., FilterValueT], Callable[[FilterValueT], FilterValueT]]], - Generic[FilterValueT] + Generic[FilterValueT], ): """Allows interested parties to register to modify a specific kind of data. For example, this might be used to allow modification of spoken messages before they are passed to the synthesizer. diff --git a/source/extensionPoints/util.py b/source/extensionPoints/util.py index c062db99d6a..556d156a85d 100644 --- a/source/extensionPoints/util.py +++ b/source/extensionPoints/util.py @@ -47,7 +47,7 @@ class BoundMethodWeakref(Generic[HandlerT]): def __init__( self, target: HandlerT, - onDelete: Optional[Callable[[BoundMethodWeakref], None]] = None + onDelete: Optional[Callable[[BoundMethodWeakref], None]] = None, ): if onDelete: def onRefDelete(weak): @@ -102,7 +102,7 @@ def __init__(self): #: and the values are weak references. self._handlers = OrderedDict[ HandlerKeyT, - Union[BoundMethodWeakref[HandlerT], AnnotatableWeakref[HandlerT]] + Union[BoundMethodWeakref[HandlerT], AnnotatableWeakref[HandlerT]], ]() def register(self, handler: HandlerT): diff --git a/source/fileUtils.py b/source/fileUtils.py index 8ed45d6a8ef..660b8e2148a 100644 --- a/source/fileUtils.py +++ b/source/fileUtils.py @@ -87,18 +87,21 @@ def getFileVersionInfo(name, *attributes): r = ctypes.c_uint() l = ctypes.c_uint() # noqa: E741 # Look for codepages - ctypes.windll.version.VerQueryValueW(res, u'\\VarFileInfo\\Translation', - ctypes.byref(r), ctypes.byref(l)) + ctypes.windll.version.VerQueryValueW( + res, u'\\VarFileInfo\\Translation', + ctypes.byref(r), ctypes.byref(l), + ) if not l.value: raise RuntimeError("No codepage") # Take the first codepage (what else ?) codepage = array.array('H', ctypes.string_at(r.value, 4)) codepage = "%04x%04x" % tuple(codepage) for attr in attributes: - if not ctypes.windll.version.VerQueryValueW(res, - u'\\StringFileInfo\\%s\\%s' % (codepage, attr), - ctypes.byref(r), ctypes.byref(l) - ): + if not ctypes.windll.version.VerQueryValueW( + res, + u'\\StringFileInfo\\%s\\%s' % (codepage, attr), + ctypes.byref(r), ctypes.byref(l), + ): log.warning("Invalid or unavailable version info attribute for %r: %s" % (name, attr)) fileVersionInfo[attr] = None else: diff --git a/source/fonts/__init__.py b/source/fonts/__init__.py index 34339989801..e53246529d3 100644 --- a/source/fonts/__init__.py +++ b/source/fonts/__init__.py @@ -53,7 +53,7 @@ def _addFontResource(fontPath: str) -> int: # The system will take care of unloading the font when the process ends. FR_PRIVATE, # Reserved. Must be zero. - 0 + 0, ) return res diff --git a/source/garbageHandler.py b/source/garbageHandler.py index a9dcc51b4ec..776e31b5999 100644 --- a/source/garbageHandler.py +++ b/source/garbageHandler.py @@ -69,7 +69,7 @@ def notifyObjectDeletion(obj): if _reportCountDuringCollection == 1: log.debugWarning( "Garbage collector has found one or more unreachable objects. See further warnings for specific objects.", - stack_info=True + stack_info=True, ) log.debugWarning(f"Deleting unreachable object {obj}") diff --git a/source/globalCommands.py b/source/globalCommands.py index eb88ec83a79..5ddfa125b01 100755 --- a/source/globalCommands.py +++ b/source/globalCommands.py @@ -130,10 +130,10 @@ class GlobalCommands(ScriptableObject): @script( description=_( # Translators: Describes the Cycle audio ducking mode command. - "Cycles through audio ducking modes which determine when NVDA lowers the volume of other sounds" + "Cycles through audio ducking modes which determine when NVDA lowers the volume of other sounds", ), category=SCRCAT_AUDIO, - gesture="kb:NVDA+shift+d" + gesture="kb:NVDA+shift+d", ) def script_cycleAudioDuckingMode(self,gesture): if not audioDucking.isAudioDuckingSupported(): @@ -153,7 +153,7 @@ def script_cycleAudioDuckingMode(self,gesture): # Translators: Input help mode message for toggle input help command. "Turns input help on or off. " "When on, any input such as pressing a key on the keyboard " - "will tell you what script is associated with that input, if any." + "will tell you what script is associated with that input, if any.", ), category=SCRCAT_INPUT, gesture="kb:NVDA+1", @@ -172,7 +172,7 @@ def script_toggleInputHelp(self,gesture): # Translators: Input help mode message for toggle sleep mode command. description=_("Toggles sleep mode on and off for the active application."), gestures=("kb(desktop):NVDA+shift+s", "kb(laptop):NVDA+shift+z"), - allowInSleepMode=True + allowInSleepMode=True, ) def script_toggleCurrentAppSleepMode(self,gesture): curFocus=api.getFocusObject() @@ -193,7 +193,7 @@ def script_toggleCurrentAppSleepMode(self,gesture): # Translators: Input help mode message for report current line command. "Reports the current line under the application cursor. " "Pressing this key twice will spell the current line. " - "Pressing three times will spell the line using character descriptions." + "Pressing three times will spell the line using character descriptions.", ), category=SCRCAT_SYSTEMCARET, gestures=("kb(desktop):NVDA+upArrow", "kb(laptop):NVDA+l"), @@ -219,7 +219,7 @@ def script_reportCurrentLine(self,gesture): # Translators: Input help mode message for left mouse click command. description=_("Clicks the left mouse button once at the current mouse position"), category=SCRCAT_MOUSE, - gestures=("kb:numpadDivide", "kb(laptop):NVDA+[") + gestures=("kb:numpadDivide", "kb(laptop):NVDA+["), ) def script_leftMouseClick(self,gesture): # Translators: Reported when left mouse button is clicked. @@ -231,7 +231,7 @@ def script_leftMouseClick(self,gesture): # Translators: Input help mode message for right mouse click command. description=_("Clicks the right mouse button once at the current mouse position"), category=SCRCAT_MOUSE, - gestures=("kb:numpadMultiply", "kb(laptop):NVDA+]") + gestures=("kb:numpadMultiply", "kb(laptop):NVDA+]"), ) def script_rightMouseClick(self,gesture): # Translators: Reported when right mouse button is clicked. @@ -243,7 +243,7 @@ def script_rightMouseClick(self,gesture): # Translators: Input help mode message for left mouse lock/unlock toggle command. description=_("Locks or unlocks the left mouse button"), category=SCRCAT_MOUSE, - gestures=("kb:shift+numpadDivide", "kb(laptop):NVDA+control+[") + gestures=("kb:shift+numpadDivide", "kb(laptop):NVDA+control+["), ) def script_toggleLeftMouseButton(self,gesture): if mouseHandler.isLeftMouseButtonLocked(): @@ -255,7 +255,7 @@ def script_toggleLeftMouseButton(self,gesture): # Translators: Input help mode message for right mouse lock/unlock command. description=_("Locks or unlocks the right mouse button"), category=SCRCAT_MOUSE, - gestures=("kb:shift+numpadMultiply", "kb(laptop):NVDA+control+]") + gestures=("kb:shift+numpadMultiply", "kb(laptop):NVDA+control+]"), ) def script_toggleRightMouseButton(self,gesture): if mouseHandler.isRightMouseButtonLocked(): @@ -266,9 +266,9 @@ def script_toggleRightMouseButton(self,gesture): @script( description=_( # Translators: Input help mode message for scroll up at the mouse position command. - "Scroll up at the mouse position" + "Scroll up at the mouse position", ), - category=SCRCAT_MOUSE + category=SCRCAT_MOUSE, ) def script_mouseScrollUp(self, gesture: "inputCore.InputGesture") -> None: mouseHandler.scrollMouseWheel(winUser.WHEEL_DELTA, isVertical=True) @@ -276,9 +276,9 @@ def script_mouseScrollUp(self, gesture: "inputCore.InputGesture") -> None: @script( description=_( # Translators: Input help mode message for scroll down at the mouse position command. - "Scroll down at the mouse position" + "Scroll down at the mouse position", ), - category=SCRCAT_MOUSE + category=SCRCAT_MOUSE, ) def script_mouseScrollDown(self, gesture: "inputCore.InputGesture") -> None: mouseHandler.scrollMouseWheel(-winUser.WHEEL_DELTA, isVertical=True) @@ -286,9 +286,9 @@ def script_mouseScrollDown(self, gesture: "inputCore.InputGesture") -> None: @script( description=_( # Translators: Input help mode message for scroll left at the mouse position command. - "Scroll left at the mouse position" + "Scroll left at the mouse position", ), - category=SCRCAT_MOUSE + category=SCRCAT_MOUSE, ) def script_mouseScrollLeft(self, gesture: "inputCore.InputGesture") -> None: mouseHandler.scrollMouseWheel(-winUser.WHEEL_DELTA, isVertical=False) @@ -296,9 +296,9 @@ def script_mouseScrollLeft(self, gesture: "inputCore.InputGesture") -> None: @script( description=_( # Translators: Input help mode message for scroll right at the mouse position command. - "Scroll right at the mouse position" + "Scroll right at the mouse position", ), - category=SCRCAT_MOUSE + category=SCRCAT_MOUSE, ) def script_mouseScrollRight(self, gesture: "inputCore.InputGesture") -> None: mouseHandler.scrollMouseWheel(winUser.WHEEL_DELTA, isVertical=False) @@ -309,7 +309,7 @@ def script_mouseScrollRight(self, gesture: "inputCore.InputGesture") -> None: "Announces the current selection in edit controls and documents. " "Pressing twice spells this information. " "Pressing three times spells it using character descriptions. " - "Pressing four times shows it in a browsable message. " + "Pressing four times shows it in a browsable message. ", ), category=SCRCAT_SYSTEMCARET, gestures=("kb(desktop):NVDA+shift+upArrow", "kb(laptop):NVDA+shift+s"), @@ -365,7 +365,7 @@ def script_dateTime(self,gesture): @script( # Translators: Input help mode message for set the first value in the synth ring setting. description=_("Set the first value of the current setting in the synth settings ring"), - category=SCRCAT_SPEECH + category=SCRCAT_SPEECH, ) def script_firstValueSynthRing(self, gesture: inputCore.InputGesture): settingName = globalVars.settingsRing.currentSettingName @@ -378,7 +378,7 @@ def script_firstValueSynthRing(self, gesture: inputCore.InputGesture): @script( # Translators: Input help mode message for set the last value in the synth ring settings. description=_("Set the last value of the current setting in the synth settings ring"), - category=SCRCAT_SPEECH + category=SCRCAT_SPEECH, ) def script_lastValueSynthRing(self, gesture: inputCore.InputGesture): settingName = globalVars.settingsRing.currentSettingName @@ -392,7 +392,7 @@ def script_lastValueSynthRing(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for increase synth setting value command. description=_("Increases the currently active setting in the synth settings ring"), category=SCRCAT_SPEECH, - gestures=("kb(desktop):NVDA+control+upArrow", "kb(laptop):NVDA+shift+control+upArrow") + gestures=("kb(desktop):NVDA+control+upArrow", "kb(laptop):NVDA+shift+control+upArrow"), ) def script_increaseSynthSetting(self,gesture): settingName=globalVars.settingsRing.currentSettingName @@ -406,7 +406,7 @@ def script_increaseSynthSetting(self,gesture): # Translators: Input help mode message for increasing synth setting value command in larger steps. description=_("Increases the currently active setting in the synth settings ring in a larger step"), category=SCRCAT_SPEECH, - gestures=("kb(desktop):NVDA+control+pageUp", "kb(laptop):NVDA+shift+control+pageUp") + gestures=("kb(desktop):NVDA+control+pageUp", "kb(laptop):NVDA+shift+control+pageUp"), ) def script_increaseLargeSynthSetting(self, gesture: inputCore.InputGesture): settingName = globalVars.settingsRing.currentSettingName @@ -420,7 +420,7 @@ def script_increaseLargeSynthSetting(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for decrease synth setting value command. description=_("Decreases the currently active setting in the synth settings ring"), category=SCRCAT_SPEECH, - gestures=("kb(desktop):NVDA+control+downArrow", "kb(laptop):NVDA+control+shift+downArrow") + gestures=("kb(desktop):NVDA+control+downArrow", "kb(laptop):NVDA+control+shift+downArrow"), ) def script_decreaseSynthSetting(self,gesture): settingName=globalVars.settingsRing.currentSettingName @@ -434,7 +434,7 @@ def script_decreaseSynthSetting(self,gesture): # Translators: Input help mode message for decreasing synth setting value command in larger steps. description=_("Decreases the currently active setting in the synth settings ring in a larger step"), category=SCRCAT_SPEECH, - gestures=("kb(desktop):NVDA+control+pageDown", "kb(laptop):NVDA+control+shift+pageDown") + gestures=("kb(desktop):NVDA+control+pageDown", "kb(laptop):NVDA+control+shift+pageDown"), ) def script_decreaseLargeSynthSetting(self, gesture: inputCore.InputGesture): settingName = globalVars.settingsRing.currentSettingName @@ -448,7 +448,7 @@ def script_decreaseLargeSynthSetting(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for next synth setting command. description=_("Moves to the next available setting in the synth settings ring"), category=SCRCAT_SPEECH, - gestures=("kb(desktop):NVDA+control+rightArrow", "kb(laptop):NVDA+shift+control+rightArrow") + gestures=("kb(desktop):NVDA+control+rightArrow", "kb(laptop):NVDA+shift+control+rightArrow"), ) def script_nextSynthSetting(self,gesture): nextSettingName=globalVars.settingsRing.next() @@ -462,7 +462,7 @@ def script_nextSynthSetting(self,gesture): # Translators: Input help mode message for previous synth setting command. description=_("Moves to the previous available setting in the synth settings ring"), category=SCRCAT_SPEECH, - gestures=("kb(desktop):NVDA+control+leftArrow", "kb(laptop):NVDA+shift+control+leftArrow") + gestures=("kb(desktop):NVDA+control+leftArrow", "kb(laptop):NVDA+shift+control+leftArrow"), ) def script_previousSynthSetting(self,gesture): previousSettingName=globalVars.settingsRing.previous() @@ -476,7 +476,7 @@ def script_previousSynthSetting(self,gesture): # Translators: Input help mode message for toggle speaked typed characters command. description=_("Toggles on and off the speaking of typed characters"), category=SCRCAT_SPEECH, - gesture="kb:NVDA+2" + gesture="kb:NVDA+2", ) def script_toggleSpeakTypedCharacters(self,gesture): if config.conf["keyboard"]["speakTypedCharacters"]: @@ -493,7 +493,7 @@ def script_toggleSpeakTypedCharacters(self,gesture): # Translators: Input help mode message for toggle speak typed words command. description=_("Toggles on and off the speaking of typed words"), category=SCRCAT_SPEECH, - gesture="kb:NVDA+3" + gesture="kb:NVDA+3", ) def script_toggleSpeakTypedWords(self,gesture): if config.conf["keyboard"]["speakTypedWords"]: @@ -510,7 +510,7 @@ def script_toggleSpeakTypedWords(self,gesture): # Translators: Input help mode message for toggle speak command keys command. description=_("Toggles on and off the speaking of typed keys, that are not specifically characters"), category=SCRCAT_SPEECH, - gesture="kb:NVDA+4" + gesture="kb:NVDA+4", ) def script_toggleSpeakCommandKeys(self,gesture): if config.conf["keyboard"]["speakCommandKeys"]: @@ -526,7 +526,7 @@ def script_toggleSpeakCommandKeys(self,gesture): @script( # Translators: Input help mode message for toggle report font name command. description=_("Toggles on and off the reporting of font changes"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportFontName(self,gesture): if config.conf["documentFormatting"]["reportFontName"]: @@ -542,7 +542,7 @@ def script_toggleReportFontName(self,gesture): @script( # Translators: Input help mode message for toggle report font size command. description=_("Toggles on and off the reporting of font size changes"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportFontSize(self,gesture): if config.conf["documentFormatting"]["reportFontSize"]: @@ -558,7 +558,7 @@ def script_toggleReportFontSize(self,gesture): @script( # Translators: Input help mode message for toggle report font attributes command. description=_("Toggles on and off the reporting of font attributes"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportFontAttributes(self,gesture): if config.conf["documentFormatting"]["reportFontAttributes"]: @@ -574,7 +574,7 @@ def script_toggleReportFontAttributes(self,gesture): @script( # Translators: Input help mode message for toggle superscripts and subscripts command. description=_("Toggles on and off the reporting of superscripts and subscripts"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportSuperscriptsAndSubscripts(self, gesture): shouldReport: bool = not config.conf["documentFormatting"]["reportSuperscriptsAndSubscripts"] @@ -592,7 +592,7 @@ def script_toggleReportSuperscriptsAndSubscripts(self, gesture): @script( # Translators: Input help mode message for toggle report revisions command. description=_("Toggles on and off the reporting of revisions"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportRevisions(self,gesture): if config.conf["documentFormatting"]["reportRevisions"]: @@ -608,7 +608,7 @@ def script_toggleReportRevisions(self,gesture): @script( # Translators: Input help mode message for toggle report emphasis command. description=_("Toggles on and off the reporting of emphasis"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportEmphasis(self,gesture): if config.conf["documentFormatting"]["reportEmphasis"]: @@ -624,7 +624,7 @@ def script_toggleReportEmphasis(self,gesture): @script( # Translators: Input help mode message for toggle report marked (highlighted) content command. description=_("Toggles on and off the reporting of highlighted text"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportHighlightedText(self, gesture): shouldReport: bool = not config.conf["documentFormatting"]["reportHighlight"] @@ -640,7 +640,7 @@ def script_toggleReportHighlightedText(self, gesture): @script( # Translators: Input help mode message for toggle report colors command. description=_("Toggles on and off the reporting of colors"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportColor(self,gesture): if config.conf["documentFormatting"]["reportColor"]: @@ -656,7 +656,7 @@ def script_toggleReportColor(self,gesture): @script( # Translators: Input help mode message for toggle report alignment command. description=_("Toggles on and off the reporting of text alignment"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportAlignment(self,gesture): if config.conf["documentFormatting"]["reportAlignment"]: @@ -672,7 +672,7 @@ def script_toggleReportAlignment(self,gesture): @script( # Translators: Input help mode message for toggle report style command. description=_("Toggles on and off the reporting of style changes"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportStyle(self,gesture): if config.conf["documentFormatting"]["reportStyle"]: @@ -688,7 +688,7 @@ def script_toggleReportStyle(self,gesture): @script( # Translators: Input help mode message for toggle report spelling errors command. description=_("Toggles on and off the reporting of spelling errors"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportSpellingErrors(self,gesture): if config.conf["documentFormatting"]["reportSpellingErrors"]: @@ -704,7 +704,7 @@ def script_toggleReportSpellingErrors(self,gesture): @script( # Translators: Input help mode message for toggle report pages command. description=_("Toggles on and off the reporting of pages"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportPage(self,gesture): if config.conf["documentFormatting"]["reportPage"]: @@ -720,7 +720,7 @@ def script_toggleReportPage(self,gesture): @script( # Translators: Input help mode message for toggle report line numbers command. description=_("Toggles on and off the reporting of line numbers"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportLineNumber(self,gesture): if config.conf["documentFormatting"]["reportLineNumber"]: @@ -736,7 +736,7 @@ def script_toggleReportLineNumber(self,gesture): @script( # Translators: Input help mode message for toggle report line indentation command. description=_("Cycles through line indentation settings"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportLineIndentation(self, gesture: inputCore.InputGesture): ReportLineIndentation = config.configFlags.ReportLineIndentation @@ -750,7 +750,7 @@ def script_toggleReportLineIndentation(self, gesture: inputCore.InputGesture): @script( # Translators: Input help mode message for toggle ignore blank lines for line indentation reporting command. description=_("Toggles on and off the ignoring of blank lines for line indentation reporting"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleignoreBlankLinesForReportLineIndentation(self, gesture: inputCore.InputGesture) -> None: ignore = config.conf['documentFormatting']['ignoreBlankLinesForRLI'] @@ -767,7 +767,7 @@ def script_toggleignoreBlankLinesForReportLineIndentation(self, gesture: inputCo @script( # Translators: Input help mode message for toggle report paragraph indentation command. description=_("Toggles on and off the reporting of paragraph indentation"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportParagraphIndentation(self,gesture): if config.conf["documentFormatting"]["reportParagraphIndentation"]: @@ -783,7 +783,7 @@ def script_toggleReportParagraphIndentation(self,gesture): @script( # Translators: Input help mode message for toggle report line spacing command. description=_("Toggles on and off the reporting of line spacing"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportLineSpacing(self,gesture): if config.conf["documentFormatting"]["reportLineSpacing"]: @@ -799,7 +799,7 @@ def script_toggleReportLineSpacing(self,gesture): @script( # Translators: Input help mode message for toggle report tables command. description=_("Toggles on and off the reporting of tables"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportTables(self,gesture): if config.conf["documentFormatting"]["reportTables"]: @@ -815,7 +815,7 @@ def script_toggleReportTables(self,gesture): @script( # Translators: Input help mode message for toggle report table row/column headers command. description=_("Cycle through the possible modes to report table row and column headers"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportTableHeaders(self,gesture): ReportTableHeaders = config.configFlags.ReportTableHeaders @@ -829,7 +829,7 @@ def script_toggleReportTableHeaders(self,gesture): @script( # Translators: Input help mode message for toggle report table cell coordinates command. description=_("Toggles on and off the reporting of table cell coordinates"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportTableCellCoords(self,gesture): if config.conf["documentFormatting"]["reportTableCellCoords"]: @@ -859,7 +859,7 @@ def script_toggleReportCellBorders(self, gesture: inputCore.InputGesture): @script( # Translators: Input help mode message for toggle report links command. description=_("Toggles on and off the reporting of links"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportLinks(self,gesture): if config.conf["documentFormatting"]["reportLinks"]: @@ -875,7 +875,7 @@ def script_toggleReportLinks(self,gesture): @script( # Translators: Input help mode message for toggle report graphics command. description=_("Toggles on and off the reporting of graphics"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportGraphics(self, gesture): if config.conf["documentFormatting"]["reportGraphics"]: @@ -891,7 +891,7 @@ def script_toggleReportGraphics(self, gesture): @script( # Translators: Input help mode message for toggle report comments command. description=_("Toggles on and off the reporting of comments"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportComments(self,gesture): if config.conf["documentFormatting"]["reportComments"]: @@ -907,7 +907,7 @@ def script_toggleReportComments(self,gesture): @script( # Translators: Input help mode message for toggle report lists command. description=_("Toggles on and off the reporting of lists"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportLists(self,gesture): if config.conf["documentFormatting"]["reportLists"]: @@ -923,7 +923,7 @@ def script_toggleReportLists(self,gesture): @script( # Translators: Input help mode message for toggle report headings command. description=_("Toggles on and off the reporting of headings"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportHeadings(self,gesture): if config.conf["documentFormatting"]["reportHeadings"]: @@ -939,7 +939,7 @@ def script_toggleReportHeadings(self,gesture): @script( # Translators: Input help mode message for toggle report groupings command. description=_("Toggles on and off the reporting of groupings"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportGroupings(self, gesture): if config.conf["documentFormatting"]["reportGroupings"]: @@ -955,7 +955,7 @@ def script_toggleReportGroupings(self, gesture): @script( # Translators: Input help mode message for toggle report block quotes command. description=_("Toggles on and off the reporting of block quotes"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportBlockQuotes(self,gesture): if config.conf["documentFormatting"]["reportBlockQuotes"]: @@ -971,7 +971,7 @@ def script_toggleReportBlockQuotes(self,gesture): @script( # Translators: Input help mode message for toggle report landmarks command. description=_("Toggles on and off the reporting of landmarks"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportLandmarks(self,gesture): if config.conf["documentFormatting"]["reportLandmarks"]: @@ -987,7 +987,7 @@ def script_toggleReportLandmarks(self,gesture): @script( # Translators: Input help mode message for toggle report articles command. description=_("Toggles on and off the reporting of articles"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportArticles(self, gesture): if config.conf["documentFormatting"]["reportArticles"]: @@ -1003,7 +1003,7 @@ def script_toggleReportArticles(self, gesture): @script( # Translators: Input help mode message for toggle report frames command. description=_("Toggles on and off the reporting of frames"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportFrames(self,gesture): if config.conf["documentFormatting"]["reportFrames"]: @@ -1019,7 +1019,7 @@ def script_toggleReportFrames(self,gesture): @script( # Translators: Input help mode message for toggle report if clickable command. description=_("Toggles on and off reporting if clickable"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportClickable(self,gesture): if config.conf["documentFormatting"]["reportClickable"]: @@ -1035,7 +1035,7 @@ def script_toggleReportClickable(self,gesture): @script( # Translators: Input help mode message for toggle report figures and captions command. description=_("Toggles on and off the reporting of figures and captions"), - category=SCRCAT_DOCUMENTFORMATTING + category=SCRCAT_DOCUMENTFORMATTING, ) def script_toggleReportFigures(self, gesture: inputCore.InputGesture): if config.conf["documentFormatting"]["reportFigures"]: @@ -1054,7 +1054,7 @@ def script_toggleReportFigures(self, gesture: inputCore.InputGesture): description=_( # Translators: Input help mode message for cycle through automatic language switching mode command. "Cycles through the possible choices for automatic language switching: " - "off, language only and language and dialect." + "off, language only and language and dialect.", ), category=SCRCAT_SPEECH, ) @@ -1080,7 +1080,7 @@ def script_cycleSpeechAutomaticLanguageSwitching(self, gesture): # Translators: Input help mode message for cycle speech symbol level command. description=_("Cycles through speech symbol levels which determine what symbols are spoken"), category=SCRCAT_SPEECH, - gesture="kb:NVDA+p" + gesture="kb:NVDA+p", ) def script_cycleSpeechSymbolLevel(self,gesture): curLevel = config.conf["speech"]["symbolLevel"] @@ -1116,7 +1116,7 @@ def script_toggleDelayedCharacterDescriptions(self, gesture: inputCore.InputGest # Translators: Input help mode message for move mouse to navigator object command. description=_("Moves the mouse pointer to the current navigator object"), category=SCRCAT_MOUSE, - gestures=("kb:NVDA+numpadDivide", "kb(laptop):NVDA+shift+m") + gestures=("kb:NVDA+numpadDivide", "kb(laptop):NVDA+shift+m"), ) def script_moveMouseToNavigatorObject(self, gesture: inputCore.InputGesture): reviewPosition = api.getReviewPosition() @@ -1162,7 +1162,7 @@ def script_moveMouseToNavigatorObject(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for move navigator object to mouse command. description=_("Sets the navigator object to the current object under the mouse pointer and speaks it"), category=SCRCAT_MOUSE, - gestures=("kb:NVDA+numpadMultiply", "kb(laptop):NVDA+shift+n") + gestures=("kb:NVDA+numpadMultiply", "kb(laptop):NVDA+shift+n"), ) def script_moveNavigatorObjectToMouse(self, gesture: inputCore.InputGesture): # Translators: Reported when attempting to move the navigator object to the object under mouse pointer. @@ -1182,10 +1182,10 @@ def script_moveNavigatorObjectToMouse(self, gesture: inputCore.InputGesture): description=_( # Translators: Script help message for next review mode command. "Switches to the next review mode (e.g. object, document or screen) " - "and positions the review position at the point of the navigator object" + "and positions the review position at the point of the navigator object", ), category=SCRCAT_TEXTREVIEW, - gestures=("kb:NVDA+numpad7", "kb(laptop):NVDA+pageUp", "ts(object):2finger_flickUp") + gestures=("kb:NVDA+numpad7", "kb(laptop):NVDA+pageUp", "ts(object):2finger_flickUp"), ) def script_reviewMode_next(self,gesture): label=review.nextMode() @@ -1203,10 +1203,10 @@ def script_reviewMode_next(self,gesture): description=_( # Translators: Script help message for previous review mode command. "Switches to the previous review mode (e.g. object, document or screen) " - "and positions the review position at the point of the navigator object" + "and positions the review position at the point of the navigator object", ), category=SCRCAT_TEXTREVIEW, - gestures=("kb:NVDA+numpad1", "kb(laptop):NVDA+pageDown", "ts(object):2finger_flickDown") + gestures=("kb:NVDA+numpad1", "kb(laptop):NVDA+pageDown", "ts(object):2finger_flickDown"), ) def script_reviewMode_previous(self,gesture): label=review.nextMode(prev=True) @@ -1223,7 +1223,7 @@ def script_reviewMode_previous(self,gesture): @script( # Translators: Input help mode message for toggle simple review mode command. description=_("Toggles simple review mode on and off"), - category=SCRCAT_OBJECTNAVIGATION + category=SCRCAT_OBJECTNAVIGATION, ) def script_toggleSimpleReviewMode(self,gesture): if config.conf["reviewCursor"]["simpleReviewMode"]: @@ -1241,7 +1241,7 @@ def script_toggleSimpleReviewMode(self,gesture): # Translators: Input help mode message for report current navigator object command. "Reports the current navigator object. " "Pressing twice spells this information, " - "and pressing three times Copies name and value of this object to the clipboard" + "and pressing three times Copies name and value of this object to the clipboard", ), category=SCRCAT_OBJECTNAVIGATION, gestures=("kb:NVDA+numpad5", "kb(laptop):NVDA+shift+o"), @@ -1312,7 +1312,7 @@ def _reportLocationText(objs: Tuple[Union[None, NVDAObject, textInfos.TextInfo], # Translators: Description for a keyboard command which reports location of the # review cursor, falling back to the location of navigator object if needed. "Reports information about the location of the text at the review cursor, " - "or location of the navigator object if there is no text under review cursor." + "or location of the navigator object if there is no text under review cursor.", ), category=SCRCAT_OBJECTNAVIGATION, speakOnDemand=True, @@ -1323,7 +1323,7 @@ def script_reportReviewCursorLocation(self, gesture): @script( description=_( # Translators: Description for a keyboard command which reports location of the navigator object. - "Reports information about the location of the current navigator object." + "Reports information about the location of the current navigator object.", ), category=SCRCAT_OBJECTNAVIGATION, speakOnDemand=True, @@ -1336,21 +1336,21 @@ def script_reportCurrentNavigatorObjectLocation(self, gesture): # Translators: Description for a keyboard command which reports location of the # current caret position falling back to the location of focused object if needed. "Reports information about the location of the text at the caret, " - "or location of the currently focused object if there is no caret." + "or location of the currently focused object if there is no caret.", ), category=SCRCAT_SYSTEMCARET, speakOnDemand=True, ) def script_reportCaretLocation(self, gesture): self._reportLocationText( - (self._getTIAtCaret(fallbackToPOSITION_FIRST=True, reportFailure=False), api.getFocusObject()) + (self._getTIAtCaret(fallbackToPOSITION_FIRST=True, reportFailure=False), api.getFocusObject()), ) @script( description=_( # Translators: Description for a keyboard command which reports location of the # currently focused object. - "Reports information about the location of the currently focused object." + "Reports information about the location of the currently focused object.", ), category=SCRCAT_FOCUS, speakOnDemand=True, @@ -1362,7 +1362,7 @@ def script_reportFocusObjectLocation(self, gesture): description=_( # Translators: Description for report review cursor location command. "Reports information about the location of the text or object at the review cursor. " - "Pressing twice may provide further detail." + "Pressing twice may provide further detail.", ), category=SCRCAT_OBJECTNAVIGATION, gestures=("kb:NVDA+shift+numpadDelete", "kb(laptop):NVDA+shift+delete"), @@ -1380,7 +1380,7 @@ def script_navigatorObject_currentDimensions(self, gesture): # which reports location of the text at the caret position # or object with focus if there is no caret. "Reports information about the location of the text or object at the position of system caret. " - "Pressing twice may provide further detail." + "Pressing twice may provide further detail.", ), category=SCRCAT_SYSTEMCARET, gestures=("kb:NVDA+numpadDelete", "kb(laptop):NVDA+delete"), @@ -1396,10 +1396,10 @@ def script_caretPos_currentDimensions(self, gesture): description=_( # Translators: Input help mode message for move navigator object to current focus command. "Sets the navigator object to the current focus, " - "and the review cursor to the position of the caret inside it, if possible." + "and the review cursor to the position of the caret inside it, if possible.", ), category=SCRCAT_OBJECTNAVIGATION, - gestures=("kb:NVDA+numpadMinus", "kb(laptop):NVDA+backspace") + gestures=("kb:NVDA+numpadMinus", "kb(laptop):NVDA+backspace"), ) def script_navigatorObject_toFocus(self, gesture: inputCore.InputGesture): tIAtCaret = self._getTIAtCaret(True) @@ -1423,10 +1423,10 @@ def script_navigatorObject_toFocus(self, gesture: inputCore.InputGesture): description=_( # Translators: Input help mode message for move focus to current navigator object command. "Pressed once sets the keyboard focus to the navigator object, " - "pressed twice sets the system caret to the position of the review cursor" + "pressed twice sets the system caret to the position of the review cursor", ), category=SCRCAT_OBJECTNAVIGATION, - gestures=("kb:NVDA+shift+numpadMinus", "kb(laptop):NVDA+shift+backspace") + gestures=("kb:NVDA+shift+numpadMinus", "kb(laptop):NVDA+shift+backspace"), ) def script_navigatorObject_moveFocus(self, gesture: inputCore.InputGesture): obj=api.getNavigatorObject() @@ -1470,7 +1470,7 @@ def script_navigatorObject_moveFocus(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for move to parent object command. description=_("Moves the navigator object to the object containing it"), category=SCRCAT_OBJECTNAVIGATION, - gestures=("kb:NVDA+numpad8", "kb(laptop):NVDA+shift+upArrow", "ts(object):flickup") + gestures=("kb:NVDA+numpad8", "kb(laptop):NVDA+shift+upArrow", "ts(object):flickup"), ) def script_navigatorObject_parent(self, gesture: inputCore.InputGesture): curObject=api.getNavigatorObject() @@ -1501,7 +1501,7 @@ def script_navigatorObject_parent(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for move to next object command. description=_("Moves the navigator object to the next object"), category=SCRCAT_OBJECTNAVIGATION, - gestures=("kb:NVDA+numpad6", "kb(laptop):NVDA+shift+rightArrow", "ts(object):2finger_flickright") + gestures=("kb:NVDA+numpad6", "kb(laptop):NVDA+shift+rightArrow", "ts(object):2finger_flickright"), ) def script_navigatorObject_next(self, gesture: inputCore.InputGesture): curObject=api.getNavigatorObject() @@ -1531,7 +1531,7 @@ def script_navigatorObject_next(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for move to previous object command. description=_("Moves the navigator object to the previous object"), category=SCRCAT_OBJECTNAVIGATION, - gestures=("kb:NVDA+numpad4", "kb(laptop):NVDA+shift+leftArrow", "ts(object):2finger_flickleft") + gestures=("kb:NVDA+numpad4", "kb(laptop):NVDA+shift+leftArrow", "ts(object):2finger_flickleft"), ) def script_navigatorObject_previous(self, gesture: inputCore.InputGesture): curObject=api.getNavigatorObject() @@ -1560,7 +1560,7 @@ def script_navigatorObject_previous(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for move to first child object command. description=_("Moves the navigator object to the first object inside it"), category=SCRCAT_OBJECTNAVIGATION, - gestures=("kb:NVDA+numpad2", "kb(laptop):NVDA+shift+downArrow", "ts(object):flickdown") + gestures=("kb:NVDA+numpad2", "kb(laptop):NVDA+shift+downArrow", "ts(object):flickdown"), ) def script_navigatorObject_firstChild(self, gesture: inputCore.InputGesture): curObject=api.getNavigatorObject() @@ -1591,10 +1591,10 @@ def script_navigatorObject_firstChild(self, gesture: inputCore.InputGesture): description=_( # Translators: Input help mode message for activate current object command. "Performs the default action on the current navigator object " - "(example: presses it if it is a button)." + "(example: presses it if it is a button).", ), category=SCRCAT_OBJECTNAVIGATION, - gestures=("kb:NVDA+numpadEnter", "kb(laptop):NVDA+enter", "ts:double_tap") + gestures=("kb:NVDA+numpadEnter", "kb(laptop):NVDA+enter", "ts:double_tap"), ) def script_review_activate(self, gesture: inputCore.InputGesture): # Translators: a message reported when the action at the position of the review cursor or navigator object is performed. @@ -1643,7 +1643,7 @@ def script_review_activate(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for move review cursor to top line command. description=_("Moves the review cursor to the top line of the current navigator object and speaks it"), category=SCRCAT_TEXTREVIEW, - gestures=("kb:shift+numpad7", "kb(laptop):NVDA+control+home") + gestures=("kb:shift+numpad7", "kb(laptop):NVDA+control+home"), ) def script_review_top(self, gesture: inputCore.InputGesture): info=api.getReviewPosition().obj.makeTextInfo(textInfos.POSITION_FIRST) @@ -1656,7 +1656,7 @@ def script_review_top(self, gesture: inputCore.InputGesture): speech.speakTextInfo( info, unit=textInfos.UNIT_LINE, - reason=controlTypes.OutputReason.CARET + reason=controlTypes.OutputReason.CARET, ) else: ui.reviewMessage(gui.blockAction.Context.WINDOWS_LOCKED.translatedMessage) @@ -1667,7 +1667,7 @@ def script_review_top(self, gesture: inputCore.InputGesture): description=_("Moves the review cursor to the previous line of the current navigator object and speaks it"), resumeSayAllMode=sayAll.CURSOR.REVIEW, category=SCRCAT_TEXTREVIEW, - gestures=("kb:numpad7", "kb(laptop):NVDA+upArrow", "ts(text):flickUp") + gestures=("kb:numpad7", "kb(laptop):NVDA+upArrow", "ts(text):flickUp"), ) def script_review_previousLine(self, gesture: inputCore.InputGesture): info=api.getReviewPosition().copy() @@ -1691,7 +1691,7 @@ def script_review_previousLine(self, gesture: inputCore.InputGesture): speech.speakTextInfo( info, unit=textInfos.UNIT_LINE, - reason=controlTypes.OutputReason.CARET + reason=controlTypes.OutputReason.CARET, ) @script( @@ -1699,7 +1699,7 @@ def script_review_previousLine(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for read current line under review cursor command. "Reports the line of the current navigator object where the review cursor is situated. " "If this key is pressed twice, the current line will be spelled. " - "Pressing three times will spell the line using character descriptions." + "Pressing three times will spell the line using character descriptions.", ), category=SCRCAT_TEXTREVIEW, gestures=("kb:numpad8", "kb(laptop):NVDA+shift+."), @@ -1727,7 +1727,7 @@ def script_review_currentLine(self, gesture: inputCore.InputGesture): description=_("Moves the review cursor to the next line of the current navigator object and speaks it"), resumeSayAllMode=sayAll.CURSOR.REVIEW, category=SCRCAT_TEXTREVIEW, - gestures=("kb:numpad9", "kb(laptop):NVDA+downArrow", "ts(text):flickDown") + gestures=("kb:numpad9", "kb(laptop):NVDA+downArrow", "ts(text):flickDown"), ) def script_review_nextLine(self, gesture: inputCore.InputGesture): origInfo = api.getReviewPosition().copy() @@ -1756,7 +1756,7 @@ def script_review_nextLine(self, gesture: inputCore.InputGesture): speech.speakTextInfo( newLine, unit=textInfos.UNIT_LINE, - reason=controlTypes.OutputReason.CARET + reason=controlTypes.OutputReason.CARET, ) @script( @@ -1764,7 +1764,7 @@ def script_review_nextLine(self, gesture: inputCore.InputGesture): description=_("Moves the review cursor to the previous page of the current navigator object and speaks it"), resumeSayAllMode=sayAll.CURSOR.REVIEW, category=SCRCAT_TEXTREVIEW, - gestures=("kb:NVDA+pageUp", "kb(laptop):NVDA+shift+pageUp") + gestures=("kb:NVDA+pageUp", "kb(laptop):NVDA+shift+pageUp"), ) def script_review_previousPage(self, gesture: inputCore.InputGesture) -> None: info = api.getReviewPosition().copy() @@ -1796,7 +1796,7 @@ def script_review_previousPage(self, gesture: inputCore.InputGesture) -> None: description=_("Moves the review cursor to the next page of the current navigator object and speaks it"), resumeSayAllMode=sayAll.CURSOR.REVIEW, category=SCRCAT_TEXTREVIEW, - gestures=("kb:NVDA+pageDown", "kb(laptop):NVDA+shift+pageDown") + gestures=("kb:NVDA+pageDown", "kb(laptop):NVDA+shift+pageDown"), ) def script_review_nextPage(self, gesture: inputCore.InputGesture) -> None: origInfo = api.getReviewPosition().copy() @@ -1832,7 +1832,7 @@ def script_review_nextPage(self, gesture: inputCore.InputGesture) -> None: # Translators: Input help mode message for move review cursor to bottom line command. description=_("Moves the review cursor to the bottom line of the current navigator object and speaks it"), category=SCRCAT_TEXTREVIEW, - gestures=("kb:shift+numpad9", "kb(laptop):NVDA+control+end") + gestures=("kb:shift+numpad9", "kb(laptop):NVDA+control+end"), ) def script_review_bottom(self, gesture: inputCore.InputGesture): info=api.getReviewPosition().obj.makeTextInfo(textInfos.POSITION_LAST) @@ -1845,7 +1845,7 @@ def script_review_bottom(self, gesture: inputCore.InputGesture): speech.speakTextInfo( info, unit=textInfos.UNIT_LINE, - reason=controlTypes.OutputReason.CARET + reason=controlTypes.OutputReason.CARET, ) else: ui.reviewMessage(gui.blockAction.Context.WINDOWS_LOCKED.translatedMessage) @@ -1855,7 +1855,7 @@ def script_review_bottom(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for move review cursor to previous word command. description=_("Moves the review cursor to the previous word of the current navigator object and speaks it"), category=SCRCAT_TEXTREVIEW, - gestures=("kb:numpad4", "kb(laptop):NVDA+control+leftArrow", "ts(text):2finger_flickLeft") + gestures=("kb:numpad4", "kb(laptop):NVDA+control+leftArrow", "ts(text):2finger_flickLeft"), ) def script_review_previousWord(self, gesture: inputCore.InputGesture): info=api.getReviewPosition().copy() @@ -1879,7 +1879,7 @@ def script_review_previousWord(self, gesture: inputCore.InputGesture): speech.speakTextInfo( info, reason=controlTypes.OutputReason.CARET, - unit=textInfos.UNIT_WORD + unit=textInfos.UNIT_WORD, ) @script( @@ -1887,7 +1887,7 @@ def script_review_previousWord(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for report current word under review cursor command. "Speaks the word of the current navigator object where the review cursor is situated. " "Pressing twice spells the word. " - "Pressing three times spells the word using character descriptions" + "Pressing three times spells the word using character descriptions", ), category=SCRCAT_TEXTREVIEW, gestures=("kb:numpad5", "kb(laptop):NVDA+control+.", "ts(text):hoverUp"), @@ -1915,7 +1915,7 @@ def script_review_currentWord(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for move review cursor to next word command. description=_("Moves the review cursor to the next word of the current navigator object and speaks it"), category=SCRCAT_TEXTREVIEW, - gestures=("kb:numpad6", "kb(laptop):NVDA+control+rightArrow", "ts(text):2finger_flickRight") + gestures=("kb:numpad6", "kb(laptop):NVDA+control+rightArrow", "ts(text):2finger_flickRight"), ) def script_review_nextWord(self, gesture: inputCore.InputGesture): origInfo = api.getReviewPosition().copy() @@ -1944,17 +1944,17 @@ def script_review_nextWord(self, gesture: inputCore.InputGesture): speech.speakTextInfo( newWord, unit=textInfos.UNIT_WORD, - reason=controlTypes.OutputReason.CARET + reason=controlTypes.OutputReason.CARET, ) @script( description=_( # Translators: Input help mode message for move review cursor to start of current line command. "Moves the review cursor to the first character of the line " - "where it is situated in the current navigator object and speaks it" + "where it is situated in the current navigator object and speaks it", ), category=SCRCAT_TEXTREVIEW, - gestures=("kb:shift+numpad1", "kb(laptop):NVDA+home") + gestures=("kb:shift+numpad1", "kb(laptop):NVDA+home"), ) def script_review_startOfLine(self, gesture: inputCore.InputGesture): info=api.getReviewPosition().copy() @@ -1970,7 +1970,7 @@ def script_review_startOfLine(self, gesture: inputCore.InputGesture): speech.speakTextInfo( info, unit=textInfos.UNIT_CHARACTER, - reason=controlTypes.OutputReason.CARET + reason=controlTypes.OutputReason.CARET, ) else: ui.reviewMessage(gui.blockAction.Context.WINDOWS_LOCKED.translatedMessage) @@ -1979,10 +1979,10 @@ def script_review_startOfLine(self, gesture: inputCore.InputGesture): @script( description=_( # Translators: Input help mode message for move review cursor to previous character command. - "Moves the review cursor to the previous character of the current navigator object and speaks it" + "Moves the review cursor to the previous character of the current navigator object and speaks it", ), category=SCRCAT_TEXTREVIEW, - gestures=("kb:numpad1", "kb(laptop):NVDA+leftArrow", "ts(text):flickLeft") + gestures=("kb:numpad1", "kb(laptop):NVDA+leftArrow", "ts(text):flickLeft"), ) def script_review_previousCharacter(self, gesture: inputCore.InputGesture): lineInfo=api.getReviewPosition().copy() @@ -2010,7 +2010,7 @@ def script_review_previousCharacter(self, gesture: inputCore.InputGesture): speech.speakTextInfo( reviewInfo, unit=textInfos.UNIT_CHARACTER, - reason=controlTypes.OutputReason.CARET + reason=controlTypes.OutputReason.CARET, ) @script( @@ -2018,7 +2018,7 @@ def script_review_previousCharacter(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for report current character under review cursor command. "Reports the character of the current navigator object where the review cursor is situated. " "Pressing twice reports a description or example of that character. " - "Pressing three times reports the numeric value of the character in decimal and hexadecimal" + "Pressing three times reports the numeric value of the character in decimal and hexadecimal", ), category=SCRCAT_TEXTREVIEW, gestures=("kb:numpad2", "kb(laptop):NVDA+."), @@ -2061,10 +2061,10 @@ def script_review_currentCharacter(self, gesture: inputCore.InputGesture): @script( description=_( # Translators: Input help mode message for move review cursor to next character command. - "Moves the review cursor to the next character of the current navigator object and speaks it" + "Moves the review cursor to the next character of the current navigator object and speaks it", ), category=SCRCAT_TEXTREVIEW, - gestures=("kb:numpad3", "kb(laptop):NVDA+rightArrow", "ts(text):flickRight") + gestures=("kb:numpad3", "kb(laptop):NVDA+rightArrow", "ts(text):flickRight"), ) def script_review_nextCharacter(self, gesture: inputCore.InputGesture): lineInfo=api.getReviewPosition().copy() @@ -2092,17 +2092,17 @@ def script_review_nextCharacter(self, gesture: inputCore.InputGesture): speech.speakTextInfo( reviewInfo, unit=textInfos.UNIT_CHARACTER, - reason=controlTypes.OutputReason.CARET + reason=controlTypes.OutputReason.CARET, ) @script( description=_( # Translators: Input help mode message for move review cursor to end of current line command. "Moves the review cursor to the last character of the line " - "where it is situated in the current navigator object and speaks it" + "where it is situated in the current navigator object and speaks it", ), category=SCRCAT_TEXTREVIEW, - gestures=("kb:shift+numpad3", "kb(laptop):NVDA+end") + gestures=("kb:shift+numpad3", "kb(laptop):NVDA+end"), ) def script_review_endOfLine(self, gesture: inputCore.InputGesture): info=api.getReviewPosition().copy() @@ -2164,10 +2164,10 @@ def script_review_currentSymbol(self,gesture): @script( description=_( # Translators: Input help mode message for cycle speech mode command. - "Cycles between speech modes." + "Cycles between speech modes.", ), category=SCRCAT_SPEECH, - gesture="kb:NVDA+s" + gesture="kb:NVDA+s", ) def script_speechMode(self, gesture: inputCore.InputGesture) -> None: curMode = speech.getState().speechMode @@ -2194,10 +2194,10 @@ def script_speechMode(self, gesture: inputCore.InputGesture) -> None: description=_( # Translators: Input help mode message for move to next document with focus command, # mostly used in web browsing to move from embedded object to the webpage document. - "Moves the focus out of the current embedded object and into the document that contains it" + "Moves the focus out of the current embedded object and into the document that contains it", ), category=SCRCAT_FOCUS, - gesture="kb:NVDA+control+space" + gesture="kb:NVDA+control+space", ) def script_moveToParentTreeInterceptor(self,gesture): obj=api.getFocusObject() @@ -2222,10 +2222,10 @@ def script_moveToParentTreeInterceptor(self,gesture): "Toggles between browse mode and focus mode. " "When in focus mode, keys will pass straight through to the application, " "allowing you to interact directly with a control. " - "When in browse mode, you can navigate the document with the cursor, quick navigation keys, etc." + "When in browse mode, you can navigate the document with the cursor, quick navigation keys, etc.", ), category=inputCore.SCRCAT_BROWSEMODE, - gesture="kb:NVDA+space" + gesture="kb:NVDA+space", ) def script_toggleVirtualBufferPassThrough(self,gesture): focus = api.getFocusObject() @@ -2270,14 +2270,14 @@ def script_toggleVirtualBufferPassThrough(self,gesture): @script( # Translators: Input help mode message for quit NVDA command. description=_("Quits NVDA!"), - gesture="kb:NVDA+q" + gesture="kb:NVDA+q", ) def script_quit(self,gesture): wx.CallAfter(gui.mainFrame.onExitCommand, None) @script( # Translators: Input help mode message for restart NVDA command. - description=_("Restarts NVDA!") + description=_("Restarts NVDA!"), ) def script_restart(self,gesture): core.restart() @@ -2285,7 +2285,7 @@ def script_restart(self,gesture): @script( # Translators: Input help mode message for show NVDA menu command. description=_("Shows the NVDA menu"), - gestures=("kb:NVDA+n", "ts:2finger_double_tap") + gestures=("kb:NVDA+n", "ts:2finger_double_tap"), ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_showGui(self,gesture): @@ -2295,7 +2295,7 @@ def script_showGui(self,gesture): description=_( # Translators: Input help mode message for say all in review cursor command. "Reads from the review cursor up to the end of the current text," - " moving the review cursor as it goes" + " moving the review cursor as it goes", ), category=SCRCAT_TEXTREVIEW, gestures=("kb:numpadPlus", "kb(laptop):NVDA+shift+a", "ts(text):3finger_flickDown"), @@ -2390,13 +2390,13 @@ def _reportFormattingHelper(self, info, browseable=False): ui.browseableMessage( message, # Translators: title for formatting information dialog. - _("Formatting") + _("Formatting"), ) @staticmethod def _getTIAtCaret( fallbackToPOSITION_FIRST: bool = False, - reportFailure: bool = True + reportFailure: bool = True, ) -> Optional[textInfos.TextInfo]: # Returns text info at the caret position if there is a caret in the current control, None otherwise. # Note that if there is no caret this fact is announced in speech and braille @@ -2430,7 +2430,7 @@ def script_reportFormattingAtReview(self, gesture): @script( # Translators: Input help mode message for show formatting at review cursor command. description=_("Presents, in browse mode, formatting info for the current review cursor position."), - category=SCRCAT_TEXTREVIEW + category=SCRCAT_TEXTREVIEW, ) def script_showFormattingAtReview(self, gesture): self._reportFormattingHelper(api.getReviewPosition(), True) @@ -2439,7 +2439,7 @@ def script_showFormattingAtReview(self, gesture): description=_( # Translators: Input help mode message for report formatting command. "Reports formatting info for the current review cursor position." - " If pressed twice, presents the information in browse mode" + " If pressed twice, presents the information in browse mode", ), category=SCRCAT_TEXTREVIEW, gesture="kb:NVDA+shift+f", @@ -2464,7 +2464,7 @@ def script_reportFormattingAtCaret(self, gesture): @script( # Translators: Input help mode message for show formatting at caret position command. description=_("Presents, in browse mode, formatting info for the text under the caret."), - category=SCRCAT_SYSTEMCARET + category=SCRCAT_SYSTEMCARET, ) def script_showFormattingAtCaret(self, gesture): self._reportFormattingHelper(self._getTIAtCaret(True), True) @@ -2473,7 +2473,7 @@ def script_showFormattingAtCaret(self, gesture): description=_( # Translators: Input help mode message for report formatting at caret command. "Reports formatting info for the text under the caret." - " If pressed twice, presents the information in browse mode" + " If pressed twice, presents the information in browse mode", ), category=SCRCAT_SYSTEMCARET, gesture="kb:NVDA+f", @@ -2538,7 +2538,7 @@ def _getNvdaObjWithAnnotationUnderCaret(self) -> Optional[NVDAObject]: gesture="kb:NVDA+d", description=_( # Translators: the description for the reportDetailsSummary script. - "Report summary of any annotation details at the system caret." + "Report summary of any annotation details at the system caret.", ), category=SCRCAT_SYSTEMCARET, speakOnDemand=True, @@ -2582,14 +2582,14 @@ def script_reportDetailsSummary(self, gesture: inputCore.InputGesture): if _isDebugLogCatEnabled: log.debug( "No prior target summary reported:" - f" lastReported: {self._annotationNav.lastReported}" + f" lastReported: {self._annotationNav.lastReported}", ) if self._annotationNav.lastReported and _isDebugLogCatEnabled: log.debug( f" objWithAnnotation == self._annotationNav.lastReported.origin: " f"{objWithAnnotation == self._annotationNav.lastReported.origin}" f" self._annotationNav.lastReported.indexOfLastReportedSummary: " - f"{self._annotationNav.lastReported.indexOfLastReportedSummary}" + f"{self._annotationNav.lastReported.indexOfLastReportedSummary}", ) indexOfNextTarget = 0 @@ -2597,7 +2597,7 @@ def script_reportDetailsSummary(self, gesture: inputCore.InputGesture): ui.message(targetToReport.summary) self._annotationNav.lastReported = _AnnotationNavigationNode( origin=objWithAnnotation, - indexOfLastReportedSummary=indexOfNextTarget + indexOfLastReportedSummary=indexOfNextTarget, ) return @@ -2606,7 +2606,7 @@ def script_reportDetailsSummary(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for report current focus command. "Reports the object with focus. " "If pressed twice, spells the information. " - "Pressing three times spells it using character descriptions." + "Pressing three times spells it using character descriptions.", ), category=SCRCAT_FOCUS, gesture="kb:NVDA+tab", @@ -2689,7 +2689,7 @@ def _getStatusBarText(setReviewCursor: bool = False) -> Optional[str]: @script( description=_( # Translators: Input help mode message for command which reads content of the status bar. - "Reads the current application status bar." + "Reads the current application status bar.", ), category=SCRCAT_FOCUS, speakOnDemand=True, @@ -2707,7 +2707,7 @@ def script_readStatusLine(self, gesture): @script( description=_( # Translators: Input help mode message for command which spells content of the status bar. - "Spells the current application status bar." + "Spells the current application status bar.", ), category=SCRCAT_FOCUS, speakOnDemand=True, @@ -2725,7 +2725,7 @@ def script_spellStatusLine(self, gesture): @script( description=_( # Translators: Input help mode message for command which copies status bar content to the clipboard. - "Copies content of the status bar of current application to the clipboard." + "Copies content of the status bar of current application to the clipboard.", ), category=SCRCAT_FOCUS, ) @@ -2742,7 +2742,7 @@ def script_copyStatusLine(self, gesture): @script( description=_( # Translators: Input help mode message for Command which moves review cursor to the status bar. - "Reads the current application status bar and moves navigator object into it." + "Reads the current application status bar and moves navigator object into it.", ), category=SCRCAT_OBJECTNAVIGATION, ) @@ -2761,7 +2761,7 @@ def script_reviewCursorToStatusLine(self, gesture): # Translators: Input help mode message for report status line text command. "Reads the current application status bar. " "If pressed twice, spells the information. " - "If pressed three times, copies the status bar to the clipboard" + "If pressed three times, copies the status bar to the clipboard", ), category=SCRCAT_FOCUS, gestures=("kb(desktop):NVDA+end", "kb(laptop):NVDA+shift+end"), @@ -2804,7 +2804,7 @@ def script_reportFocusObjectAccelerator(self, gesture: inputCore.InputGesture) - # Translators: Input help mode message for toggle mouse tracking command. description=_("Toggles the reporting of information as the mouse moves"), category=SCRCAT_MOUSE, - gesture="kb:NVDA+m" + gesture="kb:NVDA+m", ) def script_toggleMouseTracking(self,gesture): if config.conf["mouse"]["enableMouseTracking"]: @@ -2820,7 +2820,7 @@ def script_toggleMouseTracking(self,gesture): @script( # Translators: Input help mode message for toggle mouse text unit resolution command. description=_("Toggles how much text will be spoken when the mouse moves"), - category=SCRCAT_MOUSE + category=SCRCAT_MOUSE, ) def script_toggleMouseTextResolution(self,gesture): values = textInfos.MOUSE_TEXT_RESOLUTION_UNITS @@ -2843,7 +2843,7 @@ def script_toggleMouseTextResolution(self,gesture): # Translators: Input help mode message for report title bar command. "Reports the title of the current application or foreground window. " "If pressed twice, spells the title. " - "If pressed three times, copies the title to the clipboard" + "If pressed three times, copies the title to the clipboard", ), category=SCRCAT_FOCUS, gesture="kb:NVDA+t", @@ -2884,7 +2884,7 @@ def script_speakForeground(self,gesture): sayAll.SayAllHandler.readObjects(obj) @script( - gesture="kb(desktop):NVDA+control+f2" + gesture="kb(desktop):NVDA+control+f2", ) def script_test_navigatorDisplayModelText(self,gesture): obj=api.getNavigatorObject() @@ -2895,9 +2895,9 @@ def script_test_navigatorDisplayModelText(self,gesture): @script( description=_( # Translators: GUI development tool, to get information about the components used in the NVDA GUI - "Opens the WX GUI inspection tool. Used to get more information about the state of GUI components." + "Opens the WX GUI inspection tool. Used to get more information about the state of GUI components.", ), - category=SCRCAT_TOOLS + category=SCRCAT_TOOLS, ) @gui.blockAction.when(gui.blockAction.Context.SECURE_MODE) def script_startWxInspectionTool(self, gesture): @@ -2910,10 +2910,10 @@ def script_startWxInspectionTool(self, gesture): # used by developers to examine technical info on navigator object. # This command also serves as a shortcut to open NVDA log viewer. "Logs information about the current navigator object which is useful to developers " - "and activates the log viewer so the information can be examined." + "and activates the log viewer so the information can be examined.", ), category=SCRCAT_TOOLS, - gesture="kb:NVDA+f1" + gesture="kb:NVDA+f1", ) @gui.blockAction.when(gui.blockAction.Context.SECURE_MODE) def script_navigatorObject_devInfo(self,gesture): @@ -2928,10 +2928,10 @@ def script_navigatorObject_devInfo(self,gesture): # Translators: Input help mode message for a command to delimit then # copy a fragment of the log to clipboard "Mark the current end of the log as the start of the fragment to be" - " copied to clipboard by pressing again." + " copied to clipboard by pressing again.", ), category=SCRCAT_TOOLS, - gesture="kb:NVDA+control+shift+f1" + gesture="kb:NVDA+control+shift+f1", ) @gui.blockAction.when(gui.blockAction.Context.SECURE_MODE) def script_log_markStartThenCopy(self, gesture): @@ -2961,7 +2961,7 @@ def script_log_markStartThenCopy(self, gesture): @script( # Translators: Input help mode message for Open user configuration directory command. description=_("Opens NVDA configuration directory for the current user."), - category=SCRCAT_TOOLS + category=SCRCAT_TOOLS, ) @gui.blockAction.when(gui.blockAction.Context.SECURE_MODE) def script_openUserConfigurationDirectory(self, gesture): @@ -2970,10 +2970,10 @@ def script_openUserConfigurationDirectory(self, gesture): @script( description=_( # Translators: Input help mode message for toggle progress bar output command. - "Toggles between beeps, speech, beeps and speech, and off, for reporting progress bar updates" + "Toggles between beeps, speech, beeps and speech, and off, for reporting progress bar updates", ), category=SCRCAT_SPEECH, - gesture="kb:NVDA+u" + gesture="kb:NVDA+u", ) def script_toggleProgressBarOutput(self,gesture): outputMode=config.conf["presentation"]["progressBarUpdates"]["progressBarOutputMode"] @@ -2999,10 +2999,10 @@ def script_toggleProgressBarOutput(self,gesture): description=_( # Translators: Input help mode message for toggle dynamic content changes command. "Toggles on and off the reporting of dynamic content changes, " - "such as new text in dos console windows" + "such as new text in dos console windows", ), category=SCRCAT_SPEECH, - gesture="kb:NVDA+5" + gesture="kb:NVDA+5", ) def script_toggleReportDynamicContentChanges(self,gesture): if config.conf["presentation"]["reportDynamicContentChanges"]: @@ -3019,7 +3019,7 @@ def script_toggleReportDynamicContentChanges(self,gesture): # Translators: Input help mode message for toggle caret moves review cursor command. description=_("Toggles on and off the movement of the review cursor due to the caret moving."), category=SCRCAT_TEXTREVIEW, - gesture="kb:NVDA+6" + gesture="kb:NVDA+6", ) def script_toggleCaretMovesReviewCursor(self,gesture): if config.conf["reviewCursor"]["followCaret"]: @@ -3036,7 +3036,7 @@ def script_toggleCaretMovesReviewCursor(self,gesture): # Translators: Input help mode message for toggle focus moves navigator object command. description=_("Toggles on and off the movement of the navigator object due to focus changes"), category=SCRCAT_OBJECTNAVIGATION, - gesture="kb:NVDA+7" + gesture="kb:NVDA+7", ) def script_toggleFocusMovesNavigatorObject(self,gesture): if config.conf["reviewCursor"]["followFocus"]: @@ -3053,7 +3053,7 @@ def script_toggleFocusMovesNavigatorObject(self,gesture): # Translators: Input help mode message for toggle auto focus focusable elements command. description=_("Toggles on and off automatic movement of the system focus due to browse mode commands"), category=inputCore.SCRCAT_BROWSEMODE, - gesture="kb:NVDA+8" + gesture="kb:NVDA+8", ) def script_toggleAutoFocusFocusableElements(self,gesture): if config.conf["virtualBuffers"]["autoFocusFocusableElements"]: @@ -3081,10 +3081,10 @@ def script_say_battery_status(self, gesture: inputCore.InputGesture) -> None: description=_( # Translators: Input help mode message for pass next key through command. "The next key that is pressed will not be handled at all by NVDA, " - "it will be passed directly through to Windows." + "it will be passed directly through to Windows.", ), category=SCRCAT_INPUT, - gesture="kb:NVDA+f2" + gesture="kb:NVDA+f2", ) def script_passNextKeyThrough(self,gesture): keyboardHandler.passNextKeyThrough() @@ -3094,7 +3094,7 @@ def script_passNextKeyThrough(self,gesture): @script( description=_( # Translators: Input help mode message for report current program name and app module name command. - "Speaks the filename of the active application along with the name of the currently loaded appModule" + "Speaks the filename of the active application along with the name of the currently loaded appModule", ), category=SCRCAT_TOOLS, gesture="kb:NVDA+control+f1", @@ -3119,7 +3119,7 @@ def script_reportAppModuleInfo(self,gesture): # Translators: Input help mode message for go to general settings command. description=_("Shows NVDA's general settings"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+g" + gesture="kb:NVDA+control+g", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateGeneralSettingsDialog(self, gesture): @@ -3129,7 +3129,7 @@ def script_activateGeneralSettingsDialog(self, gesture): # Translators: Input help mode message for go to select synthesizer command. description=_("Shows the NVDA synthesizer selection dialog"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+s" + gesture="kb:NVDA+control+s", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateSynthesizerDialog(self, gesture): @@ -3139,7 +3139,7 @@ def script_activateSynthesizerDialog(self, gesture): # Translators: Input help mode message for go to speech settings command. description=_("Shows NVDA's speech settings"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+v" + gesture="kb:NVDA+control+v", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateVoiceDialog(self, gesture): @@ -3149,7 +3149,7 @@ def script_activateVoiceDialog(self, gesture): # Translators: Input help mode message for go to select braille display command. description=_("Shows the NVDA braille display selection dialog"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+a" + gesture="kb:NVDA+control+a", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateBrailleDisplayDialog(self, gesture): @@ -3158,7 +3158,7 @@ def script_activateBrailleDisplayDialog(self, gesture): @script( # Translators: Input help mode message for go to braille settings command. description=_("Shows NVDA's braille settings"), - category=SCRCAT_CONFIG + category=SCRCAT_CONFIG, ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateBrailleSettingsDialog(self, gesture): @@ -3168,7 +3168,7 @@ def script_activateBrailleSettingsDialog(self, gesture): # Translators: Input help mode message for go to audio settings command. description=_("Shows NVDA's audio settings"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+u" + gesture="kb:NVDA+control+u", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateAudioSettingsDialog(self, gesture): @@ -3178,7 +3178,7 @@ def script_activateAudioSettingsDialog(self, gesture): # Translators: Input help mode message for go to keyboard settings command. description=_("Shows NVDA's keyboard settings"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+k" + gesture="kb:NVDA+control+k", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateKeyboardSettingsDialog(self, gesture): @@ -3188,7 +3188,7 @@ def script_activateKeyboardSettingsDialog(self, gesture): # Translators: Input help mode message for go to mouse settings command. description=_("Shows NVDA's mouse settings"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+m" + gesture="kb:NVDA+control+m", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateMouseSettingsDialog(self, gesture): @@ -3197,7 +3197,7 @@ def script_activateMouseSettingsDialog(self, gesture): @script( # Translators: Input help mode message for go to review cursor settings command. description=_("Shows NVDA's review cursor settings"), - category=SCRCAT_CONFIG + category=SCRCAT_CONFIG, ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateReviewCursorDialog(self, gesture): @@ -3206,7 +3206,7 @@ def script_activateReviewCursorDialog(self, gesture): @script( # Translators: Input help mode message for go to input composition settings command. description=_("Shows NVDA's input composition settings"), - category=SCRCAT_CONFIG + category=SCRCAT_CONFIG, ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateInputCompositionDialog(self, gesture): @@ -3216,7 +3216,7 @@ def script_activateInputCompositionDialog(self, gesture): # Translators: Input help mode message for go to object presentation settings command. description=_("Shows NVDA's object presentation settings"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+o" + gesture="kb:NVDA+control+o", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateObjectPresentationDialog(self, gesture): @@ -3226,7 +3226,7 @@ def script_activateObjectPresentationDialog(self, gesture): # Translators: Input help mode message for go to browse mode settings command. description=_("Shows NVDA's browse mode settings"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+b" + gesture="kb:NVDA+control+b", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateBrowseModeDialog(self, gesture): @@ -3236,7 +3236,7 @@ def script_activateBrowseModeDialog(self, gesture): # Translators: Input help mode message for go to document formatting settings command. description=_("Shows NVDA's document formatting settings"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+d" + gesture="kb:NVDA+control+d", ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateDocumentFormattingDialog(self, gesture): @@ -3245,7 +3245,7 @@ def script_activateDocumentFormattingDialog(self, gesture): @script( # Translators: Input help mode message for opening default dictionary dialog. description=_("Shows the NVDA default dictionary dialog"), - category=SCRCAT_CONFIG + category=SCRCAT_CONFIG, ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateDefaultDictionaryDialog(self, gesture): @@ -3254,7 +3254,7 @@ def script_activateDefaultDictionaryDialog(self, gesture): @script( # Translators: Input help mode message for opening voice-specific dictionary dialog. description=_("Shows the NVDA voice-specific dictionary dialog"), - category=SCRCAT_CONFIG + category=SCRCAT_CONFIG, ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateVoiceDictionaryDialog(self, gesture): @@ -3263,7 +3263,7 @@ def script_activateVoiceDictionaryDialog(self, gesture): @script( # Translators: Input help mode message for opening temporary dictionary. description=_("Shows the NVDA temporary dictionary dialog"), - category=SCRCAT_CONFIG + category=SCRCAT_CONFIG, ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateTemporaryDictionaryDialog(self, gesture): @@ -3272,7 +3272,7 @@ def script_activateTemporaryDictionaryDialog(self, gesture): @script( # Translators: Input help mode message for go to punctuation/symbol pronunciation dialog. description=_("Shows the NVDA symbol pronunciation dialog"), - category=SCRCAT_CONFIG + category=SCRCAT_CONFIG, ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateSpeechSymbolsDialog(self, gesture): @@ -3281,7 +3281,7 @@ def script_activateSpeechSymbolsDialog(self, gesture): @script( # Translators: Input help mode message for go to input gestures dialog command. description=_("Shows the NVDA input gestures dialog"), - category=SCRCAT_CONFIG + category=SCRCAT_CONFIG, ) @gui.blockAction.when(gui.blockAction.Context.MODAL_DIALOG_OPEN) def script_activateInputGesturesDialog(self, gesture): @@ -3304,7 +3304,7 @@ def script_reportActiveConfigurationProfile(self, gesture): # Translators: Message announced when the command to report the current configuration profile # is active. The placeholder '{profilename}' is replaced with the name of the current active profile. activeProfileMessage = _("{profileName} configuration profile active").format( - profileName=activeProfileName + profileName=activeProfileName, ) ui.message(activeProfileMessage) @@ -3312,7 +3312,7 @@ def script_reportActiveConfigurationProfile(self, gesture): # Translators: Input help mode message for save current configuration command. description=_("Saves the current NVDA configuration"), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+c" + gesture="kb:NVDA+control+c", ) def script_saveConfiguration(self,gesture): wx.CallAfter(gui.mainFrame.onSaveConfigurationCommand, None) @@ -3321,10 +3321,10 @@ def script_saveConfiguration(self,gesture): description=_( # Translators: Input help mode message for apply last saved or default settings command. "Pressing once reverts the current configuration to the most recently saved state." - " Pressing three times resets to factory defaults." + " Pressing three times resets to factory defaults.", ), category=SCRCAT_CONFIG, - gesture="kb:NVDA+control+r" + gesture="kb:NVDA+control+r", ) def script_revertConfiguration(self,gesture): scriptCount=scriptHandler.getLastScriptRepeatCount() @@ -3337,11 +3337,11 @@ def script_revertConfiguration(self,gesture): # Translators: Input help mode message for activate python console command. description=_("Activates the NVDA Python Console, primarily useful for development"), category=SCRCAT_TOOLS, - gesture="kb:NVDA+control+z" + gesture="kb:NVDA+control+z", ) @gui.blockAction.when( gui.blockAction.Context.WINDOWS_STORE_VERSION, - gui.blockAction.Context.SECURE_MODE + gui.blockAction.Context.SECURE_MODE, ) def script_activatePythonConsole(self,gesture): import pythonConsole @@ -3355,7 +3355,7 @@ def script_activatePythonConsole(self,gesture): @script( # Translators: Input help mode message to activate Add-on Store command. description=_("Activates the Add-on Store to browse and manage add-on packages for NVDA"), - category=SCRCAT_TOOLS + category=SCRCAT_TOOLS, ) def script_activateAddonsManager(self, gesture: inputCore.InputGesture): wx.CallAfter(gui.mainFrame.onAddonStoreCommand, None) @@ -3364,9 +3364,9 @@ def script_activateAddonsManager(self, gesture: inputCore.InputGesture): description=_( # Translators: Input help mode message for toggle speech viewer command. "Toggles the NVDA Speech viewer, " - "a floating window that allows you to view all the text that NVDA is currently speaking" + "a floating window that allows you to view all the text that NVDA is currently speaking", ), - category=SCRCAT_TOOLS + category=SCRCAT_TOOLS, ) @gui.blockAction.when(gui.blockAction.Context.SECURE_MODE) def script_toggleSpeechViewer(self, gesture: inputCore.InputGesture): @@ -3386,9 +3386,9 @@ def script_toggleSpeechViewer(self, gesture: inputCore.InputGesture): description=_( # Translators: Input help mode message for toggle Braille viewer command. "Toggles the NVDA Braille viewer, a floating window that allows you to view braille output, " - "and the text equivalent for each braille character" + "and the text equivalent for each braille character", ), - category=SCRCAT_TOOLS + category=SCRCAT_TOOLS, ) @gui.blockAction.when(gui.blockAction.Context.SECURE_MODE) def script_toggleBrailleViewer(self, gesture: inputCore.InputGesture): @@ -3410,7 +3410,7 @@ def script_toggleBrailleViewer(self, gesture: inputCore.InputGesture): # (tethered means connected to or follows). description=_("Toggle tethering of braille between the focus and the review position"), category=SCRCAT_BRAILLE, - gesture="kb:NVDA+control+t" + gesture="kb:NVDA+control+t", ) @gui.blockAction.when(gui.blockAction.Context.BRAILLE_MODE_SPEECH_OUTPUT) def script_braille_toggleTether(self, gesture): @@ -3434,7 +3434,7 @@ def script_braille_toggleTether(self, gesture): # Translators: Input help mode message for toggle braille mode command description=_("Toggles braille mode"), category=SCRCAT_BRAILLE, - gesture="kb:nvda+alt+t" + gesture="kb:nvda+alt+t", ) def script_toggleBrailleMode(self, gesture: inputCore.InputGesture): curMode = BrailleMode(config.conf["braille"]["mode"]) @@ -3459,7 +3459,7 @@ def script_toggleBrailleMode(self, gesture: inputCore.InputGesture): # Translators: Input help mode message for cycle through # braille move system caret when routing review cursor command. description=_("Cycle through the braille move system caret when routing review cursor states"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) @gui.blockAction.when(gui.blockAction.Context.BRAILLE_MODE_SPEECH_OUTPUT) def script_braille_cycleReviewRoutingMovesSystemCaret(self, gesture: inputCore.InputGesture) -> None: @@ -3468,7 +3468,7 @@ def script_braille_cycleReviewRoutingMovesSystemCaret(self, gesture: inputCore.I if TetherTo.FOCUS.value == config.conf["braille"]["tetherTo"]: ui.message( # Translators: Reported when action is unavailable because braille tether is to focus. - _("Action unavailable. Braille is tethered to focus") + _("Action unavailable. Braille is tethered to focus"), ) return featureFlag: FeatureFlag = config.conf["braille"]["reviewRoutingMovesSystemCaret"] @@ -3483,19 +3483,19 @@ def script_braille_cycleReviewRoutingMovesSystemCaret(self, gesture: inputCore.I msg = _( # Translators: Used when reporting braille move system caret when routing review cursor # state (default behavior). - "Braille move system caret when routing review cursor default (%s)" + "Braille move system caret when routing review cursor default (%s)", ) % featureFlag.behaviorOfDefault.displayString else: msg = _( # Translators: Used when reporting braille move system caret when routing review cursor state. - "Braille move system caret when routing review cursor %s" + "Braille move system caret when routing review cursor %s", ) % reviewRoutingMovesSystemCaretFlag[nextName].displayString ui.message(msg) @script( # Translators: Input help mode message for toggle braille focus context presentation command. description=_("Toggle the way context information is presented in braille"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) @gui.blockAction.when(gui.blockAction.Context.BRAILLE_MODE_SPEECH_OUTPUT) def script_braille_toggleFocusContextPresentation(self, gesture): @@ -3517,7 +3517,7 @@ def script_braille_toggleFocusContextPresentation(self, gesture): @script( # Translators: Input help mode message for toggle braille cursor command. description=_("Toggle the braille cursor on and off"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) @gui.blockAction.when(gui.blockAction.Context.BRAILLE_MODE_SPEECH_OUTPUT) def script_braille_toggleShowCursor(self, gesture): @@ -3536,7 +3536,7 @@ def script_braille_toggleShowCursor(self, gesture): @script( # Translators: Input help mode message for cycle braille cursor shape command. description=_("Cycle through the braille cursor shapes"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) @gui.blockAction.when(gui.blockAction.Context.BRAILLE_MODE_SPEECH_OUTPUT) def script_braille_cycleCursorShape(self, gesture): @@ -3563,7 +3563,7 @@ def script_braille_cycleCursorShape(self, gesture): @script( # Translators: Input help mode message for cycle through braille show messages command. description=_("Cycle through the braille show messages modes"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) @gui.blockAction.when(gui.blockAction.Context.BRAILLE_MODE_SPEECH_OUTPUT) def script_braille_cycleShowMessages(self, gesture: inputCore.InputGesture) -> None: @@ -3581,7 +3581,7 @@ def script_braille_cycleShowMessages(self, gesture: inputCore.InputGesture) -> N @script( # Translators: Input help mode message for cycle through braille show selection command. description=_("Cycle through the braille show selection states"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) @gui.blockAction.when(gui.blockAction.Context.BRAILLE_MODE_SPEECH_OUTPUT) def script_braille_cycleShowSelection(self, gesture: inputCore.InputGesture) -> None: @@ -3609,7 +3609,7 @@ def script_braille_cycleShowSelection(self, gesture: inputCore.InputGesture) -> @script( # Translators: Input help mode message for Braille Unicode normalization command. description=_("Cycle through the braille Unicode normalization states"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) def script_braille_cycleUnicodeNormalization(self, gesture: inputCore.InputGesture) -> None: featureFlag: FeatureFlag = config.conf["braille"]["unicodeNormalization"] @@ -3624,13 +3624,13 @@ def script_braille_cycleUnicodeNormalization(self, gesture: inputCore.InputGestu # Translators: Used when reporting braille Unicode normalization state # (default behavior). msg = _("Braille Unicode normalization default ({default})").format( - default=featureFlag.behaviorOfDefault.displayString + default=featureFlag.behaviorOfDefault.displayString, ) else: # Translators: Used when reporting braille Unicode normalization state # (disabled or enabled). msg = _("Braille Unicode normalization {state}").format( - state=BoolFlag[nextName].displayString + state=BoolFlag[nextName].displayString, ) ui.message(msg) @@ -3639,7 +3639,7 @@ def script_braille_cycleUnicodeNormalization(self, gesture: inputCore.InputGestu # Translators: Input help mode message for report clipboard text command. "Reports the text on the Windows clipboard. " "Pressing twice spells this information. " - "Pressing three times spells it using character descriptions." + "Pressing three times spells it using character descriptions.", ), category=SCRCAT_SYSTEM, gesture="kb:NVDA+c", @@ -3662,23 +3662,25 @@ def script_reportClipboardText(self,gesture): else: speech.speakSpelling(text, useCharacterDescriptions=repeatCount > 1) else: - ui.message(ngettext( - # Translators: If the number of characters on the clipboard is greater than about 1000, it reports this - # message and gives number of characters on the clipboard. - # Example output: The clipboard contains a large amount of text. It is 2300 characters long. - "The clipboard contains a large amount of text. It is %s character long", - "The clipboard contains a large amount of text. It is %s characters long", - textLength, - ) % textLength) + ui.message( + ngettext( + # Translators: If the number of characters on the clipboard is greater than about 1000, it reports this + # message and gives number of characters on the clipboard. + # Example output: The clipboard contains a large amount of text. It is 2300 characters long. + "The clipboard contains a large amount of text. It is %s character long", + "The clipboard contains a large amount of text. It is %s characters long", + textLength, + ) % textLength, + ) @script( description=_( # Translators: Input help mode message for mark review cursor position for a select or copy command # (that is, marks the current review cursor position as the starting point for text to be selected). - "Marks the current position of the review cursor as the start of text to be selected or copied" + "Marks the current position of the review cursor as the start of text to be selected or copied", ), category=SCRCAT_TEXTREVIEW, - gesture="kb:NVDA+f9" + gesture="kb:NVDA+f9", ) def script_review_markStartForCopy(self, gesture): reviewPos = api.getReviewPosition() @@ -3692,10 +3694,10 @@ def script_review_markStartForCopy(self, gesture): description=_( # Translators: Input help mode message for move review cursor to marked start position for a # select or copy command - "Move the review cursor to the position marked as the start of text to be selected or copied" + "Move the review cursor to the position marked as the start of text to be selected or copied", ), category=SCRCAT_TEXTREVIEW, - gesture="kb:NVDA+shift+F9" + gesture="kb:NVDA+shift+F9", ) def script_review_moveToStartMarkedForCopy(self, gesture: inputCore.InputGesture): pos = api.getReviewPosition() @@ -3714,7 +3716,7 @@ def script_review_moveToStartMarkedForCopy(self, gesture: inputCore.InputGesture speech.speakTextInfo( startMarker, unit=textInfos.UNIT_CHARACTER, - reason=controlTypes.OutputReason.CARET + reason=controlTypes.OutputReason.CARET, ) else: ui.reviewMessage(gui.blockAction.Context.WINDOWS_LOCKED.translatedMessage) @@ -3725,10 +3727,10 @@ def script_review_moveToStartMarkedForCopy(self, gesture: inputCore.InputGesture # Translators: Input help mode message for the select then copy command. # The select then copy command first selects the review cursor text, then copies it to the clipboard. "If pressed once, the text from the previously set start marker up to and including the current " - "position of the review cursor is selected. If pressed twice, the text is copied to the clipboard" + "position of the review cursor is selected. If pressed twice, the text is copied to the clipboard", ), category=SCRCAT_TEXTREVIEW, - gesture="kb:NVDA+f10" + gesture="kb:NVDA+f10", ) def script_review_copy(self, gesture): pos = api.getReviewPosition().copy() @@ -3798,7 +3800,7 @@ def script_review_copy(self, gesture): # Translators: Input help mode message for a braille command. description=_("Scrolls the braille display back"), category=SCRCAT_BRAILLE, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_scrollBack(self, gesture): braille.handler.scrollBack() @@ -3807,7 +3809,7 @@ def script_braille_scrollBack(self, gesture): # Translators: Input help mode message for a braille command. description=_("Scrolls the braille display forward"), category=SCRCAT_BRAILLE, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_scrollForward(self, gesture): braille.handler.scrollForward() @@ -3815,7 +3817,7 @@ def script_braille_scrollForward(self, gesture): @script( # Translators: Input help mode message for a braille command. description=_("Routes the cursor to or activates the object under this braille cell"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) def script_braille_routeTo(self, gesture): braille.handler.routeTo(gesture.routingIndex) @@ -3823,7 +3825,7 @@ def script_braille_routeTo(self, gesture): @script( # Translators: Input help mode message for Braille report formatting command. description=_("Reports formatting info for the text under this braille cell"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) def script_braille_reportFormatting(self, gesture): info = braille.handler.getTextInfoForWindowPos(gesture.routingIndex) @@ -3836,7 +3838,7 @@ def script_braille_reportFormatting(self, gesture): @script( # Translators: Input help mode message for a braille command. description=_("Moves the braille display to the previous line"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) def script_braille_previousLine(self, gesture): if braille.handler.buffer.regions: @@ -3845,7 +3847,7 @@ def script_braille_previousLine(self, gesture): @script( # Translators: Input help mode message for a braille command. description=_("Moves the braille display to the next line"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) def script_braille_nextLine(self, gesture): if braille.handler.buffer.regions: @@ -3855,7 +3857,7 @@ def script_braille_nextLine(self, gesture): # Translators: Input help mode message for a braille command. description=_("Inputs braille dots via the braille keyboard"), category=SCRCAT_BRAILLE, - gesture="bk:dots" + gesture="bk:dots", ) def script_braille_dots(self, gesture): brailleInput.handler.input(gesture.dots) @@ -3863,7 +3865,7 @@ def script_braille_dots(self, gesture): @script( # Translators: Input help mode message for a braille command. description=_("Moves the braille display to the current focus"), - category=SCRCAT_BRAILLE + category=SCRCAT_BRAILLE, ) def script_braille_toFocus(self, gesture): braille.handler.setTether(TetherTo.FOCUS.value, auto=True) @@ -3886,7 +3888,7 @@ def script_braille_toFocus(self, gesture): # Translators: Input help mode message for a braille command. description=_("Erases the last entered braille cell or character"), category=SCRCAT_BRAILLE, - gesture="bk:dot7" + gesture="bk:dot7", ) def script_braille_eraseLastCell(self, gesture): brailleInput.handler.eraseLastCell() @@ -3895,7 +3897,7 @@ def script_braille_eraseLastCell(self, gesture): # Translators: Input help mode message for a braille command. description=_("Translates any braille input and presses the enter key"), category=SCRCAT_BRAILLE, - gesture="bk:dot8" + gesture="bk:dot8", ) def script_braille_enter(self, gesture): brailleInput.handler.enter() @@ -3904,7 +3906,7 @@ def script_braille_enter(self, gesture): # Translators: Input help mode message for a braille command. description=_("Translates any braille input"), category=SCRCAT_BRAILLE, - gesture="bk:dot7+dot8" + gesture="bk:dot7+dot8", ) def script_braille_translate(self, gesture): brailleInput.handler.translate() @@ -3913,7 +3915,7 @@ def script_braille_translate(self, gesture): # Translators: Input help mode message for a braille command. description=_("Virtually toggles the shift key to emulate a keyboard shortcut with braille input"), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleShift(self, gesture): brailleInput.handler.toggleModifier("shift") @@ -3922,7 +3924,7 @@ def script_braille_toggleShift(self, gesture): # Translators: Input help mode message for a braille command. description=_("Virtually toggles the control key to emulate a keyboard shortcut with braille input"), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleControl(self, gesture): brailleInput.handler.toggleModifier("control") @@ -3931,7 +3933,7 @@ def script_braille_toggleControl(self, gesture): # Translators: Input help mode message for a braille command. description=_("Virtually toggles the alt key to emulate a keyboard shortcut with braille input"), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleAlt(self, gesture): brailleInput.handler.toggleModifier("alt") @@ -3940,7 +3942,7 @@ def script_braille_toggleAlt(self, gesture): # Translators: Input help mode message for a braille command. description=_("Virtually toggles the left windows key to emulate a keyboard shortcut with braille input"), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleWindows(self, gesture): brailleInput.handler.toggleModifier("leftWindows") @@ -3949,7 +3951,7 @@ def script_braille_toggleWindows(self, gesture): # Translators: Input help mode message for a braille command. description=_("Virtually toggles the NVDA key to emulate a keyboard shortcut with braille input"), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleNVDAKey(self, gesture): brailleInput.handler.toggleModifier("NVDA") @@ -3958,9 +3960,10 @@ def script_braille_toggleNVDAKey(self, gesture): description=_( # Translators: Input help mode message for a braille command. "Virtually toggles the control and shift keys to emulate a " - "keyboard shortcut with braille input"), + "keyboard shortcut with braille input", + ), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleControlShift(self, gesture): brailleInput.handler.toggleModifiers(["control", "shift"]) @@ -3969,9 +3972,10 @@ def script_braille_toggleControlShift(self, gesture): description=_( # Translators: Input help mode message for a braille command. "Virtually toggles the alt and shift keys to emulate a " - "keyboard shortcut with braille input"), + "keyboard shortcut with braille input", + ), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleAltShift(self, gesture): brailleInput.handler.toggleModifiers(["alt", "shift"]) @@ -3980,9 +3984,10 @@ def script_braille_toggleAltShift(self, gesture): description=_( # Translators: Input help mode message for a braille command. "Virtually toggles the left windows and shift keys to emulate a " - "keyboard shortcut with braille input"), + "keyboard shortcut with braille input", + ), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleWindowsShift(self, gesture): brailleInput.handler.toggleModifiers(["leftWindows", "shift"]) @@ -3991,9 +3996,10 @@ def script_braille_toggleWindowsShift(self, gesture): description=_( # Translators: Input help mode message for a braille command. "Virtually toggles the NVDA and shift keys to emulate a " - "keyboard shortcut with braille input"), + "keyboard shortcut with braille input", + ), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleNVDAKeyShift(self, gesture): brailleInput.handler.toggleModifiers(["NVDA", "shift"]) @@ -4002,9 +4008,10 @@ def script_braille_toggleNVDAKeyShift(self, gesture): description=_( # Translators: Input help mode message for a braille command. "Virtually toggles the control and alt keys to emulate a " - "keyboard shortcut with braille input"), + "keyboard shortcut with braille input", + ), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleControlAlt(self, gesture): brailleInput.handler.toggleModifiers(["control", "alt"]) @@ -4013,9 +4020,10 @@ def script_braille_toggleControlAlt(self, gesture): description=_( # Translators: Input help mode message for a braille command. "Virtually toggles the control, alt, and shift keys to emulate a " - "keyboard shortcut with braille input"), + "keyboard shortcut with braille input", + ), category=inputCore.SCRCAT_KBEMU, - bypassInputHelp=True + bypassInputHelp=True, ) def script_braille_toggleControlAltShift(self, gesture): brailleInput.handler.toggleModifiers(["control", "alt", "shift"]) @@ -4023,10 +4031,10 @@ def script_braille_toggleControlAltShift(self, gesture): @script( description=_( # Translators: Input help mode message for reload plugins command. - "Reloads app modules and global plugins without restarting NVDA, which can be Useful for developers" + "Reloads app modules and global plugins without restarting NVDA, which can be Useful for developers", ), category=SCRCAT_TOOLS, - gesture="kb:NVDA+control+f3" + gesture="kb:NVDA+control+f3", ) def script_reloadPlugins(self, gesture): import globalPluginHandler @@ -4040,14 +4048,14 @@ def script_reloadPlugins(self, gesture): description=_( # Translators: input help mode message for Report destination URL of a link command "Report the destination URL of the link at the position of caret or focus. " - "If pressed twice, shows the URL in a window for easier review." + "If pressed twice, shows the URL in a window for easier review.", ), gesture="kb:NVDA+k", category=SCRCAT_TOOLS, speakOnDemand=True, ) def script_reportLinkDestination( - self, gesture: inputCore.InputGesture, forceBrowseable: bool = False + self, gesture: inputCore.InputGesture, forceBrowseable: bool = False, ) -> None: """Generates a ui.message or ui.browseableMessage of a link's destination, if focus or caret is positioned on a link, or an element with an included link such as a graphic. @@ -4088,7 +4096,7 @@ def script_reportLinkDestination( linkDestination, # Translators: Informs the user that the window contains the destination of the # link with given title - title=_("Destination of: {name}").format(name=obj.name) + title=_("Destination of: {name}").format(name=obj.name), ) elif presses == 0: # One press ui.message(linkDestination) # Speak the link @@ -4102,9 +4110,9 @@ def script_reportLinkDestination( description=_( # Translators: input help mode message for Report URL of a link in a window command "Displays the destination URL of the link at the position of caret or focus in a window, " - "instead of just speaking it. May be preferred by braille users." + "instead of just speaking it. May be preferred by braille users.", ), - category=SCRCAT_TOOLS + category=SCRCAT_TOOLS, ) def script_reportLinkDestinationInWindow(self, gesture: inputCore.InputGesture) -> None: """Uses the forceBrowseable flag of script_reportLinkDestination, to generate a @@ -4187,7 +4195,7 @@ def script_navigatorObject_previousInFlow(self, gesture: inputCore.InputGesture) # Translators: Describes a command. description=_("Toggles the support of touch interaction"), category=SCRCAT_TOUCH, - gesture="kb:NVDA+control+alt+t" + gesture="kb:NVDA+control+alt+t", ) def script_toggleTouchSupport(self, gesture): enabled = not bool(config.conf["touch"]["enabled"]) @@ -4210,7 +4218,7 @@ def script_toggleTouchSupport(self, gesture): # Translators: Input help mode message for a touchscreen gesture. description=_("Cycles between available touch modes"), category=SCRCAT_TOUCH, - gesture="ts:3finger_tap" + gesture="ts:3finger_tap", ) def script_touch_changeMode(self,gesture): mode=touchHandler.handler._curTouchMode @@ -4229,7 +4237,7 @@ def script_touch_changeMode(self,gesture): # Translators: Input help mode message for a touchscreen gesture. description=_("Reports the object and content directly under your finger"), category=SCRCAT_TOUCH, - gestures=("ts:tap", "ts:hoverDown") + gestures=("ts:tap", "ts:hoverDown"), ) def script_touch_newExplore(self,gesture): touchHandler.handler.screenExplorer.moveTo(gesture.x,gesture.y,new=True) @@ -4238,17 +4246,17 @@ def script_touch_newExplore(self,gesture): description=_( # Translators: Input help mode message for a touchscreen gesture. "Reports the new object or content under your finger " - "if different to where your finger was last" + "if different to where your finger was last", ), category=SCRCAT_TOUCH, - gesture="ts:hover" + gesture="ts:hover", ) def script_touch_explore(self,gesture): touchHandler.handler.screenExplorer.moveTo(gesture.x,gesture.y) @script( category=SCRCAT_TOUCH, - gesture="ts:hoverUp" + gesture="ts:hoverUp", ) def script_touch_hoverUp(self,gesture): #Specifically for touch typing with onscreen keyboard keys @@ -4264,10 +4272,10 @@ def script_touch_hoverUp(self,gesture): description=_( # Translators: Input help mode message for touch right click command. "Clicks the right mouse button at the current touch position. " - "This is generally used to activate a context menu." + "This is generally used to activate a context menu.", ), category=SCRCAT_TOUCH, - gesture="ts:tapAndHold" + gesture="ts:tapAndHold", ) def script_touch_rightClick(self, gesture): obj = api.getNavigatorObject() @@ -4301,7 +4309,7 @@ def script_touch_rightClick(self, gesture): # Translators: Describes the command to open the Configuration Profiles dialog. description=_("Shows the NVDA Configuration Profiles dialog"), category=SCRCAT_CONFIG_PROFILES, - gesture="kb:NVDA+control+p" + gesture="kb:NVDA+control+p", ) def script_activateConfigProfilesDialog(self, gesture): wx.CallAfter(gui.mainFrame.onConfigProfilesCommand, None) @@ -4310,9 +4318,9 @@ def script_activateConfigProfilesDialog(self, gesture): description=_( # Translators: Input help mode message for toggle configuration profile triggers command. "Toggles disabling of all configuration profile triggers. " - "Disabling remains in effect until NVDA is restarted" + "Disabling remains in effect until NVDA is restarted", ), - category=SCRCAT_CONFIG + category=SCRCAT_CONFIG, ) def script_toggleConfigProfileTriggers(self,gesture): if config.conf.profileTriggersEnabled: @@ -4332,7 +4340,7 @@ def script_toggleConfigProfileTriggers(self,gesture): @script( # Translators: Describes a command. description=_("Begins interaction with math content"), - gesture="kb:NVDA+alt+m" + gesture="kb:NVDA+alt+m", ) def script_interactWithMath(self, gesture): import mathPres @@ -4354,7 +4362,7 @@ def script_interactWithMath(self, gesture): @script( # Translators: Describes a command. description=_("Recognizes the content of the current navigator object with Windows OCR"), - gesture="kb:NVDA+r" + gesture="kb:NVDA+r", ) def script_recognizeWithUwpOcr(self, gesture): if not winVersion.isUwpOcrAvailable(): @@ -4396,7 +4404,7 @@ def script_cycleOcrLanguage(self, gesture: inputCore.InputGesture) -> None: @script( # Translators: Input help mode message for toggle report CLDR command. description=_("Toggles on and off the reporting of CLDR characters, such as emojis"), - category=SCRCAT_SPEECH + category=SCRCAT_SPEECH, ) def script_toggleReportCLDR(self, gesture): if config.conf["speech"]["includeCLDR"]: @@ -4413,7 +4421,7 @@ def script_toggleReportCLDR(self, gesture): @script( # Translators: Input help mode message for speech Unicode normalization command. description=_("Cycle through the speech Unicode normalization states"), - category=SCRCAT_SPEECH + category=SCRCAT_SPEECH, ) def script_speech_cycleUnicodeNormalization(self, gesture: inputCore.InputGesture) -> None: featureFlag: FeatureFlag = config.conf["speech"]["unicodeNormalization"] @@ -4428,13 +4436,13 @@ def script_speech_cycleUnicodeNormalization(self, gesture: inputCore.InputGestur # Translators: Used when reporting speech Unicode normalization state # (default behavior). msg = _("Speech Unicode normalization default ({default})").format( - default=featureFlag.behaviorOfDefault.displayString + default=featureFlag.behaviorOfDefault.displayString, ) else: # Translators: Used when reporting speech Unicode normalization state # (disabled or enabled). msg = _("Speech Unicode normalization {state}").format( - state=BoolFlag[nextName].displayString + state=BoolFlag[nextName].displayString, ) ui.message(msg) @@ -4447,7 +4455,7 @@ def script_speech_cycleUnicodeNormalization(self, gesture: inputCore.InputGestur "Toggles the state of the screen curtain, " "enable to make the screen black or disable to show the contents of the screen. " "Pressed once, screen curtain is enabled until you restart NVDA. " - "Pressed twice, screen curtain is enabled until you disable it" + "Pressed twice, screen curtain is enabled until you disable it", ), category=SCRCAT_VISION, gesture="kb:NVDA+control+escape", @@ -4477,11 +4485,11 @@ def script_toggleScreenCurtain(self, gesture): speech.cancelSpeech() speech.speakObject( api.getForegroundObject(), - reason=controlTypes.OutputReason.FOCUS + reason=controlTypes.OutputReason.FOCUS, ) speech.speakObject( api.getFocusObject(), - reason=controlTypes.OutputReason.FOCUS + reason=controlTypes.OutputReason.FOCUS, ) return @@ -4493,7 +4501,7 @@ def script_toggleScreenCurtain(self, gesture): # it takes preference, and there shouldn't be a valid completion message in this case anyway. ui.message( self._toggleScreenCurtainMessage, - speechPriority=speech.priorities.Spri.NOW + speechPriority=speech.priorities.Spri.NOW, ) return @@ -4561,7 +4569,7 @@ def _enableScreenCurtain(doEnable: bool = True): parent = gui.mainFrame dlg = WarnOnLoadDialog( screenCurtainSettingsStorage=settingsStorage, - parent=parent + parent=parent, ) self._waitingOnScreenCurtainWarningDialog = dlg gui.runScriptModalDialog( @@ -4569,8 +4577,8 @@ def _enableScreenCurtain(doEnable: bool = True): lambda res: wx.CallLater( millis=100, callableObj=_enableScreenCurtain, - doEnable=res == wx.YES - ) + doEnable=res == wx.YES, + ), ) else: from contentRecog.recogUi import RefreshableRecogResultNVDAObject @@ -4587,7 +4595,7 @@ def _enableScreenCurtain(doEnable: bool = True): # Translators: Describes a command. "Cycles through paragraph navigation styles", ), - category=SCRCAT_SYSTEMCARET + category=SCRCAT_SYSTEMCARET, ) def script_cycleParagraphStyle(self, gesture: "inputCore.InputGesture") -> None: from documentNavigation.paragraphHelper import nextParagraphStyle diff --git a/source/gui/__init__.py b/source/gui/__init__.py index df248598b12..b40d793e5e0 100644 --- a/source/gui/__init__.py +++ b/source/gui/__init__.py @@ -261,7 +261,7 @@ def onExecuteUpdateCommand(self, evt): destPath=destPath, version=version, apiVersion=apiVersion, - backCompatTo=backCompatToAPIVersion + backCompatTo=backCompatToAPIVersion, ) runScriptModalDialog(confirmUpdateDialog) else: @@ -459,15 +459,16 @@ def onRunCOMRegistrationFixesCommand(self, evt): # Translators: A message to warn the user when starting the COM Registration Fixing tool _("You are about to run the COM Registration Fixing tool. This tool will try to fix common system problems that stop NVDA from being able to access content in many programs including Firefox and Internet Explorer. This tool must make changes to the System registry and therefore requires administrative access. Are you sure you wish to proceed?"), # Translators: The title of the warning dialog displayed when launching the COM Registration Fixing tool - _("Warning"),wx.YES|wx.NO|wx.ICON_WARNING,self + _("Warning"),wx.YES|wx.NO|wx.ICON_WARNING,self, )==wx.NO: return - progressDialog = IndeterminateProgressDialog(mainFrame, - # Translators: The title of the dialog presented while NVDA is running the COM Registration fixing tool - _("COM Registration Fixing Tool"), - # Translators: The message displayed while NVDA is running the COM Registration fixing tool - _("Please wait while NVDA tries to fix your system's COM registrations.") - ) + progressDialog = IndeterminateProgressDialog( + mainFrame, + # Translators: The title of the dialog presented while NVDA is running the COM Registration fixing tool + _("COM Registration Fixing Tool"), + # Translators: The message displayed while NVDA is running the COM Registration fixing tool + _("Please wait while NVDA tries to fix your system's COM registrations."), + ) try: systemUtils.execElevated(config.SLAVE_FILENAME, ["fixCOMRegistrations"]) except: # noqa: E722 @@ -478,11 +479,11 @@ def onRunCOMRegistrationFixesCommand(self, evt): _( # Translators: The message displayed when the COM Registration Fixing tool completes. "The COM Registration Fixing tool has finished. " - "It is highly recommended that you restart your computer now, to make sure the changes take full effect." + "It is highly recommended that you restart your computer now, to make sure the changes take full effect.", ), # Translators: The title of a dialog presented when the COM Registration Fixing tool is complete. _("COM Registration Fixing Tool"), - wx.OK + wx.OK, ) @blockAction.when(blockAction.Context.MODAL_DIALOG_OPEN) @@ -502,11 +503,13 @@ def __init__(self, frame: MainFrame): self.menu=wx.Menu() menu_preferences=self.preferencesMenu=wx.Menu() - item = menu_preferences.Append(wx.ID_ANY, - # Translators: The label for the menu item to open NVDA Settings dialog. - _("&Settings..."), - # Translators: The description for the menu item to open NVDA Settings dialog. - _("NVDA settings")) + item = menu_preferences.Append( + wx.ID_ANY, + # Translators: The label for the menu item to open NVDA Settings dialog. + _("&Settings..."), + # Translators: The description for the menu item to open NVDA Settings dialog. + _("NVDA settings"), + ) self.Bind(wx.EVT_MENU, frame.onNVDASettingsCommand, item) if not globalVars.appArgs.secure: # Translators: The label for a submenu under NvDA Preferences menu to select speech dictionaries. @@ -534,7 +537,7 @@ def __init__(self, frame: MainFrame): self.menu_tools_toggleBrailleViewer: wx.MenuItem = menu_tools.AppendCheckItem( wx.ID_ANY, # Translators: The label for the menu item to toggle Braille Viewer. - _("&Braille viewer") + _("&Braille viewer"), ) item = self.menu_tools_toggleBrailleViewer @@ -619,7 +622,7 @@ def _createSpeechDictsSubMenu(self, frame: MainFrame) -> wx.Menu: # Translators: The label for the menu item to open Default speech dictionary dialog. _("&Default dictionary..."), # Translators: The help text for the menu item to open Default speech dictionary dialog. - _("A dialog where you can set default dictionary by adding dictionary entries to the list") + _("A dialog where you can set default dictionary by adding dictionary entries to the list"), ) self.Bind(wx.EVT_MENU, frame.onDefaultDictionaryCommand, item) item = subMenu_speechDicts.Append( @@ -630,8 +633,8 @@ def _createSpeechDictsSubMenu(self, frame: MainFrame) -> wx.Menu: # Translators: The help text for the menu item # to open Voice specific speech dictionary dialog. "A dialog where you can set voice-specific dictionary by adding" - " dictionary entries to the list" - ) + " dictionary entries to the list", + ), ) self.Bind(wx.EVT_MENU, frame.onVoiceDictionaryCommand, item) item = subMenu_speechDicts.Append( @@ -639,7 +642,7 @@ def _createSpeechDictsSubMenu(self, frame: MainFrame) -> wx.Menu: # Translators: The label for the menu item to open Temporary speech dictionary dialog. _("&Temporary dictionary..."), # Translators: The help text for the menu item to open Temporary speech dictionary dialog. - _("A dialog where you can set temporary dictionary by adding dictionary entries to the edit box") + _("A dialog where you can set temporary dictionary by adding dictionary entries to the edit box"), ) self.Bind(wx.EVT_MENU, frame.onTemporaryDictionaryCommand, item) return subMenu_speechDicts @@ -654,7 +657,7 @@ def _appendConfigManagementSection(self, frame: MainFrame) -> None: # Translators: The label for the menu item to revert to saved configuration. _("&Revert to saved configuration"), # Translators: The help text for the menu item to revert to saved configuration. - _("Reset all settings to saved state") + _("Reset all settings to saved state"), ) self.Bind(wx.EVT_MENU, frame.onRevertToSavedConfigurationCommand, item) item = self.menu.Append( @@ -664,7 +667,7 @@ def _appendConfigManagementSection(self, frame: MainFrame) -> None: _("Reset configuration to &factory defaults"), # Translators: The help text for the menu item to reset settings to default settings. # Here, default settings means settings that were there when the user first used NVDA. - _("Reset all settings to default state") + _("Reset all settings to default state"), ) self.Bind(wx.EVT_MENU, frame.onRevertToDefaultConfigurationCommand, item) if NVDAState.shouldWriteToDisk(): @@ -673,7 +676,7 @@ def _appendConfigManagementSection(self, frame: MainFrame) -> None: # Translators: The label for the menu item to save current settings. _("&Save configuration"), # Translators: The help text for the menu item to save current settings. - _("Write the current configuration to nvda.ini") + _("Write the current configuration to nvda.ini"), ) self.Bind(wx.EVT_MENU, frame.onSaveConfigurationCommand, item) @@ -710,14 +713,14 @@ def _appendHelpSubMenu(self, frame: MainFrame) -> None: self.Bind( wx.EVT_MENU, lambda evt: systemUtils._displayTextFileWorkaround(getDocFilePath("copying.txt", False)), - item + item, ) # Translators: The label for the menu item to view NVDA Contributors list document. item = self.helpMenu.Append(wx.ID_ANY, _("C&ontributors")) self.Bind( wx.EVT_MENU, lambda evt: systemUtils._displayTextFileWorkaround(getDocFilePath("contributors.txt", False)), - item + item, ) self.helpMenu.AppendSeparator() @@ -747,7 +750,7 @@ def _appendPendingUpdateSection(self, frame: MainFrame) -> None: # Translators: The label for the menu item to run a pending update. _("Install pending &update"), # Translators: The description for the menu item to run a pending update. - _("Execute a previously downloaded NVDA update") + _("Execute a previously downloaded NVDA update"), ) self.Bind(wx.EVT_MENU, frame.onExecuteUpdateCommand, item) diff --git a/source/gui/addonGui.py b/source/gui/addonGui.py index 2c127f08711..9807f1b06c1 100644 --- a/source/gui/addonGui.py +++ b/source/gui/addonGui.py @@ -29,14 +29,14 @@ def promptUserForRestart(): # as addons have been added, enabled/disabled or removed. "Changes were made to add-ons. " "You must restart NVDA for these changes to take effect. " - "Would you like to restart now?" + "Would you like to restart now?", ) # Translators: Title for message asking if the user wishes to restart NVDA as addons have been added or removed. restartTitle = _("Restart NVDA") result = gui.messageBox( message=restartMessage, caption=restartTitle, - style=wx.YES | wx.NO | wx.ICON_WARNING + style=wx.YES | wx.NO | wx.ICON_WARNING, ) if wx.YES == result: if gui.message.isModalMessageBoxActive(): @@ -52,7 +52,7 @@ def __init__(self, parent, title, message, showAddonInfoFunction): parent, title, message, - dialogType=nvdaControls.MessageDialog.DIALOG_TYPE_WARNING + dialogType=nvdaControls.MessageDialog.DIALOG_TYPE_WARNING, ) self._showAddonInfoFunction = showAddonInfoFunction @@ -61,7 +61,7 @@ def _addButtons(self, buttonHelper): self, # Translators: A button in the addon installation warning / blocked dialog which shows # more information about the addon - label=_("&About add-on...") + label=_("&About add-on..."), ) addonInfoButton.Bind(wx.EVT_BUTTON, lambda evt: self._showAddonInfoFunction()) yesButton = buttonHelper.addButton( @@ -69,7 +69,7 @@ def _addButtons(self, buttonHelper): id=wx.ID_YES, # Translators: A button in the addon installation warning dialog which allows the user to agree to installing # the add-on - label=_("&Yes") + label=_("&Yes"), ) yesButton.SetDefault() yesButton.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.YES)) @@ -79,7 +79,7 @@ def _addButtons(self, buttonHelper): id=wx.ID_NO, # Translators: A button in the addon installation warning dialog which allows the user to decide not to # install the add-on - label=_("&No") + label=_("&No"), ) noButton.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.NO)) @@ -90,7 +90,7 @@ def __init__(self, parent, title, message, showAddonInfoFunction): parent, title, message, - dialogType=nvdaControls.MessageDialog.DIALOG_TYPE_ERROR + dialogType=nvdaControls.MessageDialog.DIALOG_TYPE_ERROR, ) self._showAddonInfoFunction = showAddonInfoFunction @@ -99,7 +99,7 @@ def _addButtons(self, buttonHelper): self, # Translators: A button in the addon installation warning / blocked dialog which shows # more information about the addon - label=_("&About add-on...") + label=_("&About add-on..."), ) addonInfoButton.Bind(wx.EVT_BUTTON, lambda evt: self._showAddonInfoFunction()) @@ -107,14 +107,16 @@ def _addButtons(self, buttonHelper): self, id=wx.ID_OK, # Translators: A button in the addon installation blocked dialog which will dismiss the dialog. - label=_("OK") + label=_("OK"), ) okButton.SetDefault() okButton.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.OK)) - displayDialogAsModal(IncompatibleAddonsDialog( - parent=self, - # the defaults from the addon GUI are fine. We are testing against the running version. - )) + displayDialogAsModal( + IncompatibleAddonsDialog( + parent=self, + # the defaults from the addon GUI are fine. We are testing against the running version. + ), + ) # C901 'installAddon' is too complex (16) @@ -142,7 +144,7 @@ def installAddon(parentWindow: wx.Window, addonPath: str) -> bool: # noqa: C901 _("Failed to open add-on package file at %s - missing file or invalid file format") % addonPath, # Translators: The title of a dialog presented when an error occurs. _("Error"), - wx.OK | wx.ICON_ERROR + wx.OK | wx.ICON_ERROR, ) return False # Exit early, can't install an invalid bundle @@ -176,20 +178,20 @@ def installAddon(parentWindow: wx.Window, addonPath: str) -> bool: # noqa: C901 # currently installed according to the version number. "You are about to install version {newVersion} of {summary}," " which appears to be already installed. " - "Would you still like to update?" + "Would you still like to update?", ).format(summary=summary, newVersion=newVersion) updateAddonInstallationMessage = _( # Translators: A message asking if the user wishes to update a previously installed # add-on with this one. "A version of this add-on is already installed. " - "Would you like to update {summary} version {curVersion} to version {newVersion}?" + "Would you like to update {summary} version {curVersion} to version {newVersion}?", ).format(summary=summary, curVersion=curVersion, newVersion=newVersion) if gui.messageBox( overwriteExistingAddonInstallationMessage if curVersion == newVersion else updateAddonInstallationMessage, messageBoxTitle, - wx.YES|wx.NO|wx.ICON_WARNING + wx.YES|wx.NO|wx.ICON_WARNING, ) != wx.YES: return False @@ -213,7 +215,7 @@ def doneAndDestroy(window): # Translators: The title of the dialog presented while an Addon is being installed. _("Installing Add-on"), # Translators: The message displayed while an addon is being installed. - _("Please wait while the add-on is being installed.") + _("Please wait while the add-on is being installed."), ) try: @@ -234,7 +236,7 @@ def doneAndDestroy(window): _("Failed to install add-on from %s") % addonPath, # Translators: The title of a dialog presented when an error occurs. _("Error"), - wx.OK | wx.ICON_ERROR + wx.OK | wx.ICON_ERROR, ) finally: if addonObj is not None: @@ -250,7 +252,8 @@ def handleRemoteAddonInstall(addonPath: str): _("Add-ons cannot be installed in the Windows Store version of NVDA"), # Translators: The title of a dialog presented when an error occurs. _("Error"), - wx.OK | wx.ICON_ERROR) + wx.OK | wx.ICON_ERROR, + ) return gui.mainFrame.prePopup() if installAddon(gui.mainFrame, addonPath): @@ -260,7 +263,7 @@ def handleRemoteAddonInstall(addonPath: str): class IncompatibleAddonsDialog( DpiScalingHelperMixinWithoutInit, gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): """A dialog that lists incompatible addons, and why they are not compatible""" @classmethod @@ -283,7 +286,7 @@ def __init__( self, parent, APIVersion = addonAPIVersion.CURRENT, - APIBackwardsCompatToVersion = addonAPIVersion.BACK_COMPAT_TO + APIBackwardsCompatToVersion = addonAPIVersion.BACK_COMPAT_TO, ): if IncompatibleAddonsDialog._instance() is not None: raise RuntimeError("Attempting to open multiple IncompatibleAddonsDialog instances") @@ -292,10 +295,12 @@ def __init__( self._APIVersion = APIVersion self._APIBackwardsCompatToVersion = APIBackwardsCompatToVersion - self.unknownCompatibilityAddonsList = list(addonHandler.getIncompatibleAddons( - currentAPIVersion=APIVersion, - backCompatToAPIVersion=APIBackwardsCompatToVersion - )) + self.unknownCompatibilityAddonsList = list( + addonHandler.getIncompatibleAddons( + currentAPIVersion=APIVersion, + backCompatToAPIVersion=APIBackwardsCompatToVersion, + ), + ) if not len(self.unknownCompatibilityAddonsList) > 0: # this dialog is not designed to show an empty list. raise RuntimeError("No incompatible addons.") @@ -315,7 +320,7 @@ def __init__( # Translators: The title of the Incompatible Addons Dialog "The following add-ons are incompatible with NVDA version {}." " These add-ons can not be enabled." - " Please contact the add-on author for further assistance." + " Please contact the add-on author for further assistance.", ).format(addonAPIVersion.formatForGUI(self._APIVersion)) AddonSelectionIntroLabel=wx.StaticText(self, label=introText) AddonSelectionIntroLabel.Wrap(self.scaleSize(maxControlWidth)) @@ -348,7 +353,7 @@ def __init__( settingsSizer, border=guiHelper.BORDER_FOR_DIALOGS, flag=wx.ALL | wx.EXPAND, - proportion=1 + proportion=1, ) mainSizer.Fit(self) self.SetSizer(mainSizer) diff --git a/source/gui/addonStoreGui/controls/actions.py b/source/gui/addonStoreGui/controls/actions.py index 2a0b057591a..2fca22adeae 100644 --- a/source/gui/addonStoreGui/controls/actions.py +++ b/source/gui/addonStoreGui/controls/actions.py @@ -39,7 +39,7 @@ def _menuItemClicked(self, evt: wx.ContextMenuEvent, actionVM: AddonActionT): def popupContextMenuFromPosition( self, targetWindow: wx.Window, - position: wx.Position = wx.DefaultPosition + position: wx.Position = wx.DefaultPosition, ): self._populateContextMenu() targetWindow.PopupMenu(self._contextMenu, pos=position) @@ -64,7 +64,7 @@ def _populateContextMenu(self): self._actionMenuItemMap[action] = self._contextMenu.Insert( prevActionIndex, id=-1, - item=action.displayName + item=action.displayName, ) # Bind the menu item to the latest action VM @@ -121,7 +121,7 @@ def _updateSelectedAddons(self, selectedAddons: Iterable[AddonListItemVM]): def popupContextMenuFromPosition( self, targetWindow: wx.Window, - position: wx.Position = wx.DefaultPosition + position: wx.Position = wx.DefaultPosition, ): super().popupContextMenuFromPosition(targetWindow, position) if self._contextMenu.GetMenuItemCount() == 0: @@ -144,14 +144,14 @@ def _actions(self) -> List[BatchAddonActionVM]: self._storeVM._filteredStatusKey == _StatusFilterKey.AVAILABLE and AddonListValidator(aVMs).canUseInstallAction() ), - actionTarget=self._selectedAddons + actionTarget=self._selectedAddons, ), BatchAddonActionVM( # Translators: Label for an action that updates the selected add-ons displayName=pgettext("addonStore", "&Update selected add-ons"), actionHandler=self._storeVM.getAddons, validCheck=lambda aVMs: AddonListValidator(aVMs).canUseUpdateAction(), - actionTarget=self._selectedAddons + actionTarget=self._selectedAddons, ), BatchAddonActionVM( # Translators: Label for an action that removes the selected add-ons @@ -166,21 +166,21 @@ def _actions(self) -> List[BatchAddonActionVM]: ] and AddonListValidator(aVMs).canUseRemoveAction() ), - actionTarget=self._selectedAddons + actionTarget=self._selectedAddons, ), BatchAddonActionVM( # Translators: Label for an action that enables the selected add-ons displayName=pgettext("addonStore", "&Enable selected add-ons"), actionHandler=self._storeVM.enableAddons, validCheck=lambda aVMs: AddonListValidator(aVMs).canUseEnableAction(), - actionTarget=self._selectedAddons + actionTarget=self._selectedAddons, ), BatchAddonActionVM( # Translators: Label for an action that disables the selected add-ons displayName=pgettext("addonStore", "&Disable selected add-ons"), actionHandler=self._storeVM.disableAddons, validCheck=lambda aVMs: AddonListValidator(aVMs).canUseDisableAction(), - actionTarget=self._selectedAddons + actionTarget=self._selectedAddons, ), ] diff --git a/source/gui/addonStoreGui/controls/addonList.py b/source/gui/addonStoreGui/controls/addonList.py index b023fdb170a..db865dc665f 100644 --- a/source/gui/addonStoreGui/controls/addonList.py +++ b/source/gui/addonStoreGui/controls/addonList.py @@ -140,7 +140,7 @@ def OnItemDeselected(self, evt: wx.ListEvent): def OnGetItemText(self, itemIndex: int, colIndex: int) -> str: dataItem = self._addonsListVM.getAddonFieldText( itemIndex, - self._addonsListVM.presentedFields[colIndex] + self._addonsListVM.presentedFields[colIndex], ) if dataItem is None: # Failed to get dataItem, index may have been lost in refresh. diff --git a/source/gui/addonStoreGui/controls/details.py b/source/gui/addonStoreGui/controls/details.py index c194c6ab770..ca8e1fc2794 100644 --- a/source/gui/addonStoreGui/controls/details.py +++ b/source/gui/addonStoreGui/controls/details.py @@ -66,7 +66,7 @@ def __init__( wx.Panel.__init__( self, parent, - style=wx.TAB_TRAVERSAL | wx.BORDER_THEME + style=wx.TAB_TRAVERSAL | wx.BORDER_THEME, ) selfSizer = wx.BoxSizer(wx.VERTICAL) @@ -75,7 +75,7 @@ def __init__( self.addonNameCtrl = wx.StaticText( self, - style=wx.ALIGN_CENTRE_HORIZONTAL | wx.ST_NO_AUTORESIZE + style=wx.ALIGN_CENTRE_HORIZONTAL | wx.ST_NO_AUTORESIZE, ) self.updateAddonName(AddonDetails._noAddonSelectedLabelText) self._setAddonNameCtrlStyle() @@ -102,7 +102,7 @@ def __init__( # Instead, add a hidden label for the textBox, Windows exposes this as the accessible name. self.descriptionLabel = wx.StaticText( self.contentsPanel, - label=AddonDetails._descriptionLabelText + label=AddonDetails._descriptionLabelText, ) self.contents.Add(self.descriptionLabel, flag=wx.EXPAND) self.descriptionLabel.Hide() @@ -113,7 +113,7 @@ def __init__( | wx.TE_MULTILINE # details will require multiple lines | wx.TE_READONLY # the details shouldn't be user editable | wx.BORDER_NONE - ) + ), ) panelWidth = -1 # maximize width descriptionMinSize = wx.Size(self.scaleSize((panelWidth, 100))) @@ -129,7 +129,7 @@ def __init__( self.contents.Add(self.actionsButton) self.actionsButton.Bind( event=wx.EVT_BUTTON, - handler=lambda e: self._actionsContextMenu.popupContextMenuFromPosition(self, self.actionsButton.Position) + handler=lambda e: self._actionsContextMenu.popupContextMenuFromPosition(self, self.actionsButton.Position), ) self.contents.AddSpacer(guiHelper.SPACE_BETWEEN_VERTICAL_DIALOG_ITEMS) @@ -140,7 +140,7 @@ def __init__( self.contentsPanel, # Translators: Label for the text control containing extra details about the selected add-on. # In the add-on store dialog. - label=pgettext("addonStore", "&Other Details:") + label=pgettext("addonStore", "&Other Details:"), ) self.contents.Add(self.otherDetailsLabel, flag=wx.EXPAND) self.otherDetailsTextCtrl = wx.TextCtrl( @@ -153,7 +153,7 @@ def __init__( | wx.TE_RICH2 | wx.TE_NO_VSCROLL # No scroll by default. | wx.BORDER_NONE - ) + ), ) self._createRichTextStyles() self.contents.Add(self.otherDetailsTextCtrl, flag=wx.EXPAND, proportion=1) @@ -211,14 +211,16 @@ def _refresh(self): self.otherDetailsTextCtrl.SetValue("") if numSelectedAddons > 1: self.contentsPanel.Hide() - self.updateAddonName(npgettext( - "addonStore", - # Translators: Header (usually the add-on name) when multiple add-ons are selected. - # In the add-on store dialog. - "{num} add-on selected.", - "{num} add-ons selected.", - numSelectedAddons, - ).format(num=numSelectedAddons)) + self.updateAddonName( + npgettext( + "addonStore", + # Translators: Header (usually the add-on name) when multiple add-ons are selected. + # In the add-on store dialog. + "{num} add-on selected.", + "{num} add-ons selected.", + numSelectedAddons, + ).format(num=numSelectedAddons), + ) elif not details: self.contentsPanel.Hide() if self._detailsVM._listVM._isLoading: @@ -235,7 +237,7 @@ def _refresh(self): self.descriptionTextCtrl.SetStyle( 0, self.descriptionTextCtrl.GetLastPosition(), - self.defaultStyle + self.defaultStyle, ) if isinstance(details, _AddonStoreModel): @@ -243,20 +245,20 @@ def _refresh(self): self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Publisher:"), - details.publisher + details.publisher, ) if isinstance(details, _AddonManifestModel): # Author comes from the manifest, and is only available for installed add-ons. self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Author:"), - details.author + details.author, ) self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "ID:"), - details.addonId + details.addonId, ) currentStatusKey = self._actionsContextMenu._storeVM._filteredStatusKey @@ -264,31 +266,31 @@ def _refresh(self): self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Installed version:"), - details._addonHandlerModel.version + details._addonHandlerModel.version, ) self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Minimum NVDA version:"), - formatVersionForGUI(*details.minimumNVDAVersion) + formatVersionForGUI(*details.minimumNVDAVersion), ) self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Last tested NVDA version:"), - formatVersionForGUI(*details.lastTestedNVDAVersion) + formatVersionForGUI(*details.lastTestedNVDAVersion), ) if currentStatusKey not in AddonListField.availableAddonVersionName.hideStatuses: self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Available version:"), - details.addonVersionName + details.addonVersionName, ) self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Channel:"), - details.channel.displayString + details.channel.displayString, ) incompatibleReason = details.getIncompatibleReason() @@ -296,7 +298,7 @@ def _refresh(self): self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Incompatible Reason:"), - incompatibleReason + incompatibleReason, ) # Links and license info @@ -304,39 +306,39 @@ def _refresh(self): self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Homepage:"), - details.homepage + details.homepage, ) if isinstance(details, _AddonStoreModel): self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "License:"), - details.license + details.license, ) if details.licenseURL is not None: self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "License URL:"), - details.licenseURL + details.licenseURL, ) self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Download URL:"), - details.URL + details.URL, ) self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Source URL:"), - details.sourceURL + details.sourceURL, ) if details.reviewURL is not None: self._appendDetailsLabelValue( # Translators: Label for an extra detail field for the selected add-on. In the add-on store dialog. pgettext("addonStore", "Reviews URL:"), - details.reviewURL + details.reviewURL, ) self.contentsPanel.Show() diff --git a/source/gui/addonStoreGui/controls/messageDialogs.py b/source/gui/addonStoreGui/controls/messageDialogs.py index ca30adcd72e..f160d44cee2 100644 --- a/source/gui/addonStoreGui/controls/messageDialogs.py +++ b/source/gui/addonStoreGui/controls/messageDialogs.py @@ -50,7 +50,7 @@ def _addButtons(self, buttonHelper: ButtonHelper) -> None: self, # Translators: A button in the addon installation warning / blocked dialog which shows # more information about the addon - label=pgettext("addonStore", "&About add-on...") + label=pgettext("addonStore", "&About add-on..."), ) addonInfoButton.Bind(wx.EVT_BUTTON, lambda evt: self._showAddonInfoFunction()) @@ -58,7 +58,7 @@ def _addButtons(self, buttonHelper: ButtonHelper) -> None: self, id=wx.ID_YES, # Translators: A button in the addon installation blocked dialog which will confirm the available action. - label=pgettext("addonStore", "&Yes") + label=pgettext("addonStore", "&Yes"), ) yesButton.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.YES)) @@ -66,7 +66,7 @@ def _addButtons(self, buttonHelper: ButtonHelper) -> None: self, id=wx.ID_NO, # Translators: A button in the addon installation blocked dialog which will dismiss the dialog. - label=pgettext("addonStore", "&No") + label=pgettext("addonStore", "&No"), ) noButton.SetDefault() noButton.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.NO)) @@ -102,13 +102,13 @@ def _shouldProceedWhenInstalledAddonVersionUnknown( "The installed add-on version cannot be compared with the add-on store version. " "Installed version: {oldVersion}. " "Available version: {version}.\n" - "Proceed with installation anyway? " - ).format( + "Proceed with installation anyway? ", + ).format( name=addon.displayName, version=addon.addonVersionName, oldVersion=addon._addonHandlerModel.version, lastTestedNVDAVersion=addonAPIVersion.formatForGUI(addon.lastTestedNVDAVersion), - NVDAVersion=addonAPIVersion.formatForGUI(addonAPIVersion.CURRENT) + NVDAVersion=addonAPIVersion.formatForGUI(addonAPIVersion.CURRENT), ) dlg = ErrorAddonInstallDialogWithYesNoButtons( parent=parent, @@ -132,7 +132,7 @@ def _shouldProceedToRemoveAddonDialog( # Translators: Presented when attempting to remove the selected add-on. # {addon} is replaced with the add-on name. "Are you sure you wish to remove the {addon} add-on from NVDA? " - "This cannot be undone." + "This cannot be undone.", ).format(addon=addon.displayName) dlg = ErrorAddonInstallDialogWithYesNoButtons( parent=parent, @@ -160,12 +160,12 @@ def _shouldInstallWhenAddonTooOldDialog( "The last tested NVDA version for this add-on is {lastTestedNVDAVersion}, " "your current NVDA version is {NVDAVersion}. " "Installation may cause unstable behavior in NVDA.\n" - "Proceed with installation anyway? " - ).format( + "Proceed with installation anyway? ", + ).format( name=addon.displayName, version=addon.addonVersionName, lastTestedNVDAVersion=addonAPIVersion.formatForGUI(addon.lastTestedNVDAVersion), - NVDAVersion=addonAPIVersion.formatForGUI(addonAPIVersion.CURRENT) + NVDAVersion=addonAPIVersion.formatForGUI(addonAPIVersion.CURRENT), ) dlg = ErrorAddonInstallDialogWithYesNoButtons( parent=parent, @@ -193,12 +193,12 @@ def _shouldEnableWhenAddonTooOldDialog( "The last tested NVDA version for this add-on is {lastTestedNVDAVersion}, " "your current NVDA version is {NVDAVersion}. " "Enabling may cause unstable behavior in NVDA.\n" - "Proceed with enabling anyway? " - ).format( + "Proceed with enabling anyway? ", + ).format( name=addon.displayName, version=addon.addonVersionName, lastTestedNVDAVersion=addonAPIVersion.formatForGUI(addon.lastTestedNVDAVersion), - NVDAVersion=addonAPIVersion.formatForGUI(addonAPIVersion.CURRENT) + NVDAVersion=addonAPIVersion.formatForGUI(addonAPIVersion.CURRENT), ) dlg = ErrorAddonInstallDialogWithYesNoButtons( parent=parent, @@ -214,49 +214,53 @@ def _shouldEnableWhenAddonTooOldDialog( def _showAddonRequiresNVDAUpdateDialog( parent: wx.Window, - addon: _AddonGUIModel + addon: _AddonGUIModel, ) -> None: incompatibleMessage = _( # Translators: The message displayed when installing an add-on package is prohibited, # because it requires a later version of NVDA than is currently installed. "Installation of {summary} {version} has been blocked. The minimum NVDA version required for " - "this add-on is {minimumNVDAVersion}, your current NVDA version is {NVDAVersion}" - ).format( + "this add-on is {minimumNVDAVersion}, your current NVDA version is {NVDAVersion}", + ).format( summary=addon.displayName, version=addon.addonVersionName, minimumNVDAVersion=addonAPIVersion.formatForGUI(addon.minimumNVDAVersion), - NVDAVersion=addonAPIVersion.formatForGUI(addonAPIVersion.CURRENT) + NVDAVersion=addonAPIVersion.formatForGUI(addonAPIVersion.CURRENT), ) - displayDialogAsModal(ErrorAddonInstallDialog( - parent=parent, - # Translators: The title of a dialog presented when an error occurs. - title=pgettext("addonStore", "Add-on installation failure"), - message=incompatibleMessage, - showAddonInfoFunction=lambda: _showAddonInfo(addon) - )) + displayDialogAsModal( + ErrorAddonInstallDialog( + parent=parent, + # Translators: The title of a dialog presented when an error occurs. + title=pgettext("addonStore", "Add-on installation failure"), + message=incompatibleMessage, + showAddonInfoFunction=lambda: _showAddonInfo(addon), + ), + ) def _showConfirmAddonInstallDialog( parent: wx.Window, - addon: _AddonGUIModel + addon: _AddonGUIModel, ) -> int: confirmInstallMessage = _( # Translators: A message asking the user if they really wish to install an addon. "Are you sure you want to install this add-on?\n" "Only install add-ons from trusted sources.\n" - "Addon: {summary} {version}" - ).format( + "Addon: {summary} {version}", + ).format( summary=addon.displayName, version=addon.addonVersionName, - ) + ) - return displayDialogAsModal(ConfirmAddonInstallDialog( - parent=parent, - # Translators: Title for message asking if the user really wishes to install an Addon. - title=pgettext("addonStore", "Add-on Installation"), - message=confirmInstallMessage, - showAddonInfoFunction=lambda: _showAddonInfo(addon) - )) + return displayDialogAsModal( + ConfirmAddonInstallDialog( + parent=parent, + # Translators: Title for message asking if the user really wishes to install an Addon. + title=pgettext("addonStore", "Add-on Installation"), + message=confirmInstallMessage, + showAddonInfoFunction=lambda: _showAddonInfo(addon), + ), + ) @@ -267,13 +271,13 @@ def _showAddonInfo(addon: _AddonGUIModel) -> None: # Translators: message shown in the Addon Information dialog. "{summary} ({name})\n" "Version: {version}\n" - "Description: {description}\n" - ).format( + "Description: {description}\n", + ).format( summary=addon.displayName, name=addon.addonId, version=addon.addonVersionName, description=addon.description, - ) + ), ] if isinstance(addon, _AddonStoreModel): # Translators: the publisher part of the About Add-on information @@ -287,12 +291,12 @@ def _showAddonInfo(addon: _AddonGUIModel) -> None: minimumNVDAVersion = addonAPIVersion.formatForGUI(addon.minimumNVDAVersion) message.append( # Translators: the minimum NVDA version part of the About Add-on information - pgettext("addonStore", "Minimum required NVDA version: {}\n").format(minimumNVDAVersion) + pgettext("addonStore", "Minimum required NVDA version: {}\n").format(minimumNVDAVersion), ) lastTestedNVDAVersion = addonAPIVersion.formatForGUI(addon.lastTestedNVDAVersion) message.append( # Translators: the last NVDA version tested part of the About Add-on information - pgettext("addonStore", "Last NVDA version tested: {}\n").format(lastTestedNVDAVersion) + pgettext("addonStore", "Last NVDA version tested: {}\n").format(lastTestedNVDAVersion), ) # Translators: title for the Addon Information dialog title = pgettext("addonStore", "Add-on Information") @@ -301,7 +305,7 @@ def _showAddonInfo(addon: _AddonGUIModel) -> None: class _SafetyWarningDialog( ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): """A dialog warning the user about the risks of installing add-ons.""" @@ -319,7 +323,7 @@ def __init__(self, parent: wx.Window): "Add-ons are created by the NVDA community and are not vetted by NV Access. " "NV Access cannot be held responsible for add-on behavior. " "The functionality of add-ons is unrestricted and can include " - "accessing your personal data or even the entire system. " + "accessing your personal data or even the entire system. ", ) sText = sHelper.addItem(wx.StaticText(self, label=_warningText)) @@ -327,7 +331,7 @@ def __init__(self, parent: wx.Window): self.scaleFactor = windowUtils.getWindowScalingFactor(self.GetHandle()) sText.Wrap( # 600 was fairly arbitrarily chosen by a visual user to look acceptable on their machine. - self.scaleFactor * 600 + self.scaleFactor * 600, ) sHelper.sizer.AddSpacer(SPACE_BETWEEN_VERTICAL_DIALOG_ITEMS) @@ -338,7 +342,7 @@ def __init__(self, parent: wx.Window): label=pgettext( "addonStore", # Translators: The label of a checkbox in the add-on store warning dialog - "&Don't show this message again" + "&Don't show this message again", ), ), ) @@ -361,7 +365,7 @@ def onOkButton(self, evt: wx.CommandEvent): class UpdatableAddonsDialog( ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): """A dialog notifying users that updatable add-ons are available""" @@ -398,7 +402,7 @@ def _setupMessage(self, sHelper: BoxSizerHelper): _message = pgettext( "addonStore", # Translators: Message displayed when updates are available for some installed add-ons. - "Updates are available for some of your installed add-ons. " + "Updates are available for some of your installed add-ons. ", ) sText = sHelper.addItem(wx.StaticText(self, label=_message)) @@ -505,7 +509,7 @@ def onClose(self, evt: wx.CloseEvent): numInProgress, ).format(numInProgress), AddonStoreDialog._installationPromptTitle, - style=wx.YES_NO + style=wx.YES_NO, ) if res == wx.YES: log.debug("Cancelling the download.") @@ -527,7 +531,7 @@ def onClose(self, evt: wx.CloseEvent): "Installing {} add-on, please wait.", "Installing {} add-ons, please wait.", nAddonsPendingInstall, - ).format(nAddonsPendingInstall) + ).format(nAddonsPendingInstall), ) AddonStoreVM.installPending() diff --git a/source/gui/addonStoreGui/controls/storeDialog.py b/source/gui/addonStoreGui/controls/storeDialog.py index 9238e514845..d78a51d711a 100644 --- a/source/gui/addonStoreGui/controls/storeDialog.py +++ b/source/gui/addonStoreGui/controls/storeDialog.py @@ -100,7 +100,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer): self.listLabel = wx.StaticText(self) tabPageHelper.addItem( self.listLabel, - flag=wx.EXPAND + flag=wx.EXPAND, ) self._setListLabels() @@ -155,34 +155,40 @@ def _createFilterControls(self, filterCtrlHelper: guiHelper.BoxSizerHelper) -> N filterCtrlsLine1.sizer.AddSpacer(FILTER_MARGIN_PADDING) filterCtrlHelper.addItem(filterCtrlsLine1.sizer, flag=wx.EXPAND, proportion=1) - self.channelFilterCtrl = cast(wx.Choice, filterCtrlsLine0.addLabeledControl( - # Translators: The label of a selection field to filter the list of add-ons in the add-on store dialog. - labelText=pgettext("addonStore", "Cha&nnel:"), - wxCtrlClass=wx.Choice, - choices=list(c.displayString for c in _channelFilters), - )) + self.channelFilterCtrl = cast( + wx.Choice, filterCtrlsLine0.addLabeledControl( + # Translators: The label of a selection field to filter the list of add-ons in the add-on store dialog. + labelText=pgettext("addonStore", "Cha&nnel:"), + wxCtrlClass=wx.Choice, + choices=list(c.displayString for c in _channelFilters), + ), + ) self.channelFilterCtrl.Bind(wx.EVT_CHOICE, self.onChannelFilterChange, self.channelFilterCtrl) self.bindHelpEvent("AddonStoreFilterChannel", self.channelFilterCtrl) # Translators: The label of a checkbox to filter the list of add-ons in the add-on store dialog. incompatibleAddonsLabel = pgettext("addonStore", "Include &incompatible add-ons") - self.includeIncompatibleCtrl = cast(wx.CheckBox, filterCtrlsLine0.addItem( - wx.CheckBox(self, label=incompatibleAddonsLabel) - )) + self.includeIncompatibleCtrl = cast( + wx.CheckBox, filterCtrlsLine0.addItem( + wx.CheckBox(self, label=incompatibleAddonsLabel), + ), + ) self.includeIncompatibleCtrl.SetValue(0) self.includeIncompatibleCtrl.Bind( wx.EVT_CHECKBOX, self.onIncompatibleFilterChange, - self.includeIncompatibleCtrl + self.includeIncompatibleCtrl, ) self.bindHelpEvent("AddonStoreFilterIncompatible", self.includeIncompatibleCtrl) - self.enabledFilterCtrl = cast(wx.Choice, filterCtrlsLine0.addLabeledControl( - # Translators: The label of a selection field to filter the list of add-ons in the add-on store dialog. - labelText=pgettext("addonStore", "Ena&bled/disabled:"), - wxCtrlClass=wx.Choice, - choices=list(c.displayString for c in EnabledStatus), - )) + self.enabledFilterCtrl = cast( + wx.Choice, filterCtrlsLine0.addLabeledControl( + # Translators: The label of a selection field to filter the list of add-ons in the add-on store dialog. + labelText=pgettext("addonStore", "Ena&bled/disabled:"), + wxCtrlClass=wx.Choice, + choices=list(c.displayString for c in EnabledStatus), + ), + ) self.enabledFilterCtrl.Bind(wx.EVT_CHOICE, self.onEnabledFilterChange, self.enabledFilterCtrl) self.bindHelpEvent("AddonStoreFilterEnabled", self.enabledFilterCtrl) @@ -228,7 +234,7 @@ def onClose(self, evt: wx.CommandEvent): numInProgress, ).format(numInProgress), self._installationPromptTitle, - style=wx.YES_NO + style=wx.YES_NO, ) if res == wx.YES: log.debug("Cancelling the download.") @@ -250,7 +256,7 @@ def onClose(self, evt: wx.CommandEvent): "Installing {} add-on, please wait.", "Installing {} add-ons, please wait.", nAddonsPendingInstall, - ).format(nAddonsPendingInstall) + ).format(nAddonsPendingInstall), ) self._storeVM.installPending() @@ -274,7 +280,7 @@ def _requiresRestart(self) -> bool: log.debug( "Add-ons pending install, restart required.\n" f"Downloads pending install (add-on store installs): {addonDataManager._downloadsPendingInstall}.\n" - f"Addons pending install (external installs): {state[AddonStateCategory.PENDING_INSTALL]}.\n" + f"Addons pending install (external installs): {state[AddonStateCategory.PENDING_INSTALL]}.\n", ) return True diff --git a/source/gui/addonStoreGui/viewModels/action.py b/source/gui/addonStoreGui/viewModels/action.py index 339ae3c9a5e..999667b6a1f 100644 --- a/source/gui/addonStoreGui/viewModels/action.py +++ b/source/gui/addonStoreGui/viewModels/action.py @@ -27,8 +27,8 @@ class _AddonAction(Generic[ActionTargetT], ABC): def __init__( self, displayName: str, - actionHandler: Callable[[ActionTargetT, ], None], - validCheck: Callable[[ActionTargetT, ], bool], + actionHandler: Callable[[ActionTargetT], None], + validCheck: Callable[[ActionTargetT], bool], actionTarget: ActionTargetT, ): """ @@ -74,8 +74,8 @@ class AddonActionVM(_AddonAction[Optional["AddonListItemVM"]]): def __init__( self, displayName: str, - actionHandler: Callable[["AddonListItemVM", ], None], - validCheck: Callable[["AddonListItemVM", ], bool], + actionHandler: Callable[["AddonListItemVM"], None], + validCheck: Callable[["AddonListItemVM"], bool], actionTarget: Optional["AddonListItemVM"], ): """ @@ -129,8 +129,8 @@ class BatchAddonActionVM(_AddonAction[Iterable["AddonListItemVM"]]): def __init__( self, displayName: str, - actionHandler: Callable[[Iterable["AddonListItemVM"], ], None], - validCheck: Callable[[Iterable["AddonListItemVM"], ], bool], + actionHandler: Callable[[Iterable["AddonListItemVM"]], None], + validCheck: Callable[[Iterable["AddonListItemVM"]], bool], actionTarget: Iterable["AddonListItemVM"], ): """ diff --git a/source/gui/addonStoreGui/viewModels/addonList.py b/source/gui/addonStoreGui/viewModels/addonList.py index ec0f5a50550..b52c1745894 100644 --- a/source/gui/addonStoreGui/viewModels/addonList.py +++ b/source/gui/addonStoreGui/viewModels/addonList.py @@ -59,7 +59,7 @@ class AddonListField(_AddonListFieldData, Enum): # Translators: The name of the column that contains the status of the addon. # e.g. available, downloading installing pgettext("addonStore", "Status"), - 150 + 150, ) currentAddonVersionName = ( # Translators: The name of the column that contains the installed addon's version string. @@ -82,13 +82,13 @@ class AddonListField(_AddonListFieldData, Enum): # Translators: The name of the column that contains the addon's publisher. pgettext("addonStore", "Publisher"), 100, - frozenset({_StatusFilterKey.INCOMPATIBLE, _StatusFilterKey.INSTALLED}) + frozenset({_StatusFilterKey.INCOMPATIBLE, _StatusFilterKey.INSTALLED}), ) author = ( # Translators: The name of the column that contains the addon's author. pgettext("addonStore", "Author"), 100, - frozenset({_StatusFilterKey.AVAILABLE, _StatusFilterKey.UPDATE}) + frozenset({_StatusFilterKey.AVAILABLE, _StatusFilterKey.UPDATE}), ) @@ -99,7 +99,7 @@ class AddonListItemVM(Generic[_AddonModelT]): def __init__( self, model: _AddonModelT, - status: AvailableAddonStatus = AvailableAddonStatus.AVAILABLE + status: AvailableAddonStatus = AvailableAddonStatus.AVAILABLE, ): self._model: _AddonModelT = model # read-only self._status: AvailableAddonStatus = status # modifications triggers L{updated.notify} @@ -212,7 +212,7 @@ def __init__( self._validate( sortField=self._sortByModelField, selectionIndex=self.getSelectedIndex(), - selectionId=self.selectedAddonId + selectionId=self.selectedAddonId, ) self.selectedAddonId = self._tryPersistSelection(self._addonsFilteredOrdered) self.resetListItems(addons) @@ -392,7 +392,7 @@ def _tryPersistSelection( f"oldSelectedIndex: {selectedIndex}, " f"oldMaxIndex: {oldMaxIndex}, " f"newSelectedIndex: {newSelectedIndex}, " - f"newMaxIndex: {newMaxIndex}" + f"newMaxIndex: {newMaxIndex}", ) return newOrder[newSelectedIndex] elif self.lastSelectedAddonId in newOrder: diff --git a/source/gui/addonStoreGui/viewModels/store.py b/source/gui/addonStoreGui/viewModels/store.py index 33f015b1ed2..3532311f450 100644 --- a/source/gui/addonStoreGui/viewModels/store.py +++ b/source/gui/addonStoreGui/viewModels/store.py @@ -97,7 +97,7 @@ def __init__(self): storeVM=self, ) self.detailsVM: AddonDetailsVM = AddonDetailsVM( - listVM=self.listVM + listVM=self.listVM, ) self.actionVMList = self._makeActionsList() self.listVM.selectionChanged.register(self._onSelectedItemChanged) @@ -117,28 +117,28 @@ def _makeActionsList(self): displayName=pgettext("addonStore", "&Install"), actionHandler=self.getAddon, validCheck=lambda aVM: aVM.canUseInstallAction(), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that installs the selected addon displayName=pgettext("addonStore", "&Install (override incompatibility)"), actionHandler=self.installOverrideIncompatibilityForAddon, validCheck=lambda aVM: aVM.canUseInstallOverrideIncompatibilityAction(), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that updates the selected addon displayName=pgettext("addonStore", "&Update"), actionHandler=self.getAddon, validCheck=lambda aVM: aVM.canUseUpdateAction(), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that installs the selected addon displayName=pgettext("addonStore", "&Update (override incompatibility)"), actionHandler=self.installOverrideIncompatibilityForAddon, validCheck=lambda aVM: aVM.canUseUpdateOverrideIncompatibilityAction(), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that replaces the selected addon with @@ -146,28 +146,28 @@ def _makeActionsList(self): displayName=pgettext("addonStore", "Re&place"), actionHandler=self.replaceAddon, validCheck=lambda aVM: aVM.canUseReplaceAction(), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that disables the selected addon displayName=pgettext("addonStore", "&Disable"), actionHandler=self.disableAddon, validCheck=lambda aVM: aVM.canUseDisableAction(), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that enables the selected addon displayName=pgettext("addonStore", "&Enable"), actionHandler=self.enableAddon, validCheck=lambda aVM: aVM.canUseEnableAction(), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that enables the selected addon displayName=pgettext("addonStore", "&Enable (override incompatibility)"), actionHandler=self.enableOverrideIncompatibilityForAddon, validCheck=lambda aVM: aVM.canUseEnableOverrideIncompatibilityAction(), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that removes the selected addon @@ -182,7 +182,7 @@ def _makeActionsList(self): _StatusFilterKey.INCOMPATIBLE, ) ), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that opens help for the selected addon @@ -199,14 +199,14 @@ def _makeActionsList(self): and aVM.model._addonHandlerModel is not None and aVM.model._addonHandlerModel.getDocFilePath() is not None ), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that opens the homepage for the selected addon displayName=pgettext("addonStore", "Ho&mepage"), actionHandler=lambda aVM: startfile(aVM.model.homepage), validCheck=lambda aVM: aVM.model.homepage is not None, - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that opens the license for the selected addon @@ -214,21 +214,21 @@ def _makeActionsList(self): actionHandler=lambda aVM: startfile( cast( str, - cast(_AddonStoreModel, aVM.model).licenseURL - ) + cast(_AddonStoreModel, aVM.model).licenseURL, + ), ), validCheck=lambda aVM: ( isinstance(aVM.model, _AddonStoreModel) and aVM.model.licenseURL is not None ), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that opens the source code for the selected addon displayName=pgettext("addonStore", "Source &Code"), actionHandler=lambda aVM: startfile(cast(_AddonStoreModel, aVM.model).sourceURL), validCheck=lambda aVM: isinstance(aVM.model, _AddonStoreModel), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), AddonActionVM( # Translators: Label for an action that opens the webpage to see and send feedback for the selected add-on @@ -236,14 +236,14 @@ def _makeActionsList(self): actionHandler=lambda aVM: startfile( cast( str, - cast(_AddonStoreModel, aVM.model).reviewURL - ) + cast(_AddonStoreModel, aVM.model).reviewURL, + ), ), validCheck=lambda aVM: ( isinstance(aVM.model, _AddonStoreModel) and aVM.model.reviewURL is not None ), - actionTarget=selectedListItem + actionTarget=selectedListItem, ), ] @@ -292,7 +292,7 @@ def removeAddons(self, listItemVMs: Iterable[AddonListItemVM[_AddonStoreModel]]) else: log.debug( f"Skipping {aVM.Id} as removal has been previously declined for all remaining" - " add-ons." + " add-ons.", ) else: shouldRemove, shouldRememberChoice = self.removeAddon( @@ -327,14 +327,14 @@ def installOverrideIncompatibilityForAddon( "addonStore", # Translators: The message displayed when the add-on cannot be enabled. # {addon} is replaced with the add-on name. - "Could not enable the add-on: {addon}." + "Could not enable the add-on: {addon}.", ) _disableErrorMessage: str = pgettext( "addonStore", # Translators: The message displayed when the add-on cannot be disabled. # {addon} is replaced with the add-on name. - "Could not disable the add-on: {addon}." + "Could not disable the add-on: {addon}.", ) def _handleEnableDisable(self, listItemVM: AddonListItemVM[_AddonManifestModel], shouldEnable: bool) -> None: @@ -347,7 +347,7 @@ def _handleEnableDisable(self, listItemVM: AddonListItemVM[_AddonManifestModel], errorMessage = self._disableErrorMessage log.debug(errorMessage, exc_info=True) displayableError = DisplayableError( - displayMessage=errorMessage.format(addon=listItemVM.model.displayName) + displayMessage=errorMessage.format(addon=listItemVM.model.displayName), ) # ensure calling on the main thread. core.callLater(delay=0, callable=self.onDisplayableError.notify, displayableError=displayableError) @@ -391,7 +391,7 @@ def enableAddons(self, listItemVMs: Iterable[AddonListItemVM[_AddonStoreModel]]) else: log.debug( f"Skipping {aVM.Id} as override incompatibility has been previously declined for all remaining" - " add-ons." + " add-ons.", ) else: shouldEnableIncompatible, shouldRememberChoice = self.enableOverrideIncompatibilityForAddon( @@ -448,7 +448,7 @@ def replaceAddons(self, listItemVMs: Iterable[AddonListItemVM[_AddonStoreModel]] self.replaceAddon(aVM, askConfirmation=False) else: log.debug( - f"Skipping {aVM.Id} as replacement has been previously declined for all remaining add-ons." + f"Skipping {aVM.Id} as replacement has been previously declined for all remaining add-ons.", ) else: shouldReplace, shouldRememberChoice = self.replaceAddon( @@ -480,7 +480,7 @@ def getAddons(cls, listItemVMs: Iterable[AddonListItemVM[_AddonStoreModel]]) -> cls.replaceAddon(aVM, askConfirmation=False) else: log.debug( - f"Skipping {aVM.Id} as replacement has been previously declined for all remaining add-ons." + f"Skipping {aVM.Id} as replacement has been previously declined for all remaining add-ons.", ) else: shouldReplace, shouldRememberReplaceChoice = cls.replaceAddon( @@ -495,13 +495,13 @@ def getAddons(cls, listItemVMs: Iterable[AddonListItemVM[_AddonStoreModel]]) -> else: log.debug( f"Skipping {aVM.Id} as override incompatibility has been previously declined for all remaining" - " add-ons." + " add-ons.", ) else: shouldInstallIncompatible, shouldRememberInstallChoice = cls.installOverrideIncompatibilityForAddon( aVM, askConfirmation=True, - useRememberChoiceCheckbox=True + useRememberChoiceCheckbox=True, ) else: log.debug(f"Skipping {aVM.Id} ({aVM.status}) as it is not available or updatable") @@ -510,7 +510,7 @@ def getAddons(cls, listItemVMs: Iterable[AddonListItemVM[_AddonStoreModel]]) -> def _downloadComplete( cls, listItemVM: AddonListItemVM[_AddonStoreModel], - fileDownloaded: Optional[PathLike] + fileDownloaded: Optional[PathLike], ): try: addonDataManager._downloadsPendingCompletion.remove(listItemVM) diff --git a/source/gui/configProfiles.py b/source/gui/configProfiles.py index 3b214438e79..338b0c05786 100644 --- a/source/gui/configProfiles.py +++ b/source/gui/configProfiles.py @@ -15,7 +15,7 @@ class ProfilesDialog( gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): shouldSuspendConfigProfileTriggers = True helpId = "ConfigurationProfiles" @@ -49,7 +49,7 @@ def __init__(self, parent): changeProfilesSizer = wx.BoxSizer(wx.VERTICAL) item = self.profileList = wx.ListBox( profilesListBox, - choices=[self.getProfileDisplay(name, includeStates=True) for name in self.profileNames] + choices=[self.getProfileDisplay(name, includeStates=True) for name in self.profileNames], ) self.bindHelpEvent("ProfilesBasicManagement", self.profileList) item.Bind(wx.EVT_LISTBOX, self.onProfileListChoice) @@ -172,8 +172,10 @@ def onChangeState(self, evt): except: # noqa: E722 log.debugWarning("", exc_info=True) # Translators: An error displayed when activating a configuration profile fails. - gui.messageBox(_("Error activating profile."), - _("Error"), wx.OK | wx.ICON_ERROR, self) + gui.messageBox( + _("Error activating profile."), + _("Error"), wx.OK | wx.ICON_ERROR, self, + ) return self.Close() @@ -190,7 +192,7 @@ def onDelete(self, evt): _("The profile {} will be permanently deleted. This action cannot be undone.").format(name), # Translators: The title of the confirmation dialog for deletion of a configuration profile. _("Confirm Deletion"), - wx.OK | wx.CANCEL | wx.CANCEL_DEFAULT | wx.ICON_QUESTION, self + wx.OK | wx.CANCEL | wx.CANCEL_DEFAULT | wx.ICON_QUESTION, self, ) != wx.OK: return try: @@ -198,8 +200,10 @@ def onDelete(self, evt): except: # noqa: E722 log.debugWarning("", exc_info=True) # Translators: An error displayed when deleting a configuration profile fails. - gui.messageBox(_("Error deleting profile."), - _("Error"), wx.OK | wx.ICON_ERROR, self) + gui.messageBox( + _("Error deleting profile."), + _("Error"), wx.OK | wx.ICON_ERROR, self, + ) return del self.profileNames[index] self.profileList.Delete(index) @@ -237,7 +241,7 @@ def onRename(self, evt): _("New name:"), # Translators: The title of the dialog to rename a configuration profile. caption=_("Rename Profile"), - value=oldName + value=oldName, ) as d: if d.ShowModal() == wx.ID_CANCEL: return @@ -251,7 +255,7 @@ def onRename(self, evt): # Translators: The title of an error message dialog. caption=_("Error"), style=wx.ICON_ERROR, - parent=self + parent=self, ) newName = api.filterFileName(newName) try: @@ -259,13 +263,17 @@ def onRename(self, evt): except ValueError: # Translators: An error displayed when renaming a configuration profile # and a profile with the new name already exists. - gui.messageBox(_("That profile already exists. Please choose a different name."), - _("Error"), wx.OK | wx.ICON_ERROR, self) + gui.messageBox( + _("That profile already exists. Please choose a different name."), + _("Error"), wx.OK | wx.ICON_ERROR, self, + ) return except: # noqa: E722 log.debugWarning("", exc_info=True) - gui.messageBox(_("Error renaming profile."), - _("Error"), wx.OK | wx.ICON_ERROR, self) + gui.messageBox( + _("Error renaming profile."), + _("Error"), wx.OK | wx.ICON_ERROR, self, + ) return self.profileNames[index] = newName self.profileList.SetString(index, self.getProfileDisplay(newName, includeStates=True)) @@ -278,11 +286,13 @@ def onTriggers(self, evt): def getSimpleTriggers(self): # Yields (spec, display, manualEdit) - yield ("app:%s" % self.currentAppName, - # Translators: Displayed for the configuration profile trigger for the current application. - # %s is replaced by the application executable name. - _("Current application (%s)") % self.currentAppName, - False) + yield ( + "app:%s" % self.currentAppName, + # Translators: Displayed for the configuration profile trigger for the current application. + # %s is replaced by the application executable name. + _("Current application (%s)") % self.currentAppName, + False, + ) # Translators: Displayed for the configuration profile trigger for say all. yield "sayAll", _("Say all"), True @@ -301,8 +311,10 @@ def saveTriggers(self, parentWindow=None): except: # noqa: E722 log.debugWarning("", exc_info=True) # Translators: An error displayed when saving configuration profile triggers fails. - gui.messageBox(_("Error saving configuration profile triggers - probably read only file system."), - _("Error"), wx.OK | wx.ICON_ERROR, parent=parentWindow) + gui.messageBox( + _("Error saving configuration profile triggers - probably read only file system."), + _("Error"), wx.OK | wx.ICON_ERROR, parent=parentWindow, + ) class TriggerInfo(object): __slots__ = ("spec", "display", "profile") @@ -315,7 +327,7 @@ def __init__(self, spec, display, profile): class TriggersDialog( gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): helpId = "ConfigProfileTriggers" @@ -379,8 +391,10 @@ def onTriggerListChoice(self, evt): try: self.profileList.Selection = self.Parent.profileNames.index(trig.profile) except ValueError: - log.error("Trigger %s: invalid profile %s" - % (trig.spec, trig.profile)) + log.error( + "Trigger %s: invalid profile %s" + % (trig.spec, trig.profile), + ) self.profileList.Selection = 0 trig.profile = None @@ -406,7 +420,7 @@ def onClose(self, evt): class NewProfileDialog( gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): helpId = "ProfilesCreating" @@ -425,8 +439,12 @@ def __init__(self, parent): # in the new configuration profile dialog. self.triggers = triggers = [(None, _("Manual activation"), True)] triggers.extend(parent.getSimpleTriggers()) - self.triggerChoice = sHelper.addItem(wx.RadioBox(self, label=_("Use this profile for:"), - choices=[trig[1] for trig in triggers])) + self.triggerChoice = sHelper.addItem( + wx.RadioBox( + self, label=_("Use this profile for:"), + choices=[trig[1] for trig in triggers], + ), + ) self.triggerChoice.Bind(wx.EVT_RADIOBOX, self.onTriggerChoice) self.autoProfileName = "" self.onTriggerChoice(None) @@ -449,10 +467,12 @@ def onOk(self, evt): if spec in confTrigs and gui.messageBox( # Translators: The confirmation prompt presented when creating a new configuration profile # and the selected trigger is already associated. - _("This trigger is already associated with another profile. " - "If you continue, it will be removed from that profile and associated with this one.\n" - "Are you sure you want to continue?"), - _("Warning"), wx.ICON_WARNING | wx.YES | wx.NO, self + _( + "This trigger is already associated with another profile. " + "If you continue, it will be removed from that profile and associated with this one.\n" + "Are you sure you want to continue?", + ), + _("Warning"), wx.ICON_WARNING | wx.YES | wx.NO, self, ) == wx.NO: return @@ -465,7 +485,7 @@ def onOk(self, evt): # Translators: The title of an error message dialog. caption=_("Error"), style=wx.ICON_ERROR, - parent=self + parent=self, ) self.profileName.SetFocus() return @@ -474,14 +494,18 @@ def onOk(self, evt): config.conf.createProfile(name) except ValueError: # Translators: An error displayed when the user attempts to create a configuration profile which already exists. - gui.messageBox(_("That profile already exists. Please choose a different name."), - _("Error"), wx.OK | wx.ICON_ERROR, self) + gui.messageBox( + _("That profile already exists. Please choose a different name."), + _("Error"), wx.OK | wx.ICON_ERROR, self, + ) return except: # noqa: E722 log.debugWarning("", exc_info=True) # Translators: An error displayed when creating a configuration profile fails. - gui.messageBox(_("Error creating profile - probably read only file system."), - _("Error"), wx.OK | wx.ICON_ERROR, self) + gui.messageBox( + _("Error creating profile - probably read only file system."), + _("Error"), wx.OK | wx.ICON_ERROR, self, + ) self.onCancel(evt) return if spec: @@ -493,11 +517,13 @@ def onOk(self, evt): if gui.messageBox( # Translators: The prompt asking the user whether they wish to # manually activate a configuration profile that has just been created. - _("To edit this profile, you will need to manually activate it. " - "Once you have finished editing, you will need to manually deactivate it to resume normal usage.\n" - "Do you wish to manually activate it now?"), + _( + "To edit this profile, you will need to manually activate it. " + "Once you have finished editing, you will need to manually deactivate it to resume normal usage.\n" + "Do you wish to manually activate it now?", + ), # Translators: The title of the confirmation dialog for manual activation of a created profile. - _("Manual Activation"), wx.YES | wx.NO | wx.ICON_QUESTION, self + _("Manual Activation"), wx.YES | wx.NO | wx.ICON_QUESTION, self, ) == wx.YES: config.conf.manualActivateProfile(name) else: diff --git a/source/gui/exit.py b/source/gui/exit.py index 0ca53327ad0..62fa2b38ed2 100644 --- a/source/gui/exit.py +++ b/source/gui/exit.py @@ -80,7 +80,7 @@ def __init__(self, parent): addonsDisabledText = _( # Translators: A message in the exit Dialog shown when all add-ons are disabled. "All add-ons are now disabled. " - "They will be re-enabled on the next restart unless you choose to disable them again." + "They will be re-enabled on the next restart unless you choose to disable them again.", ) warningMessages.append(addonsDisabledText) if languageHandler.isLanguageForced(): @@ -88,7 +88,7 @@ def __init__(self, parent): # Translators: A message in the exit Dialog shown when NVDA language has been # overwritten from the command line. "NVDA's interface language is now forced from the command line." - " On the next restart, the language saved in NVDA's configuration will be used instead." + " On the next restart, the language saved in NVDA's configuration will be used instead.", ) warningMessages.append(langForcedMsg) if warningMessages: @@ -149,7 +149,7 @@ def onOk(self, evt): destPath=destPath, version=version, apiVersion=apiVersion, - backCompatTo=backCompatTo + backCompatTo=backCompatTo, ) displayDialogAsModal(confirmUpdateDialog) else: diff --git a/source/gui/guiHelper.py b/source/gui/guiHelper.py index 96d9d224102..9f331c3ee78 100644 --- a/source/gui/guiHelper.py +++ b/source/gui/guiHelper.py @@ -134,13 +134,15 @@ def associateElements(firstElement: wx.Control, secondElement: wx.Control) -> wx # staticText and input control # likely a labelled control from LabeledControlHelper - if isinstance(firstElement, wx.StaticText) and isinstance(secondElement, ( - wx.Button, - wx.Choice, - wx.Slider, - wx.SpinCtrl, - wx.TextCtrl, - )): + if isinstance(firstElement, wx.StaticText) and isinstance( + secondElement, ( + wx.Button, + wx.Choice, + wx.Slider, + wx.SpinCtrl, + wx.TextCtrl, + ), + ): sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(firstElement, flag=wx.ALIGN_CENTER_VERTICAL) sizer.AddSpacer(SPACE_BETWEEN_ASSOCIATED_CONTROL_HORIZONTAL) @@ -306,7 +308,7 @@ def __init__( self, parent: wx.Dialog, orientation: Optional[int] = None, - sizer: Optional[Union[wx.BoxSizer, wx.StaticBoxSizer]] = None + sizer: Optional[Union[wx.BoxSizer, wx.StaticBoxSizer]] = None, ): """ Init. Pass in either orientation OR sizer. @param parent: An instance of the parent wx window. EG wx.Dialog @@ -374,7 +376,7 @@ def addLabeledControl( self, labelText: str, wxCtrlClass: Type[_LabeledControlT], - **kwargs + **kwargs, ) -> _LabeledControlT: """ Convenience method to create a labeled control @param labelText: Text to use when constructing the wx.StaticText to label the control. @@ -399,7 +401,7 @@ def addLabeledControl( def addDialogDismissButtons( self, buttons: "_ButtonsT", - separated: bool = False + separated: bool = False, ) -> "_ButtonsT": """ Adds and aligns the buttons for dismissing the dialog; e.g. "ok | cancel". These buttons are expected to be the last items added to the dialog. Buttons that launch an action, do not dismiss the dialog, or are not @@ -415,7 +417,7 @@ def addDialogDismissButtons( """ if self.sizer.GetOrientation() != wx.VERTICAL: raise NotImplementedError( - "Adding dialog dismiss buttons to a horizontal BoxSizerHelper is not implemented." + "Adding dialog dismiss buttons to a horizontal BoxSizerHelper is not implemented.", ) if isinstance(buttons, ButtonHelper): toAdd = buttons.sizer diff --git a/source/gui/inputGestures.py b/source/gui/inputGestures.py index d27059a87bd..d2763c9df83 100644 --- a/source/gui/inputGestures.py +++ b/source/gui/inputGestures.py @@ -35,14 +35,14 @@ #: Type for structure returned by inputCore _GesturesModel = Dict[ str, # category name - _ScriptsModel + _ScriptsModel, ] def _getAllGestureScriptInfo() -> _GesturesModel: gestureMappings = inputCore.manager.getAllGestureMappings( obj=gui.mainFrame.prevFocus, - ancestors=gui.mainFrame.prevFocusAncestors + ancestors=gui.mainFrame.prevFocusAncestors, ) if inputCore.SCRCAT_KBEMU not in gestureMappings: gestureMappings[inputCore.SCRCAT_KBEMU] = {} @@ -149,10 +149,12 @@ def __init__(self, displayName: str, scripts: _ScriptsModel): self.scripts = [] for scriptName in sorted(scripts, key=strxfrm): scriptInfo = scripts[scriptName] - self.scripts.append(_ScriptVM( - displayName=scriptName, - scriptInfo=scriptInfo - )) + self.scripts.append( + _ScriptVM( + displayName=scriptName, + scriptInfo=scriptInfo, + ), + ) def __repr__(self): return f"Category: {self.displayName}" @@ -170,7 +172,7 @@ def __init__(self, emuGestureInfo: inputCore.AllGesturesScriptInfo): # will be replaced by the gesture that can be triggered by a mapped gesture. # E.G. Emulate key press: NVDA+b emuGestureDisplayName = _("Emulate key press: {emulateGesture}").format( - emulateGesture=emuGestureInfo.displayName + emulateGesture=emuGestureInfo.displayName, ) super(_EmulatedGestureVM, self).__init__(displayName=emuGestureDisplayName, scriptInfo=emuGestureInfo) @@ -214,9 +216,11 @@ def __init__(self, displayName: str, emuGestures: _ScriptsModel): for scriptName in sorted(emuGestures, key=strxfrm): emuG = emuGestures[scriptName] if isinstance(emuG, inputCore.KbEmuScriptInfo): - self.scripts.append(_EmulatedGestureVM( - emuGestureInfo=emuG - )) + self.scripts.append( + _EmulatedGestureVM( + emuGestureInfo=emuG, + ), + ) elif isinstance(emuG, inputCore.AllGesturesScriptInfo): self.scripts.append(_ScriptVM(scriptName, emuG)) else: @@ -229,7 +233,7 @@ def createPendingEmuGesture(self) -> _PendingEmulatedGestureVM: def finalisePending( self, - scriptInfo: inputCore.AllGesturesScriptInfo + scriptInfo: inputCore.AllGesturesScriptInfo, ) -> _EmulatedGestureVM: assert self.pending is not None self.scripts.remove(self.pending) @@ -237,7 +241,7 @@ def finalisePending( def _addEmulation( self, - scriptInfo: inputCore.AllGesturesScriptInfo + scriptInfo: inputCore.AllGesturesScriptInfo, ) -> _EmulatedGestureVM: emuGesture = self.removedKbEmulation.pop(scriptInfo.displayName, None) if not emuGesture: @@ -265,7 +269,7 @@ def removeEmulation(self, gestureEmulation: _EmulatedGestureVM): _VmSelection = Tuple[ _CategoryVMTypes, Optional[_ScriptVMTypes], - Optional[_GestureVMTypes] + Optional[_GestureVMTypes], ] @@ -295,7 +299,7 @@ def getIndexInTree(self, vmSelection: _VmSelection): return ( catIndex, catVM.scripts.index(scriptVM), - scriptVM.gestures.index(gestureVM) + scriptVM.gestures.index(gestureVM), ) if scriptVM is not None: return ( @@ -313,15 +317,19 @@ def _fillAllGestures(self): for catName in sorted(gestureMappings, key=strxfrm): scripts = gestureMappings[catName] if catName == inputCore.SCRCAT_KBEMU: - self.allGestures.append(_EmuCategoryVM( - displayName=catName, - emuGestures=scripts - )) + self.allGestures.append( + _EmuCategoryVM( + displayName=catName, + emuGestures=scripts, + ), + ) else: - self.allGestures.append(_CategoryVM( - displayName=catName, - scripts=scripts - )) + self.allGestures.append( + _CategoryVM( + displayName=catName, + scripts=scripts, + ), + ) def commitChanges(self): gesturesToRemove = [ @@ -340,14 +348,14 @@ def commitChanges(self): didRemove = False for gestureVM, scriptInfo in itertools.chain(gesturesToRemove, gesturesForRemovedKbEmu): log.debug( - f"removing gesture: {gestureVM.normalizedGestureIdentifier} for script: {scriptInfo.scriptName}" + f"removing gesture: {gestureVM.normalizedGestureIdentifier} for script: {scriptInfo.scriptName}", ) try: inputCore.manager.userGestureMap.remove( gestureVM.normalizedGestureIdentifier, scriptInfo.moduleName, scriptInfo.className, - scriptInfo.scriptName + scriptInfo.scriptName, ) except ValueError: # The user wants to unbind a gesture they didn't define. @@ -355,7 +363,7 @@ def commitChanges(self): gestureVM.normalizedGestureIdentifier, scriptInfo.moduleName, scriptInfo.className, - None # replace script with None + None, # replace script with None ) didRemove = True @@ -374,7 +382,7 @@ def commitChanges(self): gestureVM.normalizedGestureIdentifier, scriptInfo.moduleName, scriptInfo.className, - None # replace script with None + None, # replace script with None ) except ValueError: pass @@ -382,7 +390,7 @@ def commitChanges(self): gestureVM.normalizedGestureIdentifier, scriptInfo.moduleName, scriptInfo.className, - scriptInfo.scriptName + scriptInfo.scriptName, ) didAdd = True @@ -407,7 +415,7 @@ def filter(self, filterText: str): filterText = re.escape(filterText) pattern = re.compile( r"(?=.*?" + r")(?=.*?".join(filterText.split(r"\ ")) + r")", - re.U | re.IGNORECASE + re.U | re.IGNORECASE, ) for catVM in self.allGestures: filteredScripts = [ @@ -430,7 +438,7 @@ def __init__(self, parent, gesturesVM: _InputGesturesViewModel): super().__init__( parent, size=wx.Size(600, 400), - style=wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT | wx.TR_LINES_AT_ROOT | wx.TR_SINGLE + style=wx.TR_HAS_BUTTONS | wx.TR_HIDE_ROOT | wx.TR_LINES_AT_ROOT | wx.TR_SINGLE, ) def OnGetChildrenCount(self, index: Tuple[int, ...]) -> int: @@ -492,13 +500,13 @@ def getSelectedItemData(self) -> Optional[_VmSelection]: ) return None # ensure that the length of tuple is 3, missing elements replaced with None - nonesForMissingElements = ((None, ) * (3 - len(selIdx))) + nonesForMissingElements = ((None,) * (3 - len(selIdx))) selIdx: Tuple[int, Optional[int], Optional[int]] = selIdx + nonesForMissingElements return self.getData(selIdx) def getData( self, - index: Tuple[int, Optional[int], Optional[int]] + index: Tuple[int, Optional[int], Optional[int]], ) -> Optional[_VmSelection]: assert 3 == len(index) and index[0] is not None if len(self.gesturesVM.filteredGestures) == 0: @@ -542,7 +550,7 @@ def getData( if not isinstance(scriptVM, _PendingEmulatedGestureVM): log.error( "Pending emulated gestures can not have gestures yet. This indicates a logic error." - f" Trying to get index {gestureIndex} of pending emulation." + f" Trying to get index {gestureIndex} of pending emulation.", ) raise return (catVM, scriptVM, gestureVM) @@ -561,10 +569,10 @@ def doRefresh(self, postFilter=False, focus: Optional[_VmSelection] = None): log.debug(f"expanding: {focus}") catVM, scriptVM, gestureVM = focus catIndex = self.gesturesVM.filteredGestures.index(catVM) - self.Expand(self.GetItemByIndex((catIndex, ))) + self.Expand(self.GetItemByIndex((catIndex,))) if scriptVM is not None: scriptIndex = catVM.scripts.index(scriptVM) - self.Expand(self.GetItemByIndex((catIndex, scriptIndex, ))) + self.Expand(self.GetItemByIndex((catIndex, scriptIndex))) if focus: # selecting the item must be done after the freeze has completed (thawed) other wise WX calculates # the wrong scrolling position and puts the item outside of the virtual window. @@ -718,7 +726,7 @@ def _addCaptured(self, catVM: _CategoryVMTypes, scriptVM: _ScriptVMTypes, gestur self.Bind( wx.EVT_MENU, lambda evt, gid=gid: self._addChoice(catVM, scriptVM, gid), - item + item, ) self.PopupMenu(menu) if self.gesturesVM.isExpectingNewGesture: @@ -747,13 +755,13 @@ def _addCapturedKbEmu(self, gesture: inputCore.InputGesture, catVM: _EmulatedGes from globalCommands import GlobalCommands scriptInfo = inputCore._AllGestureMappingsRetriever.makeKbEmuScriptInfo( GlobalCommands, - kbGestureIdentifier=gestureToEmulate + kbGestureIdentifier=gestureToEmulate, ) catVM = self.gesturesVM.isExpectingNewEmuGesture newScript = catVM.finalisePending(scriptInfo) self.gesturesVM.isExpectingNewEmuGesture = None - self.tree.doRefresh(focus=(catVM, newScript, None,)) + self.tree.doRefresh(focus=(catVM, newScript, None)) self._refreshButtonState() def onRemove(self, evt): @@ -766,7 +774,7 @@ def onRemove(self, evt): if not isinstance(catVM, _EmuCategoryVM): log.error( f"Trying to remove script, only emulatedGestures can be removed from level of tree." - f" Trying to remove: {catVM.displayName}" + f" Trying to remove: {catVM.displayName}", ) return catVM.removeEmulation(scriptVM) @@ -785,7 +793,7 @@ def onReset(self, evt): This cannot be undone."""), # Translators: A prompt for confirmation to reset all gestures in the Input Gestures dialog. _("Reset gestures"), - style=wx.YES | wx.NO | wx.NO_DEFAULT + style=wx.YES | wx.NO | wx.NO_DEFAULT, ) != wx.YES: return inputCore.manager.userGestureMap.clear() @@ -797,7 +805,7 @@ def onReset(self, evt): gui.messageBox( _("Error saving user defined gestures - probably read only file system."), caption=_("Error"), - style=wx.OK | wx.ICON_ERROR + style=wx.OK | wx.ICON_ERROR, ) self.onCancel(None) return @@ -811,7 +819,7 @@ def onOk(self, evt): _("Error saving user defined gestures - probably read only file system."), # Translators: An title for an error displayed when saving user defined input gestures fails. _("Error"), - wx.OK | wx.ICON_ERROR + wx.OK | wx.ICON_ERROR, ) super(InputGesturesDialog, self).onOk(evt) diff --git a/source/gui/installerGui.py b/source/gui/installerGui.py index 093b116f4c3..da75aae3c9b 100644 --- a/source/gui/installerGui.py +++ b/source/gui/installerGui.py @@ -49,23 +49,25 @@ def doInstall( isUpdate=False, copyPortableConfig=False, silent=False, - startAfterInstall=True + startAfterInstall=True, ): - progressDialog = gui.IndeterminateProgressDialog(gui.mainFrame, - # Translators: The title of the dialog presented while NVDA is being updated. - _("Updating NVDA") if isUpdate - # Translators: The title of the dialog presented while NVDA is being installed. - else _("Installing NVDA"), - # Translators: The message displayed while NVDA is being updated. - _("Please wait while your previous installation of NVDA is being updated.") if isUpdate - # Translators: The message displayed while NVDA is being installed. - else _("Please wait while NVDA is being installed")) + progressDialog = gui.IndeterminateProgressDialog( + gui.mainFrame, + # Translators: The title of the dialog presented while NVDA is being updated. + _("Updating NVDA") if isUpdate + # Translators: The title of the dialog presented while NVDA is being installed. + else _("Installing NVDA"), + # Translators: The message displayed while NVDA is being updated. + _("Please wait while your previous installation of NVDA is being updated.") if isUpdate + # Translators: The message displayed while NVDA is being installed. + else _("Please wait while NVDA is being installed"), + ) try: res = systemUtils.execElevated( config.SLAVE_FILENAME, ["install", str(int(createDesktopShortcut)), str(int(startOnLogon))], wait=True, - handleAlreadyElevated=True + handleAlreadyElevated=True, ) if res==2: raise installer.RetriableFailure # noqa: E701 if copyPortableConfig: @@ -90,27 +92,32 @@ def doInstall( copyPortableConfig=copyPortableConfig, isUpdate=isUpdate, silent=silent, - startAfterInstall=startAfterInstall + startAfterInstall=startAfterInstall, ) if res!=0: log.error("Installation failed: %s"%res) # Translators: The message displayed when an error occurs during installation of NVDA. - gui.messageBox(_("The installation of NVDA failed. Please check the Log Viewer for more information."), - # Translators: The title of a dialog presented when an error occurs. - _("Error"), - wx.OK | wx.ICON_ERROR) + gui.messageBox( + _("The installation of NVDA failed. Please check the Log Viewer for more information."), + # Translators: The title of a dialog presented when an error occurs. + _("Error"), + wx.OK | wx.ICON_ERROR, + ) return if not silent: msg = ( # Translators: The message displayed when NVDA has been successfully installed. _("Successfully installed NVDA. ") if not isUpdate # Translators: The message displayed when NVDA has been successfully updated. - else _("Successfully updated your installation of NVDA. ")) + else _("Successfully updated your installation of NVDA. ") + ) # Translators: The message displayed to the user after NVDA is installed # and the installed copy is about to be started. - gui.messageBox(msg+_("Please press OK to start the installed copy."), - # Translators: The title of a dialog presented to indicate a successful operation. - _("Success")) + gui.messageBox( + msg+_("Please press OK to start the installed copy."), + # Translators: The title of a dialog presented to indicate a successful operation. + _("Success"), + ) newNVDA = None if startAfterInstall: @@ -123,7 +130,7 @@ def doInstall( def doSilentInstall( copyPortableConfig=False, - startAfterInstall=True + startAfterInstall=True, ): prevInstall=installer.comparePreviousInstall() is not None startOnLogon=globalVars.appArgs.enableStartOnLogon @@ -135,7 +142,7 @@ def doSilentInstall( isUpdate=prevInstall, copyPortableConfig=copyPortableConfig, silent=True, - startAfterInstall=startAfterInstall + startAfterInstall=startAfterInstall, ) @@ -158,9 +165,11 @@ def __init__(self, parent, isUpdate): getAddonCompatibilityConfirmationMessage, getAddonCompatibilityMessage, ) - shouldAskAboutAddons = any(addonHandler.getIncompatibleAddons( - # the defaults from the installer are ok. We are testing against the running version. - )) + shouldAskAboutAddons = any( + addonHandler.getIncompatibleAddons( + # the defaults from the installer are ok. We are testing against the running version. + ), + ) mainSizer = self.mainSizer = wx.BoxSizer(wx.VERTICAL) sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL) @@ -182,8 +191,8 @@ def __init__(self, parent, isUpdate): self.confirmationCheckbox = sHelper.addItem( wx.CheckBox( self, - label=getAddonCompatibilityConfirmationMessage() - ) + label=getAddonCompatibilityConfirmationMessage(), + ), ) self.bindHelpEvent("InstallWithIncompatibleAddons", self.confirmationCheckbox) self.confirmationCheckbox.SetFocus() @@ -243,7 +252,7 @@ def __init__(self, parent, isUpdate): if shouldAskAboutAddons: self.confirmationCheckbox.Bind( wx.EVT_CHECKBOX, - lambda evt: continueButton.Enable(not continueButton.Enabled) + lambda evt: continueButton.Enable(not continueButton.Enabled), ) continueButton.Enable(False) @@ -262,7 +271,7 @@ def onInstall(self, evt): createDesktopShortcut=self.createDesktopShortcutCheckbox.Value, startOnLogon=self.startOnLogonCheckbox.Value, copyPortableConfig=self.copyPortableConfigCheckbox.Value, - isUpdate=self.isUpdate + isUpdate=self.isUpdate, ) wx.GetApp().ScheduleForDestruction(self) @@ -301,8 +310,9 @@ def __init__(self): "than the version currently installed. " "If you really wish to revert to an earlier version, " "you should first cancel this installation " - "and completely uninstall NVDA before installing the earlier version." - )) + "and completely uninstall NVDA before installing the earlier version.", + ), + ) text.Wrap(self.scaleSize(600)) contentSizer.addItem(text) @@ -312,11 +322,11 @@ def __init__(self): id=wx.ID_OK, # Translators: The label of a button to proceed with installation, # even though this is not recommended. - label=_("&Proceed with installation (not recommended)") + label=_("&Proceed with installation (not recommended)"), ) cancelButton = buttonHelper.addButton( parent=self, - id=wx.ID_CANCEL + id=wx.ID_CANCEL, ) contentSizer.addDialogDismissButtons(buttonHelper) @@ -358,12 +368,12 @@ def _warnAndConfirmForNonEmptyDirectory(portableDirectory: str) -> bool: # Translators: The message displayed when the user has specified a destination directory # that already has a portable copy in the Create Portable NVDA dialog. f"A portable copy already exists in the directory '{portableDirectory}'. " - "Do you want to update it?" + "Do you want to update it?", ), # Translators: The title of a dialog presented when the user has specified a destination directory # that already has a portable copy in the Create Portable NVDA dialog. _("Portable Copy Exists"), - wx.YES_NO | wx.ICON_QUESTION + wx.YES_NO | wx.ICON_QUESTION, ): return False elif wx.NO == gui.messageBox( @@ -372,12 +382,12 @@ def _warnAndConfirmForNonEmptyDirectory(portableDirectory: str) -> bool: # that already exists in the Create Portable NVDA dialog. f"The specified directory '{portableDirectory}' is not empty. " "Proceeding will delete and replace existing files in the directory. " - "Do you want to overwrite the contents of this folder? " + "Do you want to overwrite the contents of this folder? ", ), # Translators: The title of a dialog presented when the user has specified a destination directory # that already exists in the Create Portable NVDA dialog. _("Directory Exists"), - wx.YES_NO | wx.ICON_QUESTION + wx.YES_NO | wx.ICON_QUESTION, ): return False return True @@ -470,7 +480,7 @@ def onCreatePortable(self, evt): _("Please specify a directory in which to create the portable copy."), # Translators: the title of an error dialog. _("Error"), - wx.OK | wx.ICON_ERROR + wx.OK | wx.ICON_ERROR, ) return expandedPortableDirectory = os.path.expandvars(self.portableDirectoryEdit.Value) @@ -480,12 +490,12 @@ def onCreatePortable(self, evt): # Translators: The message displayed when the user has not specified an absolute destination directory # in the Create Portable NVDA dialog. "Please specify the absolute path where the portable copy should be created. " - "It may include system variables (%temp%, %homepath%, etc.)." + "It may include system variables (%temp%, %homepath%, etc.).", ), # Translators: The message title displayed when the user has not specified an absolute # destination directory in the Create Portable NVDA dialog. _("Error"), - wx.OK | wx.ICON_ERROR + wx.OK | wx.ICON_ERROR, ) return # isabs determines if the path is absolute, with or without a drive letter. abspath adds any missing initial @@ -537,7 +547,7 @@ def doCreatePortable( # Translators: The title of the dialog presented while a portable copy of NVDA is being created. _("Creating Portable Copy"), # Translators: The message displayed while a portable copy of NVDA is being created. - _("Please wait while a portable copy of NVDA is created.") + _("Please wait while a portable copy of NVDA is created."), ) try: systemUtils.ExecAndPump(installer.createPortableCopy, portableDirectory, copyUserConfig) @@ -557,7 +567,7 @@ def doCreatePortable( _("Failed to create portable copy: {error}.").format(error=e), # Translators: Title of an error dialog shown when an error occurs while creating a portable copy of NVDA. _("Error"), - wx.OK | wx.ICON_ERROR + wx.OK | wx.ICON_ERROR, ) return d.done() @@ -567,7 +577,7 @@ def doCreatePortable( # {dir} will be replaced with the destination directory. _("Successfully created a portable copy of NVDA at {dir}").format(dir=portableDirectory), # Translators: Title of a dialog shown when a portable copy of NVDA is created. - _("Success") + _("Success"), ) if silent or startAfterCreate: newNVDA = None diff --git a/source/gui/logViewer.py b/source/gui/logViewer.py index d87dec4eb12..80898468eb1 100755 --- a/source/gui/logViewer.py +++ b/source/gui/logViewer.py @@ -19,7 +19,7 @@ class LogViewer( gui.contextHelp.ContextHelpMixin, - wx.Frame # wxPython does not seem to call base class initializer, put last in MRO + wx.Frame, # wxPython does not seem to call base class initializer, put last in MRO ): """The NVDA log viewer GUI. """ @@ -126,7 +126,7 @@ def activate(): _("Log is unavailable"), # Translators: The title of an error message dialog. _("Error"), - wx.OK | wx.ICON_ERROR + wx.OK | wx.ICON_ERROR, ) return logViewer.Raise() diff --git a/source/gui/message.py b/source/gui/message.py index 3f15661d92f..b117dab052c 100644 --- a/source/gui/message.py +++ b/source/gui/message.py @@ -73,7 +73,7 @@ def messageBox( message: str, caption: str = wx.MessageBoxCaptionStr, style: int = wx.OK | wx.CENTER, - parent: Optional[wx.Window] = None + parent: Optional[wx.Window] = None, ) -> int: """Display a message dialog. Avoid using C{wx.MessageDialog} and C{wx.MessageBox} directly. diff --git a/source/gui/nvdaControls.py b/source/gui/nvdaControls.py index 13d80a33c51..2ac44101f04 100644 --- a/source/gui/nvdaControls.py +++ b/source/gui/nvdaControls.py @@ -43,7 +43,7 @@ def __init__( itemTextCallable=None, pos=wx.DefaultPosition, size=wx.DefaultSize, - style=0 + style=0, ): """ initialiser Takes the same parameter as a wx.ListCtrl with the following additions: @@ -148,9 +148,10 @@ class AutoWidthColumnCheckListCtrl(AutoWidthColumnListCtrl, listmix.CheckListCtr This event is only fired when an item is toggled with the mouse or keyboard. """ - def __init__(self, parent, id=wx.ID_ANY, autoSizeColumn="LAST", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, - check_image=None, uncheck_image=None, imgsz=(16, 16) - ): + def __init__( + self, parent, id=wx.ID_ANY, autoSizeColumn="LAST", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, + check_image=None, uncheck_image=None, imgsz=(16, 16), + ): AutoWidthColumnListCtrl.__init__(self, parent, id=id, pos=pos, size=size, style=style, autoSizeColumn=autoSizeColumn) listmix.CheckListCtrlMixin.__init__(self, check_image, uncheck_image, imgsz) # Register a custom wx.Accessible implementation to fix accessibility incompleties @@ -257,7 +258,7 @@ def _addButtons(self, buttonHelper): self, id=wx.ID_OK, # Translators: An ok button on a message dialog. - label=_("OK") + label=_("OK"), ) ok.SetDefault() ok.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.OK)) @@ -266,7 +267,7 @@ def _addButtons(self, buttonHelper): self, id=wx.ID_CANCEL, # Translators: A cancel button on a message dialog. - label=_("Cancel") + label=_("Cancel"), ) cancel.Bind(wx.EVT_BUTTON, lambda evt: self.EndModal(wx.CANCEL)) @@ -321,7 +322,7 @@ def __init__(self, parent, title, message, dialogType=DIALOG_TYPE_STANDARD): mainSizer.Add( contentsSizer.sizer, border=guiHelper.BORDER_FOR_DIALOGS, - flag=wx.ALL + flag=wx.ALL, ) mainSizer.Fit(self) self.SetSizer(mainSizer) @@ -393,7 +394,7 @@ def GetChildRectRelativeToSelf(self, child: wx.Window) -> wx.Rect: childRectRelativeToScreen.x - scrolledPanelScreenPosition.x, childRectRelativeToScreen.y - scrolledPanelScreenPosition.y, childRectRelativeToScreen.width, - childRectRelativeToScreen.height + childRectRelativeToScreen.height, ) def ScrollChildIntoView(self, child: wx.Window) -> None: @@ -450,7 +451,7 @@ def __init__( if self._optionsEnumClass.DEFAULT in translatedOptions: raise ValueError( f"The translatedOptions dictionary should not contain the key {self._optionsEnumClass.DEFAULT!r}" - " It will be added automatically. See _setDefaultOptionLabel" + " It will be added automatically. See _setDefaultOptionLabel", ) self._translatedOptions = self._createOptionsDict(translatedOptions) choices = list(self._translatedOptions.values()) @@ -466,7 +467,7 @@ def __init__( if onChoiceEventHandler is not None: self.Bind( wx.EVT_CHOICE, - onChoiceEventHandler + onChoiceEventHandler, ) self.SetSelection(self._getChoiceIndex(configValue.value)) self.defaultValue = self._getConfSpecDefaultValue() @@ -535,7 +536,7 @@ def saveCurrentValueToConf(self) -> None: def _createOptionsDict( self, - translatedOptions: OrderedDict[FeatureFlagEnumT, str] + translatedOptions: OrderedDict[FeatureFlagEnumT, str], ) -> OrderedDict[enum.Enum, str]: behaviorOfDefault = self._getConfigValue().behaviorOfDefault translatedStringForBehaviorOfDefault = translatedOptions[behaviorOfDefault] @@ -544,9 +545,9 @@ def _createOptionsDict( # The placeholder {} is replaced with the label of the option which describes current default behavior # in NVDA. EG "Default (Yes)". defaultOptionLabel: str = _("Default ({})").format( - translatedStringForBehaviorOfDefault + translatedStringForBehaviorOfDefault, ) return collections.OrderedDict({ self._optionsEnumClass.DEFAULT: defaultOptionLabel, # make sure default is the first option. - **translatedOptions + **translatedOptions, }) diff --git a/source/gui/settingsDialogs.py b/source/gui/settingsDialogs.py index 86d01509d91..e7385fa090c 100644 --- a/source/gui/settingsDialogs.py +++ b/source/gui/settingsDialogs.py @@ -87,7 +87,7 @@ class SettingsDialog( DpiScalingHelperMixinWithoutInit, gui.contextHelp.ContextHelpMixin, wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO - metaclass=guiHelper.SIPABCMeta + metaclass=guiHelper.SIPABCMeta, ): """A settings dialog. A settings dialog consists of one or more settings controls and OK and Cancel buttons and an optional Apply button. @@ -136,7 +136,7 @@ def __new__(cls, *args, **kwargs): instancesState = dict(SettingsDialog._instances) log.debug( "Creating new settings dialog (multiInstanceAllowed:{}). " - "State of _instances {!r}".format(multiInstanceAllowed, instancesState) + "State of _instances {!r}".format(multiInstanceAllowed, instancesState), ) if state is cls.DialogState.CREATED and not multiInstanceAllowed: raise SettingsDialog.MultiInstanceErrorWithDialog( @@ -147,7 +147,7 @@ def __new__(cls, *args, **kwargs): # The dialog has been destroyed by wx, but the instance is still available. # This indicates there is something keeping it alive. raise RuntimeError( - f"Cannot open new settings dialog while instance still exists: {firstMatchingInstance!r}" + f"Cannot open new settings dialog while instance still exists: {firstMatchingInstance!r}", ) obj = super().__new__(cls, *args, **kwargs) SettingsDialog._instances[obj] = cls.DialogState.CREATED @@ -172,7 +172,7 @@ def _setInstanceDestroyedState(self): instancesList = list(instanceStatesGen) log.debug( f"Setting state to destroyed for instance: {self.title} - {self.__class__.__qualname__} - {self}\n" - f"Current _instances {instancesList}" + f"Current _instances {instancesList}", ) SettingsDialog._instances[self] = self.DialogState.DESTROYED @@ -211,7 +211,7 @@ def __init__( if hasApplyButton: log.debugWarning( "The hasApplyButton parameter is deprecated. " - "Use buttons instead. " + "Use buttons instead. ", ) buttonFlag |= wx.APPLY self.hasApply = hasApplyButton or wx.APPLY in buttons @@ -226,7 +226,7 @@ def __init__( self.mainSizer.Add( self.CreateSeparatedButtonSizer(buttonFlag), border=guiHelper.BORDER_FOR_DIALOGS, - flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT + flag=wx.EXPAND | wx.BOTTOM | wx.LEFT | wx.RIGHT, ) self.mainSizer.Fit(self) @@ -331,7 +331,7 @@ class SettingsPanel( DpiScalingHelperMixinWithoutInit, gui.contextHelp.ContextHelpMixin, wx.Panel, # wxPython does not seem to call base class initializer, put last in MRO - metaclass=guiHelper.SIPABCMeta + metaclass=guiHelper.SIPABCMeta, ): """A settings panel, to be used in a multi category settings dialog. A settings panel consists of one or more settings controls. @@ -427,12 +427,12 @@ def _validationErrorMessageBox( "{message}\n" "\n" 'Category: "{category}"\n' - 'Option: "{option}"' - ).format( + 'Option: "{option}"', + ).format( message=message, category=category, option=option, - ), + ), # Translators: The title of the message box when a setting's configuration is not valid. caption=_("Invalid configuration"), style=wx.OK | wx.ICON_ERROR, @@ -508,7 +508,7 @@ def __init__(self, parent, initialCategory=None): if gui._isDebug(): log.debug("Unable to open category: {}".format(initialCategory), stack_info=True) raise MultiCategorySettingsDialog.CategoryUnavailableError( - "The provided initial category is not a part of this dialog" + "The provided initial category is not a part of this dialog", ) self.initialCategory = initialCategory self.currentCategory = None @@ -562,7 +562,7 @@ def makeSettings(self, settingsSizer): self, autoSizeColumn=1, size=catListDim, - style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.LC_NO_HEADER + style=wx.LC_REPORT|wx.LC_SINGLE_SEL|wx.LC_NO_HEADER, ) # This list consists of only one column. # The provided column header is just a placeholder, as it is hidden due to the wx.LC_NO_HEADER style flag. @@ -571,7 +571,7 @@ def makeSettings(self, settingsSizer): self.container = nvdaControls.TabbableScrolledPanel( parent = self, style = wx.TAB_TRAVERSAL | wx.BORDER_THEME, - size=containerDim + size=containerDim, ) # Th min size is reset so that they can be reduced to below their "size" constraint. @@ -598,7 +598,7 @@ def makeSettings(self, settingsSizer): self.gridBagSizer=gridBagSizer=wx.GridBagSizer( hgap=guiHelper.SPACE_BETWEEN_BUTTONS_HORIZONTAL, - vgap=guiHelper.SPACE_BETWEEN_BUTTONS_VERTICAL + vgap=guiHelper.SPACE_BETWEEN_BUTTONS_VERTICAL, ) # add the label, the categories list, and the settings panel to a 2 by 2 grid. # The label should span two columns, so that the start of the categories list @@ -631,16 +631,17 @@ def _getCategoryPanel(self, catId): panel.Hide() self.containerSizer.Add( panel, flag=wx.ALL | wx.EXPAND, - border=guiHelper.SPACE_BETWEEN_ASSOCIATED_CONTROL_HORIZONTAL + border=guiHelper.SPACE_BETWEEN_ASSOCIATED_CONTROL_HORIZONTAL, ) self.catIdToInstanceMap[catId] = panel panelWidth = panel.Size[0] availableWidth = self.containerSizer.GetSize()[0] if panelWidth > availableWidth and gui._isDebug(): log.debugWarning( - ("Panel width ({1}) too large for: {0} Try to reduce the width of this panel, or increase width of " + - "MultiCategorySettingsDialog.MIN_SIZE" - ).format(cls, panel.Size[0]) + ( + "Panel width ({1}) too large for: {0} Try to reduce the width of this panel, or increase width of " + + "MultiCategorySettingsDialog.MIN_SIZE" + ).format(cls, panel.Size[0]), ) panel.SetLabel(panel.title.replace('&', '&&')) panel.SetAccessible(SettingsPanelAccessible(panel)) @@ -780,7 +781,7 @@ class GeneralSettingsPanel(SettingsPanel): # Translators: One of the log levels of NVDA (the input/output shows keyboard commands and/or braille commands as well as speech and/or braille output of NVDA). (log.IO, _("input/output")), # Translators: One of the log levels of NVDA (the debug mode shows debug messages as NVDA runs). - (log.DEBUG, _("debug")) + (log.DEBUG, _("debug")), ) def makeSettings(self, settingsSizer): @@ -801,7 +802,7 @@ def makeSettings(self, settingsSizer): languageChoices.append( # Translators: Shown for a language which has been provided from the command line # 'langDesc' would be replaced with description of the given locale. - _("Command line option: {langDesc}").format(langDesc=cmdLangDescription) + _("Command line option: {langDesc}").format(langDesc=cmdLangDescription), ) self.languageNames.append("FORCED") # Translators: The label for a setting in general settings to select NVDA's interface language @@ -873,7 +874,7 @@ def makeSettings(self, settingsSizer): # allow NVDA to come up in Windows login screen (useful if user # needs to enter passwords or if multiple user accounts are present # to allow user to choose the correct account). - label=_("Use NVDA during sign-in (requires administrator privileges)") + label=_("Use NVDA during sign-in (requires administrator privileges)"), ) self.bindHelpEvent("GeneralSettingsStartOnLogOnScreen", self.startOnLogonScreenCheckBox) self.startOnLogonScreenCheckBox.SetValue(config.getStartOnLogonScreen()) @@ -889,8 +890,8 @@ def makeSettings(self, settingsSizer): # settings to be used in secure screens such as User Account # Control (UAC) dialog). "Use currently saved settings during sign-in and on secure screens" - " (requires administrator privileges)" - ) + " (requires administrator privileges)", + ), ) self.bindHelpEvent("GeneralSettingsCopySettings", self.copySettingsButton) self.copySettingsButton.Bind(wx.EVT_BUTTON,self.onCopySettings) @@ -917,7 +918,7 @@ def makeSettings(self, settingsSizer): item = self.allowUsageStatsCheckBox = wx.CheckBox( self, # Translators: The label of a checkbox in general settings to toggle allowing of usage stats gathering - label=_("Allow NV Access to gather NVDA usage statistics") + label=_("Allow NV Access to gather NVDA usage statistics"), ) self.bindHelpEvent("GeneralSettingsGatherUsageStats", self.allowUsageStatsCheckBox) item.Value=config.conf["update"]["allowUsageStats"] @@ -935,7 +936,7 @@ def onCopySettings(self,evt): # settings to system settings. "Add-ons were detected in your user settings directory. " "Copying these to the system profile could be a security risk. " - "Do you still wish to copy your settings?" + "Do you still wish to copy your settings?", ) # Translators: The title of the warning dialog displayed when trying to # copy settings for use in secure screens. @@ -949,7 +950,7 @@ def onCopySettings(self,evt): _("Copying Settings"), # Translators: The message displayed while settings are being copied # to the system configuration (for use on Windows logon etc) - _("Please wait while settings are copied to the system configuration.") + _("Please wait while settings are copied to the system configuration."), ) while True: try: @@ -1085,8 +1086,8 @@ def makeSettings(self, settingsSizer): synthGroup.addItem( guiHelper.associateElements( self.synthNameCtrl, - changeSynthBtn - ) + changeSynthBtn, + ), ) changeSynthBtn.Bind(wx.EVT_BUTTON,self.onChangeSynth) @@ -1214,14 +1215,14 @@ def __call__(self,evt): speech.cancelSpeech() changeVoice( self.driver, - getattr(self.container,"_%ss"%self.setting.id)[evt.GetSelection()].id + getattr(self.container,"_%ss"%self.setting.id)[evt.GetSelection()].id, ) self.container.updateDriverSettings(changedSetting=self.setting.id) else: setattr( self.driver, self.setting.id, - getattr(self.container,"_%ss"%self.setting.id)[evt.GetSelection()].id + getattr(self.container,"_%ss"%self.setting.id)[evt.GetSelection()].id, ) @@ -1256,7 +1257,7 @@ def __init__(self, *args, **kwargs): # We also use the weakref to refresh the gui when an instance dies. self._currentSettingsRef = weakref.ref( self.getSettings(), - lambda ref: wx.CallAfter(self.refreshGui) + lambda ref: wx.CallAfter(self.refreshGui), ) settingsSizer: wx.BoxSizer @@ -1294,7 +1295,7 @@ def _getSettingControlHelpId(self, controlId): def _makeSliderSettingControl( self, setting: NumericDriverSetting, - settingsStorage: Any + settingsStorage: Any, ) -> wx.BoxSizer: """Constructs appropriate GUI controls for given L{DriverSetting} such as label and slider. @param setting: Setting to construct controls for @@ -1308,16 +1309,18 @@ def _makeSliderSettingControl( f"{setting.displayNameWithAccelerator}:", nvdaControls.EnhancedInputSlider, minValue=setting.minVal, - maxValue=setting.maxVal + maxValue=setting.maxVal, ) lSlider=labeledControl.control setattr(self, f"{setting.id}Slider", lSlider) - lSlider.Bind(wx.EVT_SLIDER, DriverSettingChanger( - settingsStorage, setting - )) + lSlider.Bind( + wx.EVT_SLIDER, DriverSettingChanger( + settingsStorage, setting, + ), + ) self.bindHelpEvent( self._getSettingControlHelpId(setting.id), - lSlider + lSlider, ) self._setSliderStepSizes(lSlider, setting) lSlider.SetValue(getattr(settingsStorage, setting.id)) @@ -1329,7 +1332,7 @@ def _makeSliderSettingControl( def _makeStringSettingControl( self, setting: DriverSetting, - settingsStorage: Any + settingsStorage: Any, ): """ Same as L{_makeSliderSettingControl} but for string settings displayed in a wx.Choice control @@ -1345,23 +1348,25 @@ def _makeStringSettingControl( stringSettingAttribName, # Settings are stored as an ordered dict. # Therefore wrap this inside a list call. - list(getattr( - self.getSettings(), - f"available{setting.id.capitalize()}s" - ).values()) + list( + getattr( + self.getSettings(), + f"available{setting.id.capitalize()}s", + ).values(), + ), ) stringSettings = getattr(self, stringSettingAttribName) labeledControl = guiHelper.LabeledControlHelper( self, labelText, wx.Choice, - choices=[x.displayName for x in stringSettings] + choices=[x.displayName for x in stringSettings], ) lCombo = labeledControl.control setattr(self, f"{setting.id}List", lCombo) self.bindHelpEvent( self._getSettingControlHelpId(setting.id), - lCombo + lCombo, ) try: @@ -1374,7 +1379,7 @@ def _makeStringSettingControl( pass lCombo.Bind( wx.EVT_CHOICE, - StringDriverSettingChanger(settingsStorage, setting, self) + StringDriverSettingChanger(settingsStorage, setting, self), ) if self.lastControl: lCombo.MoveAfterInTabOrder(self.lastControl) @@ -1384,7 +1389,7 @@ def _makeStringSettingControl( def _makeBooleanSettingControl( self, setting: BooleanDriverSetting, - settingsStorage: Any + settingsStorage: Any, ): """ Same as L{_makeSliderSettingControl} but for boolean settings. Returns checkbox. @@ -1399,10 +1404,12 @@ def _onCheckChanged(evt: wx.CommandEvent): setattr(settingsStorageProxy, setting.id, evt.IsChecked()) checkbox.Bind(wx.EVT_CHECKBOX, _onCheckChanged) - checkbox.SetValue(getattr( - settingsStorage, - setting.id - )) + checkbox.SetValue( + getattr( + settingsStorage, + setting.id, + ), + ) if self.lastControl: checkbox.MoveAfterInTabOrder(self.lastControl) self.lastControl=checkbox @@ -1448,7 +1455,7 @@ def _createNewControl(self, setting, settingsStorage): len(self.sizerDict) - 1, s, border=10, - flag=wx.BOTTOM + flag=wx.BOTTOM, ) def _getSettingMaker(self, setting): @@ -1464,11 +1471,11 @@ def _updateValueForControl(self, setting, settingsStorage): self.settingsSizer.Show(self.sizerDict[setting.id]) if isinstance(setting, NumericDriverSetting): getattr(self, f"{setting.id}Slider").SetValue( - getattr(settingsStorage, setting.id) + getattr(settingsStorage, setting.id), ) elif isinstance(setting, BooleanDriverSetting): getattr(self, f"{setting.id}Checkbox").SetValue( - getattr(settingsStorage, setting.id) + getattr(settingsStorage, setting.id), ) else: options = getattr(self, f"_{setting.id}s") @@ -1501,7 +1508,7 @@ def refreshGui(self): self.settingsSizer.Clear(delete_windows=True) self._currentSettingsRef = weakref.ref( self.getSettings(), - lambda ref: wx.CallAfter(self.refreshGui) + lambda ref: wx.CallAfter(self.refreshGui), ) self.makeSettings(self.settingsSizer) @@ -1545,11 +1552,12 @@ def makeSettings(self, settingsSizer): self.autoLanguageSwitchingCheckbox = settingsSizerHelper.addItem( wx.CheckBox( self, - label=autoLanguageSwitchingText - )) + label=autoLanguageSwitchingText, + ), + ) self.bindHelpEvent("SpeechSettingsLanguageSwitching", self.autoLanguageSwitchingCheckbox) self.autoLanguageSwitchingCheckbox.SetValue( - config.conf["speech"]["autoLanguageSwitching"] + config.conf["speech"]["autoLanguageSwitching"], ) # Translators: This is the label for a checkbox in the @@ -1557,11 +1565,11 @@ def makeSettings(self, settingsSizer): # read text in that dialect). autoDialectSwitchingText = _("Automatic dialect switching (when supported)") self.autoDialectSwitchingCheckbox = settingsSizerHelper.addItem( - wx.CheckBox(self, label=autoDialectSwitchingText) + wx.CheckBox(self, label=autoDialectSwitchingText), ) self.bindHelpEvent("SpeechSettingsDialectSwitching", self.autoDialectSwitchingCheckbox) self.autoDialectSwitchingCheckbox.SetValue( - config.conf["speech"]["autoDialectSwitching"] + config.conf["speech"]["autoDialectSwitching"], ) # Translators: This is the label for a combobox in the @@ -1572,19 +1580,19 @@ def makeSettings(self, settingsSizer): symbolLevelLabels[level] for level in characterProcessing.CONFIGURABLE_SPEECH_SYMBOL_LEVELS ] self.symbolLevelList = settingsSizerHelper.addLabeledControl( - punctuationLabelText, wx.Choice, choices=symbolLevelChoices + punctuationLabelText, wx.Choice, choices=symbolLevelChoices, ) self.bindHelpEvent("SpeechSettingsSymbolLevel", self.symbolLevelList) curLevel = config.conf["speech"]["symbolLevel"] self.symbolLevelList.SetSelection( - characterProcessing.CONFIGURABLE_SPEECH_SYMBOL_LEVELS.index(curLevel) + characterProcessing.CONFIGURABLE_SPEECH_SYMBOL_LEVELS.index(curLevel), ) # Translators: This is the label for a checkbox in the # voice settings panel (if checked, text will be read using the voice for the language of the text). trustVoiceLanguageText = _("Trust voice's language when processing characters and symbols") self.trustVoiceLanguageCheckbox = settingsSizerHelper.addItem( - wx.CheckBox(self, label=trustVoiceLanguageText) + wx.CheckBox(self, label=trustVoiceLanguageText), ) self.bindHelpEvent("SpeechSettingsTrust", self.trustVoiceLanguageCheckbox) self.trustVoiceLanguageCheckbox.SetValue(config.conf["speech"]["trustVoiceLanguage"]) @@ -1592,7 +1600,7 @@ def makeSettings(self, settingsSizer): self.unicodeNormalizationCombo: nvdaControls.FeatureFlagCombo = settingsSizerHelper.addLabeledControl( labelText=_( # Translators: This is a label for a combo-box in the Speech settings panel. - "Unicode normali&zation" + "Unicode normali&zation", ), wxCtrlClass=nvdaControls.FeatureFlagCombo, keyPath=["speech", "unicodeNormalization"], @@ -1605,40 +1613,44 @@ def makeSettings(self, settingsSizer): # speech settings panel. reportNormalizedForCharacterNavigationText = _("Report '&Normalized' when navigating by character") self.reportNormalizedForCharacterNavigationCheckBox = settingsSizerHelper.addItem( - wx.CheckBox(self, label=reportNormalizedForCharacterNavigationText) + wx.CheckBox(self, label=reportNormalizedForCharacterNavigationText), ) self.bindHelpEvent( "SpeechReportNormalizedForCharacterNavigation", - self.reportNormalizedForCharacterNavigationCheckBox + self.reportNormalizedForCharacterNavigationCheckBox, ) self.reportNormalizedForCharacterNavigationCheckBox.SetValue( - config.conf["speech"]["reportNormalizedForCharacterNavigation"] + config.conf["speech"]["reportNormalizedForCharacterNavigation"], ) includeCLDRText = _( # Translators: This is the label for a checkbox in the # voice settings panel (if checked, data from the unicode CLDR will be used # to speak emoji descriptions). - "Include Unicode Consortium data (including emoji) when processing characters and symbols" + "Include Unicode Consortium data (including emoji) when processing characters and symbols", ) self.includeCLDRCheckbox = settingsSizerHelper.addItem( - wx.CheckBox(self, label=includeCLDRText) + wx.CheckBox(self, label=includeCLDRText), ) self.bindHelpEvent( "SpeechSettingsCLDR", - self.includeCLDRCheckbox + self.includeCLDRCheckbox, ) self.includeCLDRCheckbox.SetValue(config.conf["speech"]["includeCLDR"]) self._appendDelayedCharacterDescriptions(settingsSizerHelper) - minPitchChange = int(config.conf.getConfigValidation( - ("speech", self.driver.name, "capPitchChange") - ).kwargs["min"]) + minPitchChange = int( + config.conf.getConfigValidation( + ("speech", self.driver.name, "capPitchChange"), + ).kwargs["min"], + ) - maxPitchChange = int(config.conf.getConfigValidation( - ("speech", self.driver.name, "capPitchChange") - ).kwargs["max"]) + maxPitchChange = int( + config.conf.getConfigValidation( + ("speech", self.driver.name, "capPitchChange"), + ).kwargs["max"], + ) # Translators: This is a label for a setting in voice settings (an edit box to change # voice pitch for capital letters; the higher the value, the pitch will be higher). @@ -1648,46 +1660,47 @@ def makeSettings(self, settingsSizer): nvdaControls.SelectOnFocusSpinCtrl, min=minPitchChange, max=maxPitchChange, - initial=config.conf["speech"][self.driver.name]["capPitchChange"]) + initial=config.conf["speech"][self.driver.name]["capPitchChange"], + ) self.bindHelpEvent( "SpeechSettingsCapPitchChange", - self.capPitchChangeEdit + self.capPitchChangeEdit, ) # Translators: This is the label for a checkbox in the # voice settings panel. sayCapForCapsText = _("Say &cap before capitals") self.sayCapForCapsCheckBox = settingsSizerHelper.addItem( - wx.CheckBox(self, label=sayCapForCapsText) + wx.CheckBox(self, label=sayCapForCapsText), ) self.bindHelpEvent("SpeechSettingsSayCapBefore", self.sayCapForCapsCheckBox) self.sayCapForCapsCheckBox.SetValue( - config.conf["speech"][self.driver.name]["sayCapForCapitals"] + config.conf["speech"][self.driver.name]["sayCapForCapitals"], ) # Translators: This is the label for a checkbox in the # voice settings panel. beepForCapsText =_("&Beep for capitals") self.beepForCapsCheckBox = settingsSizerHelper.addItem( - wx.CheckBox(self, label=beepForCapsText) + wx.CheckBox(self, label=beepForCapsText), ) self.bindHelpEvent( "SpeechSettingsBeepForCaps", - self.beepForCapsCheckBox + self.beepForCapsCheckBox, ) self.beepForCapsCheckBox.SetValue( - config.conf["speech"][self.driver.name]["beepForCapitals"] + config.conf["speech"][self.driver.name]["beepForCapitals"], ) # Translators: This is the label for a checkbox in the # voice settings panel. useSpellingFunctionalityText = _("Use &spelling functionality if supported") self.useSpellingFunctionalityCheckBox = settingsSizerHelper.addItem( - wx.CheckBox(self, label=useSpellingFunctionalityText) + wx.CheckBox(self, label=useSpellingFunctionalityText), ) self.bindHelpEvent("SpeechSettingsUseSpelling", self.useSpellingFunctionalityCheckBox) self.useSpellingFunctionalityCheckBox.SetValue( - config.conf["speech"][self.driver.name]["useSpellingFunctionality"] + config.conf["speech"][self.driver.name]["useSpellingFunctionality"], ) self._appendSpeechModesList(settingsSizerHelper) @@ -1697,7 +1710,7 @@ def _appendSpeechModesList(self, settingsSizerHelper: guiHelper.BoxSizerHelper) # Translators: Label of the list where user can select speech modes that will be available. _("&Modes available in the Cycle speech mode command:"), nvdaControls.CustomCheckListBox, - choices=[mode.displayString for mode in self._allSpeechModes] + choices=[mode.displayString for mode in self._allSpeechModes], ) self.bindHelpEvent("SpeechModesDisabling", self.speechModesList) excludedModes = config.conf["speech"]["excludedSpeechModes"] @@ -1711,11 +1724,11 @@ def _appendDelayedCharacterDescriptions(self, settingsSizerHelper: guiHelper.Box # Translators: This is the label for a checkbox in the voice settings panel. delayedCharacterDescriptionsText = _("&Delayed descriptions for characters on cursor movement") self.delayedCharacterDescriptionsCheckBox = settingsSizerHelper.addItem( - wx.CheckBox(self, label=delayedCharacterDescriptionsText) + wx.CheckBox(self, label=delayedCharacterDescriptionsText), ) self.bindHelpEvent("delayedCharacterDescriptions", self.delayedCharacterDescriptionsCheckBox) self.delayedCharacterDescriptionsCheckBox.SetValue( - config.conf["speech"]["delayedCharacterDescriptions"] + config.conf["speech"]["delayedCharacterDescriptions"], ) def onSave(self): @@ -1759,7 +1772,7 @@ def _onSpeechModesListChange(self, evt: wx.CommandEvent): # Translators: Warning shown when 'talk' speech mode is disabled in settings. "You did not choose Talk as one of your speech mode options. " "Please note that this may result in no speech output at all. " - "Are you sure you want to continue?" + "Are you sure you want to continue?", ), # Translators: Title of the warning message. _("Warning"), @@ -1768,13 +1781,13 @@ def _onSpeechModesListChange(self, evt: wx.CommandEvent): ) == wx.NO: self.speechModesList.SetCheckedItems( list(self.speechModesList.GetCheckedItems()) - + [self._allSpeechModes.index(speech.SpeechMode.talk)] + + [self._allSpeechModes.index(speech.SpeechMode.talk)], ) def _onUnicodeNormalizationChange(self, evt: wx.CommandEvent): evt.Skip() self.reportNormalizedForCharacterNavigationCheckBox.Enable( - bool(self.unicodeNormalizationCombo._getControlCurrentFlag()) + bool(self.unicodeNormalizationCombo._getControlCurrentFlag()), ) def isValid(self) -> bool: @@ -1833,7 +1846,7 @@ def makeSettings(self, settingsSizer): self.charsCheckBox=sHelper.addItem(wx.CheckBox(self,label=charsText)) self.bindHelpEvent( "KeyboardSettingsSpeakTypedCharacters", - self.charsCheckBox + self.charsCheckBox, ) self.charsCheckBox.SetValue(config.conf["keyboard"]["speakTypedCharacters"]) @@ -1966,7 +1979,7 @@ def makeSettings(self, settingsSizer): # mouse settings panel. reportObjectPropertiesText = _("Report &object when mouse enters it") self.reportObjectPropertiesCheckBox = sHelper.addItem( - wx.CheckBox(self, label=reportObjectPropertiesText) + wx.CheckBox(self, label=reportObjectPropertiesText), ) self.bindHelpEvent("MouseSettingsRole", self.reportObjectPropertiesCheckBox) self.reportObjectPropertiesCheckBox.SetValue(config.conf["mouse"]["reportObjectRoleOnMouseEnter"]) @@ -2065,7 +2078,7 @@ def makeSettings(self, settingsSizer): self.candidateIncludesShortCharacterDescriptionCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Always include short character &description when announcing candidates")) self.bindHelpEvent( "InputCompositionCandidateIncludesShortCharacterDescription", - self.candidateIncludesShortCharacterDescriptionCheckBox + self.candidateIncludesShortCharacterDescriptionCheckBox, ) self.candidateIncludesShortCharacterDescriptionCheckBox.SetValue(config.conf["inputComposition"]["alwaysIncludeShortCharacterDescriptionInCandidateName"]) settingsSizer.Add(self.candidateIncludesShortCharacterDescriptionCheckBox,border=10,flag=wx.BOTTOM) @@ -2074,7 +2087,7 @@ def makeSettings(self, settingsSizer): self.reportReadingStringChangesCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Report changes to the &reading string")) self.bindHelpEvent( "InputCompositionReadingStringChanges", - self.reportReadingStringChangesCheckBox + self.reportReadingStringChangesCheckBox, ) self.reportReadingStringChangesCheckBox.SetValue(config.conf["inputComposition"]["reportReadingStringChanges"]) settingsSizer.Add(self.reportReadingStringChangesCheckBox,border=10,flag=wx.BOTTOM) @@ -2083,7 +2096,7 @@ def makeSettings(self, settingsSizer): self.reportCompositionStringChangesCheckBox=wx.CheckBox(self,wx.ID_ANY,label=_("Report changes to the &composition string")) self.bindHelpEvent( "InputCompositionCompositionStringChanges", - self.reportCompositionStringChangesCheckBox + self.reportCompositionStringChangesCheckBox, ) self.reportCompositionStringChangesCheckBox.SetValue(config.conf["inputComposition"]["reportCompositionStringChanges"]) settingsSizer.Add(self.reportCompositionStringChangesCheckBox,border=10,flag=wx.BOTTOM) @@ -2102,7 +2115,7 @@ class ObjectPresentationPanel(SettingsPanel): # Translators: This is a label appearing on the Object Presentation settings panel. "Configure how much information NVDA will present about controls." " These options apply to focus reporting and NVDA object navigation," - " but not when reading text content e.g. web content with browse mode." + " but not when reading text content e.g. web content with browse mode.", ) # Translators: This is the label for the object presentation panel. @@ -2131,7 +2144,7 @@ def makeSettings(self, settingsSizer): sHelper = guiHelper.BoxSizerHelper(self, sizer=settingsSizer) self.windowText = sHelper.addItem( - wx.StaticText(self, label=self.panelDescription) + wx.StaticText(self, label=self.panelDescription), ) self.windowText.Wrap(self.scaleSize(PANEL_DESCRIPTION_WIDTH)) @@ -2196,7 +2209,7 @@ def makeSettings(self, settingsSizer): self.reportBackgroundProgressBarsCheckBox=sHelper.addItem(wx.CheckBox(self,label=reportBackgroundProgressBarsText)) self.bindHelpEvent( "ObjectPresentationReportBackgroundProgressBars", - self.reportBackgroundProgressBarsCheckBox + self.reportBackgroundProgressBarsCheckBox, ) self.reportBackgroundProgressBarsCheckBox.SetValue(config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"]) @@ -2206,7 +2219,7 @@ def makeSettings(self, settingsSizer): self.dynamicContentCheckBox=sHelper.addItem(wx.CheckBox(self,label=dynamicContentText)) self.bindHelpEvent( "ObjectPresentationReportDynamicContent", - self.dynamicContentCheckBox + self.dynamicContentCheckBox, ) self.dynamicContentCheckBox.SetValue(config.conf["presentation"]["reportDynamicContentChanges"]) @@ -2216,7 +2229,7 @@ def makeSettings(self, settingsSizer): self.autoSuggestionSoundsCheckBox=sHelper.addItem(wx.CheckBox(self,label=autoSuggestionsLabelText)) self.bindHelpEvent( "ObjectPresentationSuggestionSounds", - self.autoSuggestionSoundsCheckBox + self.autoSuggestionSoundsCheckBox, ) self.autoSuggestionSoundsCheckBox.SetValue(config.conf["presentation"]["reportAutoSuggestionsWithSound"]) @@ -2242,19 +2255,23 @@ def makeSettings(self, settingsSizer): # Translators: This is the label for a textfield in the # browse mode settings panel. maxLengthLabelText = _("&Maximum number of characters on one line") - self.maxLengthEdit = sHelper.addLabeledControl(maxLengthLabelText, nvdaControls.SelectOnFocusSpinCtrl, - # min and max are not enforced in the config for virtualBuffers.maxLineLength - min=10, max=250, - initial=config.conf["virtualBuffers"]["maxLineLength"]) + self.maxLengthEdit = sHelper.addLabeledControl( + maxLengthLabelText, nvdaControls.SelectOnFocusSpinCtrl, + # min and max are not enforced in the config for virtualBuffers.maxLineLength + min=10, max=250, + initial=config.conf["virtualBuffers"]["maxLineLength"], + ) self.bindHelpEvent("BrowseModeSettingsMaxLength", self.maxLengthEdit) # Translators: This is the label for a textfield in the # browse mode settings panel. pageLinesLabelText = _("&Number of lines per page") - self.pageLinesEdit = sHelper.addLabeledControl(pageLinesLabelText, nvdaControls.SelectOnFocusSpinCtrl, - # min and max are not enforced in the config for virtualBuffers.linesPerPage - min=5, max=150, - initial=config.conf["virtualBuffers"]["linesPerPage"]) + self.pageLinesEdit = sHelper.addLabeledControl( + pageLinesLabelText, nvdaControls.SelectOnFocusSpinCtrl, + # min and max are not enforced in the config for virtualBuffers.linesPerPage + min=5, max=150, + initial=config.conf["virtualBuffers"]["linesPerPage"], + ) self.bindHelpEvent("BrowseModeSettingsPageLines", self.pageLinesEdit) # Translators: This is the label for a checkbox in the @@ -2291,7 +2308,7 @@ def makeSettings(self, settingsSizer): self.autoPassThroughOnFocusChangeCheckBox = sHelper.addItem(wx.CheckBox(self, label=autoPassThroughOnFocusChangeText)) self.bindHelpEvent( "BrowseModeSettingsAutoPassThroughOnFocusChange", - self.autoPassThroughOnFocusChangeCheckBox + self.autoPassThroughOnFocusChangeCheckBox, ) self.autoPassThroughOnFocusChangeCheckBox.SetValue(config.conf["virtualBuffers"]["autoPassThroughOnFocusChange"]) @@ -2301,7 +2318,7 @@ def makeSettings(self, settingsSizer): self.autoPassThroughOnCaretMoveCheckBox = sHelper.addItem(wx.CheckBox(self, label=autoPassThroughOnCaretMoveText)) self.bindHelpEvent( "BrowseModeSettingsAutoPassThroughOnCaretMove", - self.autoPassThroughOnCaretMoveCheckBox + self.autoPassThroughOnCaretMoveCheckBox, ) self.autoPassThroughOnCaretMoveCheckBox.SetValue(config.conf["virtualBuffers"]["autoPassThroughOnCaretMove"]) @@ -2311,7 +2328,7 @@ def makeSettings(self, settingsSizer): self.passThroughAudioIndicationCheckBox = sHelper.addItem(wx.CheckBox(self, label=passThroughAudioIndicationText)) self.bindHelpEvent( "BrowseModeSettingsPassThroughAudioIndication", - self.passThroughAudioIndicationCheckBox + self.passThroughAudioIndicationCheckBox, ) self.passThroughAudioIndicationCheckBox.SetValue(config.conf["virtualBuffers"]["passThroughAudioIndication"]) @@ -2321,7 +2338,7 @@ def makeSettings(self, settingsSizer): self.trapNonCommandGesturesCheckBox = sHelper.addItem(wx.CheckBox(self, label=trapNonCommandGesturesText)) self.bindHelpEvent( "BrowseModeSettingsTrapNonCommandGestures", - self.trapNonCommandGesturesCheckBox + self.trapNonCommandGesturesCheckBox, ) self.trapNonCommandGesturesCheckBox.SetValue(config.conf["virtualBuffers"]["trapNonCommandGestures"]) @@ -2329,14 +2346,14 @@ def makeSettings(self, settingsSizer): # browse mode settings panel. autoFocusFocusableElementsText = _("Automatically set system &focus to focusable elements") self.autoFocusFocusableElementsCheckBox = sHelper.addItem( - wx.CheckBox(self, label=autoFocusFocusableElementsText) + wx.CheckBox(self, label=autoFocusFocusableElementsText), ) self.bindHelpEvent( "BrowseModeSettingsAutoFocusFocusableElements", - self.autoFocusFocusableElementsCheckBox + self.autoFocusFocusableElementsCheckBox, ) self.autoFocusFocusableElementsCheckBox.SetValue( - config.conf["virtualBuffers"]["autoFocusFocusableElements"] + config.conf["virtualBuffers"]["autoFocusFocusableElements"], ) def onSave(self): @@ -2398,10 +2415,10 @@ def makeSettings(self, settingsSizer): # document formatting settings panel. superscriptsAndSubscriptsText = _("Su&perscripts and subscripts") self.superscriptsAndSubscriptsCheckBox = fontGroup.addItem( - wx.CheckBox(fontGroupBox, label=superscriptsAndSubscriptsText) + wx.CheckBox(fontGroupBox, label=superscriptsAndSubscriptsText), ) self.superscriptsAndSubscriptsCheckBox.SetValue( - config.conf["documentFormatting"]["reportSuperscriptsAndSubscripts"] + config.conf["documentFormatting"]["reportSuperscriptsAndSubscripts"], ) # Translators: This is the label for a checkbox in the @@ -2414,10 +2431,10 @@ def makeSettings(self, settingsSizer): # document formatting settings panel. highlightText = _("Highlighted (mar&ked) text") self.highlightCheckBox = fontGroup.addItem( - wx.CheckBox(fontGroupBox, label=highlightText) + wx.CheckBox(fontGroupBox, label=highlightText), ) self.highlightCheckBox.SetValue( - config.conf["documentFormatting"]["reportHighlight"] + config.conf["documentFormatting"]["reportHighlight"], ) # Translators: This is the label for a checkbox in the @@ -2494,7 +2511,7 @@ def makeSettings(self, settingsSizer): ) self.bindHelpEvent( "DocumentFormattingSettingsLineIndentation", - self.lineIndentationCombo + self.lineIndentationCombo, ) self.lineIndentationCombo.Bind(wx.EVT_CHOICE, self._onLineIndentationChange) reportLineIndentation = config.conf['documentFormatting']['reportLineIndentation'] @@ -2507,7 +2524,7 @@ def makeSettings(self, settingsSizer): self.ignoreBlankLinesRLICheckbox = pageAndSpaceGroup.addItem(ignoreBlankLinesCheckBox) self.bindHelpEvent( "DocumentFormattingSettingsLineIndentation", - self.ignoreBlankLinesRLICheckbox + self.ignoreBlankLinesRLICheckbox, ) self.ignoreBlankLinesRLICheckbox.SetValue(config.conf["documentFormatting"]["ignoreBlankLinesForRLI"]) self.ignoreBlankLinesRLICheckbox.Enable(reportLineIndentation != 0) @@ -2567,7 +2584,7 @@ def makeSettings(self, settingsSizer): # document formatting settings panel. _("Cell &borders:"), wx.Choice, - choices=borderChoices + choices=borderChoices, ) self.borderComboBox.SetSelection(config.conf["documentFormatting"]["reportCellBorders"]) @@ -2630,7 +2647,8 @@ def makeSettings(self, settingsSizer): self.figuresCheckBox = elementsGroup.addItem( # Translators: This is the label for a checkbox in the # document formatting settings panel. - wx.CheckBox(elementsGroupBox, label=_("&Figures and captions"))) + wx.CheckBox(elementsGroupBox, label=_("&Figures and captions")), + ) self.figuresCheckBox.Value = config.conf["documentFormatting"]["reportFigures"] # Translators: This is the label for a checkbox in the @@ -2644,7 +2662,7 @@ def makeSettings(self, settingsSizer): self.detectFormatAfterCursorCheckBox = wx.CheckBox(self, label=detectFormatAfterCursorText) self.bindHelpEvent( "DocumentFormattingDetectFormatAfterCursor", - self.detectFormatAfterCursorCheckBox + self.detectFormatAfterCursorCheckBox, ) self.detectFormatAfterCursorCheckBox.SetValue(config.conf["documentFormatting"]["detectFormatAfterCursor"]) sHelper.addItem(self.detectFormatAfterCursorCheckBox) @@ -2705,7 +2723,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer) -> None: labelText=paragraphStyleLabel, wxCtrlClass=nvdaControls.FeatureFlagCombo, keyPath=["documentNavigation", "paragraphStyle"], - conf=config.conf + conf=config.conf, ) self.bindHelpEvent("ParagraphStyle", self.paragraphStyleCombo) @@ -2754,7 +2772,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer) -> None: self.duckingList = sHelper.addLabeledControl( duckingListLabelText, wx.Choice, - choices=[mode.displayString for mode in audioDucking.AudioDuckingMode] + choices=[mode.displayString for mode in audioDucking.AudioDuckingMode], ) self.bindHelpEvent("SelectSynthesizerDuckingMode", self.duckingList) index = config.conf["audio"]["audioDuckingMode"] @@ -2777,7 +2795,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer) -> None: label, nvdaControls.EnhancedInputSlider, minValue=0, - maxValue=100 + maxValue=100, ) self.bindHelpEvent("SoundVolume", self.soundVolSlider) self.soundVolSlider.SetValue(config.conf["audio"]["soundVolume"]) @@ -2787,7 +2805,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer) -> None: self.soundSplitComboBox = sHelper.addLabeledControl( soundSplitLabelText, wx.Choice, - choices=[mode.displayString for mode in audio.SoundSplitState] + choices=[mode.displayString for mode in audio.SoundSplitState], ) self.bindHelpEvent("SelectSoundSplitMode", self.soundSplitComboBox) index = config.conf["audio"]["soundSplitState"] @@ -2800,7 +2818,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer) -> None: audioAwakeTimeLabelText = _( # Translators: The label for a setting in Audio settings panel # to change how long the audio device is kept awake after speech - "Time to &keep audio device awake after speech (seconds)" + "Time to &keep audio device awake after speech (seconds)", ) minTime = int(config.conf.getConfigValidation(("audio", "audioAwakeTime")).kwargs["min"]) maxTime = int(config.conf.getConfigValidation(("audio", "audioAwakeTime")).kwargs["max"]) @@ -2809,7 +2827,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer) -> None: nvdaControls.SelectOnFocusSpinCtrl, min=minTime, max=maxTime, - initial=config.conf["audio"]["audioAwakeTime"] + initial=config.conf["audio"]["audioAwakeTime"], ) self.bindHelpEvent("AudioAwakeTime", self.audioAwakeTimeEdit) self.audioAwakeTimeEdit.Enable(nvwave.usingWasapiWavePlayer()) @@ -2820,7 +2838,7 @@ def _appendSoundSplitModesList(self, settingsSizerHelper: guiHelper.BoxSizerHelp # Translators: Label of the list where user can select sound split modes that will be available. _("&Modes available in the 'Cycle sound split mode' command:"), nvdaControls.CustomCheckListBox, - choices=[mode.displayString for mode in self._allSoundSplitModes] + choices=[mode.displayString for mode in self._allSoundSplitModes], ) self.bindHelpEvent("CustomizeSoundSplitModes", self.soundSplitModesList) includedModes: list[int] = config.conf["audio"]["includedSoundSplitModes"] @@ -2871,7 +2889,7 @@ def _onSoundVolChange(self, event: wx.Event) -> None: self.soundVolFollowCheckBox.Enable(wasapi) self.soundVolSlider.Enable( wasapi - and not self.soundVolFollowCheckBox.IsChecked() + and not self.soundVolFollowCheckBox.IsChecked(), ) self.soundSplitComboBox.Enable(wasapi) self.soundSplitModesList.Enable(wasapi) @@ -2905,7 +2923,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer) -> None: self.automaticUpdatesComboBox = sHelper.addLabeledControl( automaticUpdatesLabelText, wx.Choice, - choices=[mode.displayString for mode in AddonsAutomaticUpdate] + choices=[mode.displayString for mode in AddonsAutomaticUpdate], ) self.bindHelpEvent("AutomaticAddonUpdates", self.automaticUpdatesComboBox) index = [x.value for x in AddonsAutomaticUpdate].index(config.conf["addonStore"]["automaticUpdates"]) @@ -2973,7 +2991,7 @@ def makeSettings(self, settingsSizer): # Translators: Label for an option in the Windows OCR settings panel. autoRefreshText = _("Periodically &refresh recognized content") self.autoRefreshCheckbox = sHelper.addItem( - wx.CheckBox(self, label=autoRefreshText) + wx.CheckBox(self, label=autoRefreshText), ) self.bindHelpEvent("Win10OcrSettingsAutoRefresh", self.autoRefreshCheckbox) self.autoRefreshCheckbox.SetValue(config.conf["uwpOcr"]["autoRefresh"]) @@ -3017,7 +3035,7 @@ def __init__(self, parent): self.scratchpadCheckBox.defaultValue = self._getDefaultValue(["development", "enableScratchpadDir"]) self.scratchpadCheckBox.Bind( wx.EVT_CHECKBOX, - lambda evt: self.openScratchpadButton.Enable(evt.IsChecked()) + lambda evt: self.openScratchpadButton.Enable(evt.IsChecked()), ) if config.isAppX: self.scratchpadCheckBox.Disable() @@ -3055,36 +3073,36 @@ def __init__(self, parent): # Translators: A choice in a combo box in the advanced settings # panel to have NVDA register for all UI Automation events # in all cases. - _("Global") + _("Global"), ] #: The possible event registration config values, in the order they appear #: in the combo box. self.selectiveUIAEventRegistrationVals = ( "auto", "selective", - "global" + "global", ) self.selectiveUIAEventRegistrationCombo = UIAGroup.addLabeledControl( selectiveUIAEventRegistrationComboText, wx.Choice, - choices=selectiveUIAEventRegistrationChoices + choices=selectiveUIAEventRegistrationChoices, ) self.bindHelpEvent( "AdvancedSettingsSelectiveUIAEventRegistration", - self.selectiveUIAEventRegistrationCombo + self.selectiveUIAEventRegistrationCombo, ) curChoice = self.selectiveUIAEventRegistrationVals.index( - config.conf['UIA']['eventRegistration'] + config.conf['UIA']['eventRegistration'], ) self.selectiveUIAEventRegistrationCombo.SetSelection(curChoice) self.selectiveUIAEventRegistrationCombo.defaultValue = self.selectiveUIAEventRegistrationVals.index( - self._getDefaultValue(["UIA", "eventRegistration"]) + self._getDefaultValue(["UIA", "eventRegistration"]), ) label = pgettext( "advanced.uiaWithMSWord", # Translators: Label for the Use UIA with MS Word combobox, in the Advanced settings panel. - "Use UI Automation to access Microsoft &Word document controls" + "Use UI Automation to access Microsoft &Word document controls", ) wordChoices = ( # Translators: Label for the default value of the Use UIA with MS Word combobox, @@ -3124,30 +3142,30 @@ def __init__(self, parent): # Translators: A choice in a combo box in the advanced settings # panel to have NVDA use its legacy Windows Console support # in all cases. - _("Legacy") + _("Legacy"), ] #: The possible console config values, in the order they appear #: in the combo box. self.consoleVals = ( "auto", "UIA", - "legacy" + "legacy", ) self.consoleCombo = UIAGroup.addLabeledControl(consoleComboText, wx.Choice, choices=consoleChoices) self.bindHelpEvent("AdvancedSettingsConsoleUIA", self.consoleCombo) curChoice = self.consoleVals.index( - config.conf['UIA']['winConsoleImplementation'] + config.conf['UIA']['winConsoleImplementation'], ) self.consoleCombo.SetSelection(curChoice) self.consoleCombo.defaultValue = self.consoleVals.index( - self._getDefaultValue(["UIA", "winConsoleImplementation"]) + self._getDefaultValue(["UIA", "winConsoleImplementation"]), ) label = pgettext( "advanced.uiaWithChromium", # Translators: Label for the Use UIA with Chromium combobox, in the Advanced settings panel. # Note the '\n' is used to split this long label approximately in half. - "Use UIA with Microsoft Edge and other \n&Chromium based browsers when available:" + "Use UIA with Microsoft Edge and other \n&Chromium based browsers when available:", ) chromiumChoices = ( # Translators: Label for the default value of the Use UIA with Chromium combobox, @@ -3167,12 +3185,14 @@ def __init__(self, parent): # Translators: This is the label for a COMBOBOX in the Advanced settings panel. label = _("Use en&hanced event processing (requires restart)") - self.enhancedEventProcessingComboBox = cast(nvdaControls.FeatureFlagCombo, UIAGroup.addLabeledControl( - labelText=label, - wxCtrlClass=nvdaControls.FeatureFlagCombo, - keyPath=["UIA", "enhancedEventProcessing"], - conf=config.conf, - )) + self.enhancedEventProcessingComboBox = cast( + nvdaControls.FeatureFlagCombo, UIAGroup.addLabeledControl( + labelText=label, + wxCtrlClass=nvdaControls.FeatureFlagCombo, + keyPath=["UIA", "enhancedEventProcessing"], + conf=config.conf, + ), + ) self.bindHelpEvent("UIAEnhancedEventProcessing", self.enhancedEventProcessingComboBox) # Translators: This is the label for a group of advanced options in the @@ -3195,7 +3215,7 @@ def __init__(self, parent): # Advanced settings panel. label = _("Report aria-description always") self.ariaDescCheckBox: wx.CheckBox = AnnotationsGroup.addItem( - wx.CheckBox(AnnotationsBox, label=label) + wx.CheckBox(AnnotationsBox, label=label), ) self.ariaDescCheckBox.SetValue(config.conf["annotations"]["reportAriaDescription"]) self.ariaDescCheckBox.defaultValue = self._getDefaultValue(["annotations", "reportAriaDescription"]) @@ -3256,29 +3276,29 @@ def __init__(self, parent): # Translators: A choice in a combo box in the advanced settings # panel to have NVDA detect changes in terminals # by line, using the difflib algorithm. - _("Difflib") + _("Difflib"), ] #: The possible diffAlgo config values, in the order they appear #: in the combo box. self.diffAlgoVals = ( "auto", "dmp", - "difflib" + "difflib", ) self.diffAlgoCombo = terminalsGroup.addLabeledControl(diffAlgoComboText, wx.Choice, choices=diffAlgoChoices) self.bindHelpEvent("DiffAlgo", self.diffAlgoCombo) curChoice = self.diffAlgoVals.index( - config.conf['terminals']['diffAlgo'] + config.conf['terminals']['diffAlgo'], ) self.diffAlgoCombo.SetSelection(curChoice) self.diffAlgoCombo.defaultValue = self.diffAlgoVals.index( - self._getDefaultValue(["terminals", "diffAlgo"]) + self._getDefaultValue(["terminals", "diffAlgo"]), ) self.wtStrategyCombo: nvdaControls.FeatureFlagCombo = terminalsGroup.addLabeledControl( labelText=_( # Translators: This is the label for a combo-box in the Advanced settings panel. - "Speak new text in Windows Terminal via:" + "Speak new text in Windows Terminal via:", ), wxCtrlClass=nvdaControls.FeatureFlagCombo, keyPath=["terminals", "wtStrategy"], @@ -3310,14 +3330,14 @@ def __init__(self, parent): self.cancelExpiredFocusSpeechCombo: wx.Choice = speechGroup.addLabeledControl( cancelExpiredFocusSpeechText, wx.Choice, - choices=expiredFocusSpeechChoices + choices=expiredFocusSpeechChoices, ) self.bindHelpEvent("CancelExpiredFocusSpeech", self.cancelExpiredFocusSpeechCombo) self.cancelExpiredFocusSpeechCombo.SetSelection( - config.conf["featureFlag"]["cancelExpiredFocusSpeech"] + config.conf["featureFlag"]["cancelExpiredFocusSpeech"], ) self.cancelExpiredFocusSpeechCombo.defaultValue = self._getDefaultValue( - ["featureFlag", "cancelExpiredFocusSpeech"] + ["featureFlag", "cancelExpiredFocusSpeech"], ) # Translators: This is the label for a group of advanced options in the @@ -3330,7 +3350,7 @@ def __init__(self, parent): self.loadChromeVBufWhenBusyCombo: nvdaControls.FeatureFlagCombo = vBufGroup.addLabeledControl( labelText=_( # Translators: This is the label for a combo-box in the Advanced settings panel. - "Load Chromium virtual buffer when document busy." + "Load Chromium virtual buffer when document busy.", ), wxCtrlClass=nvdaControls.FeatureFlagCombo, keyPath=["virtualBuffers", "loadChromiumVBufOnBusyState"], @@ -3352,7 +3372,7 @@ def __init__(self, parent): nvdaControls.SelectOnFocusSpinCtrl, min=0, max=2000, - initial=config.conf["editableText"]["caretMoveTimeoutMs"] + initial=config.conf["editableText"]["caretMoveTimeoutMs"], ) self.bindHelpEvent("AdvancedSettingsCaretMoveTimeout", self.caretMoveTimeoutSpinControl) self.caretMoveTimeoutSpinControl.defaultValue = self._getDefaultValue(["editableText", "caretMoveTimeoutMs"]) @@ -3369,14 +3389,15 @@ def __init__(self, parent): # Advanced settings panel. label = _("Report transparent color values") self.reportTransparentColorCheckBox: wx.CheckBox = docFormattingGroup.addItem( - wx.CheckBox(docFormattingBox, label=label) + wx.CheckBox(docFormattingBox, label=label), ) self.bindHelpEvent("ReportTransparentColors", self.reportTransparentColorCheckBox) self.reportTransparentColorCheckBox.SetValue( - config.conf["documentFormatting"]["reportTransparentColor"] + config.conf["documentFormatting"]["reportTransparentColor"], ) self.reportTransparentColorCheckBox.defaultValue = self._getDefaultValue( - ["documentFormatting", "reportTransparentColor"]) + ["documentFormatting", "reportTransparentColor"], + ) # Translators: This is the label for a group of advanced options in the # Advanced settings panel @@ -3388,12 +3409,14 @@ def __init__(self, parent): # Translators: This is the label for a checkbox control in the Advanced settings panel. label = _("Use WASAPI for audio output (requires restart)") - self.wasapiComboBox = cast(nvdaControls.FeatureFlagCombo, audioGroup.addLabeledControl( - labelText=label, - wxCtrlClass=nvdaControls.FeatureFlagCombo, - keyPath=["audio", "WASAPI"], - conf=config.conf, - )) + self.wasapiComboBox = cast( + nvdaControls.FeatureFlagCombo, audioGroup.addLabeledControl( + labelText=label, + wxCtrlClass=nvdaControls.FeatureFlagCombo, + keyPath=["audio", "WASAPI"], + conf=config.conf, + ), + ) self.bindHelpEvent("WASAPI", self.wasapiComboBox) # Translators: This is the label for a group of advanced options in the @@ -3426,7 +3449,7 @@ def __init__(self, parent): self.logCategoriesList=debugLogGroup.addLabeledControl( logCategoriesLabel, nvdaControls.CustomCheckListBox, - choices=self.logCategories + choices=self.logCategories, ) self.bindHelpEvent("AdvancedSettingsDebugLoggingCategories", self.logCategoriesList) self.logCategoriesList.CheckedItems = [ @@ -3435,8 +3458,8 @@ def __init__(self, parent): self.logCategoriesList.Select(0) self.logCategoriesList.defaultCheckedItems = [ index for index, x in enumerate(self.logCategories) if bool( - self._getDefaultValue(['debugLog', x]) - ) + self._getDefaultValue(['debugLog', x]), + ) ] # Translators: Label for the Play a sound for logged errors combobox, in the Advanced settings panel. @@ -3521,7 +3544,7 @@ def haveConfigDefaultsBeenRestored(self): def restoreToDefaults(self): self.scratchpadCheckBox.SetValue(self.scratchpadCheckBox.defaultValue) self.selectiveUIAEventRegistrationCombo.SetSelection( - self.selectiveUIAEventRegistrationCombo.defaultValue + self.selectiveUIAEventRegistrationCombo.defaultValue, ) self.UIAInMSWordCombo.SetSelection(self.UIAInMSWordCombo.defaultValue) self.UIAInMSExcelCheckBox.SetValue(self.UIAInMSExcelCheckBox.defaultValue) @@ -3601,7 +3624,7 @@ class AdvancedPanel(SettingsPanel): "The following settings are for advanced users. " "Changing them may cause NVDA to function incorrectly. " "Please only change these if you know what you are doing or " - "have been specifically instructed by NVDA developers." + "have been specifically instructed by NVDA developers.", ) panelDescription = u"{}\n{}".format(warningHeader, warningExplanation) @@ -3625,10 +3648,10 @@ def makeSettings(self, settingsSizer): enableAdvancedControlslabel = _( # Translators: This is the label for a checkbox in the Advanced settings panel. - "I understand that changing these settings may cause NVDA to function incorrectly." + "I understand that changing these settings may cause NVDA to function incorrectly.", ) self.enableControlsCheckBox = warningGroup.addItem( - wx.CheckBox(parent=warningBox, label=enableAdvancedControlslabel, id=wx.NewIdRef()) + wx.CheckBox(parent=warningBox, label=enableAdvancedControlslabel, id=wx.NewIdRef()), ) boldedFont = self.enableControlsCheckBox.GetFont().Bold() self.enableControlsCheckBox.SetFont(boldedFont) @@ -3636,7 +3659,7 @@ def makeSettings(self, settingsSizer): restoreDefaultsButton = warningGroup.addItem( # Translators: This is the label for a button in the Advanced settings panel - wx.Button(warningBox, label=_("Restore defaults")) + wx.Button(warningBox, label=_("Restore defaults")), ) self.bindHelpEvent("AdvancedSettingsRestoringDefaults", restoreDefaultsButton) restoreDefaultsButton.Bind(wx.EVT_BUTTON, lambda evt: self.advancedControls.restoreToDefaults()) @@ -3646,7 +3669,7 @@ def makeSettings(self, settingsSizer): self.enableControlsCheckBox.Bind( wx.EVT_CHECKBOX, - self.onEnableControlsCheckBox + self.onEnableControlsCheckBox, ) self.advancedControls.Enable(self.enableControlsCheckBox.IsChecked()) @@ -3692,7 +3715,7 @@ def makeSettings(self, settingsSizer): self.displayNameCtrl = ExpandoTextCtrl( displayBox, size=(self.scaleSize(250), -1), - style=wx.TE_READONLY + style=wx.TE_READONLY, ) self.bindHelpEvent("BrailleSettingsChange", self.displayNameCtrl) self.updateCurrentDisplay() @@ -3703,8 +3726,8 @@ def makeSettings(self, settingsSizer): displayGroup.addItem( guiHelper.associateElements( self.displayNameCtrl, - changeDisplayBtn - ) + changeDisplayBtn, + ), ) self.displayNameCtrl.Bind(wx.EVT_CHAR_HOOK, self._enterTriggersOnChangeDisplay) changeDisplayBtn.Bind(wx.EVT_BUTTON,self.onChangeDisplay) @@ -3771,7 +3794,7 @@ def makeSettings(self, settingsSizer): self.autoDetectList = sHelper.addLabeledControl( autoDetectLabelText, nvdaControls.CustomCheckListBox, - choices=[] + choices=[], ) self.bindHelpEvent("SelectBrailleDisplayAutoDetect", self.autoDetectList) @@ -3886,7 +3909,7 @@ def onOk(self, evt): # braille display. caption=_("Braille Display Error"), style=wx.OK | wx.ICON_WARNING, - parent=self + parent=self, ) return @@ -3932,7 +3955,7 @@ def makeSettings(self, settingsSizer): if shouldDebugGui: timePassed = time.time() - startTime log.debug( - f"Loading output tables completed, now at {timePassed:.2f} seconds from start" + f"Loading output tables completed, now at {timePassed:.2f} seconds from start", ) # Translators: The label for a setting in braille settings to select the input table (the braille table used to type braille characters on a braille keyboard). @@ -3949,7 +3972,7 @@ def makeSettings(self, settingsSizer): if shouldDebugGui: timePassed = time.time() - startTime log.debug( - f"Loading input tables completed, now at {timePassed:.2f} seconds from start" + f"Loading input tables completed, now at {timePassed:.2f} seconds from start", ) # Translators: The label for a setting in braille settings to select which braille mode to use modeListText = _("Braille mode:") @@ -3970,7 +3993,7 @@ def makeSettings(self, settingsSizer): # Translators: The label for a setting in braille settings to expand the current word under cursor to computer braille. expandAtCursorText = _("E&xpand to computer braille for the word at the cursor") self.expandAtCursorCheckBox = followCursorGroupHelper.addItem( - wx.CheckBox(self.followCursorGroupBox, wx.ID_ANY, label=expandAtCursorText) + wx.CheckBox(self.followCursorGroupBox, wx.ID_ANY, label=expandAtCursorText), ) self.bindHelpEvent("BrailleSettingsExpandToComputerBraille", self.expandAtCursorCheckBox) self.expandAtCursorCheckBox.SetValue(config.conf["braille"]["expandAtCursor"]) @@ -3978,7 +4001,7 @@ def makeSettings(self, settingsSizer): # Translators: The label for a setting in braille settings to show the cursor. showCursorLabelText = _("&Show cursor") self.showCursorCheckBox = followCursorGroupHelper.addItem( - wx.CheckBox(self.followCursorGroupBox, label=showCursorLabelText) + wx.CheckBox(self.followCursorGroupBox, label=showCursorLabelText), ) self.bindHelpEvent("BrailleSettingsShowCursor", self.showCursorCheckBox) self.showCursorCheckBox.Bind(wx.EVT_CHECKBOX, self.onShowCursorChange) @@ -3987,7 +4010,7 @@ def makeSettings(self, settingsSizer): # Translators: The label for a setting in braille settings to enable cursor blinking. cursorBlinkLabelText = _("Blink cursor") self.cursorBlinkCheckBox = followCursorGroupHelper.addItem( - wx.CheckBox(self.followCursorGroupBox, label=cursorBlinkLabelText) + wx.CheckBox(self.followCursorGroupBox, label=cursorBlinkLabelText), ) self.bindHelpEvent("BrailleSettingsBlinkCursor", self.cursorBlinkCheckBox) self.cursorBlinkCheckBox.Bind(wx.EVT_CHECKBOX, self.onBlinkCursorChange) @@ -3997,16 +4020,18 @@ def makeSettings(self, settingsSizer): # Translators: The label for a setting in braille settings to change cursor blink rate in milliseconds (1 second is 1000 milliseconds). cursorBlinkRateLabelText = _("Cursor blink rate (ms)") - minBlinkRate = int(config.conf.getConfigValidation( - ("braille", "cursorBlinkRate") - ).kwargs["min"]) + minBlinkRate = int( + config.conf.getConfigValidation( + ("braille", "cursorBlinkRate"), + ).kwargs["min"], + ) maxBlinkRate = int(config.conf.getConfigValidation(("braille", "cursorBlinkRate")).kwargs["max"]) self.cursorBlinkRateEdit = followCursorGroupHelper.addLabeledControl( cursorBlinkRateLabelText, nvdaControls.SelectOnFocusSpinCtrl, min=minBlinkRate, max=maxBlinkRate, - initial=config.conf["braille"]["cursorBlinkRate"] + initial=config.conf["braille"]["cursorBlinkRate"], ) self.bindHelpEvent("BrailleSettingsBlinkRate", self.cursorBlinkRateEdit) if not self.showCursorCheckBox.GetValue() or not self.cursorBlinkCheckBox.GetValue() : @@ -4020,7 +4045,7 @@ def makeSettings(self, settingsSizer): self.cursorShapeFocusList = followCursorGroupHelper.addLabeledControl( cursorShapeFocusLabelText, wx.Choice, - choices=cursorShapeChoices + choices=cursorShapeChoices, ) self.bindHelpEvent("BrailleSettingsCursorShapeForFocus", self.cursorShapeFocusList) try: @@ -4036,7 +4061,7 @@ def makeSettings(self, settingsSizer): self.cursorShapeReviewList = followCursorGroupHelper.addLabeledControl( cursorShapeReviewLabelText, wx.Choice, - choices=cursorShapeChoices + choices=cursorShapeChoices, ) self.bindHelpEvent("BrailleSettingsCursorShapeForReview", self.cursorShapeReviewList) try: @@ -4062,12 +4087,16 @@ def makeSettings(self, settingsSizer): self.showMessagesList.Bind(wx.EVT_CHOICE, self.onShowMessagesChange) self.showMessagesList.SetSelection(config.conf['braille']['showMessages']) - minTimeout = int(config.conf.getConfigValidation( - ("braille", "messageTimeout") - ).kwargs["min"]) - maxTimeOut = int(config.conf.getConfigValidation( - ("braille", "messageTimeout") - ).kwargs["max"]) + minTimeout = int( + config.conf.getConfigValidation( + ("braille", "messageTimeout"), + ).kwargs["min"], + ) + maxTimeOut = int( + config.conf.getConfigValidation( + ("braille", "messageTimeout"), + ).kwargs["max"], + ) # Translators: The label for a setting in braille settings to change how long a message stays on the braille display (in seconds). messageTimeoutText = _("Message &timeout (sec)") self.messageTimeoutEdit = followCursorGroupHelper.addLabeledControl( @@ -4075,7 +4104,7 @@ def makeSettings(self, settingsSizer): nvdaControls.SelectOnFocusSpinCtrl, min=minTimeout, max=maxTimeOut, - initial=config.conf["braille"]["messageTimeout"] + initial=config.conf["braille"]["messageTimeout"], ) self.bindHelpEvent("BrailleSettingsMessageTimeout", self.messageTimeoutEdit) if self.showMessagesList.GetSelection() != ShowMessages.USE_TIMEOUT: @@ -4092,7 +4121,7 @@ def makeSettings(self, settingsSizer): self.tetherList = followCursorGroupHelper.addLabeledControl( tetherListText, wx.Choice, - choices=tetherChoices + choices=tetherChoices, ) self.bindHelpEvent("BrailleTether", self.tetherList) self.tetherList.Bind(wx.EVT_CHOICE, self.onTetherToChange) @@ -4106,7 +4135,7 @@ def makeSettings(self, settingsSizer): followCursorGroupHelper.addLabeledControl( labelText=_( # Translators: This is a label for a combo-box in the Braille settings panel. - "Move system caret when ro&uting review cursor" + "Move system caret when ro&uting review cursor", ), wxCtrlClass=nvdaControls.FeatureFlagCombo, keyPath=["braille", "reviewRoutingMovesSystemCaret"], @@ -4115,7 +4144,7 @@ def makeSettings(self, settingsSizer): ) self.bindHelpEvent( "BrailleSettingsReviewRoutingMovesSystemCaret", - self.brailleReviewRoutingMovesSystemCaretCombo + self.brailleReviewRoutingMovesSystemCaretCombo, ) # Setting has no effect when braille is tethered to focus. if tetherChoice == TetherTo.FOCUS.value: @@ -4124,7 +4153,7 @@ def makeSettings(self, settingsSizer): # Translators: The label for a setting in braille settings to read by paragraph (if it is checked, the commands to move the display by lines moves the display by paragraphs instead). readByParagraphText = _("Read by ¶graph") self.readByParagraphCheckBox = followCursorGroupHelper.addItem( - wx.CheckBox(self.followCursorGroupBox, label=readByParagraphText) + wx.CheckBox(self.followCursorGroupBox, label=readByParagraphText), ) self.bindHelpEvent("BrailleSettingsReadByParagraph", self.readByParagraphCheckBox) self.readByParagraphCheckBox.Value = config.conf["braille"]["readByParagraph"] @@ -4136,7 +4165,7 @@ def makeSettings(self, settingsSizer): self.focusContextPresentationList = followCursorGroupHelper.addLabeledControl( focusContextPresentationLabelText, wx.Choice, - choices=focusContextPresentationChoices + choices=focusContextPresentationChoices, ) self.bindHelpEvent("BrailleSettingsFocusContextPresentation", self.focusContextPresentationList) try: @@ -4148,7 +4177,7 @@ def makeSettings(self, settingsSizer): self.brailleShowSelectionCombo: nvdaControls.FeatureFlagCombo = followCursorGroupHelper.addLabeledControl( labelText=_( # Translators: This is a label for a combo-box in the Braille settings panel. - "Show se&lection" + "Show se&lection", ), wxCtrlClass=nvdaControls.FeatureFlagCombo, keyPath=["braille", "showSelection"], @@ -4156,7 +4185,7 @@ def makeSettings(self, settingsSizer): ) self.bindHelpEvent("BrailleSettingsShowSelection", self.brailleShowSelectionCombo) self.followCursorGroupBox.Enable( - list(braille.BrailleMode)[self.brailleModes.GetSelection()] is braille.BrailleMode.FOLLOW_CURSORS + list(braille.BrailleMode)[self.brailleModes.GetSelection()] is braille.BrailleMode.FOLLOW_CURSORS, ) # Translators: The label for a setting in braille settings to enable word wrap @@ -4169,7 +4198,7 @@ def makeSettings(self, settingsSizer): self.unicodeNormalizationCombo: nvdaControls.FeatureFlagCombo = sHelper.addLabeledControl( labelText=_( # Translators: This is a label for a combo-box in the Braille settings panel. - "Unicode normali&zation" + "Unicode normali&zation", ), wxCtrlClass=nvdaControls.FeatureFlagCombo, keyPath=["braille", "unicodeNormalization"], @@ -4180,7 +4209,7 @@ def makeSettings(self, settingsSizer): self.brailleInterruptSpeechCombo: nvdaControls.FeatureFlagCombo = sHelper.addLabeledControl( labelText=_( # Translators: This is a label for a combo-box in the Braille settings panel. - "I&nterrupt speech while scrolling" + "I&nterrupt speech while scrolling", ), wxCtrlClass=nvdaControls.FeatureFlagCombo, keyPath=["braille", "interruptSpeechWhileScrolling"], @@ -4253,14 +4282,14 @@ def showStartErrorForProviders( # Translators: This message is presented when # NVDA is unable to load a single vision enhancement provider. message = _("Could not load the {providerName} vision enhancement provider").format( - providerName=providerName + providerName=providerName, ) else: providerNames = ", ".join(provider.displayName for provider in providers) # Translators: This message is presented when NVDA is unable to # load multiple vision enhancement providers. message = _("Could not load the following vision enhancement providers:\n{providerNames}").format( - providerNames=providerNames + providerNames=providerNames, ) gui.messageBox( message, @@ -4283,7 +4312,7 @@ def showTerminationErrorForProviders( # Translators: This message is presented when # NVDA is unable to gracefully terminate a single vision enhancement provider. message = _("Could not gracefully terminate the {providerName} vision enhancement provider").format( - providerName=providerName + providerName=providerName, ) else: providerNames = ", ".join(provider.displayName for provider in providers) @@ -4291,7 +4320,7 @@ def showTerminationErrorForProviders( # Translators: This message is presented when # NVDA is unable to terminate multiple vision enhancement providers. "Could not gracefully terminate the following vision enhancement providers:\n" - "{providerNames}" + "{providerNames}", ).format(providerNames=providerNames) gui.messageBox( message, @@ -4311,7 +4340,7 @@ class VisionProviderStateControl(vision.providerBase.VisionProviderStateControl) def __init__( self, parent: wx.Window, - providerInfo: vision.providerInfo.ProviderInfo + providerInfo: vision.providerInfo.ProviderInfo, ): self._providerInfo = providerInfo self._parent = weakref.ref(parent) # don't keep parent dialog alive with a circular reference. @@ -4324,7 +4353,7 @@ def getProviderInstance(self) -> Optional[vision.providerBase.VisionEnhancementP def startProvider( self, - shouldPromptOnError: bool = True + shouldPromptOnError: bool = True, ) -> bool: """Initializes the provider, prompting user with the error if necessary. @param shouldPromptOnError: True if the user should be presented with any errors that may occur. @@ -4332,12 +4361,12 @@ def startProvider( """ success = self._doStartProvider() if not success and shouldPromptOnError: - showStartErrorForProviders(self._parent(), [self._providerInfo, ]) + showStartErrorForProviders(self._parent(), [self._providerInfo]) return success def terminateProvider( self, - shouldPromptOnError: bool = True + shouldPromptOnError: bool = True, ) -> bool: """Terminate the provider, prompting user with the error if necessary. @param shouldPromptOnError: True if the user should be presented with any errors that may occur. @@ -4345,7 +4374,7 @@ def terminateProvider( """ success = self._doTerminate() if not success and shouldPromptOnError: - showTerminationErrorForProviders(self._parent(), [self._providerInfo, ]) + showTerminationErrorForProviders(self._parent(), [self._providerInfo]) return success def _doStartProvider(self) -> bool: @@ -4358,7 +4387,7 @@ def _doStartProvider(self) -> bool: except Exception: log.error( f"Could not initialize the {self._providerInfo.providerId} vision enhancement provider", - exc_info=True + exc_info=True, ) return False @@ -4376,7 +4405,7 @@ def _doTerminate(self) -> bool: except Exception: log.error( f"Could not terminate the {self._providerInfo.providerId} vision enhancement provider", - exc_info=True + exc_info=True, ) return False @@ -4394,7 +4423,7 @@ class VisionSettingsPanel(SettingsPanel): def _createProviderSettingsPanel( self, - providerInfo: vision.providerInfo.ProviderInfo + providerInfo: vision.providerInfo.ProviderInfo, ) -> Optional[SettingsPanel]: settingsPanelCls = providerInfo.providerClass.getSettingsPanelClass() if not settingsPanelCls: @@ -4409,7 +4438,7 @@ def _createProviderSettingsPanel( try: return settingsPanelCls( parent=self, - providerControl=providerControl + providerControl=providerControl, ) # Broad except used since we can not know what exceptions a provider might throw. # We should be able to continue despite a buggy provider. @@ -4426,7 +4455,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer): for providerInfo in vision.handler.getProviderList(reloadFromSystem=True): providerSizer = self.settingsSizerHelper.addItem( wx.StaticBoxSizer(wx.VERTICAL, self, label=providerInfo.displayName), - flag=wx.EXPAND + flag=wx.EXPAND, ) if len(self.providerPanelInstances) > 0: settingsSizer.AddSpacer(guiHelper.SPACE_BETWEEN_VERTICAL_DIALOG_ITEMS) @@ -4440,7 +4469,7 @@ def makeSettings(self, settingsSizer: wx.BoxSizer): def safeInitProviders( self, - providers: List[vision.providerInfo.ProviderInfo] + providers: List[vision.providerInfo.ProviderInfo], ) -> None: """Initializes one or more providers in a way that is gui friendly, showing an error if appropriate. @@ -4455,7 +4484,7 @@ def safeInitProviders( def safeTerminateProviders( self, providers: List[vision.providerInfo.ProviderInfo], - verbose: bool = False + verbose: bool = False, ) -> None: """Terminates one or more providers in a way that is gui friendly, @verbose: Whether to show a termination error. @@ -4515,7 +4544,7 @@ def onSave(self): class VisionProviderSubPanel_Settings( AutoSettingsMixin, - SettingsPanel + SettingsPanel, ): helpId = "VisionSettings" @@ -4525,7 +4554,7 @@ def __init__( self, parent: wx.Window, *, # Make next argument keyword only - settingsCallable: Callable[[], vision.providerBase.VisionEnhancementProviderSettings] + settingsCallable: Callable[[], vision.providerBase.VisionEnhancementProviderSettings], ): """ @param settingsCallable: A callable that returns an instance to a VisionEnhancementProviderSettings. @@ -4544,7 +4573,7 @@ def makeSettings(self, settingsSizer): class VisionProviderSubPanel_Wrapper( - SettingsPanel + SettingsPanel, ): _checkBox: wx.CheckBox @@ -4552,7 +4581,7 @@ class VisionProviderSubPanel_Wrapper( def __init__( self, parent: wx.Window, - providerControl: VisionProviderStateControl + providerControl: VisionProviderStateControl, ): self._providerControl = providerControl self._providerSettings: Optional[VisionProviderSubPanel_Settings] = None @@ -4563,7 +4592,7 @@ def makeSettings(self, settingsSizer): self._checkBox = wx.CheckBox( self, # Translators: Enable checkbox on a vision enhancement provider on the vision settings category panel - label=_("Enable") + label=_("Enable"), ) settingsSizer.Add(self._checkBox) self.bindHelpEvent("VisionSettings", self._checkBox) @@ -4576,12 +4605,12 @@ def makeSettings(self, settingsSizer): self._providerSettingsSizer, border=self.scaleSize(15), flag=wx.LEFT | wx.EXPAND, - proportion=1 + proportion=1, ) settingsSizer.Add( self._optionsSizer, flag=wx.EXPAND, - proportion=1 + proportion=1, ) self._checkBox.SetValue(bool(self._providerControl.getProviderInstance())) if self._createProviderSettings(): @@ -4603,7 +4632,7 @@ def _createProviderSettings(self): getSettingsCallable = self._providerControl.getProviderInfo().providerClass.getSettings self._providerSettings = VisionProviderSubPanel_Settings( self, - settingsCallable=getSettingsCallable + settingsCallable=getSettingsCallable, ) self._providerSettingsSizer.Add(self._providerSettings, flag=wx.EXPAND, proportion=1) # Broad except used since we can not know what exceptions a provider might throw. @@ -4704,14 +4733,14 @@ def _doOnCategoryChange(self): self.SetTitle(self._getDialogTitle()) self.bindHelpEvent( self.currentCategory.helpId, - self.catListCtrl + self.catListCtrl, ) def _getDialogTitle(self): return u"{dialogTitle}: {panelTitle} ({configProfile})".format( dialogTitle=self.title, panelTitle=self.currentCategory.title, - configProfile=NvdaSettingsDialogActiveConfigProfile + configProfile=NvdaSettingsDialogActiveConfigProfile, ) def onCategoryChange(self,evt): @@ -4729,7 +4758,7 @@ def Destroy(self): class AddSymbolDialog( gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): helpId = "SymbolPronunciation" @@ -4798,7 +4827,7 @@ def makeSettings(self, settingsSizer): nvdaControls.AutoWidthColumnListCtrl, autoSizeColumn=2, # The replacement column is likely to need the most space itemTextCallable=self.getItemTextForList, - style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_VIRTUAL + style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.LC_VIRTUAL, ) # Translators: The label for a column in symbols list used to identify a symbol. @@ -4962,8 +4991,10 @@ def OnAddClick(self, evt): for index, symbol in enumerate(self.symbols): if identifier == symbol.identifier: # Translators: An error reported in the Symbol Pronunciation dialog when adding a symbol that is already present. - gui.messageBox(_('Symbol "%s" is already present.') % identifier, - _("Error"), wx.OK | wx.ICON_ERROR) + gui.messageBox( + _('Symbol "%s" is already present.') % identifier, + _("Error"), wx.OK | wx.ICON_ERROR, + ) self.symbolsList.Select(index) self.symbolsList.Focus(index) self.symbolsList.SetFocus() diff --git a/source/gui/speechDict.py b/source/gui/speechDict.py index 870cd7d1ac2..563edbf8019 100644 --- a/source/gui/speechDict.py +++ b/source/gui/speechDict.py @@ -32,12 +32,12 @@ class DictionaryEntryDialog( # Translators: This is a label for an Entry Type radio button in add dictionary entry dialog. speechDictHandler.ENTRY_TYPE_WORD: _("Whole &word"), # Translators: This is a label for an Entry Type radio button in add dictionary entry dialog. - speechDictHandler.ENTRY_TYPE_REGEXP: _("Regular &expression") + speechDictHandler.ENTRY_TYPE_REGEXP: _("Regular &expression"), } TYPE_LABELS_ORDERING = ( speechDictHandler.ENTRY_TYPE_ANYWHERE, speechDictHandler.ENTRY_TYPE_WORD, - speechDictHandler.ENTRY_TYPE_REGEXP + speechDictHandler.ENTRY_TYPE_REGEXP, ) # Translators: This is the label for the edit dictionary entry dialog. @@ -92,7 +92,7 @@ def onOk(self, evt): # Translators: The title of an error message raised by the Dictionary Entry dialog _("Dictionary Entry Error"), wx.OK | wx.ICON_WARNING, - self + self, ) self.patternTextCtrl.SetFocus() return @@ -115,7 +115,7 @@ def onOk(self, evt): # Translators: The title of an error message raised by the Dictionary Entry dialog _("Dictionary Entry Error"), wx.OK | wx.ICON_WARNING, - self + self, ) self.patternTextCtrl.SetFocus() return @@ -131,7 +131,7 @@ def onOk(self, evt): # Translators: The title of an error message raised by the Dictionary Entry dialog _("Dictionary Entry Error"), wx.OK | wx.ICON_WARNING, - self + self, ) self.replacementTextCtrl.SetFocus() return @@ -174,7 +174,7 @@ def makeSettings(self, settingsSizer): entriesLabelText = _("&Dictionary entries") self.dictList = sHelper.addLabeledControl( entriesLabelText, - wx.ListCtrl, style=wx.LC_REPORT | wx.LC_SINGLE_SEL + wx.ListCtrl, style=wx.LC_REPORT | wx.LC_SINGLE_SEL, ) # Translators: The label for a column in dictionary entries list used to identify comments for the entry. self.dictList.AppendColumn(_("Comment"), width=150) @@ -197,7 +197,7 @@ def makeSettings(self, settingsSizer): entry.pattern, entry.replacement, self.offOn[int(entry.caseSensitive)], - DictionaryDialog.TYPE_LABELS[entry.type] + DictionaryDialog.TYPE_LABELS[entry.type], )) self.editingIndex = -1 @@ -205,19 +205,19 @@ def makeSettings(self, settingsSizer): bHelper.addButton( parent=self, # Translators: The label for a button in speech dictionaries dialog to add new entries. - label=_("&Add") + label=_("&Add"), ).Bind(wx.EVT_BUTTON, self.onAddClick) bHelper.addButton( parent=self, # Translators: The label for a button in speech dictionaries dialog to edit existing entries. - label=_("&Edit") + label=_("&Edit"), ).Bind(wx.EVT_BUTTON, self.onEditClick) bHelper.addButton( parent=self, # Translators: The label for a button in speech dictionaries dialog to remove existing entries. - label=_("&Remove") + label=_("&Remove"), ).Bind(wx.EVT_BUTTON, self.onRemoveClick) bHelper.sizer.AddStretchSpacer() @@ -225,7 +225,7 @@ def makeSettings(self, settingsSizer): bHelper.addButton( parent=self, # Translators: The label for a button on the Speech Dictionary dialog. - label=_("Remove all") + label=_("Remove all"), ).Bind(wx.EVT_BUTTON, self.onRemoveAll) sHelper.addItem(bHelper, flag=wx.EXPAND) @@ -255,7 +255,7 @@ def onAddClick(self, evt): entryDialog.patternTextCtrl.GetValue(), entryDialog.replacementTextCtrl.GetValue(), self.offOn[int(entryDialog.caseSensitiveCheckBox.GetValue())], - DictionaryDialog.TYPE_LABELS[entryDialog.getType()] + DictionaryDialog.TYPE_LABELS[entryDialog.getType()], )) index = self.dictList.GetFirstSelected() while index >= 0: @@ -303,7 +303,7 @@ def onRemoveAll(self, evt): _("Are you sure you want to remove all the entries in this dictionary?"), # Translators: The title on a prompt for confirmation on the Speech Dictionary dialog. _("Remove all"), - style=wx.YES | wx.NO | wx.NO_DEFAULT + style=wx.YES | wx.NO | wx.NO_DEFAULT, ) != wx.YES: return # Looping instead of clearing here in order to avoid recreation of the columns diff --git a/source/gui/startupDialogs.py b/source/gui/startupDialogs.py index e4a10ff09c6..a392d1b96a6 100644 --- a/source/gui/startupDialogs.py +++ b/source/gui/startupDialogs.py @@ -22,7 +22,7 @@ class WelcomeDialog( gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): """The NVDA welcome dialog. This provides essential information for new users, @@ -38,7 +38,7 @@ class WelcomeDialog( "By default, the Insert and numpad Insert keys may both be used as the NVDA key.\n" "You can also configure NVDA to use the CapsLock as the NVDA key.\n" "Press NVDA+n at any time to activate the NVDA menu.\n" - "From this menu, you can configure NVDA, get help, and access other NVDA functions." + "From this menu, you can configure NVDA, get help, and access other NVDA functions.", ) _instances: Set["WelcomeDialog"] = weakref.WeakSet() @@ -93,7 +93,7 @@ def __init__(self, parent): mainSizer.Add( self.CreateButtonSizer(wx.OK), border=gui.guiHelper.BORDER_FOR_DIALOGS, - flag=wx.ALL | wx.ALIGN_RIGHT + flag=wx.ALL | wx.ALIGN_RIGHT, ) self.Bind(wx.EVT_BUTTON, self.onOk, id=wx.ID_OK) @@ -116,7 +116,7 @@ def onOk(self, evt): _( # Translators: The title of an error message box displayed when validating the startup dialog "At least one NVDA modifier key must be set. " - "Caps lock will remain as an NVDA modifier key. " + "Caps lock will remain as an NVDA modifier key. ", ), # Translators: The title of an error message box displayed when validating the startup dialog _("Error"), @@ -158,7 +158,7 @@ def closeInstances(cls): class LauncherDialog( DpiScalingHelperMixinWithoutInit, gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): """The dialog that is displayed when NVDA is started from the launcher. This displays the license and allows the user to install or create a portable copy of NVDA. @@ -266,7 +266,7 @@ def run(cls): class AskAllowUsageStatsDialog( gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): """A dialog asking if the user wishes to allow NVDA usage stats to be collected by NV Access.""" @@ -286,7 +286,7 @@ def __init__(self, parent): "certain NVDA configuration such as current synthesizer, braille display and braille table. " "No spoken or braille content will be ever sent to NV Access. " "Please refer to the User Guide for a current list of all data collected.\n\n" - "Do you wish to allow NV Access to periodically collect this data in order to improve NVDA?" + "Do you wish to allow NV Access to periodically collect this data in order to improve NVDA?", ) sText = sHelper.addItem(wx.StaticText(self, label=message)) # the wx.Window must be constructed before we can get the handle. @@ -294,7 +294,7 @@ def __init__(self, parent): self.scaleFactor = windowUtils.getWindowScalingFactor(self.GetHandle()) sText.Wrap( # 600 was fairly arbitrarily chosen by a visual user to look acceptable on their machine. - self.scaleFactor * 600 + self.scaleFactor * 600, ) bHelper = sHelper.addDialogDismissButtons(gui.guiHelper.ButtonHelper(wx.HORIZONTAL)) diff --git a/source/hidpi.py b/source/hidpi.py index 79e0dadec8c..f6439974277 100644 --- a/source/hidpi.py +++ b/source/hidpi.py @@ -146,5 +146,5 @@ class HIDP_CAPS (Structure): ("NumberOutputDataIndices", USHORT), ("NumberFeatureButtonCaps", USHORT), ("NumberFeatureValueCaps", USHORT), - ("NumberFeatureDataIndices", USHORT) + ("NumberFeatureDataIndices", USHORT), ) diff --git a/source/hwIo/__init__.py b/source/hwIo/__init__.py index 288ff69225f..b1fbd86c983 100644 --- a/source/hwIo/__init__.py +++ b/source/hwIo/__init__.py @@ -17,7 +17,7 @@ Bulk, boolToByte, intToByte, - getByte + getByte, ) from .hid import Hid # noqa: F401 from .ioThread import IoThread diff --git a/source/hwIo/base.py b/source/hwIo/base.py index 70e98f74683..f6d8311380d 100644 --- a/source/hwIo/base.py +++ b/source/hwIo/base.py @@ -33,7 +33,7 @@ def __getattr__(attrName: str) -> Any: if attrName == "LPOVERLAPPED_COMPLETION_ROUTINE" and NVDAState._allowDeprecatedAPI(): log.warning( "Importing LPOVERLAPPED_COMPLETION_ROUTINE from hwIo.base is deprecated. " - "Import LPOVERLAPPED_COMPLETION_ROUTINE from hwIo.ioThread instead." + "Import LPOVERLAPPED_COMPLETION_ROUTINE from hwIo.ioThread instead.", ) from .ioThread import LPOVERLAPPED_COMPLETION_ROUTINE return LPOVERLAPPED_COMPLETION_ROUTINE @@ -123,7 +123,7 @@ def _prepareWriteBuffer(self, data: bytes) -> Tuple[int, ctypes.c_char_p]: size = len(data) return ( size, - ctypes.create_string_buffer(data) # this will append a null char, which is intentional + ctypes.create_string_buffer(data), # this will append a null char, which is intentional ) def write(self, data: bytes): @@ -171,7 +171,7 @@ def _asyncRead(self, param: Optional[int] = None): self._readBuf, self._readSize, byref(self._readOl), - ioThread.queueAsCompletionRoutine(self._ioDone, self._readOl) + ioThread.queueAsCompletionRoutine(self._ioDone, self._readOl), ) def _ioDone(self, error, numberOfBytes: int, overlapped): @@ -216,7 +216,7 @@ def __init__( onReceive: Callable[[bytes], None], onReadError: Optional[Callable[[int], bool]] = None, ioThread: Optional[IoThread] = None, - **kwargs + **kwargs, ): """Constructor. Pass the arguments you would normally pass to L{serial.Serial}. @@ -247,7 +247,7 @@ def __init__( self._ser._port_handle, onReceive, onReadError=onReadError, - ioThread=ioThread + ioThread=ioThread, ) def read(self, size=1) -> bytes: @@ -321,14 +321,18 @@ def __init__( log.debug("Opening device %s" % path) readPath="{path}\\{endpoint}".format(path=path,endpoint=epIn) writePath="{path}\\{endpoint}".format(path=path,endpoint=epOut) - readHandle = CreateFile(readPath, winKernel.GENERIC_READ, - 0, None, winKernel.OPEN_EXISTING, FILE_FLAG_OVERLAPPED, None) + readHandle = CreateFile( + readPath, winKernel.GENERIC_READ, + 0, None, winKernel.OPEN_EXISTING, FILE_FLAG_OVERLAPPED, None, + ) if readHandle == INVALID_HANDLE_VALUE: if _isDebug(): log.debug("Open read handle failed: %s" % ctypes.WinError()) raise ctypes.WinError() - writeHandle = CreateFile(writePath, winKernel.GENERIC_WRITE, - 0, None, winKernel.OPEN_EXISTING, FILE_FLAG_OVERLAPPED, None) + writeHandle = CreateFile( + writePath, winKernel.GENERIC_WRITE, + 0, None, winKernel.OPEN_EXISTING, FILE_FLAG_OVERLAPPED, None, + ) if writeHandle == INVALID_HANDLE_VALUE: if _isDebug(): log.debug("Open write handle failed: %s" % ctypes.WinError()) @@ -339,7 +343,7 @@ def __init__( writeFileHandle=writeHandle, onReceiveSize=onReceiveSize, onReadError=onReadError, - ioThread=ioThread + ioThread=ioThread, ) def close(self): @@ -354,7 +358,7 @@ def boolToByte(arg: bool) -> bytes: return arg.to_bytes( length=1, byteorder=sys.byteorder, # for a single byte big/little endian does not matter. - signed=False # Since this represents length, it makes no sense to send a negative value. + signed=False, # Since this represents length, it makes no sense to send a negative value. ) @@ -364,7 +368,7 @@ def intToByte(arg: int) -> bytes: return arg.to_bytes( length=1, # Will raise if value overflows, eg arg > 255 byteorder=sys.byteorder, # for a single byte big/little endian does not matter. - signed=False # Since this represents length, it makes no sense to send a negative value. + signed=False, # Since this represents length, it makes no sense to send a negative value. ) def getByte(arg: bytes, index: int) -> bytes: diff --git a/source/hwIo/hid.py b/source/hwIo/hid.py index 22839f114e6..0877d53aa37 100644 --- a/source/hwIo/hid.py +++ b/source/hwIo/hid.py @@ -72,7 +72,7 @@ def getUsages(self, usagePage, linkCollection=0): ctypes.byref(numUsages), self._dev._pd, self._reportBuf, - self._reportSize + self._reportSize, ) return usageList[0:numUsages.value] @@ -87,7 +87,7 @@ def getDataItems(self): ctypes.byref(numDataLength), self._dev._pd, self._reportBuf, - self._reportSize + self._reportSize, ) return dataList[0:numDataLength.value] @@ -118,7 +118,7 @@ def setUsageValueArray(self, usagePage, linkCollection, usage, data): len(dataBuf), self._dev._pd, self._reportBuf, - self._reportSize + self._reportSize, ) @@ -155,7 +155,7 @@ def __init__( None, winKernel.OPEN_EXISTING, FILE_FLAG_OVERLAPPED, - None + None, ) if handle == INVALID_HANDLE_VALUE: if _isDebug(): @@ -173,8 +173,8 @@ def __init__( log.debug( "Report byte lengths: input %d, output %d, feature %d" % ( - caps.InputReportByteLength, caps.OutputReportByteLength, caps.FeatureReportByteLength - ) + caps.InputReportByteLength, caps.OutputReportByteLength, caps.FeatureReportByteLength, + ), ) self._featureSize = caps.FeatureReportByteLength self._writeSize = caps.OutputReportByteLength @@ -186,7 +186,7 @@ def __init__( onReceive, onReceiveSize=caps.InputReportByteLength, onReadError=onReadError, - ioThread=ioThread + ioThread=ioThread, ) @property @@ -209,7 +209,7 @@ def inputButtonCaps(self): hidpi.HIDP_REPORT_TYPE.INPUT, ctypes.byref(valueCapsList), ctypes.byref(numValueCaps), - self._pd + self._pd, ) self._inputButtonCaps = valueCapsList return self._inputButtonCaps @@ -225,7 +225,7 @@ def inputValueCaps(self): hidpi.HIDP_REPORT_TYPE.INPUT, ctypes.byref(valueCapsList), ctypes.byref(numValueCaps), - self._pd + self._pd, ) self._inputValueCaps = valueCapsList return self._inputValueCaps @@ -241,7 +241,7 @@ def outputValueCaps(self): hidpi.HIDP_REPORT_TYPE.OUTPUT, ctypes.byref(valueCapsList), ctypes.byref(numValueCaps), - self._pd + self._pd, ) self._outputValueCaps = valueCapsList return self._outputValueCaps @@ -260,7 +260,7 @@ def _prepareWriteBuffer(self, data: bytes) -> Tuple[int, ctypes.c_char_p]: raise RuntimeError("Unable to send buffer of: %d", len(data)) return ( self._writeSize, - ctypes.create_string_buffer(data, self._writeSize) + ctypes.create_string_buffer(data, self._writeSize), ) def getFeature(self, reportId: bytes) -> bytes: @@ -273,7 +273,7 @@ def getFeature(self, reportId: bytes) -> bytes: if _isDebug(): log.debug( "Get feature %r failed: %s" - % (reportId, ctypes.WinError()) + % (reportId, ctypes.WinError()), ) raise ctypes.WinError() if _isDebug(): @@ -291,7 +291,7 @@ def setFeature(self, report: bytes) -> None: result = hidDll.HidD_SetFeature( self._file, buf, - bufSize + bufSize, ) if not result: if _isDebug(): @@ -311,7 +311,7 @@ def setOutputReport(self, report: bytes) -> None: result = hidDll.HidD_SetOutputReport( self._writeFile, buf, - bufSize + bufSize, ) if not result: if _isDebug(): diff --git a/source/hwIo/ioThread.py b/source/hwIo/ioThread.py index 2ffc6f8c2b2..7fcccb1e0d6 100644 --- a/source/hwIo/ioThread.py +++ b/source/hwIo/ioThread.py @@ -20,7 +20,7 @@ None, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD, - LPOVERLAPPED + LPOVERLAPPED, ) ApcT = typing.Callable[[int], None] ApcIdT = int @@ -29,15 +29,15 @@ ApcStoreT = typing.Dict[ ApcIdT, typing.Tuple[ - typing.Union[ApcT, BoundMethodWeakref[ApcT], AnnotatableWeakref[ApcT]], ApcIdT - ] + typing.Union[ApcT, BoundMethodWeakref[ApcT], AnnotatableWeakref[ApcT]], ApcIdT, + ], ] CompletionRoutineStoreTypeT = typing.Dict[ OverlappedStructAddressT, typing.Tuple[ typing.Union[BoundMethodWeakref[CompletionRoutineT], AnnotatableWeakref[CompletionRoutineT]], - OVERLAPPED - ] + OVERLAPPED, + ], ] @@ -75,7 +75,7 @@ class IoThread(threading.Thread): def __init__(self): super().__init__( name=f"{self.__class__.__module__}.{self.__class__.__qualname__}", - daemon=True + daemon=True, ) @winKernel.PAPCFUNC @@ -93,7 +93,7 @@ def _internalApc(param: ApcIdT): function = reference() if not function: log.debugWarning( - f"Not executing queued APC {param}:{reference.funcName} with param {actualParam} because reference died" + f"Not executing queued APC {param}:{reference.funcName} with param {actualParam} because reference died", ) return else: @@ -108,7 +108,7 @@ def _internalApc(param: ApcIdT): def _internalCompletionRoutine( error: int, numberOfBytes: int, - overlapped: LPOVERLAPPED + overlapped: LPOVERLAPPED, ): threadinst = threading.current_thread() if not isinstance(threadinst, IoThread): @@ -124,7 +124,7 @@ def _internalCompletionRoutine( function = reference() if not function: log.debugWarning( - f"Not executing queued completion routine 0x{ptr:x}:{reference.funcName} because reference died" + f"Not executing queued completion routine 0x{ptr:x}:{reference.funcName} because reference died", ) return @@ -167,7 +167,7 @@ def _registerToCallAsApc( def queueAsApc( self, func: ApcT, - param: int = 0 + param: int = 0, ): """safely queues a Python function call as an Asynchronous Procedure Call (APC). The function and param are saved in a store on the IoThread instance. @@ -185,7 +185,7 @@ def setWaitableTimer( handle: typing.Union[int, ctypes.wintypes.HANDLE], dueTime: int, func: ApcT, - param: int = 0 + param: int = 0, ): """"Safe wrapper around winKernel.setWaitableTimer that uses an internal APC. A weak reference to the function and its param are saved in a store on the IoThread instance. @@ -202,7 +202,7 @@ def setWaitableTimer( handle, dueTime, completionRoutine=self._internalApc, - arg=internalParam + arg=internalParam, ) def queueAsCompletionRoutine( @@ -226,7 +226,7 @@ def queueAsCompletionRoutine( if addr in self._completionRoutineStore: raise RuntimeError( f"Overlapped structure with address 0x{addr:x} has a completion routine queued already. " - "Only one completion routine for one overlapped structure can be queued at a time." + "Only one completion routine for one overlapped structure can be queued at a time.", ) # Generate a weak reference to the function diff --git a/source/hwPortUtils.py b/source/hwPortUtils.py index 030bc3fa600..3fb8caee47f 100644 --- a/source/hwPortUtils.py +++ b/source/hwPortUtils.py @@ -176,7 +176,7 @@ def _getBluetoothPortInfo(regKey: int, hwID: str) -> dict: try: addr = winreg.QueryValueEx( regKey, - "Bluetooth_UniqueID" + "Bluetooth_UniqueID", )[0].split("#", 1)[1].split("_", 1)[0] addr = int(addr, 16) info["bluetoothAddress"] = addr @@ -185,7 +185,7 @@ def _getBluetoothPortInfo(regKey: int, hwID: str) -> dict: except Exception: log.debugWarning( f"Couldn't get Microsoft bt name for hardware id {hwID!r}", - exc_info=True + exc_info=True, ) case r"Bluetooth\0004&0002": # This is a Toshiba bluetooth port. @@ -220,7 +220,7 @@ def listComPorts(onlyAvailable: bool = True) -> typing.Iterator[dict]: SPDRP_HARDWAREID, None, ctypes.byref(buf), ctypes.sizeof(buf) - 1, - None + None, ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: @@ -235,7 +235,7 @@ def listComPorts(onlyAvailable: bool = True) -> typing.Iterator[dict]: DICS_FLAG_GLOBAL, 0, DIREG_DEV, - winreg.KEY_READ + winreg.KEY_READ, ) try: portInfo = _getBluetoothPortInfo(regKey, hwID) @@ -254,7 +254,7 @@ def listComPorts(onlyAvailable: bool = True) -> typing.Iterator[dict]: SPDRP_FRIENDLYNAME, None, ctypes.byref(buf), ctypes.sizeof(buf) - 1, - None + None, ): # #6007: SPDRP_FRIENDLYNAME sometimes doesn't exist/isn't valid. log.debugWarning(f"Couldn't get SPDRP_FRIENDLYNAME for {entry!r}: {ctypes.WinError()}") @@ -284,7 +284,7 @@ class BLUETOOTH_DEVICE_INFO(ctypes.Structure): ("fAuthenticated", BOOL), ("stLastSeen", SYSTEMTIME), ("stLastUsed", SYSTEMTIME), - ("szName", WCHAR * BLUETOOTH_MAX_NAME_SIZE) + ("szName", WCHAR * BLUETOOTH_MAX_NAME_SIZE), ) def __init__(self, **kwargs): @@ -302,7 +302,7 @@ def getBluetoothDeviceInfo(address): def getToshibaBluetoothPortInfo(port): with winreg.OpenKey( winreg.HKEY_CURRENT_USER, - r"Software\Toshiba\BluetoothStack\V1.0\EZC\DATA" + r"Software\Toshiba\BluetoothStack\V1.0\EZC\DATA", ) as rootKey: for index in itertools.count(): try: @@ -373,7 +373,7 @@ def _listDevices( None, ctypes.byref(deviceClass), dwIndex, - ctypes.byref(did) + ctypes.byref(did), ): if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS: raise ctypes.WinError() @@ -387,7 +387,7 @@ def _listDevices( None, 0, ctypes.byref(dwNeeded), - None + None, ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: @@ -413,7 +413,7 @@ def __str__(self): ctypes.byref(idd), dwNeeded, None, - ctypes.byref(devinfo) + ctypes.byref(devinfo), ): raise ctypes.WinError() @@ -437,7 +437,7 @@ def listUsbDevices(onlyAvailable: bool = True) -> typing.Iterator[dict]: SPDRP_HARDWAREID, None, ctypes.byref(buf), ctypes.sizeof(buf) - 1, - None + None, ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: @@ -448,7 +448,7 @@ def listUsbDevices(onlyAvailable: bool = True) -> typing.Iterator[dict]: entry.update({ "hardwareID": buf.value, "usbID": usbId, - "devicePath": idd.DevicePath + "devicePath": idd.DevicePath, }) if _isDebug(): log.debug(f"USB Id: {usbId!r}") @@ -463,10 +463,10 @@ def listUsbDevices(onlyAvailable: bool = True) -> typing.Iterator[dict]: ctypes.byref(buf), ctypes.sizeof(buf) - 1, None, - 0 + 0, ): log.debugWarning( - f"Couldn't get DEVPKEY_Device_BusReportedDeviceDesc for {entry!r}: {ctypes.WinError()}" + f"Couldn't get DEVPKEY_Device_BusReportedDeviceDesc for {entry!r}: {ctypes.WinError()}", ) else: entry["busReportedDeviceDescription"] = buf.value @@ -481,7 +481,7 @@ class HIDD_ATTRIBUTES(ctypes.Structure): ("Size", ULONG), ("VendorID", USHORT), ("ProductID", USHORT), - ("VersionNumber", USHORT) + ("VersionNumber", USHORT), ) def __init__(self, **kwargs): @@ -491,7 +491,7 @@ def __init__(self, **kwargs): def _getHidInfo(hwId, path): info = { "hardwareID": hwId, - "devicePath": path + "devicePath": path, } hwId = hwId.split("\\", 1)[1] if hwId.startswith("VID"): @@ -573,7 +573,7 @@ def listHidDevices(onlyAvailable: bool = True) -> typing.Iterator[dict]: SPDRP_HARDWAREID, None, ctypes.byref(buf), ctypes.sizeof(buf) - 1, - None + None, ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: diff --git a/source/inputCore.py b/source/inputCore.py index 61b0a5c7078..f8ff37de1b8 100644 --- a/source/inputCore.py +++ b/source/inputCore.py @@ -276,7 +276,7 @@ def add( module: str, className: str, script: Optional[ScriptNameT], - replace: bool = False + replace: bool = False, ): """Add a gesture mapping. @param gesture: The gesture identifier. @@ -505,7 +505,7 @@ def executeGesture(self, gesture): # lead to unexpected behavior for gesture emulation, i.e. the gesture will be send to the system # when the decider decided not to execute it. log.debug( - "Gesture execution canceled by handler registered to decide_executeGesture extension point" + "Gesture execution canceled by handler registered to decide_executeGesture extension point", ) return @@ -567,7 +567,7 @@ def suppressCancelSpeech(): queueHandler.eventQueue, speech.speakMessage, gesture.displayName, - _immediate=True + _immediate=True, ) gesture.reportExtra() @@ -607,7 +607,7 @@ def _inputHelpCaptor(self, gesture): self._handleInputHelp, gesture, onlyLog=bypass or not gesture.reportInInputHelp, - _immediate=immediate + _immediate=immediate, ) return bypass @@ -639,7 +639,7 @@ def _handleInputHelp(self, gesture, onlyLog=False): speech.speakText( textList[0], reason=controlTypes.OutputReason.MESSAGE, - symbolLevel=characterProcessing.SymbolLevel.ALL + symbolLevel=characterProcessing.SymbolLevel.ALL, ) for text in textList[1:]: speech.speakMessage(text) @@ -694,7 +694,7 @@ class _AllGestureMappingsRetriever(object): Dict[ str, # command display name Any, # AllGesturesScriptInfo - ] + ], ] def __init__(self, obj, ancestors): @@ -793,7 +793,7 @@ def makeKbEmuScriptInfo(cls, scriptCls, kbGestureIdentifier): info = KbEmuScriptInfo(scriptCls, kbGestureIdentifier) info.category = SCRCAT_KBEMU info.displayName = getDisplayTextForGestureIdentifier( - normalizeGestureIdentifier(kbGestureIdentifier) + normalizeGestureIdentifier(kbGestureIdentifier), )[1] return info @@ -959,9 +959,10 @@ def logTimeSinceInput(): """Log the time since the last input was received. This does nothing if time since input logging is disabled. """ - if (not log.isEnabledFor(log.IO) - or not config.conf["debugLog"]["timeSinceInput"] - or not manager or not manager._lastInputTime - ): + if ( + not log.isEnabledFor(log.IO) + or not config.conf["debugLog"]["timeSinceInput"] + or not manager or not manager._lastInputTime + ): return log.io("%.3f sec since input" % (time.time() - manager._lastInputTime)) diff --git a/source/installer.py b/source/installer.py index db1a5e1201b..26e0eb10901 100644 --- a/source/installer.py +++ b/source/installer.py @@ -183,7 +183,7 @@ def removeOldLibFiles(destPath, rebootOK=False): log.warning( "Failed to remove a directory no longer needed. " "This can be manually removed after a reboot or the installer will try" - f" removing it again next time. Directory: {repr(path)}" + f" removing it again next time. Directory: {repr(path)}", ) for f in files: path = os.path.join(parent, f) @@ -220,13 +220,16 @@ def removeOldProgramFiles(destPath): # Also remove old .dll and .manifest files. for curDestDir,subDirs,files in os.walk(destPath): if curDestDir == destPath: - subDirs[:] = [x for x in subDirs if os.path.basename(x).lower() not in ( - 'userconfig', - 'systemconfig', - # Do not remove old libraries here. It is done by removeOldLibFiles. - 'lib', - 'lib64', - 'libarm64')] + subDirs[:] = [ + x for x in subDirs if os.path.basename(x).lower() not in ( + 'userconfig', + 'systemconfig', + # Do not remove old libraries here. It is done by removeOldLibFiles. + 'lib', + 'lib64', + 'libarm64', + ) + ] for f in files: if f.endswith((".pyc", ".pyo", ".pyd", ".dll", ".manifest")): path=os.path.join(curDestDir, f) @@ -274,7 +277,7 @@ def registerInstallation( startMenuFolder: str, shouldCreateDesktopShortcut: bool, startOnLogonScreen: bool, - configInLocalAppData: bool = False + configInLocalAppData: bool = False, ) -> None: calculatedUninstallerRegInfo = getUninstallerRegInfo(installDir) log.debug(f"Estimated install size: {calculatedUninstallerRegInfo.get('EstimatedSize')} KiB") @@ -282,7 +285,7 @@ def registerInstallation( winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\NVDA", 0, - winreg.KEY_WRITE + winreg.KEY_WRITE, ) as k: for name, value in calculatedUninstallerRegInfo.items(): if isinstance(value, int): @@ -296,7 +299,7 @@ def registerInstallation( name, None, regType, - value + value, ) with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\nvda.exe",0,winreg.KEY_WRITE) as k: winreg.SetValueEx(k,"",None,winreg.REG_SZ,os.path.join(installDir,"nvda.exe")) @@ -308,7 +311,7 @@ def registerInstallation( config.RegistryKey.CONFIG_IN_LOCAL_APPDATA_SUBKEY.value, None, winreg.REG_DWORD, - int(configInLocalAppData) + int(configInLocalAppData), ) if NVDAState._forceSecureModeEnabled(): winreg.SetValueEx( @@ -316,7 +319,7 @@ def registerInstallation( config.RegistryKey.FORCE_SECURE_MODE_SUBKEY.value, None, winreg.REG_DWORD, - 1 + 1, ) registerEaseOfAccess(installDir) if startOnLogonScreen is not None: @@ -353,7 +356,7 @@ def _createShortcutWithFallback( iconLocation, workingDirectory, hotkey, - prependSpecialFolder + prependSpecialFolder, ) except Exception: if hotkey is not None and fallbackHotkey is not None: @@ -381,7 +384,7 @@ def _createShortcutWithFallback( else: log.error( f"Error creating {path}, no mitigation possible. " - f"Perhaps controlled folder access is active for this directory." + f"Perhaps controlled folder access is active for this directory.", ) @@ -411,7 +414,7 @@ def _updateShortcuts(NVDAExe, installDir, shouldCreateDesktopShortcut, slaveExe, path=os.path.join(startMenuFolder, "NVDA.lnk"), targetPath=NVDAExe, workingDirectory=installDir, - prependSpecialFolder="AllUsersPrograms" + prependSpecialFolder="AllUsersPrograms", ) # Translators: A label for a shortcut in start menu and a menu entry in NVDA menu (to go to NVDA website). @@ -420,7 +423,7 @@ def _updateShortcuts(NVDAExe, installDir, shouldCreateDesktopShortcut, slaveExe, path=os.path.join(startMenuFolder, webSiteTranslated + ".lnk"), fallbackPath=os.path.join(startMenuFolder, "NVDA web site.lnk"), targetPath=versionInfo.url, - prependSpecialFolder="AllUsersPrograms" + prependSpecialFolder="AllUsersPrograms", ) # Translators: A label for a shortcut item in start menu to uninstall NVDA from the computer. @@ -430,7 +433,7 @@ def _updateShortcuts(NVDAExe, installDir, shouldCreateDesktopShortcut, slaveExe, fallbackPath=os.path.join(startMenuFolder, "Uninstall NVDA.lnk"), targetPath=os.path.join(installDir, "uninstall.exe"), workingDirectory=installDir, - prependSpecialFolder="AllUsersPrograms" + prependSpecialFolder="AllUsersPrograms", ) # Translators: A label for a shortcut item in start menu to open current user's NVDA configuration directory. @@ -441,7 +444,7 @@ def _updateShortcuts(NVDAExe, installDir, shouldCreateDesktopShortcut, slaveExe, targetPath=slaveExe, arguments="explore_userConfigPath", workingDirectory=installDir, - prependSpecialFolder="AllUsersPrograms" + prependSpecialFolder="AllUsersPrograms", ) # Translators: The label of the NVDA Documentation menu in the Start Menu. @@ -453,7 +456,7 @@ def _updateShortcuts(NVDAExe, installDir, shouldCreateDesktopShortcut, slaveExe, path=os.path.join(docFolder, commandsRefTranslated + ".lnk"), fallbackPath=os.path.join(docFolder, "Commands Quick Reference.lnk"), targetPath=getDocFilePath("keyCommands.html", installDir), - prependSpecialFolder="AllUsersPrograms" + prependSpecialFolder="AllUsersPrograms", ) # Translators: A label for a shortcut in start menu to open NVDA user guide. @@ -462,7 +465,7 @@ def _updateShortcuts(NVDAExe, installDir, shouldCreateDesktopShortcut, slaveExe, path=os.path.join(docFolder, userGuideTranslated + ".lnk"), fallbackPath=os.path.join(docFolder, "User Guide.lnk"), targetPath=getDocFilePath("userGuide.html", installDir), - prependSpecialFolder="AllUsersPrograms" + prependSpecialFolder="AllUsersPrograms", ) # Translators: A label for a shortcut in start menu to open NVDA what's new. @@ -471,7 +474,7 @@ def _updateShortcuts(NVDAExe, installDir, shouldCreateDesktopShortcut, slaveExe, path=os.path.join(docFolder, changesTranslated + ".lnk"), fallbackPath=os.path.join(docFolder, "What's new.lnk"), targetPath=getDocFilePath("changes.html", installDir), - prependSpecialFolder="AllUsersPrograms" + prependSpecialFolder="AllUsersPrograms", ) @@ -486,7 +489,7 @@ def unregisterInstallation(keepDesktopShortcut=False): winreg.DeleteKeyEx( winreg.HKEY_LOCAL_MACHINE, easeOfAccess.RegistryKey.APP.value, - winreg.KEY_WOW64_64KEY + winreg.KEY_WOW64_64KEY, ) easeOfAccess.setAutoStart(easeOfAccess.AutoStartContext.ON_LOGON_SCREEN, False) except WindowsError: @@ -574,7 +577,7 @@ def tryRemoveFile( path: str, numRetries: int = 6, retryInterval: float = 0.5, - rebootOK: bool = False + rebootOK: bool = False, ): dirPath=os.path.dirname(path) tempPath = _createEmptyTempFileForDeletingFile(dir=dirPath) @@ -637,7 +640,7 @@ def tryCopyFile(sourceFilePath,destFilePath): "nvda_noUIAccess.exe", "nvda_uiAccess.exe", "nvda_dmp.exe", - "nvda_slave.exe" + "nvda_slave.exe", } @@ -656,7 +659,7 @@ def _deleteFileGroupOrFail( installDir: str, relativeFilepaths: Iterable[str], numTries: int = 6, - retryWaitInterval: float = 0.5 + retryWaitInterval: float = 0.5, ): """ Delete a group of files in the installer folder. @@ -727,7 +730,7 @@ def install(shouldCreateDesktopShortcut: bool = True, shouldRunAtLogon: bool = T installDir, _nvdaExes.union({"nvda_service.exe"}), numTries=6, - retryWaitInterval=0.5 + retryWaitInterval=0.5, ) unregisterInstallation(keepDesktopShortcut=shouldCreateDesktopShortcut) if prevInstallPath: @@ -747,7 +750,7 @@ def install(shouldCreateDesktopShortcut: bool = True, shouldRunAtLogon: bool = T startMenuFolder, shouldCreateDesktopShortcut, shouldRunAtLogon, - NVDAState._configInLocalAppDataEnabled() + NVDAState._configInLocalAppDataEnabled(), ) COMRegistrationFixes.fixCOMRegistrations() @@ -782,51 +785,55 @@ def registerEaseOfAccess(installDir): winreg.HKEY_LOCAL_MACHINE, easeOfAccess.RegistryKey.APP.value, 0, - winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY + winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY, ) as appKey: - winreg.SetValueEx(appKey, "ApplicationName", None, winreg.REG_SZ, - versionInfo.name) - winreg.SetValueEx(appKey, "Description", None, winreg.REG_SZ, - versionInfo.longName) + winreg.SetValueEx( + appKey, "ApplicationName", None, winreg.REG_SZ, + versionInfo.name, + ) + winreg.SetValueEx( + appKey, "Description", None, winreg.REG_SZ, + versionInfo.longName, + ) winreg.SetValueEx( appKey, "Profile", None, winreg.REG_SZ, - '' + '', ) winreg.SetValueEx( appKey, "SimpleProfile", None, winreg.REG_SZ, - "screenreader" + "screenreader", ) winreg.SetValueEx( appKey, "ATExe", None, winreg.REG_SZ, - "nvda.exe" + "nvda.exe", ) winreg.SetValueEx( appKey, "StartExe", None, winreg.REG_SZ, - os.path.join(installDir, "nvda.exe") + os.path.join(installDir, "nvda.exe"), ) winreg.SetValueEx( appKey, "StartParams", None, winreg.REG_SZ, - "--ease-of-access" + "--ease-of-access", ) winreg.SetValueEx( appKey, "TerminateOnDesktopSwitch", None, winreg.REG_DWORD, - 0 + 0, ) diff --git a/source/keyboardHandler.py b/source/keyboardHandler.py index 36c03a30117..1587f28cb2e 100644 --- a/source/keyboardHandler.py +++ b/source/keyboardHandler.py @@ -119,7 +119,7 @@ def __getattr__(attrName: str) -> Any: if attrName == "SUPPORTED_NVDA_MODIFIER_KEYS" and NVDAState._allowDeprecatedAPI(): log.warning( "keyboardHandler.SUPPORTED_NVDA_MODIFIER_KEYS is deprecated with no direct replacement. " - "Consider using the class config.configFlags.NVDAKey instead." + "Consider using the class config.configFlags.NVDAKey instead.", ) return ("capslock", "numpadinsert", "insert") raise AttributeError(f"module {repr(__name__)} has no attribute {repr(attrName)}") @@ -489,13 +489,14 @@ def _get_displayName(self): # Translators: Reported for an unknown key press. # %s will be replaced with the key code. _("unknown %s") % key[8:] if key.startswith("unknown_") - else localizedKeyLabels.get(key.lower(), key) for key in self._keyNamesInDisplayOrder) + else localizedKeyLabels.get(key.lower(), key) for key in self._keyNamesInDisplayOrder + ) def _get_identifiers(self): keyName = "+".join(self._keyNamesInDisplayOrder) return ( u"kb({layout}):{key}".format(layout=self.layout, key=keyName), - u"kb:{key}".format(key=keyName) + u"kb:{key}".format(key=keyName), ) def _get_shouldReportAsCommand(self): @@ -549,9 +550,12 @@ def reportExtra(self): def _reportToggleKey(self): toggleState = winUser.getKeyState(self.vkCode) & 1 key = self.mainKeyName - ui.message(u"{key} {state}".format( - key=localizedKeyLabels.get(key.lower(), key), - state=_("on") if toggleState else _("off"))) + ui.message( + u"{key} {state}".format( + key=localizedKeyLabels.get(key.lower(), key), + state=_("on") if toggleState else _("off"), + ), + ) def executeScript(self, script): if canModifiersPerformAction(self.generalizedModifiers): diff --git a/source/languageHandler.py b/source/languageHandler.py index e9de9fb1a25..8697f96fe24 100644 --- a/source/languageHandler.py +++ b/source/languageHandler.py @@ -52,7 +52,7 @@ # Windows maps this to "ku-Arab-IQ", however a translation is added for # Central Kurdish in localesData.LANG_NAMES_TO_LOCALIZED_DESCS["ckb"] # and NVDA may drop "Arab-IQ" from this locale to get the language. - 1170: 'ckb' + 1170: 'ckb', } """ Map Windows locale identifiers to language codes. @@ -322,7 +322,7 @@ def getWindowsLanguage(): def _createGettextTranslation( - localeName: str + localeName: str, ) -> Union[None, gettext.GNUTranslations, gettext.NullTranslations]: if localeName in LANGS_WITHOUT_TRANSLATIONS: globalVars.appArgs.language = localeName diff --git a/source/logHandler.py b/source/logHandler.py index 204f28bdb3b..8ae2b5cff5e 100755 --- a/source/logHandler.py +++ b/source/logHandler.py @@ -239,8 +239,10 @@ def _log(self, level, msg, args, exc_info=None, extra=None, codepath=None, activ if stack_info: if stack_info is True: stack_info = traceback.extract_stack(f) - msg += ("\nStack trace:\n" - + stripBasePathFromTracebackText("".join(traceback.format_list(stack_info)).rstrip())) + msg += ( + "\nStack trace:\n" + + stripBasePathFromTracebackText("".join(traceback.format_list(stack_info)).rstrip()) + ) res = super()._log(level, msg, args, exc_info, extra) @@ -283,7 +285,7 @@ def exception(self, msg: str = "", exc_info: Literal[True] | _excInfo_t = True, RPCConstants.RPC.S_SERVER_UNAVAILABLE, RPCConstants.RPC.S_CALL_FAILED_DNE, EPT_S_NOT_REGISTERED, - RPCConstants.RPC.E_CALL_CANCELED + RPCConstants.RPC.E_CALL_CANCELED, ) ) or ( @@ -295,8 +297,10 @@ def exception(self, msg: str = "", exc_info: Literal[True] | _excInfo_t = True, EVENT_E_ALL_SUBSCRIBERS_FAILED, RPCConstants.RPC.E_CALL_REJECTED, RPCConstants.RPC.E_CALL_CANCELED, - RPCConstants.RPC.E_DISCONNECTED - ) or exc.hresult & 0xFFFF == RPCConstants.RPC.S_SERVER_UNAVAILABLE)) + RPCConstants.RPC.E_DISCONNECTED, + ) or exc.hresult & 0xFFFF == RPCConstants.RPC.S_SERVER_UNAVAILABLE + ) + ) or isinstance(exc, exceptions.CallCancelled) ): level = self.DEBUGWARNING @@ -534,7 +538,7 @@ def initialize(shouldDoRemoteLogging=False): # Input: kb(desktop):v logFormatter = Formatter( fmt="{levelname!s} - {codepath!s} ({asctime}) - {threadName} ({thread}):\n{message}", - style="{" + style="{", ) if _shouldDisableLogging(): logHandler = logging.NullHandler() @@ -571,7 +575,7 @@ def initialize(shouldDoRemoteLogging=False): logHandler = RemoteHandler() logFormatter = Formatter( fmt="{codepath!s}:\n{message}", - style="{" + style="{", ) logHandler.setFormatter(logFormatter) log.root.addHandler(logHandler) diff --git a/source/mathPres/__init__.py b/source/mathPres/__init__.py index 06da1a8d4bf..7a337828d32 100644 --- a/source/mathPres/__init__.py +++ b/source/mathPres/__init__.py @@ -88,8 +88,10 @@ def initialize() -> None: except: # noqa: E722 log.warning("MathPlayer 4 not available") else: - registerProvider(provider, speech=not speechProvider, - braille=not brailleProvider, interaction=not interactionProvider) + registerProvider( + provider, speech=not speechProvider, + braille=not brailleProvider, interaction=not interactionProvider, + ) class MathInteractionNVDAObject(Window): diff --git a/source/mathPres/mathPlayer.py b/source/mathPres/mathPlayer.py index 8b686c8f925..25219d1aeb2 100644 --- a/source/mathPres/mathPlayer.py +++ b/source/mathPres/mathPlayer.py @@ -49,7 +49,8 @@ # Commas indicating pauses in navigation messages. r"| ?(?P,) ?" # Actual content. - r"|(?P[^<,]+)") + r"|(?P[^<,]+)", +) PROSODY_COMMANDS = { "pitch": PitchCommand, "volume": VolumeCommand, @@ -100,8 +101,12 @@ def __init__(self, provider=None, mathMl=None): def reportFocus(self): super(MathPlayerInteraction, self).reportFocus() - speech.speak(_processMpSpeech(self.provider._mpSpeech.GetSpokenText(), - self.provider._language)) + speech.speak( + _processMpSpeech( + self.provider._mpSpeech.GetSpokenText(), + self.provider._language, + ), + ) def getBrailleRegions( self, @@ -132,8 +137,10 @@ def getScript(self, gesture): def script_navigate(self, gesture): modNames = gesture.modifierNames try: - text = self.provider._mpNavigation.DoNavigateKeyPress(gesture.vkCode, - "shift" in modNames, "control" in modNames, "alt" in modNames, False) + text = self.provider._mpNavigation.DoNavigateKeyPress( + gesture.vkCode, + "shift" in modNames, "control" in modNames, "alt" in modNames, False, + ) except COMError: return speech.speak(_processMpSpeech(text, self.provider._language)) diff --git a/source/mathType.py b/source/mathType.py index f5ddd6ddb76..078a184cfb6 100644 --- a/source/mathType.py +++ b/source/mathType.py @@ -37,5 +37,5 @@ def getMathMl(oleFormat, runForConversion=True): # 1 is OLECLOSE_NOSAVE lib.MTCloseOleObject(1, mt) return mathPres.stripExtraneousXml( - mathMl.value.decode('utf8') + mathMl.value.decode('utf8'), ) diff --git a/source/mouseHandler.py b/source/mouseHandler.py index 66a50b025bf..70a0fa07eb6 100644 --- a/source/mouseHandler.py +++ b/source/mouseHandler.py @@ -162,7 +162,8 @@ def getMouseRestrictedToScreens(x, y, displays): scrCenterToMouse = mpos - screenCenter mouseLimitedToScreen = screenCenter + wx.RealPoint( # relative to origin max(min(scrCenterToMouse.x, halfWidth.x), -halfWidth.x), - max(min(scrCenterToMouse.y, halfWidth.y), -halfWidth.y)) + max(min(scrCenterToMouse.y, halfWidth.y), -halfWidth.y), + ) edgeToMouse = mpos - mouseLimitedToScreen distFromRectToMouseSqd = abs(edgeToMouse.x) + abs(edgeToMouse.y) if closestDistValue == None or closestDistValue > distFromRectToMouseSqd: # noqa: E711 @@ -202,16 +203,18 @@ def getTotalWidthAndHeightAndMinimumPosition(displays): def executeMouseMoveEvent(x,y): desktopObject=api.getDesktopObject() - displays = [ wx.Display(i).GetGeometry() for i in range(wx.Display.GetCount()) ] + displays = [ wx.Display(i).GetGeometry() for i in range(wx.Display.GetCount())] x, y = getMouseRestrictedToScreens(x, y, displays) screenWidth, screenHeight, minPos = getTotalWidthAndHeightAndMinimumPosition(displays) oldMouseObject = api.getMouseObject() mouseObject = desktopObject.objectFromPoint(x, y) if config.conf["mouse"]["audioCoordinatesOnMouseMove"] and not oldMouseObject.sleepMode: - playAudioCoordinates(x, y, screenWidth, screenHeight, minPos, - config.conf['mouse']['audioCoordinates_detectBrightness'], - config.conf['mouse']['audioCoordinates_blurFactor']) + playAudioCoordinates( + x, y, screenWidth, screenHeight, minPos, + config.conf['mouse']['audioCoordinates_detectBrightness'], + config.conf['mouse']['audioCoordinates_blurFactor'], + ) while mouseObject and mouseObject.beTransparentToMouse: mouseObject=mouseObject.parent @@ -309,7 +312,7 @@ def getLogicalButtonFlags() -> LogicalButtonFlags: def _doClick( downFlag: int, upFlag: int, - releaseDelay: Optional[float] = None + releaseDelay: Optional[float] = None, ): executeMouseEvent(downFlag, 0, 0) if releaseDelay: diff --git a/source/nvwave.py b/source/nvwave.py index 7548b947771..9bd1eaedb72 100644 --- a/source/nvwave.py +++ b/source/nvwave.py @@ -34,7 +34,7 @@ LPSTR, WCHAR, UINT, - LPUINT + LPUINT, ) from comtypes import HRESULT from comtypes.hresult import E_INVALIDARG @@ -85,7 +85,7 @@ class WAVEFORMATEX(Structure): ("nAvgBytesPerSec", DWORD), ("nBlockAlign", WORD), ("wBitsPerSample", WORD), - ("cbSize", WORD) + ("cbSize", WORD), ] LPWAVEFORMATEX = POINTER(WAVEFORMATEX) @@ -100,7 +100,7 @@ class WAVEHDR(Structure): ("dwFlags", DWORD), ("dwLoops", DWORD), ("lpNext", LPWAVEHDR), - ("reserved", DWORD) + ("reserved", DWORD), ] WHDR_DONE = 1 @@ -209,7 +209,7 @@ def __init__( wantDucking: bool = True, buffered: bool = False, purpose: AudioPurpose = AudioPurpose.SPEECH, - ): + ): """Constructor. @param channels: The number of channels of audio; e.g. 2 for stereo, 1 for mono. @param samplesPerSec: Samples per second (hz). @@ -265,7 +265,7 @@ def _setCurrentDevice(self, preferredDevice: typing.Union[str, int]) -> None: if isinstance(preferredDevice, str): self._outputDeviceID = outputDeviceNameToID( preferredDevice, - useDefaultIfInvalid=True # fallback to WAVE_MAPPER + useDefaultIfInvalid=True, # fallback to WAVE_MAPPER ) # If default is used, get the appropriate name. self._outputDeviceName = outputDeviceIDToName(self._outputDeviceID) @@ -277,7 +277,7 @@ def _setCurrentDevice(self, preferredDevice: typing.Union[str, int]) -> None: except (LookupError, TypeError): log.warning( f"Unsupported WavePlayer device argument: {preferredDevice}" - f" Falling back to WAVE_MAPPER" + f" Falling back to WAVE_MAPPER", ) self._setCurrentDevice(WAVE_MAPPER) @@ -287,7 +287,7 @@ def _isPreferredDeviceOpen(self) -> bool: if _isDebugForNvWave(): log.debug( f"preferred device: {self._preferredDeviceName}" - f" current device name: {self._outputDeviceName} (id: {self._outputDeviceID})" + f" current device name: {self._outputDeviceName} (id: {self._outputDeviceID})", ) return self._outputDeviceName == self._preferredDeviceName @@ -318,7 +318,7 @@ def open(self): log.debug( f"Calling winmm.waveOutOpen." f" outputDeviceName: {self._outputDeviceName}" - f" outputDeviceID: {self._outputDeviceID}" + f" outputDeviceID: {self._outputDeviceID}", ) wfx = WAVEFORMATEX() wfx.wFormatTag = WAVE_FORMAT_PCM @@ -336,7 +336,7 @@ def open(self): LPWAVEFORMATEX(wfx), self._waveout_event, 0, - CALLBACK_EVENT + CALLBACK_EVENT, ) except WindowsError: lastOutputDeviceID = self._outputDeviceID @@ -359,7 +359,7 @@ def feed( self, data: typing.Union[bytes, c_void_p], size: typing.Optional[int] = None, - onDone: typing.Optional[typing.Callable] = None + onDone: typing.Optional[typing.Callable] = None, ) -> None: """Feed a chunk of audio data to be played. This is normally synchronous. @@ -586,7 +586,7 @@ def _handleWinmmError(self, message: str): f"Winmm Error: {message}" f" outputDeviceName: {self._outputDeviceName}" f" with id: {self._outputDeviceID}", - stack_info=True + stack_info=True, ) WavePlayer.audioDeviceError_static = True self._close() @@ -594,7 +594,7 @@ def _handleWinmmError(self, message: str): def _safe_winmm_call( self, winmmCall: Callable[[Optional[int]], None], - messageOnFailure: str + messageOnFailure: str, ) -> bool: if not self._waveout: return False @@ -675,7 +675,7 @@ def outputDeviceNameToID(name: str, useDefaultIfInvalid=False) -> int: def playWaveFile( fileName: str, asynchronous: bool = True, - isSpeechWaveFileCommand: bool = False + isSpeechWaveFileCommand: bool = False, ): """plays a specified wave file. @param fileName: the path to the wave file, usually absolute. @@ -698,10 +698,10 @@ def playWaveFile( if not decide_playWaveFile.decide( fileName=fileName, asynchronous=asynchronous, - isSpeechWaveFileCommand=isSpeechWaveFileCommand + isSpeechWaveFileCommand=isSpeechWaveFileCommand, ): log.debug( - "Playing wave file canceled by handler registered to decide_playWaveFile extension point" + "Playing wave file canceled by handler registered to decide_playWaveFile extension point", ) return @@ -725,7 +725,7 @@ def play(): bitsPerSample=f.getsampwidth() * 8, outputDevice=config.conf["speech"]["outputDevice"], wantDucking=False, - purpose=AudioPurpose.SOUNDS + purpose=AudioPurpose.SOUNDS, ) if asynchronous: fileWavePlayerThread = threading.Thread( @@ -823,7 +823,7 @@ def __init__( self._player = NVDAHelper.localLib.wasPlay_create( outputDevice, format, - WasapiWavePlayer._callback + WasapiWavePlayer._callback, ) self._doneCallbacks = {} self._instances[self._player] = self @@ -875,7 +875,7 @@ def open(self): except WindowsError: log.warning( "Couldn't open specified or default audio device. " - "There may be no audio devices." + "There may be no audio devices.", ) WavePlayer.audioDeviceError_static = True raise @@ -891,7 +891,7 @@ def feed( self, data: typing.Union[bytes, c_void_p], size: typing.Optional[int] = None, - onDone: typing.Optional[typing.Callable] = None + onDone: typing.Optional[typing.Callable] = None, ) -> None: """Feed a chunk of audio data to be played. This will block until there is sufficient space in the buffer. @@ -915,7 +915,7 @@ def feed( self._player, data, size if size is not None else len(data), - byref(feedId) if onDone else None + byref(feedId) if onDone else None, ) except WindowsError: # #16722: This might occur on a Remote Desktop server when a client session @@ -986,7 +986,7 @@ def setVolume( *, all: Optional[float] = None, left: Optional[float] = None, - right: Optional[float] = None + right: Optional[float] = None, ): """Set the volume of one or more channels in this stream. Levels must be specified as a number between 0 and 1. @@ -1027,7 +1027,7 @@ def _scheduleIdleCheck(cls): try: core.callLater( cls._IDLE_CHECK_INTERVAL, - cls._idleCheck + cls._idleCheck, ) except core.NVDANotInitializedError: # This can happen when playing the start sound. We close the stream after diff --git a/source/objidl.py b/source/objidl.py index f58fa8115c6..843fa19072b 100644 --- a/source/objidl.py +++ b/source/objidl.py @@ -14,12 +14,14 @@ class IOleWindow(IUnknown): _iid_ = GUID("{00000114-0000-0000-C000-000000000046}") _methods_ = [ - COMMETHOD([], HRESULT, "GetWindow", - (["out"], POINTER(HWND), "phwnd") - ), - COMMETHOD([], HRESULT, "ContextSensitiveHelp", - (["in"], BOOL, "fEnterMode") - ), + COMMETHOD( + [], HRESULT, "GetWindow", + (["out"], POINTER(HWND), "phwnd"), + ), + COMMETHOD( + [], HRESULT, "ContextSensitiveHelp", + (["in"], BOOL, "fEnterMode"), + ), ] class _LARGE_INTEGER(Structure): @@ -52,47 +54,67 @@ class ISequentialStream(IUnknown): _iid_ = GUID('{0C733A30-2A1C-11CE-ADE5-00AA0044773D}') _idlflags_ = [] _methods_ = [ - COMMETHOD([], HRESULT, 'RemoteRead', - ( ['out'], POINTER(c_ubyte), 'pv' ), - ( ['in'], c_ulong, 'cb' ), - ( ['out'], POINTER(c_ulong), 'pcbRead' )), - COMMETHOD([], HRESULT, 'RemoteWrite', - ( ['in'], POINTER(c_ubyte), 'pv' ), - ( ['in'], c_ulong, 'cb' ), - ( ['out'], POINTER(c_ulong), 'pcbWritten' )), + COMMETHOD( + [], HRESULT, 'RemoteRead', + ( ['out'], POINTER(c_ubyte), 'pv'), + ( ['in'], c_ulong, 'cb'), + ( ['out'], POINTER(c_ulong), 'pcbRead'), + ), + COMMETHOD( + [], HRESULT, 'RemoteWrite', + ( ['in'], POINTER(c_ubyte), 'pv'), + ( ['in'], c_ulong, 'cb'), + ( ['out'], POINTER(c_ulong), 'pcbWritten'), + ), ] class IStream(ISequentialStream): _iid_ = GUID('{0000000C-0000-0000-C000-000000000046}') _idlflags_ = [] IStream._methods_ = [ - COMMETHOD([], HRESULT, 'RemoteSeek', - ( ['in'], _LARGE_INTEGER, 'dlibMove' ), - ( ['in'], c_ulong, 'dwOrigin' ), - ( ['out'], POINTER(_ULARGE_INTEGER), 'plibNewPosition' )), - COMMETHOD([], HRESULT, 'SetSize', - ( ['in'], _ULARGE_INTEGER, 'libNewSize' )), - COMMETHOD([], HRESULT, 'RemoteCopyTo', - ( ['in'], POINTER(IStream), 'pstm' ), - ( ['in'], _ULARGE_INTEGER, 'cb' ), - ( ['out'], POINTER(_ULARGE_INTEGER), 'pcbRead' ), - ( ['out'], POINTER(_ULARGE_INTEGER), 'pcbWritten' )), - COMMETHOD([], HRESULT, 'Commit', - ( ['in'], c_ulong, 'grfCommitFlags' )), + COMMETHOD( + [], HRESULT, 'RemoteSeek', + ( ['in'], _LARGE_INTEGER, 'dlibMove'), + ( ['in'], c_ulong, 'dwOrigin'), + ( ['out'], POINTER(_ULARGE_INTEGER), 'plibNewPosition'), + ), + COMMETHOD( + [], HRESULT, 'SetSize', + ( ['in'], _ULARGE_INTEGER, 'libNewSize'), + ), + COMMETHOD( + [], HRESULT, 'RemoteCopyTo', + ( ['in'], POINTER(IStream), 'pstm'), + ( ['in'], _ULARGE_INTEGER, 'cb'), + ( ['out'], POINTER(_ULARGE_INTEGER), 'pcbRead'), + ( ['out'], POINTER(_ULARGE_INTEGER), 'pcbWritten'), + ), + COMMETHOD( + [], HRESULT, 'Commit', + ( ['in'], c_ulong, 'grfCommitFlags'), + ), COMMETHOD([], HRESULT, 'Revert'), - COMMETHOD([], HRESULT, 'LockRegion', - ( ['in'], _ULARGE_INTEGER, 'libOffset' ), - ( ['in'], _ULARGE_INTEGER, 'cb' ), - ( ['in'], c_ulong, 'dwLockType' )), - COMMETHOD([], HRESULT, 'UnlockRegion', - ( ['in'], _ULARGE_INTEGER, 'libOffset' ), - ( ['in'], _ULARGE_INTEGER, 'cb' ), - ( ['in'], c_ulong, 'dwLockType' )), - COMMETHOD([], HRESULT, 'Stat', - ( ['out'], POINTER(tagSTATSTG), 'pstatstg' ), - ( ['in'], c_ulong, 'grfStatFlag' )), - COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IStream)), 'ppstm' )), + COMMETHOD( + [], HRESULT, 'LockRegion', + ( ['in'], _ULARGE_INTEGER, 'libOffset'), + ( ['in'], _ULARGE_INTEGER, 'cb'), + ( ['in'], c_ulong, 'dwLockType'), + ), + COMMETHOD( + [], HRESULT, 'UnlockRegion', + ( ['in'], _ULARGE_INTEGER, 'libOffset'), + ( ['in'], _ULARGE_INTEGER, 'cb'), + ( ['in'], c_ulong, 'dwLockType'), + ), + COMMETHOD( + [], HRESULT, 'Stat', + ( ['out'], POINTER(tagSTATSTG), 'pstatstg'), + ( ['in'], c_ulong, 'grfStatFlag'), + ), + COMMETHOD( + [], HRESULT, 'Clone', + ( ['out'], POINTER(POINTER(IStream)), 'ppstm'), + ), ] class IPersistStream(IPersist): @@ -100,13 +122,19 @@ class IPersistStream(IPersist): _idlflags_ = [] _methods_ = [ COMMETHOD([], HRESULT, 'IsDirty'), - COMMETHOD([], HRESULT, 'Load', - ( ['in'], POINTER(IStream), 'pstm' )), - COMMETHOD([], HRESULT, 'Save', - ( ['in'], POINTER(IStream), 'pstm' ), - ( ['in'], c_int, 'fClearDirty' )), - COMMETHOD([], HRESULT, 'GetSizeMax', - ( ['out'], POINTER(_ULARGE_INTEGER), 'pcbSize' )), + COMMETHOD( + [], HRESULT, 'Load', + ( ['in'], POINTER(IStream), 'pstm'), + ), + COMMETHOD( + [], HRESULT, 'Save', + ( ['in'], POINTER(IStream), 'pstm'), + ( ['in'], c_int, 'fClearDirty'), + ), + COMMETHOD( + [], HRESULT, 'GetSizeMax', + ( ['out'], POINTER(_ULARGE_INTEGER), 'pcbSize'), + ), ] class IRunningObjectTable(IUnknown): @@ -120,42 +148,66 @@ class IEnumString(IUnknown): _iid_ = GUID('{00000101-0000-0000-C000-000000000046}') _idlflags_ = [] IEnumString._methods_ = [ - COMMETHOD([], HRESULT, 'RemoteNext', - ( ['in'], c_ulong, 'celt' ), - ( ['out'], POINTER(WSTRING), 'rgelt' ), - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), - COMMETHOD([], HRESULT, 'Skip', - ( ['in'], c_ulong, 'celt' )), + COMMETHOD( + [], HRESULT, 'RemoteNext', + ( ['in'], c_ulong, 'celt'), + ( ['out'], POINTER(WSTRING), 'rgelt'), + ( ['out'], POINTER(c_ulong), 'pceltFetched'), + ), + COMMETHOD( + [], HRESULT, 'Skip', + ( ['in'], c_ulong, 'celt'), + ), COMMETHOD([], HRESULT, 'Reset'), - COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumString)), 'ppenum' )), + COMMETHOD( + [], HRESULT, 'Clone', + ( ['out'], POINTER(POINTER(IEnumString)), 'ppenum'), + ), ] class IBindCtx(IUnknown): _iid_ = GUID('{0000000E-0000-0000-C000-000000000046}') _idlflags_ = [] _methods_ = [ - COMMETHOD([], HRESULT, 'RegisterObjectBound', - ( ['in'], POINTER(IUnknown), 'punk' )), - COMMETHOD([], HRESULT, 'RevokeObjectBound', - ( ['in'], POINTER(IUnknown), 'punk' )), + COMMETHOD( + [], HRESULT, 'RegisterObjectBound', + ( ['in'], POINTER(IUnknown), 'punk'), + ), + COMMETHOD( + [], HRESULT, 'RevokeObjectBound', + ( ['in'], POINTER(IUnknown), 'punk'), + ), COMMETHOD([], HRESULT, 'ReleaseBoundObjects'), - COMMETHOD([], HRESULT, 'RemoteSetBindOptions', - ( ['in'], POINTER(tagBIND_OPTS2), 'pbindopts' )), - COMMETHOD([], HRESULT, 'RemoteGetBindOptions', - ( ['in', 'out'], POINTER(tagBIND_OPTS2), 'pbindopts' )), - COMMETHOD([], HRESULT, 'GetRunningObjectTable', - ( ['out'], POINTER(POINTER(IRunningObjectTable)), 'pprot' )), - COMMETHOD([], HRESULT, 'RegisterObjectParam', - ( ['in'], WSTRING, 'pszKey' ), - ( ['in'], POINTER(IUnknown), 'punk' )), - COMMETHOD([], HRESULT, 'GetObjectParam', - ( ['in'], WSTRING, 'pszKey' ), - ( ['out'], POINTER(POINTER(IUnknown)), 'ppunk' )), - COMMETHOD([], HRESULT, 'EnumObjectParam', - ( ['out'], POINTER(POINTER(IEnumString)), 'ppenum' )), - COMMETHOD([], HRESULT, 'RevokeObjectParam', - ( ['in'], WSTRING, 'pszKey' )), + COMMETHOD( + [], HRESULT, 'RemoteSetBindOptions', + ( ['in'], POINTER(tagBIND_OPTS2), 'pbindopts'), + ), + COMMETHOD( + [], HRESULT, 'RemoteGetBindOptions', + ( ['in', 'out'], POINTER(tagBIND_OPTS2), 'pbindopts'), + ), + COMMETHOD( + [], HRESULT, 'GetRunningObjectTable', + ( ['out'], POINTER(POINTER(IRunningObjectTable)), 'pprot'), + ), + COMMETHOD( + [], HRESULT, 'RegisterObjectParam', + ( ['in'], WSTRING, 'pszKey'), + ( ['in'], POINTER(IUnknown), 'punk'), + ), + COMMETHOD( + [], HRESULT, 'GetObjectParam', + ( ['in'], WSTRING, 'pszKey'), + ( ['out'], POINTER(POINTER(IUnknown)), 'ppunk'), + ), + COMMETHOD( + [], HRESULT, 'EnumObjectParam', + ( ['out'], POINTER(POINTER(IEnumString)), 'ppenum'), + ), + COMMETHOD( + [], HRESULT, 'RevokeObjectParam', + ( ['in'], WSTRING, 'pszKey'), + ), ] class IMoniker(IPersistStream): @@ -193,105 +245,149 @@ def __next__(self): raise StopIteration IEnumMoniker._methods_ = [ - COMMETHOD([], HRESULT, 'Next', - ( ['in'], c_ulong, 'celt' ), - ( ['out'], POINTER(POINTER(IMoniker)), 'rgelt' ), - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), - COMMETHOD([], HRESULT, 'Skip', - ( ['in'], c_ulong, 'celt' )), + COMMETHOD( + [], HRESULT, 'Next', + ( ['in'], c_ulong, 'celt'), + ( ['out'], POINTER(POINTER(IMoniker)), 'rgelt'), + ( ['out'], POINTER(c_ulong), 'pceltFetched'), + ), + COMMETHOD( + [], HRESULT, 'Skip', + ( ['in'], c_ulong, 'celt'), + ), COMMETHOD([], HRESULT, 'Reset'), - COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumMoniker)), 'ppenum' )), + COMMETHOD( + [], HRESULT, 'Clone', + ( ['out'], POINTER(POINTER(IEnumMoniker)), 'ppenum'), + ), ] IMoniker._methods_ = [ - COMMETHOD([], HRESULT, 'RemoteBindToObject', - ( ['in'], POINTER(IBindCtx), 'pbc' ), - ( ['in'], POINTER(IMoniker), 'pmkToLeft' ), - ( ['in'], POINTER(GUID), 'riidResult' ), - ( ['out'], POINTER(POINTER(IUnknown)), 'ppvResult' )), - COMMETHOD([], HRESULT, 'RemoteBindToStorage', - ( ['in'], POINTER(IBindCtx), 'pbc' ), - ( ['in'], POINTER(IMoniker), 'pmkToLeft' ), - ( ['in'], POINTER(GUID), 'riid' ), - ( ['out'], POINTER(POINTER(IUnknown)), 'ppvObj' )), - COMMETHOD([], HRESULT, 'Reduce', - ( ['in'], POINTER(IBindCtx), 'pbc' ), - ( ['in'], c_ulong, 'dwReduceHowFar' ), - ( ['in', 'out'], POINTER(POINTER(IMoniker)), 'ppmkToLeft' ), - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkReduced' )), - COMMETHOD([], HRESULT, 'ComposeWith', - ( ['in'], POINTER(IMoniker), 'pmkRight' ), - ( ['in'], c_int, 'fOnlyIfNotGeneric' ), - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkComposite' )), - COMMETHOD([], HRESULT, 'Enum', - ( ['in'], c_int, 'fForward' ), - ( ['out'], POINTER(POINTER(IEnumMoniker)), 'ppenumMoniker' )), - COMMETHOD([], HRESULT, 'IsEqual', - ( ['in'], POINTER(IMoniker), 'pmkOtherMoniker' )), - COMMETHOD([], HRESULT, 'Hash', - ( ['out'], POINTER(c_ulong), 'pdwHash' )), - COMMETHOD([], HRESULT, 'IsRunning', - ( ['in'], POINTER(IBindCtx), 'pbc' ), - ( ['in'], POINTER(IMoniker), 'pmkToLeft' ), - ( ['in'], POINTER(IMoniker), 'pmkNewlyRunning' )), + COMMETHOD( + [], HRESULT, 'RemoteBindToObject', + ( ['in'], POINTER(IBindCtx), 'pbc'), + ( ['in'], POINTER(IMoniker), 'pmkToLeft'), + ( ['in'], POINTER(GUID), 'riidResult'), + ( ['out'], POINTER(POINTER(IUnknown)), 'ppvResult'), + ), + COMMETHOD( + [], HRESULT, 'RemoteBindToStorage', + ( ['in'], POINTER(IBindCtx), 'pbc'), + ( ['in'], POINTER(IMoniker), 'pmkToLeft'), + ( ['in'], POINTER(GUID), 'riid'), + ( ['out'], POINTER(POINTER(IUnknown)), 'ppvObj'), + ), + COMMETHOD( + [], HRESULT, 'Reduce', + ( ['in'], POINTER(IBindCtx), 'pbc'), + ( ['in'], c_ulong, 'dwReduceHowFar'), + ( ['in', 'out'], POINTER(POINTER(IMoniker)), 'ppmkToLeft'), + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkReduced'), + ), + COMMETHOD( + [], HRESULT, 'ComposeWith', + ( ['in'], POINTER(IMoniker), 'pmkRight'), + ( ['in'], c_int, 'fOnlyIfNotGeneric'), + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkComposite'), + ), + COMMETHOD( + [], HRESULT, 'Enum', + ( ['in'], c_int, 'fForward'), + ( ['out'], POINTER(POINTER(IEnumMoniker)), 'ppenumMoniker'), + ), + COMMETHOD( + [], HRESULT, 'IsEqual', + ( ['in'], POINTER(IMoniker), 'pmkOtherMoniker'), + ), + COMMETHOD( + [], HRESULT, 'Hash', + ( ['out'], POINTER(c_ulong), 'pdwHash'), + ), + COMMETHOD( + [], HRESULT, 'IsRunning', + ( ['in'], POINTER(IBindCtx), 'pbc'), + ( ['in'], POINTER(IMoniker), 'pmkToLeft'), + ( ['in'], POINTER(IMoniker), 'pmkNewlyRunning'), + ), COMMETHOD( [], HRESULT, 'GetTimeOfLastChange', - ( ['in'], POINTER(IBindCtx), 'pbc' ), - ( ['in'], POINTER(IMoniker), 'pmkToLeft' ), - (['out'], POINTER(winKernel.FILETIME), 'pfiletime') + ( ['in'], POINTER(IBindCtx), 'pbc'), + ( ['in'], POINTER(IMoniker), 'pmkToLeft'), + (['out'], POINTER(winKernel.FILETIME), 'pfiletime'), ), - COMMETHOD([], HRESULT, 'Inverse', - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmk' )), - COMMETHOD([], HRESULT, 'CommonPrefixWith', - ( ['in'], POINTER(IMoniker), 'pmkOther' ), - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkPrefix' )), - COMMETHOD([], HRESULT, 'RelativePathTo', - ( ['in'], POINTER(IMoniker), 'pmkOther' ), - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkRelPath' )), - COMMETHOD([], HRESULT, 'GetDisplayName', - ( ['in'], POINTER(IBindCtx), 'pbc' ), - ( ['in'], POINTER(IMoniker), 'pmkToLeft' ), - ( ['out'], POINTER(WSTRING), 'ppszDisplayName' )), - COMMETHOD([], HRESULT, 'ParseDisplayName', - ( ['in'], POINTER(IBindCtx), 'pbc' ), - ( ['in'], POINTER(IMoniker), 'pmkToLeft' ), - ( ['in'], WSTRING, 'pszDisplayName' ), - ( ['out'], POINTER(c_ulong), 'pchEaten' ), - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkOut' )), - COMMETHOD([], HRESULT, 'IsSystemMoniker', - ( ['out'], POINTER(c_ulong), 'pdwMksys' )), + COMMETHOD( + [], HRESULT, 'Inverse', + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmk'), + ), + COMMETHOD( + [], HRESULT, 'CommonPrefixWith', + ( ['in'], POINTER(IMoniker), 'pmkOther'), + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkPrefix'), + ), + COMMETHOD( + [], HRESULT, 'RelativePathTo', + ( ['in'], POINTER(IMoniker), 'pmkOther'), + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkRelPath'), + ), + COMMETHOD( + [], HRESULT, 'GetDisplayName', + ( ['in'], POINTER(IBindCtx), 'pbc'), + ( ['in'], POINTER(IMoniker), 'pmkToLeft'), + ( ['out'], POINTER(WSTRING), 'ppszDisplayName'), + ), + COMMETHOD( + [], HRESULT, 'ParseDisplayName', + ( ['in'], POINTER(IBindCtx), 'pbc'), + ( ['in'], POINTER(IMoniker), 'pmkToLeft'), + ( ['in'], WSTRING, 'pszDisplayName'), + ( ['out'], POINTER(c_ulong), 'pchEaten'), + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkOut'), + ), + COMMETHOD( + [], HRESULT, 'IsSystemMoniker', + ( ['out'], POINTER(c_ulong), 'pdwMksys'), + ), ] IRunningObjectTable._methods_ = [ - COMMETHOD([], HRESULT, 'Register', - ( ['in'], c_ulong, 'grfFlags' ), - ( ['in'], POINTER(IUnknown), 'punkObject' ), - ( ['in'], POINTER(IMoniker), 'pmkObjectName' ), - ( ['out'], POINTER(c_ulong), 'pdwRegister' )), - COMMETHOD([], HRESULT, 'Revoke', - ( ['in'], c_ulong, 'dwRegister' )), - COMMETHOD([], HRESULT, 'IsRunning', - ( ['in'], POINTER(IMoniker), 'pmkObjectName' )), - COMMETHOD([], HRESULT, 'GetObject', - ( ['in'], POINTER(IMoniker), 'pmkObjectName' ), - ( ['out'], POINTER(POINTER(IUnknown)), 'ppunkObject' )), + COMMETHOD( + [], HRESULT, 'Register', + ( ['in'], c_ulong, 'grfFlags'), + ( ['in'], POINTER(IUnknown), 'punkObject'), + ( ['in'], POINTER(IMoniker), 'pmkObjectName'), + ( ['out'], POINTER(c_ulong), 'pdwRegister'), + ), + COMMETHOD( + [], HRESULT, 'Revoke', + ( ['in'], c_ulong, 'dwRegister'), + ), + COMMETHOD( + [], HRESULT, 'IsRunning', + ( ['in'], POINTER(IMoniker), 'pmkObjectName'), + ), + COMMETHOD( + [], HRESULT, 'GetObject', + ( ['in'], POINTER(IMoniker), 'pmkObjectName'), + ( ['out'], POINTER(POINTER(IUnknown)), 'ppunkObject'), + ), COMMETHOD( [], HRESULT, 'NoteChangeTime', - ( ['in'], c_ulong, 'dwRegister' ), - (['in'], POINTER(winKernel.FILETIME), 'pfiletime') + ( ['in'], c_ulong, 'dwRegister'), + (['in'], POINTER(winKernel.FILETIME), 'pfiletime'), ), COMMETHOD( [], HRESULT, 'GetTimeOfLastChange', - ( ['in'], POINTER(IMoniker), 'pmkObjectName' ), - (['out'], POINTER(winKernel.FILETIME), 'pfiletime') + ( ['in'], POINTER(IMoniker), 'pmkObjectName'), + (['out'], POINTER(winKernel.FILETIME), 'pfiletime'), ), - COMMETHOD([], HRESULT, 'EnumRunning', - ( ['out'], POINTER(POINTER(IEnumMoniker)), 'ppenumMoniker' )), + COMMETHOD( + [], HRESULT, 'EnumRunning', + ( ['out'], POINTER(POINTER(IEnumMoniker)), 'ppenumMoniker'), + ), ] diff --git a/source/oleTypes.py b/source/oleTypes.py index 1b7e153e84c..43e6cf50816 100755 --- a/source/oleTypes.py +++ b/source/oleTypes.py @@ -109,30 +109,42 @@ class IEnumOLEVERB(IUnknown): class tagOLEVERB(Structure): # noqa: F405 pass IEnumOLEVERB._methods_ = [ - COMMETHOD([], HRESULT, 'RemoteNext', - ( ['in'], c_ulong, 'celt' ), # noqa: F405 - ( ['out'], POINTER(tagOLEVERB), 'rgelt' ), # noqa: F405 - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), # noqa: F405 - COMMETHOD([], HRESULT, 'Skip', - ( ['in'], c_ulong, 'celt' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteNext', + ( ['in'], c_ulong, 'celt'), # noqa: F405 + ( ['out'], POINTER(tagOLEVERB), 'rgelt'), # noqa: F405 + ( ['out'], POINTER(c_ulong), 'pceltFetched'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Skip', + ( ['in'], c_ulong, 'celt'), + ), # noqa: F405 COMMETHOD([], HRESULT, 'Reset'), - COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumOLEVERB)), 'ppenum' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Clone', + ( ['out'], POINTER(POINTER(IEnumOLEVERB)), 'ppenum'), + ), # noqa: F405 ] class IEnumUnknown(IUnknown): _case_insensitive_ = True _iid_ = GUID('{00000100-0000-0000-C000-000000000046}') _idlflags_ = [] IEnumUnknown._methods_ = [ - COMMETHOD([], HRESULT, 'RemoteNext', - ( ['in'], c_ulong, 'celt' ), # noqa: F405 - ( ['out'], POINTER(POINTER(IUnknown)), 'rgelt' ), # noqa: F405 - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), # noqa: F405 - COMMETHOD([], HRESULT, 'Skip', - ( ['in'], c_ulong, 'celt' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteNext', + ( ['in'], c_ulong, 'celt'), # noqa: F405 + ( ['out'], POINTER(POINTER(IUnknown)), 'rgelt'), # noqa: F405 + ( ['out'], POINTER(c_ulong), 'pceltFetched'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Skip', + ( ['in'], c_ulong, 'celt'), + ), # noqa: F405 COMMETHOD([], HRESULT, 'Reset'), - COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumUnknown)), 'ppenum' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Clone', + ( ['out'], POINTER(POINTER(IEnumUnknown)), 'ppenum'), + ), # noqa: F405 ] class _RemotableHandle(Structure): # noqa: F405 pass @@ -205,18 +217,24 @@ class IOleContainer(IParseDisplayName): _iid_ = GUID('{0000011B-0000-0000-C000-000000000046}') _idlflags_ = [] IParseDisplayName._methods_ = [ - COMMETHOD([], HRESULT, 'ParseDisplayName', - ( ['in'], POINTER(IBindCtx), 'pbc' ), # noqa: F405 - ( ['in'], WSTRING, 'pszDisplayName' ), - ( ['out'], POINTER(c_ulong), 'pchEaten' ), # noqa: F405 - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkOut' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'ParseDisplayName', + ( ['in'], POINTER(IBindCtx), 'pbc'), # noqa: F405 + ( ['in'], WSTRING, 'pszDisplayName'), + ( ['out'], POINTER(c_ulong), 'pchEaten'), # noqa: F405 + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkOut'), + ), # noqa: F405 ] IOleContainer._methods_ = [ - COMMETHOD([], HRESULT, 'EnumObjects', - ( ['in'], c_ulong, 'grfFlags' ), # noqa: F405 - ( ['out'], POINTER(POINTER(IEnumUnknown)), 'ppenum' )), # noqa: F405 - COMMETHOD([], HRESULT, 'LockContainer', - ( ['in'], c_int, 'fLock' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'EnumObjects', + ( ['in'], c_ulong, 'grfFlags'), # noqa: F405 + ( ['out'], POINTER(POINTER(IEnumUnknown)), 'ppenum'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'LockContainer', + ( ['in'], c_int, 'fLock'), + ), # noqa: F405 ] class IOleObject(IUnknown): _case_insensitive_ = True @@ -243,63 +261,101 @@ class IEnumSTATDATA(IUnknown): _iid_ = GUID('{00000105-0000-0000-C000-000000000046}') _idlflags_ = [] IOleObject._methods_ = [ - COMMETHOD([], HRESULT, 'SetClientSite', - ( ['in'], POINTER(IOleClientSite), 'pClientSite' )), # noqa: F405 - COMMETHOD([], HRESULT, 'GetClientSite', - ( ['out'], POINTER(POINTER(IOleClientSite)), 'ppClientSite' )), # noqa: F405 - COMMETHOD([], HRESULT, 'SetHostNames', - ( ['in'], WSTRING, 'szContainerApp' ), - ( ['in'], WSTRING, 'szContainerObj' )), - COMMETHOD([], HRESULT, 'Close', - ( ['in'], c_ulong, 'dwSaveOption' )), # noqa: F405 - COMMETHOD([], HRESULT, 'SetMoniker', - ( ['in'], c_ulong, 'dwWhichMoniker' ), # noqa: F405 - ( ['in'], POINTER(IMoniker), 'pmk' )), # noqa: F405 - COMMETHOD([], HRESULT, 'GetMoniker', - ( ['in'], c_ulong, 'dwAssign' ), # noqa: F405 - ( ['in'], c_ulong, 'dwWhichMoniker' ), # noqa: F405 - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmk' )), # noqa: F405 - COMMETHOD([], HRESULT, 'InitFromData', - ( ['in'], POINTER(IDataObject), 'pDataObject' ), # noqa: F405 - ( ['in'], c_int, 'fCreation' ), # noqa: F405 - ( ['in'], c_ulong, 'dwReserved' )), # noqa: F405 - COMMETHOD([], HRESULT, 'GetClipboardData', - ( ['in'], c_ulong, 'dwReserved' ), # noqa: F405 - ( ['out'], POINTER(POINTER(IDataObject)), 'ppDataObject' )), # noqa: F405 - COMMETHOD([], HRESULT, 'DoVerb', - ( ['in'], c_int, 'iVerb' ), # noqa: F405 - ( ['in'], POINTER(tagMSG), 'lpmsg' ), # noqa: F405 - ( ['in'], POINTER(IOleClientSite), 'pActiveSite' ), # noqa: F405 - ( ['in'], c_int, 'lindex' ), # noqa: F405 - ( ['in'], wireHWND, 'hwndParent' ), - ( ['in'], POINTER(tagRECT), 'lprcPosRect' )), # noqa: F405 - COMMETHOD([], HRESULT, 'EnumVerbs', - ( ['out'], POINTER(POINTER(IEnumOLEVERB)), 'ppEnumOleVerb' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'SetClientSite', + ( ['in'], POINTER(IOleClientSite), 'pClientSite'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetClientSite', + ( ['out'], POINTER(POINTER(IOleClientSite)), 'ppClientSite'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'SetHostNames', + ( ['in'], WSTRING, 'szContainerApp'), + ( ['in'], WSTRING, 'szContainerObj'), + ), + COMMETHOD( + [], HRESULT, 'Close', + ( ['in'], c_ulong, 'dwSaveOption'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'SetMoniker', + ( ['in'], c_ulong, 'dwWhichMoniker'), # noqa: F405 + ( ['in'], POINTER(IMoniker), 'pmk'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetMoniker', + ( ['in'], c_ulong, 'dwAssign'), # noqa: F405 + ( ['in'], c_ulong, 'dwWhichMoniker'), # noqa: F405 + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmk'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'InitFromData', + ( ['in'], POINTER(IDataObject), 'pDataObject'), # noqa: F405 + ( ['in'], c_int, 'fCreation'), # noqa: F405 + ( ['in'], c_ulong, 'dwReserved'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetClipboardData', + ( ['in'], c_ulong, 'dwReserved'), # noqa: F405 + ( ['out'], POINTER(POINTER(IDataObject)), 'ppDataObject'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'DoVerb', + ( ['in'], c_int, 'iVerb'), # noqa: F405 + ( ['in'], POINTER(tagMSG), 'lpmsg'), # noqa: F405 + ( ['in'], POINTER(IOleClientSite), 'pActiveSite'), # noqa: F405 + ( ['in'], c_int, 'lindex'), # noqa: F405 + ( ['in'], wireHWND, 'hwndParent'), + ( ['in'], POINTER(tagRECT), 'lprcPosRect'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'EnumVerbs', + ( ['out'], POINTER(POINTER(IEnumOLEVERB)), 'ppEnumOleVerb'), + ), # noqa: F405 COMMETHOD([], HRESULT, 'Update'), COMMETHOD([], HRESULT, 'IsUpToDate'), - COMMETHOD([], HRESULT, 'GetUserClassID', - ( ['out'], POINTER(GUID), 'pClsid' )), # noqa: F405 - COMMETHOD([], HRESULT, 'GetUserType', - ( ['in'], c_ulong, 'dwFormOfType' ), # noqa: F405 - ( ['out'], POINTER(WSTRING), 'pszUserType' )), # noqa: F405 - COMMETHOD([], HRESULT, 'SetExtent', - ( ['in'], c_ulong, 'dwDrawAspect' ), # noqa: F405 - ( ['in'], POINTER(tagSIZEL), 'psizel' )), # noqa: F405 - COMMETHOD([], HRESULT, 'GetExtent', - ( ['in'], c_ulong, 'dwDrawAspect' ), # noqa: F405 - ( ['out'], POINTER(tagSIZEL), 'psizel' )), # noqa: F405 - COMMETHOD([], HRESULT, 'Advise', - ( ['in'], POINTER(IAdviseSink), 'pAdvSink' ), # noqa: F405 - ( ['out'], POINTER(c_ulong), 'pdwConnection' )), # noqa: F405 - COMMETHOD([], HRESULT, 'Unadvise', - ( ['in'], c_ulong, 'dwConnection' )), # noqa: F405 - COMMETHOD([], HRESULT, 'EnumAdvise', - ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenumAdvise' )), # noqa: F405 - COMMETHOD([], HRESULT, 'GetMiscStatus', - ( ['in'], c_ulong, 'dwAspect' ), # noqa: F405 - ( ['out'], POINTER(c_ulong), 'pdwStatus' )), # noqa: F405 - COMMETHOD([], HRESULT, 'SetColorScheme', - ( ['in'], POINTER(tagLOGPALETTE), 'pLogpal' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetUserClassID', + ( ['out'], POINTER(GUID), 'pClsid'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetUserType', + ( ['in'], c_ulong, 'dwFormOfType'), # noqa: F405 + ( ['out'], POINTER(WSTRING), 'pszUserType'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'SetExtent', + ( ['in'], c_ulong, 'dwDrawAspect'), # noqa: F405 + ( ['in'], POINTER(tagSIZEL), 'psizel'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetExtent', + ( ['in'], c_ulong, 'dwDrawAspect'), # noqa: F405 + ( ['out'], POINTER(tagSIZEL), 'psizel'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Advise', + ( ['in'], POINTER(IAdviseSink), 'pAdvSink'), # noqa: F405 + ( ['out'], POINTER(c_ulong), 'pdwConnection'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Unadvise', + ( ['in'], c_ulong, 'dwConnection'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'EnumAdvise', + ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenumAdvise'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetMiscStatus', + ( ['in'], c_ulong, 'dwAspect'), # noqa: F405 + ( ['out'], POINTER(c_ulong), 'pdwStatus'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'SetColorScheme', + ( ['in'], POINTER(tagLOGPALETTE), 'pLogpal'), + ), # noqa: F405 ] class __MIDL_IWinTypes_0005(Union): # noqa: F405 pass @@ -377,15 +433,21 @@ class tagFORMATETC(Structure): # noqa: F405 assert alignment(_userHGLOBAL) == 8, alignment(_userHGLOBAL) # noqa: F405 IOleClientSite._methods_ = [ COMMETHOD([], HRESULT, 'SaveObject'), - COMMETHOD([], HRESULT, 'GetMoniker', - ( ['in'], c_ulong, 'dwAssign' ), # noqa: F405 - ( ['in'], c_ulong, 'dwWhichMoniker' ), # noqa: F405 - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmk' )), # noqa: F405 - COMMETHOD([], HRESULT, 'GetContainer', - ( ['out'], POINTER(POINTER(IOleContainer)), 'ppContainer' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetMoniker', + ( ['in'], c_ulong, 'dwAssign'), # noqa: F405 + ( ['in'], c_ulong, 'dwWhichMoniker'), # noqa: F405 + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmk'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetContainer', + ( ['out'], POINTER(POINTER(IOleContainer)), 'ppContainer'), + ), # noqa: F405 COMMETHOD([], HRESULT, 'ShowObject'), - COMMETHOD([], HRESULT, 'OnShowWindow', - ( ['in'], c_int, 'fShow' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'OnShowWindow', + ( ['in'], c_int, 'fShow'), + ), # noqa: F405 COMMETHOD([], HRESULT, 'RequestNewObjectLayout'), ] class __MIDL_IAdviseSink_0002(Union): # noqa: F405 @@ -413,36 +475,56 @@ class IEnumFORMATETC(IUnknown): _iid_ = GUID('{00000103-0000-0000-C000-000000000046}') _idlflags_ = [] IDataObject._methods_ = [ - COMMETHOD([], HRESULT, 'GetData', - ( ['in'], POINTER(tagFORMATETC), 'pformatetcIn' ), # noqa: F405 - ( ['out'], POINTER(wireSTGMEDIUM), 'pmedium' )), # noqa: F405 - COMMETHOD([], HRESULT, 'RemoteGetData', - ( ['in'], POINTER(tagFORMATETC), 'pformatetcIn' ), # noqa: F405 - ( ['out'], POINTER(wireSTGMEDIUM), 'pRemoteMedium' )), # noqa: F405 - COMMETHOD([], HRESULT, 'RemoteGetDataHere', - ( ['in'], POINTER(tagFORMATETC), 'pformatetc' ), # noqa: F405 - ( ['in', 'out'], POINTER(wireSTGMEDIUM), 'pRemoteMedium' )), # noqa: F405 - COMMETHOD([], HRESULT, 'QueryGetData', - ( ['in'], POINTER(tagFORMATETC), 'pformatetc' )), # noqa: F405 - COMMETHOD([], HRESULT, 'GetCanonicalFormatEtc', - ( ['in'], POINTER(tagFORMATETC), 'pformatectIn' ), # noqa: F405 - ( ['out'], POINTER(tagFORMATETC), 'pformatetcOut' )), # noqa: F405 - COMMETHOD([], HRESULT, 'RemoteSetData', - ( ['in'], POINTER(tagFORMATETC), 'pformatetc' ), # noqa: F405 - ( ['in'], POINTER(wireFLAG_STGMEDIUM), 'pmedium' ), # noqa: F405 - ( ['in'], c_int, 'fRelease' )), # noqa: F405 - COMMETHOD([], HRESULT, 'EnumFormatEtc', - ( ['in'], c_ulong, 'dwDirection' ), # noqa: F405 - ( ['out'], POINTER(POINTER(IEnumFORMATETC)), 'ppenumFormatEtc' )), # noqa: F405 - COMMETHOD([], HRESULT, 'DAdvise', - ( ['in'], POINTER(tagFORMATETC), 'pformatetc' ), # noqa: F405 - ( ['in'], c_ulong, 'advf' ), # noqa: F405 - ( ['in'], POINTER(IAdviseSink), 'pAdvSink' ), # noqa: F405 - ( ['out'], POINTER(c_ulong), 'pdwConnection' )), # noqa: F405 - COMMETHOD([], HRESULT, 'DUnadvise', - ( ['in'], c_ulong, 'dwConnection' )), # noqa: F405 - COMMETHOD([], HRESULT, 'EnumDAdvise', - ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenumAdvise' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetData', + ( ['in'], POINTER(tagFORMATETC), 'pformatetcIn'), # noqa: F405 + ( ['out'], POINTER(wireSTGMEDIUM), 'pmedium'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteGetData', + ( ['in'], POINTER(tagFORMATETC), 'pformatetcIn'), # noqa: F405 + ( ['out'], POINTER(wireSTGMEDIUM), 'pRemoteMedium'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteGetDataHere', + ( ['in'], POINTER(tagFORMATETC), 'pformatetc'), # noqa: F405 + ( ['in', 'out'], POINTER(wireSTGMEDIUM), 'pRemoteMedium'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'QueryGetData', + ( ['in'], POINTER(tagFORMATETC), 'pformatetc'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'GetCanonicalFormatEtc', + ( ['in'], POINTER(tagFORMATETC), 'pformatectIn'), # noqa: F405 + ( ['out'], POINTER(tagFORMATETC), 'pformatetcOut'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteSetData', + ( ['in'], POINTER(tagFORMATETC), 'pformatetc'), # noqa: F405 + ( ['in'], POINTER(wireFLAG_STGMEDIUM), 'pmedium'), # noqa: F405 + ( ['in'], c_int, 'fRelease'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'EnumFormatEtc', + ( ['in'], c_ulong, 'dwDirection'), # noqa: F405 + ( ['out'], POINTER(POINTER(IEnumFORMATETC)), 'ppenumFormatEtc'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'DAdvise', + ( ['in'], POINTER(tagFORMATETC), 'pformatetc'), # noqa: F405 + ( ['in'], c_ulong, 'advf'), # noqa: F405 + ( ['in'], POINTER(IAdviseSink), 'pAdvSink'), # noqa: F405 + ( ['out'], POINTER(c_ulong), 'pdwConnection'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'DUnadvise', + ( ['in'], c_ulong, 'dwConnection'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'EnumDAdvise', + ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenumAdvise'), + ), # noqa: F405 ] class tagPOINT(Structure): # noqa: F405 pass @@ -453,14 +535,20 @@ class tagPOINT(Structure): # noqa: F405 assert sizeof(tagPOINT) == 8, sizeof(tagPOINT) # noqa: F405 assert alignment(tagPOINT) == 4, alignment(tagPOINT) # noqa: F405 IAdviseSink._methods_ = [ - COMMETHOD([], HRESULT, 'RemoteOnDataChange', - ( ['in'], POINTER(tagFORMATETC), 'pformatetc' ), # noqa: F405 - ( ['in'], POINTER(wireASYNC_STGMEDIUM), 'pStgmed' )), # noqa: F405 - COMMETHOD([], HRESULT, 'RemoteOnViewChange', - ( ['in'], c_ulong, 'dwAspect' ), # noqa: F405 - ( ['in'], c_int, 'lindex' )), # noqa: F405 - COMMETHOD([], HRESULT, 'RemoteOnRename', - ( ['in'], POINTER(IMoniker), 'pmk' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteOnDataChange', + ( ['in'], POINTER(tagFORMATETC), 'pformatetc'), # noqa: F405 + ( ['in'], POINTER(wireASYNC_STGMEDIUM), 'pStgmed'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteOnViewChange', + ( ['in'], c_ulong, 'dwAspect'), # noqa: F405 + ( ['in'], c_int, 'lindex'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteOnRename', + ( ['in'], POINTER(IMoniker), 'pmk'), + ), # noqa: F405 COMMETHOD([], HRESULT, 'RemoteOnSave'), COMMETHOD([], HRESULT, 'RemoteOnClose'), ] @@ -484,15 +572,21 @@ class __MIDL___MIDL_itf_oleTypes_0005_0001_0001(Structure): # noqa: F405 class tagSTATDATA(Structure): # noqa: F405 pass IEnumSTATDATA._methods_ = [ - COMMETHOD([], HRESULT, 'RemoteNext', - ( ['in'], c_ulong, 'celt' ), # noqa: F405 - ( ['out'], POINTER(tagSTATDATA), 'rgelt' ), # noqa: F405 - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), # noqa: F405 - COMMETHOD([], HRESULT, 'Skip', - ( ['in'], c_ulong, 'celt' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteNext', + ( ['in'], c_ulong, 'celt'), # noqa: F405 + ( ['out'], POINTER(tagSTATDATA), 'rgelt'), # noqa: F405 + ( ['out'], POINTER(c_ulong), 'pceltFetched'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Skip', + ( ['in'], c_ulong, 'celt'), + ), # noqa: F405 COMMETHOD([], HRESULT, 'Reset'), - COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenum' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Clone', + ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenum'), + ), # noqa: F405 ] tagSIZEL._fields_ = [ ('cx', c_int), # noqa: F405 @@ -511,15 +605,21 @@ class tagSTATDATA(Structure): # noqa: F405 assert sizeof(tagMSG) == 28, sizeof(tagMSG) # noqa: F405 assert alignment(tagMSG) == 4, alignment(tagMSG) # noqa: F405 IEnumFORMATETC._methods_ = [ - COMMETHOD([], HRESULT, 'RemoteNext', - ( ['in'], c_ulong, 'celt' ), # noqa: F405 - ( ['out'], POINTER(tagFORMATETC), 'rgelt' ), # noqa: F405 - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), # noqa: F405 - COMMETHOD([], HRESULT, 'Skip', - ( ['in'], c_ulong, 'celt' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'RemoteNext', + ( ['in'], c_ulong, 'celt'), # noqa: F405 + ( ['out'], POINTER(tagFORMATETC), 'rgelt'), # noqa: F405 + ( ['out'], POINTER(c_ulong), 'pceltFetched'), + ), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Skip', + ( ['in'], c_ulong, 'celt'), + ), # noqa: F405 COMMETHOD([], HRESULT, 'Reset'), - COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumFORMATETC)), 'ppenum' )), # noqa: F405 + COMMETHOD( + [], HRESULT, 'Clone', + ( ['out'], POINTER(POINTER(IEnumFORMATETC)), 'ppenum'), + ), # noqa: F405 ] _FLAGGED_BYTE_BLOB._fields_ = [ ('fFlags', c_ulong), # noqa: F405 diff --git a/source/pythonConsole.py b/source/pythonConsole.py index a3a5f19c7ef..d19729270ed 100755 --- a/source/pythonConsole.py +++ b/source/pythonConsole.py @@ -285,7 +285,7 @@ def removeNamespaceSnapshotVars(self): class ConsoleUI( gui.contextHelp.ContextHelpMixin, - wx.Frame # wxPython does not seem to call base class initializer, put last in MRO + wx.Frame, # wxPython does not seem to call base class initializer, put last in MRO ): """The NVDA Python console GUI. """ @@ -405,9 +405,11 @@ def complete(self): # Only show text after the last dot (so as to not keep repeting the class or module in the context menu) label=comp.rsplit('.',1)[-1] item = menu.Append(wx.ID_ANY, label) - self.Bind(wx.EVT_MENU, - lambda evt, completion=comp: self._insertCompletion(original, completion), - item) + self.Bind( + wx.EVT_MENU, + lambda evt, completion=comp: self._insertCompletion(original, completion), + item, + ) self.PopupMenu(menu) menu.Destroy() return True diff --git a/source/review.py b/source/review.py index 993c4390d64..bb0a587b2c3 100644 --- a/source/review.py +++ b/source/review.py @@ -110,7 +110,7 @@ def getCurrentMode(): def setCurrentMode( mode: Union[int, str], - updateReviewPosition: bool = True + updateReviewPosition: bool = True, ) -> Optional[str]: """ Sets the current review mode to the given mode ID or index and updates the review position. diff --git a/source/scriptHandler.py b/source/scriptHandler.py index 3ef4dda420f..285d75e5788 100644 --- a/source/scriptHandler.py +++ b/source/scriptHandler.py @@ -32,9 +32,9 @@ [ Optional[_ScriptFunctionT], "NVDAObjects.NVDAObject", - "inputCore.InputGesture" + "inputCore.InputGesture", ], - Optional[_ScriptFunctionT] + Optional[_ScriptFunctionT], ] _numScriptsQueued=0 #Number of scripts that are queued to be executed @@ -166,7 +166,7 @@ def _getFocusAncestorScript( def _yieldObjectsForFindScript( - gesture: "inputCore.InputGesture" + gesture: "inputCore.InputGesture", ) -> Generator[Tuple["NVDAObjects.NVDAObject", Optional[_ScriptFilterT]], None, None]: """ This generator is used to determine which NVDAObject to perform an input gesture on, @@ -254,7 +254,7 @@ def queueScript(script,gesture): _queueScriptCallback, script, gesture, - _immediate=getattr(gesture, "_immediate", True) + _immediate=getattr(gesture, "_immediate", True), ) def willSayAllResume(gesture): @@ -372,13 +372,13 @@ def script_decorator(decoratedScript): if not isinstance(decoratedScript, types.FunctionType): log.warning( "Using the script decorator is unsupported for %r" % decoratedScript, - stack_info=True + stack_info=True, ) return decoratedScript if not decoratedScript.__name__.startswith("script_"): log.warning( "Can't apply script decorator to %r which name does not start with 'script_'" % decoratedScript.__name__, - stack_info=True + stack_info=True, ) return decoratedScript decoratedScript.__doc__ = description diff --git a/source/setup.py b/source/setup.py index ff083aad0b5..050c8f08ba6 100755 --- a/source/setup.py +++ b/source/setup.py @@ -105,8 +105,8 @@ def getRecursiveDataFiles(dest: str, source: str, excludes: tuple = ()) -> list[ getRecursiveDataFiles( os.path.join(dest, dirName), os.path.join(source, dirName), - excludes=excludes - ) + excludes=excludes, + ), ) return rulesList @@ -115,7 +115,7 @@ def _genManifestTemplate(shouldHaveUIAccess: bool) -> tuple[int, int, bytes]: return ( RT_MANIFEST, 1, - (_manifestTemplate % {"uiAccess": shouldHaveUIAccess}).encode("utf-8") + (_manifestTemplate % {"uiAccess": shouldHaveUIAccess}).encode("utf-8"), ) @@ -132,7 +132,7 @@ def _genManifestTemplate(shouldHaveUIAccess: bool) -> tuple[int, int, bytes]: "product_version": version, "copyright": NVDAcopyright, "company_name": publisher, - } + }, }, # The nvda_uiAccess target will be added at runtime if required. { @@ -146,24 +146,26 @@ def _genManifestTemplate(shouldHaveUIAccess: bool) -> tuple[int, int, bytes]: "product_version": version, "copyright": NVDAcopyright, "company_name": publisher, - } + }, }, ] if _partialArgs.uiAccess: - _py2ExeWindows.insert(1, { - "script": "nvda.pyw", - "dest_base": "nvda_uiAccess", - "icon_resources": [(1, "images/nvda.ico")], - "other_resources": [_genManifestTemplate(shouldHaveUIAccess=True)], - "version_info": { - "version": formatBuildVersionString(), - "description": "NVDA application (has UIAccess)", - "product_name": name, - "product_version": version, - "copyright": NVDAcopyright, - "company_name": publisher, - } - }) + _py2ExeWindows.insert( + 1, { + "script": "nvda.pyw", + "dest_base": "nvda_uiAccess", + "icon_resources": [(1, "images/nvda.ico")], + "other_resources": [_genManifestTemplate(shouldHaveUIAccess=True)], + "version_info": { + "version": formatBuildVersionString(), + "description": "NVDA application (has UIAccess)", + "product_name": name, + "product_version": version, + "copyright": NVDAcopyright, + "company_name": publisher, + }, + }, + ) freeze( @@ -259,39 +261,40 @@ def _genManifestTemplate(shouldHaveUIAccess: bool) -> tuple[int, int, bytes]: (".", glob("../miscDeps/python/*.dll")), (".", ['message.html']), (".", [os.path.join(sys.base_prefix, "python3.dll")]), - ] + ( + ] + ( getLocaleDataFiles() + getRecursiveDataFiles( "synthDrivers", "synthDrivers", excludes=tuple( f"*{ext}" for ext in importlib.machinery.all_suffixes() - ) + ( + ) + ( "*.exp", "*.lib", - "*.pdb" - )) + "*.pdb", + ), + ) + getRecursiveDataFiles( "brailleDisplayDrivers", "brailleDisplayDrivers", excludes=tuple( f"*{ext}" for ext in importlib.machinery.all_suffixes() - ) + ( + ) + ( "*.md", - ) + ), ) + getRecursiveDataFiles( "documentation", "../user_docs", excludes=tuple( f"*{ext}" for ext in importlib.machinery.all_suffixes() - ) + ( + ) + ( "__pycache__", "*.md", "*/user_docs/styles.css", "*/user_docs/numberedHeadings.css", - "*/developerGuide.*" - ) + "*/developerGuide.*", + ), ) ), ) diff --git a/source/shellapi.py b/source/shellapi.py index fb1ae674baa..555b9e64589 100644 --- a/source/shellapi.py +++ b/source/shellapi.py @@ -41,7 +41,7 @@ def ShellExecute( file: str, parameters: Optional[str], directory: Optional[str], - showCmd: int + showCmd: int, ) -> None: if not file: raise RuntimeError("file cannot be None") diff --git a/source/shlobj.py b/source/shlobj.py index c3998ddfc3a..c985a784325 100644 --- a/source/shlobj.py +++ b/source/shlobj.py @@ -41,7 +41,7 @@ class FolderId(str, Enum): def SHGetKnownFolderPath( folderGuid: Union[FolderId, str], dwFlags: int = 0, - hToken: Optional[int] = None + hToken: Optional[int] = None, ) -> str: """Wrapper for `SHGetKnownFolderPath` which caches the results to avoid calling the win32 function unnecessarily.""" @@ -54,7 +54,7 @@ def SHGetKnownFolderPath( comtypes.byref(guid), dwFlags, hToken, - ctypes.byref(pathPointer) + ctypes.byref(pathPointer), ) if res != 0: raise RuntimeError(f"SHGetKnownFolderPath failed with error code {res}") diff --git a/source/speech/__init__.py b/source/speech/__init__.py index 80200f514d6..bb5c818b88f 100644 --- a/source/speech/__init__.py +++ b/source/speech/__init__.py @@ -71,7 +71,7 @@ SequenceItemT, logBadSequenceTypes, GeneratorWithReturn, - _flattenNestedSequences + _flattenNestedSequences, ) __all__ = [ diff --git a/source/speech/commands.py b/source/speech/commands.py index 19291abd69e..08ca88240b6 100644 --- a/source/speech/commands.py +++ b/source/speech/commands.py @@ -33,7 +33,7 @@ class _CancellableSpeechCommand(SpeechCommand): def __init__( self, - reportDevInfo=False + reportDevInfo=False, ): """ @param reportDevInfo: If true, developer info is reported for repr implementation. @@ -304,7 +304,8 @@ def __repr__(self): else: param = "" return "{type}({param})".format( - type=type(self).__name__, param=param) + type=type(self).__name__, param=param, + ) def __eq__(self, __o: object) -> bool: if __o is self: @@ -402,7 +403,7 @@ def run(self,*args, **kwargs): def __repr__(self): return "CallbackCommand(name={name})".format( - name=self._name + name=self._name, ) class BeepCommand(BaseCallbackCommand): @@ -422,12 +423,13 @@ def run(self): self.length, left=self.left, right=self.right, - isSpeechBeepCommand=True + isSpeechBeepCommand=True, ) def __repr__(self): return "BeepCommand({hz}, {length}, left={left}, right={right})".format( - hz=self.hz, length=self.length, left=self.left, right=self.right) + hz=self.hz, length=self.length, left=self.left, right=self.right, + ) class WaveFileCommand(BaseCallbackCommand): """Play a wave file. diff --git a/source/speech/manager.py b/source/speech/manager.py index 6a179b27002..0854a3879a2 100644 --- a/source/speech/manager.py +++ b/source/speech/manager.py @@ -251,7 +251,7 @@ def speak(self, speechSequence: SpeechSequence, priority: Spri): f" | _indexesSpeaking: {self._indexesSpeaking!r}" f" | _curPriQueue valid: {not self._hasNoMoreSpeech()}" f" | _shouldPushWhenDoneSpeaking: {self._shouldPushWhenDoneSpeaking}" - f" | _cancelledLastSpeechWithSynth {self._cancelledLastSpeechWithSynth}" + f" | _cancelledLastSpeechWithSynth {self._cancelledLastSpeechWithSynth}", ) if interrupt: log._speechManagerDebug("Interrupting speech") @@ -274,14 +274,14 @@ def _queueSpeechSequence(self, inSeq: SpeechSequence, priority: Spri) -> bool: queue = self._priQueues.get(priority) log._speechManagerDebug( f"Current priority: {priority}," - f" queLen: {0 if queue is None else len(queue.pendingSequences)}" + f" queLen: {0 if queue is None else len(queue.pendingSequences)}", ) if not queue: queue = self._priQueues[priority] = _ManagerPriorityQueue(priority) else: log._speechManagerDebug( "current queue: %r", # expensive string to build - defer - queue.pendingSequences + queue.pendingSequences, ) first = len(queue.pendingSequences) == 0 queue.pendingSequences.extend(outSeq) @@ -458,7 +458,7 @@ def _buildNextUtterance(self): except IndexError: log.error( f"Checking for cancellations failed, cancelling sequence: {utterance}", - exc_info=True + exc_info=True, ) # Avoid infinite recursion by removing the problematic sequences: del self._curPriQueue.pendingSequences[:lastSequenceIndexAddedToUtterance + 1] @@ -482,7 +482,7 @@ def _checkForCancellations(self, utterance: SpeechSequence) -> bool: utteranceIndex = self._getUtteranceIndex(utterance) if utteranceIndex is None: raise IndexError( - f"no utterance index({utteranceIndex}, cant save cancellable commands" + f"no utterance index({utteranceIndex}, cant save cancellable commands", ) cancellableItems = list( item for item in reversed(utterance) if isinstance(item, _CancellableSpeechCommand) @@ -496,7 +496,7 @@ def _checkForCancellations(self, utterance: SpeechSequence) -> bool: else: item._utteranceIndex = utteranceIndex log._speechManagerDebug( - f"Speaking utterance with cancellable item, index: {utteranceIndex}" + f"Speaking utterance with cancellable item, index: {utteranceIndex}", ) self._cancelCommandsForUtteranceBeingSpokenBySynth[item] = utteranceIndex return True @@ -535,7 +535,7 @@ def _getMostRecentlyCancelledUtterance(self) -> Optional[_IndexT]: f"Length of _cancelCommandsForUtteranceBeingSpokenBySynth: " f"{len(self._cancelCommandsForUtteranceBeingSpokenBySynth)} " f"Length of _indexesSpeaking: " - f"{len(self._indexesSpeaking)} " + f"{len(self._indexesSpeaking)} ", ) cancelledIndexes = ( index for command, index @@ -613,7 +613,7 @@ def _removeCompletedFromQueue(self, index: int) -> Tuple[bool, bool]: # noqa: C break # Found it! else: log._speechManagerDebug( - "Unknown index. Probably from a previous utterance which was cancelled." + "Unknown index. Probably from a previous utterance which was cancelled.", ) return False, False if endOfUtterance: @@ -638,7 +638,7 @@ def _removeCompletedFromQueue(self, index: int) -> Tuple[bool, bool]: # noqa: C for seq in toRemove for item in seq if isinstance( - item, _CancellableSpeechCommand + item, _CancellableSpeechCommand, ) ) for item in cancellables: @@ -646,7 +646,7 @@ def _removeCompletedFromQueue(self, index: int) -> Tuple[bool, bool]: # noqa: C # Debug logging for cancelling expired focus events. log._speechManagerDebug( f"Item is in _cancelCommandsForUtteranceBeingSpokenBySynth: " - f"{item in self._cancelCommandsForUtteranceBeingSpokenBySynth.keys()}" + f"{item in self._cancelCommandsForUtteranceBeingSpokenBySynth.keys()}", ) self._cancelCommandsForUtteranceBeingSpokenBySynth.pop(item, None) del self._curPriQueue.pendingSequences[:seqIndex + 1] @@ -696,7 +696,7 @@ def _handleIndex(self, index: int): if self._indexesSpeaking: log._speechManagerDebug( f"Indexes speaking: {self._indexesSpeaking!r}," - f" queue: {self._curPriQueue.pendingSequences}" + f" queue: {self._curPriQueue.pendingSequences}", ) # Even if we have many indexes, we should only push next speech once. self._pushNextSpeech(False) @@ -710,7 +710,7 @@ def _onSynthDoneSpeaking(self, synth: Optional[synthDriverHandler.SynthDriver] = def _handleDoneSpeaking(self): log._speechManagerDebug( - f"Synth done speaking, should push: {self._shouldPushWhenDoneSpeaking}" + f"Synth done speaking, should push: {self._shouldPushWhenDoneSpeaking}", ) if self._shouldPushWhenDoneSpeaking: self._shouldPushWhenDoneSpeaking = False diff --git a/source/speech/sayAll.py b/source/speech/sayAll.py index 3d920f26d2d..feca97b9179 100644 --- a/source/speech/sayAll.py +++ b/source/speech/sayAll.py @@ -145,7 +145,7 @@ def next(self): # We just started speaking this object, so move the navigator to it. if not api.setNavigatorObject( self.prevObj, - isFocus=self.handler.lastSayAllMode == CURSOR.CARET + isFocus=self.handler.lastSayAllMode == CURSOR.CARET, ): return winKernel.SetThreadExecutionState(winKernel.ES_SYSTEM_REQUIRED) @@ -158,7 +158,7 @@ def next(self): SayAllHandler._speakObject( obj, reason=controlTypes.OutputReason.SAYALL, - _prefixSpeechCommand=callbackCommand + _prefixSpeechCommand=callbackCommand, ) def stop(self): @@ -281,7 +281,7 @@ def _onLineReached(obj=self.reader.obj, state=state): cb = CallbackCommand( _onLineReached, - name="say-all:lineReached" + name="say-all:lineReached", ) # Generate the speech sequence for the reader textInfo @@ -292,7 +292,7 @@ def _onLineReached(obj=self.reader.obj, state=state): self.reader, unit=textInfos.UNIT_READINGCHUNK, reason=controlTypes.OutputReason.SAYALL, - useCache=state + useCache=state, ) seq = list(_flattenNestedSequences(speechGen)) seq.insert(0, cb) @@ -351,7 +351,7 @@ def finish(self): self.handler.speechWithoutPausesInstance.speakWithoutPauses([ EndUtteranceCommand(), cb, - EndUtteranceCommand() + EndUtteranceCommand(), ]) def stop(self): diff --git a/source/speech/speech.py b/source/speech/speech.py index e01cc4676dc..5d9e718b0ac 100644 --- a/source/speech/speech.py +++ b/source/speech/speech.py @@ -48,7 +48,7 @@ SequenceItemT, logBadSequenceTypes, GeneratorWithReturn, - _flattenNestedSequences + _flattenNestedSequences, ) from typing import ( Iterable, @@ -165,7 +165,7 @@ def processText( locale: str, text: str, symbolLevel: characterProcessing.SymbolLevel, - normalize: bool = False + normalize: bool = False, ) -> str: """ Processes text for symbol pronunciation, speech dictionaries and Unicode normalization. @@ -222,12 +222,12 @@ def _getSpeakMessageSpeech( # Translators: This is spoken when the line is considered blank. _("blank"), ] - return [text, ] + return [text] def speakMessage( text: str, - priority: Optional[Spri] = None + priority: Optional[Spri] = None, ) -> None: """Speaks a given message. @param text: the message to speak @@ -264,7 +264,7 @@ def speakSsml( markCallback: "MarkCallbackT | None" = None, symbolLevel: characterProcessing.SymbolLevel | None = None, _prefixSpeechCommand: SpeechCommand | None = None, - priority: Spri | None = None + priority: Spri | None = None, ) -> None: """Speaks a given speech sequence provided as ssml. :param ssml: The SSML data to speak. @@ -296,7 +296,7 @@ def getCurrentLanguage() -> str: def spellTextInfo( info: textInfos.TextInfo, useCharacterDescriptions: bool = False, - priority: Optional[Spri] = None + priority: Optional[Spri] = None, ) -> None: """Spells the text from the given TextInfo, honouring any LangChangeCommand objects it finds if autoLanguageSwitching is enabled.""" if not config.conf['speech']['autoLanguageSwitching']: @@ -314,14 +314,16 @@ def speakSpelling( text: str, locale: Optional[str] = None, useCharacterDescriptions: bool = False, - priority: Optional[Spri] = None + priority: Optional[Spri] = None, ) -> None: # This could be a very large list. In future we could convert this into chunks. - seq = list(getSpellingSpeech( - text, - locale=locale, - useCharacterDescriptions=useCharacterDescriptions - )) + seq = list( + getSpellingSpeech( + text, + locale=locale, + useCharacterDescriptions=useCharacterDescriptions, + ), + ) speak(seq, priority=priority) @@ -476,7 +478,7 @@ def _getSpellingSpeechWithoutCharMode( uppercase and sayCapForCapitals, capPitchChange if uppercase else 0, uppercase and beepForCapitals, - isNormalized and reportNormalizedForCharacterNavigation + isNormalized and reportNormalizedForCharacterNavigation, ) yield EndUtteranceCommand() @@ -532,7 +534,7 @@ def getSingleCharDescription( def getSpellingSpeech( text: str, locale: Optional[str] = None, - useCharacterDescriptions: bool = False + useCharacterDescriptions: bool = False, ) -> Generator[SequenceItemT, None, None]: synth = getSynth() @@ -595,7 +597,7 @@ def speakObjectProperties( reason: OutputReason = OutputReason.QUERY, _prefixSpeechCommand: Optional[SpeechCommand] = None, priority: Optional[Spri] = None, - **allowedProperties + **allowedProperties, ): speechSequence = getObjectPropertiesSpeech( obj, @@ -614,7 +616,7 @@ def getObjectPropertiesSpeech( # noqa: C901 obj: "NVDAObjects.NVDAObject", reason: OutputReason = OutputReason.QUERY, _prefixSpeechCommand: Optional[SpeechCommand] = None, - **allowedProperties + **allowedProperties, ) -> SpeechSequence: if objectBelowLockScreenAndWindowsIsLocked(obj): return [] @@ -762,7 +764,7 @@ def speakObject( obj, reason: OutputReason = OutputReason.QUERY, _prefixSpeechCommand: Optional[SpeechCommand] = None, - priority: Optional[Spri] = None + priority: Optional[Spri] = None, ): sequence = getObjectSpeech( obj, @@ -807,7 +809,7 @@ def getObjectSpeech( obj, reason=reason, _prefixSpeechCommand=_prefixSpeechCommand, - **allowProperties + **allowProperties, ) if reason == OutputReason.ONLYCACHE: return sequence @@ -836,7 +838,7 @@ def getObjectSpeech( if mathPres.speechProvider: try: sequence.extend( - mathPres.speechProvider.getSpeechForMathMl(obj.mathMl) + mathPres.speechProvider.getSpeechForMathMl(obj.mathMl), ) except (NotImplementedError, LookupError): pass @@ -938,7 +940,7 @@ def speakText( text: str, reason: OutputReason = OutputReason.MESSAGE, symbolLevel: characterProcessing.SymbolLevel | None = None, - priority: Spri | None = None + priority: Spri | None = None, ): """Speaks some text. @param text: The text to speak. @@ -977,12 +979,12 @@ def getIndentationSpeech(indentation: str, formatConfig: Dict[str, bool]) -> Spe """ speechIndentConfig = formatConfig["reportLineIndentation"] in ( ReportLineIndentation.SPEECH, - ReportLineIndentation.SPEECH_AND_TONES + ReportLineIndentation.SPEECH_AND_TONES, ) toneIndentConfig = ( formatConfig["reportLineIndentation"] in ( ReportLineIndentation.TONES, - ReportLineIndentation.SPEECH_AND_TONES + ReportLineIndentation.SPEECH_AND_TONES, ) and _speechState.speechMode == SpeechMode.talk ) @@ -993,7 +995,7 @@ def getIndentationSpeech(indentation: str, formatConfig: Dict[str, bool]) -> Spe if speechIndentConfig: indentSequence.append( # Translators: This is spoken when the given line has no indentation. - _("no indent") + _("no indent"), ) return indentSequence @@ -1034,7 +1036,7 @@ def getIndentationSpeech(indentation: str, formatConfig: Dict[str, bool]) -> Spe def speak( # noqa: C901 speechSequence: SpeechSequence, symbolLevel: characterProcessing.SymbolLevel | None = None, - priority: Spri = Spri.NORMAL + priority: Spri = Spri.NORMAL, ): """Speaks a sequence of text and speech commands @param speechSequence: the sequence of text and L{SpeechCommand} objects to speak @@ -1123,7 +1125,7 @@ def speak( # noqa: C901 curLanguage, item, symbolLevel, - normalize=unicodeNormalization + normalize=unicodeNormalization, ) if not inCharacterMode: speechSequence[index]+=CHUNK_SEPARATOR @@ -1132,7 +1134,7 @@ def speak( # noqa: C901 def speakPreselectedText( text: str, - priority: Optional[Spri] = None + priority: Optional[Spri] = None, ): """ Helper method to announce that a newly focused control already has text selected. This method is in contrast with L{speakTextSelected}. @@ -1149,7 +1151,7 @@ def speakPreselectedText( def getPreselectedTextSpeech( - text: str + text: str, ) -> SpeechSequence: """ Helper method to get the speech sequence to announce a newly focused control already has text selected. @@ -1166,13 +1168,13 @@ def getPreselectedTextSpeech( # 'selected' preceding text is intentional. # For example 'selected hello world' _("selected %s"), - text + text, ) def speakTextSelected( text: str, - priority: Optional[Spri] = None + priority: Optional[Spri] = None, ): """ Helper method to announce that the user has caused text to be selected. This method is in contrast with L{speakPreselectedText}. @@ -1190,7 +1192,7 @@ def speakTextSelected( def speakSelectionMessage( message: str, text: str, - priority: Optional[Spri] = None + priority: Optional[Spri] = None, ): seq = _getSelectionMessageSpeech(message, text) if seq: @@ -1222,7 +1224,7 @@ def speakSelectionChange( # noqa: C901 speakSelected: bool = True, speakUnselected: bool = True, generalize: bool = False, - priority: Optional[Spri] = None + priority: Optional[Spri] = None, ): """Speaks a change in selection, either selected or unselected text. @param oldInfo: a TextInfo instance representing what the selection was before @@ -1381,7 +1383,7 @@ def copy(self): def _extendSpeechSequence_addMathForTextInfo( - speechSequence: SpeechSequence, info: textInfos.TextInfo, field: textInfos.Field + speechSequence: SpeechSequence, info: textInfos.TextInfo, field: textInfos.Field, ) -> None: import mathPres if not mathPres.speechProvider: @@ -1401,7 +1403,7 @@ def speakTextInfo( _prefixSpeechCommand: Optional[SpeechCommand] = None, onlyInitialFields: bool = False, suppressBlanks: bool = False, - priority: Optional[Spri] = None + priority: Optional[Spri] = None, ) -> bool: speechGen = getTextInfoSpeech( info, @@ -1411,7 +1413,7 @@ def speakTextInfo( reason, _prefixSpeechCommand, onlyInitialFields, - suppressBlanks + suppressBlanks, ) speechGen = GeneratorWithReturn(speechGen) @@ -1431,7 +1433,7 @@ def getTextInfoSpeech( # noqa: C901 reason: OutputReason = OutputReason.QUERY, _prefixSpeechCommand: Optional[SpeechCommand] = None, onlyInitialFields: bool = False, - suppressBlanks: bool = False + suppressBlanks: bool = False, ) -> Generator[SpeechSequence, None, bool]: if isinstance(useCache,SpeakTextInfoState): speakTextInfoState=useCache @@ -1524,7 +1526,7 @@ def getTextInfoSpeech( # noqa: C901 "end_removedFromControlFieldStack", formatConfig, extraDetail, - reason=reason + reason=reason, ) if fieldSequence: speechSequence.extend(fieldSequence) @@ -1550,7 +1552,7 @@ def getTextInfoSpeech( # noqa: C901 "start_inControlFieldStack", formatConfig, extraDetail, - reason=reason + reason=reason, ) if fieldSequence: speechSequence.extend(fieldSequence) @@ -1579,7 +1581,7 @@ def getTextInfoSpeech( # noqa: C901 "start_addedToControlFieldStack", formatConfig, extraDetail, - reason=reason + reason=reason, ) if fieldSequence: speechSequence.extend(fieldSequence) @@ -1597,7 +1599,7 @@ def getTextInfoSpeech( # noqa: C901 reason=reason, unit=unit, extraDetail=extraDetail, - initialFormat=True + initialFormat=True, ) if fieldSequence: speechSequence.extend(fieldSequence) @@ -1675,14 +1677,16 @@ def getTextInfoSpeech( # noqa: C901 if not presCat or presCat is command.field.PRESCAT_LAYOUT: fieldSequence.append(controlTypes.State.CLICKABLE.displayString) inClickable=True - fieldSequence.extend(info.getControlFieldSpeech( - command.field, - newControlFieldStack, - "start_relative", - formatConfig, - extraDetail, - reason=reason - )) + fieldSequence.extend( + info.getControlFieldSpeech( + command.field, + newControlFieldStack, + "start_relative", + formatConfig, + extraDetail, + reason=reason, + ), + ) newControlFieldStack.append(command.field) elif command.command=="controlEnd": # Exiting a controlField should break a run of clickables @@ -1695,7 +1699,7 @@ def getTextInfoSpeech( # noqa: C901 "end_relative", formatConfig, extraDetail, - reason=reason + reason=reason, ) del newControlFieldStack[-1] if commonFieldCount>len(newControlFieldStack): @@ -1707,7 +1711,7 @@ def getTextInfoSpeech( # noqa: C901 formatConfig, reason=reason, unit=unit, - extraDetail=extraDetail + extraDetail=extraDetail, ) if fieldSequence: inTextChunk=False @@ -1767,7 +1771,7 @@ def getTextInfoSpeech( # noqa: C901 #Finally get speech text for any fields left in new controlFieldStack that are common with the old controlFieldStack (for closing), if extra detail is not requested if autoLanguageSwitching and lastLanguage is not None: speechSequence.append( - LangChangeCommand(None) + LangChangeCommand(None), ) lastLanguage=None if not extraDetail: @@ -1778,7 +1782,7 @@ def getTextInfoSpeech( # noqa: C901 "end_inControlFieldStack", formatConfig, extraDetail, - reason=reason + reason=reason, ) if fieldSequence: speechSequence.extend(fieldSequence) @@ -1825,10 +1829,12 @@ def _getTextInfoSpeech_considerSpelling( if onlyInitialFields or any(isinstance(x, str) for x in speechSequence): yield speechSequence if not onlyInitialFields: - spellingSequence = list(getSpellingSpeech( - textWithFields[0], - locale=language - )) + spellingSequence = list( + getSpellingSpeech( + textWithFields[0], + locale=language, + ), + ) logBadSequenceTypes(spellingSequence) yield spellingSequence if ( @@ -1836,10 +1842,12 @@ def _getTextInfoSpeech_considerSpelling( and unit == textInfos.UNIT_CHARACTER and config.conf["speech"]["delayedCharacterDescriptions"] ): - descriptionSequence = list(getSingleCharDescription( - textWithFields[0], - locale=language, - )) + descriptionSequence = list( + getSingleCharDescription( + textWithFields[0], + locale=language, + ), + ) yield descriptionSequence @@ -1860,7 +1868,7 @@ def _getTextInfoSpeech_updateCache( # and move logic out into smaller helper functions. def getPropertiesSpeech( # noqa: C901 reason: OutputReason = OutputReason.QUERY, - **propertyValues + **propertyValues, ) -> SpeechSequence: textList: SpeechSequence = [] name: Optional[str] = propertyValues.get('name') @@ -1893,7 +1901,7 @@ def getPropertiesSpeech( # noqa: C901 OutputReason.SAYALL, OutputReason.CARET, OutputReason.FOCUS, - OutputReason.QUICKNAV + OutputReason.QUICKNAV, ) or not ( name @@ -1908,9 +1916,10 @@ def getPropertiesSpeech( # noqa: C901 role != controlTypes.Role.MATH or reason not in ( OutputReason.CARET, - OutputReason.SAYALL + OutputReason.SAYALL, ) - )): + ) + ): textList.append(roleText if roleText else role.displayString) if value: textList.append(value) @@ -1988,7 +1997,7 @@ def getPropertiesSpeech( # noqa: C901 # (example output: through row 5 column 3). rowColSpanTranslation: str = _("through row {row} column {column}").format( row=rowNumber + rowSpan - 1, - column=columnNumber + columnSpan - 1 + column=columnNumber + columnSpan - 1, ) textList.append(rowColSpanTranslation) rowCount=propertyValues.get('rowCount',0) @@ -2015,12 +2024,12 @@ def getPropertiesSpeech( # noqa: C901 textList.append( # Translators: Speaks when there are further details/annotations that can be fetched manually. # %s specifies the type of details (e.g. "comment, suggestion, details") - _("has %s") % roleString + _("has %s") % roleString, ) else: textList.append( # Translators: Speaks when there are further details/annotations that can be fetched manually. - _("has details") + _("has details"), ) placeholder: Optional[str] = propertyValues.get('placeholder', None) @@ -2034,7 +2043,7 @@ def getPropertiesSpeech( # noqa: C901 # {total} is replaced with the total number of items in the group. itemPosTranslation: str = _("{number} of {total}").format( number=indexInGroup, - total=similarItemsInGroup + total=similarItemsInGroup, ) textList.append(itemPosTranslation) if 'positionInfo_level' in propertyValues: @@ -2141,7 +2150,7 @@ def getControlFieldSpeech( # noqa: C901 fieldType: str, formatConfig: Optional[Dict[str, bool]] = None, extraDetail: bool = False, - reason: Optional[OutputReason] = None + reason: Optional[OutputReason] = None, ) -> SpeechSequence: if attrs.get('isHidden'): return [] @@ -2152,7 +2161,7 @@ def getControlFieldSpeech( # noqa: C901 ancestorAttrs, formatConfig, reason=reason, - extraDetail=extraDetail + extraDetail=extraDetail, ) childControlCount=int(attrs.get('_childcontrolcount',"0")) role = attrs.get('role', controlTypes.Role.UNKNOWN) @@ -2216,7 +2225,7 @@ def getControlFieldSpeech( # noqa: C901 roleText = attrs.get('roleText') landmark = attrs.get("landmark") if roleText: - roleTextSequence = [roleText, ] + roleTextSequence = [roleText] elif role == controlTypes.Role.LANDMARK and landmark: roleTextSequence = [ f"{aria.landmarkRoles[landmark]} {controlTypes.Role.LANDMARK.displayString}", @@ -2227,7 +2236,7 @@ def getControlFieldSpeech( # noqa: C901 keyboardShortcutSequence = [] if config.conf["presentation"]["reportKeyboardShortcuts"]: keyboardShortcutSequence = getPropertiesSpeech( - reason=reason, keyboardShortcut=keyboardShortcut + reason=reason, keyboardShortcut=keyboardShortcut, ) isCurrentSequence = getPropertiesSpeech(reason=reason, current=isCurrent) hasDetailsSequence = getPropertiesSpeech(reason=reason, hasDetails=hasDetails, detailsRoles=detailsRoles) @@ -2238,7 +2247,7 @@ def getControlFieldSpeech( # noqa: C901 descriptionSequence = [] if description is not None: descriptionSequence = getPropertiesSpeech( - reason=reason, description=description + reason=reason, description=description, ) levelSequence = getPropertiesSpeech(reason=reason, positionInfo_level=level) @@ -2258,7 +2267,7 @@ def getControlFieldSpeech( # noqa: C901 speakEntry=True speakExitForLine = bool( attrs.get('roleText') - or role != controlTypes.Role.LANDMARK + or role != controlTypes.Role.LANDMARK, ) speakExitForOther=True @@ -2295,8 +2304,9 @@ def getControlFieldSpeech( # noqa: C901 getPropertiesSpeech( _tableID=tableID, rowCount=rowCount, - columnCount=columnCount - )) + columnCount=columnCount, + ), + ) tableSeq.extend(levelSequence) types.logBadSequenceTypes(tableSeq) return tableSeq @@ -2329,7 +2339,7 @@ def getControlFieldSpeech( # noqa: C901 and role in ( controlTypes.Role.TABLECELL, controlTypes.Role.TABLECOLUMNHEADER, - controlTypes.Role.TABLEROWHEADER + controlTypes.Role.TABLEROWHEADER, ) and tableID ): @@ -2341,7 +2351,7 @@ def getControlFieldSpeech( # noqa: C901 'columnNumber': (attrs.get("table-columnnumber-presentational") or attrs.get("table-columnnumber")), 'rowSpan': attrs.get("table-rowsspanned"), 'columnSpan': attrs.get("table-columnsspanned"), - 'includeTableCellCoords': reportTableCellCoords + 'includeTableCellCoords': reportTableCellCoords, } if reportTableHeaders in (ReportTableHeaders.ROWS_AND_COLUMNS, ReportTableHeaders.ROWS): getProps['rowHeaderText'] = attrs.get("table-rowheadertext") @@ -2379,7 +2389,7 @@ def getControlFieldSpeech( # noqa: C901 if valueSequence: log.error( f"valueSequence exists when expected none: " - f"valueSequence: {valueSequence!r} placeholderSequence: {placeholderSequence!r}" + f"valueSequence: {valueSequence!r} placeholderSequence: {placeholderSequence!r}", ) valueSequence = placeholderSequence @@ -2420,7 +2430,8 @@ def getControlFieldSpeech( # noqa: C901 and ( (not extraDetail and speakExitForLine) or (extraDetail and speakExitForOther) - )): + ) + ): if all(isinstance(item, str) for item in roleTextSequence): joinedRoleText = " ".join(roleTextSequence) out = [ @@ -2446,11 +2457,11 @@ def getControlFieldSpeech( # noqa: C901 if role == controlTypes.Role.TREEVIEWITEM: if controlTypes.State.EXPANDED in states: out.extend( - getPropertiesSpeech(reason=reason, states={controlTypes.State.EXPANDED}, _role=role) + getPropertiesSpeech(reason=reason, states={controlTypes.State.EXPANDED}, _role=role), ) elif controlTypes.State.COLLAPSED in states: out.extend( - getPropertiesSpeech(reason=reason, states={controlTypes.State.COLLAPSED}, _role=role) + getPropertiesSpeech(reason=reason, states={controlTypes.State.COLLAPSED}, _role=role), ) if levelSequence: out.extend(levelSequence) @@ -2481,7 +2492,7 @@ def getFormatFieldSpeech( # noqa: C901 tableInfo=attrs.get("table-info") oldTableInfo=attrsCache.get("table-info") if attrsCache is not None else None tableSequence = getTableInfoSpeech( - tableInfo, oldTableInfo, extraDetail=extraDetail + tableInfo, oldTableInfo, extraDetail=extraDetail, ) if tableSequence: textList.extend(tableSequence) @@ -2624,9 +2635,12 @@ def getFormatFieldSpeech( # noqa: C901 # Translators: Reported when both the text and background colors change. # {color} will be replaced with the text color. # {backgroundColor} will be replaced with the background color. - textList.append(_("{color} on {backgroundColor}").format( - color=color.name if isinstance(color,colors.RGB) else color, - backgroundColor=bgColorText)) + textList.append( + _("{color} on {backgroundColor}").format( + color=color.name if isinstance(color,colors.RGB) else color, + backgroundColor=bgColorText, + ), + ) elif color and color!=oldColor: # Translators: Reported when the text color changes (but not the background color). # {color} will be replaced with the text color. @@ -2657,17 +2671,21 @@ def getFormatFieldSpeech( # noqa: C901 oldRevision=attrsCache.get("revision-insertion") if attrsCache is not None else None if (revision or oldRevision is not None) and revision!=oldRevision: # Translators: Reported when text is marked as having been inserted - text=(_("inserted") if revision - # Translators: Reported when text is no longer marked as having been inserted. - else _("not inserted")) + text=( + _("inserted") if revision + # Translators: Reported when text is no longer marked as having been inserted. + else _("not inserted") + ) textList.append(text) revision=attrs.get("revision-deletion") oldRevision=attrsCache.get("revision-deletion") if attrsCache is not None else None if (revision or oldRevision is not None) and revision!=oldRevision: # Translators: Reported when text is marked as having been deleted - text=(_("deleted") if revision - # Translators: Reported when text is no longer marked as having been deleted. - else _("not deleted")) + text=( + _("deleted") if revision + # Translators: Reported when text is no longer marked as having been deleted. + else _("not deleted") + ) textList.append(text) revision=attrs.get("revision") oldRevision=attrsCache.get("revision") if attrsCache is not None else None @@ -2685,9 +2703,11 @@ def getFormatFieldSpeech( # noqa: C901 oldMarked=attrsCache.get("marked") if attrsCache is not None else None if (marked or oldMarked is not None) and marked!=oldMarked: # Translators: Reported when text is marked - text=(_("marked") if marked - # Translators: Reported when text is no longer marked - else _("not marked")) + text=( + _("marked") if marked + # Translators: Reported when text is no longer marked + else _("not marked") + ) textList.append(text) # color-highlighted text in Word hlColor = attrs.get("highlight-color") @@ -2698,7 +2718,8 @@ def getFormatFieldSpeech( # noqa: C901 # Translators: Reported when text is color-highlighted _("highlighted in {color}").format(color=colorName) if hlColor # Translators: Reported when text is no longer marked - else _("not highlighted")) + else _("not highlighted") + ) textList.append(text) if formatConfig["reportEmphasis"]: # strong text @@ -2706,35 +2727,43 @@ def getFormatFieldSpeech( # noqa: C901 oldStrong=attrsCache.get("strong") if attrsCache is not None else None if (strong or oldStrong is not None) and strong!=oldStrong: # Translators: Reported when text is marked as strong (e.g. bold) - text=(_("strong") if strong - # Translators: Reported when text is no longer marked as strong (e.g. bold) - else _("not strong")) + text=( + _("strong") if strong + # Translators: Reported when text is no longer marked as strong (e.g. bold) + else _("not strong") + ) textList.append(text) # emphasised text emphasised=attrs.get("emphasised") oldEmphasised=attrsCache.get("emphasised") if attrsCache is not None else None if (emphasised or oldEmphasised is not None) and emphasised!=oldEmphasised: # Translators: Reported when text is marked as emphasised - text=(_("emphasised") if emphasised - # Translators: Reported when text is no longer marked as emphasised - else _("not emphasised")) + text=( + _("emphasised") if emphasised + # Translators: Reported when text is no longer marked as emphasised + else _("not emphasised") + ) textList.append(text) if formatConfig["reportFontAttributes"]: bold=attrs.get("bold") oldBold=attrsCache.get("bold") if attrsCache is not None else None if (bold or oldBold is not None) and bold!=oldBold: # Translators: Reported when text is bolded. - text=(_("bold") if bold - # Translators: Reported when text is not bolded. - else _("no bold")) + text=( + _("bold") if bold + # Translators: Reported when text is not bolded. + else _("no bold") + ) textList.append(text) italic=attrs.get("italic") oldItalic=attrsCache.get("italic") if attrsCache is not None else None if (italic or oldItalic is not None) and italic!=oldItalic: # Translators: Reported when text is italicized. - text=(_("italic") if italic - # Translators: Reported when text is not italicized. - else _("no italic")) + text=( + _("italic") if italic + # Translators: Reported when text is not italicized. + else _("no italic") + ) textList.append(text) strikethrough=attrs.get("strikethrough") oldStrikethrough=attrsCache.get("strikethrough") if attrsCache is not None else None @@ -2742,10 +2771,12 @@ def getFormatFieldSpeech( # noqa: C901 if strikethrough: # Translators: Reported when text is formatted with double strikethrough. # See http://en.wikipedia.org/wiki/Strikethrough - text=(_("double strikethrough") if strikethrough=="double" - # Translators: Reported when text is formatted with strikethrough. - # See http://en.wikipedia.org/wiki/Strikethrough - else _("strikethrough")) + text=( + _("double strikethrough") if strikethrough=="double" + # Translators: Reported when text is formatted with strikethrough. + # See http://en.wikipedia.org/wiki/Strikethrough + else _("strikethrough") + ) else: # Translators: Reported when text is formatted without strikethrough. # See http://en.wikipedia.org/wiki/Strikethrough @@ -2755,9 +2786,11 @@ def getFormatFieldSpeech( # noqa: C901 oldUnderline=attrsCache.get("underline") if attrsCache is not None else None if (underline or oldUnderline is not None) and underline!=oldUnderline: # Translators: Reported when text is underlined. - text=(_("underlined") if underline - # Translators: Reported when text is not underlined. - else _("not underlined")) + text=( + _("underlined") if underline + # Translators: Reported when text is not underlined. + else _("not underlined") + ) textList.append(text) hidden = attrs.get("hidden") oldHidden = attrsCache.get("hidden") if attrsCache is not None else None @@ -2917,14 +2950,14 @@ def getFormatFieldSpeech( # noqa: C901 def getTableInfoSpeech( tableInfo: Optional[Dict[str, Any]], oldTableInfo: Optional[Dict[str, Any]], - extraDetail: bool = False + extraDetail: bool = False, ) -> SpeechSequence: if tableInfo is None and oldTableInfo is None: return [] if tableInfo is None and oldTableInfo is not None: return [ # Translators: Indicates end of a table. - _("out of table") + _("out of table"), ] if not oldTableInfo or tableInfo.get("table-id")!=oldTableInfo.get("table-id"): newTable=True diff --git a/source/speech/speechWithoutPauses.py b/source/speech/speechWithoutPauses.py index 195b2f6b348..91be96d2c81 100644 --- a/source/speech/speechWithoutPauses.py +++ b/source/speech/speechWithoutPauses.py @@ -35,12 +35,12 @@ class SpeechWithoutPauses: _pendingSpeechSequence: SpeechSequence re_last_pause = re.compile( r"^(.*(?<=[^\s.!?])[.!?][\"'”’)]?(?:\s+|$))(.*$)", - re.DOTALL | re.UNICODE + re.DOTALL | re.UNICODE, ) def __init__( self, - speakFunc: Callable[[SpeechSequence], None] + speakFunc: Callable[[SpeechSequence], None], ): """ :param speakFunc: Function used by L{speakWithoutPauses} to speak. This will likely be speech.speak. @@ -54,7 +54,7 @@ def reset(self): def speakWithoutPauses( self, speechSequence: Optional[SpeechSequence], - detectBreaks: bool = True + detectBreaks: bool = True, ) -> bool: """ Speaks the speech sequences given over multiple calls, @@ -63,10 +63,12 @@ def speakWithoutPauses( @return: C{True} if something was actually spoken, C{False} if only buffering occurred. """ - speech = GeneratorWithReturn(self.getSpeechWithoutPauses( - speechSequence, - detectBreaks - )) + speech = GeneratorWithReturn( + self.getSpeechWithoutPauses( + speechSequence, + detectBreaks, + ), + ) for seq in speech: self.speak(seq) return speech.returnValue @@ -74,7 +76,7 @@ def speakWithoutPauses( def getSpeechWithoutPauses( # noqa: C901 self, speechSequence: Optional[SpeechSequence], - detectBreaks: bool = True + detectBreaks: bool = True, ) -> Generator[SpeechSequence, None, bool]: """ Generate speech sequences over multiple calls, @@ -105,7 +107,7 @@ def getSpeechWithoutPauses( # noqa: C901 def _detectBreaksAndGetSpeech( self, - speechSequence: SpeechSequence + speechSequence: SpeechSequence, ) -> Generator[SpeechSequence, None, bool]: lastStartIndex = 0 sequenceLen = len(speechSequence) @@ -115,10 +117,10 @@ def _detectBreaksAndGetSpeech( if index > 0 and lastStartIndex < index: subSequence = speechSequence[lastStartIndex:index] yield from _yieldIfNonEmpty( - self._getSpeech(subSequence) + self._getSpeech(subSequence), ) yield from _yieldIfNonEmpty( - self._flushPendingSpeech() + self._flushPendingSpeech(), ) gotValidSpeech = True lastStartIndex = index + 1 @@ -140,7 +142,7 @@ def _flushPendingSpeech(self) -> SpeechSequence: def _getSpeech( self, - speechSequence: SpeechSequence + speechSequence: SpeechSequence, ) -> SpeechSequence: """ @return: May be an empty sequence diff --git a/source/speech/types.py b/source/speech/types.py index 5fd9a83a628..ca4639d92c4 100644 --- a/source/speech/types.py +++ b/source/speech/types.py @@ -43,7 +43,7 @@ def __iter__(self): def _flattenNestedSequences( - nestedSequences: Union[Iterable[SpeechSequence], GeneratorWithReturn] + nestedSequences: Union[Iterable[SpeechSequence], GeneratorWithReturn], ) -> Generator[SequenceItemT, Any, Optional[bool]]: """Turns [[a,b,c],[d,e]] into [a,b,c,d,e]""" yield from (i for seq in nestedSequences for i in seq) @@ -69,7 +69,7 @@ def logBadSequenceTypes(sequence: SpeechIterable, raiseExceptionOnError=False) - log.error( f"Unexpected Sequence Type: {type(sequence)!r} supplied," f" a {SpeechSequence!r} is required.", - stack_info=True + stack_info=True, ) if raiseExceptionOnError: raise ValueError("Unexpected type in speech sequence") diff --git a/source/speechDictHandler/__init__.py b/source/speechDictHandler/__init__.py index 9546491b49f..2159066906d 100644 --- a/source/speechDictHandler/__init__.py +++ b/source/speechDictHandler/__init__.py @@ -22,7 +22,7 @@ def __getattr__(attrName: str) -> Any: log.warning( "speechDictHandler.speechDictsPath is deprecated, " "instead use NVDAState.WritePaths.speechDictsDir", - stack_info=True + stack_info=True, ) return WritePaths.speechDictsDir raise AttributeError(f"module {repr(__name__)} has no attribute {repr(attrName)}") diff --git a/source/speechDictHandler/dictFormatUpgrade.py b/source/speechDictHandler/dictFormatUpgrade.py index 4217af754c7..e76485833c2 100644 --- a/source/speechDictHandler/dictFormatUpgrade.py +++ b/source/speechDictHandler/dictFormatUpgrade.py @@ -25,7 +25,7 @@ def __getattr__(attrName: str) -> Any: log.warning( "speechDictHandler.dictFormatUpgrade.speechDictsPath is deprecated, " "instead use NVDAState.WritePaths.speechDictsDir", - stack_info=True + stack_info=True, ) return WritePaths.speechDictsDir @@ -33,7 +33,7 @@ def __getattr__(attrName: str) -> Any: log.warning( "speechDictHandler.dictFormatUpgrade.voiceDictsPath is deprecated, " "instead use NVDAState.WritePaths.voiceDictsDir", - stack_info=True + stack_info=True, ) return WritePaths.voiceDictsDir @@ -41,7 +41,7 @@ def __getattr__(attrName: str) -> Any: log.warning( "speechDictHandler.dictFormatUpgrade.voiceDictsBackupPath is deprecated, " "instead use NVDAState.WritePaths.voiceDictsBackupDir", - stack_info=True + stack_info=True, ) return WritePaths.voiceDictsBackupDir @@ -55,8 +55,8 @@ def createVoiceDictFileName(synthName, voiceName): fileNameFormat = u"{synth}-{voice}.dic" return fileNameFormat.format( synth = synthName, - voice = api.filterFileName(voiceName) - ) + voice = api.filterFileName(voiceName), + ) def doAnyUpgrades(synth): """ Do any upgrades required for the synth passed in. @@ -105,7 +105,7 @@ def _doSynthVoiceDictBackupAndMove(synthName, oldFileNameToNewFileNameList=None) # dicts diectory voiceDictGlob = os.path.join( WritePaths.speechDictsDir, - "{synthName}*".format(synthName=synthName) + "{synthName}*".format(synthName=synthName), ) log.debug("voiceDictGlob: %s"%voiceDictGlob) @@ -122,11 +122,13 @@ def _doSynthVoiceDictBackupAndMove(synthName, oldFileNameToNewFileNameList=None) if oldFileNameToNewFileNameList: for oldFname, newFname in oldFileNameToNewFileNameList: if oldFname == actualBasename: - log.debug("renaming {} to {} and moving to {}".format( - actualPath, - newFname, - newDictPath - )) + log.debug( + "renaming {} to {} and moving to {}".format( + actualPath, + newFname, + newDictPath, + ), + ) renameTo = newFname break shutil.move(actualPath, os.path.join(newDictPath, renameTo)) @@ -137,8 +139,8 @@ def getNextVoice(): for ID, (oldName, newName) in espeakNameChanges.items(): yield ( createVoiceDictFileName(synthName, oldName), - createVoiceDictFileName(synthName, newName) - ) + createVoiceDictFileName(synthName, newName), + ) _doSynthVoiceDictBackupAndMove(synthName, list(getNextVoice())) # the ID maped to old and new names for voices in espeak-ng diff --git a/source/speechViewer.py b/source/speechViewer.py index d6398832e2f..85469612331 100644 --- a/source/speechViewer.py +++ b/source/speechViewer.py @@ -23,7 +23,7 @@ # may start at the same time) class SpeechViewerFrame( gui.contextHelp.ContextHelpMixin, - wx.Frame # wxPython does not seem to call base class initializer, put last in MRO + wx.Frame, # wxPython does not seem to call base class initializer, put last in MRO ): helpId = "SpeechViewer" @@ -44,7 +44,7 @@ def __init__(self, onDestroyCallBack: Callable[[], None]): title=_("NVDA Speech Viewer"), size=dialogSize, pos=dialogPos, - style=wx.CAPTION | wx.CLOSE_BOX | wx.RESIZE_BORDER | wx.STAY_ON_TOP + style=wx.CAPTION | wx.CLOSE_BOX | wx.RESIZE_BORDER | wx.STAY_ON_TOP, ) post_sessionLockStateChanged.register(self.onSessionLockStateChange) self._isDestroyed = False @@ -79,29 +79,29 @@ def onSessionLockStateChange(self, isNowLocked: bool): def _createControls(self, sizer, parent): self.textCtrl = wx.TextCtrl( parent, - style=wx.TE_RICH2 | wx.TE_READONLY | wx.TE_MULTILINE + style=wx.TE_RICH2 | wx.TE_READONLY | wx.TE_MULTILINE, ) sizer.Add( self.textCtrl, proportion=1, - flag=wx.EXPAND + flag=wx.EXPAND, ) self.shouldShowOnStartupCheckBox = wx.CheckBox( parent, # Translators: The label for a setting in the speech viewer that controls # whether the speech viewer is shown at startup or not. - label=_("&Show Speech Viewer on Startup") + label=_("&Show Speech Viewer on Startup"), ) sizer.Add( self.shouldShowOnStartupCheckBox, border=5, - flag=wx.EXPAND | wx.ALL + flag=wx.EXPAND | wx.ALL, ) self.shouldShowOnStartupCheckBox.SetValue(config.conf["speechViewer"]["showSpeechViewerAtStartup"]) self.shouldShowOnStartupCheckBox.Bind( wx.EVT_CHECKBOX, - self.onShouldShowOnStartupChanged + self.onShouldShowOnStartupChanged, ) if isLockScreenModeActive(): self.shouldShowOnStartupCheckBox.Disable() @@ -138,8 +138,8 @@ def doDisplaysMatchConfig(self): return len(configSizes) == len(attachedSizes) and all( configSizes[i] == attachedSizes[i] for i in range(len(configSizes))) def getAttachedDisplaySizesAsStringArray(self): - displays = ( wx.Display(i).GetGeometry().GetSize() for i in range(wx.Display.GetCount()) ) - return [repr( (i.width, i.height) ) for i in displays] + displays = ( wx.Display(i).GetGeometry().GetSize() for i in range(wx.Display.GetCount())) + return [repr( (i.width, i.height)) for i in displays] def savePositionInformation(self): position = self.GetPosition() @@ -166,7 +166,7 @@ def activate(): def _setActive( isNowActive: bool, - speechViewerFrame: Optional[SpeechViewerFrame] = None + speechViewerFrame: Optional[SpeechViewerFrame] = None, ) -> None: global _guiFrame, isActive isActive = isNowActive diff --git a/source/speechXml.py b/source/speechXml.py index 9598d298e8c..dd2bf6a0cd0 100644 --- a/source/speechXml.py +++ b/source/speechXml.py @@ -42,8 +42,10 @@ def _buildInvalidXmlRegexp(): # Ranges of invalid characters. # Both start and end are inclusive; i.e. they are both themselves considered invalid. ranges = ((0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F), (0x7F, 0x84), (0x86, 0x9F), (0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF)) - rangeExprs = [u"%s-%s" % (chr(start), chr(end)) - for start, end in ranges] + rangeExprs = [ + u"%s-%s" % (chr(start), chr(end)) + for start, end in ranges + ] leadingSurrogate = u"[\uD800-\uDBFF]" trailingSurrogate = u"[\uDC00-\uDFFF]" return re.compile(( @@ -53,10 +55,11 @@ def _buildInvalidXmlRegexp(): u"|{leading}(?!{trailing})" # Trailing surrogate is invalid if not preceded by a leading surrogate. u"|(?\d+)ms$", re.IGNORECASE) @@ -264,8 +267,10 @@ def __init__(self, defaultLanguage: str): self.defaultLanguage = toXmlLang(defaultLanguage) def generateBalancerCommands(self, speechSequence): - attrs = OrderedDict((("version", "1.0"), ("xmlns", "http://www.w3.org/2001/10/synthesis"), - ("xml:lang", self.defaultLanguage))) + attrs = OrderedDict(( + ("version", "1.0"), ("xmlns", "http://www.w3.org/2001/10/synthesis"), + ("xml:lang", self.defaultLanguage), + )) yield EncloseAllCommand("speak", attrs) for command in super(SsmlConverter, self).generateBalancerCommands(speechSequence): yield command @@ -292,8 +297,10 @@ def _convertProsody(self, command, attr): # Returning to normal. return DelAttrCommand("prosody", attr) else: - return SetAttrCommand("prosody", attr, - "%d%%" % int(command.multiplier* 100)) + return SetAttrCommand( + "prosody", attr, + "%d%%" % int(command.multiplier* 100), + ) def convertPitchCommand(self, command): return self._convertProsody(command, "pitch") diff --git a/source/synthDriverHandler.py b/source/synthDriverHandler.py index d27a4c0ddc9..4dc9d29ed77 100644 --- a/source/synthDriverHandler.py +++ b/source/synthDriverHandler.py @@ -175,7 +175,7 @@ def RateBoostSetting(cls): _("Rate boos&t"), # Translators: Label for a setting in synth settings ring. displayName=pgettext('synth setting', 'Rate boost'), - availableInSettingsRing=True + availableInSettingsRing=True, ) @classmethod @@ -368,7 +368,8 @@ def loadSettings(self, onlyChanged=False): "Loaded changed settings for SynthDriver {}" if onlyChanged else "Loaded settings for SynthDriver {}" - ).format(self.name)) + ).format(self.name), + ) def _get_initialSettingsRingSetting(self): supportedSettings = list(self.supportedSettings) diff --git a/source/synthDrivers/_espeak.py b/source/synthDrivers/_espeak.py index 5ae01873d5f..78d8fb4efbd 100755 --- a/source/synthDrivers/_espeak.py +++ b/source/synthDrivers/_espeak.py @@ -177,7 +177,7 @@ def callback(wav,numsamples,event): player.feed( c_void_p(wav + prevByte), size=indexByte - prevByte, - onDone=lambda indexNum=indexNum: onIndexReached(indexNum) + onDone=lambda indexNum=indexNum: onIndexReached(indexNum), ) prevByte = indexByte if not isSpeaking: @@ -345,7 +345,7 @@ def initialize(indexCallback=None): AUDIO_OUTPUT_SYNCHRONOUS, 300, os.fsencode(eSpeakPath), # #10607: ensure espeak does not exit NVDA's process on errors such as the espeak path being invalid. - espeakINITIALIZE_DONT_EXIT + espeakINITIALIZE_DONT_EXIT, ) if sampleRate <= 0: raise OSError(f"espeak_Initialize failed with code {sampleRate}. Given Espeak data path of {eSpeakPath}") @@ -354,7 +354,7 @@ def initialize(indexCallback=None): samplesPerSec=sampleRate, bitsPerSample=16, outputDevice=config.conf["speech"]["outputDevice"], - buffered=True + buffered=True, ) onIndexReached = indexCallback espeakDLL.espeak_SetSynthCallback(callback) diff --git a/source/synthDrivers/_sapi4.py b/source/synthDrivers/_sapi4.py index e237d90c64b..e0e6fb5c105 100755 --- a/source/synthDrivers/_sapi4.py +++ b/source/synthDrivers/_sapi4.py @@ -17,7 +17,7 @@ HRESULT, POINTER, sizeof, - Structure + Structure, ) from ctypes.wintypes import BYTE, DWORD, LPCWSTR, WORD from comtypes import GUID, IUnknown, STDMETHOD @@ -54,34 +54,40 @@ class VOICECHARSET(c_int): class LANGUAGEW(Structure): - _fields_ = [("LanguageID", LANGID), - ("szDialect", c_wchar * LANG_LEN)] + _fields_ = [ + ("LanguageID", LANGID), + ("szDialect", c_wchar * LANG_LEN), + ] LANGUAGE = LANGUAGEW class TTSMODEINFOW(Structure): - _fields_ = [("gEngine", GUID), - ("szMfgName", c_wchar * TTSI_NAMELEN), - ("szProductName", c_wchar * TTSI_NAMELEN), - ("gModeID", GUID), - ("szModeName", c_wchar * TTSI_NAMELEN), - ("language", LANGUAGEW), - ("szSpeaker", c_wchar * TTSI_NAMELEN), - ("szStyle", c_wchar * TTSI_STYLELEN), - ("wGender", WORD), - ("wAge", WORD), - ("dwFeatures", DWORD), - ("dwInterfaces", DWORD), - ("dwEngineFeatures", DWORD)] + _fields_ = [ + ("gEngine", GUID), + ("szMfgName", c_wchar * TTSI_NAMELEN), + ("szProductName", c_wchar * TTSI_NAMELEN), + ("gModeID", GUID), + ("szModeName", c_wchar * TTSI_NAMELEN), + ("language", LANGUAGEW), + ("szSpeaker", c_wchar * TTSI_NAMELEN), + ("szStyle", c_wchar * TTSI_STYLELEN), + ("wGender", WORD), + ("wAge", WORD), + ("dwFeatures", DWORD), + ("dwInterfaces", DWORD), + ("dwEngineFeatures", DWORD), + ] TTSMODEINFO = TTSMODEINFOW class SDATA(Structure): _fields_ = [("pData", c_void_p), ("dwSize", DWORD)] class TTSMOUTH(Structure): - _fields_ = [("bMouthHeight", BYTE), ("bMouthWidth", BYTE), - ("bMouthUpturn", BYTE), ("bJawOpen", BYTE), - ("bTeethUpperVisible", BYTE), ("bTeethLowerVisible", BYTE), - ("bTonguePosn", BYTE), ("bLipTension", BYTE)] + _fields_ = [ + ("bMouthHeight", BYTE), ("bMouthWidth", BYTE), + ("bMouthUpturn", BYTE), ("bJawOpen", BYTE), + ("bTeethUpperVisible", BYTE), ("bTeethLowerVisible", BYTE), + ("bTonguePosn", BYTE), ("bLipTension", BYTE), + ] def TextSDATA(text): d = SDATA() @@ -100,7 +106,7 @@ class ITTSAttributesW(IUnknown): STDMETHOD(HRESULT, "SpeedGet", [POINTER(DWORD)]), STDMETHOD(HRESULT, "SpeedSet", [DWORD]), STDMETHOD(HRESULT, "VolumeGet", [POINTER(DWORD)]), - STDMETHOD(HRESULT, "VolumeSet", [DWORD]) + STDMETHOD(HRESULT, "VolumeSet", [DWORD]), ] ITTSAttributes = ITTSAttributesW @@ -112,7 +118,7 @@ class ITTSBufNotifySink(IUnknown): STDMETHOD(HRESULT, "TextDataDone", [QWORD, DWORD]), STDMETHOD(HRESULT, "TextDataStarted", [QWORD]), STDMETHOD(HRESULT, "BookMark", [QWORD, DWORD]), - STDMETHOD(HRESULT, "WordPosition", [QWORD, DWORD]) + STDMETHOD(HRESULT, "WordPosition", [QWORD, DWORD]), ] class ITTSCentralW(IUnknown): @@ -129,7 +135,7 @@ class ITTSCentralW(IUnknown): STDMETHOD(HRESULT, "AudioResume"), STDMETHOD(HRESULT, "AudioReset"), STDMETHOD(HRESULT, "Register", [c_void_p, GUID, POINTER(DWORD)]), - STDMETHOD(HRESULT, "UnRegister", [DWORD]) + STDMETHOD(HRESULT, "UnRegister", [DWORD]), ] ITTSCentral = ITTSCentralW @@ -140,20 +146,28 @@ class IAudioMultiMediaDevice(IUnknown): IAudioMultiMediaDevice._methods_ = [ STDMETHOD(HRESULT, "CustomMessage", [c_uint, SDATA]), STDMETHOD(HRESULT, "DeviceNumGet", [POINTER(DWORD)]), - STDMETHOD(HRESULT, "DeviceNumSet", [DWORD]) + STDMETHOD(HRESULT, "DeviceNumSet", [DWORD]), ] class ITTSEnumW(IUnknown): _iid_ = GUID("{6B837B20-4A47-101B-931A-00AA0047BA4F}") ITTSEnumW._methods_ = [ - STDMETHOD(HRESULT, "Next", [c_ulong, POINTER(TTSMODEINFOW), - POINTER(c_ulong)]), + STDMETHOD( + HRESULT, "Next", [ + c_ulong, POINTER(TTSMODEINFOW), + POINTER(c_ulong), + ], + ), STDMETHOD(HRESULT, "Skip", [c_ulong]), STDMETHOD(HRESULT, "Reset"), STDMETHOD(HRESULT, "Clone", [POINTER(POINTER(ITTSEnumW))]), - STDMETHOD(HRESULT, "Select", [GUID, POINTER(POINTER(ITTSCentralW)), - POINTER(IUnknown)]) + STDMETHOD( + HRESULT, "Select", [ + GUID, POINTER(POINTER(ITTSCentralW)), + POINTER(IUnknown), + ], + ), ] ITTSEnum = ITTSEnumW @@ -165,8 +179,12 @@ class ITTSNotifySinkW(IUnknown): STDMETHOD(HRESULT, "AttribChanged", [DWORD]), STDMETHOD(HRESULT, "AudioStart", [QWORD]), STDMETHOD(HRESULT, "AudioStop", [QWORD]), - STDMETHOD(HRESULT, "Visual", [QWORD, c_wchar, c_wchar, DWORD, - POINTER(TTSMOUTH)]) + STDMETHOD( + HRESULT, "Visual", [ + QWORD, c_wchar, c_wchar, DWORD, + POINTER(TTSMOUTH), + ], + ), ] ITTSNotifySink = ITTSNotifySinkW diff --git a/source/synthDrivers/espeak.py b/source/synthDrivers/espeak.py index a0f20a7f77a..19041a2e953 100644 --- a/source/synthDrivers/espeak.py +++ b/source/synthDrivers/espeak.py @@ -262,7 +262,7 @@ def _normalizeLangCommand(self, command: LangChangeCommand) -> LangChangeCommand # Check for any language where the language code matches, regardless of dialect: e.g. ru-ru to ru matchingLangs = filter( lambda lang: stripLocaleFromLangCode(lang) == langWithoutLocale, - lowerCaseAvailableLangs + lowerCaseAvailableLangs, ) anyLocaleMatchingLang = next(matchingLangs, None) diff --git a/source/synthDrivers/oneCore.py b/source/synthDrivers/oneCore.py index 48012bfe80c..6ba80220d30 100644 --- a/source/synthDrivers/oneCore.py +++ b/source/synthDrivers/oneCore.py @@ -15,7 +15,7 @@ Optional, Set, Tuple, - Union + Union, ) from collections import OrderedDict import ctypes @@ -264,7 +264,7 @@ def _maybeInitPlayer(self, wav): channels=wav.getnchannels(), samplesPerSec=samplesPerSec, bitsPerSample=bytesPerSample * 8, - outputDevice=config.conf["speech"]["outputDevice"] + outputDevice=config.conf["speech"]["outputDevice"], ) def terminate(self): @@ -286,8 +286,10 @@ def cancel(self): # There might be more text pending. Throw it away. if self.supportsProsodyOptions: # In this case however, we must keep any parameter changes. - self._queuedSpeech = [item for item in self._queuedSpeech - if not isinstance(item, str)] + self._queuedSpeech = [ + item for item in self._queuedSpeech + if not isinstance(item, str) + ] else: self._queuedSpeech = [] if self._player: @@ -302,7 +304,7 @@ def speak(self, speechSequence: SpeechSequence) -> None: self.availableLanguages, self._rate, self._pitch, - self._volume + self._volume, ) text = conv.convertToXml(speechSequence) # #7495: Calling WaveOutOpen blocks for ~100 ms if called from the callback @@ -477,7 +479,7 @@ def _callback(self, bytes, len, markers): self._player.feed( ctypes.c_void_p(data + prevPos), size=pos - prevPos, - onDone=lambda index=index: synthIndexReached.notify(synth=self, index=index) + onDone=lambda index=index: synthIndexReached.notify(synth=self, index=index), ) prevPos = pos if self._wasCancelled: diff --git a/source/synthDrivers/sapi4.py b/source/synthDrivers/sapi4.py index bc4d15dac4b..21abe709e0a 100755 --- a/source/synthDrivers/sapi4.py +++ b/source/synthDrivers/sapi4.py @@ -32,7 +32,7 @@ TTSFEATURE_SPEED, TTSFEATURE_VOLUME, TTSMODEINFO, - VOICECHARSET + VOICECHARSET, ) import config import nvwave @@ -46,7 +46,7 @@ PitchCommand, RateCommand, VolumeCommand, - BaseProsodyCommand + BaseProsodyCommand, ) from speech.types import SpeechSequence @@ -194,7 +194,7 @@ def speak(self, speechSequence: SpeechSequence): flags, TextSDATA(text), self._bufSinkPtr, - ITTSBufNotifySink._iid_ + ITTSBufNotifySink._iid_, ) def cancel(self): diff --git a/source/synthDrivers/sapi5.py b/source/synthDrivers/sapi5.py index 12c9ca5e856..2f051428b27 100644 --- a/source/synthDrivers/sapi5.py +++ b/source/synthDrivers/sapi5.py @@ -321,8 +321,10 @@ def outputTags(): tagsChanged[0] = True elif isinstance(item, PhonemeCommand): try: - textList.append(u'%s' - % (self._convertPhoneme(item.ipa), item.text or u"")) + textList.append( + u'%s' + % (self._convertPhoneme(item.ipa), item.text or u""), + ) except LookupError: log.debugWarning("Couldn't convert character in IPA string: %s" % item.ipa) if item.text: diff --git a/source/synthSettingsRing.py b/source/synthSettingsRing.py index f9875d73c53..72e81cfb8c3 100644 --- a/source/synthSettingsRing.py +++ b/source/synthSettingsRing.py @@ -234,5 +234,5 @@ def updateSupportedSettings(self,synth): # We have just reverted to first setting, so report this change to user queueHandler.queueFunction( queueHandler.eventQueue, - ui.message,"%s %s" % (self.currentSettingName,self.currentSettingValue) + ui.message,"%s %s" % (self.currentSettingName,self.currentSettingValue), ) diff --git a/source/systemUtils.py b/source/systemUtils.py index 4cfc0d6d23b..6f6b6db361e 100644 --- a/source/systemUtils.py +++ b/source/systemUtils.py @@ -72,7 +72,7 @@ def hasUiAccess(): ctypes.windll.advapi32.OpenProcessToken( ctypes.windll.kernel32.GetCurrentProcess(), winKernel.MAXIMUM_ALLOWED, - ctypes.byref(token) + ctypes.byref(token), ) try: val = ctypes.wintypes.DWORD() @@ -81,7 +81,7 @@ def hasUiAccess(): TokenUIAccess, ctypes.byref(val), ctypes.sizeof(ctypes.wintypes.DWORD), - ctypes.byref(ctypes.wintypes.DWORD()) + ctypes.byref(ctypes.wintypes.DWORD()), ) return bool(val.value) finally: @@ -103,7 +103,7 @@ class TokenOrigin(ctypes.Structure): This structure is used in calls to the Win32 GetTokenInformation function. """ _fields_ = [ - ("originatingLogonSession", ctypes.c_ulonglong) # OriginatingLogonSession in C structure + ("originatingLogonSession", ctypes.c_ulonglong), # OriginatingLogonSession in C structure ] @@ -122,7 +122,7 @@ def getProcessLogonSessionId(processHandle: int) -> int: if not ctypes.windll.advapi32.OpenProcessToken( processHandle, winKernel.MAXIMUM_ALLOWED, - ctypes.byref(token) + ctypes.byref(token), ): raise ctypes.WinError() try: @@ -132,7 +132,7 @@ def getProcessLogonSessionId(processHandle: int) -> int: TOKEN_ORIGIN, ctypes.byref(val), ctypes.sizeof(val), - ctypes.byref(ctypes.wintypes.DWORD()) + ctypes.byref(ctypes.wintypes.DWORD()), ): raise ctypes.WinError() return val.originatingLogonSession @@ -179,7 +179,7 @@ def _getDesktopName() -> str: UOI_NAME, byref(name), sizeof(name), - None + None, ) return name.value @@ -231,7 +231,7 @@ def __init__(self, func: Callable[..., _execAndPumpResT], *args, **kwargs) -> No self.funcRes: Optional[_execAndPumpResT] = None fname = repr(func) super().__init__( - name=f"{self.__class__.__module__}.{self.__class__.__qualname__}({fname})" + name=f"{self.__class__.__module__}.{self.__class__.__qualname__}({fname})", ) self.threadExc: Exception | None = None self.start() diff --git a/source/textInfos/__init__.py b/source/textInfos/__init__.py index 67b3bb63297..5a9551e4cf8 100755 --- a/source/textInfos/__init__.py +++ b/source/textInfos/__init__.py @@ -67,7 +67,7 @@ def getPresentationCategory( ancestors, formatConfig, reason=OutputReason.CARET, - extraDetail=False + extraDetail=False, ): role = self.get("role", controlTypes.Role.UNKNOWN) states = self.get("states", set()) @@ -152,7 +152,7 @@ def getPresentationCategory( controlTypes.Role.FOOTNOTE, controlTypes.Role.ENDNOTE, controlTypes.Role.EMBEDDEDOBJECT, - controlTypes.Role.MATH + controlTypes.Role.MATH, ) or ( extraDetail and role == controlTypes.Role.LISTITEM @@ -180,10 +180,12 @@ def getPresentationCategory( controlTypes.Role.ARTICLE, controlTypes.Role.MARKED_CONTENT, ) - or (role == controlTypes.Role.EDITABLETEXT and ( - controlTypes.State.READONLY not in states - or controlTypes.State.FOCUSABLE in states - ) and controlTypes.State.MULTILINE in states) + or ( + role == controlTypes.Role.EDITABLETEXT and ( + controlTypes.State.READONLY not in states + or controlTypes.State.FOCUSABLE in states + ) and controlTypes.State.MULTILINE in states + ) or (role == controlTypes.Role.LIST and controlTypes.State.READONLY in states) or (role == controlTypes.Role.LANDMARK or landmark) or (controlTypes.State.FOCUSABLE in states and controlTypes.State.EDITABLE in states) @@ -592,12 +594,12 @@ def getControlFieldSpeech( fieldType: str, formatConfig: Optional[Dict[str, bool]] = None, extraDetail: bool = False, - reason: Optional[OutputReason] = None + reason: Optional[OutputReason] = None, ) -> SpeechSequence: # Import late to avoid circular import. import speech sequence = speech.getControlFieldSpeech( - attrs, ancestorAttrs, fieldType, formatConfig, extraDetail, reason + attrs, ancestorAttrs, fieldType, formatConfig, extraDetail, reason, ) _logBadSequenceTypes(sequence) return sequence @@ -631,7 +633,7 @@ def getFormatFieldSpeech( reason=reason, unit=unit, extraDetail=extraDetail, - initialFormat=initialFormat + initialFormat=initialFormat, ) def activate(self): @@ -911,7 +913,7 @@ def _cmp(self, other: "TextInfoEndpoint") -> int: def __init__( self, textInfo: TextInfo, - isStart: bool + isStart: bool, ): """ @param textInfo: the TextInfo instance you wish to represent an endpoint of. diff --git a/source/textInfos/offsets.py b/source/textInfos/offsets.py index 23d1e324f7d..e5d96304b22 100755 --- a/source/textInfos/offsets.py +++ b/source/textInfos/offsets.py @@ -234,15 +234,15 @@ def _get_boundingRects(self) -> List[locationHelper.RectLTWH]: # noqa: C901 rects.append( locationHelper.RectLTWH.fromCollection( startLocation if lineStart == startOffset else getLocationFromOffset(lineStart), - getLocationFromOffset(inclusiveLineEnd) - ) + getLocationFromOffset(inclusiveLineEnd), + ), ) offset = inclusiveLineEnd + 1 else: rects.append( locationHelper.RectLTWH.fromCollection( - startLocation - ) + startLocation, + ), ) intersectedRects = [] for rect in rects: @@ -344,7 +344,7 @@ def _calculateUniscribeOffsets(self, lineText: str, unit: str, relOffset: int) - uniscribeLineLength, relOffset, ctypes.byref(relStart), - ctypes.byref(relEnd) + ctypes.byref(relEnd), ): relStart = relStart.value relEnd = min(lineLength, relEnd.value) diff --git a/source/textUtils/__init__.py b/source/textUtils/__init__.py index 19d5dee4129..d0e14a438e5 100644 --- a/source/textUtils/__init__.py +++ b/source/textUtils/__init__.py @@ -66,7 +66,7 @@ def strToEncodedOffsets( if strEnd is not None and strEnd < strStart: raise ValueError( "strEnd=%d must be greater than or equal to strStart=%d" - % (strEnd, strStart) + % (strEnd, strStart), ) if strStart < 0 or strStart > self.strLength: if raiseOnError: @@ -95,7 +95,7 @@ def encodedToStrOffsets( """ if encodedEnd is not None and encodedEnd < encodedStart: raise ValueError( - f"{encodedEnd=} must be greater than or equal to {encodedStart=}" + f"{encodedEnd=} must be greater than or equal to {encodedStart=}", ) if encodedStart < 0 or encodedStart > self.encodedStringLength: if raiseOnError: @@ -244,7 +244,7 @@ def getTextFromRawBytes( buf: bytes, numChars: int, encoding: Optional[str] = None, - errorsFallback: str = "replace" + errorsFallback: str = "replace", ): """ Gets a string from a raw bytes object, decoded using the specified L{encoding}. @@ -491,7 +491,7 @@ def encodedToStrOffsets( self, encodedStart: int, encodedEnd: int | None = None, - raiseOnError: bool = False + raiseOnError: bool = False, ) -> int | Tuple[int]: super().encodedToStrOffsets(encodedStart, encodedEnd, raiseOnError) if encodedStart == 0: diff --git a/source/textUtils/uniscribe.py b/source/textUtils/uniscribe.py index c73c2065e5c..294435e788d 100644 --- a/source/textUtils/uniscribe.py +++ b/source/textUtils/uniscribe.py @@ -29,7 +29,7 @@ def splitAtCharacterBoundaries(text: str) -> Generator[str, None, None]: offsetsCount = ctypes.c_int() offsets = (ctypes.c_int * textLength)() if not NVDAHelper.localLib.calculateCharacterBoundaries( - buffer, textLength, ctypes.byref(offsets), ctypes.byref(offsetsCount) + buffer, textLength, ctypes.byref(offsets), ctypes.byref(offsetsCount), ): raise RuntimeError("NVDAHelper calculateCharacterBoundaries failed") # Get the end offsets of the characters we need. diff --git a/source/tones.py b/source/tones.py index 7702afc5a47..571a63e724e 100644 --- a/source/tones.py +++ b/source/tones.py @@ -26,7 +26,7 @@ def initialize(): bitsPerSample=16, outputDevice=config.conf["speech"]["outputDevice"], wantDucking=False, - purpose=nvwave.AudioPurpose.SOUNDS + purpose=nvwave.AudioPurpose.SOUNDS, ) except Exception: log.warning("Failed to initialize audio for tones", exc_info=True) @@ -56,7 +56,7 @@ def beep( length: int, left: int = 50, right: int = 50, - isSpeechBeepCommand: bool = False + isSpeechBeepCommand: bool = False, ): """Plays a tone at the given hz, length, and stereo balance. @param hz: pitch in hz of the tone @@ -71,10 +71,10 @@ def beep( length=length, left=left, right=right, - isSpeechBeepCommand=isSpeechBeepCommand + isSpeechBeepCommand=isSpeechBeepCommand, ): log.debug( - "Beep canceled by handler registered to decide_beep extension point" + "Beep canceled by handler registered to decide_beep extension point", ) return if not player: diff --git a/source/touchHandler.py b/source/touchHandler.py index 03917d2371b..60b17a7ce90 100644 --- a/source/touchHandler.py +++ b/source/touchHandler.py @@ -294,8 +294,10 @@ def notifyInteraction(self, obj): @param obj: The NVDAObject with which the user is interacting. @type obj: L{NVDAObjects.NVDAObject} """ - oledll.oleacc.AccNotifyTouchInteraction(gui.mainFrame.Handle, obj.windowHandle, # noqa: F405 - obj.location.center.toPOINT()) + oledll.oleacc.AccNotifyTouchInteraction( + gui.mainFrame.Handle, obj.windowHandle, # noqa: F405 + obj.location.center.toPOINT(), + ) handler=None @@ -342,7 +344,7 @@ def initialize(): if not touchSupported(debugLog=True): raise NotImplementedError log.debug( - "Touchscreen detected, maximum touch inputs: %d" % winUser.user32.GetSystemMetrics(SM_MAXIMUMTOUCHES) + "Touchscreen detected, maximum touch inputs: %d" % winUser.user32.GetSystemMetrics(SM_MAXIMUMTOUCHES), ) config.post_configProfileSwitch.register(handlePostConfigProfileSwitch) setTouchSupport(config.conf["touch"]["enabled"]) diff --git a/source/touchTracker.py b/source/touchTracker.py index 58310b8093a..727de8583fd 100644 --- a/source/touchTracker.py +++ b/source/touchTracker.py @@ -136,7 +136,7 @@ class MultiTouchTracker: "actionCount", "childTrackers", "rawSingleTouchTracker", - "pluralTimeout" + "pluralTimeout", ] def __init__( @@ -149,7 +149,7 @@ def __init__( numFingers: int = 1, actionCount: int = 1, rawSingleTouchTracker: SingleTouchTracker | None = None, - pluralTimeout: float | None = None + pluralTimeout: float | None = None, ): """Represents an action jointly performed by 1 or more fingers. diff --git a/source/treeInterceptorHandler.py b/source/treeInterceptorHandler.py index bd9719973f2..0893d0aff2a 100644 --- a/source/treeInterceptorHandler.py +++ b/source/treeInterceptorHandler.py @@ -283,7 +283,7 @@ def getFormatFieldSpeech( reason=reason, unit=unit, extraDetail=extraDetail, - initialFormat=initialFormat + initialFormat=initialFormat, ) textInfos._logBadSequenceTypes(sequence) return sequence diff --git a/source/ui.py b/source/ui.py index 5c6b73f9189..33c59131d2f 100644 --- a/source/ui.py +++ b/source/ui.py @@ -14,7 +14,7 @@ from ctypes import ( windll, byref, - POINTER + POINTER, ) import comtypes.client from comtypes import IUnknown @@ -54,14 +54,14 @@ def _warnBrowsableMessageNotAvailableOnSecureScreens(title: Optional[str]) -> No log.warning( "While on secure screens browsable messages can not be used." " The browsable message window creates a security risk." - f" Attempted to open message with title: {title!r}" + f" Attempted to open message with title: {title!r}", ) if not title: browsableMessageUnavailableMsg: str = _( # Translators: This is the message for a warning shown if NVDA cannot open a browsable message window # when Windows is on a secure screen (sign-on screen / UAC prompt). - "This feature is unavailable while on secure screens such as the sign-on screen or UAC prompt." + "This feature is unavailable while on secure screens such as the sign-on screen or UAC prompt.", ) else: browsableMessageUnavailableMsg: str = _( @@ -71,7 +71,7 @@ def _warnBrowsableMessageNotAvailableOnSecureScreens(title: Optional[str]) -> No # The {title} will be replaced with the title. # The title may be something like "Formatting". "This feature ({title}) is unavailable while on secure screens" - " such as the sign-on screen or UAC prompt." + " such as the sign-on screen or UAC prompt.", ) browsableMessageUnavailableMsg = browsableMessageUnavailableMsg.format(title=title) @@ -100,8 +100,8 @@ def browseableMessage(message: str, title: Optional[str] = None, isHtml: bool = return htmlFileName = os.path.join(globalVars.appDir, 'message.html') - if not os.path.isfile(htmlFileName ): - raise LookupError(htmlFileName ) + if not os.path.isfile(htmlFileName): + raise LookupError(htmlFileName) moniker = POINTER(IUnknown)() windll.urlmon.CreateURLMonikerEx(0, htmlFileName, byref(moniker), URL_MK_UNIFORM) if not title: @@ -129,7 +129,7 @@ def browseableMessage(message: str, title: Optional[str] = None, isHtml: bool = HTMLDLG_MODELESS , byref(dialogArgsVar), DIALOG_OPTIONS, - None + None, ) gui.mainFrame.postPopup() @@ -183,5 +183,5 @@ def reportTextCopiedToClipboard(text: Optional[str] = None): text=_("Copied to clipboard: {text}").format(text=spokenText), # Translators: Displayed in braille when a text has been copied to clipboard. # {text} is replaced by the copied text. - brailleText=_("Copied: {text}").format(text=text) + brailleText=_("Copied: {text}").format(text=text), ) diff --git a/source/updateCheck.py b/source/updateCheck.py index 018e3915c07..84df1ef3440 100644 --- a/source/updateCheck.py +++ b/source/updateCheck.py @@ -203,7 +203,7 @@ def getPendingUpdate() -> Optional[Tuple]: else: if pendingUpdateFile and os.path.isfile(pendingUpdateFile): return ( - pendingUpdateFile, pendingUpdateVersion, pendingUpdateAPIVersion, pendingUpdateBackCompatToAPIVersion + pendingUpdateFile, pendingUpdateVersion, pendingUpdateAPIVersion, pendingUpdateBackCompatToAPIVersion, ) else: _setStateToNone(state) @@ -236,7 +236,7 @@ def _executeUpdate(destPath): if os.access(portablePath, os.W_OK): executeParams = u'--create-portable --portable-path "{portablePath}" --config-path "{configPath}" -m'.format( portablePath=portablePath, - configPath=WritePaths.configDir + configPath=WritePaths.configDir, ) else: executeParams = u"--launcher" @@ -286,21 +286,25 @@ def _bg(self): autoChecker.setNextCheck() def _started(self): - self._progressDialog = gui.IndeterminateProgressDialog(gui.mainFrame, - # Translators: The title of the dialog displayed while manually checking for an NVDA update. - _("Checking for Update"), - # Translators: The progress message displayed while manually checking for an NVDA update. - _("Checking for update")) + self._progressDialog = gui.IndeterminateProgressDialog( + gui.mainFrame, + # Translators: The title of the dialog displayed while manually checking for an NVDA update. + _("Checking for Update"), + # Translators: The progress message displayed while manually checking for an NVDA update. + _("Checking for update"), + ) def _error(self): wx.CallAfter(self._progressDialog.done) self._progressDialog = None - wx.CallAfter(gui.messageBox, - # Translators: A message indicating that an error occurred while checking for an update to NVDA. - _("Error checking for update."), - # Translators: The title of an error message dialog. - _("Error"), - wx.OK | wx.ICON_ERROR) + wx.CallAfter( + gui.messageBox, + # Translators: A message indicating that an error occurred while checking for an update to NVDA. + _("Error checking for update."), + # Translators: The title of an error message dialog. + _("Error"), + wx.OK | wx.ICON_ERROR, + ) def _result(self, info: Optional[Dict]) -> None: wx.CallAfter(self._progressDialog.done) @@ -353,7 +357,7 @@ def _result(self, info): class UpdateResultDialog( DpiScalingHelperMixinWithoutInit, gui.contextHelp.ContextHelpMixin, - wx.Dialog # wxPython does not seem to call base class initializer, put last in MRO + wx.Dialog, # wxPython does not seem to call base class initializer, put last in MRO ): helpId = "GeneralSettingsCheckForUpdates" @@ -382,24 +386,28 @@ def __init__(self, parent, updateInfo: Optional[Dict], auto: bool) -> None: message = _( # Translators: A message indicating that an update to NVDA has been downloaded and is ready to be # applied. - "Update to NVDA version {version} has been downloaded and is ready to be applied." + "Update to NVDA version {version} has been downloaded and is ready to be applied.", ).format(**updateInfo) self.apiVersion = pendingUpdateDetails[2] self.backCompatTo = pendingUpdateDetails[3] - showAddonCompat = any(getIncompatibleAddons( - currentAPIVersion=self.apiVersion, - backCompatToAPIVersion=self.backCompatTo - )) + showAddonCompat = any( + getIncompatibleAddons( + currentAPIVersion=self.apiVersion, + backCompatToAPIVersion=self.backCompatTo, + ), + ) if showAddonCompat: message += "\n\n" + getAddonCompatibilityMessage() - confirmationCheckbox = sHelper.addItem(wx.CheckBox( - self, - label=getAddonCompatibilityConfirmationMessage() - )) + confirmationCheckbox = sHelper.addItem( + wx.CheckBox( + self, + label=getAddonCompatibilityConfirmationMessage(), + ), + ) confirmationCheckbox.Bind( wx.EVT_CHECKBOX, - lambda evt: self.updateButton.Enable(not self.updateButton.Enabled) + lambda evt: self.updateButton.Enable(not self.updateButton.Enabled), ) confirmationCheckbox.SetFocus() # Translators: The label of a button to review add-ons prior to NVDA update. @@ -409,17 +417,17 @@ def __init__(self, parent, updateInfo: Optional[Dict], auto: bool) -> None: self, # Translators: The label of a button to apply a pending NVDA update. # {version} will be replaced with the version; e.g. 2011.3. - label=_("&Update to NVDA {version}").format(**updateInfo) + label=_("&Update to NVDA {version}").format(**updateInfo), ) self.updateButton.Bind( wx.EVT_BUTTON, - lambda evt: self.onUpdateButton(pendingUpdateDetails[0]) + lambda evt: self.onUpdateButton(pendingUpdateDetails[0]), ) self.updateButton.Enable(not showAddonCompat) bHelper.addButton( self, # Translators: The label of a button to re-download a pending NVDA update. - label=_("Re-&download update") + label=_("Re-&download update"), ).Bind(wx.EVT_BUTTON, self.onDownloadButton) else: # Translators: A message indicating that an updated version of NVDA is available. @@ -428,7 +436,7 @@ def __init__(self, parent, updateInfo: Optional[Dict], auto: bool) -> None: bHelper.addButton( self, # Translators: The label of a button to download an NVDA update. - label=_("&Download update") + label=_("&Download update"), ).Bind(wx.EVT_BUTTON, self.onDownloadButton) if auto: # this prompt was triggered by auto update checker # the user might not want to wait for a download right now, so give the option to be reminded later. @@ -475,7 +483,7 @@ def onReviewAddonsButton(self, evt): incompatibleAddons = addonGui.IncompatibleAddonsDialog( parent=self, APIVersion=self.apiVersion, - APIBackwardsCompatToVersion=self.backCompatTo + APIBackwardsCompatToVersion=self.backCompatTo, ) displayDialogAsModal(incompatibleAddons) @@ -501,20 +509,24 @@ def __init__(self, parent, destPath, version, apiVersion, backCompatTo): # Translators: A message indicating that an update to NVDA is ready to be applied. message = _("Update to NVDA version {version} is ready to be applied.\n").format(version=version) - showAddonCompat = any(getIncompatibleAddons( - currentAPIVersion=self.apiVersion, - backCompatToAPIVersion=self.backCompatTo - )) + showAddonCompat = any( + getIncompatibleAddons( + currentAPIVersion=self.apiVersion, + backCompatToAPIVersion=self.backCompatTo, + ), + ) if showAddonCompat: message += "\n" + getAddonCompatibilityMessage() text = sHelper.addItem(wx.StaticText(self, label=message)) text.Wrap(self.scaleSize(500)) if showAddonCompat: - self.confirmationCheckbox = sHelper.addItem(wx.CheckBox( - self, - label=getAddonCompatibilityConfirmationMessage() - )) + self.confirmationCheckbox = sHelper.addItem( + wx.CheckBox( + self, + label=getAddonCompatibilityConfirmationMessage(), + ), + ) bHelper = sHelper.addDialogDismissButtons(guiHelper.ButtonHelper(wx.HORIZONTAL)) if showAddonCompat: @@ -530,7 +542,7 @@ def __init__(self, parent, destPath, version, apiVersion, backCompatTo): self.confirmationCheckbox.SetFocus() self.confirmationCheckbox.Bind( wx.EVT_CHECKBOX, - lambda evt: updateButton.Enable(not updateButton.Enabled) + lambda evt: updateButton.Enable(not updateButton.Enabled), ) updateButton.Enable(False) if self.storeUpdatesDirWritable: @@ -551,7 +563,7 @@ def onReviewAddonsButton(self, evt): incompatibleAddons = addonGui.IncompatibleAddonsDialog( parent=self, APIVersion=self.apiVersion, - APIBackwardsCompatToVersion=self.backCompatTo + APIBackwardsCompatToVersion=self.backCompatTo, ) displayDialogAsModal(incompatibleAddons) @@ -575,7 +587,8 @@ def onPostponeButton(self, evt): _("Unable to postpone update."), # Translators: The title of the message when a downloaded update file could not be preserved. _("Error"), - wx.OK | wx.ICON_ERROR) + wx.OK | wx.ICON_ERROR, + ) finalDest=self.destPath state["pendingUpdateFile"]=finalDest state["pendingUpdateVersion"]=self.version @@ -616,13 +629,15 @@ def start(self): self._guiExecTimer = gui.NonReEntrantTimer(self._guiExecNotify) gui.mainFrame.prePopup() # Translators: The title of the dialog displayed while downloading an NVDA update. - self._progressDialog = wx.ProgressDialog(_("Downloading Update"), - # Translators: The progress message indicating that a connection is being established. - _("Connecting"), - # PD_AUTO_HIDE is required because ProgressDialog.Update blocks at 100% - # and waits for the user to press the Close button. - style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_AUTO_HIDE, - parent=gui.mainFrame) + self._progressDialog = wx.ProgressDialog( + _("Downloading Update"), + # Translators: The progress message indicating that a connection is being established. + _("Connecting"), + # PD_AUTO_HIDE is required because ProgressDialog.Update blocks at 100% + # and waits for the user to press the Close button. + style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_AUTO_HIDE, + parent=gui.mainFrame, + ) self._progressDialog.CentreOnScreen() self._progressDialog.Raise() t = threading.Thread( @@ -731,17 +746,20 @@ def _error(self): # Translators: A message indicating that an error occurred while downloading an update to NVDA. _("Error downloading update."), _("Error"), - wx.OK | wx.ICON_ERROR) + wx.OK | wx.ICON_ERROR, + ) def _downloadSuccess(self): self._stopped() - gui.runScriptModalDialog(UpdateAskInstallDialog( - parent=gui.mainFrame, - destPath=self.destPath, - version=self.version, - apiVersion=self.apiVersion, - backCompatTo=self.backCompatToAPIVersion - )) + gui.runScriptModalDialog( + UpdateAskInstallDialog( + parent=gui.mainFrame, + destPath=self.destPath, + version=self.version, + apiVersion=self.apiVersion, + backCompatTo=self.backCompatToAPIVersion, + ), + ) class DonateRequestDialog(wx.Dialog): MESSAGE = _( @@ -750,7 +768,7 @@ class DonateRequestDialog(wx.Dialog): "This project relies primarily on donations and grants. By donating, you are helping to fund full time development.\n" "If even $10 is donated for every download, we will be able to cover all of the ongoing costs of the project.\n" "All donations are received by NV Access, the non-profit organisation which develops NVDA.\n" - "Thank you for your support." + "Thank you for your support.", ) def __init__(self, parent, continueFunc): @@ -890,13 +908,20 @@ def _updateWindowsRootCertificates(): certCont = crypt.CertCreateCertificateContext( 0x00000001, # X509_ASN_ENCODING cert, - len(cert)) + len(cert), + ) # Ask Windows to build a certificate chain, thus triggering a root certificate update. chainCont = ctypes.c_void_p() - crypt.CertGetCertificateChain(None, certCont, None, None, - ctypes.byref(CERT_CHAIN_PARA(cbSize=ctypes.sizeof(CERT_CHAIN_PARA), - RequestedUsage=CERT_USAGE_MATCH())), - 0, None, - ctypes.byref(chainCont)) + crypt.CertGetCertificateChain( + None, certCont, None, None, + ctypes.byref( + CERT_CHAIN_PARA( + cbSize=ctypes.sizeof(CERT_CHAIN_PARA), + RequestedUsage=CERT_USAGE_MATCH(), + ), + ), + 0, None, + ctypes.byref(chainCont), + ) crypt.CertFreeCertificateChain(chainCont) crypt.CertFreeCertificateContext(certCont) diff --git a/source/utils/blockUntilConditionMet.py b/source/utils/blockUntilConditionMet.py index 37a5207aa05..df67394cc61 100644 --- a/source/utils/blockUntilConditionMet.py +++ b/source/utils/blockUntilConditionMet.py @@ -34,9 +34,9 @@ def blockUntilConditionMet( giveUpAfterSeconds: float, shouldStopEvaluator: Callable[[GetValueResultT], bool] = lambda value: bool(value), intervalBetweenSeconds: float = DEFAULT_INTERVAL_BETWEEN_EVAL_SECONDS, - ) -> Tuple[ +) -> Tuple[ EvaluatorWasMetT, # Was evaluator met? -Optional[GetValueResultT] # None or the value when the evaluator was met +Optional[GetValueResultT], # None or the value when the evaluator was met ]: """Repeatedly tries to get a value up until a time limit expires. Tries are separated by a time interval. diff --git a/source/utils/caseInsensitiveCollections.py b/source/utils/caseInsensitiveCollections.py index ec1584be7ba..9f708b00114 100644 --- a/source/utils/caseInsensitiveCollections.py +++ b/source/utils/caseInsensitiveCollections.py @@ -13,7 +13,7 @@ def __init__(self, *args: Iterable[str]): if len(args) > 1: raise TypeError( f"{type(self).__name__} expected at most 1 argument, " - f"got {len(args)}" + f"got {len(args)}", ) values = args[0] if args else () for v in values: diff --git a/source/utils/schedule.py b/source/utils/schedule.py index 62a22fc8798..e0fd940eba6 100644 --- a/source/utils/schedule.py +++ b/source/utils/schedule.py @@ -99,7 +99,7 @@ def scheduleDailyJobAtStartUp( task: Callable, queueToThread: ThreadTarget, *args, - **kwargs + **kwargs, ) -> schedule.Job: """ Schedule a daily job to run at startup. @@ -127,7 +127,7 @@ def scheduleDailyJob( cronTime: str, queueToThread: ThreadTarget, *args, - **kwargs + **kwargs, ) -> schedule.Job: """ Schedule a daily job to run at specific times. @@ -150,7 +150,7 @@ def scheduleJob( jobSchedule: schedule.Job, queueToThread: ThreadTarget, *args, - **kwargs + **kwargs, ) -> schedule.Job: """ Schedule a job to run at specific times. @@ -198,7 +198,7 @@ def callJobOnThread(*args, **kwargs): # noqa F811: lint bug with flake8 4.0.1 n # raise warning that job time clashes with existing job raise JobClashError( f"Job time {jobSchedule.at_time} clashes with existing job: " - f"{existingJob.job_func} and {task.__name__}" + f"{existingJob.job_func} and {task.__name__}", ) return jobSchedule.do(callJobOnThread, *args, **kwargs) diff --git a/source/utils/security.py b/source/utils/security.py index d6f0f51dda8..a70f81619b4 100644 --- a/source/utils/security.py +++ b/source/utils/security.py @@ -33,7 +33,7 @@ def __getattr__(attrName: str) -> Any: if attrName == "isObjectAboveLockScreen": log.warning( "isObjectAboveLockScreen(obj) is deprecated. " - "Instead use obj.isBelowLockScreen. " + "Instead use obj.isBelowLockScreen. ", ) return _isObjectAboveLockScreen if attrName == "postSessionLockStateChanged": @@ -187,7 +187,7 @@ def objectBelowLockScreenAndWindowsIsLocked( def _isObjectAboveLockScreen(obj: "NVDAObjects.NVDAObject") -> bool: log.error( "This function is deprecated. " - "Instead use obj.isBelowLockScreen. " + "Instead use obj.isBelowLockScreen. ", ) return not obj.isBelowLockScreen @@ -229,7 +229,7 @@ def _isObjectBelowLockScreen(obj: "NVDAObjects.NVDAObject") -> bool: from NVDAObjects.window import Window if not isinstance(obj, Window): log.debug( - "Cannot detect if object is below lock app, considering object as safe. " + "Cannot detect if object is below lock app, considering object as safe. ", ) # Must be a window instance to get the HWNDVal, other NVDAObjects do not support this. return False @@ -267,7 +267,7 @@ def _isWindowLockScreen(hwnd: winUser.HWNDVal) -> bool: except _UnexpectedWindowCountError: log.debugWarning( "Couldn't determine lock screen and NVDA object relative z-order", - exc_info=True + exc_info=True, ) return False @@ -282,7 +282,7 @@ class _UnexpectedWindowCountError(Exception): def _isWindowBelowWindowMatchesCond( window: winUser.HWNDVal, - matchCond: Callable[[winUser.HWNDVal], bool] + matchCond: Callable[[winUser.HWNDVal], bool], ) -> bool: """ This is a risky hack. @@ -328,7 +328,7 @@ def _isWindowBelowWindowMatchesCond( raise _UnexpectedWindowCountError( "Windows found\n" f" - window 1 indexes: {window1Indexes} (expects len 1)\n" - f" - window 2 index: {window2Index}\n" + f" - window 2 index: {window2Index}\n", ) if window1Indexes[0] >= window2Index: return False @@ -358,7 +358,7 @@ def warnSessionLockStateUnknown() -> None: " While this instance of NVDA is running," " your desktop will not be secure when Windows is locked." " Restarting Windows may address this." - " If this error is ongoing then disabling the Windows lock screen is recommended." + " If this error is ongoing then disabling the Windows lock screen is recommended.", ) unableToDetermineSessionLockStateMsg = _( @@ -368,7 +368,7 @@ def warnSessionLockStateUnknown() -> None: " While this instance of NVDA is running," " your desktop will not be secure when Windows is locked." " Restarting Windows may address this." - " If this error is ongoing then disabling the Windows lock screen is recommended." + " If this error is ongoing then disabling the Windows lock screen is recommended.", ) import wx # Late import to prevent circular dependency. diff --git a/source/versionInfo.py b/source/versionInfo.py index c8252384457..593e9d590e6 100644 --- a/source/versionInfo.py +++ b/source/versionInfo.py @@ -16,7 +16,8 @@ url = "https://www.nvaccess.org" copyrightYears = "2006-2024" copyright = _("Copyright (C) {years} NVDA Contributors").format( - years=copyrightYears) + years=copyrightYears, +) aboutMessage = _( # Translators: "About NVDA" dialog box message """{longName} ({name}) @@ -29,5 +30,5 @@ It can also be viewed online at: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html {name} is developed by NV Access, a non-profit organisation committed to helping and promoting free and open source solutions for blind and vision impaired people. -If you find NVDA useful and want it to continue to improve, please consider donating to NV Access. You can do this by selecting Donate from the NVDA menu.""" # noqa: E501 line too long +If you find NVDA useful and want it to continue to improve, please consider donating to NV Access. You can do this by selecting Donate from the NVDA menu.""", # noqa: E501 line too long ).format(**globals()) diff --git a/source/virtualBuffers/MSHTML.py b/source/virtualBuffers/MSHTML.py index de8f3d279ba..40e743fd31d 100644 --- a/source/virtualBuffers/MSHTML.py +++ b/source/virtualBuffers/MSHTML.py @@ -105,7 +105,7 @@ def _normalizeControlField(self, attrs: textInfos.ControlField): # noqa: C901 #Priority is aria role -> HTML tag name -> IAccessible role role = next( (aria.ariaRolesToNVDARoles[ar] for ar in ariaRoles if ar in aria.ariaRolesToNVDARoles), - controlTypes.Role.UNKNOWN + controlTypes.Role.UNKNOWN, ) if role == controlTypes.Role.UNKNOWN and nodeName: role=NVDAObjects.IAccessible.MSHTML.nodeNamesToNVDARoles.get(nodeName,controlTypes.Role.UNKNOWN) @@ -368,15 +368,17 @@ def _searchableAttribsForNodeType(self,nodeType): {"HTMLAttrib::role": [VBufStorage_findMatch_word(lr) for lr in aria.landmarkRoles]}, { "HTMLAttrib::role": [VBufStorage_findMatch_word("region")], - "name": [VBufStorage_findMatch_notEmpty] + "name": [VBufStorage_findMatch_notEmpty], }, - {"IHTMLDOMNode::nodeName": [ - VBufStorage_findMatch_word(node.upper()) for node, lr in aria.htmlNodeNameToAriaRoles.items() - if lr in aria.landmarkRoles - ]}, + { + "IHTMLDOMNode::nodeName": [ + VBufStorage_findMatch_word(node.upper()) for node, lr in aria.htmlNodeNameToAriaRoles.items() + if lr in aria.landmarkRoles + ], + }, { "IHTMLDOMNode::nodeName": [VBufStorage_findMatch_word("SECTION")], - "name": [VBufStorage_findMatch_notEmpty] + "name": [VBufStorage_findMatch_notEmpty], }, ] elif nodeType == "article": @@ -390,11 +392,11 @@ def _searchableAttribsForNodeType(self,nodeType): "HTMLAttrib::role": [ VBufStorage_findMatch_word(r) for r in ("group", "radiogroup") ], - "name": [VBufStorage_findMatch_notEmpty] + "name": [VBufStorage_findMatch_notEmpty], }, { "IHTMLDOMNode::nodeName": [VBufStorage_findMatch_word("FIELDSET")], - "name": [VBufStorage_findMatch_notEmpty] + "name": [VBufStorage_findMatch_notEmpty], }, ] elif nodeType == "tab": diff --git a/source/virtualBuffers/__init__.py b/source/virtualBuffers/__init__.py index 624e4aee00e..14b0b23d14e 100644 --- a/source/virtualBuffers/__init__.py +++ b/source/virtualBuffers/__init__.py @@ -91,7 +91,7 @@ def _prepareForFindByAttributes(attribs): optRegexp.append(r")\b(?:\\;|[^;])*;") else: # Assume all are exact matches or None (must not exist). - optRegexp.append("(?:" ) + optRegexp.append("(?:") optRegexp.append("|".join((escape(val)+u';') if val is not None else u';' for val in values)) optRegexp.append(")") regexp.append("".join(optRegexp)) @@ -128,8 +128,10 @@ def propertyGetter(prop): def isChild(self,parent): if self.itemType == "heading": try: - if (int(self.textInfo._getControlFieldAttribs(self.vbufFieldIdentifier[0], self.vbufFieldIdentifier[1])["level"]) - > int(parent.textInfo._getControlFieldAttribs(parent.vbufFieldIdentifier[0], parent.vbufFieldIdentifier[1])["level"])): + if ( + int(self.textInfo._getControlFieldAttribs(self.vbufFieldIdentifier[0], self.vbufFieldIdentifier[1])["level"]) + > int(parent.textInfo._getControlFieldAttribs(parent.vbufFieldIdentifier[0], parent.vbufFieldIdentifier[1])["level"]) + ): return True except (KeyError, ValueError, TypeError): return False @@ -246,7 +248,8 @@ def _getPlaceholderAttribute(self, attrs, placeholderAttrsKey): try: start, end = self._getOffsetsFromFieldIdentifier( int(attrs.get('controlIdentifier_docHandle')), - int(attrs.get('controlIdentifier_ID'))) + int(attrs.get('controlIdentifier_ID')), + ) except (LookupError, ValueError): log.debugWarning("unable to get offsets used to fetch content") return placeholder @@ -476,7 +479,7 @@ def _loadBuffer(self): self.VBufHandle=NVDAHelper.localLib.VBuf_createBuffer( self.rootNVDAObject.appModule.helperLocalBindingHandle, self.rootDocHandle,self.rootID, - self.backendName + self.backendName, ) if not self.VBufHandle: raise RuntimeError("Could not remotely create virtualBuffer") @@ -485,9 +488,12 @@ def _loadBuffer(self): queueHandler.queueFunction(queueHandler.eventQueue, self._loadBufferDone, success=False) return if log.isEnabledFor(log.DEBUG): - log.debug("Buffer load took %.3f sec, %d chars" % ( - time.time() - startTime, - NVDAHelper.localLib.VBuf_getTextLength(self.VBufHandle))) + log.debug( + "Buffer load took %.3f sec, %d chars" % ( + time.time() - startTime, + NVDAHelper.localLib.VBuf_getTextLength(self.VBufHandle), + ), + ) queueHandler.queueFunction(queueHandler.eventQueue, self._loadBufferDone) def _loadBufferDone(self, success=True): @@ -593,7 +599,7 @@ def script_refreshBuffer(self,gesture): @script( description=_( # Translators: the description for the toggleScreenLayout script on virtualBuffers. - "Toggles on and off if the screen layout is preserved while rendering the document content" + "Toggles on and off if the screen layout is preserved while rendering the document content", ), gesture="kb:NVDA+v", ) @@ -667,7 +673,7 @@ def _getNearestTableCell( axis: documentBase._Axis, ) -> textInfos.TextInfo: tableID, origRow, origCol, origRowSpan, origColSpan = ( - cell.tableID, cell.row, cell.col, cell.rowSpan, cell.colSpan + cell.tableID, cell.row, cell.col, cell.rowSpan, cell.colSpan, ) # Determine destination row and column. destRow = origRow @@ -779,8 +785,10 @@ def _isNVDAObjectInApplication_noWalk(self, obj): try: docHandle, objId = self.getIdentifierFromNVDAObject(obj) except: # noqa: E722 - log.debugWarning("getIdentifierFromNVDAObject failed. " - "Object probably died while walking ancestors.", exc_info=True) + log.debugWarning( + "getIdentifierFromNVDAObject failed. " + "Object probably died while walking ancestors.", exc_info=True, + ) return None node = VBufRemote_nodeHandle_t() if not self.VBufHandle: diff --git a/source/virtualBuffers/adobeAcrobat.py b/source/virtualBuffers/adobeAcrobat.py index d6593afdaa4..3f8ac7fccd7 100644 --- a/source/virtualBuffers/adobeAcrobat.py +++ b/source/virtualBuffers/adobeAcrobat.py @@ -56,7 +56,7 @@ def _normalizeControlField(self,attrs): and states.issuperset({ controlTypes.State.READONLY, controlTypes.State.FOCUSABLE, - controlTypes.State.LINKED + controlTypes.State.LINKED, }) ): # HACK: Acrobat sets focus states on text nodes beneath links, diff --git a/source/virtualBuffers/gecko_ia2.py b/source/virtualBuffers/gecko_ia2.py index c0bfc60e848..33e5fa1933e 100755 --- a/source/virtualBuffers/gecko_ia2.py +++ b/source/virtualBuffers/gecko_ia2.py @@ -41,7 +41,7 @@ def _getNormalizedCurrentAttrs(attrs: textInfos.ControlField) -> typing.Dict[str isCurrent = controlTypes.IsCurrent.NO if isCurrent != controlTypes.IsCurrent.NO: return { - 'current': isCurrent + 'current': isCurrent, } return {} @@ -113,7 +113,7 @@ def _normalizeControlField(self, attrs): # noqa: C901 "table-rownumber-presentational", "table-columnnumber-presentational", "table-rowcount-presentational", - "table-columncount-presentational" + "table-columncount-presentational", ): attrVal = attrs.get(attr) if attrVal is not None and attrVal.lstrip('-').isdigit(): @@ -190,7 +190,7 @@ def _normalizeControlField(self, attrs): # noqa: C901 states.discard(controlTypes.State.CHECKED) states.add(controlTypes.State.ON) popupState = aria.ariaHaspopupValuesToNVDAStates.get( - attrs.get("IAccessible2::attribute_haspopup") + attrs.get("IAccessible2::attribute_haspopup"), ) if popupState: states.discard(controlTypes.State.HASPOPUP) @@ -322,7 +322,7 @@ def _get_isAlive(self): def getNVDAObjectFromIdentifier( self, docHandle: int, - ID: int + ID: int, ) -> NVDAObjects.IAccessible.IAccessible: try: pacc = self.rootNVDAObject.IAccessibleObject.accChild(ID) @@ -331,7 +331,7 @@ def getNVDAObjectFromIdentifier( return NVDAObjects.IAccessible.IAccessible( windowHandle=docHandle, IAccessibleObject=IAccessibleHandler.normalizeIAccessible(pacc), - IAccessibleChildID=0 + IAccessibleChildID=0, ) def getIdentifierFromNVDAObject(self,obj): @@ -370,7 +370,7 @@ def _searchableAttribsForNodeType(self,nodeType): attrs = {"IAccessible::role": [IA2.IA2_ROLE_HEADING], "IAccessible2::attribute_level": [nodeType[7:]]} elif nodeType == "annotation": attrs = { - "IAccessible::role": [IA2.IA2_ROLE_CONTENT_DELETION, IA2.IA2_ROLE_CONTENT_INSERTION] + "IAccessible::role": [IA2.IA2_ROLE_CONTENT_DELETION, IA2.IA2_ROLE_CONTENT_INSERTION], } elif nodeType=="heading": attrs = {"IAccessible::role": [IA2.IA2_ROLE_HEADING]} @@ -403,7 +403,7 @@ def _searchableAttribsForNodeType(self,nodeType): { "IAccessible::role": [ oleacc.ROLE_SYSTEM_COMBOBOX, - oleacc.ROLE_SYSTEM_TEXT + oleacc.ROLE_SYSTEM_TEXT, ], f"IAccessible2::state_{IA2.IA2_STATE_EDITABLE}": [1], }, @@ -421,18 +421,18 @@ def _searchableAttribsForNodeType(self,nodeType): "IAccessible::role": [ oleacc.ROLE_SYSTEM_PUSHBUTTON, oleacc.ROLE_SYSTEM_BUTTONMENU, - IA2.IA2_ROLE_TOGGLE_BUTTON - ] + IA2.IA2_ROLE_TOGGLE_BUTTON, + ], } elif nodeType=="edit": attrs=[ { "IAccessible::role": [oleacc.ROLE_SYSTEM_TEXT], - f"IAccessible2::state_{IA2.IA2_STATE_EDITABLE}":[1] + f"IAccessible2::state_{IA2.IA2_STATE_EDITABLE}":[1], }, { f"IAccessible2::state_{IA2.IA2_STATE_EDITABLE}": [1], - f"parent::IAccessible2::state_{IA2.IA2_STATE_EDITABLE}":[None] + f"parent::IAccessible2::state_{IA2.IA2_STATE_EDITABLE}":[None], }, ] elif nodeType=="frame": @@ -463,12 +463,14 @@ def _searchableAttribsForNodeType(self,nodeType): attrs = [ {"IAccessible::role": [IA2.IA2_ROLE_LANDMARK]}, {"IAccessible2::attribute_xml-roles": [VBufStorage_findMatch_word(lr) for lr in aria.landmarkRoles]}, - {"IAccessible2::attribute_xml-roles": [VBufStorage_findMatch_word("region")], - "name": [VBufStorage_findMatch_notEmpty]} - ] + { + "IAccessible2::attribute_xml-roles": [VBufStorage_findMatch_word("region")], + "name": [VBufStorage_findMatch_notEmpty], + }, + ] elif nodeType == "article": attrs = [ - {"IAccessible2::attribute_xml-roles": [VBufStorage_findMatch_word("article")]} + {"IAccessible2::attribute_xml-roles": [VBufStorage_findMatch_word("article")]}, ] elif nodeType == "grouping": attrs = [ @@ -476,24 +478,24 @@ def _searchableAttribsForNodeType(self,nodeType): "IAccessible2::attribute_xml-roles": [ VBufStorage_findMatch_word(r) for r in ("group", "radiogroup") ], - "name": [VBufStorage_findMatch_notEmpty] + "name": [VBufStorage_findMatch_notEmpty], }, { "IAccessible2::attribute_tag": self._searchableTagValues(["fieldset"]), - "name": [VBufStorage_findMatch_notEmpty] + "name": [VBufStorage_findMatch_notEmpty], }, ] elif nodeType=="embeddedObject": attrs=[ { "IAccessible2::attribute_tag": - self._searchableTagValues(["embed", "object", "applet", "audio", "video", "figure"]) + self._searchableTagValues(["embed", "object", "applet", "audio", "video", "figure"]), }, {"IAccessible::role":[oleacc.ROLE_SYSTEM_APPLICATION,oleacc.ROLE_SYSTEM_DIALOG]}, ] elif nodeType == "tab": attrs = [ - {"IAccessible::role": [oleacc.ROLE_SYSTEM_PAGETAB]} + {"IAccessible::role": [oleacc.ROLE_SYSTEM_PAGETAB]}, ] elif nodeType == "figure": attrs = [ @@ -504,22 +506,24 @@ def _searchableAttribsForNodeType(self,nodeType): ] elif nodeType == "menuItem": attrs = [ - {"IAccessible::role": [ - oleacc.ROLE_SYSTEM_BUTTONMENU, - oleacc.ROLE_SYSTEM_MENUITEM, - ]} + { + "IAccessible::role": [ + oleacc.ROLE_SYSTEM_BUTTONMENU, + oleacc.ROLE_SYSTEM_MENUITEM, + ], + }, ] elif nodeType == "toggleButton": attrs = [ - {"IAccessible::role": [IA2.IA2_ROLE_TOGGLE_BUTTON]} + {"IAccessible::role": [IA2.IA2_ROLE_TOGGLE_BUTTON]}, ] elif nodeType == "progressBar": attrs = [ - {"IAccessible::role": [oleacc.ROLE_SYSTEM_PROGRESSBAR]} + {"IAccessible::role": [oleacc.ROLE_SYSTEM_PROGRESSBAR]}, ] elif nodeType == "math": attrs = [ - {"IAccessible::role": [oleacc.ROLE_SYSTEM_EQUATION]} + {"IAccessible::role": [oleacc.ROLE_SYSTEM_EQUATION]}, ] else: return None @@ -609,7 +613,7 @@ def _getStartSelection(self, ia2Sel: "_Ia2Selection", selFields: TextInfo.TextWi log.debug(f"ia2 start ID: {ia2Sel.startID}") log.debug(f"ia2 start offset: {ia2Sel.startOffset}") ia2Sel.startObj, childID = IAccessibleHandler.accessibleObjectFromEvent( - ia2Sel.startWindow, winUser.OBJID_CLIENT, ia2Sel.startID + ia2Sel.startWindow, winUser.OBJID_CLIENT, ia2Sel.startID, ) assert (childID == 0), "childID should be 0" ia2Sel.startObj = ia2Sel.startObj.QueryInterface(IAccessibleText) @@ -656,7 +660,7 @@ def _getEndSelection(self, ia2Sel: "_Ia2Selection", selFields: TextInfo.TextWith log.debug("Reusing ia2Sel.startObj for ia2Sel.endObj") else: ia2Sel.endObj, childID = IAccessibleHandler.accessibleObjectFromEvent( - ia2Sel.endWindow, winUser.OBJID_CLIENT, ia2Sel.endID + ia2Sel.endWindow, winUser.OBJID_CLIENT, ia2Sel.endID, ) assert (childID == 0), "childID should be 0" ia2Sel.endObj = ia2Sel.endObj.QueryInterface(IAccessibleText) @@ -666,7 +670,7 @@ def updateAppSelection(self): """Update the native selection in the application to match the browse mode selection in NVDA.""" try: paccTextSelectionContainer = self.rootNVDAObject.IAccessibleObject.QueryInterface( - IAccessibleTextSelectionContainer + IAccessibleTextSelectionContainer, ) except COMError as e: raise NotImplementedError from e @@ -685,7 +689,7 @@ def updateAppSelection(self): ia2Sel.startOffset, ia2Sel.endObj, ia2Sel.endOffset, - False + False, ) paccTextSelectionContainer.SetSelections(1, byref(r)) else: # No selection @@ -696,7 +700,7 @@ def clearAppSelection(self): """Clear the native selection in the application.""" try: paccTextSelectionContainer = self.rootNVDAObject.IAccessibleObject.QueryInterface( - IAccessibleTextSelectionContainer + IAccessibleTextSelectionContainer, ) except COMError as e: raise NotImplementedError from e diff --git a/source/vision/util.py b/source/vision/util.py index ef25163171c..9acd59a6a33 100644 --- a/source/vision/util.py +++ b/source/vision/util.py @@ -63,7 +63,7 @@ def getObjectRect(obj: NVDAObject) -> locationHelper.RectLTRB: def getContextRect( context: Context, - obj: Optional[TextContainerObject] = None + obj: Optional[TextContainerObject] = None, ) -> Optional[locationHelper.RectLTRB]: """Gets a rectangle for the specified context.""" if context == Context.FOCUS: diff --git a/source/vision/visionHandler.py b/source/vision/visionHandler.py index 4f33567dad3..2dde9043662 100644 --- a/source/vision/visionHandler.py +++ b/source/vision/visionHandler.py @@ -27,13 +27,13 @@ def _getProviderClass( moduleName: str, - caseSensitive: bool = True + caseSensitive: bool = True, ) -> Type[VisionEnhancementProvider]: """Returns a registered provider class with the specified moduleName.""" try: return importlib.import_module( "visionEnhancementProviders.%s" % moduleName, - package="visionEnhancementProviders" + package="visionEnhancementProviders", ).VisionEnhancementProvider except ImportError as initialException: if caseSensitive: @@ -43,7 +43,7 @@ def _getProviderClass( continue return importlib.import_module( "visionEnhancementProviders.%s" % name, - package="visionEnhancementProviders" + package="visionEnhancementProviders", ).VisionEnhancementProvider else: raise initialException @@ -63,12 +63,12 @@ def _getProvidersFromFileSystem(): providerId=providerId, moduleName=moduleName, displayName=displayName, - providerClass=provider + providerClass=provider, ) except Exception: # Purposely catch everything as we don't know what a provider might raise. log.error( f"Error while importing vision enhancement provider module {moduleName}", - exc_info=True + exc_info=True, ) continue @@ -104,7 +104,7 @@ def _getBuiltInProviderIds(self): from visionEnhancementProviders.screenCurtain import ScreenCurtainSettings return [ NVDAHighlighterSettings.getId(), - ScreenCurtainSettings.getId() + ScreenCurtainSettings.getId(), ] def _updateAllProvidersList(self): @@ -112,7 +112,7 @@ def _updateAllProvidersList(self): # id is used because it will not vary by locale allProviders = sorted( _getProvidersFromFileSystem(), - key=lambda info: info.providerId.lower() + key=lambda info: info.providerId.lower(), ) # Built in providers should come first # Python list.sort is stable sort again by 'built-in' @@ -120,7 +120,7 @@ def _updateAllProvidersList(self): allProviders = sorted( allProviders, key=lambda info: info.providerId in builtInProviderIds, - reverse=True # Because False comes before True, we want built-ins first. + reverse=True, # Because False comes before True, we want built-ins first. ) self._allProviders = list(allProviders) @@ -148,7 +148,7 @@ def getProviderList( providerList.append(provider) else: log.debugWarning( - f"Excluding Vision enhancement provider module {provider.moduleName} which is unable to start" + f"Excluding Vision enhancement provider module {provider.moduleName} which is unable to start", ) return providerList @@ -176,14 +176,14 @@ def getConfiguredProviderInfos(self) -> List[providerInfo.ProviderInfo]: def getProviderInstance( self, - provider: providerInfo.ProviderInfo + provider: providerInfo.ProviderInfo, ) -> Optional[VisionEnhancementProvider]: return self._providers.get(provider.providerId) def terminateProvider( self, provider: providerInfo.ProviderInfo, - saveSettings: bool = True + saveSettings: bool = True, ) -> None: """Terminates a currently active provider. When termination fails, an exception is raised. @@ -197,7 +197,7 @@ def terminateProvider( providerInstance = self._providers.pop(providerId, None) if not providerInstance: raise exceptions.ProviderTerminateException( - f"Tried to terminate uninitialized provider {providerId!r}" + f"Tried to terminate uninitialized provider {providerId!r}", ) exception = None if saveSettings: @@ -227,7 +227,7 @@ def terminateProvider( def initializeProvider( self, provider: providerInfo.ProviderInfo, - temporary: bool = False + temporary: bool = False, ) -> None: """ Enables and activates the supplied provider. @@ -249,7 +249,7 @@ def initializeProvider( providerCls = provider.providerClass if not providerCls.canStart(): raise exceptions.ProviderInitException( - f"Trying to initialize provider {providerId} which reported being unable to start" + f"Trying to initialize provider {providerId} which reported being unable to start", ) try: # Initialize the provider. @@ -270,7 +270,8 @@ def initializeProvider( providerInst.terminate() except Exception: log.error( - f"Error terminating provider {providerId} after registering to extension points", exc_info=True) + f"Error terminating provider {providerId} after registering to extension points", exc_info=True, + ) raise registerEventExtensionPointsException if not temporary: providerInst.enableInConfig(True) @@ -339,7 +340,7 @@ def handleConfigProfileSwitch(self) -> None: except Exception: log.error( f"Could not terminate the {providerId} vision enhancement provider", - exc_info=True + exc_info=True, ) for providerId in providersToInitialize: try: @@ -348,7 +349,7 @@ def handleConfigProfileSwitch(self) -> None: except Exception: log.error( f"Could not initialize the {providerId} vision enhancement provider", - exc_info=True + exc_info=True, ) def initialFocus(self) -> None: diff --git a/source/visionEnhancementProviders/NVDAHighlighter.py b/source/visionEnhancementProviders/NVDAHighlighter.py index 1e471d3f06e..4fdb5a91e0e 100644 --- a/source/visionEnhancementProviders/NVDAHighlighter.py +++ b/source/visionEnhancementProviders/NVDAHighlighter.py @@ -37,7 +37,7 @@ class HighlightStyle( - namedtuple("HighlightStyle", ("color", "width", "style", "margin")) + namedtuple("HighlightStyle", ("color", "width", "style", "margin")), ): """Represents the style of a highlight for a particular context. @ivar color: The color to use for the style @@ -110,7 +110,7 @@ def updateLocationForDisplays(self): self.handle, winUser.HWND_TOPMOST, left, top, width, height, - winUser.SWP_NOACTIVATE + winUser.SWP_NOACTIVATE, ): raise WinError() winUser.user32.ShowWindow(self.handle, winUser.SW_SHOWNA) @@ -121,7 +121,7 @@ def __init__(self, highlighter): super().__init__( windowName=self.windowName, windowStyle=self.windowStyle, - extendedWindowStyle=self.extendedWindowStyle + extendedWindowStyle=self.extendedWindowStyle, ) self.location = None self.highlighterRef = weakref.ref(highlighter) @@ -129,7 +129,8 @@ def __init__(self, highlighter): self.handle, self.transparentColor, self.transparency, - winUser.LWA_ALPHA | winUser.LWA_COLORKEY) + winUser.LWA_ALPHA | winUser.LWA_COLORKEY, + ) self.updateLocationForDisplays() if not winUser.user32.UpdateWindow(self.handle): raise WinError() @@ -142,7 +143,7 @@ def windowProc(self, hwnd, msg, wParam, lParam): self.handle, winUser.HWND_TOPMOST, 0, 0, 0, 0, - winUser.SWP_NOACTIVATE | winUser.SWP_NOMOVE | winUser.SWP_NOSIZE + winUser.SWP_NOACTIVATE | winUser.SWP_NOMOVE | winUser.SWP_NOSIZE, ) elif msg == winUser.WM_DESTROY: winUser.user32.PostQuitMessage(0) @@ -193,7 +194,7 @@ def _paint(self): with winGDI.GDIPlusPen( HighlightStyle.color.toGDIPlusARGB(), HighlightStyle.width, - HighlightStyle.style + HighlightStyle.style, ) as pen: winGDI.gdiPlusDrawRectangle(graphicsContext, pen, *rect.toLTWH()) @@ -236,7 +237,7 @@ def _get_supportedSettings(self) -> SupportedSettingType: BooleanDriverSetting( 'highlight%s' % (context[0].upper() + context[1:]), _contextOptionLabelsWithAccelerators[context], - defaultVal=True + defaultVal=True, ) for context in _supportedContexts ] @@ -244,7 +245,7 @@ def _get_supportedSettings(self) -> SupportedSettingType: class NVDAHighlighterGuiPanel( AutoSettingsMixin, - SettingsPanel + SettingsPanel, ): _enableCheckSizer: wx.BoxSizer @@ -255,7 +256,7 @@ class NVDAHighlighterGuiPanel( def __init__( self, parent: wx.Window, - providerControl: VisionProviderStateControl + providerControl: VisionProviderStateControl, ): self._providerControl = providerControl initiallyEnabledInConfig = NVDAHighlighter.isEnabledInConfig() @@ -269,7 +270,7 @@ def __init__( if any(settingsToCheck): log.debugWarning( "Highlighter disabled in config while some of its settings are enabled. " - "This will be corrected" + "This will be corrected", ) settingsStorage.highlightBrowseMode = False settingsStorage.highlightFocus = False @@ -284,7 +285,7 @@ def _buildGui(self): # Translators: The label for a checkbox that enables / disables focus highlighting # in the NVDA Highlighter vision settings panel. label=_("&Enable Highlighting"), - style=wx.CHK_3STATE + style=wx.CHK_3STATE, ) self.mainSizer.Add(self._enabledCheckbox) @@ -294,7 +295,7 @@ def _buildGui(self): self.optionsText = wx.StaticText( self, # Translators: The label for a group box containing the NVDA highlighter options. - label=_("Options:") + label=_("Options:"), ) self.mainSizer.Add(self.optionsText) @@ -405,7 +406,7 @@ def canStart(cls) -> bool: def registerEventExtensionPoints( # override self, - extensionPoints: EventExtensionPoints + extensionPoints: EventExtensionPoints, ) -> None: extensionPoints.post_focusChange.register(self.handleFocusChange) extensionPoints.post_reviewMove.register(self.handleReviewMove) diff --git a/source/visionEnhancementProviders/_exampleProvider_autoGui.py b/source/visionEnhancementProviders/_exampleProvider_autoGui.py index f0772e79b7f..dc41135e556 100644 --- a/source/visionEnhancementProviders/_exampleProvider_autoGui.py +++ b/source/visionEnhancementProviders/_exampleProvider_autoGui.py @@ -61,17 +61,17 @@ def getPreInitSettings(cls) -> SupportedSettingType: BooleanDriverSetting( "shouldDoX", # value stored in matching property name on class "Should Do X", - defaultVal=True + defaultVal=True, ), BooleanDriverSetting( "shouldDoY", # value stored in matching property name on class "Should Do Y", - defaultVal=False + defaultVal=False, ), NumericDriverSetting( "amountOfZ", # value stored in matching property name on class "Amount of Z", - defaultVal=11 + defaultVal=11, ), DriverSetting( # options for this come from a property with name generated by @@ -82,7 +82,7 @@ def getPreInitSettings(cls) -> SupportedSettingType: # result: 'availableNameofsomethings' "nameOfSomething", # value stored in matching property name on class "Name of something", - ) + ), ] def clearRuntimeSettingAvailability(self): @@ -154,12 +154,12 @@ def _initRuntimeOnlySettings(self): settings = self.getSettings() settings.addRuntimeSettingsAvailibility([ "runtimeOnlySetting_localDefault", - "runtimeOnlySetting_externalValueLoad" + "runtimeOnlySetting_externalValueLoad", ]) # load and set values from the external source, this will override values loaded from config. settings.runtimeOnlySetting_externalValueLoad = self._getValueFromDeviceOrOtherApplication( - "runtimeOnlySetting_externalValueLoad" + "runtimeOnlySetting_externalValueLoad", ) def _getValueFromDeviceOrOtherApplication(self, settingId: str) -> Any: diff --git a/source/visionEnhancementProviders/screenCurtain.py b/source/visionEnhancementProviders/screenCurtain.py index 662fc655a3a..9c738afc908 100644 --- a/source/visionEnhancementProviders/screenCurtain.py +++ b/source/visionEnhancementProviders/screenCurtain.py @@ -75,17 +75,17 @@ class Magnification: try: MagSetFullscreenColorEffect = _MagSetFullscreenColorEffectFuncType( ("MagSetFullscreenColorEffect", _magnification), - _MagSetFullscreenColorEffectArgTypes + _MagSetFullscreenColorEffectArgTypes, ) MagSetFullscreenColorEffect.errcheck = _errCheck MagGetFullscreenColorEffect = _MagGetFullscreenColorEffectFuncType( ("MagGetFullscreenColorEffect", _magnification), - _MagGetFullscreenColorEffectArgTypes + _MagGetFullscreenColorEffectArgTypes, ) MagGetFullscreenColorEffect.errcheck = _errCheck MagShowSystemCursor = _MagShowSystemCursorFuncType( ("MagShowSystemCursor", _magnification), - _MagShowSystemCursorArgTypes + _MagShowSystemCursorArgTypes, ) MagShowSystemCursor.errcheck = _errCheck except AttributeError: @@ -124,12 +124,12 @@ def _get_supportedSettings(self) -> SupportedSettingType: BooleanDriverSetting( "warnOnLoad", warnOnLoadCheckBoxText, - defaultVal=True + defaultVal=True, ), BooleanDriverSetting( "playToggleSounds", playToggleSoundsCheckBoxText, - defaultVal=True + defaultVal=True, ), ] @@ -140,7 +140,7 @@ def _get_supportedSettings(self) -> SupportedSettingType: "Enabling Screen Curtain will make the screen of your computer completely black. " "Ensure you will be able to navigate without any use of your screen before continuing. " "\n\n" - "Do you wish to continue?" + "Do you wish to continue?", ) @@ -155,7 +155,7 @@ def __init__( parent, title=_("Warning"), message=warnOnLoadText, - dialogType=MessageDialog.DIALOG_TYPE_WARNING + dialogType=MessageDialog.DIALOG_TYPE_WARNING, ): self._settingsStorage = screenCurtainSettingsStorage super().__init__(parent, title, message, dialogType) @@ -164,11 +164,11 @@ def __init__( def _addContents(self, contentsSizer): self.showWarningOnLoadCheckBox: wx.CheckBox = wx.CheckBox( self, - label=warnOnLoadCheckBoxText + label=warnOnLoadCheckBoxText, ) contentsSizer.addItem(self.showWarningOnLoadCheckBox) self.showWarningOnLoadCheckBox.SetValue( - self._settingsStorage.warnOnLoad + self._settingsStorage.warnOnLoad, ) def _addButtons(self, buttonHelper): @@ -177,7 +177,7 @@ def _addButtons(self, buttonHelper): id=wx.ID_YES, # Translators: A button in the screen curtain warning dialog which allows the user to # agree to enabling the curtain. - label=_("&Yes") + label=_("&Yes"), ) yesButton.Bind(wx.EVT_BUTTON, lambda evt: self._exitDialog(wx.YES)) @@ -186,7 +186,7 @@ def _addButtons(self, buttonHelper): id=wx.ID_NO, # Translators: A button in the screen curtain warning dialog which allows the user to # disagree to enabling the curtain. - label=_("&No") + label=_("&No"), ) noButton.SetDefault() noButton.Bind(wx.EVT_BUTTON, lambda evt: self._exitDialog(wx.NO)) @@ -230,7 +230,7 @@ class ScreenCurtainGuiPanel( def __init__( self, parent, - providerControl: VisionProviderStateControl + providerControl: VisionProviderStateControl, ): self._providerControl = providerControl super().__init__(parent) @@ -241,7 +241,7 @@ def _buildGui(self): self._enabledCheckbox = wx.CheckBox( self, # Translators: option to enable screen curtain in the vision settings panel - label=_("Make screen black (immediate effect)") + label=_("Make screen black (immediate effect)"), ) isProviderActive = bool(self._providerControl.getProviderInstance()) self._enabledCheckbox.SetValue(isProviderActive) @@ -253,7 +253,7 @@ def _buildGui(self): self.optionsText = wx.StaticText( self, # Translators: The label for a group box containing the NVDA highlighter options. - label=_("Options:") + label=_("Options:"), ) self.mainSizer.Add(self.optionsText) self.lastControl = self.optionsText @@ -309,7 +309,7 @@ def confirmInitWithUser(self) -> bool: parent = self with WarnOnLoadDialog( screenCurtainSettingsStorage=settingsStorage, - parent=parent + parent=parent, ) as dlg: res = dlg.ShowModal() # WarnOnLoadDialog can change settings, reload them diff --git a/source/watchdog.py b/source/watchdog.py index 8adc862bbf7..ff4508ef487 100644 --- a/source/watchdog.py +++ b/source/watchdog.py @@ -80,18 +80,21 @@ def alive(): SECOND_TO_100_NANOSECOND = 10 ** 7 # nanosecond is 10^9, 10^7 is hundreds of nanoseconds windll.kernel32.SetWaitableTimer( _coreDeadTimer, - ctypes.byref(ctypes.wintypes.LARGE_INTEGER( - # The time after which the state of the timer is to be set to signaled, - # in 100 nanosecond intervals. - # Use the format described by the FILETIME structure. - # Positive values indicate absolute time. - # Be sure to use a UTC-based absolute time, as the system uses UTC-based time internally. - # Negative values indicate relative time. - # The actual timer accuracy depends on the capability of your hardware. - # For more information about UTC-based time, see System Time. - -int(SECOND_TO_100_NANOSECOND * MIN_CORE_ALIVE_TIMEOUT) - )), - 0, None, None, False) + ctypes.byref( + ctypes.wintypes.LARGE_INTEGER( + # The time after which the state of the timer is to be set to signaled, + # in 100 nanosecond intervals. + # Use the format described by the FILETIME structure. + # Positive values indicate absolute time. + # Be sure to use a UTC-based absolute time, as the system uses UTC-based time internally. + # Negative values indicate relative time. + # The actual timer accuracy depends on the capability of your hardware. + # For more information about UTC-based time, see System Time. + -int(SECOND_TO_100_NANOSECOND * MIN_CORE_ALIVE_TIMEOUT), + ), + ), + 0, None, None, False, + ) def asleep(): @@ -165,7 +168,7 @@ def waitForFreezeRecovery(waitedSince: float): if log.isEnabledFor(log.DEBUGWARNING): stacks = logHandler.getFormattedStacksForAllThreads() log.debugWarning( - f"Listing stacks for Python threads:\n{stacks}" + f"Listing stacks for Python threads:\n{stacks}", ) # After every FROZEN_WARNING_TIMEOUT seconds have elapsed @@ -190,7 +193,7 @@ def waitForFreezeRecovery(waitedSince: float): time.sleep(RECOVER_ATTEMPT_INTERVAL) log.info( - f"Recovered from freeze after {_timer() - waitedSince} seconds." + f"Recovered from freeze after {_timer() - waitedSince} seconds.", ) def _shouldRecoverAfterMinTimeout(): @@ -240,8 +243,10 @@ def _crashHandler(exceptionInfo): # Though we aren't using pythonic functions to write to the dump file, # open it in binary mode as opening it in text mode (the default) doesn't make sense. with open(dumpPath, "wb") as mdf: - mdExc = MINIDUMP_EXCEPTION_INFORMATION(ThreadId=threadId, - ExceptionPointers=exceptionInfo, ClientPointers=False) + mdExc = MINIDUMP_EXCEPTION_INFORMATION( + ThreadId=threadId, + ExceptionPointers=exceptionInfo, ClientPointers=False, + ) if not ctypes.windll.DbgHelp.MiniDumpWriteDump( winKernel.kernel32.GetCurrentProcess(), globalVars.appPid, @@ -249,7 +254,7 @@ def _crashHandler(exceptionInfo): 0, # MiniDumpNormal ctypes.byref(mdExc), None, - None + None, ): raise ctypes.WinError() except: # noqa: E722 @@ -289,8 +294,10 @@ def initialize(): windll.kernel32.SetUnhandledExceptionFilter(_crashHandler) oledll.ole32.CoEnableCallCancellation(None) # Cache cancelCallEvent. - _cancelCallEvent = ctypes.wintypes.HANDLE.in_dll(NVDAHelper.localLib, - "cancelCallEvent") + _cancelCallEvent = ctypes.wintypes.HANDLE.in_dll( + NVDAHelper.localLib, + "cancelCallEvent", + ) # Handle cancelled SendMessage calls. NVDAHelper._setDllFuncPointer(NVDAHelper.localLib, "_notifySendMessageCancelled", _notifySendMessageCancelled) _watcherThread = threading.Thread( @@ -310,9 +317,11 @@ def terminate(): isRunning=False oledll.ole32.CoDisableCallCancellation(None) # Wake up the watcher so it knows to finish. - windll.kernel32.SetWaitableTimer(_coreDeadTimer, - ctypes.byref(ctypes.wintypes.LARGE_INTEGER(0)), - 0, None, None, False) + windll.kernel32.SetWaitableTimer( + _coreDeadTimer, + ctypes.byref(ctypes.wintypes.LARGE_INTEGER(0)), + 0, None, None, False, + ) _watcherThread.join() class Suspender(object): @@ -356,7 +365,8 @@ def execute(self, func, *args, pumpMessages=True, **kwargs): self._executeEvent.set() waitHandles = (ctypes.wintypes.HANDLE * 2)( - self._executionDoneEvent, _cancelCallEvent) + self._executionDoneEvent, _cancelCallEvent, + ) waitIndex = ctypes.wintypes.DWORD() if pumpMessages: oledll.ole32.CoWaitForMultipleHandles(0, winKernel.INFINITE, 2, waitHandles, ctypes.byref(waitIndex)) diff --git a/source/winAPI/_displayTracking.py b/source/winAPI/_displayTracking.py index 7095ee899c5..d15777ef808 100644 --- a/source/winAPI/_displayTracking.py +++ b/source/winAPI/_displayTracking.py @@ -64,7 +64,7 @@ def getPrimaryDisplayOrientation() -> OrientationState: return OrientationState( width, height, - _getOrientationStyle(width=width, height=height) + _getOrientationStyle(width=width, height=height), ) diff --git a/source/winAPI/_powerTracking.py b/source/winAPI/_powerTracking.py index 6ae107690e9..733d4561c37 100644 --- a/source/winAPI/_powerTracking.py +++ b/source/winAPI/_powerTracking.py @@ -92,7 +92,7 @@ class SystemPowerStatus(ctypes.Structure): ("BatteryLifePercent", ctypes.c_byte), ("Reserved1", ctypes.c_byte), ("BatteryLifeTime", ctypes.wintypes.DWORD), - ("BatteryFullLiveTime", ctypes.wintypes.DWORD) + ("BatteryFullLiveTime", ctypes.wintypes.DWORD), ] BatteryFlag: BatteryFlag diff --git a/source/winAPI/_wtsApi32.py b/source/winAPI/_wtsApi32.py index f75062bb608..b522098ecdb 100644 --- a/source/winAPI/_wtsApi32.py +++ b/source/winAPI/_wtsApi32.py @@ -165,7 +165,7 @@ class WTSINFOEXW(ctypes.Structure): POINTER(LPWSTR), # [out] LPWSTR * ppBuffer. Holds WTSINFOEXW, use ctypes.cast POINTER(DWORD), # [out] DWORD * pBytesReturned ], - bool + bool, ] WTSQuerySessionInformation: WTSQuerySessionInformationT = windll.wtsapi32.WTSQuerySessionInformationW WTSQuerySessionInformation.argtypes = ( @@ -173,7 +173,7 @@ class WTSINFOEXW(ctypes.Structure): DWORD, # [ in] DWORD SessionId c_int, # [ in] WTS_INFO_CLASS WTSInfoClass, POINTER(LPWSTR), # [out] LPWSTR * ppBuffer, - POINTER(DWORD) # [out] DWORD * pBytesReturned + POINTER(DWORD), # [out] DWORD * pBytesReturned ) WTSQuerySessionInformation.restype = BOOL # On Failure, the return value is zero. diff --git a/source/winAPI/sessionTracking.py b/source/winAPI/sessionTracking.py index c2259fd84ee..e330c2a7879 100644 --- a/source/winAPI/sessionTracking.py +++ b/source/winAPI/sessionTracking.py @@ -141,7 +141,7 @@ def _isWindowsLocked() -> bool: if _lockStateTracker is None: log.error( "_TrackNVDAInitialization.markInitializationComplete was called " - "before sessionTracking.initialize" + "before sessionTracking.initialize", ) return False return _lockStateTracker.isWindowsLocked @@ -182,7 +182,7 @@ def _isWindowsLocked_checkViaSessionQuery() -> bool: if sessionQueryLockState == WTS_LockState.WTS_SESSIONSTATE_UNKNOWN: log.error( "Unable to determine lock state via Session Query." - f" Lock state value: {sessionQueryLockState!r}" + f" Lock state value: {sessionQueryLockState!r}", ) return False return sessionQueryLockState == WTS_LockState.WTS_SESSIONSTATE_LOCK @@ -240,11 +240,11 @@ def _getCurrentSessionInfoEx() -> Optional[_WTS_INFO_POINTER_T]: raise RuntimeError(f"Failure calling WTSQuerySessionInformationW: {res}") elif ctypes.sizeof(WTSINFOEXW) != pBytesReturned.value: raise RuntimeError( - f"Returned data size failure, got {pBytesReturned.value}, expected {ctypes.sizeof(WTSINFOEXW)}" + f"Returned data size failure, got {pBytesReturned.value}, expected {ctypes.sizeof(WTSINFOEXW)}", ) info = ctypes.cast( ppBuffer, - _WTS_INFO_POINTER_T + _WTS_INFO_POINTER_T, ) if ( not info.contents @@ -254,7 +254,7 @@ def _getCurrentSessionInfoEx() -> Optional[_WTS_INFO_POINTER_T]: # https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/ns-wtsapi32-wtsinfoexa ): raise RuntimeError( - f"Unexpected Level data, got {info.contents.Level}." + f"Unexpected Level data, got {info.contents.Level}.", ) return info except Exception as e: diff --git a/source/winGDI.py b/source/winGDI.py index 1f9f933a3f6..21435340800 100644 --- a/source/winGDI.py +++ b/source/winGDI.py @@ -54,14 +54,14 @@ class GdiplusStartupInput(Structure): ('GdiplusVersion', c_uint32), ('DebugEventCallback', c_void_p), ('SuppressBackgroundThread', BOOL), - ('SuppressExternalCodecs', BOOL) + ('SuppressExternalCodecs', BOOL), ] class GdiplusStartupOutput(Structure): _fields = [ ('NotificationHookProc', c_void_p), - ('NotificationUnhookProc', c_void_p) + ('NotificationUnhookProc', c_void_p), ] diff --git a/source/winKernel.py b/source/winKernel.py index 88d189fc6b7..cb0262f5e1a 100644 --- a/source/winKernel.py +++ b/source/winKernel.py @@ -35,7 +35,7 @@ def __getattr__(attrName: str) -> Any: from winAPI._powerTracking import SystemPowerStatus log.warning( "winKernel.SYSTEM_POWER_STATUS is deprecated, " - "use winAPI._powerTracking.SystemPowerStatus instead." + "use winAPI._powerTracking.SystemPowerStatus instead.", ) return SystemPowerStatus raise AttributeError(f"module {repr(__name__)} has no attribute {repr(attrName)}") @@ -153,7 +153,7 @@ def setWaitableTimer(handle, dueTime, period=0, completionRoutine=None, arg=None period, completionRoutine, arg, - resume + resume, ) if res==0: raise ctypes.WinError() @@ -213,14 +213,14 @@ class SYSTEMTIME(ctypes.Structure): ("wHour", WORD), ("wMinute", WORD), ("wSecond", WORD), - ("wMilliseconds", WORD) + ("wMilliseconds", WORD), ) class FILETIME(Structure): _fields_ = ( ("dwLowDateTime", DWORD), - ("dwHighDateTime", DWORD) + ("dwHighDateTime", DWORD), ) @@ -232,7 +232,7 @@ class TIME_ZONE_INFORMATION(Structure): ("StandardBias", ctypes.wintypes.LONG), ("DaylightName", ctypes.wintypes.WCHAR * 32), ("DaylightDate", SYSTEMTIME), - ("DaylightBias", ctypes.wintypes.LONG) + ("DaylightBias", ctypes.wintypes.LONG), ) @@ -256,7 +256,7 @@ def FileTimeToSystemTime(lpFileTime: FILETIME, lpSystemTime: SYSTEMTIME) -> None def SystemTimeToTzSpecificLocalTime( lpTimeZoneInformation: Union[TIME_ZONE_INFORMATION, None], lpUniversalTime: SYSTEMTIME, - lpLocalTime: SYSTEMTIME + lpLocalTime: SYSTEMTIME, ) -> None: """Wrapper for `SystemTimeToTzSpecificLocalTime` from kernel32. :param lpTimeZoneInformation: Either TIME_ZONE_INFORMATION containing info about the desired time zone @@ -268,7 +268,7 @@ def SystemTimeToTzSpecificLocalTime( if lpTimeZoneInformation is not None: lpTimeZoneInformation = byref(lpTimeZoneInformation) if kernel32.SystemTimeToTzSpecificLocalTime( - lpTimeZoneInformation, byref(lpUniversalTime), byref(lpLocalTime) + lpTimeZoneInformation, byref(lpUniversalTime), byref(lpLocalTime), ) == 0: raise WinError() @@ -355,7 +355,7 @@ class SECURITY_ATTRIBUTES(Structure): _fields_ = ( ("nLength", DWORD), ("lpSecurityDescriptor", LPVOID), - ("bInheritHandle", BOOL) + ("bInheritHandle", BOOL), ) def __init__(self, **kwargs): super(SECURITY_ATTRIBUTES, self).__init__(nLength=sizeof(self), **kwargs) diff --git a/source/winUser.py b/source/winUser.py index 7c9b0953ebb..386d1bb315c 100644 --- a/source/winUser.py +++ b/source/winUser.py @@ -60,7 +60,7 @@ def __getattr__(attrName: str) -> Any: replacementSymbol = _deprecatedConstantsMap[attrName] log.warning( f"Importing {attrName} from here is deprecated. " - f"Import {replacementSymbol.name} from winAPI.winUser.constants instead. " + f"Import {replacementSymbol.name} from winAPI.winUser.constants instead. ", ) return replacementSymbol raise AttributeError(f"module {repr(__name__)} has no attribute {repr(attrName)}") @@ -696,33 +696,43 @@ def getSystemStickyKeys(): # START SENDINPUT TYPE DECLARATIONS PUL = POINTER(c_ulong) # noqa: F405 class KeyBdInput(Structure): - _fields_ = [("wVk", c_ushort), # noqa: F405 - ("wScan", c_ushort), # noqa: F405 - ("dwFlags", c_ulong), # noqa: F405 - ("time", c_ulong), # noqa: F405 - ("dwExtraInfo", PUL)] + _fields_ = [ + ("wVk", c_ushort), # noqa: F405 + ("wScan", c_ushort), # noqa: F405 + ("dwFlags", c_ulong), # noqa: F405 + ("time", c_ulong), # noqa: F405 + ("dwExtraInfo", PUL), + ] class HardwareInput(Structure): - _fields_ = [("uMsg", c_ulong), # noqa: F405 - ("wParamL", c_short), # noqa: F405 - ("wParamH", c_ushort)] # noqa: F405 + _fields_ = [ + ("uMsg", c_ulong), # noqa: F405 + ("wParamL", c_short), # noqa: F405 + ("wParamH", c_ushort), + ] # noqa: F405 class MouseInput(Structure): - _fields_ = [("dx", c_long), # noqa: F405 - ("dy", c_long), # noqa: F405 - ("mouseData", c_ulong), # noqa: F405 - ("dwFlags", c_ulong), # noqa: F405 - ("time",c_ulong), # noqa: F405 - ("dwExtraInfo", PUL)] + _fields_ = [ + ("dx", c_long), # noqa: F405 + ("dy", c_long), # noqa: F405 + ("mouseData", c_ulong), # noqa: F405 + ("dwFlags", c_ulong), # noqa: F405 + ("time",c_ulong), # noqa: F405 + ("dwExtraInfo", PUL), + ] class Input_I(Union): # noqa: F405 - _fields_ = [("ki", KeyBdInput), - ("mi", MouseInput), - ("hi", HardwareInput)] + _fields_ = [ + ("ki", KeyBdInput), + ("mi", MouseInput), + ("hi", HardwareInput), + ] class Input(Structure): - _fields_ = [("type", c_ulong), # noqa: F405 - ("ii", Input_I)] + _fields_ = [ + ("type", c_ulong), # noqa: F405 + ("ii", Input_I), + ] INPUT_MOUSE = 0 # The event is a mouse event. Use the mi structure of the union. @@ -744,7 +754,7 @@ class PAINTSTRUCT(Structure): ('rcPaint', RECT), ('fRestore', c_int), ('fIncUpdate', c_int), - ('rgbReserved', c_char * 32) + ('rgbReserved', c_char * 32), ] diff --git a/source/winVersion.py b/source/winVersion.py index 2347f1b7df2..6423292d7fd 100644 --- a/source/winVersion.py +++ b/source/winVersion.py @@ -53,7 +53,7 @@ def _getRunningVersionNameFromWinReg() -> str: """ # Cache the version in use on the system. with winreg.OpenKey( - winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows NT\CurrentVersion" + winreg.HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows NT\CurrentVersion", ) as currentVersion: # Version 20H2 and later where a separate display version string is used. try: @@ -64,7 +64,7 @@ def _getRunningVersionNameFromWinReg() -> str: releaseId = winreg.QueryValueEx(currentVersion, "ReleaseID")[0] except OSError: raise RuntimeError( - "Release name is not recorded in Windows Registry on this version of Windows" + "Release name is not recorded in Windows Registry on this version of Windows", ) from None return releaseId @@ -85,7 +85,7 @@ def __init__( releaseName: str | None = None, servicePack: str = "", productType: str = "", - processorArchitecture: str = "" + processorArchitecture: str = "", ): self.major = major self.minor = minor @@ -182,7 +182,7 @@ def getWinVer(): if WinVersion( major=winVer.major, minor=winVer.minor, - build=winVer.build + build=winVer.build, ) >= WIN11: releaseName = f"Windows 11 {_getRunningVersionNameFromWinReg()}" else: @@ -196,7 +196,7 @@ def getWinVer(): releaseName=releaseName, servicePack=winVer.service_pack, productType=("workstation", "domain controller", "server")[winVer.product_type - 1], - processorArchitecture=platform.machine() + processorArchitecture=platform.machine(), ) @@ -222,7 +222,7 @@ def isFullScreenMagnificationAvailable() -> bool: log.debugWarning( "Deprecated function called: winVersion.isFullScreenMagnificationAvailable, " "use visionEnhancementProviders.screenCurtain.ScreenCurtainProvider.canStart instead.", - stack_info=True + stack_info=True, ) return True diff --git a/source/wincon.py b/source/wincon.py index 4dd78c597e4..5a017e186da 100755 --- a/source/wincon.py +++ b/source/wincon.py @@ -34,7 +34,7 @@ class CONSOLE_SELECTION_INFO(Structure): # noqa: F405 class CHAR_INFO(Structure): # noqa: F405 _fields_ = [ ('Char', c_wchar), #union of char and wchar_t isn't needed since we deal only with unicode # noqa: F405 - ('Attributes', WORD) # noqa: F405 + ('Attributes', WORD), # noqa: F405 ] PHANDLER_ROUTINE=WINFUNCTYPE(BOOL,DWORD) # noqa: F405 diff --git a/source/windowUtils.py b/source/windowUtils.py index 47b04985516..7771ae3b911 100644 --- a/source/windowUtils.py +++ b/source/windowUtils.py @@ -127,9 +127,11 @@ def getWindowScalingFactor(window: int) -> int: # There is little information about what GetDeviceCaps does in the case of a failure for LOGPIXELSX, however, # a value of zero is certainly an error. if winDpi <= 0: - log.debugWarning("Failed to get the DPI for the window, assuming a " - "DPI of {} and using a scaling of 1. The hWnd value " - "used was: {}".format(DEFAULT_DPI_LEVEL, window)) + log.debugWarning( + "Failed to get the DPI for the window, assuming a " + "DPI of {} and using a scaling of 1. The hWnd value " + "used was: {}".format(DEFAULT_DPI_LEVEL, window), + ) return 1 return round(winDpi / DEFAULT_DPI_LEVEL) @@ -182,7 +184,7 @@ def __init__( windowName: Optional[str] = None, windowStyle: int = 0, extendedWindowStyle: int = 0, - parent: Optional[int] = None + parent: Optional[int] = None, ): """Constructor. @param windowName: The name of the window. @@ -218,7 +220,7 @@ def __init__( parent, None, appInstance, - None + None, ) if res == 0: raise ctypes.WinError() @@ -237,7 +239,7 @@ def destroy(self): if not ctypes.windll.user32.UnregisterClassW(self._classAtom, appInstance): log.error( f"Error unregistering window class for {self.__class__.__qualname__}", - exc_info=ctypes.WinError() + exc_info=ctypes.WinError(), ) self._classAtom = None diff --git a/tests/checkPot.py b/tests/checkPot.py index 3a2506d4f66..a57c33e6afa 100644 --- a/tests/checkPot.py +++ b/tests/checkPot.py @@ -157,29 +157,33 @@ def checkPot(fileName): expectedErrors += 1 continue if hasComment and isExpectedError: - error = ("Message has translator comment, but one wasn't expected.\n" - "This is good, but please remove from EXPECTED_MESSAGES_WITHOUT_COMMENTS in tests/checkPot.py") + error = ( + "Message has translator comment, but one wasn't expected.\n" + "This is good, but please remove from EXPECTED_MESSAGES_WITHOUT_COMMENTS in tests/checkPot.py" + ) unexpectedSuccesses += 1 elif not hasComment: errors += 1 error = "Message has no translator comment." else: continue - print("{error}\n" - "Source lines: {lines}\n" - "Message: {message}\n" - .format(error=error, lines=" ".join(sourceLines), message=message)) + print( + "{error}\n" + "Source lines: {lines}\n" + "Message: {message}\n" + .format(error=error, lines=" ".join(sourceLines), message=message), + ) continue removedTranslatableMessages = EXPECTED_MESSAGES_WITHOUT_COMMENTS - foundMessagesWithOutComments if removedTranslatableMessages: print( "The following messages are no longer present in the source code " - "and should be removed from `EXPECTED_MESSAGES_WITHOUT_COMMENTS`:" + "and should be removed from `EXPECTED_MESSAGES_WITHOUT_COMMENTS`:", ) print('\n'.join(removedTranslatableMessages)) print( f"{errors} errors, {unexpectedSuccesses} unexpected successes, {expectedErrors} expected errors, " - f"{len(removedTranslatableMessages)} messages marked as expected errors not present in the source code" + f"{len(removedTranslatableMessages)} messages marked as expected errors not present in the source code", ) return errors + unexpectedSuccesses + len(removedTranslatableMessages) diff --git a/tests/system/libraries/AssertsLib.py b/tests/system/libraries/AssertsLib.py index 6669989cd9e..54f27b7b963 100644 --- a/tests/system/libraries/AssertsLib.py +++ b/tests/system/libraries/AssertsLib.py @@ -19,14 +19,14 @@ def strings_match(actual, expected, ignore_case=False, comparison="speech", mess # can be determined entirely from the report, even when the test passes. builtIn.log( f"{message}assert {comparison} string matches (ignore case: {ignore_case}): '{expected}'", - level="INFO" + level="INFO", ) try: builtIn.should_be_equal_as_strings( actual, expected, msg=f"{message}{comparison} Actual != Expected", - ignore_case=ignore_case + ignore_case=ignore_case, ) except AssertionError: # Occasionally on assert failure the repr of the string makes it easier to determine the differences. @@ -35,9 +35,9 @@ def strings_match(actual, expected, ignore_case=False, comparison="speech", mess comparison, ignore_case, repr(actual), - repr(expected) + repr(expected), ), - level="DEBUG" + level="DEBUG", ) raise @@ -47,14 +47,14 @@ def string_contains_strings( expectedSubStrings: List[str], ignore_case: bool = False, comparison: str = "speech", - message: str = "" + message: str = "", ): message += '\n' if message else '' # Include expected text in robot test report so that the actual behavior # can be determined entirely from the report, even when the test passes. builtIn.log( f"{message}assert {comparison} string matches (ignore case: {ignore_case}): '{expectedSubStrings}'", - level="INFO" + level="INFO", ) try: for subString in expectedSubStrings: @@ -62,7 +62,7 @@ def string_contains_strings( actual, subString, msg=f"{message}{comparison} Actual != Expected", - ignore_case=ignore_case + ignore_case=ignore_case, ) except AssertionError: # Occasionally on assert failure the repr of the string makes it easier to determine the differences. @@ -71,9 +71,9 @@ def string_contains_strings( comparison, ignore_case, repr(actual), - repr(subString) + repr(subString), ), - level="DEBUG" + level="DEBUG", ) raise @@ -86,14 +86,14 @@ def speech_contains( actual: str, expectedSpeechParts: List[str], ignore_case: bool = False, - message: str = "" + message: str = "", ): AssertsLib.string_contains_strings( actual, expectedSpeechParts, ignore_case, comparison="speech", - message=message + message=message, ) @staticmethod @@ -105,12 +105,12 @@ def braille_contains( actual: str, expectedBrailleParts: List[str], ignore_case: bool = False, - message: str = "" + message: str = "", ): AssertsLib.string_contains_strings( actual, expectedBrailleParts, ignore_case, comparison="braille", - message=message + message=message, ) diff --git a/tests/system/libraries/ChromeLib.py b/tests/system/libraries/ChromeLib.py index 5b12592ad70..d7061a24586 100644 --- a/tests/system/libraries/ChromeLib.py +++ b/tests/system/libraries/ChromeLib.py @@ -63,20 +63,20 @@ def close_chrome_tab(self): # An additionally started chrome process merely communicates the intent to open a URI and then exits. # Start is tracking only this process. "Is Start process still running (True expected): " - f"{process.is_process_running(ChromeLib._processRFHandleForStart)}" + f"{process.is_process_running(ChromeLib._processRFHandleForStart)}", ) if not ChromeLib._chromeWindow: builtIn.log( "Unable to close tab, Chrome window not initialised correctly.", - level="WARN" + level="WARN", ) return if not windowsLib.isWindowInForeground(ChromeLib._chromeWindow): builtIn.log( "Unable to close tab, window not in foreground: " - f"({ChromeLib._chromeWindow.title} - {ChromeLib._chromeWindow.hwndVal})" + f"({ChromeLib._chromeWindow.title} - {ChromeLib._chromeWindow.hwndVal})", ) return @@ -84,12 +84,12 @@ def close_chrome_tab(self): process.wait_for_process( ChromeLib._processRFHandleForStart, timeout="10 seconds", - on_timeout="continue" + on_timeout="continue", ) builtIn.log( # False is expected, chrome should have allowed "Start" to exit. "Is Start process still running (False expected): " - f"{process.is_process_running(ChromeLib._processRFHandleForStart)}" + f"{process.is_process_running(ChromeLib._processRFHandleForStart)}", ) def exit_chrome(self): @@ -126,7 +126,7 @@ def start_chrome(self, filePath: str, testCase: str) -> Window: giveUpAfterSeconds=10, # Chrome has been taking ~3 seconds to open a new tab on appveyor. shouldStopEvaluator=lambda _window: _window is not None, intervalBetweenSeconds=0.5, - errorMessage="Unable to get chrome window" + errorMessage="Unable to get chrome window", ) if not success or ChromeLib._chromeWindow is None: @@ -184,7 +184,7 @@ def _waitForStartMarker(self) -> bool: moveToAddressBarSpeech = _NvdaLib.getSpeechAfterKey('alt+d') # focus the address bar, chrome shortcut if expectedAddressBarSpeech not in moveToAddressBarSpeech: builtIn.log( - f"Didn't read '{expectedAddressBarSpeech}' after alt+d, instead got: {moveToAddressBarSpeech}" + f"Didn't read '{expectedAddressBarSpeech}' after alt+d, instead got: {moveToAddressBarSpeech}", ) return False @@ -192,14 +192,14 @@ def _waitForStartMarker(self) -> bool: if ChromeLib._testCaseTitle not in afterControlF6Speech: builtIn.log( f"Didn't get tab title '{ChromeLib._testCaseTitle}' after moving to document, " - f"instead got: {afterControlF6Speech}" + f"instead got: {afterControlF6Speech}", ) return False afterUpArrowSpeech = _NvdaLib.getSpeechAfterKey('upArrow') # focus web content, chrome shortcut. if ChromeLib._beforeMarker not in afterUpArrowSpeech: builtIn.log( - f"Didn't get '{ChromeLib._beforeMarker}' after moving to document, instead got: {afterUpArrowSpeech}" + f"Didn't get '{ChromeLib._beforeMarker}' after moving to document, instead got: {afterUpArrowSpeech}", ) return False @@ -210,7 +210,7 @@ def _waitForStartMarker(self) -> bool: if ChromeLib._beforeMarker not in afterNumPad8Speech: builtIn.log( f"Didn't get {ChromeLib._beforeMarker} after reporting the current line" - f", instead got: {afterNumPad8Speech}" + f", instead got: {afterNumPad8Speech}", ) return False return True @@ -218,7 +218,7 @@ def _waitForStartMarker(self) -> bool: def canChromeTitleBeReported(self, chromeTitleSpeechPattern: re.Pattern) -> bool: speech = _NvdaLib.getSpeechAfterKey('NVDA+t') return bool( - chromeTitleSpeechPattern.search(speech) + chromeTitleSpeechPattern.search(speech), ) def prepareChrome(self, testCase: str, _alwaysDoToggleFocus: bool = False) -> None: @@ -263,7 +263,7 @@ def prepareChrome(self, testCase: str, _alwaysDoToggleFocus: bool = False) -> No if not self._waitForStartMarker(): builtIn.fail( "Unable to locate 'before sample' marker." - " See NVDA log for full speech." + " See NVDA log for full speech.", ) # Move to the loading status line, and wait for it to become complete # the page has fully loaded. @@ -276,7 +276,7 @@ def prepareChrome(self, testCase: str, _alwaysDoToggleFocus: bool = False) -> No else: # Exceeded the number of tries spy.dump_speech_to_log() builtIn.fail( - "Failed to wait for Test page load complete." + "Failed to wait for Test page load complete.", ) @staticmethod diff --git a/tests/system/libraries/NotepadLib.py b/tests/system/libraries/NotepadLib.py index f156d095636..c207d14bc8e 100644 --- a/tests/system/libraries/NotepadLib.py +++ b/tests/system/libraries/NotepadLib.py @@ -58,7 +58,7 @@ def exit_notepad(self): builtIn.log( # True is expected due to /wait argument. "Is Start process still running (True expected): " - f"{process.is_process_running(NotepadLib.processRFHandleForStart)}" + f"{process.is_process_running(NotepadLib.processRFHandleForStart)}", ) spy = _NvdaLib.getSpyLib() if _getForegroundHwnd() == NotepadLib.notepadWindow.hwndVal: @@ -67,14 +67,14 @@ def exit_notepad(self): process.wait_for_process( NotepadLib.processRFHandleForStart, timeout="10 seconds", - on_timeout="continue" + on_timeout="continue", ) else: builtIn.log("Test case not in foreground, can't close it.") builtIn.log( # False is expected, notepad should have allowed "Start" to exit. "Is Start process still running (False expected): " - f"{process.is_process_running(NotepadLib.processRFHandleForStart)}" + f"{process.is_process_running(NotepadLib.processRFHandleForStart)}", ) def start_notepad(self, filePath: str, expectedTitlePattern: re.Pattern) -> _Window: @@ -95,7 +95,7 @@ def start_notepad(self, filePath: str, expectedTitlePattern: re.Pattern) -> _Win giveUpAfterSeconds=3, shouldStopEvaluator=lambda _window: _window is not None, intervalBetweenSeconds=0.5, - errorMessage="Unable to get notepad window" + errorMessage="Unable to get notepad window", ) if not success or NotepadLib.notepadWindow is None: @@ -134,7 +134,7 @@ def _isNotepadInForeground() -> bool: success, _success = _blockUntilConditionMet( getValue=_isNotepadInForeground, giveUpAfterSeconds=3, - intervalBetweenSeconds=0.5 + intervalBetweenSeconds=0.5, ) if success: return @@ -146,13 +146,13 @@ def _isNotepadInForeground() -> bool: builtIn.log(f"Couldn't retrieve active window information.\nException: {e}") raise AssertionError( "Unable to focus Notepad.\n" - f"{windowInformation}" + f"{windowInformation}", ) def canNotepadTitleBeReported(self, notepadTitleSpeechPattern: re.Pattern) -> bool: titleSpeech = _NvdaLib.getSpeechAfterKey('NVDA+t') return bool( - notepadTitleSpeechPattern.search(titleSpeech) + notepadTitleSpeechPattern.search(titleSpeech), ) def prepareNotepad(self, testCase: str) -> None: @@ -174,7 +174,7 @@ def prepareNotepad(self, testCase: str) -> None: windowsLib.logForegroundWindowTitle() testCaseNotepadTitleSpeech = re.compile( # Unlike getUniqueTestCaseTitleRegex, this speech does not have to be at the start of the string. - f"{NotepadLib._testCaseTitle} \\({abs(_testCaseHash)}\\)" + f"{NotepadLib._testCaseTitle} \\({abs(_testCaseHash)}\\)", ) if not self.canNotepadTitleBeReported(notepadTitleSpeechPattern=testCaseNotepadTitleSpeech): builtIn.log("Trying to switch to notepad Window") diff --git a/tests/system/libraries/NvdaLib.py b/tests/system/libraries/NvdaLib.py index 5d561938963..fb2b749db4c 100644 --- a/tests/system/libraries/NvdaLib.py +++ b/tests/system/libraries/NvdaLib.py @@ -38,7 +38,7 @@ DEFAULT_INTERVAL_BETWEEN_EVAL_SECONDS, _getLib, _nvdaSpyAlias, - configManager + configManager, ) if typing.TYPE_CHECKING: @@ -82,7 +82,7 @@ def __init__(self): self.logPath = _pJoin(self.profileDir, 'nvda.log') self.preservedLogsDir = _pJoin( builtIn.get_variable_value("${OUTPUT DIR}"), - "nvdaTestRunLogs" + "nvdaTestRunLogs", ) def getPy2exeBootLogPath(self) -> _Optional[str]: @@ -151,7 +151,7 @@ def setup_nvda_profile(configFileName, gesturesFileName: _Optional[str] = None): @staticmethod def teardown_nvda_profile(): configManager.teardownProfile( - _locations.stagingDir + _locations.stagingDir, ) nvdaProcessAlias = 'nvdaAlias' @@ -252,7 +252,7 @@ def runKeyword(*args, **kwargs): builtIn.log( f"{keyword}" f"{f' {args}' if args else ''}" - f"{f' {kwargs}' if kwargs else ''}" + f"{f' {kwargs}' if kwargs else ''}", ) return lib.run_keyword(keyword, args, kwargs) return runKeyword @@ -261,7 +261,7 @@ def runKeyword(*args, **kwargs): setattr( remoteLib, name, - _makeKeywordCaller(remoteLib, name) + _makeKeywordCaller(remoteLib, name), ) return remoteLib @@ -279,7 +279,7 @@ def start_NVDAInstaller(self, settingsFileName): def enable_verbose_debug_logging_if_requested(self): builtIn.should_be_true(self.nvdaSpy is not None) shouldEnableVerboseDebugLogging = bool( - builtIn.get_variable_value("${verboseDebugLogging}", "") + builtIn.get_variable_value("${verboseDebugLogging}", ""), ) if shouldEnableVerboseDebugLogging: self.nvdaSpy.modifyNVDAConfig( @@ -287,7 +287,8 @@ def enable_verbose_debug_logging_if_requested(self): (["debugLog", "MSAA"], True), (["debugLog", "UIA"], True), (["debugLog", "timeSinceInput"], True), - ]) + ], + ) def start_NVDA(self, settingsFileName: str, gesturesFileName: _Optional[str] = None): self.lastNVDAStart = _datetime.utcnow() @@ -309,7 +310,7 @@ def save_NVDA_log(self): saveToPath = self.create_preserved_test_output_filename("nvda.log") opSys.copy_file( _locations.logPath, - saveToPath + saveToPath, ) builtIn.log(f"Log saved to: {saveToPath}", level='DEBUG') @@ -327,7 +328,7 @@ def save_py2exe_boot_log(self): saveToPath = self.create_preserved_test_output_filename("py2exe-nvda.log") opSys.copy_file( copyFrom, - saveToPath + saveToPath, ) builtIn.log(f"py2exe log saved to: {saveToPath}", level='DEBUG') @@ -398,7 +399,7 @@ def save_crash_dump_if_exists(self, deleteCachedAfter: bool = True) -> _Optional saveToPath = self.create_preserved_test_output_filename("nvda_crash.dmp") opSys.copy_file( crashPath, - saveToPath + saveToPath, ) if deleteCachedAfter: opSys.remove_file(crashPath) diff --git a/tests/system/libraries/SystemTestSpy/blockUntilConditionMet.py b/tests/system/libraries/SystemTestSpy/blockUntilConditionMet.py index 0cfe2458a52..24e0efef7eb 100644 --- a/tests/system/libraries/SystemTestSpy/blockUntilConditionMet.py +++ b/tests/system/libraries/SystemTestSpy/blockUntilConditionMet.py @@ -37,10 +37,10 @@ def _blockUntilConditionMet( giveUpAfterSeconds: float, shouldStopEvaluator: Callable[[GetValueResultT], bool] = lambda value: bool(value), intervalBetweenSeconds: float = DEFAULT_INTERVAL_BETWEEN_EVAL_SECONDS, - errorMessage: Optional[str] = None - ) -> Tuple[ + errorMessage: Optional[str] = None, +) -> Tuple[ EvaluatorWasMetT, # Was evaluator met? -Optional[GetValueResultT] # Value when the evaluator was met, if it was met. +Optional[GetValueResultT], # Value when the evaluator was met, if it was met. ]: """Repeatedly tries to get a value up until a time limit expires. Tries are separated by a time interval. diff --git a/tests/system/libraries/SystemTestSpy/configManager.py b/tests/system/libraries/SystemTestSpy/configManager.py index bd952738ec5..db333deb27a 100644 --- a/tests/system/libraries/SystemTestSpy/configManager.py +++ b/tests/system/libraries/SystemTestSpy/configManager.py @@ -49,7 +49,7 @@ def _installSystemTestSpyToScratchPad(repoRoot: str, scratchPadDir: str): pythonImports=[ # relative to the python path r"robotremoteserver", ], - libsDest=spyPackageLibsDir + libsDest=spyPackageLibsDir, ) try: @@ -60,23 +60,23 @@ def _installSystemTestSpyToScratchPad(repoRoot: str, scratchPadDir: str): pythonImports=[ # relative to the python path "xmlrpc", ], - libsDest=spyPackageLibsDir + libsDest=spyPackageLibsDir, ) # install the global plugin # Despite duplication, specify full paths for clarity. opSys.copy_file( _pJoin(repoRoot, "tests", "system", "libraries", "SystemTestSpy", "speechSpyGlobalPlugin.py"), - _pJoin(scratchPadDir, "globalPlugins", "speechSpyGlobalPlugin", "__init__.py") + _pJoin(scratchPadDir, "globalPlugins", "speechSpyGlobalPlugin", "__init__.py"), ) opSys.copy_file( _pJoin(repoRoot, "tests", "system", "libraries", "SystemTestSpy", "blockUntilConditionMet.py"), - _pJoin(scratchPadDir, "globalPlugins", "speechSpyGlobalPlugin") + _pJoin(scratchPadDir, "globalPlugins", "speechSpyGlobalPlugin"), ) # install the test spy speech synth opSys.copy_file( _pJoin(repoRoot, "tests", "system", "libraries", "SystemTestSpy", "speechSpySynthDriver.py"), - _pJoin(scratchPadDir, "synthDrivers", "speechSpySynthDriver.py") + _pJoin(scratchPadDir, "synthDrivers", "speechSpySynthDriver.py"), ) @@ -101,18 +101,18 @@ def setupProfile( opSys.copy_file( # Despite duplication, specify full paths for clarity. _pJoin(repoRoot, "tests", "system", "nvdaSettingsFiles", settingsFileName), - _pJoin(stagingDir, "nvdaProfile", "nvda.ini") + _pJoin(stagingDir, "nvdaProfile", "nvda.ini"), ) if gesturesFileName is not None: opSys.copy_file( # Despite duplication, specify full paths for clarity. _pJoin(repoRoot, "tests", "system", "nvdaSettingsFiles", gesturesFileName), - _pJoin(stagingDir, "nvdaProfile", "gestures.ini") + _pJoin(stagingDir, "nvdaProfile", "gestures.ini"), ) # create a package to use as the globalPlugin _installSystemTestSpyToScratchPad( repoRoot, - _pJoin(stagingDir, "nvdaProfile", "scratchpad") + _pJoin(stagingDir, "nvdaProfile", "scratchpad"), ) @@ -124,5 +124,5 @@ def teardownProfile(stagingDir: str): builtIn.log("Cleaning up NVDA profile", level='DEBUG') opSys.remove_directory( _pJoin(stagingDir, "nvdaProfile"), - recursive=True + recursive=True, ) diff --git a/tests/system/libraries/SystemTestSpy/speechSpyGlobalPlugin.py b/tests/system/libraries/SystemTestSpy/speechSpyGlobalPlugin.py index 72ec5c3dd62..c73e527a401 100644 --- a/tests/system/libraries/SystemTestSpy/speechSpyGlobalPlugin.py +++ b/tests/system/libraries/SystemTestSpy/speechSpyGlobalPlugin.py @@ -111,7 +111,7 @@ def assignGesture( module: str, className: str, script: Optional[str], - replace: bool = False + replace: bool = False, ): import inputCore inputCore.manager.userGestureMap.add( @@ -133,7 +133,7 @@ class Translation_Fake(gettext.NullTranslations): def __init__( self, - originalTranslationFunction: Optional + originalTranslationFunction: Optional, ): self.originalTranslationFunction = originalTranslationFunction self.translationResults = {} @@ -153,7 +153,7 @@ def restore(self) -> None: self.originalTranslationFunction.install() self.fakeTranslations = Translation_Fake( - languageHandler.installedTranslation() if languageHandler.installedTranslation else None + languageHandler.installedTranslation() if languageHandler.installedTranslation else None, ) self.fakeTranslations.translationResults[invariantString] = replacementString @@ -242,7 +242,7 @@ def _hasSpeechFinished(self, speechStartedIndex: Optional[int] = None): log.debug( f"started: {started}" f" (speechStartedIndex: {speechStartedIndex}, nextIndex: {nextIndex})" - f" elapsedSinceLastSpeech: {elapsed}" + f" elapsedSinceLastSpeech: {elapsed}", ) finished = self.SPEECH_HAS_FINISHED_SECONDS < elapsed return started and finished @@ -370,7 +370,7 @@ def _has_speech_occurred_before_timeout( giveUpAfterSeconds=self._minTimeout(maxWaitSeconds), shouldStopEvaluator=lambda indexFound: indexFound >= (afterIndex if afterIndex else 0), intervalBetweenSeconds=intervalBetweenSeconds, - errorMessage=None + errorMessage=None, ) def wait_for_specific_speech_no_raise( @@ -391,7 +391,7 @@ def wait_for_specific_speech_no_raise( speech, afterIndex, maxWaitSeconds, - intervalBetweenSeconds + intervalBetweenSeconds, ) if not success: return None @@ -415,13 +415,13 @@ def wait_for_specific_speech( speech, afterIndex, maxWaitSeconds, - intervalBetweenSeconds + intervalBetweenSeconds, ) if not success: self.dump_speech_to_log() raise AssertionError( f"Specific speech did not occur before timeout: {speech}\n" - "See NVDA log for dump of all speech." + "See NVDA log for dump of all speech.", ) return speechIndex @@ -444,20 +444,20 @@ def ensure_speech_did_not_occur( speech, afterIndex, maxWaitSeconds, - intervalBetweenSeconds + intervalBetweenSeconds, ) if success: self.dump_speech_to_log() raise AssertionError( f"Specific speech occurred unexpectedly before timeout: {speech}\n" - "See NVDA log for dump of all speech." + "See NVDA log for dump of all speech.", ) def wait_for_speech_to_finish( self, maxWaitSeconds=5.0, speechStartedIndex: Optional[int] = None, - errorMessage: Optional[str] = "Speech did not finish before timeout" + errorMessage: Optional[str] = "Speech did not finish before timeout", ) -> bool: """speechStartedIndex should generally be fetched with get_next_speech_index @param errorMessage: Supply None to bypass assert. @@ -480,7 +480,7 @@ def wait_for_braille_update( _blockUntilConditionMet( getValue=lambda: self.get_last_braille_index() == nextBrailleIndex, giveUpAfterSeconds=self._minTimeout(maxWaitSeconds), - errorMessage=None + errorMessage=None, ) def get_last_braille(self) -> str: @@ -547,7 +547,7 @@ def _start(self): server = self._server = RobotRemoteServer( spyLibrary, # provides library behaviour port=8270, # default:8270 is `registered by IANA` for remote server usage. Two ASCII values, RF. - serve=False # we want to start this serving on another thread so as not to block. + serve=False, # we want to start this serving on another thread so as not to block. ) log.debug("Server address: {}".format(server.server_address)) server_thread = threading.Thread( diff --git a/tests/system/libraries/SystemTestSpy/speechSpySynthDriver.py b/tests/system/libraries/SystemTestSpy/speechSpySynthDriver.py index 84a1e86a365..b55ab96bccc 100644 --- a/tests/system/libraries/SystemTestSpy/speechSpySynthDriver.py +++ b/tests/system/libraries/SystemTestSpy/speechSpySynthDriver.py @@ -55,7 +55,7 @@ def check(cls): supportedSettings = [] supportedNotifications = { synthDriverHandler.synthIndexReached, - synthDriverHandler.synthDoneSpeaking + synthDriverHandler.synthDoneSpeaking, } POLL_INTERVAL_SECS = 0.3 @@ -91,7 +91,7 @@ def _processSpeech(self): try: speechSequence = self._queuedSpeech.get( block=True, - timeout=self.POLL_INTERVAL_SECS # interruptable so that NVDA can exit. + timeout=self.POLL_INTERVAL_SECS, # interruptable so that NVDA can exit. ) except queue.Empty: if self._speechStarted: diff --git a/tests/system/libraries/SystemTestSpy/windows.py b/tests/system/libraries/SystemTestSpy/windows.py index 3f16e09eeb3..8139109e9e5 100644 --- a/tests/system/libraries/SystemTestSpy/windows.py +++ b/tests/system/libraries/SystemTestSpy/windows.py @@ -72,7 +72,7 @@ def _append_title(hwnd: HWNDVal, _lParam: LPARAM) -> bool: def _GetVisibleWindows() -> List[Window]: return _GetWindows( - filterUsingWindow=lambda window: windll.user32.IsWindowVisible(window.hwndVal) and bool(window.title) + filterUsingWindow=lambda window: windll.user32.IsWindowVisible(window.hwndVal) and bool(window.title), ) @@ -81,9 +81,11 @@ def CloseWindow(window: Window) -> bool: @return: True if the window exists and the message was sent. """ if windowWithHandleExists(window.hwndVal): - return bool(windll.user32.CloseWindow( - window.hwndVal, - )) + return bool( + windll.user32.CloseWindow( + window.hwndVal, + ), + ) return False @@ -111,7 +113,7 @@ def SetForegroundWindow(window: Window, logger: Logger) -> bool: def GetWindowWithTitle(targetTitle: re.Pattern, logger: Logger) -> Optional[Window]: windows = _GetWindows( - filterUsingWindow=lambda _window: bool(re.match(targetTitle, _window.title)) + filterUsingWindow=lambda _window: bool(re.match(targetTitle, _window.title)), ) if len(windows) == 1: logger(f"Found window (HWND: {windows[0].hwndVal}) (title: {windows[0].title})") diff --git a/tests/system/libraries/WindowsLib.py b/tests/system/libraries/WindowsLib.py index 199245a2f3d..f93da242ce4 100644 --- a/tests/system/libraries/WindowsLib.py +++ b/tests/system/libraries/WindowsLib.py @@ -138,7 +138,7 @@ def taskSwitchToItemMatching(targetWindowNamePattern: _re.Pattern, maxWindowsToT spy.wait_for_speech_to_finish(speechStartedIndex=nextIndex) raise AssertionError( f"Unable to find Window in task switcher matching: {targetWindowNamePattern}\n" - "See NVDA log for dump of all speech." + "See NVDA log for dump of all speech.", ) else: builtIn.log("Found, attempting to select.", level="DEBUG") @@ -149,7 +149,7 @@ def taskSwitchToItemMatching(targetWindowNamePattern: _re.Pattern, maxWindowsToT "Expected some speech after enter press." f" Speech at index: {nextIndex}" f", nextIndex: {spy.get_next_speech_index()}" - f", speech in range: {spy.get_speech_at_index_until_now(nextIndex)}" + f", speech in range: {spy.get_speech_at_index_until_now(nextIndex)}", ) @@ -167,7 +167,7 @@ def _tryOpenTaskSwitcher() -> _Optional["_SpeechIndexT"]: firstRow, afterIndex=expectedStartOfKeypressSpeechIndex - 1, maxWaitSeconds=5, - intervalBetweenSeconds=0.3 + intervalBetweenSeconds=0.3, ) builtIn.log(f"indexOfSpeech '{firstRow}': {indexOfSpeech}", level="DEBUG") if indexOfSpeech: diff --git a/tests/system/robot/NVDAInstaller.py b/tests/system/robot/NVDAInstaller.py index 4ed1b0d860e..09c70762888 100644 --- a/tests/system/robot/NVDAInstaller.py +++ b/tests/system/robot/NVDAInstaller.py @@ -64,7 +64,8 @@ def read_portable_copy_dialog(): spy.emulateKeyPress("alt+p") spy.wait_for_specific_speech( - "To create a portable copy of NVDA, please select the path and other options and then press Continue") + "To create a portable copy of NVDA, please select the path and other options and then press Continue", + ) # exit NVDA Installer spy.emulateKeyPress("escape") diff --git a/tests/system/robot/chromeTests.py b/tests/system/robot/chromeTests.py index 39f56430643..d57525bfa0a 100644 --- a/tests/system/robot/chromeTests.py +++ b/tests/system/robot/chromeTests.py @@ -51,7 +51,7 @@ def checkbox_labelled_by_inner_element(): Simulate evil cat - """ + """, ) actualSpeech = _chrome.getSpeechAfterTab() _asserts.strings_match( @@ -59,7 +59,7 @@ def checkbox_labelled_by_inner_element(): # The name for the element is also in it's content, the name is spoken twice: # "Simulate evil cat Simulate evil cat check box not checked" # Instead this should be spoken as: - "Simulate evil cat check box not checked" + "Simulate evil cat check box not checked", ) @@ -97,7 +97,7 @@ def _doTestAriaDetails_NoVBufNoTextInterface(nvdaConfValues: "NVDASpyLib.NVDACon "button", "has details", ]), - message="Tab to button" + message="Tab to button", ) _asserts.braille_matches( actualBraille, @@ -108,7 +108,7 @@ def _doTestAriaDetails_NoVBufNoTextInterface(nvdaConfValues: "NVDASpyLib.NVDACon _asserts.speech_matches( actualSpeech, "Press to self-destruct", - message="Report details" + message="Report details", ) _asserts.braille_matches( actualBraille, @@ -125,7 +125,8 @@ def test_aria_details_noVBufNoTextInterface(): nvdaConfValues=[ (REVIEW_CURSOR_FOLLOW_CARET_KEY, True), (REVIEW_CURSOR_FOLLOW_FOCUS_KEY, True), - ]) + ], + ) def test_aria_details_noVBufNoTextInterface_freeReview(): @@ -136,7 +137,8 @@ def test_aria_details_noVBufNoTextInterface_freeReview(): nvdaConfValues=[ (REVIEW_CURSOR_FOLLOW_CARET_KEY, False), (REVIEW_CURSOR_FOLLOW_FOCUS_KEY, False), - ]) + ], + ) def test_mark_aria_details(): @@ -144,7 +146,8 @@ def test_mark_aria_details(): nvdaConfValues=[ (REVIEW_CURSOR_FOLLOW_CARET_KEY, True), (REVIEW_CURSOR_FOLLOW_FOCUS_KEY, True), - ]) + ], + ) def test_mark_aria_details_FreeReviewCursor(): @@ -152,7 +155,8 @@ def test_mark_aria_details_FreeReviewCursor(): nvdaConfValues=[ (REVIEW_CURSOR_FOLLOW_CARET_KEY, False), (REVIEW_CURSOR_FOLLOW_FOCUS_KEY, False), - ]) + ], + ) def test_mark_aria_details_role(): @@ -200,7 +204,7 @@ def test_mark_aria_details_role():
details with role form

- """ + """, ) expectedSpeech = SPEECH_SEP.join([ "edit", @@ -236,7 +240,7 @@ def test_mark_aria_details_role(): _asserts.speech_matches( actualSpeech, expectedSpeech, - message="Browse mode speech: Read line with different aria details roles." + message="Browse mode speech: Read line with different aria details roles.", ) _asserts.braille_matches( message="Browse mode braille: Read line with different aria details roles.", @@ -266,7 +270,7 @@ def test_mark_aria_details_role(): "details", "form", "edt end", - ]) + ]), ) # Reset caret @@ -293,7 +297,7 @@ def test_mark_aria_details_role(): _asserts.speech_matches( actualSpeech, expectedSpeech, - message="Focus mode speech: Read line with different aria details roles" + message="Focus mode speech: Read line with different aria details roles", ) _asserts.braille_matches( message="Focus mode braille: Read line with different aria details roles", @@ -322,7 +326,7 @@ def test_mark_aria_details_role(): "details", "form", # "edt end", - ]) + ]), ) @@ -347,7 +351,7 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): - """ + """, ) spy: "NVDASpyLib" = _NvdaLib.getSpyLib() spy.modifyNVDAConfig(nvdaConfValues) @@ -365,7 +369,7 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): "out of highlighted", "has a comment tied to it.", # content ]), - message="Browse mode: Read line with details." + message="Browse mode: Read line with details.", ) _asserts.braille_matches( actualBraille, @@ -377,7 +381,7 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): _asserts.speech_matches( actualSpeech, "word", - message="Browse mode: Move by word to word without details" + message="Browse mode: Move by word to word without details", ) _asserts.braille_matches( actualBraille, @@ -390,7 +394,7 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): _asserts.speech_matches( actualSpeech, "No additional details", - message="Browse mode: Report details on word without details" + message="Browse mode: Report details on word without details", ) _asserts.braille_matches( actualBraille, @@ -414,7 +418,7 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): _asserts.speech_matches( actualSpeech, "Cats go woof BTW —Jonathon Commentor No they don't —Zara", - message="Browse mode: Report details on word with details" + message="Browse mode: Report details on word with details", ) _asserts.braille_matches( actualBraille, @@ -462,7 +466,7 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): "out of highlighted", "has a comment tied to it.", # content ]), - message="Browse mode: Reset to prior line before jump to the link." + message="Browse mode: Reset to prior line before jump to the link.", ) actualSpeech, actualBraille = _NvdaLib.getSpeechAndBrailleAfterKey("k") _asserts.speech_matches( @@ -480,12 +484,12 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): _asserts.speech_matches( actualSpeech, "No additional details", - message="Browse mode: Report details on nested link with details" + message="Browse mode: Report details on nested link with details", ) _asserts.braille_matches( actualBraille, "No additional details", - message="Browse mode: Report details on nested link with details" + message="Browse mode: Report details on nested link with details", ) # Reset caret @@ -522,7 +526,7 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): "out of highlighted", "has a comment tied to it.", # content ]), - message="Focus mode: report content editable with details" + message="Focus mode: report content editable with details", ) _asserts.braille_matches( actualBraille, @@ -556,7 +560,7 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): "cat", # highlighted content "out of highlighted", ]), - message="Focus mode: Move by word to word with details" + message="Focus mode: Move by word to word with details", ) _asserts.braille_matches( actualBraille, @@ -589,14 +593,14 @@ def exercise_mark_aria_details(nvdaConfValues: "NVDASpyLib.NVDAConfMods"): SPEECH_SEP.join([ "test", "link", - ]) + ]), ]), message="Focus mode: tab to link nested in container with details", ) _asserts.braille_matches( actualBraille, "hlght details test lnk", - message="Focus mode: tab to link nested in container with details" + message="Focus mode: tab to link nested in container with details", ) # Try to read the details @@ -628,7 +632,7 @@ def test_annotations_multi_target():
example form

- """ + """, ) expectedSpeechParts = [ "has foot note", @@ -651,7 +655,7 @@ def test_annotations_multi_target(): _asserts.speech_contains( actualSpeech, expectedSpeechParts, - message="Browse mode speech: Read line with different aria details roles." + message="Browse mode speech: Read line with different aria details roles.", ) _asserts.braille_contains( actualBraille, @@ -684,7 +688,7 @@ def test_annotations_multi_target(): _asserts.speech_contains( actualSpeech, expectedSpeechParts, - message="Focus mode speech: Read line with different aria details roles" + message="Focus mode speech: Read line with different aria details roles", ) _asserts.braille_contains( actualBraille, @@ -721,45 +725,45 @@ def announce_list_item_when_moving_by_word_or_character():
  • big dog
  • - """ + """, ) # Force focus mode actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) # Tab into the contenteditable actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "section multi line editable Before list" + "section multi line editable Before list", ) # Ensure that moving into a list by line, "list item" is not reported. actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "list small cat" + "list small cat", ) # Ensure that when moving by word (control+rightArrow) # within the list item, "list item" is not announced. actualSpeech = _chrome.getSpeechAfterKey("control+rightArrow") _asserts.strings_match( actualSpeech, - "cat" + "cat", ) # Ensure that when moving by character (rightArrow) # within the list item, "list item" is not announced. actualSpeech = _chrome.getSpeechAfterKey("rightArrow") _asserts.strings_match( actualSpeech, - "a" + "a", ) # move to the end of the line (and therefore the list item) actualSpeech = _chrome.getSpeechAfterKey("end") _asserts.strings_match( actualSpeech, - "blank" + "blank", ) # Ensure that when moving by character (rightArrow) # onto the next list item, "list item" is reported. @@ -768,8 +772,8 @@ def announce_list_item_when_moving_by_word_or_character(): actualSpeech, SPEECH_CALL_SEP.join([ "list item level 1", - "b" - ]) + "b", + ]), ) # Ensure that when moving by character (leftArrow) # onto the previous list item, "list item" is reported. @@ -777,14 +781,14 @@ def announce_list_item_when_moving_by_word_or_character(): actualSpeech = _chrome.getSpeechAfterKey("leftArrow") _asserts.strings_match( actualSpeech, - "list item level 1" + "list item level 1", ) # Ensure that when moving by word (control+rightArrow) # onto the next list item, "list item" is reported. actualSpeech = _chrome.getSpeechAfterKey("control+rightArrow") _asserts.strings_match( actualSpeech, - "list item level 1 big" + "list item level 1 big", ) # Ensure that when moving by word (control+leftArrow) # onto the previous list item, "list item" is reported. @@ -792,7 +796,7 @@ def announce_list_item_when_moving_by_word_or_character(): actualSpeech = _chrome.getSpeechAfterKey("control+leftArrow") _asserts.strings_match( actualSpeech, - "list item level 1" + "list item level 1", ) @@ -808,31 +812,31 @@ def test_i7562():

    after

    - """ + """, ) # Force focus mode actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) # Tab into the contenteditable actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "section multi line editable before" + "section multi line editable before", ) # DownArow into the list. 'list' should be announced when entering. actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "list bullet frogs" + "list bullet frogs", ) # DownArrow to the second list item. 'list' should not be announced. actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "bullet birds" + "bullet birds", ) # DownArrow out of the list. 'out of list' should be announced. actualSpeech = _chrome.getSpeechAfterKey("downArrow") @@ -854,19 +858,19 @@ def test_pr11606():
  • C D
  • - """ + """, ) # Force focus mode actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) # Tab into the contenteditable actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "section multi line editable list bullet link A link B" + "section multi line editable list bullet link A link B", ) # move past the end of the first link. # This should not be affected due to pr #11606. @@ -875,22 +879,22 @@ def test_pr11606(): actualSpeech, SPEECH_CALL_SEP.join([ "out of link", - "space" - ]) + "space", + ]), ) # Move to the end of the line (which is also the end of the second link) # Before pr #11606 this would have announced the bullet on the next line. actualSpeech = _chrome.getSpeechAfterKey("end") _asserts.strings_match( actualSpeech, - "link" + "link", ) # Read the current line. # Before pr #11606 the next line ("C D") would have been read. actualSpeech = _chrome.getSpeechAfterKey("NVDA+upArrow") _asserts.strings_match( actualSpeech, - "bullet link A link B" + "bullet link A link B", ) @@ -902,13 +906,13 @@ def test_ariaTreeGrid_browseMode(): _chrome.prepareChrome( f""" - """ + """, ) # Jump to the first heading in the iframe. actualSpeech = _chrome.getSpeechAfterKey("h") _asserts.strings_match( actualSpeech, - "frame main landmark Treegrid Email Inbox Example heading level 1" + "frame main landmark Treegrid Email Inbox Example heading level 1", ) # Tab to the first link. # This ensures that focus is totally within the iframe @@ -917,26 +921,26 @@ def test_ariaTreeGrid_browseMode(): actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "Treegrid Pattern link" + "Treegrid Pattern link", ) # Jump to the ARIA treegrid with the next table quicknav command. # The browse mode caret will be inside the table on the caption before the first row. actualSpeech = _chrome.getSpeechAfterKey("t") _asserts.strings_match( actualSpeech, - "Inbox table clickable with 5 rows and 3 columns Inbox" + "Inbox table clickable with 5 rows and 3 columns Inbox", ) # Move past the caption onto row 1 with downArrow actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "row 1 column 1 Subject" + "row 1 column 1 Subject", ) # Navigate to row 2 column 1 with NVDA table navigation command actualSpeech = _chrome.getSpeechAfterKey("control+alt+downArrow") _asserts.strings_match( actualSpeech, - "expanded level 1 row 2 Treegrids are awesome" + "expanded level 1 row 2 Treegrids are awesome", ) # Press enter to activate NVDA focus mode and focus the current row actualSpeech = _chrome.getSpeechAfterKey("enter") @@ -952,9 +956,9 @@ def test_ariaTreeGrid_browseMode(): "level 1", "Treegrids are awesome Want to learn how to use them? aaron at thegoogle dot rocks", "expanded", - "1 of 1" + "1 of 1", ]), - ]) + ]), ) @@ -972,22 +976,22 @@ def ARIAInvalid_spellingAndGrammar():

    Big caat meos

    Small a dog woofs

    Fat a ffrog crokes

    - """ + """, ) actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "Big spelling error caat meos" + "Big spelling error caat meos", ) actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "Small grammar error a dog woofs" + "Small grammar error a dog woofs", ) actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "Fat spelling error grammar error a ffrog crokes" + "Fat spelling error grammar error a ffrog crokes", ) @@ -999,19 +1003,19 @@ def test_ariaCheckbox_browseMode(): _chrome.prepareChrome( f""" - """ + """, ) # Jump to the first heading in the iframe. actualSpeech = _chrome.getSpeechAfterKey("h") _asserts.strings_match( actualSpeech, - "frame main landmark Checkbox Example (Two State) heading level 1" + "frame main landmark Checkbox Example (Two State) heading level 1", ) # Navigate to the checkbox. actualSpeech = _chrome.getSpeechAfterKey("x") _asserts.strings_match( actualSpeech, - "Sandwich Condiments grouping list with 4 items Lettuce check box not checked" + "Sandwich Condiments grouping list with 4 items Lettuce check box not checked", ) @@ -1033,19 +1037,19 @@ def test_i12147(): focusTarget.focus(); }) - """ + """, ) # Jump to the first button (the trigger) actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "trigger 0 button" + "trigger 0 button", ) # Activate the button, we should hear the new focus target. actualSpeech = _chrome.getSpeechAfterKey("enter") _asserts.strings_match( actualSpeech, - "target 0 heading level 4" + "target 0 heading level 4", ) @@ -1074,18 +1078,18 @@ def test_tableInStyleDisplayTable(): - """ + """, ) # Jump to the table actualSpeech = _chrome.getSpeechAfterKey("t") _asserts.strings_match( actualSpeech, - "table with 2 rows and 2 columns row 1 column 1 First heading" + "table with 2 rows and 2 columns row 1 column 1 First heading", ) nextActualSpeech = _chrome.getSpeechAfterKey("control+alt+downArrow") _asserts.strings_match( nextActualSpeech, - "row 2 First content cell" + "row 2 First content cell", ) @@ -1097,23 +1101,23 @@ def test_ariaRoleDescription_focus(): """
    - """ + """, ) actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "Cheese pizza" + "Cheese pizza", ) # Force focus mode actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "Meat pizza" + "Meat pizza", ) @@ -1126,7 +1130,7 @@ def test_ariaRoleDescription_inline_browseMode():

    Start Our logo End

    - """ + """, ) # When reading the entire line, # entering the custom role should be reported, @@ -1134,24 +1138,24 @@ def test_ariaRoleDescription_inline_browseMode(): actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "Start drawing Our logo End" + "Start drawing Our logo End", ) # When reading the line by word, # Both entering and exiting the custom role should be reported. actualSpeech = _chrome.getSpeechAfterKey("control+rightArrow") _asserts.strings_match( actualSpeech, - "drawing Our" + "drawing Our", ) actualSpeech = _chrome.getSpeechAfterKey("control+rightArrow") _asserts.strings_match( actualSpeech, - "logo out of drawing" + "logo out of drawing", ) actualSpeech = _chrome.getSpeechAfterKey("control+rightArrow") _asserts.strings_match( actualSpeech, - "End" + "End", ) @@ -1166,24 +1170,24 @@ def test_ariaRoleDescription_block_browseMode():

    Please be careful.

    End

    - """ + """, ) # when reading the page by line, # both entering and exiting the custom role should be reported. actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "warning Wet paint!" + "warning Wet paint!", ) actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "Please be careful." + "Please be careful.", ) actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "out of warning End" + "out of warning End", ) @@ -1199,18 +1203,18 @@ def test_ariaRoleDescription_inline_contentEditable(): Our logo End

    - """ + """, ) # Force focus mode actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "section multi line editable Top line" + "section multi line editable Top line", ) # When reading the entire line, # entering the custom role should be reported, @@ -1218,19 +1222,19 @@ def test_ariaRoleDescription_inline_contentEditable(): actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "Start drawing Our logo End" + "Start drawing Our logo End", ) # When reading the line by word, # Both entering and exiting the custom role should be reported. actualSpeech = _chrome.getSpeechAfterKey("control+rightArrow") _asserts.strings_match( actualSpeech, - "drawing Our logo out of drawing" + "drawing Our logo out of drawing", ) actualSpeech = _chrome.getSpeechAfterKey("control+rightArrow") _asserts.strings_match( actualSpeech, - "End" + "End", ) @@ -1248,35 +1252,35 @@ def test_ariaRoleDescription_block_contentEditable():

    End

    - """ + """, ) # Force focus mode actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "section multi line editable Top line" + "section multi line editable Top line", ) # when reading the page by line, # both entering and exiting the custom role should be reported. actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "warning Wet paint!" + "warning Wet paint!", ) actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "Please be careful." + "Please be careful.", ) actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "out of warning End" + "out of warning End", ) @@ -1324,7 +1328,7 @@ def test_ariaDescription_focusMode(): actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - "edit multi line This is a line with no annotation\nFocus mode" + "edit multi line This is a line with no annotation\nFocus mode", ) actualSpeech = _chrome.getSpeechAfterKey('downArrow') @@ -1336,7 +1340,7 @@ def test_ariaDescription_focusMode(): "User nearby, Aaron", # annotation "Here is a sentence that is being edited by someone else.", # span text "Multiple can edit this.", # bold paragraph text - ]) + ]), ) actualSpeech = _chrome.getSpeechAfterKey('downArrow') @@ -1349,8 +1353,8 @@ def test_ariaDescription_focusMode(): "link", # link role "opens in a new tab", # link description "to google's", # link contents (name) - "website" # paragraph text - ]) + "website", # paragraph text + ]), ) # 'title' attribute for link ("conduct a search") should not be announced. @@ -1362,8 +1366,8 @@ def test_ariaDescription_focusMode(): "Testing the title attribute,", # paragraph text "link", # link role "to google's", # link contents (name) - "website" # paragraph text - ]) + "website", # paragraph text + ]), ) @@ -1377,7 +1381,7 @@ def test_ariaDescription_browseMode(): actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( actualSpeech, - "edit multi line This is a line with no annotation" + "edit multi line This is a line with no annotation", ) actualSpeech = _chrome.getSpeechAfterKey('downArrow') @@ -1389,7 +1393,7 @@ def test_ariaDescription_browseMode(): "User nearby, Aaron", # annotation "Here is a sentence that is being edited by someone else.", # span text "Multiple can edit this.", # bold paragraph text - ]) + ]), ) actualSpeech = _chrome.getSpeechAfterKey('downArrow') @@ -1402,8 +1406,8 @@ def test_ariaDescription_browseMode(): "link", # link role "opens in a new tab", # link description "to google's", # link contents (name) - "website" # paragraph text - ]) + "website", # paragraph text + ]), ) # 'title' attribute for link ("conduct a search") should not be announced. @@ -1415,8 +1419,8 @@ def test_ariaDescription_browseMode(): "Testing the title attribute,", # paragraph text "link", # link role "to google's", # link contents (name) - "website" # paragraph text - ]) + "website", # paragraph text + ]), ) @@ -1459,10 +1463,10 @@ def test_ariaDescription_sayAll(): # note description missing when sourced from title attribute "to google's", # link contents (name) "website", # paragraph text - "out of edit" + "out of edit", ]), - "After Test Case Marker" - ]) + "After Test Case Marker", + ]), ) @@ -1497,18 +1501,18 @@ def test_i10840(): - """ + """, ) # Jump to the table actualSpeech = _chrome.getSpeechAfterKey("t") _asserts.strings_match( actualSpeech, - "table with 4 rows and 2 columns row 1 column 1 Month" + "table with 4 rows and 2 columns row 1 column 1 Month", ) nextActualSpeech = _chrome.getSpeechAfterKey("control+alt+rightArrow") _asserts.strings_match( nextActualSpeech, - "column 2 items" + "column 2 items", ) @@ -1518,23 +1522,23 @@ def test_mark_browse():

    The word Kangaroo is important.

    - """ + """, ) actualSpeech = _chrome.getSpeechAfterKey('downArrow') _asserts.strings_match( actualSpeech, - "The word highlighted Kangaroo out of highlighted is important." + "The word highlighted Kangaroo out of highlighted is important.", ) # Test moving by word actualSpeech = _chrome.getSpeechAfterKey("numpad6") _asserts.strings_match( actualSpeech, - "word" + "word", ) actualSpeech = _chrome.getSpeechAfterKey("numpad6") _asserts.strings_match( actualSpeech, - "highlighted Kangaroo out of highlighted" + "highlighted Kangaroo out of highlighted", ) @@ -1544,20 +1548,20 @@ def test_mark_focus():

    The word Kangaroo is important.

    - """ + """, ) # Force focus mode actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) actualSpeech = _chrome.getSpeechAfterKey('tab') _asserts.strings_match( actualSpeech, - "highlighted\nKangaroo link" + "highlighted\nKangaroo link", ) @@ -1572,7 +1576,7 @@ def test_preventDuplicateSpeechFromDescription_browse_tab(): """ apple contents - """ + """, ) spy = _NvdaLib.getSpyLib() @@ -1583,12 +1587,12 @@ def test_preventDuplicateSpeechFromDescription_browse_tab(): actualSpeech = _chrome.getSpeechAfterKey('tab') _asserts.strings_match( actualSpeech, - "apple link" + "apple link", ) actualSpeech = _chrome.getSpeechAfterKey('tab') _asserts.strings_match( actualSpeech, - "banana link" + "banana link", ) @@ -1603,7 +1607,7 @@ def preventDuplicateSpeechFromDescription_focus(): """ apple contents - """ + """, ) spy = _NvdaLib.getSpyLib() REPORT_OBJ_DESC_KEY = ["presentation", "reportObjectDescriptions"] @@ -1613,17 +1617,17 @@ def preventDuplicateSpeechFromDescription_focus(): actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) actualSpeech = _chrome.getSpeechAfterKey('tab') _asserts.strings_match( actualSpeech, - "apple link" + "apple link", ) actualSpeech = _chrome.getSpeechAfterKey('tab') _asserts.strings_match( actualSpeech, - "banana link" + "banana link", ) @@ -1638,7 +1642,7 @@ def test_ensureNoBrowseModeDescription(): r'Apple', # second link to make testing second focus mode tab easier r'Banana', - ]) + ]), ) REPORT_OBJ_DESC_KEY = ["presentation", "reportObjectDescriptions"] @@ -1660,7 +1664,7 @@ def test_ensureNoBrowseModeDescription(): # No link description (from title) "Apple", # link name / contents ]), - message="Test browse mode with reportObjectDescriptions=True" + message="Test browse mode with reportObjectDescriptions=True", ) _asserts.braille_matches( actualBraille, @@ -1669,7 +1673,7 @@ def test_ensureNoBrowseModeDescription(): # No link description (from title) "Apple", # link name / contents ]), - message="Test browse mode with reportObjectDescriptions=True" + message="Test browse mode with reportObjectDescriptions=True", ) # move virtual cursor back up to reset to start position @@ -1685,7 +1689,7 @@ def test_ensureNoBrowseModeDescription(): # No link description (from title) "Apple", # link name / contents ]), - message="Test browse mode with reportObjectDescriptions=False" + message="Test browse mode with reportObjectDescriptions=False", ) _asserts.braille_matches( actualBraille, @@ -1694,7 +1698,7 @@ def test_ensureNoBrowseModeDescription(): # No link description (from title) "Apple", # link name / contents ]), - message="Test browse mode with reportObjectDescriptions=False" + message="Test browse mode with reportObjectDescriptions=False", ) # move virtual cursor back up to reset to start position @@ -1714,7 +1718,7 @@ def test_ensureNoBrowseModeDescription(): "link", # role description "Cat", # link description (from title) ]), - message="Test focus mode with reportObjectDescriptions=True" + message="Test focus mode with reportObjectDescriptions=True", ) _asserts.braille_matches( actualBraille, @@ -1723,7 +1727,7 @@ def test_ensureNoBrowseModeDescription(): "lnk", # role description "Cat", # link description (from title) ]), - message="Test focus mode with reportObjectDescriptions=True" + message="Test focus mode with reportObjectDescriptions=True", ) # Use second link to test focus mode when 'reportObjectDescriptions' is off. @@ -1736,7 +1740,7 @@ def test_ensureNoBrowseModeDescription(): "link", # role description # No link description (from title) ]), - message="Test focus mode with reportObjectDescriptions=False" + message="Test focus mode with reportObjectDescriptions=False", ) _asserts.braille_matches( actualBraille, @@ -1745,7 +1749,7 @@ def test_ensureNoBrowseModeDescription(): "lnk", # role description # No link description (from title) ]), - message="Test focus mode with reportObjectDescriptions=False" + message="Test focus mode with reportObjectDescriptions=False", ) @@ -1769,7 +1773,7 @@ def test_quickNavTargetReporting(): A bunch of text. - """ + """, ) spy = _NvdaLib.getSpyLib() REPORT_ARTICLES = ["documentFormatting", "reportArticles"] @@ -1783,7 +1787,7 @@ def test_quickNavTargetReporting(): "Quick Nav Target", # Heading content (quick nav target), should read first "heading", # Heading role "level 1", # Heading level - ]) + ]), ) # Reset to allow trying again with report articles enabled actualSpeech = _chrome.getSpeechAfterKey("control+home") @@ -1791,7 +1795,7 @@ def test_quickNavTargetReporting(): actualSpeech, SPEECH_SEP.join([ "Before Test Case Marker", - ]) + ]), ) # Quick nav to heading with report articles enabled @@ -1805,7 +1809,7 @@ def test_quickNavTargetReporting(): "level 1", # Heading level "article", # article role, enabled via report article "A bunch of text.", # article (ancestor) description - ]) + ]), ) @@ -1830,7 +1834,7 @@ def test_focusTargetReporting(): A bunch of text. - """ + """, ) spy = _NvdaLib.getSpyLib() @@ -1844,7 +1848,7 @@ def test_focusTargetReporting(): SPEECH_SEP.join([ "before Target", "link", - ]) + ]), ) # Focus the link @@ -1855,7 +1859,7 @@ def test_focusTargetReporting(): "Focus Target", # link content (focus target), should read first "link", # link role ]), - message="browse mode - focus with Report Articles disabled" + message="browse mode - focus with Report Articles disabled", ) # Reset to allow trying again with report articles enabled actualSpeech = _chrome.getSpeechAfterKey("shift+tab") @@ -1864,7 +1868,7 @@ def test_focusTargetReporting(): SPEECH_SEP.join([ "before Target", "link", - ]) + ]), ) # Focus the link with report articles enabled @@ -1878,7 +1882,7 @@ def test_focusTargetReporting(): "article", # article role, enabled via report article "A bunch of text.", # article (ancestor) description ]), - message="browse mode - focus with Report Articles enabled" + message="browse mode - focus with Report Articles enabled", ) # Reset to allow trying again in focus mode @@ -1888,14 +1892,14 @@ def test_focusTargetReporting(): SPEECH_SEP.join([ "before Target", "link", - ]) + ]), ) # Force focus mode actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) spy.set_configValue(REPORT_ARTICLES, False) @@ -1914,7 +1918,7 @@ def test_focusTargetReporting(): "link", # link role ]), ]), - message="focus mode - focus with Report Articles disabled" + message="focus mode - focus with Report Articles disabled", ) # Reset to allow trying again with report articles enabled actualSpeech = _chrome.getSpeechAfterKey("shift+tab") @@ -1923,7 +1927,7 @@ def test_focusTargetReporting(): SPEECH_SEP.join([ "before Target", "link", - ]) + ]), ) # Focus the link with report articles enabled @@ -1942,7 +1946,7 @@ def test_focusTargetReporting(): "link", # link role ]), ]), - message="focus mode - focus with Report Articles enabled" + message="focus mode - focus with Report Articles enabled", ) @@ -2122,7 +2126,7 @@ def test_tableSpeakAllCommands(): "row 3 column 1 through 2 A 3 plus B 3", "row 4 column 2 B 4", "row 5 B 5", - ]) + ]), ) _asserts.braille_matches( actualBraille, @@ -2144,7 +2148,7 @@ def test_tableSpeakAllCommands(): "row 1 through 2 column 3 C 1 plus C 2", "row 2 D 2", "column 4 E 2", - ]) + ]), ) # Check that cursor stays at B2 @@ -2167,7 +2171,7 @@ def test_tableSayAllAxisCachingForMergedCells(): actualSpeech = _chrome.getSpeechAfterKey("control+alt+downArrow") _asserts.strings_match( actualSpeech, - "row 4 column 3 through row 5 column 4 C 4 plus D 4 plus C 5 plus D 5" + "row 4 column 3 through row 5 column 4 C 4 plus D 4 plus C 5 plus D 5", ) # Speak current column - should reuse cached column @@ -2198,7 +2202,7 @@ def test_focus_mode_on_focusable_read_only_lists(): - """ + """, ) # Set focus actualSpeech = _chrome.getSpeechAfterKey("tab") @@ -2207,7 +2211,7 @@ def test_focus_mode_on_focusable_read_only_lists(): SPEECH_SEP.join([ "before Target", "link", - ]) + ]), ) # focus the list item @@ -2226,7 +2230,7 @@ def test_focus_mode_on_focusable_read_only_lists(): ]), "Focus mode", # Focus mode should be enabled automatically and be indicated ]), - message="focus mode - focus list item and turn on focus mode" + message="focus mode - focus list item and turn on focus mode", ) @@ -2242,7 +2246,7 @@ def test_i10890(): _chrome.prepareChrome( f""" - """ + """, ) # Jump to the Example 2 heading _chrome.getSpeechAfterKey("3") @@ -2253,7 +2257,7 @@ def test_i10890(): "Example 2: Sortable Data Grid With Editable Cells", "heading", "level 3", - ]) + ]), ) # Jump to the table actualSpeech = _chrome.getSpeechAfterKey("t") @@ -2268,7 +2272,7 @@ def test_i10890(): "sorted ascending", "Date", "button", - ]) + ]), ) # Press the button actualSpeech = _chrome.getSpeechAfterKey("space") @@ -2287,7 +2291,7 @@ def test_ARIASwitchRole(): _chrome.prepareChrome( f""" - """ + """, ) # Jump to the second heading 2 in the iframe. _chrome.getSpeechAfterKey("2") @@ -2296,7 +2300,7 @@ def test_ARIASwitchRole(): actualSpeech, SPEECH_SEP.join([ "Example", - "heading level 2" + "heading level 2", ]), message="Move to first heading 2 in frame", ) @@ -2427,7 +2431,7 @@ def test_i13307():

    labelled by

    - """ + """, ) actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( @@ -2631,41 +2635,41 @@ def test_ariaErrorMessage(): actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Focus mode" + "Focus mode", ) # Tab to the native valid field actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - SPEECH_SEP.join(("Input 1", "edit", "blank")) + SPEECH_SEP.join(("Input 1", "edit", "blank")), ) # Tab to the native invalid field actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - SPEECH_SEP.join(("Input 2", "edit", "invalid entry", "Error 2", "selected b")) + SPEECH_SEP.join(("Input 2", "edit", "invalid entry", "Error 2", "selected b")), ) # Tab to the ARIA valid field actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - SPEECH_SEP.join(("Input 3", "edit", "blank")) + SPEECH_SEP.join(("Input 3", "edit", "blank")), ) # Tab to the native invalid field actualSpeech = _chrome.getSpeechAfterKey("tab") _asserts.strings_match( actualSpeech, - SPEECH_SEP.join(("Input 4", "edit", "invalid entry", "Error 4", "blank")) + SPEECH_SEP.join(("Input 4", "edit", "invalid entry", "Error 4", "blank")), ) # Force browse mode actualSpeech = _chrome.getSpeechAfterKey("NVDA+space") _asserts.strings_match( actualSpeech, - "Browse mode" + "Browse mode", ) # Jump to the top of the document _chrome.getSpeechAfterKey("control+home") @@ -2673,26 +2677,26 @@ def test_ariaErrorMessage(): actualSpeech = _chrome.getSpeechAfterKey("e") _asserts.strings_match( actualSpeech, - SPEECH_SEP.join(("Input 1", "edit")) + SPEECH_SEP.join(("Input 1", "edit")), ) # Quick nav to the native invalid field actualSpeech = _chrome.getSpeechAfterKey("e") _asserts.strings_match( actualSpeech, - SPEECH_SEP.join(("Input 2", "edit", "invalid entry", "Error 2", "b")) + SPEECH_SEP.join(("Input 2", "edit", "invalid entry", "Error 2", "b")), ) # Quick nav to the ARIA valid field actualSpeech = _chrome.getSpeechAfterKey("e") _asserts.strings_match( actualSpeech, - SPEECH_SEP.join(("Input 3", "edit")) + SPEECH_SEP.join(("Input 3", "edit")), ) # Quick nav to the native invalid field actualSpeech = _chrome.getSpeechAfterKey("e") _asserts.strings_match( actualSpeech, - SPEECH_SEP.join(("Input 4", "edit", "invalid entry", "Error 4")) + SPEECH_SEP.join(("Input 4", "edit", "invalid entry", "Error 4")), ) diff --git a/tests/system/robot/startupShutdownNVDA.py b/tests/system/robot/startupShutdownNVDA.py index aceee2c9fa3..fea4cb1bfc2 100644 --- a/tests/system/robot/startupShutdownNVDA.py +++ b/tests/system/robot/startupShutdownNVDA.py @@ -76,8 +76,8 @@ def quits_from_menu(showExitDialog=True): actualSpeech, "\n".join([ "Exit NVDA dialog", - "What would you like to do? combo box Exit collapsed Alt plus d" - ]) + "What would you like to do? combo box Exit collapsed Alt plus d", + ]), ) _builtIn.sleep(1) # the dialog is not always receiving the enter keypress, wait a little for it spy.emulateKeyPress("enter", blockUntilProcessed=False) # don't block so NVDA can exit @@ -85,7 +85,7 @@ def quits_from_menu(showExitDialog=True): _blockUntilConditionMet( getValue=lambda: not _nvdaIsRunning(), giveUpAfterSeconds=3, - errorMessage="NVDA failed to exit in the specified timeout" + errorMessage="NVDA failed to exit in the specified timeout", ) _builtIn.should_not_be_true(_nvdaIsRunning(), msg="NVDA is still running") @@ -105,8 +105,8 @@ def quits_from_keyboard(): actualSpeech, "\n".join([ "Exit NVDA dialog", - "What would you like to do? combo box Exit collapsed Alt plus d" - ]) + "What would you like to do? combo box Exit collapsed Alt plus d", + ]), ) _builtIn.sleep(1) # the dialog is not always receiving the enter keypress, wait a little longer for it _builtIn.should_be_true(_nvdaIsRunning(), msg="NVDA is not running") @@ -114,7 +114,7 @@ def quits_from_keyboard(): _blockUntilConditionMet( getValue=lambda: not _nvdaIsRunning(), giveUpAfterSeconds=3, - errorMessage="NVDA failed to exit in the specified timeout" + errorMessage="NVDA failed to exit in the specified timeout", ) _builtIn.should_not_be_true(_nvdaIsRunning(), msg="NVDA is still running") @@ -143,8 +143,8 @@ def read_welcome_dialog(): "NVDA, get help, and access other NVDA functions." ), "Options grouping", - "Keyboard layout: combo box desktop collapsed Alt plus k" - ]) + "Keyboard layout: combo box desktop collapsed Alt plus k", + ]), ) _builtIn.sleep(1) # the dialog is not always receiving the enter keypress, wait a little longer for it spy.emulateKeyPress("enter") @@ -167,11 +167,11 @@ def NVDA_restarts(): _blockUntilConditionMet( getValue=lambda: windowWithHandleExists(oldMsgWindowHandle) is False, giveUpAfterSeconds=10, - errorMessage="Old NVDA is still running" + errorMessage="Old NVDA is still running", ) _builtIn.should_not_be_true( windowWithHandleExists(oldMsgWindowHandle), - msg="Old NVDA process is stil running" + msg="Old NVDA process is stil running", ) waitUntilWindowFocused("Welcome to NVDA") @@ -195,11 +195,11 @@ def _ensureRestartWithCrashDump(crashFunction: _Callable[[], None]): _blockUntilConditionMet( getValue=lambda: windowWithHandleExists(oldMsgWindowHandle) is False, giveUpAfterSeconds=3, - errorMessage="Old NVDA is still running" + errorMessage="Old NVDA is still running", ) _builtIn.should_not_be_true( windowWithHandleExists(oldMsgWindowHandle), - msg="Old NVDA process is stil running" + msg="Old NVDA process is stil running", ) crashOccurred, crashPath = _blockUntilConditionMet( getValue=lambda: _nvdaRobot.check_for_crash_dump(startTime), diff --git a/tests/system/robot/symbolPronunciationTests.py b/tests/system/robot/symbolPronunciationTests.py index a0709992fbe..ed0d3969d23 100644 --- a/tests/system/robot/symbolPronunciationTests.py +++ b/tests/system/robot/symbolPronunciationTests.py @@ -188,8 +188,8 @@ def test_moveByWord(): 'right dash-pointing arrow', 't dash-shirt', 't dash-shirt', - 'blank' # end of doc - ] + 'blank', # end of doc + ], ) @@ -213,7 +213,7 @@ def test_moveByLine(): '', # tab # todo: There should not be any "empty" lines. 'blank', # four spaces 'blank', # end of doc - ] + ], ) _NvdaLib.getSpeechAfterKey(Move.REVIEW_HOME.value) # reset to start position @@ -304,18 +304,18 @@ def _testDelayedDescription(expectDescription: bool = True) -> None: raise AssertionError("Nothing spoken after character press") if spoken[0] not in _CHARACTER_DESCRIPTIONS: raise AssertionError( - f"First piece of speech not an expected character; got: '{spoken[0]}'" + f"First piece of speech not an expected character; got: '{spoken[0]}'", ) if expectDescription: if len(spoken) != 2: raise AssertionError( - f"Expected character with description; got: '{spoken}'" + f"Expected character with description; got: '{spoken}'", ) _asserts.strings_match(spoken[1], _CHARACTER_DESCRIPTIONS[spoken[0]]) else: if len(spoken) != 1: raise AssertionError( - f"Expected single character; got: '{spoken}'" + f"Expected single character; got: '{spoken}'", ) @@ -397,7 +397,7 @@ def test_selByWord(): 't dash-shirt', # end of doc ] - )) + )), ) @@ -427,7 +427,7 @@ def test_selByLine(): '', # four spaces todo: There should not be any "empty" lines. # end of doc ] - )) + )), ) _NvdaLib.getSpeechAfterKey(Move.CARET_HOME.value) # reset to start position @@ -477,7 +477,7 @@ def test_selByChar(): 'tab', # Expect tab named '', # Expect Windows/notepad newline is \r\n ] - )) + )), ) _NvdaLib.getSpeechAfterKey(Move.CARET_HOME.value) # reset to start position. @@ -497,7 +497,7 @@ def test_selByChar(): 'tab', # Expect whitespace named. '', # on Windows/notepad newline is \r\n ] - )) + )), ) @@ -517,7 +517,7 @@ def test_symbolInSpeechUI(): actual = _pressKeyAndCollectSpeech(Move.REVIEW_CHAR.value, numberOfTimes=1) _builtIn.should_be_equal( actual, - ["blank", ], + ["blank"], msg="actual vs expected. Unexpected speech when moving to final character.", ) @@ -539,7 +539,7 @@ def test_symbolInSpeechUI(): actual = _pressKeyAndCollectSpeech(Move.REVIEW_CHAR.value, numberOfTimes=1) _builtIn.should_be_equal( actual, - [f"{expected}\nblank", ], + [f"{expected}\nblank"], msg="actual vs expected. NVDA speech UI substitutes symbols", ) @@ -547,7 +547,7 @@ def test_symbolInSpeechUI(): def _setConfig( symbolLevel: SymLevel = SymLevel.SOME, reportLineIndentation: ReportLineIndentation = ReportLineIndentation.OFF, - ignoreBlankLines: bool = False + ignoreBlankLines: bool = False, ) -> None: spy = _NvdaLib.getSpyLib() spy.set_configValue(["documentFormatting", "reportLineIndentation"], reportLineIndentation.value) @@ -567,7 +567,7 @@ def _doTest( reportedAfterLast: EndSpeech, symbolLevel: SymLevel = SymLevel.SOME, reportLineIndentation: ReportLineIndentation = ReportLineIndentation.OFF, - ignoreBlankLines: bool = False + ignoreBlankLines: bool = False, ) -> None: _setConfig(symbolLevel, reportLineIndentation, ignoreBlankLines) @@ -575,7 +575,7 @@ def _doTest( _builtIn.should_be_equal( actual, expectedSpeech, - msg=f"actual vs expected. With symbolLevel {symbolLevel}" + msg=f"actual vs expected. With symbolLevel {symbolLevel}", ) if reportedAfterLast == EndSpeech.NONE: @@ -586,8 +586,8 @@ def _doTest( actual = _pressKeyAndCollectSpeech(navKey.value, 1) _builtIn.should_be_equal( actual, - [endReached, ], - msg=f"End reached failure. actual vs expected. With symbolLevel {symbolLevel}" + [endReached], + msg=f"End reached failure. actual vs expected. With symbolLevel {symbolLevel}", ) @@ -618,7 +618,7 @@ def test_tableHeaders(): c - """ + """, ) _setConfig(SymLevel.ALL) # Expected to be in browse mode @@ -632,7 +632,7 @@ def test_tableHeaders(): "row 1", # enter row 1 context "column 1", # enter column 1 context "First dash-name", # the contents of the cell - ]) + ]), ) actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( @@ -641,7 +641,7 @@ def test_tableHeaders(): ' '.join([ "column 2", # enter column 2 context, still in row 1, still in table "right-pointing arrow t-shirt", # the contents of the cell - ]) + ]), ) actualSpeech = _chrome.getSpeechAfterKey("downArrow") _asserts.strings_match( @@ -650,7 +650,7 @@ def test_tableHeaders(): ' '.join([ "column 3", # enter column 3 context, still in row 1, still in table "Don tick t", # the contents of the cell - ]) + ]), ) # into the first (non-header) row actualSpeech = _chrome.getSpeechAfterKey("downArrow") @@ -662,7 +662,7 @@ def test_tableHeaders(): "First dash-name", # reminder of the column name "column 1", # explicit column 2 context, "a", # the contents of the cell - ]) + ]), ) _doTest( @@ -673,7 +673,7 @@ def test_tableHeaders(): # name of column, column number, \n cell contents 't-shirt column 2\nb', # note symbols NOT replaced in column name "Don't column 3\nc", # note symbols NOT replaced in column name - ] + ], ) # reset to start of row. _NvdaLib.getSpeechAfterKey(Move.CARET_CHAR_BACK.value) @@ -687,23 +687,25 @@ def test_tableHeaders(): # name of column, column number 2, \n cell contents 'right-pointing arrow t-shirt column 2\nb', # note symbols ARE replaced in column name "Don tick t column 3\nc", # note symbols ARE replaced in column name - ] + ], ) def test_ignoreBlankLinesForReportLineIndentation(): """ Test line indentation reporting with ignoreBlankLinesForReportLineIndentation off and then on """ - _notepad.prepareNotepad('\n'.join([ - '', # blank line - 'def foo', - '\thello', - '', # blank line - '\tworld', - '', # blank line - 'def bar', - '', # blank line - ])) + _notepad.prepareNotepad( + '\n'.join([ + '', # blank line + 'def foo', + '\thello', + '', # blank line + '\tworld', + '', # blank line + 'def bar', + '', # blank line + ]), + ) def _doTestIgnoreBlankLines(ignoreBlankLines: bool, expectedSpeech: _typing.List[str]) -> None: _doTest( @@ -712,7 +714,7 @@ def _doTestIgnoreBlankLines(ignoreBlankLines: bool, expectedSpeech: _typing.List symbolLevel=SymLevel.ALL, reportLineIndentation=ReportLineIndentation.SPEECH, ignoreBlankLines=ignoreBlankLines, - expectedSpeech=expectedSpeech + expectedSpeech=expectedSpeech, ) _doTestIgnoreBlankLines( @@ -724,8 +726,8 @@ def _doTestIgnoreBlankLines(ignoreBlankLines: bool, expectedSpeech: _typing.List 'tab world', 'no indent blank', 'def bar', - 'blank' - ] + 'blank', + ], ) _NvdaLib.getSpeechAfterKey(Move.REVIEW_HOME.value) # reset to start position @@ -739,6 +741,6 @@ def _doTestIgnoreBlankLines(ignoreBlankLines: bool, expectedSpeech: _typing.List 'world', 'blank', 'no indent def bar', - 'blank' - ] + 'blank', + ], ) diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py index fbc05610a3d..9c1f6eb91e3 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -126,7 +126,7 @@ def _patched_handleReviewMove(shouldAutoTether=True): import ctypes # noqa: E402 import NVDAHelper # noqa: E402 NVDAHelper.localLib = ctypes.cdll.LoadLibrary( - os.path.join(NVDAHelper.versionedLibPath, 'nvdaHelperLocal.dll') + os.path.join(NVDAHelper.versionedLibPath, 'nvdaHelperLocal.dll'), ) # The focus and navigator objects need to be initialized to something. from .objectProvider import PlaceholderNVDAObject,NVDAObjectWithRole # noqa: E402, F401 diff --git a/tests/unit/contentRecog/test_contentRecog.py b/tests/unit/contentRecog/test_contentRecog.py index 50fc16ff71f..2a683b8ee30 100644 --- a/tests/unit/contentRecog/test_contentRecog.py +++ b/tests/unit/contentRecog/test_contentRecog.py @@ -60,12 +60,12 @@ class TestLinesWordsResult(unittest.TestCase): DATA = [ [ {"x": 100, "y": 200, "width": 10, "height": 20, "text": "word1"}, - {"x": 110, "y": 200, "width": 10, "height": 20, "text": "word2"} + {"x": 110, "y": 200, "width": 10, "height": 20, "text": "word2"}, ], [ {"x": 100, "y": 220, "width": 10, "height": 20, "text": "word3"}, - {"x": 110, "y": 220, "width": 10, "height": 20, "text": "word4"} - ] + {"x": 110, "y": 220, "width": 10, "height": 20, "text": "word4"}, + ], ] TOP = 0 BOTTOM = 23 diff --git a/tests/unit/extensionPointTestHelpers.py b/tests/unit/extensionPointTestHelpers.py index 7d0a38fc0da..d55de21fcc0 100644 --- a/tests/unit/extensionPointTestHelpers.py +++ b/tests/unit/extensionPointTestHelpers.py @@ -23,7 +23,7 @@ def actionTester( testCase: unittest.TestCase, action: Action, useAssertDictContainsSubset: bool = False, - **expectedKwargs + **expectedKwargs, ): """A context manager that allows testing an Action. @param testCase: The test case to apply assertions on. @@ -56,7 +56,7 @@ def deciderTester( decider: Decider, expectedDecision: bool, useAssertDictContainsSubset: bool = False, - **expectedKwargs + **expectedKwargs, ): """A context manager that allows testing a Decider. @param testCase: The test case to apply the assertion on. @@ -93,7 +93,7 @@ def filterTester( expectedInput: FilterValueT, expectedOutput: FilterValueT, useAssertDictContainsSubset: bool = False, - **expectedKwargs + **expectedKwargs, ): """A context manager that allows testing a Filter. @param testCase: The test case to apply the assertion on. @@ -132,7 +132,7 @@ def chainTester( chain: Chain, expectedOutput: Iterable[ChainValueTypeT], useAssertDictContainsSubset: bool = False, - **expectedKwargs + **expectedKwargs, ): """A context manager that allows testing a Filter. @param testCase: The test case to apply the assertion on. diff --git a/tests/unit/test_SpeechWithoutPauses.py b/tests/unit/test_SpeechWithoutPauses.py index 552677ac394..105178a0674 100644 --- a/tests/unit/test_SpeechWithoutPauses.py +++ b/tests/unit/test_SpeechWithoutPauses.py @@ -26,7 +26,7 @@ def __init__(self): def speak( self, - speechSeqence: SpeechSequence + speechSeqence: SpeechSequence, ): self.spokenSequences.append(speechSeqence) @@ -51,7 +51,7 @@ def resetSpeakDest(): def old_speakWithoutPauses( # noqa: C901 speechSequence: SpeechSequence, - detectBreaks: bool = True + detectBreaks: bool = True, ) -> bool: """ Speaks the speech sequences given over multiple calls, only sending to the synth at acceptable phrase or @@ -141,13 +141,13 @@ def createInputSequences(): callbackCommand, lang_en, 'The purpose of the wxPyWiki is to provide documentation, examples, how-tos, etc. for helping people ', - lang_default + lang_default, ], [ callbackCommand, lang_en, 'learn, understand and use ', - lang_default + lang_default, ], [ callbackCommand, @@ -159,15 +159,15 @@ def createInputSequences(): lang_default, lang_en, '. Anything that falls within those guidelines is fair game. ', - lang_default + lang_default, ], [ EndUtteranceCommand(), callbackCommand, lang_en, 'Note: To get to the main wxPython site click ', - lang_default - ] + lang_default, + ], ] expectedSpeech = repr( @@ -195,17 +195,17 @@ def createInputSequences(): 'wxPython', lang_default, lang_en, - '. Anything that falls within those guidelines is fair game. ' + '. Anything that falls within those guidelines is fair game. ', ], 'spoke:True', [ # this sequence seems incorrect, however it persists the "old" behavior: # - it is missing a callback command # - it has no speech, just a meaningless pair of lang change commands - lang_en, lang_default + lang_en, lang_default, ], - 'spoke:False' - ] + 'spoke:False', + ], ) oldSpeech = resetSpeakDest() diff --git a/tests/unit/test_addonVersionCheck.py b/tests/unit/test_addonVersionCheck.py index 122f9582c89..b5144fb075d 100644 --- a/tests/unit/test_addonVersionCheck.py +++ b/tests/unit/test_addonVersionCheck.py @@ -32,7 +32,7 @@ def __init__( minAPIVersion, lastTestedAPIVersion, name="mockAddon", - version="1.0" + version="1.0", ): super(mockAddon, self).__init__() self._name = name diff --git a/tests/unit/test_baseObject.py b/tests/unit/test_baseObject.py index 5adff003eee..d0fd8ee285e 100644 --- a/tests/unit/test_baseObject.py +++ b/tests/unit/test_baseObject.py @@ -25,7 +25,7 @@ def script_bravo(self, gesture): return __gestures = { - "kb:b": "bravo" + "kb:b": "bravo", } class NVDAObjectWithDecoratedScriptAndGesturesDictionary(PlaceholderNVDAObject): @@ -47,7 +47,7 @@ def script_delta(self, gesture): class SubclassedNVDAObjectWithDecoratedScriptAndGesturesDictionary( NVDAObjectWithDecoratedScript, NVDAObjectWithGesturesDictionary, - NVDAObjectWithDecoratedScriptAndGesturesDictionary + NVDAObjectWithDecoratedScriptAndGesturesDictionary, ): """An object with decorated scripts and L{__gestures} dictionaries, based on subclassing.""" @@ -70,7 +70,7 @@ def findOverlayClasses(self, clsList): clsList.extend([ NVDAObjectWithDecoratedScript, NVDAObjectWithGesturesDictionary, - NVDAObjectWithDecoratedScriptAndGesturesDictionary + NVDAObjectWithDecoratedScriptAndGesturesDictionary, ]) @script(gestures=["kb:g"]) @@ -140,7 +140,7 @@ def test_abstractProperty(self): TypeError, "^Can't instantiate abstract class AutoPropertyObjectWithAbstractProperty " "with abstract method x", - AutoPropertyObjectWithAbstractProperty + AutoPropertyObjectWithAbstractProperty, ) def test_subclassedAbstractProperty(self): @@ -148,7 +148,7 @@ def test_subclassedAbstractProperty(self): TypeError, "^Can't instantiate abstract class SubclassedAutoPropertyObjectWithAbstractProperty " "with abstract method x", - SubclassedAutoPropertyObjectWithAbstractProperty + SubclassedAutoPropertyObjectWithAbstractProperty, ) def test_implementedProperty(self): diff --git a/tests/unit/test_bdDetect.py b/tests/unit/test_bdDetect.py index afce5f8f49f..d18cc79ef12 100644 --- a/tests/unit/test_bdDetect.py +++ b/tests/unit/test_bdDetect.py @@ -17,12 +17,12 @@ class TestBdDetectExtensionPoints(unittest.TestCase): """A test for the extension points on the bdDetect module.""" def test_scanForDevices(self): - kwargs = dict(usb=False, bluetooth=False, limitToDevices=["noBraille"],) + kwargs = dict(usb=False, bluetooth=False, limitToDevices=["noBraille"]) with chainTester( self, bdDetect.scanForDevices, [("noBraille", bdDetect.DeviceMatch("", "", "", {}))], - **kwargs + **kwargs, ): braille.handler._enableDetection(**kwargs) # wait for the detector to be terminated. diff --git a/tests/unit/test_braille/test_brailleDisplayDrivers.py b/tests/unit/test_braille/test_brailleDisplayDrivers.py index e70b70f0635..5e0349998e6 100644 --- a/tests/unit/test_braille/test_brailleDisplayDrivers.py +++ b/tests/unit/test_braille/test_brailleDisplayDrivers.py @@ -32,7 +32,7 @@ def _handleKeys(self, arg: bytes): brailleDots = arg[0] keys = arg[1] | (arg[2] << 8) self._pressedKeys = set(seikantk._getKeyNames(keys, seikantk._keyNames)).union( - seikantk._getKeyNames(brailleDots, seikantk._dotNames) + seikantk._getKeyNames(brailleDots, seikantk._dotNames), ) def _handleRouting(self, arg: bytes): @@ -102,7 +102,7 @@ def _simulateKeyPress( self, sampleMessage: bytes, expectedKeyNames: Set[str], - expectedRoutingIndexes: Set[int] + expectedRoutingIndexes: Set[int], ): seikaTestDriver = FakeSeikantkDriver(isHid=True) seikaTestDriver.simulateMessageReceived(sampleMessage) @@ -153,7 +153,7 @@ def _simulateKeyPress( self, sampleMessage: bytes, expectedKeyNames: Set[str], - expectedRoutingIndexes: Set[int] + expectedRoutingIndexes: Set[int], ): seikaTestDriver = FakeSeikantkDriver(isHid=False) seikaTestDriver.simulateMessageReceived(sampleMessage) diff --git a/tests/unit/test_braille/test_displayTextForGestureIdentifier.py b/tests/unit/test_braille/test_displayTextForGestureIdentifier.py index 9564f8aaf9c..f80ab49da9e 100644 --- a/tests/unit/test_braille/test_displayTextForGestureIdentifier.py +++ b/tests/unit/test_braille/test_displayTextForGestureIdentifier.py @@ -18,26 +18,26 @@ def test_regex(self): regex = braille.BrailleDisplayGesture.ID_PARTS_REGEX self.assertEqual( regex.match('br(noBraille.noModel):noKey1+noKey2').groups(), - ('noBraille', 'noModel', 'noKey1+noKey2') + ('noBraille', 'noModel', 'noKey1+noKey2'), ) self.assertEqual( regex.match('br(noBraille):noKey1+noKey2').groups(), - ('noBraille', None, 'noKey1+noKey2') + ('noBraille', None, 'noKey1+noKey2'), ) # Also try a string which doesn't match the pattern self.assertEqual( regex.match('br[noBraille.noModel]:noKey1+noKey2'), - None + None, ) def test_identifierWithModel(self): self.assertEqual( braille.BrailleDisplayGesture.getDisplayTextForIdentifier('br(noBraille.noModel):noKey1+noKey2'), - ('No braille', 'noModel: noKey1+noKey2') + ('No braille', 'noModel: noKey1+noKey2'), ) def test_identifierWithoutModel(self): self.assertEqual( braille.BrailleDisplayGesture.getDisplayTextForIdentifier('br(noBraille):noKey1+noKey2'), - ('No braille', 'noKey1+noKey2') + ('No braille', 'noKey1+noKey2'), ) diff --git a/tests/unit/test_braille/test_handlerExtensionPoints.py b/tests/unit/test_braille/test_handlerExtensionPoints.py index cf9efe5ddbc..871846d1e1b 100644 --- a/tests/unit/test_braille/test_handlerExtensionPoints.py +++ b/tests/unit/test_braille/test_handlerExtensionPoints.py @@ -21,7 +21,7 @@ def test_pre_writeCells(self): expectedKwargs = dict( cells=cells, rawText=braille.handler._rawText, - currentCellCount=braille.handler.displaySize + currentCellCount=braille.handler.displaySize, ) with actionTester(self, braille.pre_writeCells, **expectedKwargs): @@ -29,7 +29,7 @@ def test_pre_writeCells(self): def test_displaySizeChanged(self): expectedKwargs = dict( - displaySize=braille.handler.displaySize + displaySize=braille.handler.displaySize, ) with actionTester(self, braille.displaySizeChanged, **expectedKwargs): @@ -41,7 +41,7 @@ def test_displaySizeChanged(self): def test_displayChanged(self): expectedKwargs = dict( isFallback=False, - detected=None + detected=None, ) with actionTester(self, braille.displayChanged, useAssertDictContainsSubset=True, **expectedKwargs): diff --git a/tests/unit/test_brailleTables.py b/tests/unit/test_brailleTables.py index 8b490537d9a..451d3c18e34 100644 --- a/tests/unit/test_brailleTables.py +++ b/tests/unit/test_brailleTables.py @@ -20,7 +20,7 @@ def test_tableExistence(self): for table in tables: self.assertTrue( os.path.isfile(os.path.join(brailleTables.TABLES_DIR, table.fileName)), - msg="{table} table not found".format(table=table.displayName) + msg="{table} table not found".format(table=table.displayName), ) def test_renamedTableExistence(self): diff --git a/tests/unit/test_characterProcessing.py b/tests/unit/test_characterProcessing.py index a4042aee098..342621dd77a 100644 --- a/tests/unit/test_characterProcessing.py +++ b/tests/unit/test_characterProcessing.py @@ -44,7 +44,7 @@ def test_group_replacement(self): replaced = self._replace( string="1", pattern=r"(\d)", - replacement="a" + replacement="a", ) self.assertEqual(replaced, "a") @@ -54,7 +54,7 @@ def test_backslash_replacement(self): replaced = self._replace( string="1", pattern=r"(\d)", - replacement=r"\\" + replacement=r"\\", ) self.assertEqual(replaced, "\\") @@ -64,7 +64,7 @@ def test_double_backslash_replacement(self): replaced = self._replace( string="1", pattern=r"(\d)", - replacement=r"\\\\" + replacement=r"\\\\", ) self.assertEqual(replaced, r"\\") @@ -76,7 +76,7 @@ def test_unknown_escape(self): self._replace( string="1", pattern=r"(\d)", - replacement=r"\a" + replacement=r"\a", ) def test_missing_group(self): @@ -87,7 +87,7 @@ def test_missing_group(self): self._replace( string="1", pattern=r"(\d)", - replacement=r"\2" + replacement=r"\2", ) def test_unterminated_escape(self): @@ -98,7 +98,7 @@ def test_unterminated_escape(self): self._replace( string="1", pattern=r"(\d)", - replacement="\\" + replacement="\\", ) def test_group_replacements(self): @@ -107,7 +107,7 @@ def test_group_replacements(self): replaced = self._replace( string="bar.BAT", pattern=r"(([a-z]*)\.([A-Z]*))", - replacement=r"\2>\1" + replacement=r"\2>\1", ) self.assertEqual(replaced, "BAT>bar") @@ -118,7 +118,7 @@ def test_multiple_group_replacement(self): string="bar.BAT", pattern=r"(baz)|(?P([a-z]*)\.([A-Z]*))", replacement=r"\2>\1", - name="foo" + name="foo", ) self.assertEqual(replaced, "BAT>bar") @@ -152,7 +152,7 @@ def test_processSpeechSymbol_withoutSymbolFile(self): # The real list is: # 'af_ZA', 'am', 'as', 'gu', 'id', 'kok', 'ml', 'mni', 'ne', 'te', 'th', 'ur' # But 'mni' has only a few symbols in CLDR (and not the smiling face) - 'af_ZA', 'am', 'as', 'gu', 'id', 'kok', 'ml', 'ne', 'te', 'th', 'ur' + 'af_ZA', 'am', 'as', 'gu', 'id', 'kok', 'ml', 'ne', 'te', 'th', 'ur', ] for locale in languagesWithoutSymbolFile: self.assertNotEqual( diff --git a/tests/unit/test_checkPot/__init__.py b/tests/unit/test_checkPot/__init__.py index e46c36bbd51..06e1caf90ef 100644 --- a/tests/unit/test_checkPot/__init__.py +++ b/tests/unit/test_checkPot/__init__.py @@ -51,9 +51,9 @@ def test_checkPot_allOk(self): ( "0 errors, 0 unexpected successes, 0 expected errors, " "2 messages marked as expected errors not present in the source code" - ) + ), ), - "checkPot error count and/or status message do not meet expectations." + "checkPot error count and/or status message do not meet expectations.", ) def test_checkPot_firstMessage(self): @@ -65,9 +65,9 @@ def test_checkPot_firstMessage(self): ( "1 errors, 0 unexpected successes, 0 expected errors, " "2 messages marked as expected errors not present in the source code" - ) + ), ), - "checkPot error count and/or status message do not meet expectations." + "checkPot error count and/or status message do not meet expectations.", ) def test_checkPot_lastMessage(self): @@ -79,9 +79,9 @@ def test_checkPot_lastMessage(self): ( "1 errors, 0 unexpected successes, 0 expected errors, " "2 messages marked as expected errors not present in the source code" - ) + ), ), - "checkPot error count and/or status message do not meet expectations." + "checkPot error count and/or status message do not meet expectations.", ) def test_checkPot_shortMessages(self): @@ -93,9 +93,9 @@ def test_checkPot_shortMessages(self): ( "3 errors, 0 unexpected successes, 0 expected errors, " "2 messages marked as expected errors not present in the source code" - ) + ), ), - "checkPot error count and/or status message do not meet expectations." + "checkPot error count and/or status message do not meet expectations.", ) def test_checkPot_longMessages(self): @@ -107,8 +107,8 @@ def test_checkPot_longMessages(self): ( "3 errors, 0 unexpected successes, 0 expected errors, " "2 messages marked as expected errors not present in the source code" - ) - ) + ), + ), ) def test_checkPot_expectedErrors(self): @@ -120,9 +120,9 @@ def test_checkPot_expectedErrors(self): ( "0 errors, 0 unexpected successes, 2 expected errors, " "1 messages marked as expected errors not present in the source code" - ) + ), ), - "checkPot error count and/or status message do not meet expectations." + "checkPot error count and/or status message do not meet expectations.", ) def test_checkPot_unexpectedSuccesses(self): @@ -134,7 +134,7 @@ def test_checkPot_unexpectedSuccesses(self): ( "0 errors, 2 unexpected successes, 0 expected errors, " "1 messages marked as expected errors not present in the source code" - ) + ), ), - "checkPot error count and/or status message do not meet expectations." + "checkPot error count and/or status message do not meet expectations.", ) diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index c90caf78319..6be7abdce20 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -38,7 +38,7 @@ TetherTo, ) from utils.displayString import ( - DisplayStringEnum + DisplayStringEnum, ) @@ -46,10 +46,12 @@ class Config_FeatureFlagEnums_getAvailableEnums(unittest.TestCase): def test_knownEnumsReturned(self): self.assertTrue( - set(getAvailableEnums()).issuperset({ - ("BoolFlag", BoolFlag), - } - )) + set(getAvailableEnums()).issuperset( + { + ("BoolFlag", BoolFlag), + }, + ), + ) def test_allEnumsHaveDefault(self): noDefault = [] @@ -69,7 +71,7 @@ def test_defaultGetsAdded(self): optionsEnum="BoolFlag", # note: configObj treats param 'default' specially, it isn't passed through as a kwarg. ), - '_featureFlag(optionsEnum="BoolFlag", behaviorOfDefault="DISABLED", default="DEFAULT")' + '_featureFlag(optionsEnum="BoolFlag", behaviorOfDefault="DISABLED", default="DEFAULT")', ) def test_behaviorOfDefaultGetsKept(self): @@ -79,7 +81,7 @@ def test_behaviorOfDefaultGetsKept(self): behaviorOfDefault="enabled", optionsEnum="BoolFlag", ), - '_featureFlag(optionsEnum="BoolFlag", behaviorOfDefault="ENABLED", default="DEFAULT")' + '_featureFlag(optionsEnum="BoolFlag", behaviorOfDefault="ENABLED", default="DEFAULT")', ) def test_paramDefaultIsError(self): @@ -125,7 +127,7 @@ def test_tooManyParamsIsError(self): 'featureFlag(behaviorOfDefault="enabled", optionsEnum="BoolFlag", someOther=True)', behaviorOfDefault="enabled", optionsEnum="BoolFlag", - someOther=True + someOther=True, ) def test_optionsEnumMustBeKnown(self): @@ -134,7 +136,7 @@ def test_optionsEnumMustBeKnown(self): 'featureFlag(behaviorOfDefault="enabled", optionsEnum="UnknownEnumClass", someOther=True)', behaviorOfDefault="enabled", optionsEnum="UnknownEnumClass", - someOther=True + someOther=True, ) @@ -146,14 +148,14 @@ def assertFeatureFlagState( enumType: typing.Type, value: enum.Enum, behaviorOfDefault: enum.Enum, - calculatedValue: bool + calculatedValue: bool, ) -> None: self.assertIsInstance(flag.value, enumType, msg="Wrong enum type created") self.assertIsInstance(value, enumType, msg="Test error: wrong enum type for checking value") self.assertIsInstance( behaviorOfDefault, enumType, - msg="Test error: wrong enum type for checking behaviorOfDefault" + msg="Test error: wrong enum type for checking behaviorOfDefault", ) self.assertEqual(bool(flag), calculatedValue, msg="Calculated value for behaviour is unexpected") @@ -161,96 +163,96 @@ def assertFeatureFlagState( self.assertEqual( flag.behaviorOfDefault, behaviorOfDefault, - msg="Flag behaviorOfDefault value is unexpected" + msg="Flag behaviorOfDefault value is unexpected", ) self.assertEqual( str(flag), # conversion to string required to save to config. value.name.upper(), - msg="Flag string conversion not as expected" + msg="Flag string conversion not as expected", ) def test_enabled_lower(self): flag = featureFlag._validateConfig_featureFlag( "enabled", behaviorOfDefault="disabled", - optionsEnum=BoolFlag.__name__ + optionsEnum=BoolFlag.__name__, ) self.assertFeatureFlagState( flag, enumType=BoolFlag, value=BoolFlag.ENABLED, behaviorOfDefault=BoolFlag.DISABLED, - calculatedValue=True + calculatedValue=True, ) def test_enabled_upper(self): flag = featureFlag._validateConfig_featureFlag( "ENABLED", behaviorOfDefault="disabled", - optionsEnum=BoolFlag.__name__ + optionsEnum=BoolFlag.__name__, ) self.assertFeatureFlagState( flag, enumType=BoolFlag, value=BoolFlag.ENABLED, behaviorOfDefault=BoolFlag.DISABLED, - calculatedValue=True + calculatedValue=True, ) def test_disabled_lower(self): flag = featureFlag._validateConfig_featureFlag( "disabled", behaviorOfDefault="enabled", - optionsEnum=BoolFlag.__name__ + optionsEnum=BoolFlag.__name__, ) self.assertFeatureFlagState( flag, enumType=BoolFlag, value=BoolFlag.DISABLED, behaviorOfDefault=BoolFlag.ENABLED, - calculatedValue=False + calculatedValue=False, ) def test_disabled_upper(self): flag = featureFlag._validateConfig_featureFlag( "DISABLED", behaviorOfDefault="enabled", - optionsEnum=BoolFlag.__name__ + optionsEnum=BoolFlag.__name__, ) self.assertFeatureFlagState( flag, enumType=BoolFlag, value=BoolFlag.DISABLED, behaviorOfDefault=BoolFlag.ENABLED, - calculatedValue=False + calculatedValue=False, ) def test_default_lower(self): flag = featureFlag._validateConfig_featureFlag( "default", behaviorOfDefault="enabled", - optionsEnum=BoolFlag.__name__ + optionsEnum=BoolFlag.__name__, ) self.assertFeatureFlagState( flag, enumType=BoolFlag, value=BoolFlag.DEFAULT, behaviorOfDefault=BoolFlag.ENABLED, - calculatedValue=True + calculatedValue=True, ) def test_default_upper(self): flag = featureFlag._validateConfig_featureFlag( "DEFAULT", behaviorOfDefault="enabled", - optionsEnum=BoolFlag.__name__ + optionsEnum=BoolFlag.__name__, ) self.assertFeatureFlagState( flag, enumType=BoolFlag, value=BoolFlag.DEFAULT, behaviorOfDefault=BoolFlag.ENABLED, - calculatedValue=True + calculatedValue=True, ) def test_empty_raises(self): @@ -258,7 +260,7 @@ def test_empty_raises(self): featureFlag._validateConfig_featureFlag( "", # Given our usage of ConfigObj, this situation is unexpected. behaviorOfDefault="disabled", - optionsEnum=BoolFlag.__name__ + optionsEnum=BoolFlag.__name__, ) def test_None_raises(self): @@ -266,7 +268,7 @@ def test_None_raises(self): featureFlag._validateConfig_featureFlag( None, # Given our usage of ConfigObj, this situation is unexpected. behaviorOfDefault="disabled", - optionsEnum=BoolFlag.__name__ + optionsEnum=BoolFlag.__name__, ) def test_invalid_raises(self): @@ -274,7 +276,7 @@ def test_invalid_raises(self): featureFlag._validateConfig_featureFlag( "invalid", # must be a valid member of BoolFlag behaviorOfDefault="disabled", - optionsEnum=BoolFlag.__name__ + optionsEnum=BoolFlag.__name__, ) diff --git a/tests/unit/test_controlTypes.py b/tests/unit/test_controlTypes.py index c1a3412edae..ee8ae5f71f3 100644 --- a/tests/unit/test_controlTypes.py +++ b/tests/unit/test_controlTypes.py @@ -81,7 +81,7 @@ def setUp(self): controlTypes.State.FOCUSABLE, controlTypes.State.INVALID_ENTRY, controlTypes.State.FOCUSED, - controlTypes.State.REQUIRED + controlTypes.State.REQUIRED, } def test_positiveStates(self): @@ -90,9 +90,9 @@ def test_positiveStates(self): self.obj.role, self.obj.states, controlTypes.OutputReason.FOCUS, - self.obj.states + self.obj.states, ), - {controlTypes.State.INVALID_ENTRY, controlTypes.State.REQUIRED} + {controlTypes.State.INVALID_ENTRY, controlTypes.State.REQUIRED}, ) def test_negativeStates(self): @@ -101,9 +101,9 @@ def test_negativeStates(self): self.obj.role, self.obj.states, controlTypes.OutputReason.FOCUS, - None + None, ), - {controlTypes.State.CHECKED} + {controlTypes.State.CHECKED}, ) class TestStateOrder(unittest.TestCase): @@ -116,7 +116,7 @@ def test_positiveMergedStatesOutput(self): controlTypes.State.FOCUSABLE, controlTypes.State.FOCUSED, controlTypes.State.SELECTED, - controlTypes.State.SELECTABLE + controlTypes.State.SELECTABLE, } self.assertEqual( controlTypes.processAndLabelStates( @@ -124,9 +124,9 @@ def test_positiveMergedStatesOutput(self): obj.states, controlTypes.OutputReason.FOCUS, obj.states, - None + None, ), - [controlTypes.State.CHECKED.displayString] + [controlTypes.State.CHECKED.displayString], ) def test_negativeMergedStatesOutput(self): @@ -136,7 +136,7 @@ def test_negativeMergedStatesOutput(self): controlTypes.State.FOCUSABLE, controlTypes.State.FOCUSED, controlTypes.State.SELECTED, - controlTypes.State.SELECTABLE + controlTypes.State.SELECTABLE, } self.assertEqual( controlTypes.processAndLabelStates( @@ -144,9 +144,9 @@ def test_negativeMergedStatesOutput(self): obj.states, controlTypes.OutputReason.FOCUS, obj.states, - None + None, ), - [controlTypes.State.CHECKED.negativeDisplayString] + [controlTypes.State.CHECKED.negativeDisplayString], ) @@ -207,7 +207,7 @@ class oldStates(enum.IntEnum): self.assertEqual( controlTypes.State(old.value), old.value, - msg=f"Can't construct from integer value: {new.name}" + msg=f"Can't construct from integer value: {new.name}", ) def test_rolesValues(self): @@ -215,40 +215,40 @@ def test_rolesValues(self): if i in self.MISSING_ROLE_VALUES: with self.assertRaises( ValueError, - msg=f"Role with value {i} expected to not exist." + msg=f"Role with value {i} expected to not exist.", ): controlTypes.Role(i) else: self.assertEqual( i, controlTypes.Role(i), - msg=f"Role with value {i} expected to exist." + msg=f"Role with value {i} expected to exist.", ) for role in controlTypes.Role: self.assertTrue( isinstance(role, int), - msg="Role expected to subclass int" + msg="Role expected to subclass int", ) self.assertEqual( type(role.value), int, - msg="Role value expected to be of type int" + msg="Role value expected to be of type int", ) self.assertEqual( role, role.value, - msg="Role (enum member) and role value (int) expected to be considered equal" + msg="Role (enum member) and role value (int) expected to be considered equal", ) self.assertLess( role, role.value + 1, - msg="Role (enum member) expected to be compared as int" + msg="Role (enum member) expected to be compared as int", ) self.assertGreater( role, role.value - 1, - msg="Role (enum member) expected to be compared as int" + msg="Role (enum member) expected to be compared as int", ) @@ -267,5 +267,5 @@ def test_translateFromAttribute(self): self.assertIn( "Unknown font-size value, can't translate 'unsupported'", logContext.output[0], - msg="Parsing attempt for unknown font-size value did not fail as expected" + msg="Parsing attempt for unknown font-size value did not fail as expected", ) diff --git a/tests/unit/test_inputCore.py b/tests/unit/test_inputCore.py index d5574c04a79..b96be3e6f8b 100644 --- a/tests/unit/test_inputCore.py +++ b/tests/unit/test_inputCore.py @@ -27,7 +27,7 @@ def test_decide_executeGesture(self): self, inputCore.decide_executeGesture, expectedDecision=False, - gesture=gesture + gesture=gesture, ): inputCore.manager.executeGesture(gesture) diff --git a/tests/unit/test_javaAccessBridge.py b/tests/unit/test_javaAccessBridge.py index 1f2761825e3..84ccdbf2e04 100644 --- a/tests/unit/test_javaAccessBridge.py +++ b/tests/unit/test_javaAccessBridge.py @@ -39,7 +39,7 @@ def test_htmlStringHasTagsRemoved(self): { AccessibleKeystroke.ALT: "alt", AccessibleKeystroke.CONTROL: "control", - AccessibleKeystroke.SHIFT: "shift" + AccessibleKeystroke.SHIFT: "shift", }, {AccessibleKeystroke.ALT: "alt", AccessibleKeystroke.SHIFT: "shift"}, {AccessibleKeystroke.ALT: "alt", AccessibleKeystroke.CONTROL: "control"}, @@ -56,8 +56,8 @@ def test_htmlStringHasTagsRemoved(self): AccessibleKeystroke.ALT: "alt", AccessibleKeystroke.META: "meta", AccessibleKeystroke.CONTROL: "control", - AccessibleKeystroke.SHIFT: "shift" - } + AccessibleKeystroke.SHIFT: "shift", + }, ] BASIC_SHORTCUT_KEYS = [chr(x) for x in range(ord('A'), ord('Z') + 1)] FKEY_SHORTCUTS = [chr(x) for x in range(1, 25)] diff --git a/tests/unit/test_languageHandler.py b/tests/unit/test_languageHandler.py index ffe3bcc6838..be9e6cdfc1d 100644 --- a/tests/unit/test_languageHandler.py +++ b/tests/unit/test_languageHandler.py @@ -140,11 +140,11 @@ def test_validAnsiCodePagesAreReturnedUnicodeOnlyLocales(self): Unicode only locale names""" self.assertIn( languageHandler.ansiCodePageFromNVDALocale("hi"), - self.POSSIBLE_CODE_PAGES_FOR_UNICODE_ONLY_LOCALES + self.POSSIBLE_CODE_PAGES_FOR_UNICODE_ONLY_LOCALES, ) self.assertIn( languageHandler.ansiCodePageFromNVDALocale("Ne"), - self.POSSIBLE_CODE_PAGES_FOR_UNICODE_ONLY_LOCALES + self.POSSIBLE_CODE_PAGES_FOR_UNICODE_ONLY_LOCALES, ) @@ -154,7 +154,7 @@ class Test_languageHandler_setLocale(unittest.TestCase): SUPPORTED_LOCALES = [ ("en", 'English_United States.1252'), ("fa-IR", "Persian_Iran.1256"), - ("pl_PL", "Polish_Poland.1250") + ("pl_PL", "Polish_Poland.1250"), ] def setUp(self): @@ -250,7 +250,7 @@ def __init__(self, *args, **kwargs): ctypes.windll.kernel32.SetThreadLocale(0) defaultThreadLocale = ctypes.windll.kernel32.GetThreadLocale() self._defaultThreadLocaleName = languageHandler.windowsLCIDToLocaleName( - defaultThreadLocale + defaultThreadLocale, ) locale.setlocale(locale.LC_ALL, "") @@ -311,7 +311,7 @@ def test_NVDASupportedLanguages_LanguageIsSetCorrectly(self): self.assertIn( locale.setlocale(locale.LC_ALL), possibleVariants, - f"full values: {localeName} {python_locale}" + f"full values: {localeName} {python_locale}", ) def test_WindowsLanguages_NoErrorsThrown(self): diff --git a/tests/unit/test_locationHelper.py b/tests/unit/test_locationHelper.py index 7c7daff4b02..7884f6037fc 100644 --- a/tests/unit/test_locationHelper.py +++ b/tests/unit/test_locationHelper.py @@ -74,38 +74,42 @@ def test_points(self): def test_collection(self): """Tests whether a collection of several rectangle and point types convert to the expected L{RectLTRB}.""" rect=RectLTRB(left=10, top=15, right=500, bottom=1000) - self.assertEqual(RectLTRB.fromCollection( - rect.topLeft, - rect.bottomRight, - rect.center, - Point(15, 15), - Point(20, 20), - Point(50, 50), - Point(400, 400), - POINT(x=15, y=15), - POINT(x=20, y=20), - POINT(x=50, y=50), - POINT(x=400, y=400), - RectLTRB(left=450, top=450, right=490, bottom=990), - RECT(450, 450, 490, 990) - ), rect) + self.assertEqual( + RectLTRB.fromCollection( + rect.topLeft, + rect.bottomRight, + rect.center, + Point(15, 15), + Point(20, 20), + Point(50, 50), + Point(400, 400), + POINT(x=15, y=15), + POINT(x=20, y=20), + POINT(x=50, y=50), + POINT(x=400, y=400), + RectLTRB(left=450, top=450, right=490, bottom=990), + RECT(450, 450, 490, 990), + ), rect, + ) location=RectLTWH(left=10, top=15, width=500, height=1000) - self.assertEqual(RectLTWH.fromCollection( - location.topLeft, - location.bottomRight, - location.center, - Point(15, 15), - Point(20, 20), - Point(50, 50), - Point(400, 400), - POINT(x=15, y=15), - POINT(x=20, y=20), - POINT(x=50, y=50), - POINT(x=400, y=400), - RectLTRB(left=450, top=450, right=505, bottom=1010), - RECT(450, 450, 490, 990) - ), location) + self.assertEqual( + RectLTWH.fromCollection( + location.topLeft, + location.bottomRight, + location.center, + Point(15, 15), + Point(20, 20), + Point(50, 50), + Point(400, 400), + POINT(x=15, y=15), + POINT(x=20, y=20), + POINT(x=50, y=50), + POINT(x=400, y=400), + RectLTRB(left=450, top=450, right=505, bottom=1010), + RECT(450, 450, 490, 990), + ), location, + ) def test_fromFloatCollection(self): self.assertEqual(RectLTRB(left=10, top=10, right=20, bottom=20), RectLTRB.fromFloatCollection(10.0, 10.0, 20.0, 20.0)) diff --git a/tests/unit/test_nvwave.py b/tests/unit/test_nvwave.py index 0978e55d6d2..f0da969102e 100644 --- a/tests/unit/test_nvwave.py +++ b/tests/unit/test_nvwave.py @@ -20,12 +20,12 @@ def test_decide_playWaveFile(self): kwargs = { "fileName": os.path.join(globalVars.appDir, "waves", "start.wav"), "asynchronous": False, - "isSpeechWaveFileCommand": False + "isSpeechWaveFileCommand": False, } with deciderTester( self, nvwave.decide_playWaveFile, expectedDecision=False, - **kwargs + **kwargs, ): nvwave.playWaveFile(**kwargs) diff --git a/tests/unit/test_orderedWinEventLimiter.py b/tests/unit/test_orderedWinEventLimiter.py index bef12c177e2..91cc3796721 100644 --- a/tests/unit/test_orderedWinEventLimiter.py +++ b/tests/unit/test_orderedWinEventLimiter.py @@ -29,7 +29,7 @@ def softAssert(errorList: List[AssertionError], method: Callable, *args, **kwarg winUser.EVENT_SYSTEM_MENUSTART, winUser.EVENT_SYSTEM_MENUEND, winUser.EVENT_SYSTEM_MENUPOPUPSTART, - winUser.EVENT_SYSTEM_MENUPOPUPEND + winUser.EVENT_SYSTEM_MENUPOPUPEND, ] @@ -78,14 +78,15 @@ def test_foregroundOverwritesFocus(self): window=n, objectID=n, childID=n, threadID=n, ) events = limiter.flushEvents() - actualEvents = [( - e[0], # eventID - e[1], # window - ) for e in events - ] + actualEvents = [ + ( + e[0], # eventID + e[1], # window + ) for e in events + ] expectedEvents = [ (winUser.EVENT_SYSTEM_FOREGROUND, n), - (winUser.EVENT_SYSTEM_FOREGROUND, n) + (winUser.EVENT_SYSTEM_FOREGROUND, n), ] self.assertEqual(expectedEvents, actualEvents) @@ -186,7 +187,7 @@ def test_alwaysAllowedObjects_specialCaseEvents(self): for n in range(2000): # send many events, to saturate all limits. eventId = specialCaseEvents[n % len(specialCaseEvents)] limiter.addEvent(eventId, *allowedSource, threadID=0) - events = limiter.flushEvents(alwaysAllowedObjects=[allowedSource, ]) + events = limiter.flushEvents(alwaysAllowedObjects=[allowedSource]) expected = [ # Two Foreground events, because they are added to multiple queues. @@ -204,13 +205,13 @@ def test_alwaysAllowedObjects_onlyLatestEventKept(self): # We have events from two unique objects: # Window, objectID, childID allowedSource = (1, 1, 1) - otherSource = (2, 2, 2,) + otherSource = (2, 2, 2) limiter = OrderedWinEventLimiter(maxFocusItems=4) for n in range(50): # send many value changed events limiter.addEvent(winUser.EVENT_OBJECT_VALUECHANGE, *allowedSource, threadID=0) limiter.addEvent(winUser.EVENT_OBJECT_VALUECHANGE, *otherSource, threadID=0) - events = limiter.flushEvents(alwaysAllowedObjects=[allowedSource, ]) + events = limiter.flushEvents(alwaysAllowedObjects=[allowedSource]) # only the most recent event of each object is kept, all previous duplicates are discarded self.assertEqual(2, len(events)) @@ -219,7 +220,7 @@ def test_threadLimit_singleObject(self): """ # We have events from two unique objects: # Window, objectID, childID - source = (2, 2, 2,) + source = (2, 2, 2) limiter = OrderedWinEventLimiter(maxFocusItems=4) @@ -241,7 +242,7 @@ def test_threadLimit_noCanary(self): eventId = nonSpecialCaseEvents[n % len(nonSpecialCaseEvents)] # same thread, different object. Ensure there are no duplicates # Window, objectID, childID - source = (2, 2, n,) + source = (2, 2, n) limiter.addEvent(eventId, *source, threadID=0) events = limiter.flushEvents() @@ -265,7 +266,7 @@ def test_threadLimit_withCanaryAtStart(self): eventId = nonSpecialCaseEvents[n % len(nonSpecialCaseEvents)] # same thread, different object. Ensure there are no duplicates # Window, objectID, childID - source = (2, 2, n,) + source = (2, 2, n) limiter.addEvent(eventId, *source, threadID=0) events = limiter.flushEvents() @@ -290,7 +291,7 @@ def test_threadLimit_canaryStartAndEnd(self): eventId = nonSpecialCaseEvents[n % len(nonSpecialCaseEvents)] # same thread, different object. Ensure there are no duplicates # Window, objectID, childID - source = (2, 2, n,) + source = (2, 2, n) limiter.addEvent(eventId, *source, threadID=0) # Note event type must differ from start canary to ensure they are not duplicates @@ -319,13 +320,13 @@ def test_alwaysAllowedObjects(self): eventId = nonSpecialCaseEvents[n % len(nonSpecialCaseEvents)] # same thread, different object. Ensure there are no duplicates # Window, objectID, childID - source = (2, 2, n,) + source = (2, 2, n) limiter.addEvent(eventId, *source, threadID=0) eventEndCanary = (winUser.EVENT_OBJECT_NAMECHANGE, *canaryObject) limiter.addEvent(*eventEndCanary, threadID=0) - events = limiter.flushEvents(alwaysAllowedObjects=[canaryObject, ]) + events = limiter.flushEvents(alwaysAllowedObjects=[canaryObject]) # only the most recent event of each object is kept, all previous duplicates are discarded self.assertEqual(11, len(events)) self.assertIn(eventStartCanary, events) diff --git a/tests/unit/test_scriptHandler.py b/tests/unit/test_scriptHandler.py index 0cb713ee506..c4dafc3de3f 100644 --- a/tests/unit/test_scriptHandler.py +++ b/tests/unit/test_scriptHandler.py @@ -22,7 +22,7 @@ def test_scriptdecoration(self): canPropagate=True, bypassInputHelp=True, allowInSleepMode=True, - resumeSayAllMode=CURSOR.CARET + resumeSayAllMode=CURSOR.CARET, ) def script_test(self, gesture): return diff --git a/tests/unit/test_speech.py b/tests/unit/test_speech.py index e2ec53d14eb..0273b2d5e21 100644 --- a/tests/unit/test_speech.py +++ b/tests/unit/test_speech.py @@ -31,20 +31,22 @@ class Test_getSpellingSpeechAddCharMode(unittest.TestCase): def test_symbolNamesAtStartAndEnd(self): # Spelling ¡hola! - seq = (c for c in [ - 'inverted exclamation point', - EndUtteranceCommand(), - 'h', - EndUtteranceCommand(), - 'o', - EndUtteranceCommand(), - 'l', - EndUtteranceCommand(), - 'a', - EndUtteranceCommand(), - 'bang', - EndUtteranceCommand() - ]) + seq = ( + c for c in [ + 'inverted exclamation point', + EndUtteranceCommand(), + 'h', + EndUtteranceCommand(), + 'o', + EndUtteranceCommand(), + 'l', + EndUtteranceCommand(), + 'a', + EndUtteranceCommand(), + 'bang', + EndUtteranceCommand(), + ] + ) expected = repr([ 'inverted exclamation point', EndUtteranceCommand(), @@ -59,25 +61,27 @@ def test_symbolNamesAtStartAndEnd(self): EndUtteranceCommand(), CharacterModeCommand(False), 'bang', - EndUtteranceCommand() + EndUtteranceCommand(), ]) output = _getSpellingSpeechAddCharMode(seq) self.assertEqual(repr(list(output)), expected) def test_manySymbolNamesInARow(self): # Spelling a...b - seq = (c for c in [ - 'a', - EndUtteranceCommand(), - 'dot', - EndUtteranceCommand(), - 'dot', - EndUtteranceCommand(), - 'dot', - EndUtteranceCommand(), - 'b', - EndUtteranceCommand() - ]) + seq = ( + c for c in [ + 'a', + EndUtteranceCommand(), + 'dot', + EndUtteranceCommand(), + 'dot', + EndUtteranceCommand(), + 'dot', + EndUtteranceCommand(), + 'b', + EndUtteranceCommand(), + ] + ) expected = repr([ CharacterModeCommand(True), 'a', @@ -91,7 +95,7 @@ def test_manySymbolNamesInARow(self): EndUtteranceCommand(), CharacterModeCommand(True), 'b', - EndUtteranceCommand() + EndUtteranceCommand(), ]) output = _getSpellingSpeechAddCharMode(seq) self.assertEqual(repr(list(output)), expected) @@ -147,7 +151,7 @@ def test_pitchNotifications(self): expected = repr([ PitchCommand(offset=30), 'A', - PitchCommand() + PitchCommand(), ]) output = _getSpellingCharAddCapNotification( speakCharAs='A', @@ -185,7 +189,7 @@ def test_capNotifications(self): def test_capNotificationsWithPlaceHolderBefore(self): self.translationsFake.translationResults["cap %s"] = "%s cap" - expected = repr(['A', ' cap', ]) # for English this would be "cap A" + expected = repr(['A', ' cap']) # for English this would be "cap A" output = _getSpellingCharAddCapNotification( speakCharAs='A', sayCapForCapitals=True, @@ -197,7 +201,7 @@ def test_capNotificationsWithPlaceHolderBefore(self): def test_normalizedNotifications(self): expected = repr([ 'A', - ' normalized' + ' normalized', ]) output = _getSpellingCharAddCapNotification( speakCharAs='A', @@ -215,7 +219,7 @@ def test_allNotifications(self): 'cap ', 'A', ' normalized', - PitchCommand() + PitchCommand(), ]) output = _getSpellingCharAddCapNotification( speakCharAs='A', @@ -235,7 +239,7 @@ def setUp(self): def tearDown(self): # Restore default value config.conf['speech']['autoLanguageSwitching'] = config.conf.getConfigValidation( - ['speech', 'autoLanguageSwitching'] + ['speech', 'autoLanguageSwitching'], ).default def test_simpleSpelling(self): diff --git a/tests/unit/test_speechManager/__init__.py b/tests/unit/test_speechManager/__init__.py index b9720f8e24c..61c0a9536a1 100644 --- a/tests/unit/test_speechManager/__init__.py +++ b/tests/unit/test_speechManager/__init__.py @@ -126,7 +126,7 @@ def testAllValuesHaveSymmetry(self): # There should only be one pair with equivalence (the equal pair) self.assertEqual( len(indexesWithEquivalence), 1, - msg=f"Indexes with neither true: {indexesWithEquivalence!r}" + msg=f"Indexes with neither true: {indexesWithEquivalence!r}", ) # Ensure equivalent indexes really are equal self.assertEqual(indexesWithEquivalence[0][0], indexesWithEquivalence[0][1]) @@ -134,13 +134,13 @@ def testAllValuesHaveSymmetry(self): # None should be: A < B < A self.assertEqual( len(bothBefore), 0, - msg=f"Indexes with both true: {bothBefore!r}" + msg=f"Indexes with both true: {bothBefore!r}", ) # Check that the number of B values before and after is as expected. self.assertAlmostEqual( stationaryBeforeCount, movingBeforeCount, - delta=1 # Odd number of available indexes since 0 is excluded and one pair is equivalent. + delta=1, # Odd number of available indexes since 0 is excluded and one pair is equivalent. ) @@ -320,14 +320,16 @@ def test_validSpeechAfterInvalid(self): smi.speak([ "Stays invalid", _CancellableSpeechCommand_withLamda(lambda: False), - smi.create_ExpectedIndex(expectedToBecomeIndex=1) + smi.create_ExpectedIndex(expectedToBecomeIndex=1), ]) with smi.expectation(): smi.speak(["Stays valid", _CancellableSpeechCommand_withLamda(lambda: True)]) - smi.expect_synthSpeak(sequence=[ - "Stays valid", smi.create_ExpectedIndex(expectedToBecomeIndex=2) - ]) + smi.expect_synthSpeak( + sequence=[ + "Stays valid", smi.create_ExpectedIndex(expectedToBecomeIndex=2), + ], + ) class SayAllEmulatedTests(unittest.TestCase): @@ -368,7 +370,7 @@ def test_standardSayAll(self): seqNum = smi.speak([ callBack(expectedToBecomeIndex=1), 'sequence 0 ', - callBack(expectedToBecomeIndex=2) + callBack(expectedToBecomeIndex=2), ]) self.assertEqual(seqNum, 0) # Speech manager is expected to get started immediately @@ -378,7 +380,7 @@ def test_standardSayAll(self): 'sequence 1 before call back ', callBack(expectedToBecomeIndex=3), 'sequence 1 after call back ', - callBack(expectedToBecomeIndex=4) + callBack(expectedToBecomeIndex=4), ]) self.assertEqual(seqNum, 1) @@ -388,14 +390,14 @@ def test_standardSayAll(self): seqNum = smi.speak([ 'sequence 2 ', - callBack(expectedToBecomeIndex=5) + callBack(expectedToBecomeIndex=5), ]) self.assertEqual(seqNum, 2) seqNum = smi.speak([ # for some reason say-all handler does not give this sequence callback commands 'sequence 3 ', - expectIndex(expectedToBecomeIndex=6) + expectIndex(expectedToBecomeIndex=6), ]) self.assertEqual(seqNum, 3) @@ -431,8 +433,8 @@ def test_standardSayAll(self): expectedSendSequenceNumber=4, seq=[ callBack(expectedToBecomeIndex=7), - 'sequence 4 ', expectIndex(expectedToBecomeIndex=8) - ] + 'sequence 4 ', expectIndex(expectedToBecomeIndex=8), + ], ) # Now ensure there is no double speaking! smi.expect_synthSpeak(3) @@ -464,8 +466,8 @@ def test_speechNotRepeated(self): expectedSendSequenceNumber=2, seq=[ callBack(expectedToBecomeIndex=3), - 'sequence 2 ', expectIndex(expectedToBecomeIndex=4) - ] + 'sequence 2 ', expectIndex(expectedToBecomeIndex=4), + ], ) # Now ensure there is no double speaking! smi.expect_synthSpeak(seq1) @@ -520,7 +522,7 @@ def test_1(self, mock_BeepCommand_run, mock_WaveFileCommand_run): "higher pitch. And for the finale, let's ", _waveFileCommand(r"waves\browseMode.wav", expectedToBecomeIndex=3), "play a sound.", - smi.create_ExpectedIndex(expectedToBecomeIndex=4) + smi.create_ExpectedIndex(expectedToBecomeIndex=4), ] with smi.expectation(): smi.speak(sequence) @@ -530,9 +532,9 @@ def test_1(self, mock_BeepCommand_run, mock_WaveFileCommand_run): with smi.expectation(): smi.indexReached(i) smi.pumpAll() - if i in [1, 2, ]: + if i in [1, 2]: smi.expect_mockCall(mock_BeepCommand_run) - if i in [3, ]: + if i in [3]: smi.expect_mockCall(mock_WaveFileCommand_run) def test2(self): @@ -607,14 +609,18 @@ def test_6_SPRI(self): ]) smi.expect_synthSpeak(first) - interrupt1 = smi.speak(priority=speech.Spri.NEXT, seq=[ - "6 7 8 9 10", - smi.create_ExpectedIndex(expectedToBecomeIndex=3) - ]) - interrupt2 = smi.speak(priority=speech.Spri.NEXT, seq=[ - "11 12 13 14 15", - smi.create_ExpectedIndex(expectedToBecomeIndex=4) - ]) + interrupt1 = smi.speak( + priority=speech.Spri.NEXT, seq=[ + "6 7 8 9 10", + smi.create_ExpectedIndex(expectedToBecomeIndex=3), + ], + ) + interrupt2 = smi.speak( + priority=speech.Spri.NEXT, seq=[ + "11 12 13 14 15", + smi.create_ExpectedIndex(expectedToBecomeIndex=4), + ], + ) with smi.expectation(): smi.indexReached(1) # endUtterance @@ -656,7 +662,7 @@ def test_7_SPRI(self, mock_BeepCommand_run): "Text before the beep ", _beepCommand(440, 10, expectedToBecomeIndex=1), "text after the beep, text, text, text, text", - smi.create_ExpectedIndex(expectedToBecomeIndex=2) + smi.create_ExpectedIndex(expectedToBecomeIndex=2), ] postInterruption = toBeInterrupted[2:] with smi.expectation(): @@ -671,7 +677,7 @@ def test_7_SPRI(self, mock_BeepCommand_run): with smi.expectation(): interrupt = smi.speak( priority=speech.Spri.NOW, - seq=["This is an interruption", smi.create_ExpectedIndex(expectedToBecomeIndex=3)] + seq=["This is an interruption", smi.create_ExpectedIndex(expectedToBecomeIndex=3)], ) smi.expect_synthCancel() smi.expect_synthSpeak(interrupt) @@ -680,7 +686,7 @@ def test_7_SPRI(self, mock_BeepCommand_run): smi.indexReached(3) smi.pumpAll() smi.expect_synthSpeak( - sequence=postInterruption + sequence=postInterruption, ) def test_8_SPRI(self): @@ -692,16 +698,20 @@ def test_8_SPRI(self): """ smi = SpeechManagerInteractions(self) with smi.expectation(): - first = smi.speak(priority=speech.Spri.NOW, seq=[ - "First ", "utterance", smi.create_ExpectedIndex(expectedToBecomeIndex=1) - ]) + first = smi.speak( + priority=speech.Spri.NOW, seq=[ + "First ", "utterance", smi.create_ExpectedIndex(expectedToBecomeIndex=1), + ], + ) smi.expect_synthSpeak(first) smi.expect_synthCancel() with smi.expectation(): - second = smi.speak(priority=speech.Spri.NOW, seq=[ - "Second ", "utterance", smi.create_ExpectedIndex(expectedToBecomeIndex=2) - ]) + second = smi.speak( + priority=speech.Spri.NOW, seq=[ + "Second ", "utterance", smi.create_ExpectedIndex(expectedToBecomeIndex=2), + ], + ) with smi.expectation(): smi.indexReached(1) @@ -717,16 +727,20 @@ def test_9_SPRI(self): """ smi = SpeechManagerInteractions(self) with smi.expectation(): - first = smi.speak(priority=speech.Spri.NOW, seq=[ - "First ", "utterance", smi.create_ExpectedIndex(expectedToBecomeIndex=1) - ]) + first = smi.speak( + priority=speech.Spri.NOW, seq=[ + "First ", "utterance", smi.create_ExpectedIndex(expectedToBecomeIndex=1), + ], + ) smi.expect_synthSpeak(first) smi.expect_synthCancel() with smi.expectation(): - second = smi.speak(priority=speech.Spri.NEXT, seq=[ - "Second ", "utterance", smi.create_ExpectedIndex(expectedToBecomeIndex=2) - ]) + second = smi.speak( + priority=speech.Spri.NEXT, seq=[ + "Second ", "utterance", smi.create_ExpectedIndex(expectedToBecomeIndex=2), + ], + ) with smi.expectation(): smi.indexReached(1) @@ -756,8 +770,8 @@ def test_13_SPRI_interruptBeforeIndexReached(self, mock_BeepCommand_run): priority=speech.Spri.NOW, seq=[ "This is an interruption", - smi.create_ExpectedIndex(expectedToBecomeIndex=3) - ] + smi.create_ExpectedIndex(expectedToBecomeIndex=3), + ], ) smi.expect_synthSpeak(interrupt) smi.expect_synthCancel() @@ -803,10 +817,12 @@ def test_13_SPRI_interruptAfterIndexReached(self, mock_BeepCommand_run): smi.expect_mockCall(mock_BeepCommand_run) with smi.expectation(): - interrupt = smi.speak(priority=speech.Spri.NOW, seq=[ - "This is an interruption", - smi.create_ExpectedIndex(expectedToBecomeIndex=3) - ]) + interrupt = smi.speak( + priority=speech.Spri.NOW, seq=[ + "This is an interruption", + smi.create_ExpectedIndex(expectedToBecomeIndex=3), + ], + ) smi.expect_synthSpeak(interrupt) smi.expect_synthCancel() @@ -815,7 +831,7 @@ def test_13_SPRI_interruptAfterIndexReached(self, mock_BeepCommand_run): smi.pumpAll() resume = [ smi.create_ExpectedProsodyCommand(firstSeq[0]), - *firstSeq[3:] + *firstSeq[3:], ] smi.expect_synthSpeak(sequence=resume) @@ -865,7 +881,7 @@ def test_4_profiles(self): # The preceeding index is expected, # as the following profile trigger commands will cause the utterance to be split here. ConfigProfileTriggerCommand(t1, False), - "9 10 11 12" + "9 10 11 12", ] with smi.expectation(): smi.speak(seq) @@ -880,11 +896,13 @@ def test_4_profiles(self): smi.expect_mockCall(t1.enter) smi.expect_synthCancel() smi.expect_mockCall(t2.enter) - smi.expect_synthSpeak(sequence=[ - seq[1], # PitchCommand - '5 6 7 8', - seq[7], # IndexCommand index=2 (due to a ConfigProfileTriggerCommand following it) - ]) + smi.expect_synthSpeak( + sequence=[ + seq[1], # PitchCommand + '5 6 7 8', + seq[7], # IndexCommand index=2 (due to a ConfigProfileTriggerCommand following it) + ], + ) with smi.expectation(): smi.indexReached(2) @@ -893,11 +911,13 @@ def test_4_profiles(self): smi.doneSpeaking() smi.pumpAll() smi.expect_synthCancel() - smi.expect_synthSpeak(sequence=[ - seq[1], # PitchCommand - '9 10 11 12', - smi.create_ExpectedIndex(expectedToBecomeIndex=3) - ]) + smi.expect_synthSpeak( + sequence=[ + seq[1], # PitchCommand + '9 10 11 12', + smi.create_ExpectedIndex(expectedToBecomeIndex=3), + ], + ) smi.expect_mockCall(t1.exit) with smi.expectation(): @@ -970,7 +990,7 @@ def test_10_SPRI_profiles(self): with smi.expectation(): first = smi.speak([ "This is a normal utterance, text, text,", - smi.create_ExpectedIndex(expectedToBecomeIndex=1) + smi.create_ExpectedIndex(expectedToBecomeIndex=1), ]) smi.expect_synthSpeak(first) @@ -979,7 +999,7 @@ def test_10_SPRI_profiles(self): interrupt = [ ConfigProfileTriggerCommand(t1, True), "This is an interruption with a different profile", - smi.create_ExpectedIndex(expectedToBecomeIndex=2) + smi.create_ExpectedIndex(expectedToBecomeIndex=2), ] smi.speak(priority=speech.Spri.NOW, seq=interrupt) smi.expect_synthCancel() # twice ?? @@ -1019,7 +1039,7 @@ def test_11_SPRI_Profile(self): first = [ ConfigProfileTriggerCommand(t1, True), "This is a normal utterance with a different profile", - smi.create_ExpectedIndex(expectedToBecomeIndex=1) + smi.create_ExpectedIndex(expectedToBecomeIndex=1), ] smi.speak(first) smi.expect_synthSpeak(sequence=first[1:]) @@ -1030,7 +1050,7 @@ def test_11_SPRI_Profile(self): with smi.expectation(): interrupt = [ "This is an interruption", - smi.create_ExpectedIndex(expectedToBecomeIndex=2) + smi.create_ExpectedIndex(expectedToBecomeIndex=2), ] interruptIndex = smi.speak(priority=speech.Spri.NOW, seq=interrupt) smi.expect_synthCancel() # 2 calls ?? @@ -1086,7 +1106,7 @@ def test_12_SPRI_profile(self): first = [ ConfigProfileTriggerCommand(t1, True), "This is a normal utterance with profile 1", - smi.create_ExpectedIndex(expectedToBecomeIndex=1) + smi.create_ExpectedIndex(expectedToBecomeIndex=1), ] smi.speak(first) smi.expect_synthSpeak(sequence=first[1:]) @@ -1098,7 +1118,7 @@ def test_12_SPRI_profile(self): interrupt = [ ConfigProfileTriggerCommand(t2, True), "This is an interruption with profile 2", - smi.create_ExpectedIndex(expectedToBecomeIndex=2) + smi.create_ExpectedIndex(expectedToBecomeIndex=2), ] smi.speak(priority=speech.Spri.NOW, seq=interrupt) smi.expect_synthCancel() # 3 calls ?? @@ -1186,7 +1206,7 @@ def test_nonSpokenCharacter(self): speechSequence = [ CharacterModeCommand(True), '', - smi.create_EndUtteranceCommand(expectedToBecomeIndex=1) + smi.create_EndUtteranceCommand(expectedToBecomeIndex=1), ] with smi.expectation(): seqIndexes = smi.speak(speechSequence) diff --git a/tests/unit/test_speechManager/speechManagerTestHarness.py b/tests/unit/test_speechManager/speechManagerTestHarness.py index 0963485aec4..9fb4b2e97ff 100644 --- a/tests/unit/test_speechManager/speechManagerTestHarness.py +++ b/tests/unit/test_speechManager/speechManagerTestHarness.py @@ -66,7 +66,7 @@ class ExpectedProsody: expectedProsody: Union[ PitchCommand, RateCommand, - VolumeCommand + VolumeCommand, ] def __eq__(self, other): @@ -255,7 +255,7 @@ def _updateKnownSequences(self, seq) -> List[_SentSequenceIndex]: def speak( self, seq: List[Union[speech.types.SequenceItemT, ExpectedProsody, ExpectedIndex, EndUtteranceCommand]], - priority=speech.Spri.NORMAL + priority=speech.Spri.NORMAL, ) -> Union[_SentSequenceIndex, List[_SentSequenceIndex]]: """Call SpeechManager.speak and track sequences used.""" sequenceNumbers = self._updateKnownSequences(seq) @@ -297,7 +297,7 @@ def create_CallBackCommand(self, expectedToBecomeIndex): self._assertStrictIndexOrder(expectedToBecomeIndex) cb = CallbackCommand( lambda i=expectedToBecomeIndex: self._indexReachedCallback(i), - name=f"indexCommandIndex: {expectedToBecomeIndex}" + name=f"indexCommandIndex: {expectedToBecomeIndex}", ) cb.expectedIndexCommandIndex = expectedToBecomeIndex return cb @@ -325,7 +325,7 @@ def create_BeepCommand(self, hz, length, left=50, right=50, expectedToBecomeInde """ self._testCase.assertIsNotNone( expectedToBecomeIndex, - "Did you forget to provide the 'expectedToBecomeIndex' argument?" + "Did you forget to provide the 'expectedToBecomeIndex' argument?", ) self._assertStrictIndexOrder(expectedToBecomeIndex) b = BeepCommand(hz, length, left, right) @@ -340,7 +340,7 @@ def create_ConfigProfileTriggerCommand(self, trigger, enter=True, expectedToBeco """ self._testCase.assertIsNotNone( expectedToBecomeIndex, - "Did you forget to provide the 'expectedToBecomeIndex' argument?" + "Did you forget to provide the 'expectedToBecomeIndex' argument?", ) self._assertStrictIndexOrder(expectedToBecomeIndex) t = ConfigProfileTriggerCommand(trigger, enter) @@ -355,7 +355,7 @@ def create_WaveFileCommand(self, filename, expectedToBecomeIndex=None): """ self._testCase.assertIsNotNone( expectedToBecomeIndex, - "Did you forget to provide the 'expectedToBecomeIndex' argument?" + "Did you forget to provide the 'expectedToBecomeIndex' argument?", ) self._assertStrictIndexOrder(expectedToBecomeIndex) w = WaveFileCommand(filename) @@ -370,7 +370,7 @@ def create_EndUtteranceCommand(self, expectedToBecomeIndex=None): """ self._testCase.assertIsNotNone( expectedToBecomeIndex, - "Did you forget to provide the 'expectedToBecomeIndex' argument?" + "Did you forget to provide the 'expectedToBecomeIndex' argument?", ) self._assertStrictIndexOrder(expectedToBecomeIndex) e = EndUtteranceCommand() @@ -380,7 +380,7 @@ def create_EndUtteranceCommand(self, expectedToBecomeIndex=None): def expect_indexReachedCallback( self, forIndex: _IndexT, - sideEffect: Optional[Callable[[], None]] = None + sideEffect: Optional[Callable[[], None]] = None, ): """Expect that upon exiting the expectation block, forIndex will have been reached. If a side effect is required (such as speaking more text) this must be called before @@ -391,7 +391,7 @@ def expect_indexReachedCallback( if not (self._lastCommandIndex >= forIndex > 0): self._testCase.fail( f"Test Case error. Index {forIndex} not sent to synth yet," - f" ensure SpeechManagerInteractions.speak has already been called." + f" ensure SpeechManagerInteractions.speak has already been called.", ) self._awaitingCallbackForIndex.append((forIndex, sideEffect)) @@ -399,7 +399,7 @@ def expect_indexReachedCallback( self._testCase.fail( f"IndexReached not yet called for {forIndex}." f" Check test for smi.indexReached({forIndex})" - f" IndexReach called for the following: {self._testDebug_IndexReached!r}" + f" IndexReach called for the following: {self._testDebug_IndexReached!r}", ) self._assertSpeechManagerKnowsAboutIndex(forIndex) @@ -449,7 +449,7 @@ def expect_synthSpeak( self._testCase.assertLess( sequenceNumbers, len(self._knownSequences), - msg=f"Less than {sequenceNumbers} sequences have been sent to the synth (see calls to speak)" + msg=f"Less than {sequenceNumbers} sequences have been sent to the synth (see calls to speak)", ) self._awaitingSpeakCalls.append(sequenceNumbers) else: @@ -458,7 +458,7 @@ def expect_synthSpeak( self.expect_synthSpeak(i) else: self._testCase.fail( - f"sequenceNumbers should be int or Iterable[int]. ArgType: {type(sequenceNumbers)}" + f"sequenceNumbers should be int or Iterable[int]. ArgType: {type(sequenceNumbers)}", ) def _updateExpectedStateFromAwaiting_speak(self): @@ -490,7 +490,7 @@ def _assertIndexCallbackState(self): f"Number of CallbackCommand callbacks not as expected." f"\nExpected: {expectedCalls}" f"\nGot: {self._indexReachedCallback.call_args_list}" - ) + ), ) self._indexReachedCallback.assert_has_calls(expectedCalls) @@ -499,7 +499,7 @@ def _assertCancelState(self): self._testCase.assertEqual( expectedCancelCallCount, self.synthMock.cancel.call_count, - msg=f"The number of calls to synth.cancel was not as expected. Expected {expectedCancelCallCount}" + msg=f"The number of calls to synth.cancel was not as expected. Expected {expectedCancelCallCount}", ) def _assertMockCallsState(self): @@ -507,7 +507,7 @@ def _assertMockCallsState(self): self._testCase.assertEqual( e, m.call_count, - msg=f"The number of calls to {m} was not as expected. Expected {e}" + msg=f"The number of calls to {m} was not as expected. Expected {e}", ) def _assertCurrentSpeechCallState(self): @@ -522,7 +522,7 @@ def _assertCurrentSpeechCallState(self): f"\nExpected a total of {len(expectedSeqIndexes)}" f"\nThe index(es) of the expected sequences: {expectedSeqIndexes}" f"\nActual calls: {mockSpeak.call_args_list}" - ) + ), ) # Build (total) expected call list replaceWithExpectedIndexTypes = ( @@ -550,7 +550,7 @@ def pumpAllAndSendSpeechOnCallback( expectCallbackForIndex: int, expectedSendSequenceNumber: Union[int, List[int]], seq, - priority=speech.Spri.NORMAL + priority=speech.Spri.NORMAL, ): """Must be called in an 'expectation' block. """ def _lineReachedSideEffect(): @@ -570,7 +570,7 @@ def _assertStrictIndexOrder(self, expectedToBecomeIndex): self._testCase.assertEqual( expectedToBecomeIndex, indexCommandIndex, - msg="Did you forget to update the 'expectedToBecomeIndex' argument?" + msg="Did you forget to update the 'expectedToBecomeIndex' argument?", ) def _filterAndSendSpeech(self, seq, priority): diff --git a/tests/unit/test_speechShortcutKeys.py b/tests/unit/test_speechShortcutKeys.py index d914331fce6..b3adad75200 100644 --- a/tests/unit/test_speechShortcutKeys.py +++ b/tests/unit/test_speechShortcutKeys.py @@ -39,7 +39,7 @@ def test_simpleLetterKeyWithSpellingFunctionalityDisabled(self): (see #15566). """ - expected = repr(['A', ]) + expected = repr(['A']) output = _getKeyboardShortcutSpeech( keyboardShortcut='A', ) diff --git a/tests/unit/test_speechXml.py b/tests/unit/test_speechXml.py index 406e29a73b5..153a4f47f5a 100644 --- a/tests/unit/test_speechXml.py +++ b/tests/unit/test_speechXml.py @@ -97,13 +97,13 @@ def test_text(self): def test_standAloneTag(self): xml = self.balancer.generateXml([ - speechXml.StandAloneTagCommand("tag", {"attr": "val"}, "content") + speechXml.StandAloneTagCommand("tag", {"attr": "val"}, "content"), ]) self.assertEqual(xml, 'content') def test_standAloneTagNoContent(self): xml = self.balancer.generateXml([ - speechXml.StandAloneTagCommand("tag", {"attr": "val"}, None) + speechXml.StandAloneTagCommand("tag", {"attr": "val"}, None), ]) self.assertEqual(xml, '') @@ -112,7 +112,7 @@ def test_attrEscaping(self): Depends on behavior tested in test_standAloneTagNoContent. """ xml = self.balancer.generateXml([ - speechXml.StandAloneTagCommand("tag", {"attr": '"v1"&"v2"'}, None) + speechXml.StandAloneTagCommand("tag", {"attr": '"v1"&"v2"'}, None), ]) self.assertEqual(xml, '') @@ -121,21 +121,21 @@ def test_encloseAll(self): """ xml = self.balancer.generateXml([ speechXml.EncloseAllCommand("encloseAll", {"attr": "val"}), - speechXml.StandAloneTagCommand("standAlone", {}, "content") + speechXml.StandAloneTagCommand("standAlone", {}, "content"), ]) self.assertEqual(xml, 'content') def test_setAttr(self): xml = self.balancer.generateXml([ speechXml.SetAttrCommand("pitch", "val", 50), - "text" + "text", ]) self.assertEqual(xml, 'text') def test_delAttrNoSetAttr(self): xml = self.balancer.generateXml([ speechXml.DelAttrCommand("pitch", "val"), - "text" + "text", ]) self.assertEqual(xml, 'text') @@ -144,7 +144,7 @@ def test_setAttrThenDelAttr(self): speechXml.SetAttrCommand("pitch", "val", 50), "t1", speechXml.DelAttrCommand("pitch", "val"), - "t2" + "t2", ]) self.assertEqual(xml, 't1t2') @@ -154,7 +154,7 @@ def test_setAttrDifferentTags(self): xml = self.balancer.generateXml([ speechXml.SetAttrCommand("pitch", "val", 50), speechXml.SetAttrCommand("volume", "val", 60), - "text" + "text", ]) self.assertEqual(xml, 'text') @@ -165,7 +165,7 @@ def test_setAttrInterspersedText(self): speechXml.SetAttrCommand("pitch", "val", 50), "t1", speechXml.SetAttrCommand("volume", "val", 60), - "t2" + "t2", ]) self.assertEqual(xml, 't1t2') @@ -175,7 +175,7 @@ def test_setAttrDifferentAttrs(self): xml = self.balancer.generateXml([ speechXml.SetAttrCommand("prosody", "pitch", 50), speechXml.SetAttrCommand("prosody", "volume", 60), - "text" + "text", ]) self.assertEqual(xml, 'text') @@ -187,7 +187,7 @@ def test_delAttrUnbalanced(self): speechXml.SetAttrCommand("volume", "val", 60), "t1", speechXml.DelAttrCommand("pitch", "val"), - "t2" + "t2", ]) self.assertEqual(xml, 't1t2') @@ -199,7 +199,7 @@ def test_delSingleAttrOfMultipleAttrs(self): speechXml.SetAttrCommand("prosody", "volume", 60), "t1", speechXml.DelAttrCommand("prosody", "pitch"), - "t2" + "t2", ]) self.assertEqual(xml, 't1t2') @@ -209,7 +209,7 @@ def test_EncloseText(self): xml = self.balancer.generateXml([ speechXml.EncloseTextCommand("say-as", {"interpret-as": "characters"}), speechXml.StandAloneTagCommand("mark", {"name": "1"}, None), - "c" + "c", ]) self.assertEqual(xml, 'c') @@ -220,7 +220,7 @@ def test_stopEnclosingText(self): speechXml.EncloseTextCommand("say-as", {}), "c", speechXml.StopEnclosingTextCommand(), - "t" + "t", ]) self.assertEqual(xml, 'ct') @@ -245,17 +245,18 @@ def test_convertComplex(self): IndexCommand(1), "c", CharacterModeCommand(False), - PhonemeCommand("phIpa", text="phText") + PhonemeCommand("phIpa", text="phText"), ]) - self.assertEqual(xml, - '' - 't1' - 't2' - '' - 'c' - 'phText' - '' - ) + self.assertEqual( + xml, + '' + 't1' + 't2' + '' + 'c' + 'phText' + '', + ) class TestSsmlParser(unittest.TestCase): diff --git a/tests/unit/test_synthDriverHandler.py b/tests/unit/test_synthDriverHandler.py index 03fbbde5087..ed056d9a798 100644 --- a/tests/unit/test_synthDriverHandler.py +++ b/tests/unit/test_synthDriverHandler.py @@ -122,13 +122,13 @@ def test_setSynth_auto_fallback_ifOneCoreDoesntSupportDefaultLanguage(self): def test_synthChangedExtensionPoint(self): expectedKwargs = dict( isFallback=False, - audioOutputDevice="default" + audioOutputDevice="default", ) with actionTester( self, synthDriverHandler.synthChanged, useAssertDictContainsSubset=True, - **expectedKwargs + **expectedKwargs, ): synthDriverHandler.setSynth("auto") diff --git a/tests/unit/test_synthDrivers/test_espeak.py b/tests/unit/test_synthDrivers/test_espeak.py index 17cec465457..6b40dd2366a 100644 --- a/tests/unit/test_synthDrivers/test_espeak.py +++ b/tests/unit/test_synthDrivers/test_espeak.py @@ -30,37 +30,37 @@ def test_normalizeLangCommand(self): self.assertEqual( LangChangeCommand("en-gb"), SynthDriver._normalizeLangCommand(FakeESpeakSynthDriver, LangChangeCommand(None)), - msg="Default language used if language code not provided" + msg="Default language used if language code not provided", ) self.assertEqual( LangChangeCommand("fr-fr"), SynthDriver._normalizeLangCommand(FakeESpeakSynthDriver, LangChangeCommand("fr_FR")), - msg="Language with locale used when available" + msg="Language with locale used when available", ) self.assertEqual( LangChangeCommand("en-gb"), SynthDriver._normalizeLangCommand(FakeESpeakSynthDriver, LangChangeCommand("default")), - msg="Default eSpeak language mappings used" + msg="Default eSpeak language mappings used", ) self.assertEqual( LangChangeCommand("fr"), SynthDriver._normalizeLangCommand(FakeESpeakSynthDriver, LangChangeCommand("fr_FAKE")), - msg="Language without locale used when available" + msg="Language without locale used when available", ) self.assertEqual( LangChangeCommand("ta-ta"), SynthDriver._normalizeLangCommand(FakeESpeakSynthDriver, LangChangeCommand("ta-gb")), - msg="Language with any locale used when available" + msg="Language with any locale used when available", ) with self.assertLogs(logHandler.log, level=logging.DEBUG) as logContext: self.assertEqual( LangChangeCommand(None), SynthDriver._normalizeLangCommand(FakeESpeakSynthDriver, LangChangeCommand("fake")), - msg="No matching available language returns None" + msg="No matching available language returns None", ) self.assertIn( "Unable to find an eSpeak language for 'fake'", - logContext.output[0] + logContext.output[0], ) @@ -89,7 +89,7 @@ def test_defaultMappingAvailableLanguage(self): msg=( "Languages mapped by default are no longer supported by eSpeak: " f"{unexpectedUnsupportedDefaultLanguages}" - ) + ), ) expectedUnsupportedMappedLanguages = set(self._driver._defaultLangToLocale.keys()) @@ -100,7 +100,7 @@ def test_defaultMappingAvailableLanguage(self): msg=( "Languages mapped to eSpeak defaults are now supported by eSpeak: " f"{unexpectedSupportedMappedLanguages}" - ) + ), ) supportedLanguagesWithLocaleStripped = set(stripLocaleFromLangCode(lang) for lang in eSpeakAvailableLangs) @@ -112,7 +112,7 @@ def test_defaultMappingAvailableLanguage(self): "eSpeak has a language with locale supported " "but the language without locale is unsupported." "Update _defaultLangToLocale to include a new mapping." - ) + ), ) def test_availableLanguagesWithoutLocale(self): @@ -126,7 +126,7 @@ def test_availableLanguagesWithoutLocale(self): self.assertEqual( langWithoutLocale, self._driver.voice.split("\\")[-1], # Language code is the last item, e.g. (gmw\en, roa\fr-CH) - msg="Language without locale not supported by eSpeak" + msg="Language without locale not supported by eSpeak", ) def test_fallbackToBritishEnglish(self): @@ -137,5 +137,5 @@ def test_fallbackToBritishEnglish(self): self.assertEqual( "gmw\\en", self._driver.voice, - msg="Language without locale not supported by eSpeak" + msg="Language without locale not supported by eSpeak", ) diff --git a/tests/unit/test_textInfos.py b/tests/unit/test_textInfos.py index 73bfa698798..20059317070 100644 --- a/tests/unit/test_textInfos.py +++ b/tests/unit/test_textInfos.py @@ -239,7 +239,7 @@ class TestMoveToCodepointOffsetInOffsetsTextInfo(unittest.TestCase): ] def runTestImpl(self, prefix: str, text: str, target: str, encoding: str): - self.assertTrue(target in text, "Invalid test case", ) + self.assertTrue(target in text, "Invalid test case") prefixOffset = textUtils.getOffsetConverter(encoding)(prefix).encodedStringLength obj = BasicTextProvider(text=prefix + text, encoding=encoding) info = obj.makeTextInfo(Offsets(0, 0)) diff --git a/tests/unit/test_textUtils.py b/tests/unit/test_textUtils.py index 6f548cfd036..ad4cc026fec 100644 --- a/tests/unit/test_textUtils.py +++ b/tests/unit/test_textUtils.py @@ -210,10 +210,12 @@ def test_wideToStrOffsets(self): self.assertEqual(converter.strLength, 3) self.assertEqual( converter.wideToStrOffsets(-1, 0, raiseOnError=False), - (0, 0)) + (0, 0), + ) self.assertEqual( converter.wideToStrOffsets(0, 4, raiseOnError=False), - (0, 3)) + (0, 3), + ) self.assertRaises(IndexError, converter.wideToStrOffsets, -1, 0, raiseOnError=True) self.assertRaises(IndexError, converter.wideToStrOffsets, 0, 4, raiseOnError=True) self.assertRaises(ValueError, converter.wideToStrOffsets, 1, 0) @@ -223,10 +225,12 @@ def test_strToWideOffsets(self): self.assertEqual(converter.wideStringLength, 3) self.assertEqual( converter.strToWideOffsets(-1, 0, raiseOnError=False), - (0, 0)) + (0, 0), + ) self.assertEqual( converter.strToWideOffsets(0, 4, raiseOnError=False), - (0, 3)) + (0, 3), + ) self.assertRaises(IndexError, converter.strToWideOffsets, -1, 0, raiseOnError=True) self.assertRaises(IndexError, converter.strToWideOffsets, 0, 4, raiseOnError=True) self.assertRaises(ValueError, converter.strToWideOffsets, 1, 0) diff --git a/tests/unit/test_tones.py b/tests/unit/test_tones.py index 5c0571b7f04..588012976ea 100644 --- a/tests/unit/test_tones.py +++ b/tests/unit/test_tones.py @@ -32,6 +32,6 @@ def test_decide_beep(self): self, tones.decide_beep, expectedDecision=False, - **kwargs + **kwargs, ): tones.beep(**kwargs) diff --git a/tests/unit/test_util/test_blockUntilConditionMet.py b/tests/unit/test_util/test_blockUntilConditionMet.py index 341f3119534..284ae56148f 100644 --- a/tests/unit/test_util/test_blockUntilConditionMet.py +++ b/tests/unit/test_util/test_blockUntilConditionMet.py @@ -105,7 +105,7 @@ def test_condition_succeeds_before_timeout(self): getValue=self._timer.getValue, giveUpAfterSeconds=giveUpAfterSeconds, shouldStopEvaluator=self._timer.createShouldStopEvaluator( - succeedAfterSeconds=giveUpAfterSeconds - _FakeTimer.POLL_INTERVAL + succeedAfterSeconds=giveUpAfterSeconds - _FakeTimer.POLL_INTERVAL, ), intervalBetweenSeconds=_FakeTimer.POLL_INTERVAL, ) @@ -113,7 +113,7 @@ def test_condition_succeeds_before_timeout(self): timeElapsed = self._timer.time() self.assertTrue( success, - msg=f"Test condition failed unexpectedly due to timeout. Elapsed time: {timeElapsed:.2f}s" + msg=f"Test condition failed unexpectedly due to timeout. Elapsed time: {timeElapsed:.2f}s", ) self.assertGreater(giveUpAfterSeconds, timeElapsed) @@ -123,14 +123,14 @@ def test_condition_fails_on_timeout(self): getValue=self._timer.getValue, giveUpAfterSeconds=giveUpAfterSeconds, shouldStopEvaluator=self._timer.createShouldStopEvaluator( - succeedAfterSeconds=giveUpAfterSeconds + _FakeTimer.POLL_INTERVAL + succeedAfterSeconds=giveUpAfterSeconds + _FakeTimer.POLL_INTERVAL, ), intervalBetweenSeconds=_FakeTimer.POLL_INTERVAL, ) timeElapsed = self._timer.time() self.assertFalse( success, - msg=f"Test condition succeeded unexpectedly before timeout. Elapsed time: {timeElapsed:.2f}s" + msg=f"Test condition succeeded unexpectedly before timeout. Elapsed time: {timeElapsed:.2f}s", ) self.assertGreaterEqual(timeElapsed, giveUpAfterSeconds) diff --git a/tests/unit/test_util/test_schedule.py b/tests/unit/test_util/test_schedule.py index 1fc3722ebce..236770836b4 100644 --- a/tests/unit/test_util/test_schedule.py +++ b/tests/unit/test_util/test_schedule.py @@ -67,12 +67,12 @@ def incrementC(scheduledVals: list): self.assertLessEqual( actualSecsOffset, expectedSecsOffsetMax, - f"Job {jobIndex} was not scheduled as expected. Job: {currentJob}" + f"Job {jobIndex} was not scheduled as expected. Job: {currentJob}", ) self.assertGreaterEqual( actualSecsOffset, expectedSecsOffsetMin, - f"Job {jobIndex} was not scheduled as expected. Job: {currentJob}" + f"Job {jobIndex} was not scheduled as expected. Job: {currentJob}", ) # Ensure the job runs as expected @@ -81,7 +81,7 @@ def incrementC(scheduledVals: list): self.assertEqual( scheduledVals, expectedResult, - f"Job {jobIndex} did not run as expected. Scheduled jobs: {schedule.jobs}" + f"Job {jobIndex} did not run as expected. Scheduled jobs: {schedule.jobs}", ) def test_scheduleJob(self): diff --git a/tests/unit/test_util/test_security.py b/tests/unit/test_util/test_security.py index d9f066e3871..3cc199b4f13 100644 --- a/tests/unit/test_util/test_security.py +++ b/tests/unit/test_util/test_security.py @@ -201,7 +201,7 @@ def test_visited_windowMoves_aboveTargets(self): move=_MoveWindow( HWNDToMove=3, insertBelowHWND=6, - triggerHWND=4 + triggerHWND=4, ), aboveWindow=5, belowWindow=2, @@ -217,10 +217,10 @@ def test_visited_windowMoves_betweenTargets(self): move=_MoveWindow( HWNDToMove=3, insertBelowHWND=5, - triggerHWND=4 + triggerHWND=4, ), aboveWindow=6, - belowWindow=2 + belowWindow=2, ) def test_visited_windowMoves_belowTargets(self): @@ -232,7 +232,7 @@ def test_visited_windowMoves_belowTargets(self): move=_MoveWindow( HWNDToMove=3, insertBelowHWND=1, - triggerHWND=4 + triggerHWND=4, ), aboveWindow=5, belowWindow=2, @@ -248,12 +248,12 @@ def test_active_windowMoves_betweenTargets(self): move=_MoveWindow( HWNDToMove=3, insertBelowHWND=8, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=10, belowWindow=6, aboveRaises=_UnexpectedWindowCountError, # handled as if window is above - belowExpectFailure=True # handled as if window is above + belowExpectFailure=True, # handled as if window is above ) def test_active_windowMoves_beforeTargets(self): @@ -265,7 +265,7 @@ def test_active_windowMoves_beforeTargets(self): move=_MoveWindow( HWNDToMove=3, insertBelowHWND=5, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=10, belowWindow=6, @@ -281,10 +281,10 @@ def test_active_windowMoves_belowTargets(self): _MoveWindow( HWNDToMove=3, insertBelowHWND=1, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=10, - belowWindow=6 + belowWindow=6, ) def test_unvisited_windowMoves_aboveTargets(self): @@ -296,10 +296,10 @@ def test_unvisited_windowMoves_aboveTargets(self): move=_MoveWindow( HWNDToMove=5, insertBelowHWND=8, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=6, - belowWindow=2 + belowWindow=2, ) def test_unvisited_windowMoves_betweenTargets(self): @@ -311,10 +311,10 @@ def test_unvisited_windowMoves_betweenTargets(self): move=_MoveWindow( HWNDToMove=4, insertBelowHWND=6, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=8, - belowWindow=2 + belowWindow=2, ) def test_unvisited_windowMoves_belowTargets(self): @@ -326,10 +326,10 @@ def test_unvisited_windowMoves_belowTargets(self): move=_MoveWindow( HWNDToMove=4, insertBelowHWND=1, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=8, - belowWindow=2 + belowWindow=2, ) def test_belowWindow_windowMoves_aboveAboveWindow(self): @@ -343,10 +343,10 @@ def test_belowWindow_windowMoves_aboveAboveWindow(self): move=_MoveWindow( HWNDToMove=belowWindow, insertBelowHWND=8, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=6, - belowWindow=belowWindow + belowWindow=belowWindow, ) def test_belowWindow_windowMoves_towardsAboveWindow(self): @@ -360,7 +360,7 @@ def test_belowWindow_windowMoves_towardsAboveWindow(self): move=_MoveWindow( HWNDToMove=belowWindow, insertBelowHWND=6, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=8, belowWindow=belowWindow, @@ -377,10 +377,10 @@ def test_belowWindow_windowMoves_furtherBelow(self): move=_MoveWindow( HWNDToMove=belowWindow, insertBelowHWND=1, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=8, - belowWindow=belowWindow + belowWindow=belowWindow, ) def test_aboveWindow_windowMoves_furtherAbove(self): @@ -393,10 +393,10 @@ def test_aboveWindow_windowMoves_furtherAbove(self): move=_MoveWindow( HWNDToMove=aboveWindow, insertBelowHWND=8, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=aboveWindow, - belowWindow=2 + belowWindow=2, ) def test_aboveWindow_windowMoves_towardsBelowWindow(self): @@ -409,10 +409,10 @@ def test_aboveWindow_windowMoves_towardsBelowWindow(self): move=_MoveWindow( HWNDToMove=aboveWindow, insertBelowHWND=6, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=aboveWindow, - belowWindow=2 + belowWindow=2, ) def test_aboveWindow_windowMoves_belowBelowWindow(self): @@ -426,9 +426,9 @@ def test_aboveWindow_windowMoves_belowBelowWindow(self): move=_MoveWindow( HWNDToMove=aboveWindow, insertBelowHWND=1, - triggerHWND=3 + triggerHWND=3, ), aboveWindow=aboveWindow, belowWindow=2, - belowRaises=_UnexpectedWindowCountError # handled as if window is above + belowRaises=_UnexpectedWindowCountError, # handled as if window is above ) diff --git a/tests/unit/test_winAPI/test_displayTracking.py b/tests/unit/test_winAPI/test_displayTracking.py index 1d92da2473d..98e952053a2 100644 --- a/tests/unit/test_winAPI/test_displayTracking.py +++ b/tests/unit/test_winAPI/test_displayTracking.py @@ -28,7 +28,7 @@ def test_orientationChange_landscape(self): ) self.assertEqual( newStyle, - Orientation.LANDSCAPE + Orientation.LANDSCAPE, ) def test_orientationChange_portrait(self): @@ -45,7 +45,7 @@ def test_orientationChange_portrait(self): ) self.assertEqual( newStyle, - Orientation.PORTRAIT + Orientation.PORTRAIT, ) def test_noChanges_screenFlip(self): @@ -63,7 +63,7 @@ def test_noChanges_screenFlip(self): ) self.assertEqual( newStyle, - Orientation.LANDSCAPE + Orientation.LANDSCAPE, ) def test_widthIncreaseLandscape(self): diff --git a/tests/unit/test_winAPI/test_powerTracking.py b/tests/unit/test_winAPI/test_powerTracking.py index 61717ab3685..d5d02320f21 100644 --- a/tests/unit/test_winAPI/test_powerTracking.py +++ b/tests/unit/test_winAPI/test_powerTracking.py @@ -21,7 +21,7 @@ class Test_GetSpeechForBatteryStatus(unittest.TestCase): def setUp(self) -> None: self.testPowerStatus = cast( SystemPowerStatus, - MagicMock(SystemPowerStatus()) + MagicMock(SystemPowerStatus()), ) def test_fetch_status_fetchFailed(self): diff --git a/tests/unit/test_winVersion.py b/tests/unit/test_winVersion.py index 3654a2dba8f..4f042cadfc0 100644 --- a/tests/unit/test_winVersion.py +++ b/tests/unit/test_winVersion.py @@ -20,7 +20,7 @@ def test_getWinVer(self): winVerPython = sys.getwindowsversion() self.assertTupleEqual( (currentWinVer.major, currentWinVer.minor, currentWinVer.build), - winVerPython[:3] + winVerPython[:3], ) def test_getWinVerFromNonExistentRelease(self): @@ -34,7 +34,7 @@ def test_moreRecentWinVer(self): minimumWinVer = winVersion.WIN81 emojiPanelIntroduced = winVersion.WIN10_1709 self.assertGreaterEqual( - emojiPanelIntroduced, minimumWinVer + emojiPanelIntroduced, minimumWinVer, ) def test_winVerKnownReleaseNameForWinVersionConstant(self): @@ -49,7 +49,7 @@ def test_winVerKnownBuildToReleaseName(self): # Try Windows 10 1809. knownMajor, knownMinor, knownBuild = 10, 0, 17763 knownPublicRelease = winVersion.WinVersion( - major=knownMajor, minor=knownMinor, build=knownBuild + major=knownMajor, minor=knownMinor, build=knownBuild, ) self.assertEqual(knownPublicRelease.releaseName, "Windows 10 1809") @@ -65,10 +65,10 @@ def test_winVerReleaseNameFromWindowsRegistry(self): # as this is defined for testing purposes. major, minor, build = 10, 0, 21390 insiderBuild = winVersion.WinVersion( - major=major, minor=minor, build=build + major=major, minor=minor, build=build, ) self.assertIn( - "unknown", insiderBuild.releaseName + "unknown", insiderBuild.releaseName, ) def test_winVerUnknownBuildToReleaseName(self): @@ -76,7 +76,7 @@ def test_winVerUnknownBuildToReleaseName(self): # Try Windows 8.1 which is actually version 6.3. unknownMajor, unknownMinor, unknownBuild = 8, 1, 0 badWin81Info = winVersion.WinVersion( - major=unknownMajor, minor=unknownMinor, build=unknownBuild + major=unknownMajor, minor=unknownMinor, build=unknownBuild, ) self.assertEqual(badWin81Info.releaseName, "Windows release unknown") @@ -91,6 +91,6 @@ def test_winVerUnknownWin11BuildToReleaseName(self): # See if build 25398 (zinc milestone) is recognized as a Windows 11 "unknown" release. zincMajor, zincMinor, zincBuild = 10, 0, 25398 win11ZincInfo = winVersion.WinVersion( - major=zincMajor, minor=zincMinor, build=zincBuild + major=zincMajor, minor=zincMinor, build=zincBuild, ) self.assertEqual(win11ZincInfo.releaseName, "Windows 11 unknown") diff --git a/user_docs/keyCommandsDoc.py b/user_docs/keyCommandsDoc.py index 6e06e22bbd5..06d39e738f3 100644 --- a/user_docs/keyCommandsDoc.py +++ b/user_docs/keyCommandsDoc.py @@ -148,7 +148,7 @@ def _command(self, cmd: Command | None = None, arg: str | None = None): if self._settingsNumLayouts < 1: raise KeyCommandsError( f"{self._lineNum}, settingsSection command must specify the header row for a table" - " summarising the settings" + " summarising the settings", ) elif cmd == Command.SETTING.value: @@ -233,7 +233,7 @@ def _handleSetting(self): if not Regex.TABLE_ROW.value.match(line): raise KeyCommandsError( f"{self._lineNum}, setting command: " - "There must be one table row for each keyboard layout" + "There must be one table row for each keyboard layout", ) # This is a table row. @@ -257,7 +257,7 @@ def _handleSetting(self): raise KeyCommandsError( f"{self._lineNum}, setting command: The keyboard shortcuts must be followed by a blank line. " "Multiple keys must be included in a table. " - f"Erroneous key: {key}" + f"Erroneous key: {key}", ) # Finally, the next line should be the description. diff --git a/venvUtils/ensureVenv.py b/venvUtils/ensureVenv.py index 53d4d730399..85e1b2cc321 100644 --- a/venvUtils/ensureVenv.py +++ b/venvUtils/ensureVenv.py @@ -26,7 +26,7 @@ if not isInteractive: print( "Warning: Running in non-interactive mode. Defaults are assumed for prompts, if applicable", - flush=True + flush=True, ) @@ -117,7 +117,7 @@ def createVenv(): "--clear", venv_path, ], - check=True + check=True, ) with open(venv_python_version_path, "w") as f: f.write(sys.version) @@ -147,7 +147,7 @@ def ensureVenvAndRequirements(): if askYesNoQuestion( f"Virtual environment at {venv_path} probably not created by NVDA. " "This directory must be removed before continuing. Should it be removed?", - default=True + default=True, ): return createVenvAndPopulate() else: @@ -168,7 +168,7 @@ def ensureVenvAndRequirements(): "This means that transitive dependencies can get out of sync " "with those used in automated builds. " "Would you like to continue recreating the environment?", - default=True + default=True, ): return createVenvAndPopulate() return populate() @@ -180,7 +180,7 @@ def ensureVenvAndRequirements(): if virtualEnv: print( "Error: It looks like another Python virtual environment is already active in this shell.\n" - "Please deactivate the current Python virtual environment and try again." + "Please deactivate the current Python virtual environment and try again.", ) sys.exit(1) ensureVenvAndRequirements() From b31c94cf5856832f2fff2c6270e1d5e44c9cd6af Mon Sep 17 00:00:00 2001 From: Sean Budd Date: Thu, 4 Jul 2024 13:21:27 +1000 Subject: [PATCH 3/4] run ruff format --- appveyor/crowdinSync.py | 8 +- appveyor/mozillaSyms.py | 55 +- appx/sconscript | 140 +- cldrDict_sconscript | 14 +- .../examples/example_python.py | 12 +- nvdaHelper/ISimpleDOM_sconscript | 60 +- nvdaHelper/UIARemote/sconscript | 38 +- nvdaHelper/acrobatAccess_sconscript | 33 +- nvdaHelper/archBuild_sconscript | 294 +-- nvdaHelper/client/sconscript | 42 +- nvdaHelper/detours/sconscript | 23 +- nvdaHelper/espeak/sconscript | 1075 +++++++-- nvdaHelper/ia2_sconscript | 101 +- nvdaHelper/liblouis/sconscript | 123 +- nvdaHelper/local/sconscript | 58 +- nvdaHelper/localWin10/sconscript | 39 +- nvdaHelper/mathPlayer_sconscript | 44 +- nvdaHelper/remote/sconscript | 50 +- nvdaHelper/remoteLoader/sconscript | 38 +- nvdaHelper/sconscript | 61 +- .../vbufBackends/adobeAcrobat/sconscript | 38 +- nvdaHelper/vbufBackends/gecko_ia2/sconscript | 34 +- .../lotusNotesRichText/sconscript | 34 +- nvdaHelper/vbufBackends/mshtml/sconscript | 34 +- nvdaHelper/vbufBackends/webKit/sconscript | 34 +- nvdaHelper/vbufBase/sconscript | 17 +- projectDocs/dev/developerGuide/conf.py | 13 +- projectDocs/dev/developerGuide/sconscript | 81 +- sconstruct | 555 +++-- site_scons/site_tools/doxygen.py | 389 ++-- site_scons/site_tools/gettextTool.py | 36 +- site_scons/site_tools/listModules.py | 18 +- site_scons/site_tools/md2html.py | 35 +- site_scons/site_tools/msrpc.py | 117 +- site_scons/site_tools/recursiveInstall.py | 54 +- source/COMRegistrationFixes/__init__.py | 5 +- source/IAccessibleHandler/__init__.py | 113 +- .../internalWinEventHandler.py | 24 +- .../orderedWinEventLimiter.py | 18 +- source/IAccessibleHandler/types.py | 1 + source/IAccessibleHandler/utils.py | 12 +- source/JABHandler.py | 1010 ++++++--- source/NVDAHelper.py | 588 +++-- source/NVDAObjects/IAccessible/MSHTML.py | 981 ++++---- .../NVDAObjects/IAccessible/SysMonthCal32.py | 16 +- source/NVDAObjects/IAccessible/__init__.py | 1680 ++++++++------ .../NVDAObjects/IAccessible/adobeAcrobat.py | 46 +- source/NVDAObjects/IAccessible/akelEdit.py | 12 +- source/NVDAObjects/IAccessible/chromium.py | 32 +- source/NVDAObjects/IAccessible/delphi.py | 12 +- source/NVDAObjects/IAccessible/hh.py | 29 +- .../NVDAObjects/IAccessible/ia2TextMozilla.py | 124 +- source/NVDAObjects/IAccessible/ia2Web.py | 95 +- source/NVDAObjects/IAccessible/mozilla.py | 57 +- source/NVDAObjects/IAccessible/msOffice.py | 127 +- source/NVDAObjects/IAccessible/mscandui.py | 294 +-- source/NVDAObjects/IAccessible/qt.py | 45 +- source/NVDAObjects/IAccessible/scintilla.py | 14 +- .../NVDAObjects/IAccessible/sysListView32.py | 585 +++-- .../NVDAObjects/IAccessible/sysTreeView32.py | 248 +- source/NVDAObjects/IAccessible/webKit.py | 20 +- source/NVDAObjects/IAccessible/winConsole.py | 12 +- source/NVDAObjects/IAccessible/winword.py | 460 ++-- source/NVDAObjects/JAB/__init__.py | 503 ++-- source/NVDAObjects/UIA/VisualStudio.py | 26 +- source/NVDAObjects/UIA/__init__.py | 1450 +++++++----- source/NVDAObjects/UIA/chromium.py | 20 +- source/NVDAObjects/UIA/excel.py | 80 +- source/NVDAObjects/UIA/spartanEdge.py | 33 +- source/NVDAObjects/UIA/sysListView32.py | 16 +- source/NVDAObjects/UIA/web.py | 115 +- source/NVDAObjects/UIA/winConsoleUIA.py | 48 +- source/NVDAObjects/UIA/wordDocument.py | 401 ++-- source/NVDAObjects/__init__.py | 444 ++-- source/NVDAObjects/behaviors.py | 311 ++- source/NVDAObjects/inputComposition.py | 217 +- source/NVDAObjects/window/__init__.py | 372 +-- source/NVDAObjects/window/_msOfficeChart.py | 1271 +++++++---- source/NVDAObjects/window/akelEdit.py | 184 +- source/NVDAObjects/window/edit.py | 1034 +++++---- source/NVDAObjects/window/excel.py | 2014 ++++++++++------- source/NVDAObjects/window/excelCellBorder.py | 147 +- source/NVDAObjects/window/scintilla.py | 334 +-- source/NVDAObjects/window/winConsole.py | 51 +- source/NVDAObjects/window/winword.py | 1824 ++++++++------- source/NVDAState.py | 7 +- source/UIAHandler/__init__.py | 362 +-- source/UIAHandler/_remoteOps/builder.py | 30 +- .../_remoteOps/instructions/__init__.py | 1 - .../_remoteOps/instructions/_base.py | 1 - .../_remoteOps/instructions/arithmetic.py | 1 + .../_remoteOps/instructions/bool.py | 1 - .../_remoteOps/instructions/controlFlow.py | 1 - .../_remoteOps/instructions/element.py | 4 +- .../_remoteOps/instructions/extension.py | 1 - .../_remoteOps/instructions/float.py | 1 - .../_remoteOps/instructions/general.py | 13 +- .../_remoteOps/instructions/guid.py | 1 - .../UIAHandler/_remoteOps/instructions/int.py | 1 - .../_remoteOps/instructions/null.py | 1 - .../_remoteOps/instructions/status.py | 1 - .../_remoteOps/instructions/string.py | 1 - .../_remoteOps/instructions/textRange.py | 1 - source/UIAHandler/_remoteOps/localExecute.py | 18 +- source/UIAHandler/_remoteOps/lowLevel.py | 98 +- source/UIAHandler/_remoteOps/operation.py | 48 +- source/UIAHandler/_remoteOps/remoteAPI.py | 36 +- .../UIAHandler/_remoteOps/remoteAlgorithms.py | 8 +- .../_remoteOps/remoteFuncWrapper.py | 68 +- .../_remoteOps/remoteTypes/__init__.py | 39 +- .../_remoteOps/remoteTypes/element.py | 6 +- .../_remoteOps/remoteTypes/extensionTarget.py | 6 +- .../_remoteOps/remoteTypes/intEnum.py | 12 +- .../_remoteOps/remoteTypes/textRange.py | 52 +- source/UIAHandler/browseMode.py | 663 ++++-- source/UIAHandler/constants.py | 1 + source/UIAHandler/customAnnotations.py | 4 +- source/UIAHandler/customProps.py | 7 +- source/UIAHandler/remote.py | 33 +- source/UIAHandler/types.py | 53 +- source/UIAHandler/utils.py | 259 ++- source/XMLFormatting.py | 43 +- source/addonAPIVersion.py | 4 +- source/addonHandler/__init__.py | 238 +- source/addonHandler/addonVersionCheck.py | 22 +- source/addonHandler/packaging.py | 7 +- source/addonStore/dataManager.py | 27 +- source/addonStore/install.py | 17 +- source/addonStore/models/addon.py | 15 +- source/addonStore/models/channel.py | 24 +- source/addonStore/models/status.py | 137 +- source/addonStore/models/version.py | 42 +- source/addonStore/network.py | 21 +- source/annotation.py | 5 +- source/api.py | 199 +- source/appModuleHandler.py | 199 +- source/appModules/1password.py | 1 - source/appModules/aim.py | 8 +- source/appModules/audacity.py | 9 +- source/appModules/azardi20.py | 13 +- source/appModules/bookshelf.py | 26 +- source/appModules/calc.py | 56 +- source/appModules/calculator.py | 25 +- source/appModules/cicero.py | 4 +- source/appModules/code.py | 6 +- source/appModules/devenv.py | 22 +- source/appModules/digitaleditions.py | 34 +- source/appModules/dllhost.py | 4 +- source/appModules/doctts.py | 4 +- source/appModules/dosvox.py | 4 +- source/appModules/eclipse.py | 38 +- source/appModules/egui.py | 1 - source/appModules/esysuite.py | 12 +- source/appModules/excel.py | 23 +- source/appModules/explorer.py | 102 +- source/appModules/fastlogentry.py | 2 - source/appModules/foobar2000.py | 5 +- source/appModules/hxmail.py | 34 +- source/appModules/instantbird.py | 22 +- source/appModules/itunes.py | 81 +- source/appModules/javaw.py | 15 +- source/appModules/kindle.py | 190 +- source/appModules/lockapp.py | 23 +- source/appModules/lockapphost.py | 10 +- source/appModules/logonui.py | 55 +- source/appModules/loudtalks.py | 26 +- source/appModules/lync.py | 76 +- source/appModules/microsoftedge.py | 11 +- source/appModules/microsoftedgecp.py | 27 +- source/appModules/mintty.py | 4 +- source/appModules/miranda32.py | 247 +- source/appModules/mirc.py | 17 +- source/appModules/mmc.py | 17 +- source/appModules/mplayerc.py | 16 +- source/appModules/msedgewebview2.py | 3 +- source/appModules/msimn.py | 163 +- source/appModules/msnmsgr.py | 100 +- source/appModules/nlnotes.py | 64 +- source/appModules/notepad.py | 6 +- source/appModules/notepadPlusPlus.py | 14 +- source/appModules/nvda.py | 28 +- source/appModules/obu.py | 17 +- source/appModules/openwith.py | 22 +- source/appModules/outlook.py | 606 ++--- source/appModules/poedit.py | 17 +- source/appModules/powerpnt.py | 1536 +++++++------ source/appModules/putty.py | 20 +- source/appModules/searchui.py | 10 +- source/appModules/securecrt.py | 22 +- source/appModules/shellexperiencehost.py | 7 +- source/appModules/skype.py | 11 +- source/appModules/soffice.py | 152 +- source/appModules/spotify.py | 28 +- source/appModules/symphony.py | 24 +- source/appModules/systemsettings.py | 12 +- source/appModules/taskmgr.py | 3 +- source/appModules/teams.py | 9 +- source/appModules/teamtalk4classic.py | 20 +- source/appModules/thunderbird.py | 22 +- source/appModules/totalcmd.py | 44 +- source/appModules/ttermpro.py | 19 +- source/appModules/tween.py | 10 +- source/appModules/utorrent.py | 40 +- source/appModules/vipmud.py | 26 +- source/appModules/webconferenceplugin.py | 16 +- source/appModules/winamp.py | 90 +- ...bleshell_experiences_textinput_inputapp.py | 103 +- source/appModules/winword.py | 4 +- source/appModules/wlmail.py | 62 +- source/appModules/wwahost.py | 6 +- source/appModules/zoom.py | 21 +- source/aria.py | 106 +- source/audio/soundSplit.py | 19 +- source/audioDucking.py | 96 +- source/autoSettingsUtils/autoSettings.py | 43 +- source/autoSettingsUtils/driverSetting.py | 64 +- source/autoSettingsUtils/utils.py | 4 +- source/baseObject.py | 135 +- source/bdDetect.py | 138 +- source/braille.py | 580 ++--- .../albatross/_threading.py | 23 +- .../albatross/constants.py | 3 + .../brailleDisplayDrivers/albatross/driver.py | 36 +- .../albatross/gestures.py | 119 +- source/brailleDisplayDrivers/alva.py | 299 ++- source/brailleDisplayDrivers/baum.py | 294 +-- source/brailleDisplayDrivers/brailleNote.py | 220 +- source/brailleDisplayDrivers/brailliantB.py | 177 +- source/brailleDisplayDrivers/brltty.py | 50 +- source/brailleDisplayDrivers/ecoBraille.py | 396 +++- .../eurobraille/constants.py | 182 +- .../eurobraille/driver.py | 122 +- .../eurobraille/gestures.py | 22 +- .../freedomScientific.py | 326 ++- source/brailleDisplayDrivers/handyTech.py | 621 ++--- source/brailleDisplayDrivers/hedoMobilLine.py | 47 +- source/brailleDisplayDrivers/hedoProfiLine.py | 68 +- .../hidBrailleStandard.py | 145 +- source/brailleDisplayDrivers/hims.py | 732 +++--- source/brailleDisplayDrivers/lilli.py | 131 +- source/brailleDisplayDrivers/nattiqbraille.py | 35 +- source/brailleDisplayDrivers/noBraille.py | 15 +- source/brailleDisplayDrivers/papenmeier.py | 581 +++-- .../papenmeier_serial.py | 300 +-- source/brailleDisplayDrivers/seika.py | 49 +- source/brailleDisplayDrivers/seikantk.py | 111 +- source/brailleDisplayDrivers/superBrl.py | 46 +- source/brailleInput.py | 116 +- source/brailleTables.py | 33 +- source/brailleViewer/__init__.py | 7 +- source/brailleViewer/brailleViewerGui.py | 101 +- .../brailleViewerInputGesture.py | 1 + source/browseMode.py | 1292 ++++++----- source/characterProcessing.py | 194 +- source/colors.py | 178 +- source/comHelper.py | 43 +- source/comInterfaces_sconscript | 80 +- source/compoundDocuments.py | 114 +- source/config/__init__.py | 188 +- source/config/aggregatedSection.py | 4 +- source/config/configDefaults.py | 52 +- source/config/configFlags.py | 55 +- source/config/configSpec.py | 2 +- source/config/featureFlag.py | 38 +- source/config/featureFlagEnums.py | 8 +- source/config/profileUpgradeSteps.py | 109 +- source/config/profileUpgrader.py | 34 +- source/contentRecog/__init__.py | 68 +- source/contentRecog/recogUi.py | 16 +- source/contentRecog/uwpOcr.py | 14 +- source/controlTypes/__init__.py | 1 + source/controlTypes/deprecatedAliases.py | 12 +- source/controlTypes/descriptionFrom.py | 1 + source/controlTypes/formatFields.py | 43 +- source/controlTypes/isCurrent.py | 1 + source/controlTypes/outputReason.py | 4 +- source/controlTypes/processAndLabelStates.py | 58 +- source/controlTypes/role.py | 1 + .../controlTypes/roleAndStateSpecialCases.py | 7 +- source/core.py | 184 +- source/cursorManager.py | 275 ++- source/diffHandler.py | 44 +- source/displayModel.py | 723 +++--- source/documentBase.py | 164 +- source/documentNavigation/paragraphHelper.py | 22 +- source/driverHandler.py | 1 + source/easeOfAccess.py | 6 +- source/editableText.py | 166 +- source/eventHandler.py | 204 +- source/exceptions.py | 3 +- source/extensionPoints/__init__.py | 7 +- source/extensionPoints/util.py | 28 +- source/fileUtils.py | 31 +- source/fonts/__init__.py | 16 +- source/garbageHandler.py | 7 +- source/globalCommands.py | 951 ++++---- source/globalPluginHandler.py | 21 +- source/globalVars.py | 12 +- source/gui/__init__.py | 192 +- source/gui/addonGui.py | 110 +- source/gui/addonStoreGui/controls/actions.py | 22 +- .../gui/addonStoreGui/controls/addonList.py | 14 +- source/gui/addonStoreGui/controls/details.py | 37 +- .../addonStoreGui/controls/messageDialogs.py | 171 +- .../gui/addonStoreGui/controls/storeDialog.py | 58 +- source/gui/addonStoreGui/viewModels/action.py | 41 +- .../gui/addonStoreGui/viewModels/addonList.py | 61 +- source/gui/addonStoreGui/viewModels/store.py | 97 +- source/gui/blockAction.py | 3 + source/gui/configProfiles.py | 192 +- source/gui/contextHelp.py | 11 +- source/gui/dpiScalingHelper.py | 10 +- source/gui/exit.py | 6 +- source/gui/guiHelper.py | 164 +- source/gui/inputGestures.py | 97 +- source/gui/installerGui.py | 166 +- source/gui/logViewer.py | 37 +- source/gui/message.py | 10 +- source/gui/nvdaControls.py | 157 +- source/gui/settingsDialogs.py | 1318 ++++++----- source/gui/speechDict.py | 78 +- source/gui/startupDialogs.py | 39 +- source/hidpi.py | 94 +- source/hwIo/__init__.py | 1 - source/hwIo/base.py | 108 +- source/hwIo/hid.py | 40 +- source/hwIo/ioThread.py | 52 +- source/hwPortUtils.py | 71 +- source/inputCore.py | 112 +- source/installer.py | 411 ++-- source/keyLabels.py | 168 +- source/keyboardHandler.py | 194 +- source/languageHandler.py | 75 +- source/localesData.py | 1 - source/locationHelper.py | 291 +-- source/logHandler.py | 159 +- source/mathPres/__init__.py | 29 +- source/mathPres/mathPlayer.py | 65 +- source/mathType.py | 20 +- source/monkeyPatches/__init__.py | 1 + source/monkeyPatches/comtypesMonkeyPatches.py | 64 +- source/monkeyPatches/wxMonkeyPatches.py | 1 + source/mouseHandler.py | 234 +- source/msoAutoShapeTypes.py | 786 +++---- source/nvda.pyw | 193 +- source/nvdaBuiltin.py | 10 +- source/nvda_slave.pyw | 60 +- source/nvwave.py | 193 +- source/objbase.py | 10 +- source/objidl.py | 624 ++--- source/oleTypes.py | 1134 ++++++---- source/oleacc.py | 396 ++-- source/pythonConsole.py | 107 +- source/queueHandler.py | 52 +- source/remotePythonConsole.py | 30 +- source/review.py | 140 +- source/screenBitmap.py | 95 +- source/screenExplorer.py | 78 +- source/scriptHandler.py | 140 +- source/setup.py | 147 +- source/shellapi.py | 64 +- source/shlobj.py | 7 +- source/sourceEnv.py | 11 +- source/speech/__init__.py | 2 +- source/speech/commands.py | 118 +- source/speech/manager.py | 77 +- source/speech/priorities.py | 1 + source/speech/sayAll.py | 78 +- source/speech/shortcutKeys.py | 38 +- source/speech/speech.py | 1798 ++++++++------- source/speech/speechWithoutPauses.py | 34 +- source/speech/types.py | 25 +- source/speechDictHandler/__init__.py | 116 +- source/speechDictHandler/dictFormatUpgrade.py | 252 ++- source/speechViewer.py | 31 +- source/speechXml.py | 91 +- source/synthDriverHandler.py | 43 +- source/synthDrivers/_espeak.py | 284 +-- source/synthDrivers/_sapi4.py | 242 +- source/synthDrivers/espeak.py | 157 +- source/synthDrivers/mssp.py | 15 +- source/synthDrivers/oneCore.py | 83 +- source/synthDrivers/sapi4.py | 185 +- source/synthDrivers/sapi5.py | 93 +- source/synthDrivers/silence.py | 9 +- source/synthSettingsRing.py | 76 +- source/systemUtils.py | 6 +- source/tableUtils.py | 101 +- source/textInfos/__init__.py | 549 ++--- source/textInfos/offsets.py | 543 +++-- source/textUtils/__init__.py | 139 +- source/textUtils/uniscribe.py | 7 +- source/tones.py | 20 +- source/touchHandler.py | 347 +-- source/touchTracker.py | 521 +++-- source/treeInterceptorHandler.py | 111 +- source/ui.py | 44 +- source/updateCheck.py | 309 +-- source/utils/blockUntilConditionMet.py | 12 +- source/utils/caseInsensitiveCollections.py | 5 +- source/utils/displayString.py | 7 + source/utils/schedule.py | 70 +- source/utils/security.py | 41 +- source/utils/tempFile.py | 6 +- source/virtualBuffers/MSHTML.py | 422 ++-- source/virtualBuffers/__init__.py | 542 +++-- source/virtualBuffers/adobeAcrobat.py | 90 +- source/virtualBuffers/gecko_ia2.py | 290 +-- source/virtualBuffers/lotusNotes.py | 113 +- source/virtualBuffers/webKit.py | 95 +- source/vision/__init__.py | 1 + source/vision/constants.py | 4 +- source/vision/exceptions.py | 9 +- source/vision/providerBase.py | 9 +- source/vision/util.py | 5 +- source/vision/visionHandler.py | 51 +- source/vision/visionHandlerExtensionPoints.py | 1 + .../NVDAHighlighter.py | 54 +- .../_exampleProvider_autoGui.py | 52 +- .../screenCurtain.py | 28 +- source/vkCodes.py | 10 +- source/watchdog.py | 178 +- source/winAPI/_displayTracking.py | 6 +- source/winAPI/_powerTracking.py | 17 +- source/winAPI/_wtsApi32.py | 26 +- source/winAPI/dpiAwareness.py | 4 +- source/winAPI/messageWindow.py | 2 +- source/winAPI/sessionTracking.py | 19 +- source/winAPI/winUser/constants.py | 8 +- source/winConsoleHandler.py | 308 +-- source/winGDI.py | 75 +- source/winInputHook.py | 134 +- source/winKernel.py | 325 ++- source/winUser.py | 820 ++++--- source/winVersion.py | 46 +- source/wincon.py | 121 +- source/windowUtils.py | 32 +- tests/checkPot.py | 142 +- tests/sconscript | 25 +- tests/system/libraries/AssertsLib.py | 35 +- tests/system/libraries/ChromeLib.py | 66 +- tests/system/libraries/NotepadLib.py | 32 +- tests/system/libraries/NvdaLib.py | 63 +- .../SystemTestSpy/blockUntilConditionMet.py | 14 +- .../libraries/SystemTestSpy/configManager.py | 22 +- .../system/libraries/SystemTestSpy/getLib.py | 3 + .../SystemTestSpy/speechSpyGlobalPlugin.py | 106 +- .../SystemTestSpy/speechSpySynthDriver.py | 8 +- .../system/libraries/SystemTestSpy/windows.py | 15 +- tests/system/libraries/WindowsLib.py | 17 +- tests/system/libraries/_chromeArgs.py | 5 +- tests/system/robot/NVDAInstaller.py | 13 +- tests/system/robot/NVDASettings.py | 5 +- tests/system/robot/chromeTests.py | 1220 +++++----- tests/system/robot/startupShutdownNVDA.py | 54 +- .../system/robot/symbolPronunciationTests.py | 646 +++--- tests/unit/__init__.py | 22 +- tests/unit/contentRecog/test_contentRecog.py | 18 +- tests/unit/contentRecog/test_uwpOcr.py | 20 +- tests/unit/extensionPointTestHelpers.py | 56 +- tests/unit/objectProvider.py | 20 +- tests/unit/test_SpeechWithoutPauses.py | 79 +- .../test_highLevel/test_bool.py | 1 - .../test_highLevel/test_element.py | 1 - .../test_highLevel/test_errorHandling.py | 1 - .../test_highLevel/test_float.py | 1 - .../test_highLevel/test_if.py | 1 - .../test_highLevel/test_instructionLimit.py | 1 - .../test_highLevel/test_int.py | 1 - .../test_highLevel/test_iterable.py | 1 - .../test_highLevel/test_numericComparison.py | 1 - .../test_highLevel/test_string.py | 3 +- .../test_highLevel/test_while.py | 1 - .../test_addonHandler/test_addonsState.py | 3 - tests/unit/test_addonVersionCheck.py | 20 +- tests/unit/test_appModules/test_foobar2000.py | 11 +- tests/unit/test_baseObject.py | 42 +- tests/unit/test_bdDetect.py | 5 +- .../test_brailleDisplayDrivers.py | 55 +- .../test_displayTextForGestureIdentifier.py | 22 +- .../test_focusContextPresentation.py | 47 +- .../test_handlerExtensionPoints.py | 6 +- tests/unit/test_braille/test_routing.py | 12 +- tests/unit/test_brailleTables.py | 14 +- tests/unit/test_characterProcessing.py | 63 +- tests/unit/test_checkPot/__init__.py | 1 + tests/unit/test_config.py | 187 +- tests/unit/test_controlTypes.py | 11 +- tests/unit/test_cursorManager.py | 205 +- tests/unit/test_excel.py | 6 +- tests/unit/test_extensionPoints.py | 466 ++-- tests/unit/test_globalCommands.py | 2 - tests/unit/test_hwIo.py | 10 +- tests/unit/test_inputCore.py | 4 +- tests/unit/test_installer.py | 3 +- tests/unit/test_javaAccessBridge.py | 2 +- tests/unit/test_languageHandler.py | 12 +- tests/unit/test_locationHelper.py | 182 +- tests/unit/test_nvwave.py | 3 +- tests/unit/test_orderedWinEventLimiter.py | 117 +- tests/unit/test_scriptHandler.py | 1 + tests/unit/test_speech.py | 424 ++-- tests/unit/test_speechManager/__init__.py | 313 +-- .../speechManagerTestHarness.py | 89 +- tests/unit/test_speechShortcutKeys.py | 184 +- tests/unit/test_speechXml.py | 307 +-- tests/unit/test_synthDriverHandler.py | 9 +- tests/unit/test_synthDrivers/test_espeak.py | 26 +- tests/unit/test_textInfos.py | 137 +- tests/unit/test_textUtils.py | 102 +- tests/unit/test_tones.py | 3 +- .../test_util/test_blockUntilConditionMet.py | 13 +- .../test_caseInsensitiveCollections.py | 3 +- tests/unit/test_util/test_displayString.py | 3 +- tests/unit/test_util/test_localisation.py | 11 +- tests/unit/test_util/test_schedule.py | 11 +- tests/unit/test_util/test_security.py | 38 +- .../unit/test_winAPI/test_displayTracking.py | 1 - tests/unit/test_winAPI/test_powerTracking.py | 10 +- tests/unit/test_winVersion.py | 23 +- tests/unit/textProvider.py | 29 +- user_docs/keyCommandsDoc.py | 17 +- venvUtils/ensureVenv.py | 41 +- 523 files changed, 38105 insertions(+), 28956 deletions(-) diff --git a/appveyor/crowdinSync.py b/appveyor/crowdinSync.py index dbd799cf8d8..0945099433d 100644 --- a/appveyor/crowdinSync.py +++ b/appveyor/crowdinSync.py @@ -20,10 +20,10 @@ def request( - path: str, - method=requests.get, - headers: dict[str, str] | None = None, - **kwargs, + path: str, + method=requests.get, + headers: dict[str, str] | None = None, + **kwargs, ) -> requests.Response: if headers is None: headers = {} diff --git a/appveyor/mozillaSyms.py b/appveyor/mozillaSyms.py index 5cbee390f69..ec6f3918fd2 100644 --- a/appveyor/mozillaSyms.py +++ b/appveyor/mozillaSyms.py @@ -18,7 +18,7 @@ NVDA_LIB = os.path.join(NVDA_SOURCE, "lib") NVDA_LIB64 = os.path.join(NVDA_SOURCE, "lib64") ZIP_FILE = os.path.join(SCRIPT_DIR, "mozillaSyms.zip") -URL = 'https://symbols.mozilla.org/upload/' +URL = "https://symbols.mozilla.org/upload/" # The dlls for which symbols are to be uploaded to Mozilla. # This only needs to include dlls injected into Mozilla products. @@ -28,59 +28,63 @@ "nvdaHelperRemote.dll", ] DLL_FILES = [ - f - for dll in DLL_NAMES - # We need both the 32 bit and 64 bit symbols. - for f in (os.path.join(NVDA_LIB, dll), os.path.join(NVDA_LIB64, dll)) + f + for dll in DLL_NAMES + # We need both the 32 bit and 64 bit symbols. + for f in (os.path.join(NVDA_LIB, dll), os.path.join(NVDA_LIB64, dll)) ] + class ProcError(Exception): def __init__(self, returncode, stderr): self.returncode = returncode self.stderr = stderr + def check_output(command): proc = subprocess.Popen( - command, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True, - ) + command, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) stdout, stderr = proc.communicate() if proc.returncode != 0: raise ProcError(proc.returncode, stderr) return stdout + def processFile(path): - print("dump_syms %s"%path) + print("dump_syms %s" % path) try: stdout = check_output([DUMP_SYMS, path]) except ProcError as e: print('Error: running "%s %s": %s' % (DUMP_SYMS, path, e.stderr)) return None, None, None - bits = stdout.splitlines()[0].split(' ', 4) + bits = stdout.splitlines()[0].split(" ", 4) if len(bits) != 5: return None, None, None _, platform, cpu_arch, debug_id, debug_file = bits # debug_file will have a .pdb extension; e.g. nvdaHelperRemote.dll.pdb. # The output file format should have a .sym extension instead. # Strip .pdb and add .sym. - sym_file = debug_file[:-4] + '.sym' + sym_file = debug_file[:-4] + ".sym" filename = os.path.join(debug_file, debug_id, sym_file) debug_filename = os.path.join(debug_file, debug_id, debug_file) return filename, stdout, debug_filename + def generate(): count = 0 - with zipfile.ZipFile(ZIP_FILE, 'w', zipfile.ZIP_DEFLATED) as zf: + with zipfile.ZipFile(ZIP_FILE, "w", zipfile.ZIP_DEFLATED) as zf: for f in DLL_FILES: filename, contents, debug_filename = processFile(f) if not (filename and contents): - print('Error dumping symbols') + print("Error dumping symbols") raise RuntimeError zf.writestr(filename, contents) count += 1 - print('Added %d files to %s' % (count, ZIP_FILE)) + print("Added %d files to %s" % (count, ZIP_FILE)) def upload(): @@ -89,12 +93,13 @@ def upload(): if i > 0: print("Sleeping for 15 seconds before next attempt.") import time + time.sleep(15) try: r = requests.post( URL, - files={'symbols.zip': open(ZIP_FILE, 'rb')}, - headers={'Auth-Token': os.getenv('mozillaSymsAuthToken')}, + files={"symbols.zip": open(ZIP_FILE, "rb")}, + headers={"Auth-Token": os.getenv("mozillaSymsAuthToken")}, allow_redirects=False, ) break # success @@ -102,24 +107,22 @@ def upload(): print(f"Attempt {i + 1} failed: {e!r}") errors.append(repr(e)) else: # no break in for loop - allErrors = "\n".join( - f"Attempt {index + 1} error: \n{e}" - for index, e in enumerate(errors) - ) + allErrors = "\n".join(f"Attempt {index + 1} error: \n{e}" for index, e in enumerate(errors)) raise RuntimeError(allErrors) if 200 <= r.status_code < 300: - print('Uploaded successfully!') + print("Uploaded successfully!") elif r.status_code < 400: - print('Error: bad auth token? (%d)' % r.status_code) + print("Error: bad auth token? (%d)" % r.status_code) raise RuntimeError else: - print('Error: %d' % r.status_code) + print("Error: %d" % r.status_code) print(r.text) raise RuntimeError return 0 -if __name__ == '__main__': + +if __name__ == "__main__": try: generate() upload() diff --git a/appx/sconscript b/appx/sconscript index 14e063d3190..7f8276daf1f 100644 --- a/appx/sconscript +++ b/appx/sconscript @@ -1,108 +1,118 @@ ### -#This file is a part of the NVDA project. -#URL: https://www.nvaccess.org/ -#Copyright 2018-2019 NV Access Limited -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: https://www.nvaccess.org/ +# Copyright 2018-2019 NV Access Limited +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### import subprocess import versionInfo import os -Import([ - 'env', - 'outFilePrefix', - 'isStoreSubmission', -]) +Import( + [ + "env", + "outFilePrefix", + "isStoreSubmission", + ] +) + def getCertPublisher(env): """ If no signing certificate is provided, then the given publisher is used as is. If a signing certificate is given, then the publisher is extracted from the certificate. """ - certFilePath = env.get('certFile') + certFilePath = env.get("certFile") if not certFilePath: - return env['publisher'] - certPassword=env.get('certPassword','') + return env["publisher"] + certPassword = env.get("certPassword", "") if not os.path.isabs(certFilePath): # If path is not absolute it is assumed that it is being given relative to the top dir of the repo - repoTopDir = Dir('#').abspath + repoTopDir = Dir("#").abspath certFilePath = os.path.abspath(os.path.normpath(os.path.join(repoTopDir, certFilePath))) - cmd=['certutil', '-dump', '-p', certPassword, certFilePath] - lines=subprocess.run(cmd,check=True,capture_output=True,text=True).stdout.splitlines() - linePrefix='Subject: ' + cmd = ["certutil", "-dump", "-p", certPassword, certFilePath] + lines = subprocess.run(cmd, check=True, capture_output=True, text=True).stdout.splitlines() + linePrefix = "Subject: " for line in lines: if line.startswith(linePrefix): - subject=line[len(linePrefix):].rstrip() + subject = line[len(linePrefix) :].rstrip() return subject -packageName="NVAccessLimited.NVDANonVisualDesktopAccess" -packageVersion="%s.%s.%s.%s"%(versionInfo.version_year,versionInfo.version_major,env['version_build'],0) + +packageName = "NVAccessLimited.NVDANonVisualDesktopAccess" +packageVersion = "%s.%s.%s.%s" % ( + versionInfo.version_year, + versionInfo.version_major, + env["version_build"], + 0, +) if isStoreSubmission: - packageFileName=outFilePrefix+"_storeSubmission.appx" + packageFileName = outFilePrefix + "_storeSubmission.appx" # NV Access Limited's Windows Store publisher ID # It is okay to be here as the only way to submit, validate and sign the package is via the NV Access store account. - packagePublisher="CN=83B1DA31-9B66-442C-88AB-77B4B815E1DE" - packagePublisherDisplayName="NV Access Limited" - productName="NVDA Screen Reader (Windows Store Edition)" -else: # not for submission, just side-loadable - packageFileName=outFilePrefix+"_sideLoadable.appx" - packagePublisher=getCertPublisher(env) - packagePublisherDisplayName=env['publisher'] - productName="NVDA Screen Reader (Windows Desktop Bridge Edition)" + packagePublisher = "CN=83B1DA31-9B66-442C-88AB-77B4B815E1DE" + packagePublisherDisplayName = "NV Access Limited" + productName = "NVDA Screen Reader (Windows Store Edition)" +else: # not for submission, just side-loadable + packageFileName = outFilePrefix + "_sideLoadable.appx" + packagePublisher = getCertPublisher(env) + packagePublisherDisplayName = env["publisher"] + productName = "NVDA Screen Reader (Windows Desktop Bridge Edition)" -signExec = env['signExec'] if (bool(env['certFile']) ^ bool(env['apiSigningToken'])) else None +signExec = env["signExec"] if (bool(env["certFile"]) ^ bool(env["apiSigningToken"])) else None # Files from NVDA's distribution that cannot be included in the appx due to policy or security restrictions excludedDistFiles = [ - 'nvda_slave.exe', - 'nvda_noUIAccess.exe', - 'lib/IAccessible2Proxy.dll', - 'lib/ISimpleDOM.dll', - 'lib/NVDAHelperRemote.dll', - 'lib64/', - 'libArm64/', - 'uninstall.exe', + "nvda_slave.exe", + "nvda_noUIAccess.exe", + "lib/IAccessible2Proxy.dll", + "lib/ISimpleDOM.dll", + "lib/NVDAHelperRemote.dll", + "lib64/", + "libArm64/", + "uninstall.exe", ] -# Create an appx manifest with version and publisher etc all filled in -manifest=env.Substfile( +# Create an appx manifest with version and publisher etc all filled in +manifest = env.Substfile( "AppxManifest.xml", - 'manifest.xml.subst', + "manifest.xml.subst", SUBST_DICT={ - '%packageName%':packageName, - '%packageVersion%':packageVersion, - '%packagePublisher%':packagePublisher, - '%publisher%':packagePublisherDisplayName, - '%productName%':productName, - '%description%':versionInfo.description, + "%packageName%": packageName, + "%packageVersion%": packageVersion, + "%packagePublisher%": packagePublisher, + "%publisher%": packagePublisherDisplayName, + "%productName%": productName, + "%description%": versionInfo.description, }, ) -# Make a copy of the dist dir produced by py2exe +# Make a copy of the dist dir produced by py2exe # And also place some extra appx specific images in there -appxContent=env.Command( - target='content', - source=[Dir("#dist"),Dir('#appx/appx_images'),manifest], +appxContent = env.Command( + target="content", + source=[Dir("#dist"), Dir("#appx/appx_images"), manifest], action=[ Delete("$TARGET"), - Copy("$TARGET","${SOURCES[0]}"), - Copy("${TARGET}\\appx_images","${SOURCES[1]}"), - Copy("${TARGET}\\AppxManifest.xml","${SOURCES[2]}"), - ]+[Delete("${TARGET}/%s"%excludeFile) for excludeFile in excludedDistFiles], + Copy("$TARGET", "${SOURCES[0]}"), + Copy("${TARGET}\\appx_images", "${SOURCES[1]}"), + Copy("${TARGET}\\AppxManifest.xml", "${SOURCES[2]}"), + ] + + [Delete("${TARGET}/%s" % excludeFile) for excludeFile in excludedDistFiles], ) -# Ensure that it is always copied as we can't tell if dist changed +# Ensure that it is always copied as we can't tell if dist changed env.AlwaysBuild(appxContent) # Package the appx -appx=env.Command(packageFileName,appxContent,"makeappx pack /p $TARGET /d $SOURCE") +appx = env.Command(packageFileName, appxContent, "makeappx pack /p $TARGET /d $SOURCE") if signExec and not isStoreSubmission: - env.AddPostAction(appx,signExec) + env.AddPostAction(appx, signExec) -Return(['appx']) +Return(["appx"]) diff --git a/cldrDict_sconscript b/cldrDict_sconscript index 192f24835f9..60f444e2bc0 100644 --- a/cldrDict_sconscript +++ b/cldrDict_sconscript @@ -5,9 +5,10 @@ import typing + if typing.TYPE_CHECKING: import SCons - from SCons import( + from SCons import ( Dir, Import, ) @@ -15,14 +16,11 @@ if typing.TYPE_CHECKING: sourceDir: "SCons.Node.FS.Dir" env: "SCons.Environment.Base" Import( - 'env', - 'sourceDir', + "env", + "sourceDir", ) -targetCldrDir = sourceDir.Dir('locale') +targetCldrDir = sourceDir.Dir("locale") cldrDataSource = Dir("include/nvda-cldr/locale") -env.RecursiveInstall( - targetCldrDir, - cldrDataSource.abspath -) +env.RecursiveInstall(targetCldrDir, cldrDataSource.abspath) diff --git a/extras/controllerClient/examples/example_python.py b/extras/controllerClient/examples/example_python.py index bd013ac02d1..b6abedaea71 100644 --- a/extras/controllerClient/examples/example_python.py +++ b/extras/controllerClient/examples/example_python.py @@ -31,19 +31,19 @@ def onMarkReached(name: str) -> int: ssml = ( - '' - 'This is one sentence. ' + "" + "This is one sentence. " '' 'This sentence is pronounced with higher pitch.' '' - 'This is a third sentence. ' + "This is a third sentence. " '' - 'This is a fourth sentence. We will stay silent for a second after this one.' + "This is a fourth sentence. We will stay silent for a second after this one." '' '' - 'This is a fifth sentence. ' + "This is a fifth sentence. " '' - '' + "" ) clientLib.nvdaController_setOnSsmlMarkReachedCallback(onMarkReached) clientLib.nvdaController_speakSsml(ssml, -1, 0, False) diff --git a/nvdaHelper/ISimpleDOM_sconscript b/nvdaHelper/ISimpleDOM_sconscript index 24eb36bbf82..cd0b858a0ea 100644 --- a/nvdaHelper/ISimpleDOM_sconscript +++ b/nvdaHelper/ISimpleDOM_sconscript @@ -1,54 +1,60 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright (C) 2014-2017 NV Access Limited. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright (C) 2014-2017 NV Access Limited. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import('env') +Import("env") -env['MIDLCOM']=env['MIDLCOM'][:-6] +env["MIDLCOM"] = env["MIDLCOM"][:-6] # Copy some secondary IDL files included by ISimpleDOMNode.idl idlDeps = [ - env.Command("ISimpleDOMText.idl","#/miscDeps/include/ISimpleDOM/ISimpleDOMText.idl",Copy("$TARGET","$SOURCE")), - env.Command("ISimpleDOMDocument.idl","#/miscDeps/include/ISimpleDOM/ISimpleDOMDocument.idl",Copy("$TARGET","$SOURCE")), + env.Command( + "ISimpleDOMText.idl", "#/miscDeps/include/ISimpleDOM/ISimpleDOMText.idl", Copy("$TARGET", "$SOURCE") + ), + env.Command( + "ISimpleDOMDocument.idl", + "#/miscDeps/include/ISimpleDOM/ISimpleDOMDocument.idl", + Copy("$TARGET", "$SOURCE"), + ), ] # copy ISimpleDOMNode.idl but changing imports of the secondary files to #includes # This is necessary as midl will not build secondary header files. this way the primary header file will contain all secondary header file content -idlFile=env.Substfile( +idlFile = env.Substfile( target="iSimpleDOMNode.idl", source="#/miscDeps/include/ISimpleDOM/ISimpleDOMNode.idl", SUBST_DICT={ - 'import "ISimpleDOM':'#include "ISimpleDOM', - } + 'import "ISimpleDOM': '#include "ISimpleDOM', + }, ) # SCons doesn't scan the file we just created, # so we must explicitly declare its dependencies. env.Depends(idlFile, idlDeps) -tlbFile,headerFile,iidSourceFile,proxySourceFile,dlldataSourceFile=env.TypeLibrary( +tlbFile, headerFile, iidSourceFile, proxySourceFile, dlldataSourceFile = env.TypeLibrary( source=idlFile, - MIDLFLAGS=[env['MIDLFLAGS'],'/c_ext','/I',Dir('.')], + MIDLFLAGS=[env["MIDLFLAGS"], "/c_ext", "/I", Dir(".")], ) # #7036: hack: Ignore midl.exe when deciding to rebuild, as its position in the dependencies # is different in the run before the idl files are copied versus subsequent runs. -midl=env.WhereIs(env["MIDL"]) -for target in (tlbFile,headerFile,iidSourceFile,proxySourceFile,dlldataSourceFile): - env.Ignore(target,midl) +midl = env.WhereIs(env["MIDL"]) +for target in (tlbFile, headerFile, iidSourceFile, proxySourceFile, dlldataSourceFile): + env.Ignore(target, midl) -proxyDll=env.COMProxyDll( - target='ISimpleDOM', - source=[iidSourceFile,proxySourceFile,dlldataSourceFile], +proxyDll = env.COMProxyDll( + target="ISimpleDOM", + source=[iidSourceFile, proxySourceFile, dlldataSourceFile], # This CLSID must be unique to this dll. A new one can be generated with import comtypes; comtypes.GUID.create_new() proxyClsid="{435E0FC9-344B-41D4-88DD-4CAAD499ACE5}", ) -Return(['proxyDll','tlbFile','headerFile','iidSourceFile','proxySourceFile','dlldataSourceFile']) +Return(["proxyDll", "tlbFile", "headerFile", "iidSourceFile", "proxySourceFile", "dlldataSourceFile"]) diff --git a/nvdaHelper/UIARemote/sconscript b/nvdaHelper/UIARemote/sconscript index 0e9bff69d68..13d8b824f99 100644 --- a/nvdaHelper/UIARemote/sconscript +++ b/nvdaHelper/UIARemote/sconscript @@ -1,26 +1,28 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2021 NV Access Limited. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2021 NV Access Limited. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import([ - 'env', - 'localLib', -]) +Import( + [ + "env", + "localLib", + ] +) -UIARemoteLib=env.SharedLibrary( +UIARemoteLib = env.SharedLibrary( target="UIARemote", source=[ - env['projectResFile'], + env["projectResFile"], "lowLevel.cpp", ], LIBS=[ @@ -31,4 +33,4 @@ UIARemoteLib=env.SharedLibrary( ], ) -Return('UIARemoteLib') +Return("UIARemoteLib") diff --git a/nvdaHelper/acrobatAccess_sconscript b/nvdaHelper/acrobatAccess_sconscript index ea615704c55..1e7d0c00d78 100644 --- a/nvdaHelper/acrobatAccess_sconscript +++ b/nvdaHelper/acrobatAccess_sconscript @@ -1,22 +1,23 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import('env') +Import("env") -idlFile=env.Command("acrobatAccess.idl","#/miscDeps/include/acrobatAccess/acrobatAccess.idl",Copy("$TARGET","$SOURCE")) +idlFile = env.Command( + "acrobatAccess.idl", "#/miscDeps/include/acrobatAccess/acrobatAccess.idl", Copy("$TARGET", "$SOURCE") +) -tlbFile,headerFile,iidSourceFile,proxySourceFile,dlldataSourceFile=env.TypeLibrary(source=idlFile) - -Return(['tlbFile','headerFile','iidSourceFile']) +tlbFile, headerFile, iidSourceFile, proxySourceFile, dlldataSourceFile = env.TypeLibrary(source=idlFile) +Return(["tlbFile", "headerFile", "iidSourceFile"]) diff --git a/nvdaHelper/archBuild_sconscript b/nvdaHelper/archBuild_sconscript index ff81939c7b6..6877b28425e 100644 --- a/nvdaHelper/archBuild_sconscript +++ b/nvdaHelper/archBuild_sconscript @@ -5,228 +5,238 @@ Import( - 'env', - 'sourceDir', - 'sourceTypelibDir', - 'libInstallDir', - 'clientInstallDir', + "env", + "sourceDir", + "sourceTypelibDir", + "libInstallDir", + "clientInstallDir", ) + # some utilities for COM proxies def clsidStringToCLSIDDefine(clsidString): """ Converts a CLSID string of the form "{abcdef12-abcd-abcd-abcd-abcdef123456}" - Into a c-style struct initializer for initializing a GUID (I.e. "{0xabcdef12,0xabcd,0xabcd,{0xab,0xcd,0xab,0xcd,0xef,0x12,0x34,0x56}}") + Into a c-style struct initializer for initializing a GUID (I.e. "{0xabcdef12,0xabcd,0xabcd,{0xab,0xcd,0xab,0xcd,0xef,0x12,0x34,0x56}}") """ - d=clsidString[1:-1].replace('-','') - return "{%s,%s,%s,%s}"%( - "0x"+d[0:8], - "0x"+d[8:12], - "0x"+d[12:16], - "{%s}"%(",".join("0x"+d[x:x+2] for x in range(16,32,2))) + d = clsidString[1:-1].replace("-", "") + return "{%s,%s,%s,%s}" % ( + "0x" + d[0:8], + "0x" + d[8:12], + "0x" + d[12:16], + "{%s}" % (",".join("0x" + d[x : x + 2] for x in range(16, 32, 2))), ) -def COMProxyDllBuilder(env,target,source,proxyClsid): + +def COMProxyDllBuilder(env, target, source, proxyClsid): """ Builds a COM proxy dll from iid, proxy and dlldata c files generated from an IDL file with MIDL. It provides the needed linker flags, and also embeds a manifest in the dll registering the given proxy CLSID for this dll's class object. """ - proxyName=str(target) - manifestFile=env.Substfile( - target=proxyName+'.manifest', - source='COMProxy.manifest.subst', + proxyName = str(target) + manifestFile = env.Substfile( + target=proxyName + ".manifest", + source="COMProxy.manifest.subst", SUBST_DICT={ - '%proxyClsid%':proxyClsid, - '%proxyName%':proxyName, - } + "%proxyClsid%": proxyClsid, + "%proxyName%": proxyName, + }, ) - proxyDll=env.SharedLibrary( + proxyDll = env.SharedLibrary( target=target, source=source, - LIBS=['rpcrt4','oleaut32','ole32'], - CPPDEFINES=list(env['CPPDEFINES']) + [ - 'WIN32', - ('PROXY_CLSID_IS',clsidStringToCLSIDDefine(proxyClsid)), + LIBS=["rpcrt4", "oleaut32", "ole32"], + CPPDEFINES=list(env["CPPDEFINES"]) + + [ + "WIN32", + ("PROXY_CLSID_IS", clsidStringToCLSIDDefine(proxyClsid)), ], LINKFLAGS=[ - env['LINKFLAGS'], - '/export:DllGetClassObject,private', - '/export:DllCanUnloadNow,private', - '/export:GetProxyDllInfo,private', - '/manifest:embed', - '/manifestinput:'+manifestFile[0].path, + env["LINKFLAGS"], + "/export:DllGetClassObject,private", + "/export:DllCanUnloadNow,private", + "/export:GetProxyDllInfo,private", + "/manifest:embed", + "/manifestinput:" + manifestFile[0].path, ], ) - env.Depends(proxyDll,manifestFile) + env.Depends(proxyDll, manifestFile) return proxyDll -env.AddMethod(COMProxyDllBuilder,'COMProxyDll') + + +env.AddMethod(COMProxyDllBuilder, "COMProxyDll") # We only support compiling with MSVC 14.2 (2019) or newer -if not env.get('MSVC_VERSION') or tuple(map(int, env.get('MSVC_VERSION').split("."))) < (14, 2): +if not env.get("MSVC_VERSION") or tuple(map(int, env.get("MSVC_VERSION").split("."))) < (14, 2): raise RuntimeError("Visual C++ 14.2 (Visual Studio 2019) or newer not found") -TARGET_ARCH=env['TARGET_ARCH'] -debug=env['nvdaHelperDebugFlags'] -release=env['release'] -signExec = env['signExec'] if (bool(env['certFile']) ^ bool(env['apiSigningToken'])) else None +TARGET_ARCH = env["TARGET_ARCH"] +debug = env["nvdaHelperDebugFlags"] +release = env["release"] +signExec = env["signExec"] if (bool(env["certFile"]) ^ bool(env["apiSigningToken"])) else None -#Some defines and includes for the environment +# Some defines and includes for the environment env.Append( CPPDEFINES=[ - 'UNICODE', - '_CRT_SECURE_NO_DEPRECATE', - ('LOGLEVEL', '${nvdaHelperLogLevel}'), - ('_WIN32_WINNT', '_WIN32_WINNT_WINBLUE'), + "UNICODE", + "_CRT_SECURE_NO_DEPRECATE", + ("LOGLEVEL", "${nvdaHelperLogLevel}"), + ("_WIN32_WINNT", "_WIN32_WINNT_WINBLUE"), # NOMINMAX: prevent minwindef.h min/max macro definition, which unexpectedly override developer # expectations - 'NOMINMAX', + "NOMINMAX", ] ) -env.Append(CXXFLAGS=['/EHsc']) +env.Append(CXXFLAGS=["/EHsc"]) -env.Append(CPPPATH=[ - '#/include', - '#/include/wil/include', - '#/miscDeps/include', - Dir('.').abspath -]) +env.Append(CPPPATH=["#/include", "#/include/wil/include", "#/miscDeps/include", Dir(".").abspath]) # Windows 8.1 (blue) subsystem = "/subsystem:windows,6.03" env.Append( LINKFLAGS=[ - '/incremental:no', - '/WX', + "/incremental:no", + "/WX", subsystem, ] ) -env.Append(LINKFLAGS='/release') #We always want a checksum in the header -if TARGET_ARCH == 'x86_64': - env.Append(MIDLFLAGS='/x64') -elif TARGET_ARCH == 'arm64': - env.Append(MIDLFLAGS='/arm64') +env.Append(LINKFLAGS="/release") # We always want a checksum in the header +if TARGET_ARCH == "x86_64": + env.Append(MIDLFLAGS="/x64") +elif TARGET_ARCH == "arm64": + env.Append(MIDLFLAGS="/arm64") else: - env.Append(MIDLFLAGS='/win32') + env.Append(MIDLFLAGS="/win32") -if not release: - env.Append(CCFLAGS=['/Od']) +if not release: + env.Append(CCFLAGS=["/Od"]) else: - env.Append(CCFLAGS='/O2') - env.Append(CCFLAGS='/GL') - env.Append(LINKFLAGS=['/LTCG']) + env.Append(CCFLAGS="/O2") + env.Append(CCFLAGS="/GL") + env.Append(LINKFLAGS=["/LTCG"]) -if 'debugCRT' not in debug: - env.Append(CPPDEFINES='NDEBUG') +if "debugCRT" not in debug: + env.Append(CPPDEFINES="NDEBUG") -if 'RTC' in debug: - env.Append(CCFLAGS=['/RTCsu']) +if "RTC" in debug: + env.Append(CCFLAGS=["/RTCsu"]) -#We always want debug symbols -env.Append(PDB='${TARGET}.pdb') -env.Append(LINKFLAGS='/OPT:REF') #having symbols usually turns this off but we have no need for unused symbols +# We always want debug symbols +env.Append(PDB="${TARGET}.pdb") +env.Append( + LINKFLAGS="/OPT:REF" +) # having symbols usually turns this off but we have no need for unused symbols -env.Append(CCFLAGS=[ - '/std:c++20', - '/permissive-', - # '/showIncludes': Useful to understand which file causes some other file to be included. - # It will output a list of the include files. - # The option also displays nested include files, that is, the files - # included by the files that you include. -]) +env.Append( + CCFLAGS=[ + "/std:c++20", + "/permissive-", + # '/showIncludes': Useful to understand which file causes some other file to be included. + # It will output a list of the include files. + # The option also displays nested include files, that is, the files + # included by the files that you include. + ] +) -if 'debugCRT' in debug: - env.Append(CCFLAGS=['/MTd']) +if "debugCRT" in debug: + env.Append(CCFLAGS=["/MTd"]) else: - env.Append(CCFLAGS=['/MT']) + env.Append(CCFLAGS=["/MT"]) # Don't enable warnings and warnings as errors or analysis to 3rd party code. thirdPartyEnv = env.Clone() -env.Append(CCFLAGS=[ - '/W3', # warning level 3 -]) -if 'analyze' in debug: - env.Append(CCFLAGS=['/analyze']) +env.Append( + CCFLAGS=[ + "/W3", # warning level 3 + ] +) +if "analyze" in debug: + env.Append(CCFLAGS=["/analyze"]) # Disable: Inconsistent annotation for 'x': this instance has no annotations. # Seems all MIDL-generated code from idl files don't add annotations - env.Append(CCFLAGS='/wd28251') + env.Append(CCFLAGS="/wd28251") # Disable: 'x': unreferenced formal parameter # We use a great deal of hook functions where we have no need for various parameters - env.Append(CCFLAGS='/wd4100') + env.Append(CCFLAGS="/wd4100") else: - env.Append(CCFLAGS=[ - '/WX', # warnings as error, don't do this with analyze, the build stops too early - ]) + env.Append( + CCFLAGS=[ + "/WX", # warnings as error, don't do this with analyze, the build stops too early + ] + ) -Export('thirdPartyEnv') -Export('env') +Export("thirdPartyEnv") +Export("env") -acrobatAccessRPCStubs=env.SConscript('acrobatAccess_sconscript') -Export('acrobatAccessRPCStubs') -if TARGET_ARCH=='x86': - env.Install(sourceTypelibDir,acrobatAccessRPCStubs[0]) #typelib +acrobatAccessRPCStubs = env.SConscript("acrobatAccess_sconscript") +Export("acrobatAccessRPCStubs") +if TARGET_ARCH == "x86": + env.Install(sourceTypelibDir, acrobatAccessRPCStubs[0]) # typelib -ia2RPCStubs=env.SConscript('ia2_sconscript') -Export('ia2RPCStubs') +ia2RPCStubs = env.SConscript("ia2_sconscript") +Export("ia2RPCStubs") if signExec: - env.AddPostAction(ia2RPCStubs[0],[signExec]) -env.Install(libInstallDir,ia2RPCStubs[0]) #proxy dll -if TARGET_ARCH=='x86': - env.Install(sourceTypelibDir,ia2RPCStubs[1]) #typelib + env.AddPostAction(ia2RPCStubs[0], [signExec]) +env.Install(libInstallDir, ia2RPCStubs[0]) # proxy dll +if TARGET_ARCH == "x86": + env.Install(sourceTypelibDir, ia2RPCStubs[1]) # typelib -iSimpleDomRPCStubs=env.SConscript('ISimpleDOM_sconscript') +iSimpleDomRPCStubs = env.SConscript("ISimpleDOM_sconscript") if signExec: - env.AddPostAction(iSimpleDomRPCStubs[0],[signExec]) -env.Install(libInstallDir,iSimpleDomRPCStubs[0]) #proxy dll -if TARGET_ARCH=='x86': - env.Install(sourceTypelibDir,iSimpleDomRPCStubs[1]) #typelib + env.AddPostAction(iSimpleDomRPCStubs[0], [signExec]) +env.Install(libInstallDir, iSimpleDomRPCStubs[0]) # proxy dll +if TARGET_ARCH == "x86": + env.Install(sourceTypelibDir, iSimpleDomRPCStubs[1]) # typelib -mathPlayerRPCStubs=env.SConscript('mathPlayer_sconscript') -if TARGET_ARCH=='x86': - env.Install(sourceTypelibDir,mathPlayerRPCStubs[0]) #typelib +mathPlayerRPCStubs = env.SConscript("mathPlayer_sconscript") +if TARGET_ARCH == "x86": + env.Install(sourceTypelibDir, mathPlayerRPCStubs[0]) # typelib -detoursLib = env.SConscript('detours/sconscript') -Export('detoursLib') +detoursLib = env.SConscript("detours/sconscript") +Export("detoursLib") -apiHookObj = env.Object("apiHook","common/apiHook.cpp") -Export('apiHookObj') +apiHookObj = env.Object("apiHook", "common/apiHook.cpp") +Export("apiHookObj") -if TARGET_ARCH=='x86': - localLib=env.SConscript('local/sconscript') - Export('localLib') +if TARGET_ARCH == "x86": + localLib = env.SConscript("local/sconscript") + Export("localLib") if signExec: - env.AddPostAction(localLib[0],[signExec]) - env.Install(libInstallDir,localLib) - win10localLib=env.SConscript('localWin10/sconscript',) + env.AddPostAction(localLib[0], [signExec]) + env.Install(libInstallDir, localLib) + win10localLib = env.SConscript( + "localWin10/sconscript", + ) if signExec: - env.AddPostAction(win10localLib[0],[signExec]) - env.Install(libInstallDir,win10localLib) - UIARemoteLib=env.SConscript('UIARemote/sconscript') + env.AddPostAction(win10localLib[0], [signExec]) + env.Install(libInstallDir, win10localLib) + UIARemoteLib = env.SConscript("UIARemote/sconscript") if signExec: - env.AddPostAction(UIARemoteLib[0],[signExec]) - env.Install(libInstallDir,UIARemoteLib) + env.AddPostAction(UIARemoteLib[0], [signExec]) + env.Install(libInstallDir, UIARemoteLib) -clientLib=env.SConscript('client/sconscript') -Export('clientLib') +clientLib = env.SConscript("client/sconscript") +Export("clientLib") if signExec: - env.AddPostAction(clientLib[0],[signExec]) -env.Install(clientInstallDir,clientLib) + env.AddPostAction(clientLib[0], [signExec]) +env.Install(clientInstallDir, clientLib) -remoteLib=env.SConscript('remote/sconscript') -Export('remoteLib') +remoteLib = env.SConscript("remote/sconscript") +Export("remoteLib") if signExec: - env.AddPostAction(remoteLib[0],[signExec]) -env.Install(libInstallDir,remoteLib) + env.AddPostAction(remoteLib[0], [signExec]) +env.Install(libInstallDir, remoteLib) -if TARGET_ARCH in ('x86_64', 'arm64'): - remoteLoaderProgram=env.SConscript('remoteLoader/sconscript') +if TARGET_ARCH in ("x86_64", "arm64"): + remoteLoaderProgram = env.SConscript("remoteLoader/sconscript") if signExec: - env.AddPostAction(remoteLoaderProgram,[signExec]) - env.Install(libInstallDir,remoteLoaderProgram) + env.AddPostAction(remoteLoaderProgram, [signExec]) + env.Install(libInstallDir, remoteLoaderProgram) -if TARGET_ARCH=='x86': - thirdPartyEnv.SConscript('espeak/sconscript') - thirdPartyEnv.SConscript('liblouis/sconscript') +if TARGET_ARCH == "x86": + thirdPartyEnv.SConscript("espeak/sconscript") + thirdPartyEnv.SConscript("liblouis/sconscript") diff --git a/nvdaHelper/client/sconscript b/nvdaHelper/client/sconscript index 5a867c5b21b..80aebba435e 100644 --- a/nvdaHelper/client/sconscript +++ b/nvdaHelper/client/sconscript @@ -1,24 +1,26 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU Lesser General Public License version 2.1, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License version 2.1, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html ### -Import([ - 'env', -]) +Import( + [ + "env", + ] +) -winIPCUtilsObj=env.Object("./winIPCUtils","../common/winIPCUtils.cpp") +winIPCUtilsObj = env.Object("./winIPCUtils", "../common/winIPCUtils.cpp") -controllerRPCHeader,controllerRPCClientSource=env.MSRPCStubs( +controllerRPCHeader, controllerRPCClientSource = env.MSRPCStubs( target="./nvdaController", source=[ "../interfaces/nvdaController/nvdaController.idl", @@ -30,14 +32,14 @@ controllerRPCHeader,controllerRPCClientSource=env.MSRPCStubs( clientLibName = "nvdaControllerClient" -clientLib=env.SharedLibrary( +clientLib = env.SharedLibrary( target=clientLibName, source=[ - env['projectResFile'], + env["projectResFile"], "client.cpp", winIPCUtilsObj, controllerRPCClientSource, - 'nvdaControllerClient.def', + "nvdaControllerClient.def", ], LIBS=[ "user32", @@ -45,4 +47,4 @@ clientLib=env.SharedLibrary( ], ) -Return(['clientLib','controllerRPCHeader']) +Return(["clientLib", "controllerRPCHeader"]) diff --git a/nvdaHelper/detours/sconscript b/nvdaHelper/detours/sconscript index 71f6acfa03f..fde5021feab 100644 --- a/nvdaHelper/detours/sconscript +++ b/nvdaHelper/detours/sconscript @@ -1,28 +1,23 @@ -Import([ - "thirdPartyEnv" -]) +Import(["thirdPartyEnv"]) import typing # noqa: E402 thirdPartyEnv: Environment = thirdPartyEnv env: Environment = typing.cast(Environment, thirdPartyEnv.Clone()) -detoursPath=Dir('#include/detours') -detoursSrcPath = detoursPath.Dir('src') +detoursPath = Dir("#include/detours") +detoursSrcPath = detoursPath.Dir("src") env.Prepend(CPPPATH=[detoursSrcPath]) -sourceFiles=[ - 'detours.cpp', - 'disasm.cpp', - 'modules.cpp', +sourceFiles = [ + "detours.cpp", + "disasm.cpp", + "modules.cpp", ] objs = [env.Object(f"{f}.obj", detoursSrcPath.File(f)) for f in sourceFiles] -detoursLib=env.Library( - target='detours', - source=objs -) +detoursLib = env.Library(target="detours", source=objs) -Return('detoursLib') +Return("detoursLib") diff --git a/nvdaHelper/espeak/sconscript b/nvdaHelper/espeak/sconscript index 5ad0a97238a..b6899349dad 100644 --- a/nvdaHelper/espeak/sconscript +++ b/nvdaHelper/espeak/sconscript @@ -10,20 +10,25 @@ from glob import glob sourceDir: SCons.Node.FS.Dir thirdPartyEnv: SCons.Environment.Environment -Import([ - 'thirdPartyEnv', - 'sourceDir', -]) +Import( + [ + "thirdPartyEnv", + "sourceDir", + ] +) + class AutoFreeCDLL(ctypes.CDLL): def __del__(self): ctypes.windll.kernel32.FreeLibrary(self._handle) -synthDriversDir=sourceDir.Dir('synthDrivers') -espeakRepo=Dir("#include/espeak") -espeakSrcDir=espeakRepo.Dir('src') -espeakIncludeDir=espeakSrcDir.Dir('include') -sonicSrcDir=Dir("#include/sonic") + +synthDriversDir = sourceDir.Dir("synthDrivers") +espeakRepo = Dir("#include/espeak") +espeakSrcDir = espeakRepo.Dir("src") +espeakIncludeDir = espeakSrcDir.Dir("include") +sonicSrcDir = Dir("#include/sonic") + class espeak_ERROR(enum.IntEnum): EE_OK = 0 @@ -58,23 +63,24 @@ class espeak_ng_STATUS(enum.IntFlag): ENS_UNKNOWN_PHONEME_FEATURE = 0x10000FFF ENS_UNKNOWN_TEXT_ENCODING = 0x100010FF + class espeak_VOICE(ctypes.Structure): - _fields_=[ - ('name',ctypes.c_char_p), - ('languages',ctypes.c_char_p), - ('identifier',ctypes.c_char_p), - ('gender',ctypes.c_byte), - ('age',ctypes.c_byte), - ('variant',ctypes.c_byte), - ('xx1',ctypes.c_byte), - ('score',ctypes.c_int), - ('spare',ctypes.c_void_p), + _fields_ = [ + ("name", ctypes.c_char_p), + ("languages", ctypes.c_char_p), + ("identifier", ctypes.c_char_p), + ("gender", ctypes.c_byte), + ("age", ctypes.c_byte), + ("variant", ctypes.c_byte), + ("xx1", ctypes.c_byte), + ("score", ctypes.c_int), + ("spare", ctypes.c_void_p), ] class espeak_AUDIO_OUTPUT(enum.IntEnum): - """From '/espeak-ng/speak_lib.h' - """ + """From '/espeak-ng/speak_lib.h'""" + #: PLAYBACK mode: plays the audio data, supplies events to the calling program AUDIO_OUTPUT_PLAYBACK = 0 #: RETRIEVAL mode: supplies audio data and events to the calling program @@ -84,56 +90,68 @@ class espeak_AUDIO_OUTPUT(enum.IntEnum): #: Synchronous playback AUDIO_OUTPUT_SYNCH_PLAYBACK = 3 + env: SCons.Environment.Environment = thirdPartyEnv.Clone() env.Append( CCFLAGS=[ # Whole-program optimization causes eSpeak to distort and warble with its Klatt4 voice # Therefore specifically force it off - '/GL-', + "/GL-", # Ignore all warnings as the code is not ours. - '/W0', + "/W0", # Preprocessor definitions. Migrated from 'nvdaHelper/espeak/config.h' '/DPACKAGE_VERSION=\\"1.52-dev 54ee11a7\\"', # See 'include/espeak/src/windows/config.h' - '/DHAVE_STDINT_H=1', - '/D__WIN32__#1', - '/DLIBESPEAK_NG_EXPORT', + "/DHAVE_STDINT_H=1", + "/D__WIN32__#1", + "/DLIBESPEAK_NG_EXPORT", # Define WIN32_LEAN_AND_MEAN for preprocessor to prevent windows.h including winsock causing redefinition # errors when winsock2 is included by espeak\src\include\compat\endian.h - '/DWIN32_LEAN_AND_MEAN', + "/DWIN32_LEAN_AND_MEAN", # Preprocessor definitions. Espeak Features - '/DUSE_SPEECHPLAYER=1', - '/DUSE_KLATT=1', - '/DUSE_LIBSONIC=1', - ]) + "/DUSE_SPEECHPLAYER=1", + "/DUSE_KLATT=1", + "/DUSE_LIBSONIC=1", + ] +) env.Append( CPPPATH=[ - '#nvdaHelper/espeak', # ensure that nvdaHelper/espeak/config.h is found first. + "#nvdaHelper/espeak", # ensure that nvdaHelper/espeak/config.h is found first. espeakIncludeDir, - espeakIncludeDir.Dir('compat'), - espeakSrcDir.Dir('speechPlayer/include'), + espeakIncludeDir.Dir("compat"), + espeakSrcDir.Dir("speechPlayer/include"), sonicSrcDir, - espeakSrcDir.Dir('ucd-tools/src/include') - ]) - -def espeak_compilePhonemeData_buildEmitter(target,source,env): - phSourceIgnores=['error_log','error_intonation','compile_prog_log','compile_report','envelopes.png'] - phSources=env.Flatten([[Dir(topDir).File(f) for f in files if f not in phSourceIgnores] for topDir,subdirs,files in os.walk(source[0].abspath)]) - sources=env.Flatten([phSources]) - targets=[target[0].File(f) for f in ['intonations','phondata','phondata-manifest','phonindex','phontab']] - phSideEffects=[source[0].File(x) for x in phSourceIgnores] - env.SideEffect(phSideEffects,targets) - return targets,sources - -def espeak_compilePhonemeData_buildAction(target,source,env): + espeakSrcDir.Dir("ucd-tools/src/include"), + ] +) + + +def espeak_compilePhonemeData_buildEmitter(target, source, env): + phSourceIgnores = ["error_log", "error_intonation", "compile_prog_log", "compile_report", "envelopes.png"] + phSources = env.Flatten( + [ + [Dir(topDir).File(f) for f in files if f not in phSourceIgnores] + for topDir, subdirs, files in os.walk(source[0].abspath) + ] + ) + sources = env.Flatten([phSources]) + targets = [ + target[0].File(f) for f in ["intonations", "phondata", "phondata-manifest", "phonindex", "phontab"] + ] + phSideEffects = [source[0].File(x) for x in phSourceIgnores] + env.SideEffect(phSideEffects, targets) + return targets, sources + + +def espeak_compilePhonemeData_buildAction(target, source, env): # We want the eSpeak dll to be freed after each dictionary. # This is because it writes to stderr but doesn't flush it. # Unfortunately, there's no way we can flush it or use a different stream # because our eSpeak statically links the CRT. - espeak=AutoFreeCDLL(espeakLib[0].abspath) + espeak = AutoFreeCDLL(espeakLib[0].abspath) espeak.espeak_ng_InitializePath(os.fsencode(espeakRepo.abspath)) - espeak.espeak_ng_CompileIntonation(None,None) - espeak.espeak_ng_CompilePhonemeData(22050,None,None) + espeak.espeak_ng_CompileIntonation(None, None) + espeak.espeak_ng_CompilePhonemeData(22050, None, None) espeak.espeak_Terminate() @@ -143,7 +161,7 @@ def removeEmoji(): Currently many of these simply crash eSpeak at runtime. Also, our own emoji processing using CLDR data is preferred. """ - emojiGlob = os.path.join(espeakRepo.abspath, 'dictsource', '*_emoji') + emojiGlob = os.path.join(espeakRepo.abspath, "dictsource", "*_emoji") for f in glob(emojiGlob): print(f"Removing emoji file: {f}") os.remove(f) @@ -156,146 +174,780 @@ def cleanFiles_preBuildAction(target, source, env): - dictionary artifacts listed in CLEANFILES """ removeEmoji() - # refer to CLEANFILES in include\espeak\Makefile.am + # refer to CLEANFILES in include\espeak\Makefile.am for f in ( - # These files are created when we moved them from espeak/dictsource/extra/*_*. - os.path.join(espeakRepo.abspath, "dictsource", "ru_listx"), - os.path.join(espeakRepo.abspath, "dictsource", "cmn_listx"), - os.path.join(espeakRepo.abspath, "dictsource", "yue_listx"), - ): + # These files are created when we moved them from espeak/dictsource/extra/*_*. + os.path.join(espeakRepo.abspath, "dictsource", "ru_listx"), + os.path.join(espeakRepo.abspath, "dictsource", "cmn_listx"), + os.path.join(espeakRepo.abspath, "dictsource", "yue_listx"), + ): if os.path.exists(f): print(f"Removing listx file: {f}") os.remove(f) -env['BUILDERS']['espeak_compilePhonemeData']=Builder(action=env.Action(espeak_compilePhonemeData_buildAction,"Compiling phoneme data"),emitter=espeak_compilePhonemeData_buildEmitter) +env["BUILDERS"]["espeak_compilePhonemeData"] = Builder( + action=env.Action(espeak_compilePhonemeData_buildAction, "Compiling phoneme data"), + emitter=espeak_compilePhonemeData_buildEmitter, +) #: See dictionaries section of /include/espeak/Makefile.am espeakDictionaryCompileList: typing.Dict[ - str, # expected dict file name EG 'es_dict' - typing.Tuple[str, typing.List[str]] # language code, list of input files + str, # expected dict file name EG 'es_dict' + typing.Tuple[str, typing.List[str]], # language code, list of input files ] = { - "af_dict": ("af", ["af_list", "af_rules", ]), - "am_dict": ("am", ["am_list", "am_rules", ]), - "an_dict": ("an", ["an_list", "an_rules", ]), + "af_dict": ( + "af", + [ + "af_list", + "af_rules", + ], + ), + "am_dict": ( + "am", + [ + "am_list", + "am_rules", + ], + ), + "an_dict": ( + "an", + [ + "an_list", + "an_rules", + ], + ), "ar_dict": ("ar", ["ar_listx", "ar_list", "ar_rules"]), - "as_dict": ("as", ["as_list", "as_rules", ]), - "az_dict": ("az", ["az_list", "az_rules", ]), - "ba_dict": ("ba", ["ba_list", "ba_rules", ]), - "be_dict": ("be", ["be_list", "be_rules", ]), + "as_dict": ( + "as", + [ + "as_list", + "as_rules", + ], + ), + "az_dict": ( + "az", + [ + "az_list", + "az_rules", + ], + ), + "ba_dict": ( + "ba", + [ + "ba_list", + "ba_rules", + ], + ), + "be_dict": ( + "be", + [ + "be_list", + "be_rules", + ], + ), "bg_dict": ("bg", ["bg_listx", "bg_list", "bg_rules"]), - "bn_dict": ("bn", ["bn_list", "bn_rules", ]), - "bpy_dict": ("bpy", ["bpy_list", "bpy_rules", ]), - "bs_dict": ("bs", ["bs_list", "bs_rules", ]), - "ca_dict": ("ca", ["ca_list", "ca_rules", ]), - "chr_dict": ("chr", ["chr_list", "chr_rules", ]), + "bn_dict": ( + "bn", + [ + "bn_list", + "bn_rules", + ], + ), + "bpy_dict": ( + "bpy", + [ + "bpy_list", + "bpy_rules", + ], + ), + "bs_dict": ( + "bs", + [ + "bs_list", + "bs_rules", + ], + ), + "ca_dict": ( + "ca", + [ + "ca_list", + "ca_rules", + ], + ), + "chr_dict": ( + "chr", + [ + "chr_list", + "chr_rules", + ], + ), "cmn_dict": ("cmn", ["cmn_listx", "cmn_list", "cmn_rules"]), - "cs_dict": ("cs", ["cs_list", "cs_rules", ]), - "cv_dict": ("cv", ["cv_list", "cv_rules", ]), - "cy_dict": ("cy", ["cy_list", "cy_rules", ]), - "da_dict": ("da", ["da_list", "da_rules", ]), - "de_dict": ("de", ["de_list", "de_rules", ]), - "el_dict": ("el", ["el_list", "el_rules", ]), - "en_dict": ("en", ["en_list", "en_rules", ]), - "eo_dict": ("eo", ["eo_list", "eo_rules", ]), - "es_dict": ("es", ["es_list", "es_rules", ]), - "et_dict": ("et", ["et_list", "et_rules", ]), - "eu_dict": ("eu", ["eu_list", "eu_rules", ]), - "fa_dict": ("fa", ["fa_list", "fa_rules", ]), - "fi_dict": ("fi", ["fi_list", "fi_rules", ]), - "fr_dict": ("fr", ["fr_list", "fr_rules", ]), - "ga_dict": ("ga", ["ga_list", "ga_rules", ]), - "gd_dict": ("gd", ["gd_list", "gd_rules", ]), - "gn_dict": ("gn", ["gn_list", "gn_rules", ]), - "grc_dict": ("grc", ["grc_list", "grc_rules", ]), - "gu_dict": ("gu", ["gu_list", "gu_rules", ]), - "hak_dict": ("hak", ["hak_list", "hak_rules", ]), - "haw_dict": ("haw", ["haw_list", "haw_rules", ]), + "cs_dict": ( + "cs", + [ + "cs_list", + "cs_rules", + ], + ), + "cv_dict": ( + "cv", + [ + "cv_list", + "cv_rules", + ], + ), + "cy_dict": ( + "cy", + [ + "cy_list", + "cy_rules", + ], + ), + "da_dict": ( + "da", + [ + "da_list", + "da_rules", + ], + ), + "de_dict": ( + "de", + [ + "de_list", + "de_rules", + ], + ), + "el_dict": ( + "el", + [ + "el_list", + "el_rules", + ], + ), + "en_dict": ( + "en", + [ + "en_list", + "en_rules", + ], + ), + "eo_dict": ( + "eo", + [ + "eo_list", + "eo_rules", + ], + ), + "es_dict": ( + "es", + [ + "es_list", + "es_rules", + ], + ), + "et_dict": ( + "et", + [ + "et_list", + "et_rules", + ], + ), + "eu_dict": ( + "eu", + [ + "eu_list", + "eu_rules", + ], + ), + "fa_dict": ( + "fa", + [ + "fa_list", + "fa_rules", + ], + ), + "fi_dict": ( + "fi", + [ + "fi_list", + "fi_rules", + ], + ), + "fr_dict": ( + "fr", + [ + "fr_list", + "fr_rules", + ], + ), + "ga_dict": ( + "ga", + [ + "ga_list", + "ga_rules", + ], + ), + "gd_dict": ( + "gd", + [ + "gd_list", + "gd_rules", + ], + ), + "gn_dict": ( + "gn", + [ + "gn_list", + "gn_rules", + ], + ), + "grc_dict": ( + "grc", + [ + "grc_list", + "grc_rules", + ], + ), + "gu_dict": ( + "gu", + [ + "gu_list", + "gu_rules", + ], + ), + "hak_dict": ( + "hak", + [ + "hak_list", + "hak_rules", + ], + ), + "haw_dict": ( + "haw", + [ + "haw_list", + "haw_rules", + ], + ), "he_dict": ("he", ["he_listx", "he_list", "he_rules"]), - "hi_dict": ("hi", ["hi_list", "hi_rules", ]), - "hr_dict": ("hr", ["hr_list", "hr_rules", ]), - "ht_dict": ("ht", ["ht_list", "ht_rules", ]), - "hu_dict": ("hu", ["hu_list", "hu_rules", ]), - "hy_dict": ("hy", ["hy_list", "hy_rules", ]), + "hi_dict": ( + "hi", + [ + "hi_list", + "hi_rules", + ], + ), + "hr_dict": ( + "hr", + [ + "hr_list", + "hr_rules", + ], + ), + "ht_dict": ( + "ht", + [ + "ht_list", + "ht_rules", + ], + ), + "hu_dict": ( + "hu", + [ + "hu_list", + "hu_rules", + ], + ), + "hy_dict": ( + "hy", + [ + "hy_list", + "hy_rules", + ], + ), "ia_dict": ("ia", ["ia_listx", "ia_list", "ia_rules"]), - "id_dict": ("id", ["id_list", "id_rules", ]), - "io_dict": ("io", ["io_list", "io_rules", ]), - "is_dict": ("is", ["is_list", "is_rules", ]), + "id_dict": ( + "id", + [ + "id_list", + "id_rules", + ], + ), + "io_dict": ( + "io", + [ + "io_list", + "io_rules", + ], + ), + "is_dict": ( + "is", + [ + "is_list", + "is_rules", + ], + ), "it_dict": ("it", ["it_listx", "it_list", "it_rules"]), - "ja_dict": ("ja", ["ja_list", "ja_rules", ]), - "jbo_dict": ("jbo", ["jbo_list", "jbo_rules", ]), - "ka_dict": ("ka", ["ka_list", "ka_rules", ]), - "kaa_dict": ("kaa", ["kaa_list", "kaa_rules", ]), - "kk_dict": ("kk", ["kk_list", "kk_rules", ]), - "kl_dict": ("kl", ["kl_list", "kl_rules", ]), - "kn_dict": ("kn", ["kn_list", "kn_rules", ]), - "kok_dict": ("kok", ["kok_list", "kok_rules", ]), - "ko_dict": ("ko", ["ko_list", "ko_rules", ]), - "ku_dict": ("ku", ["ku_list", "ku_rules", ]), - "ky_dict": ("ky", ["ky_list", "ky_rules", ]), - "la_dict": ("la", ["la_list", "la_rules", ]), - "lb_dict": ("lb", ["lb_list", "lb_rules", ]), - "lfn_dict": ("lfn", ["lfn_list", "lfn_rules", ]), - "lt_dict": ("lt", ["lt_list", "lt_rules", ]), - "lv_dict": ("lv", ["lv_list", "lv_rules", ]), - "mi_dict": ("mi", ["mi_list", "mi_rules", ]), - "mk_dict": ("mk", ["mk_list", "mk_rules", ]), - "ml_dict": ("ml", ["ml_list", "ml_rules", ]), - "mr_dict": ("mr", ["mr_list", "mr_rules", ]), - "ms_dict": ("ms", ["ms_list", "ms_rules", ]), - "mt_dict": ("mt", ["mt_list", "mt_rules", ]), - "mto_dict": ("mto", ["mto_list", "mto_rules", ]), - "my_dict": ("my", ["my_list", "my_rules", ]), - "nci_dict": ("nci", ["nci_list", "nci_rules", ]), - "ne_dict": ("ne", ["ne_list", "ne_rules", ]), - "nl_dict": ("nl", ["nl_list", "nl_rules", ]), - "nog_dict": ("nog", ["nog_list", "nog_rules", ]), - "no_dict": ("no", ["no_list", "no_rules", ]), - "om_dict": ("om", ["om_list", "om_rules", ]), - "or_dict": ("or", ["or_list", "or_rules", ]), - "pap_dict": ("pap", ["pap_list", "pap_rules", ]), - "pa_dict": ("pa", ["pa_list", "pa_rules", ]), - "piqd_dict": ("piqd", ["piqd_list", "piqd_rules", ]), - "pl_dict": ("pl", ["pl_list", "pl_rules", ]), - "pt_dict": ("pt", ["pt_list", "pt_rules", ]), - "py_dict": ("py", ["py_list", "py_rules", ]), - "qdb_dict": ("qdb", ["qdb_list", "qdb_rules", ]), - "quc_dict": ("quc", ["quc_list", "quc_rules", ]), - "qya_dict": ("qya", ["qya_list", "qya_rules", ]), - "qu_dict": ("qu", ["qu_list", "qu_rules", ]), - "ro_dict": ("ro", ["ro_list", "ro_rules", ]), + "ja_dict": ( + "ja", + [ + "ja_list", + "ja_rules", + ], + ), + "jbo_dict": ( + "jbo", + [ + "jbo_list", + "jbo_rules", + ], + ), + "ka_dict": ( + "ka", + [ + "ka_list", + "ka_rules", + ], + ), + "kaa_dict": ( + "kaa", + [ + "kaa_list", + "kaa_rules", + ], + ), + "kk_dict": ( + "kk", + [ + "kk_list", + "kk_rules", + ], + ), + "kl_dict": ( + "kl", + [ + "kl_list", + "kl_rules", + ], + ), + "kn_dict": ( + "kn", + [ + "kn_list", + "kn_rules", + ], + ), + "kok_dict": ( + "kok", + [ + "kok_list", + "kok_rules", + ], + ), + "ko_dict": ( + "ko", + [ + "ko_list", + "ko_rules", + ], + ), + "ku_dict": ( + "ku", + [ + "ku_list", + "ku_rules", + ], + ), + "ky_dict": ( + "ky", + [ + "ky_list", + "ky_rules", + ], + ), + "la_dict": ( + "la", + [ + "la_list", + "la_rules", + ], + ), + "lb_dict": ( + "lb", + [ + "lb_list", + "lb_rules", + ], + ), + "lfn_dict": ( + "lfn", + [ + "lfn_list", + "lfn_rules", + ], + ), + "lt_dict": ( + "lt", + [ + "lt_list", + "lt_rules", + ], + ), + "lv_dict": ( + "lv", + [ + "lv_list", + "lv_rules", + ], + ), + "mi_dict": ( + "mi", + [ + "mi_list", + "mi_rules", + ], + ), + "mk_dict": ( + "mk", + [ + "mk_list", + "mk_rules", + ], + ), + "ml_dict": ( + "ml", + [ + "ml_list", + "ml_rules", + ], + ), + "mr_dict": ( + "mr", + [ + "mr_list", + "mr_rules", + ], + ), + "ms_dict": ( + "ms", + [ + "ms_list", + "ms_rules", + ], + ), + "mt_dict": ( + "mt", + [ + "mt_list", + "mt_rules", + ], + ), + "mto_dict": ( + "mto", + [ + "mto_list", + "mto_rules", + ], + ), + "my_dict": ( + "my", + [ + "my_list", + "my_rules", + ], + ), + "nci_dict": ( + "nci", + [ + "nci_list", + "nci_rules", + ], + ), + "ne_dict": ( + "ne", + [ + "ne_list", + "ne_rules", + ], + ), + "nl_dict": ( + "nl", + [ + "nl_list", + "nl_rules", + ], + ), + "nog_dict": ( + "nog", + [ + "nog_list", + "nog_rules", + ], + ), + "no_dict": ( + "no", + [ + "no_list", + "no_rules", + ], + ), + "om_dict": ( + "om", + [ + "om_list", + "om_rules", + ], + ), + "or_dict": ( + "or", + [ + "or_list", + "or_rules", + ], + ), + "pap_dict": ( + "pap", + [ + "pap_list", + "pap_rules", + ], + ), + "pa_dict": ( + "pa", + [ + "pa_list", + "pa_rules", + ], + ), + "piqd_dict": ( + "piqd", + [ + "piqd_list", + "piqd_rules", + ], + ), + "pl_dict": ( + "pl", + [ + "pl_list", + "pl_rules", + ], + ), + "pt_dict": ( + "pt", + [ + "pt_list", + "pt_rules", + ], + ), + "py_dict": ( + "py", + [ + "py_list", + "py_rules", + ], + ), + "qdb_dict": ( + "qdb", + [ + "qdb_list", + "qdb_rules", + ], + ), + "quc_dict": ( + "quc", + [ + "quc_list", + "quc_rules", + ], + ), + "qya_dict": ( + "qya", + [ + "qya_list", + "qya_rules", + ], + ), + "qu_dict": ( + "qu", + [ + "qu_list", + "qu_rules", + ], + ), + "ro_dict": ( + "ro", + [ + "ro_list", + "ro_rules", + ], + ), "ru_dict": ("ru", ["ru_listx", "ru_list", "ru_rules"]), - "sd_dict": ("sd", ["sd_list", "sd_rules", ]), - "shn_dict": ("shn", ["shn_list", "shn_rules", ]), - "si_dict": ("si", ["si_list", "si_rules", ]), - "sjn_dict": ("sjn", ["sjn_list", "sjn_rules", ]), - "sk_dict": ("sk", ["sk_list", "sk_rules", ]), - "sl_dict": ("sl", ["sl_list", "sl_rules", ]), - "smj_dict": ("smj", ["smj_list", "smj_rules", ]), - "sq_dict": ("sq", ["sq_list", "sq_rules", ]), - "sr_dict": ("sr", ["sr_list", "sr_rules", ]), - "sv_dict": ("sv", ["sv_list", "sv_rules", ]), - "sw_dict": ("sw", ["sw_list", "sw_rules", ]), - "ta_dict": ("ta", ["ta_list", "ta_rules", ]), - "te_dict": ("te", ["te_list", "te_rules", ]), - "th_dict": ("th", ["th_list", "th_rules", ]), - "ti_dict": ("ti", ["ti_list", "ti_rules", ]), + "sd_dict": ( + "sd", + [ + "sd_list", + "sd_rules", + ], + ), + "shn_dict": ( + "shn", + [ + "shn_list", + "shn_rules", + ], + ), + "si_dict": ( + "si", + [ + "si_list", + "si_rules", + ], + ), + "sjn_dict": ( + "sjn", + [ + "sjn_list", + "sjn_rules", + ], + ), + "sk_dict": ( + "sk", + [ + "sk_list", + "sk_rules", + ], + ), + "sl_dict": ( + "sl", + [ + "sl_list", + "sl_rules", + ], + ), + "smj_dict": ( + "smj", + [ + "smj_list", + "smj_rules", + ], + ), + "sq_dict": ( + "sq", + [ + "sq_list", + "sq_rules", + ], + ), + "sr_dict": ( + "sr", + [ + "sr_list", + "sr_rules", + ], + ), + "sv_dict": ( + "sv", + [ + "sv_list", + "sv_rules", + ], + ), + "sw_dict": ( + "sw", + [ + "sw_list", + "sw_rules", + ], + ), + "ta_dict": ( + "ta", + [ + "ta_list", + "ta_rules", + ], + ), + "te_dict": ( + "te", + [ + "te_list", + "te_rules", + ], + ), + "th_dict": ( + "th", + [ + "th_list", + "th_rules", + ], + ), + "ti_dict": ( + "ti", + [ + "ti_list", + "ti_rules", + ], + ), "tk_dict": ("tk", ["tk_listx", "tk_list", "tk_rules"]), - "tn_dict": ("tn", ["tn_list", "tn_rules", ]), + "tn_dict": ( + "tn", + [ + "tn_list", + "tn_rules", + ], + ), "tr_dict": ("tr", ["tr_listx", "tr_list", "tr_rules"]), - "tt_dict": ("tt", ["tt_list", "tt_rules", ]), - "ug_dict": ("ug", ["ug_list", "ug_rules", ]), - "uk_dict": ("uk", ["uk_list", "uk_rules", ]), - "ur_dict": ("ur", ["ur_list", "ur_rules", ]), - "uz_dict": ("uz", ["uz_list", "uz_rules", ]), - "vi_dict": ("vi", ["vi_list", "vi_rules", ]), + "tt_dict": ( + "tt", + [ + "tt_list", + "tt_rules", + ], + ), + "ug_dict": ( + "ug", + [ + "ug_list", + "ug_rules", + ], + ), + "uk_dict": ( + "uk", + [ + "uk_list", + "uk_rules", + ], + ), + "ur_dict": ( + "ur", + [ + "ur_list", + "ur_rules", + ], + ), + "uz_dict": ( + "uz", + [ + "uz_list", + "uz_rules", + ], + ), + "vi_dict": ( + "vi", + [ + "vi_list", + "vi_rules", + ], + ), "yue_dict": ("yue", ["yue_list", "yue_listx", "yue_rules"]), } + def espeak_compileDict_buildAction( - target: typing.List[SCons.Node.FS.File], - source: typing.List[SCons.Node.FS.File], - env: SCons.Environment.Environment + target: typing.List[SCons.Node.FS.File], + source: typing.List[SCons.Node.FS.File], + env: SCons.Environment.Environment, ) -> int: """ @param target: The langCode_dict file to build @@ -322,7 +974,7 @@ def espeak_compileDict_buildAction( # This is because it writes to stderr but doesn't flush it. # Unfortunately, there's no way we can flush it or use a different stream # because our eSpeak statically links the CRT. - espeak=AutoFreeCDLL(espeakLib[0].abspath) + espeak = AutoFreeCDLL(espeakLib[0].abspath) # from: espeak-ng/speak_lib.h espeakINITIALIZE_DONT_EXIT = 0x8000 @@ -330,25 +982,22 @@ def espeak_compileDict_buildAction( espeak.espeak_Initialize( espeak_AUDIO_OUTPUT.AUDIO_OUTPUT_PLAYBACK, # espeak_AUDIO_OUTPUT output_type 0, # int buf_length - os.fsencode(target.Dir('..').abspath), # const char *path - espeakINITIALIZE_DONT_EXIT # int options + os.fsencode(target.Dir("..").abspath), # const char *path + espeakINITIALIZE_DONT_EXIT, # int options ) - try: # ensure that espeak_Terminate is called + try: # ensure that espeak_Terminate is called lang = espeakDictionaryCompileList[target.name][0] - voice = espeak_VOICE(languages=lang.encode() + b'\x00') + voice = espeak_VOICE(languages=lang.encode() + b"\x00") # see: espeak-ng/speak_lib.h for espeak_SetVoiceByProperties # returns: espeak_ERROR setVoiceResult = espeak.espeak_SetVoiceByProperties(ctypes.byref(voice)) if espeak_ERROR.EE_OK.value != setVoiceResult: - print( - f"Failed to switch to language: '{lang}'" - f"\n result: {espeak_ERROR(setVoiceResult)!s}" - ) + print(f"Failed to switch to language: '{lang}'" f"\n result: {espeak_ERROR(setVoiceResult)!s}") return ACTION_FAILURE - rulesPathEncoded = os.fsencode(dirForRules.abspath + '/') + rulesPathEncoded = os.fsencode(dirForRules.abspath + "/") # see: espeak-ng/espeak_ng.h for espeak_ng_CompileDictionary # returns: espeak_ng_STATUS compileDictResult = espeak.espeak_ng_CompileDictionary( @@ -370,15 +1019,16 @@ def espeak_compileDict_buildAction( espeak.espeak_Terminate() return ACTION_SUCCESS -sonicLib=env.StaticLibrary( - target='sonic', + +sonicLib = env.StaticLibrary( + target="sonic", srcdir=sonicSrcDir.abspath, - source='sonic.c', + source="sonic.c", ) -espeakLib=env.SharedLibrary( - target='espeak', - srcdir=espeakSrcDir.Dir('libespeak-ng').abspath, +espeakLib = env.SharedLibrary( + target="espeak", + srcdir=espeakSrcDir.Dir("libespeak-ng").abspath, source=[ # compare to src_libespeak_ng_la_SOURCES in espeak Makefile.am "../ucd-tools/src/case.c", @@ -390,7 +1040,7 @@ espeakLib=env.SharedLibrary( "common.c", "compiledata.c", "compiledict.c", -# "compilembrola.c", # we dont use MBROLA, this is a compile option in espeak + # "compilembrola.c", # we dont use MBROLA, this is a compile option in espeak "dictionary.c", "encoding.c", "error.c", @@ -398,8 +1048,8 @@ espeakLib=env.SharedLibrary( "ieee80.c", "intonation.c", "langopts.c", - "klatt.c", # we do use KLATT, this is a compile option in espeak -# "mbrowrap.c", # we don't use MBROLA, this is a compile option in espeak + "klatt.c", # we do use KLATT, this is a compile option in espeak + # "mbrowrap.c", # we don't use MBROLA, this is a compile option in espeak "mnemonics.c", "numbers.c", "phoneme.c", @@ -412,7 +1062,7 @@ espeakLib=env.SharedLibrary( "ssml.c", "synthdata.c", "synthesize.c", - "synth_mbrola.c", # provides symbols used by synthesize.obj, voices.obj, and wavegen.obj + "synth_mbrola.c", # provides symbols used by synthesize.obj, voices.obj, and wavegen.obj "translate.c", "translateword.c", "tr_languages.c", @@ -424,7 +1074,7 @@ espeakLib=env.SharedLibrary( "../speechPlayer/src/frame.cpp", "../speechPlayer/src/speechPlayer.cpp", "../speechPlayer/src/speechWaveGenerator.cpp", - #"../speak-ng.cpp", + # "../speak-ng.cpp", # if not OPT_SPEECHPLAYER # "../speak-ng.c", # espeak does not need to handle its own audio output so dont include: @@ -436,20 +1086,17 @@ espeakLib=env.SharedLibrary( # com\ttsengine.cpp # We do not use the ASYNC compile option in espeak. ], - LIBS=['advapi32'], + LIBS=["advapi32"], ) -phonemeData = env.espeak_compilePhonemeData( - espeakRepo.Dir('espeak-ng-data'), - espeakRepo.Dir('phsource') -) -env.Depends(phonemeData,espeakLib) +phonemeData = env.espeak_compilePhonemeData(espeakRepo.Dir("espeak-ng-data"), espeakRepo.Dir("phsource")) +env.Depends(phonemeData, espeakLib) for i in phonemeData: - iDir = espeakRepo.Dir('espeak-ng-data').abspath + iDir = espeakRepo.Dir("espeak-ng-data").abspath l = len(iDir) + 1 # noqa: E741 fileName = i.abspath[l:] - env.InstallAs(os.path.join(synthDriversDir.Dir('espeak-ng-data').abspath, fileName), i) + env.InstallAs(os.path.join(synthDriversDir.Dir("espeak-ng-data").abspath, fileName), i) # Removes files that are created when installing from dictsource/extra/*_* to dictsource. @@ -457,46 +1104,46 @@ for i in phonemeData: env.AddPreAction(espeakLib, env.Action(cleanFiles_preBuildAction)) # Move any extra dictionaries into dictsource for compilation env.Install( - espeakRepo.Dir('dictsource'), - env.Glob(os.path.join(espeakRepo.abspath, 'dictsource', 'extra', '*_*')) + espeakRepo.Dir("dictsource"), env.Glob(os.path.join(espeakRepo.abspath, "dictsource", "extra", "*_*")) ) -excludeLangs: typing.List[str] = [ -] +excludeLangs: typing.List[str] = [] """Used to exclude languages which don't compile. """ # Compile all dictionaries -dictSourcePath: SCons.Node.FS.Dir = espeakRepo.Dir('dictsource') +dictSourcePath: SCons.Node.FS.Dir = espeakRepo.Dir("dictsource") # Create compile commands for all languages for dictFileName, (langCode, inputFiles) in espeakDictionaryCompileList.items(): - if langCode in excludeLangs: continue # noqa: E701 + if langCode in excludeLangs: + continue # noqa: E701 - dictFilePath = espeakRepo.Dir('espeak-ng-data').File(dictFileName) + dictFilePath = espeakRepo.Dir("espeak-ng-data").File(dictFileName) dictFile = env.Command( target=dictFilePath, source=list((dictSourcePath.File(f) for f in inputFiles)), - action=espeak_compileDict_buildAction + action=espeak_compileDict_buildAction, ) env.Depends(dictFile, [espeakLib, phonemeData]) # Dictionaries can not be compiled in parallel, force SCons not to do this - env.SideEffect('_espeak_compileDict',dictFile) - env.InstallAs( # Install files to the "synthDrivers/espeak-ng-data/" dir. - os.path.join(synthDriversDir.Dir('espeak-ng-data').abspath, dictFileName), - dictFile + env.SideEffect("_espeak_compileDict", dictFile) + env.InstallAs( # Install files to the "synthDrivers/espeak-ng-data/" dir. + os.path.join(synthDriversDir.Dir("espeak-ng-data").abspath, dictFileName), dictFile ) -env.Install(synthDriversDir,espeakLib) +env.Install(synthDriversDir, espeakLib) # install espeak-ng-data -targetEspeakDataDir=synthDriversDir.Dir('espeak-ng-data') -espeakDataSource=espeakRepo.Dir('espeak-ng-data') +targetEspeakDataDir = synthDriversDir.Dir("espeak-ng-data") +espeakDataSource = espeakRepo.Dir("espeak-ng-data") # also install the lang and voices/!v directories. Exclude the voices/mb directory since we are not using mbrola. -env.RecursiveInstall(targetEspeakDataDir.Dir('lang'),espeakDataSource.Dir('lang').abspath) -env.RecursiveInstall(targetEspeakDataDir.Dir('voices').Dir('!v'),espeakDataSource.Dir('voices').Dir('!v').abspath) +env.RecursiveInstall(targetEspeakDataDir.Dir("lang"), espeakDataSource.Dir("lang").abspath) +env.RecursiveInstall( + targetEspeakDataDir.Dir("voices").Dir("!v"), espeakDataSource.Dir("voices").Dir("!v").abspath +) diff --git a/nvdaHelper/ia2_sconscript b/nvdaHelper/ia2_sconscript index bddcbc54180..ee734962a04 100644 --- a/nvdaHelper/ia2_sconscript +++ b/nvdaHelper/ia2_sconscript @@ -1,78 +1,79 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright (C) 2006-2017 NV Access Limited, Mozilla Corporation. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright (C) 2006-2017 NV Access Limited, Mozilla Corporation. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### import re -Import('env') +Import("env") # We want a single merged IDL, rather than the separate IDL files in the IA2 source. RE_IDL_IMPORT = re.compile(r'import "[A-Z].*$', re.M) + + def buildMergedIdl(target, source, env): outFile = open(str(target[0]), "w") # The first source is a header and should be included unmodified. inFile = open(str(source[0]), "r") outFile.write(inFile.read()) - outFile.write('\n') + outFile.write("\n") for idl in source[1:]: # This source should be included with import statements removed. inFile = open(str(idl), "r") - outFile.write(RE_IDL_IMPORT.sub('',inFile.read())) - outFile.write('\n') + outFile.write(RE_IDL_IMPORT.sub("", inFile.read())) + outFile.write("\n") return None + idlDir = env.Dir("#include/ia2/api") idlFiles = [ # This file contains the header for the merged IDL. - 'api_all_headers.idl', + "api_all_headers.idl", # These files must be ordered based on dependencies. # The order should not be changed without confirming dependencies first. - 'IA2CommonTypes.idl', - 'AccessibleRelation.idl', - 'AccessibleAction.idl', - 'AccessibleRole.idl', - 'AccessibleStates.idl', - 'Accessible2.idl', - 'Accessible2_2.idl', - 'AccessibleComponent.idl', - 'AccessibleValue.idl', - 'AccessibleText.idl', - 'AccessibleText2.idl', - 'AccessibleEditableText.idl', - 'AccessibleHyperlink.idl', - 'AccessibleHypertext.idl', - 'AccessibleHypertext2.idl', - 'AccessibleTable.idl', - 'AccessibleTable2.idl', - 'AccessibleTableCell.idl', - 'AccessibleImage.idl', - 'AccessibleEventID.idl', - 'AccessibleApplication.idl', - 'AccessibleDocument.idl', - 'AccessibleTextSelectionContainer.idl', - 'IA2TypeLibrary.idl', - ] -idlFile = env.Command('ia2.idl', - [idlDir.File(idl) for idl in idlFiles], - buildMergedIdl) + "IA2CommonTypes.idl", + "AccessibleRelation.idl", + "AccessibleAction.idl", + "AccessibleRole.idl", + "AccessibleStates.idl", + "Accessible2.idl", + "Accessible2_2.idl", + "AccessibleComponent.idl", + "AccessibleValue.idl", + "AccessibleText.idl", + "AccessibleText2.idl", + "AccessibleEditableText.idl", + "AccessibleHyperlink.idl", + "AccessibleHypertext.idl", + "AccessibleHypertext2.idl", + "AccessibleTable.idl", + "AccessibleTable2.idl", + "AccessibleTableCell.idl", + "AccessibleImage.idl", + "AccessibleEventID.idl", + "AccessibleApplication.idl", + "AccessibleDocument.idl", + "AccessibleTextSelectionContainer.idl", + "IA2TypeLibrary.idl", +] +idlFile = env.Command("ia2.idl", [idlDir.File(idl) for idl in idlFiles], buildMergedIdl) -tlbFile,headerFile,iidSourceFile,proxySourceFile,dlldataSourceFile=env.TypeLibrary(source=idlFile) +tlbFile, headerFile, iidSourceFile, proxySourceFile, dlldataSourceFile = env.TypeLibrary(source=idlFile) -proxyDll=env.COMProxyDll( - target='IAccessible2proxy', - source=[iidSourceFile,proxySourceFile,dlldataSourceFile], +proxyDll = env.COMProxyDll( + target="IAccessible2proxy", + source=[iidSourceFile, proxySourceFile, dlldataSourceFile], # This CLSID must be unique to this dll. A new one can be generated with import comtypes; comtypes.GUID.create_new() - proxyClsid="{62d295fe-2062-4369-a010-4f59b5e32d5e}" + proxyClsid="{62d295fe-2062-4369-a010-4f59b5e32d5e}", ) -Return(['proxyDll','tlbFile','headerFile','iidSourceFile','proxySourceFile','dlldataSourceFile']) +Return(["proxyDll", "tlbFile", "headerFile", "iidSourceFile", "proxySourceFile", "dlldataSourceFile"]) diff --git a/nvdaHelper/liblouis/sconscript b/nvdaHelper/liblouis/sconscript index 2c8220938ed..c4ee7c2bf4c 100644 --- a/nvdaHelper/liblouis/sconscript +++ b/nvdaHelper/liblouis/sconscript @@ -1,15 +1,15 @@ ### -#This file is a part of the NVDA project. -#URL: https://www.nvaccess.org/ -#Copyright 2011-2024 NV Access Limited, Joseph Lee, Babbage B.V., Leonard de Ruijter -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: https://www.nvaccess.org/ +# Copyright 2011-2024 NV Access Limited, Joseph Lee, Babbage B.V., Leonard de Ruijter +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### import os @@ -20,10 +20,12 @@ import typing from SCons.Environment import Environment from SCons.Environment import Base -Import([ - "thirdPartyEnv", - "sourceDir", -]) +Import( + [ + "thirdPartyEnv", + "sourceDir", + ] +) sourceDir: Base = sourceDir thirdPartyEnv: Environment = thirdPartyEnv env: Environment = typing.cast(Environment, thirdPartyEnv.Clone()) @@ -33,9 +35,13 @@ louisSourceDir = louisRootDir.Dir("liblouis") louisTableDir = louisRootDir.Dir("tables") outDir = sourceDir.Dir("louis") unitTestTablesDir = env.Dir("#tests/unit/brailleTables") -signExec = env['signExec'] if (bool(env['certFile']) ^ bool(env['apiSigningToken'])) else None +signExec = env["signExec"] if (bool(env["certFile"]) ^ bool(env["apiSigningToken"])) else None + +RE_AC_INIT = re.compile( + r"^AC_INIT\(\[(?P.*)\], \[(?P.*)\], \[(?P.*)\], \[(?P.*)\], \[(?P.*)\]\)" +) + -RE_AC_INIT = re.compile(r"^AC_INIT\(\[(?P.*)\], \[(?P.*)\], \[(?P.*)\], \[(?P.*)\], \[(?P.*)\]\)") def getLouisVersion(): # Get the version from configure.ac. with open(louisRootDir.File("configure.ac").abspath) as f: @@ -45,41 +51,42 @@ def getLouisVersion(): return m.group("version") return "unknown" + # Liblouis is build with Clang, as Microsoft Visual C++ is unable to build C99 code. -clangDirs = glob.glob(os.path.join( - find_vc_pdir(env, env.get("MSVC_VERSION")), - r"Tools\Llvm\bin" -)) +clangDirs = glob.glob(os.path.join(find_vc_pdir(env, env.get("MSVC_VERSION")), r"Tools\Llvm\bin")) if len(clangDirs) == 0: raise RuntimeError( "Could not find the Clang compiler. " "Perhaps the C++ Clang tools for Windows component in visual Studio is not installed" - ) -env['CC'] = 'clang-cl' -env['M4'] = str(env.File("#miscdeps/tools/m4.exe")) + ) +env["CC"] = "clang-cl" +env["M4"] = str(env.File("#miscdeps/tools/m4.exe")) # Liblouis disables GNU extensions for m4 -env.Append(M4FLAGS='-G') +env.Append(M4FLAGS="-G") # Don't analyze the code as not our project -if 'analyze' in env['nvdaHelperDebugFlags']: - env.Append(CCFLAGS='/analyze-') +if "analyze" in env["nvdaHelperDebugFlags"]: + env.Append(CCFLAGS="/analyze-") -env.Append(CPPDEFINES=[ - # The Visual C++ C Runtime deprecates standard POSIX APIs that conflict with - # reserved ISO C names (like strdup) in favour of non-portable conforming - # variants that start with an '_'. This removes those deprecation warnings. */ - "_CRT_NONSTDC_NO_DEPRECATE", - ("PACKAGE_VERSION", r'\"%s\"' % getLouisVersion()), - "WIDECHARS_ARE_UCS4", - # Tell liblouis.h that we're exporting liblouis dll functions, not importing them. - "_EXPORTING", -]) +env.Append( + CPPDEFINES=[ + # The Visual C++ C Runtime deprecates standard POSIX APIs that conflict with + # reserved ISO C names (like strdup) in favour of non-portable conforming + # variants that start with an '_'. This removes those deprecation warnings. */ + "_CRT_NONSTDC_NO_DEPRECATE", + ("PACKAGE_VERSION", r"\"%s\"" % getLouisVersion()), + "WIDECHARS_ARE_UCS4", + # Tell liblouis.h that we're exporting liblouis dll functions, not importing them. + "_EXPORTING", + ] +) env.Prepend(CPPPATH=[".", louisSourceDir]) # Upstream liblouis compiles without UNICODE defined. -env['CPPDEFINES'].remove("UNICODE") +env["CPPDEFINES"].remove("UNICODE") -liblouisH = env.Substfile("liblouis.h", louisSourceDir.File("liblouis.h.in"), - SUBST_DICT={"@WIDECHAR_TYPE@": "unsigned int"}) +liblouisH = env.Substfile( + "liblouis.h", louisSourceDir.File("liblouis.h.in"), SUBST_DICT={"@WIDECHAR_TYPE@": "unsigned int"} +) sourceFiles = [ "compileTranslationTable.c", @@ -94,34 +101,40 @@ sourceFiles = [ objs = [env.Object("%s.obj" % f, louisSourceDir.File(f)) for f in sourceFiles] louisLib = env.SharedLibrary("liblouis", objs) if signExec: - env.AddPostAction(louisLib[0],[signExec]) + env.AddPostAction(louisLib[0], [signExec]) env.Install(sourceDir, louisLib) -louisPython = env.Substfile(outDir.File("__init__.py"), louisRootDir.File("python/louis/__init__.py.in"), - SUBST_DICT={"###LIBLOUIS_SONAME###": louisLib[0].name}) +louisPython = env.Substfile( + outDir.File("__init__.py"), + louisRootDir.File("python/louis/__init__.py.in"), + SUBST_DICT={"###LIBLOUIS_SONAME###": louisLib[0].name}, +) env.Install( outDir.Dir("tables"), [ - f for f in env.Glob(f"{louisTableDir}/*") - if f.name not in ( + f + for f in env.Glob(f"{louisTableDir}/*") + if f.name + not in ( "Makefile.am", "README", "maketablelist.sh", - ) and not f.name.endswith(".in") - ] + ) + and not f.name.endswith(".in") + ], ) # Tables containing macros for f in env.Glob(f"{louisTableDir}/*.in"): - env.M4( - source=f, - target=outDir.Dir("tables").File(os.path.splitext(f.name)[0]) - ) + env.M4(source=f, target=outDir.Dir("tables").File(os.path.splitext(f.name)[0])) # Custom tables unit test testTable = env.InstallAs(unitTestTablesDir.File("test.utb"), louisTableDir.File("en-us-comp8-ext.utb")) -env.Depends(testTable, env.Install(unitTestTablesDir, [ - louisTableDir.File("latinLetterDef8Dots.uti"), - louisTableDir.File("en-us-comp8-ext.utb") -])) +env.Depends( + testTable, + env.Install( + unitTestTablesDir, + [louisTableDir.File("latinLetterDef8Dots.uti"), louisTableDir.File("en-us-comp8-ext.utb")], + ), +) # Ensure the braille tables for tests are installed when copying the louis wrapper env.Depends(louisPython, testTable) diff --git a/nvdaHelper/local/sconscript b/nvdaHelper/local/sconscript index 21035c87e71..43ba2a91520 100644 --- a/nvdaHelper/local/sconscript +++ b/nvdaHelper/local/sconscript @@ -1,26 +1,28 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import([ - 'env', - 'detoursLib', - 'apiHookObj', -]) +Import( + [ + "env", + "detoursLib", + "apiHookObj", + ] +) -winIPCUtilsObj=env.Object("./winIPCUtils","../common/winIPCUtils.cpp") +winIPCUtilsObj = env.Object("./winIPCUtils", "../common/winIPCUtils.cpp") -controllerRPCHeader,controllerRPCServerSource=env.MSRPCStubs( +controllerRPCHeader, controllerRPCServerSource = env.MSRPCStubs( target="./nvdaController", source=[ "../interfaces/nvdaController/nvdaController.idl", @@ -30,7 +32,7 @@ controllerRPCHeader,controllerRPCServerSource=env.MSRPCStubs( MSRPCStubs_prefix="nvdaController_", ) -controllerInternalRPCHeader,controllerInternalRPCServerSource=env.MSRPCStubs( +controllerInternalRPCHeader, controllerInternalRPCServerSource = env.MSRPCStubs( target="./nvdaControllerInternal", source=[ "../interfaces/nvdaControllerInternal/nvdaControllerInternal.idl", @@ -40,7 +42,7 @@ controllerInternalRPCHeader,controllerInternalRPCServerSource=env.MSRPCStubs( MSRPCStubs_prefix="nvdaControllerInternal_", ) -vbufRPCHeader,vbufRPCClientSource=env.MSRPCStubs( +vbufRPCHeader, vbufRPCClientSource = env.MSRPCStubs( target="./vbuf", source=[ "../interfaces/vbuf/vbuf.idl", @@ -49,7 +51,7 @@ vbufRPCHeader,vbufRPCClientSource=env.MSRPCStubs( MSRPCStubs_prefix="VBuf_", ) -nvdaInProcUtilsRPCHeader,nvdaInProcUtilsRPCClientSource=env.MSRPCStubs( +nvdaInProcUtilsRPCHeader, nvdaInProcUtilsRPCClientSource = env.MSRPCStubs( target="./nvdaInProcUtils", source=[ "../interfaces/nvdaInProcUtils/nvdaInProcUtils.idl", @@ -59,7 +61,7 @@ nvdaInProcUtilsRPCHeader,nvdaInProcUtilsRPCClientSource=env.MSRPCStubs( MSRPCStubs_prefix="nvdaInProcUtils_", ) -displayModelRPCHeader,displayModelRPCClientSource=env.MSRPCStubs( +displayModelRPCHeader, displayModelRPCClientSource = env.MSRPCStubs( target="./displayModel", source=[ "../interfaces/displayModel/displayModel.idl", @@ -69,21 +71,21 @@ displayModelRPCHeader,displayModelRPCClientSource=env.MSRPCStubs( MSRPCStubs_prefix="displayModel_", ) -localLib=env.SharedLibrary( +localLib = env.SharedLibrary( target="nvdaHelperLocal", source=[ - env['projectResFile'], + env["projectResFile"], apiHookObj, "nvdaHelperLocal.cpp", "beeps.cpp", vbufRPCClientSource, nvdaInProcUtilsRPCClientSource, displayModelRPCClientSource, - 'rpcSrv.cpp', - 'nvdaController.cpp', + "rpcSrv.cpp", + "nvdaController.cpp", winIPCUtilsObj, controllerRPCServerSource, - 'nvdaControllerInternal.c', + "nvdaControllerInternal.c", controllerInternalRPCServerSource, "dllImportTableHooks.cpp", "nvdaHelperLocal.def", @@ -108,4 +110,4 @@ localLib=env.SharedLibrary( ], ) -Return('localLib') +Return("localLib") diff --git a/nvdaHelper/localWin10/sconscript b/nvdaHelper/localWin10/sconscript index 8cec144caa6..f0be1ff6d40 100644 --- a/nvdaHelper/localWin10/sconscript +++ b/nvdaHelper/localWin10/sconscript @@ -18,9 +18,9 @@ import glob from SCons.Tool.MSCommon.vc import find_vc_pdir Import( - 'env', - 'sourceDir', - 'localLib', + "env", + "sourceDir", + "localLib", ) @@ -30,14 +30,15 @@ env = env.Clone() # noqa: F821 localWin10Lib = env.SharedLibrary( target="nvdaHelperLocalWin10", source=[ - env['projectResFile'], - 'oneCoreSpeech.cpp', - 'uwpOcr.cpp', + env["projectResFile"], + "oneCoreSpeech.cpp", + "uwpOcr.cpp", ], LIBS=[ "WindowsApp", # Ignoring Flake8 F821: 'undefined name' due to nonstandard SCons import - localLib[2]], # noqa: F821 + localLib[2], + ], # noqa: F821 ) # UWP dlls can only be dynamically linked with the CRT, @@ -45,13 +46,16 @@ localWin10Lib = env.SharedLibrary( # Therefore, we must include it. # VS keeps changing the path to reflect the latest major.minor.build version which we canot easily find out. # Therefore Search these versioned directories from newest to oldest to collect all the files we need. -msvc = env.get('MSVC_VERSION') -vcRedistDirs = glob.glob(os.path.join( - find_vc_pdir(env, msvc), - rf"Redist\MSVC\{msvc[:2]}*\x86\Microsoft.VC{msvc.replace('.', '')}.CRT" -)) -if len(vcRedistDirs)==0: - raise RuntimeError("Could not locate vc redistributables. Perhaps the Universal Windows Platform component in visual Studio is not installed") +msvc = env.get("MSVC_VERSION") +vcRedistDirs = glob.glob( + os.path.join( + find_vc_pdir(env, msvc), rf"Redist\MSVC\{msvc[:2]}*\x86\Microsoft.VC{msvc.replace('.', '')}.CRT" + ) +) +if len(vcRedistDirs) == 0: + raise RuntimeError( + "Could not locate vc redistributables. Perhaps the Universal Windows Platform component in visual Studio is not installed" + ) vcRedistDirs.sort(reverse=True) for fn in ("msvcp140.dll", "vccorlib140.dll", "vcruntime140.dll"): for vcRedistDir in vcRedistDirs: @@ -60,6 +64,9 @@ for fn in ("msvcp140.dll", "vccorlib140.dll", "vcruntime140.dll"): env.Install(sourceDir, path) break else: - raise RuntimeError("Could not locate %s. Perhaps the Universal Windows Platform component in visual Studio is not installed"%fn) + raise RuntimeError( + "Could not locate %s. Perhaps the Universal Windows Platform component in visual Studio is not installed" + % fn + ) -Return(['localWin10Lib']) +Return(["localWin10Lib"]) diff --git a/nvdaHelper/mathPlayer_sconscript b/nvdaHelper/mathPlayer_sconscript index c0b6891c12f..8e26b9e33bf 100644 --- a/nvdaHelper/mathPlayer_sconscript +++ b/nvdaHelper/mathPlayer_sconscript @@ -1,33 +1,37 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2014-2017 NV Access Limited. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2014-2017 NV Access Limited. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import('env') +Import("env") -idlDep = env.Command("MathSpeechEnums.idl","#/miscDeps/include/mathPlayer/MathSpeechEnums.idl",Copy("$TARGET","$SOURCE")) -idlFile=env.Command("mathPlayerDLL.idl","#/miscDeps/include/mathPlayer/mathPlayerDLL.idl",Copy("$TARGET","$SOURCE")) +idlDep = env.Command( + "MathSpeechEnums.idl", "#/miscDeps/include/mathPlayer/MathSpeechEnums.idl", Copy("$TARGET", "$SOURCE") +) +idlFile = env.Command( + "mathPlayerDLL.idl", "#/miscDeps/include/mathPlayer/mathPlayerDLL.idl", Copy("$TARGET", "$SOURCE") +) # SCons doesn't scan the file we just created, # so we must explicitly declare its dependencies. env.Depends(idlFile, idlDep) -tlbFile,headerFile,iidSourceFile,proxySourceFile,dlldataSourceFile=env.TypeLibrary( +tlbFile, headerFile, iidSourceFile, proxySourceFile, dlldataSourceFile = env.TypeLibrary( source=idlFile, - MIDLFLAGS=['/I',Dir('.')], + MIDLFLAGS=["/I", Dir(".")], ) # #7036: hack: Ignore midl.exe when deciding to rebuild, as its position in the dependencies # is different in the run before the idl files are copied versus subsequent runs. -midl=env.WhereIs(env["MIDL"]) -for target in (tlbFile,headerFile,iidSourceFile,proxySourceFile,dlldataSourceFile): - env.Ignore(target,midl) +midl = env.WhereIs(env["MIDL"]) +for target in (tlbFile, headerFile, iidSourceFile, proxySourceFile, dlldataSourceFile): + env.Ignore(target, midl) -Return(['tlbFile','headerFile','iidSourceFile','proxySourceFile','dlldataSourceFile']) +Return(["tlbFile", "headerFile", "iidSourceFile", "proxySourceFile", "dlldataSourceFile"]) diff --git a/nvdaHelper/remote/sconscript b/nvdaHelper/remote/sconscript index 5dc6b3f3585..a553d40d3bd 100644 --- a/nvdaHelper/remote/sconscript +++ b/nvdaHelper/remote/sconscript @@ -12,25 +12,27 @@ # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import([ - 'env', - 'ia2RPCStubs', - 'detoursLib', - 'apiHookObj', -]) +Import( + [ + "env", + "ia2RPCStubs", + "detoursLib", + "apiHookObj", + ] +) -winIPCUtilsObj=env.Object("./winIPCUtils","../common/winIPCUtils.cpp") +winIPCUtilsObj = env.Object("./winIPCUtils", "../common/winIPCUtils.cpp") -vbufBackendLibs=[ - env.SConscript('../vbufBase/sconscript'), - env.SConscript('../vbufBackends/adobeAcrobat/sconscript'), - env.SConscript('../vbufBackends/lotusNotesRichText/sconscript'), - env.SConscript('../vbufBackends/gecko_ia2/sconscript'), - env.SConscript('../vbufBackends/mshtml/sconscript'), - env.SConscript('../vbufBackends/webKit/sconscript'), +vbufBackendLibs = [ + env.SConscript("../vbufBase/sconscript"), + env.SConscript("../vbufBackends/adobeAcrobat/sconscript"), + env.SConscript("../vbufBackends/lotusNotesRichText/sconscript"), + env.SConscript("../vbufBackends/gecko_ia2/sconscript"), + env.SConscript("../vbufBackends/mshtml/sconscript"), + env.SConscript("../vbufBackends/webKit/sconscript"), ] -controllerRPCHeader,controllerRPCClientSource=env.MSRPCStubs( +controllerRPCHeader, controllerRPCClientSource = env.MSRPCStubs( target="./nvdaController", source=[ "../interfaces/nvdaController/nvdaController.idl", @@ -40,7 +42,7 @@ controllerRPCHeader,controllerRPCClientSource=env.MSRPCStubs( MSRPCStubs_prefix="nvdaController_", ) -controllerInternalRPCHeader,controllerInternalRPCClientSource=env.MSRPCStubs( +controllerInternalRPCHeader, controllerInternalRPCClientSource = env.MSRPCStubs( target="./nvdaControllerInternal", source=[ "../interfaces/nvdaControllerInternal/nvdaControllerInternal.idl", @@ -50,7 +52,7 @@ controllerInternalRPCHeader,controllerInternalRPCClientSource=env.MSRPCStubs( MSRPCStubs_prefix="nvdaControllerInternal_", ) -vbufRPCHeader,vbufRPCServerSource=env.MSRPCStubs( +vbufRPCHeader, vbufRPCServerSource = env.MSRPCStubs( target="./vbufRemote", source=[ "../interfaces/vbuf/vbuf.idl", @@ -60,7 +62,7 @@ vbufRPCHeader,vbufRPCServerSource=env.MSRPCStubs( MSRPCStubs_prefix="VBufRemote_", ) -displayModelRPCHeader,displayModelRPCServerSource=env.MSRPCStubs( +displayModelRPCHeader, displayModelRPCServerSource = env.MSRPCStubs( target="./displayModelRemote", source=[ "../interfaces/displayModel/displayModel.idl", @@ -70,7 +72,7 @@ displayModelRPCHeader,displayModelRPCServerSource=env.MSRPCStubs( MSRPCStubs_prefix="displayModelRemote_", ) -nvdaInProcUtilsRPCHeader,nvdaInProcUtilsRPCServerSource=env.MSRPCStubs( +nvdaInProcUtilsRPCHeader, nvdaInProcUtilsRPCServerSource = env.MSRPCStubs( target="./nvdaInProcUtils", source=[ "../interfaces/nvdaInProcUtils/nvdaInProcUtils.idl", @@ -80,10 +82,10 @@ nvdaInProcUtilsRPCHeader,nvdaInProcUtilsRPCServerSource=env.MSRPCStubs( MSRPCStubs_prefix="nvdaInProcUtils_", ) -ia2utilsObj=env.Object("./ia2utils","../common/ia2utils.cpp") +ia2utilsObj = env.Object("./ia2utils", "../common/ia2utils.cpp") source = [ - env['projectResFile'], + env["projectResFile"], "injection.cpp", "log.cpp", "inProcess.cpp", @@ -97,7 +99,7 @@ source = [ "ia2LiveRegions.cpp", "textFromIAccessible.cpp", ia2utilsObj, - env.Object('_ia2_i',ia2RPCStubs[3]), + env.Object("_ia2_i", ia2RPCStubs[3]), "rpcSrv.cpp", "vbufRemote.cpp", vbufRPCServerSource, @@ -135,10 +137,10 @@ libs = [ detoursLib, ] -remoteLib=env.SharedLibrary( +remoteLib = env.SharedLibrary( target="nvdaHelperRemote", source=source, LIBS=libs, ) -Return('remoteLib') +Return("remoteLib") diff --git a/nvdaHelper/remoteLoader/sconscript b/nvdaHelper/remoteLoader/sconscript index c2d5a09e2b3..3bc427342f9 100644 --- a/nvdaHelper/remoteLoader/sconscript +++ b/nvdaHelper/remoteLoader/sconscript @@ -1,26 +1,26 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import('env','remoteLib') +Import("env", "remoteLib") -env=env.Clone() -env.Append(LINKFLAGS='/subsystem:windows') +env = env.Clone() +env.Append(LINKFLAGS="/subsystem:windows") -remoteLoaderProgram=env.Program( - target='nvdaHelperRemoteLoader', - source=[env['projectResFile'],'loader.cpp'], - LIBS=[remoteLib[2],'kernel32'], +remoteLoaderProgram = env.Program( + target="nvdaHelperRemoteLoader", + source=[env["projectResFile"], "loader.cpp"], + LIBS=[remoteLib[2], "kernel32"], ) -Return('remoteLoaderProgram') +Return("remoteLoaderProgram") diff --git a/nvdaHelper/sconscript b/nvdaHelper/sconscript index 14d86acdab4..ead0a8f49b0 100644 --- a/nvdaHelper/sconscript +++ b/nvdaHelper/sconscript @@ -1,37 +1,44 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### Import( - 'env', - 'sourceDir', - 'clientDir', - 'sourceLibDir', - 'sourceLibDir64', + "env", + "sourceDir", + "clientDir", + "sourceLibDir", + "sourceLibDir64", ) -archLibInstallDirs={ - 'x86':sourceLibDir, - 'x86_64':sourceLibDir64, +archLibInstallDirs = { + "x86": sourceLibDir, + "x86_64": sourceLibDir64, } -archClientInstallDirs={ - 'x86':clientDir.Dir('x86'), - 'x86_64':clientDir.Dir('x64'), +archClientInstallDirs = { + "x86": clientDir.Dir("x86"), + "x86_64": clientDir.Dir("x64"), } -#Build nvdaHelper for needed architectures -for arch in env['targetArchitectures']: - archEnv = env.Clone(TARGET_ARCH = arch, HOST_ARCH = 'x86', tools = ['default', 'midl', 'msrpc']) - archEnv.SConscript('archBuild_sconscript',exports={'env':archEnv,'clientInstallDir':archClientInstallDirs[arch],'libInstallDir':archLibInstallDirs[arch]},variant_dir='build/%s'%arch) - +# Build nvdaHelper for needed architectures +for arch in env["targetArchitectures"]: + archEnv = env.Clone(TARGET_ARCH=arch, HOST_ARCH="x86", tools=["default", "midl", "msrpc"]) + archEnv.SConscript( + "archBuild_sconscript", + exports={ + "env": archEnv, + "clientInstallDir": archClientInstallDirs[arch], + "libInstallDir": archLibInstallDirs[arch], + }, + variant_dir="build/%s" % arch, + ) diff --git a/nvdaHelper/vbufBackends/adobeAcrobat/sconscript b/nvdaHelper/vbufBackends/adobeAcrobat/sconscript index 280ea63b0ce..d667c877e83 100644 --- a/nvdaHelper/vbufBackends/adobeAcrobat/sconscript +++ b/nvdaHelper/vbufBackends/adobeAcrobat/sconscript @@ -1,25 +1,27 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import([ - 'env', - 'acrobatAccessRPCStubs', -]) +Import( + [ + "env", + "acrobatAccessRPCStubs", + ] +) -adobeAcrobatBackendLib=[ +adobeAcrobatBackendLib = [ env.Object("adobeAcrobat.cpp"), - env.Object('_acrobatAccess_i',acrobatAccessRPCStubs[2]), + env.Object("_acrobatAccess_i", acrobatAccessRPCStubs[2]), ] -Return('adobeAcrobatBackendLib') +Return("adobeAcrobatBackendLib") diff --git a/nvdaHelper/vbufBackends/gecko_ia2/sconscript b/nvdaHelper/vbufBackends/gecko_ia2/sconscript index ebb01803c21..1809c3237c5 100644 --- a/nvdaHelper/vbufBackends/gecko_ia2/sconscript +++ b/nvdaHelper/vbufBackends/gecko_ia2/sconscript @@ -1,21 +1,23 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import([ - 'env', -]) +Import( + [ + "env", + ] +) -geckoBackendLib=env.Object("gecko_ia2.cpp") +geckoBackendLib = env.Object("gecko_ia2.cpp") -Return('geckoBackendLib') +Return("geckoBackendLib") diff --git a/nvdaHelper/vbufBackends/lotusNotesRichText/sconscript b/nvdaHelper/vbufBackends/lotusNotesRichText/sconscript index 8a7c36e5cf3..054a32fb1b6 100644 --- a/nvdaHelper/vbufBackends/lotusNotesRichText/sconscript +++ b/nvdaHelper/vbufBackends/lotusNotesRichText/sconscript @@ -1,21 +1,23 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import([ - 'env', -]) +Import( + [ + "env", + ] +) -lotusNotesRichTextBackendLib=env.Object("lotusNotesRichText.cpp") +lotusNotesRichTextBackendLib = env.Object("lotusNotesRichText.cpp") -Return('lotusNotesRichTextBackendLib') +Return("lotusNotesRichTextBackendLib") diff --git a/nvdaHelper/vbufBackends/mshtml/sconscript b/nvdaHelper/vbufBackends/mshtml/sconscript index be17a0e0235..b947852742e 100644 --- a/nvdaHelper/vbufBackends/mshtml/sconscript +++ b/nvdaHelper/vbufBackends/mshtml/sconscript @@ -1,24 +1,26 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import([ - 'env', -]) +Import( + [ + "env", + ] +) -mshtmlBackendLib=[ +mshtmlBackendLib = [ env.Object("mshtml.cpp"), env.Object("node.cpp"), ] -Return('mshtmlBackendLib') +Return("mshtmlBackendLib") diff --git a/nvdaHelper/vbufBackends/webKit/sconscript b/nvdaHelper/vbufBackends/webKit/sconscript index 099b9e74450..c0818656a01 100644 --- a/nvdaHelper/vbufBackends/webKit/sconscript +++ b/nvdaHelper/vbufBackends/webKit/sconscript @@ -1,21 +1,23 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2011-2016 NV Access Limited -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2011-2016 NV Access Limited +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -Import([ - 'env', -]) +Import( + [ + "env", + ] +) -webKitBackendLib=env.Object("webKit.cpp") +webKitBackendLib = env.Object("webKit.cpp") -Return('webKitBackendLib') +Return("webKitBackendLib") diff --git a/nvdaHelper/vbufBase/sconscript b/nvdaHelper/vbufBase/sconscript index a4407395854..9c5015dd75d 100644 --- a/nvdaHelper/vbufBase/sconscript +++ b/nvdaHelper/vbufBase/sconscript @@ -1,11 +1,16 @@ -Import([ - 'env', -]) +Import( + [ + "env", + ] +) -vbufBaseObjs=[env.Object(x) for x in ( +vbufBaseObjs = [ + env.Object(x) + for x in ( "storage.cpp", "utils.cpp", "backend.cpp", -)] + ) +] -Return('vbufBaseObjs') +Return("vbufBaseObjs") diff --git a/projectDocs/dev/developerGuide/conf.py b/projectDocs/dev/developerGuide/conf.py index 6a9bc6093e3..ac43e0256f8 100644 --- a/projectDocs/dev/developerGuide/conf.py +++ b/projectDocs/dev/developerGuide/conf.py @@ -9,6 +9,7 @@ import os import sys + _appDir = os.path.abspath(os.path.join("..", "..", "..", "source")) sys.path.insert(0, _appDir) @@ -23,11 +24,13 @@ # by comTypes. # This patch causes the error to be ignored, which matches the behavior at runtime. import monkeyPatches.comtypesMonkeyPatches # noqa: E402 + monkeyPatches.comtypesMonkeyPatches.replace_check_version() monkeyPatches.comtypesMonkeyPatches.appendComInterfacesToGenSearchPath() # Initialize languageHandler so that sphinx is able to deal with translatable strings. import languageHandler # noqa: E402 + languageHandler.setLanguage("en") # Initialize globalVars.appArgs to something sensible. @@ -47,6 +50,7 @@ # Import NVDA's versionInfo module. import versionInfo # noqa: E402 + # Set a suitable updateVersionType for the updateCheck module to be imported versionInfo.updateVersionType = "stable" @@ -68,17 +72,17 @@ # -- General configuration --------------------------------------------------- -default_role = 'py:obj' +default_role = "py:obj" # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', + "sphinx.ext.autodoc", ] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -100,7 +104,7 @@ # Both the class’ and the __init__ method’s docstring are concatenated and inserted. autoclass_content = "both" -autodoc_member_order = 'bysource' +autodoc_member_order = "bysource" autodoc_mock_imports = [ "louis", # Not our project ] @@ -110,5 +114,6 @@ from sphinx.ext.autodoc.mock import _make_subclass # noqa: E402 import config # noqa: E402 + # Mock an instance of the configuration manager. config.conf = _make_subclass("conf", "config")() diff --git a/projectDocs/dev/developerGuide/sconscript b/projectDocs/dev/developerGuide/sconscript index bfe60ef7be6..590727221f8 100644 --- a/projectDocs/dev/developerGuide/sconscript +++ b/projectDocs/dev/developerGuide/sconscript @@ -9,41 +9,39 @@ Import("env", "outputDir", "sourceDir") env = env.Clone() -devDocsOutputDir=outputDir.Dir('devDocs') +devDocsOutputDir = outputDir.Dir("devDocs") # Build the developer guide and move it to the output directory -htmlFile = env.md2html('developerGuide.md') +htmlFile = env.md2html("developerGuide.md") devGuide = env.Command( - target=devDocsOutputDir.File('developerGuide.html'), - source=htmlFile, - action=Move('$TARGET', '$SOURCE') + target=devDocsOutputDir.File("developerGuide.html"), source=htmlFile, action=Move("$TARGET", "$SOURCE") ) env.Alias("developerGuide", devGuide) -devDocs_nvdaHelper_temp=env.Doxygen(source='../../../nvdaHelper/doxyfile') +devDocs_nvdaHelper_temp = env.Doxygen(source="../../../nvdaHelper/doxyfile") devDocs_nvdaHelper = env.Command( - target=devDocsOutputDir.Dir('nvdaHelper'), + target=devDocsOutputDir.Dir("nvdaHelper"), source=devDocs_nvdaHelper_temp, - action=Move('$TARGET', '$SOURCE') + action=Move("$TARGET", "$SOURCE"), ) -env.Alias('devDocs_nvdaHelper', devDocs_nvdaHelper) -env.Clean('devDocs_nvdaHelper', devDocs_nvdaHelper) +env.Alias("devDocs_nvdaHelper", devDocs_nvdaHelper) +env.Clean("devDocs_nvdaHelper", devDocs_nvdaHelper) ignorePaths = [ - '_buildVersion.py', - 'comInterfaces', - 'images', - 'lib', - 'lib64', - 'libArm64', - 'locale', - 'louis', # Not our project - 'typelibs', - 'waves', + "_buildVersion.py", + "comInterfaces", + "images", + "lib", + "lib64", + "libArm64", + "locale", + "louis", # Not our project + "typelibs", + "waves", "mathType.py", # Fails when not installed - 'oleTypes.py', # Not our code - 'setup.py', # Py2exe - 'sourceEnv.py', # Only available when running from source + "oleTypes.py", # Not our code + "setup.py", # Py2exe + "sourceEnv.py", # Only available when running from source ] sphinxAPIDocs = env.Command( @@ -52,26 +50,33 @@ sphinxAPIDocs = env.Command( [ [ sys.executable, - "-m", "sphinx.ext.apidoc", + "-m", + "sphinx.ext.apidoc", # "--force", # overwrite existing files "-P", # Include private modules "--module-first", # put module documentation before submodule documentation - "--output-dir", "$TARGET", - "$SOURCE" # Module sources - ] + [f"{sourceDir}\\{f}" for f in ignorePaths] - ] + "--output-dir", + "$TARGET", + "$SOURCE", # Module sources + ] + + [f"{sourceDir}\\{f}" for f in ignorePaths] + ], ) sphinxHtml = env.Command( "_build", sphinxAPIDocs, - [[ - sys.executable, - "-m", "sphinx.cmd.build", - "-M", "html", - "projectDocs/dev/developerGuide", # Source directory - "$TARGET", # Build directory - ]] + [ + [ + sys.executable, + "-m", + "sphinx.cmd.build", + "-M", + "html", + "projectDocs/dev/developerGuide", # Source directory + "$TARGET", # Build directory + ] + ], ) -devDocs_nvda = env.Command(devDocsOutputDir.Dir('NVDA'), sphinxHtml, Move('$TARGET', '$SOURCE')) -env.Alias('devDocs', [devGuide, devDocs_nvda]) -env.Clean('devDocs', [devGuide, devDocs_nvda]) +devDocs_nvda = env.Command(devDocsOutputDir.Dir("NVDA"), sphinxHtml, Move("$TARGET", "$SOURCE")) +env.Alias("devDocs", [devGuide, devDocs_nvda]) +env.Clean("devDocs", [devGuide, devDocs_nvda]) diff --git a/sconstruct b/sconstruct index 75f3d2a3f01..4a6bb11628e 100755 --- a/sconstruct +++ b/sconstruct @@ -14,7 +14,7 @@ import sys # Ensure we are inside the Python virtual environment. nvdaVenv = os.getenv("NVDA_VENV") virtualEnv = os.getenv("VIRTUAL_ENV") -if not virtualEnv or not os.path.isdir(virtualEnv): +if not virtualEnv or not os.path.isdir(virtualEnv): print( "Error: SCons cannot detect the NVDA build system Python virtual environment.\n" "SCons must be executed using scons.bat in the root of this repository." @@ -37,46 +37,53 @@ if ( or installedPythonMinor != requiredPythonMinor ): unsupportedPythonMsg = ( - ("This script is started with Python %s.%s %s, however to build NVDA you have to use Python %s.%s %s.\n" + "This script is started with Python %s.%s %s, however to build NVDA you have to use Python %s.%s %s.\n" "Please install the needed version of Python and launch SCons again, or if you have multiple " - "versions of Python installed start this script with required version explicitly.") + "versions of Python installed start this script with required version explicitly." ) - raise RuntimeError(unsupportedPythonMsg %( - installedPythonMajor, - installedPythonMinor, - installedPythonArchitecture, - requiredPythonMajor, - requiredPythonMinor, - requiredPythonArchitecture + raise RuntimeError( + unsupportedPythonMsg + % ( + installedPythonMajor, + installedPythonMinor, + installedPythonArchitecture, + requiredPythonMajor, + requiredPythonMinor, + requiredPythonArchitecture, + ) ) - ) -sourceEnvPath = os.path.abspath(os.path.join(Dir('.').srcnode().path, "source")) +sourceEnvPath = os.path.abspath(os.path.join(Dir(".").srcnode().path, "source")) sys.path.append(sourceEnvPath) import sourceEnv # noqa: E402 + sys.path.remove(sourceEnvPath) import time # noqa: E402 import importlib.util # noqa: E402 import winreg # noqa: E402 -def recursiveCopy(env,targetDir,sourceDir): - targets=[] - for topDir,subDirs,files in os.walk(sourceDir.abspath): - relTopDir=os.path.relpath(topDir,sourceDir.abspath) + +def recursiveCopy(env, targetDir, sourceDir): + targets = [] + for topDir, subDirs, files in os.walk(sourceDir.abspath): + relTopDir = os.path.relpath(topDir, sourceDir.abspath) for f in files: - fNode=targetDir.Dir(relTopDir).File(f) - env.Command(fNode,Dir(topDir).File(f),Copy('$TARGET','$SOURCE')) + fNode = targetDir.Dir(relTopDir).File(f) + env.Command(fNode, Dir(topDir).File(f), Copy("$TARGET", "$SOURCE")) targets.append(fNode) - if len(files)==0: - dNode=targetDir.Dir(relTopDir) - env.Command(dNode,Dir(topDir),Mkdir('$TARGET')) + if len(files) == 0: + dNode = targetDir.Dir(relTopDir) + env.Command(dNode, Dir(topDir), Mkdir("$TARGET")) targets.append(dNode) return targets + # Import NVDA's versionInfo module. import gettext # noqa: E402 + gettext.install("nvda") sys.path.append("source") import versionInfo # noqa: E402 + del sys.path[-1] makensis = os.path.abspath(os.path.join("include", "nsis", "NSIS", "makensis.exe")) @@ -90,31 +97,70 @@ vars.Add("version", "The version of this build", versionInfo.version) vars.Add("version_build", "A unique number for this build.", "0") vars.Add(BoolVariable("release", "Whether this is a release version", False)) vars.Add("publisher", "The publisher of this build", versionInfo.publisher) -vars.Add("updateVersionType", "The version type for which to check for updates", versionInfo.updateVersionType or "") -vars.Add(PathVariable("certFile", "The certificate file with which to sign executables", "", - lambda key, val, env: not val or PathVariable.PathIsFile(key, val, env))) +vars.Add( + "updateVersionType", + "The version type for which to check for updates", + versionInfo.updateVersionType or "", +) +vars.Add( + PathVariable( + "certFile", + "The certificate file with which to sign executables", + "", + lambda key, val, env: not val or PathVariable.PathIsFile(key, val, env), + ) +) vars.Add("certPassword", "The password for the private key in the signing certificate", "") -vars.Add("certTimestampServer", "The URL of the timestamping server to use to timestamp authenticode signatures", "") +vars.Add( + "certTimestampServer", + "The URL of the timestamping server to use to timestamp authenticode signatures", + "", +) vars.Add("apiSigningToken", "The API key for the signing service", "") -vars.Add(PathVariable("outputDir", "The directory where the final built archives and such will be placed", "output",PathVariable.PathIsDirCreate)) -vars.Add(ListVariable("nvdaHelperDebugFlags", "a list of debugging features you require", 'none', ["debugCRT","RTC","analyze"])) -vars.Add(EnumVariable('nvdaHelperLogLevel','The level of logging you wish to see, lower is more verbose','15',allowed_values=[str(x) for x in range(60)])) - -#Base environment for this and sub sconscripts -env = Environment(variables=vars,HOST_ARCH='x86',tools=[ - "textfile", - "gettextTool", - "md2html", - "doxygen", - "recursiveInstall", - "m4", -]) +vars.Add( + PathVariable( + "outputDir", + "The directory where the final built archives and such will be placed", + "output", + PathVariable.PathIsDirCreate, + ) +) +vars.Add( + ListVariable( + "nvdaHelperDebugFlags", + "a list of debugging features you require", + "none", + ["debugCRT", "RTC", "analyze"], + ) +) +vars.Add( + EnumVariable( + "nvdaHelperLogLevel", + "The level of logging you wish to see, lower is more verbose", + "15", + allowed_values=[str(x) for x in range(60)], + ) +) + +# Base environment for this and sub sconscripts +env = Environment( + variables=vars, + HOST_ARCH="x86", + tools=[ + "textfile", + "gettextTool", + "md2html", + "doxygen", + "recursiveInstall", + "m4", + ], +) # speed up subsequent runs by checking timestamps of targets and dependencies, and only using md5 if timestamps differ. -env.Decider('MD5-timestamp') +env.Decider("MD5-timestamp") # Warn to run the build on multiple threads so it runs faster -numJobs = env.GetOption('num_jobs') +numJobs = env.GetOption("num_jobs") numCores = multiprocessing.cpu_count() if numJobs < numCores: print( @@ -125,22 +171,22 @@ if numJobs < numCores: else: print(f"Building with {numJobs} concurrent jobs") -#Make our recursiveCopy function available to any script using this environment +# Make our recursiveCopy function available to any script using this environment env.AddMethod(recursiveCopy) -#Check for any unknown variables -unknown=vars.UnknownVariables().keys() -if len(unknown)>0: - print("Unknown commandline variables: %s"%unknown) +# Check for any unknown variables +unknown = vars.UnknownVariables().keys() +if len(unknown) > 0: + print("Unknown commandline variables: %s" % unknown) Exit(1) -#Ensure that any Python subprocesses (such as for py2exe) can find our Python directory in miscDeps -env['ENV']['PYTHONPATH']=";".join(sourceEnv.PYTHON_DIRS) +# Ensure that any Python subprocesses (such as for py2exe) can find our Python directory in miscDeps +env["ENV"]["PYTHONPATH"] = ";".join(sourceEnv.PYTHON_DIRS) -env["copyright"]=versionInfo.copyright -env['version_year']=versionInfo.version_year -env['version_major']=versionInfo.version_major -env['version_minor']=versionInfo.version_minor +env["copyright"] = versionInfo.copyright +env["version_year"] = versionInfo.version_year +env["version_major"] = versionInfo.version_major +env["version_minor"] = versionInfo.version_minor version = env["version"] version_build = env["version_build"] release = env["release"] @@ -149,113 +195,133 @@ certFile = env["certFile"] certPassword = env["certPassword"] certTimestampServer = env["certTimestampServer"] apiSigningToken = env["apiSigningToken"] -userDocsDir=Dir('user_docs') +userDocsDir = Dir("user_docs") sourceDir = env.Dir("source") -Export('sourceDir') -clientDir=Dir('extras/controllerClient') -Export('clientDir') -sourceLibDir=sourceDir.Dir('lib') -Export('sourceLibDir') -sourceTypelibDir=sourceDir.Dir('typelibs') -Export('sourceTypelibDir') -sourceLibDir64=sourceDir.Dir('lib64') -Export('sourceLibDir64') -sourceLibDirArm64=sourceDir.Dir('libArm64') -Export('sourceLibDirArm64') +Export("sourceDir") +clientDir = Dir("extras/controllerClient") +Export("clientDir") +sourceLibDir = sourceDir.Dir("lib") +Export("sourceLibDir") +sourceTypelibDir = sourceDir.Dir("typelibs") +Export("sourceTypelibDir") +sourceLibDir64 = sourceDir.Dir("lib64") +Export("sourceLibDir64") +sourceLibDirArm64 = sourceDir.Dir("libArm64") +Export("sourceLibDirArm64") buildDir = Dir("build") outFilePrefix = "nvda{type}_{version}".format(type="" if release else "_snapshot", version=version) -Export('outFilePrefix') -outputDir=Dir(env['outputDir']) -Export('outputDir') +Export("outFilePrefix") +outputDir = Dir(env["outputDir"]) +Export("outputDir") -assert not (apiSigningToken and certFile), "Cannot specify signing with both API token (cloud) and local certificate" +assert not ( + apiSigningToken and certFile +), "Cannot specify signing with both API token (cloud) and local certificate" if apiSigningToken: - # Code signing with SignPath HSM + # Code signing with SignPath HSM def signExecApi(target, source, env): if len(target) > 1: print(f"Iterating through {len(target)} files passed to signExecApi") - retval = 1 # error value + retval = 1 # error value for targetFile in target: if (abspath := targetFile.abspath).endswith((".exe", ".dll")): ps_cmd = f"powershell -File appveyor\scripts\sign.ps1 -ApiToken {apiSigningToken} -FileToSign {abspath}" if (retval := env.Execute(ps_cmd, shell=True)) != 0: print(f"Error signing file: {abspath}") return retval + # Export via scons environment so other libraries can be signed env["signExec"] = signExecApi elif certFile: # Local code signing with a certFile - def signExecCert(target,source,env): - # we encrypt with SHA256 as this is the minimum required by the Windows Store for appx packages + def signExecCert(target, source, env): + # we encrypt with SHA256 as this is the minimum required by the Windows Store for appx packages signExecCmd = ["signtool", "sign", "/fd", "SHA256", "/f", certFile] if certPassword: signExecCmd.extend(("/p", certPassword)) if certTimestampServer: signExecCmd.extend(("/tr", certTimestampServer, "/td", "SHA256")) print([str(x) for x in target]) - # #3795: signtool can quite commonly fail with timestamping, so allow it to try up to 3 times with a 1 second delay between each try. - res=0 + # #3795: signtool can quite commonly fail with timestamping, so allow it to try up to 3 times with a 1 second delay between each try. + res = 0 for count in range(3): - res=env.Execute([signExecCmd+[target[0].abspath]]) + res = env.Execute([signExecCmd + [target[0].abspath]]) if not res: - return 0 # success + return 0 # success time.sleep(1) - return res # failed - #Export via scons environment so other libraries can be signed - env["signExec"] = signExecCert - -#architecture-specific environments -archTools=['default','midl','msrpc'] -env32=env.Clone(TARGET_ARCH='x86',tools=archTools) -env64=env.Clone(TARGET_ARCH='x86_64',tools=archTools) -envArm64=env.Clone(TARGET_ARCH='arm64',tools=archTools) + return res # failed + + # Export via scons environment so other libraries can be signed + env["signExec"] = signExecCert + +# architecture-specific environments +archTools = ["default", "midl", "msrpc"] +env32 = env.Clone(TARGET_ARCH="x86", tools=archTools) +env64 = env.Clone(TARGET_ARCH="x86_64", tools=archTools) +envArm64 = env.Clone(TARGET_ARCH="arm64", tools=archTools) # Hack around odd bug where some tool [after] msvc states that static and shared objects are different -env32['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 -env64['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 -envArm64['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 - -env=env32 - -projectRCSubstDict={ - '%version_year%':env['version_year'], - '%version_major%':env['version_major'], - '%version_minor%':env['version_minor'], - '%version_build%':env['version_build'], - '%copyright%':env['copyright'], - '%publisher%':env['publisher'], - '%version%':env['version'], - '%productName%':"%s (%s)"%(versionInfo.name,versionInfo.longName), +env32["STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME"] = 1 +env64["STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME"] = 1 +envArm64["STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME"] = 1 + +env = env32 + +projectRCSubstDict = { + "%version_year%": env["version_year"], + "%version_major%": env["version_major"], + "%version_minor%": env["version_minor"], + "%version_build%": env["version_build"], + "%copyright%": env["copyright"], + "%publisher%": env["publisher"], + "%version%": env["version"], + "%productName%": "%s (%s)" % (versionInfo.name, versionInfo.longName), } -resFile=env.RES(target='build/nvda.res', - source=env.Substfile(target='build/nvda.rc', source='nvdaHelper/nvda.rc.subst', SUBST_DICT=projectRCSubstDict)) -env32['projectResFile'] = resFile -env64['projectResFile'] = resFile -envArm64['projectResFile'] = resFile - -#Fill sourceDir with anything provided for it by miscDeps -env.recursiveCopy(sourceDir,Dir('miscdeps/source')) +resFile = env.RES( + target="build/nvda.res", + source=env.Substfile( + target="build/nvda.rc", source="nvdaHelper/nvda.rc.subst", SUBST_DICT=projectRCSubstDict + ), +) +env32["projectResFile"] = resFile +env64["projectResFile"] = resFile +envArm64["projectResFile"] = resFile + +# Fill sourceDir with anything provided for it by miscDeps +env.recursiveCopy(sourceDir, Dir("miscdeps/source")) # Copy in some other dependencies. jabDll = "windowsaccessbridge-32.dll" -Command(sourceLibDir.File(jabDll), - env.Dir("#include/javaAccessBridge32").File(jabDll), - Copy("$TARGET", "$SOURCE")) +Command( + sourceLibDir.File(jabDll), env.Dir("#include/javaAccessBridge32").File(jabDll), Copy("$TARGET", "$SOURCE") +) -env.SConscript('source/comInterfaces_sconscript',exports=['env']) +env.SConscript("source/comInterfaces_sconscript", exports=["env"]) -#Process nvdaHelper scons files -env32.SConscript('nvdaHelper/archBuild_sconscript',exports={'env':env32,'clientInstallDir':clientDir.Dir('x86'),'libInstallDir':sourceLibDir},variant_dir='build/x86') -env64.SConscript('nvdaHelper/archBuild_sconscript',exports={'env':env64,'clientInstallDir':clientDir.Dir('x64'),'libInstallDir':sourceLibDir64},variant_dir='build/x86_64') -envArm64.SConscript('nvdaHelper/archBuild_sconscript',exports={'env':envArm64,'clientInstallDir':clientDir.Dir('arm64'),'libInstallDir':sourceLibDirArm64},variant_dir='build/arm64') +# Process nvdaHelper scons files +env32.SConscript( + "nvdaHelper/archBuild_sconscript", + exports={"env": env32, "clientInstallDir": clientDir.Dir("x86"), "libInstallDir": sourceLibDir}, + variant_dir="build/x86", +) +env64.SConscript( + "nvdaHelper/archBuild_sconscript", + exports={"env": env64, "clientInstallDir": clientDir.Dir("x64"), "libInstallDir": sourceLibDir64}, + variant_dir="build/x86_64", +) +envArm64.SConscript( + "nvdaHelper/archBuild_sconscript", + exports={"env": envArm64, "clientInstallDir": clientDir.Dir("arm64"), "libInstallDir": sourceLibDirArm64}, + variant_dir="build/arm64", +) -#Allow all NVDA's gettext po files to be compiled in source/locale -for po in env.Glob(sourceDir.path+'/locale/*/lc_messages/*.po'): +# Allow all NVDA's gettext po files to be compiled in source/locale +for po in env.Glob(sourceDir.path + "/locale/*/lc_messages/*.po"): env.gettextMoFile(po) -styles = os.path.join(userDocsDir.path, 'styles.css') +styles = os.path.join(userDocsDir.path, "styles.css") numberedHeadingsStyle = os.path.join(userDocsDir.path, "numberedHeadings.css") # Allow all markdown files to be converted to html in user_docs -for mdFile in env.Glob(os.path.join(userDocsDir.path, '*', '*.md')): +for mdFile in env.Glob(os.path.join(userDocsDir.path, "*", "*.md")): htmlFile = env.md2html(mdFile) styleInstallPath = os.path.dirname(mdFile.abspath) installedStyle = env.Install(styleInstallPath, styles) @@ -267,17 +333,20 @@ for mdFile in env.Glob(os.path.join(userDocsDir.path, '*', '*.md')): installedStyle, numberedHeadingsStyle, installedHeadingsStyle, - ] + ], ) env.Depends(htmlFile, mdFile) # Create key commands files -for userGuideFile in env.Glob(os.path.join(userDocsDir.path, '*', 'userGuide.md')): - keyCommandsHtmlFile = env.md2html(userGuideFile.abspath.replace("userGuide.md", "keyCommands.html"), userGuideFile) +for userGuideFile in env.Glob(os.path.join(userDocsDir.path, "*", "userGuide.md")): + keyCommandsHtmlFile = env.md2html( + userGuideFile.abspath.replace("userGuide.md", "keyCommands.html"), userGuideFile + ) env.Depends(keyCommandsHtmlFile, userGuideFile) # Build unicode CLDR dictionaries -env.SConscript('cldrDict_sconscript',exports=['env', 'sourceDir']) +env.SConscript("cldrDict_sconscript", exports=["env", "sourceDir"]) + # A builder to generate an NVDA distribution. def NVDADistGenerator(target, source, env, for_signature): @@ -287,16 +356,22 @@ def NVDADistGenerator(target, source, env, for_signature): # and py2exe will cause bytecode files to be created for it which scons doesn't know about. updateVersionType = env["updateVersionType"] or None # Any '\n' characters written are translated to the system default line separator, os.linesep. - action = [lambda target, source, env: open(buildVersionFn, "w", encoding="utf-8").write( - 'version = {version!r}\n' - 'publisher = {publisher!r}\n' - 'updateVersionType = {updateVersionType!r}\n' - 'version_build = {version_build!r}\n' - .format(version=version, publisher=publisher, updateVersionType=updateVersionType,version_build=version_build) - ) - # In Python 3 write returns the number of characters written, - # which scons treats as an error code. - and None] + action = [ + lambda target, source, env: open(buildVersionFn, "w", encoding="utf-8").write( + "version = {version!r}\n" + "publisher = {publisher!r}\n" + "updateVersionType = {updateVersionType!r}\n" + "version_build = {version_build!r}\n".format( + version=version, + publisher=publisher, + updateVersionType=updateVersionType, + version_build=version_build, + ) + ) + # In Python 3 write returns the number of characters written, + # which scons treats as an error code. + and None + ] buildCmd = ["cd", source[0].path, "&&", sys.executable] if release: @@ -312,16 +387,21 @@ def NVDADistGenerator(target, source, env, for_signature): # #10031: Apps written in Python 3 require Universal CRT to be installed. We cannot assume users have it on their systems. # Therefore , copy required libraries from Windows 10 SDK. try: - with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0', 0,winreg.KEY_READ|winreg.KEY_WOW64_32KEY) as SDKKey: - sdk_installationFolder = winreg.QueryValueEx(SDKKey, 'InstallationFolder')[0] - sdk_productVersion = winreg.QueryValueEx(SDKKey, 'ProductVersion')[0] + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0", + 0, + winreg.KEY_READ | winreg.KEY_WOW64_32KEY, + ) as SDKKey: + sdk_installationFolder = winreg.QueryValueEx(SDKKey, "InstallationFolder")[0] + sdk_productVersion = winreg.QueryValueEx(SDKKey, "ProductVersion")[0] except WindowsError: raise RuntimeError("Windows 10 SDK not found") # The Universal CRT should be in an SDK version-specific directory - # But usually has a '.0' appended after the productVersion found in the registry. + # But usually has a '.0' appended after the productVersion found in the registry. # E.g. 10.0.1941 might e actually 10.0.1941.0. # Thus try both. - CRTDir = os.path.join(sdk_installationFolder, "Redist", sdk_productVersion+".0", "ucrt", "DLLs", "x86") + CRTDir = os.path.join(sdk_installationFolder, "Redist", sdk_productVersion + ".0", "ucrt", "DLLs", "x86") if not os.path.isdir(CRTDir): CRTDir = os.path.join(sdk_installationFolder, "Redist", sdk_productVersion, "ucrt", "DLLs", "x86") if not os.path.isdir(CRTDir): @@ -333,16 +413,20 @@ def NVDADistGenerator(target, source, env, for_signature): if certFile or apiSigningToken: for prog in "nvda_noUIAccess.exe", "nvda_uiAccess.exe", "nvda_slave.exe": - action.append(lambda target, source, env, progByVal=prog: env['signExec']([target[0].File(progByVal)], source, env)) + action.append( + lambda target, source, env, progByVal=prog: env["signExec"]( + [target[0].File(progByVal)], source, env + ) + ) - action.extend(( - Delete(buildVersionFn), - Delete(importlib.util.cache_from_source(buildVersionFn)) - )) + action.extend((Delete(buildVersionFn), Delete(importlib.util.cache_from_source(buildVersionFn)))) return action + + env["BUILDERS"]["NVDADist"] = Builder(generator=NVDADistGenerator, target_factory=Dir) + # A builder to generate a zip archive. # We roll our own instead of using env.Zip because we want to create some archives # relative to a specified directory. @@ -350,6 +434,7 @@ def ZipArchiveAction(target, source, env): relativeTo = env.get("relativeTo", None) if relativeTo: relativeTo = relativeTo.path + def getArcName(origName): arcName = os.path.relpath(origName, relativeTo) if arcName.startswith(".."): @@ -361,10 +446,12 @@ def ZipArchiveAction(target, source, env): # Nasty hack to make zipfile use best compression, since it isn't configurable. # Tried setting memlevel to 9 as well, but it made compression slightly worse. import zlib + origZDefComp = zlib.Z_DEFAULT_COMPRESSION zlib.Z_DEFAULT_COMPRESSION = zlib.Z_BEST_COMPRESSION import zipfile + zf = None try: zf = zipfile.ZipFile(target[0].path, "w", zipfile.ZIP_DEFLATED) @@ -384,21 +471,36 @@ def ZipArchiveAction(target, source, env): zf.close() zlib.Z_DEFAULT_COMPRESSION = origZDefComp + env["BUILDERS"]["ZipArchive"] = Builder(action=ZipArchiveAction) -uninstFile=File("dist/uninstall.exe") -uninstGen = env.Command(File("uninstaller/uninstGen.exe"), "uninstaller/uninst.nsi", - [[makensis, "/V2", - "/DVERSION=$version", '/DPUBLISHER="$publisher"','/DCOPYRIGHT="$copyright"','/DVERSION_YEAR="$version_year"','/DVERSION_MAJOR="$version_major"','/DVERSION_MINOR="$version_minor"','/DVERSION_BUILD="$version_build"', - "/DUNINSTEXE=%s"%uninstFile.abspath, - "/DINSTEXE=${TARGET.abspath}", - "$SOURCE"]]) -uninstaller=env.Command(uninstFile,uninstGen,[uninstGen]) +uninstFile = File("dist/uninstall.exe") +uninstGen = env.Command( + File("uninstaller/uninstGen.exe"), + "uninstaller/uninst.nsi", + [ + [ + makensis, + "/V2", + "/DVERSION=$version", + '/DPUBLISHER="$publisher"', + '/DCOPYRIGHT="$copyright"', + '/DVERSION_YEAR="$version_year"', + '/DVERSION_MAJOR="$version_major"', + '/DVERSION_MINOR="$version_minor"', + '/DVERSION_BUILD="$version_build"', + "/DUNINSTEXE=%s" % uninstFile.abspath, + "/DINSTEXE=${TARGET.abspath}", + "$SOURCE", + ] + ], +) +uninstaller = env.Command(uninstFile, uninstGen, [uninstGen]) if certFile or apiSigningToken: - env.AddPostAction(uninstaller, [env['signExec']]) + env.AddPostAction(uninstaller, [env["signExec"]]) -dist = env.NVDADist("dist", [sourceDir,userDocsDir], uiAccess=bool(certFile) or bool(apiSigningToken)) -env.Depends(dist,uninstaller) +dist = env.NVDADist("dist", [sourceDir, userDocsDir], uiAccess=bool(certFile) or bool(apiSigningToken)) +env.Depends(dist, uninstaller) # dist will always be considered obsolete AlwaysBuild(dist) # Dir node targets don't get cleaned, so cleaning of the dist nodes has to be explicitly specified. @@ -406,74 +508,104 @@ env.Clean(dist, dist) # Clean the intermediate build directory. env.Clean([dist], buildDir) -launcher = env.Command(outputDir.File("%s.exe" % outFilePrefix), ["launcher/nvdaLauncher.nsi", dist], - [[makensis, "/V2", - "/DVERSION=$version", '/DPUBLISHER="$publisher"','/DCOPYRIGHT="$copyright"','/DVERSION_YEAR="$version_year"','/DVERSION_MAJOR="$version_major"','/DVERSION_MINOR="$version_minor"','/DVERSION_BUILD="$version_build"', - "/DNVDADistDir=${SOURCES[1].abspath}", "/DLAUNCHEREXE=${TARGET.abspath}", - "$SOURCE"]]) +launcher = env.Command( + outputDir.File("%s.exe" % outFilePrefix), + ["launcher/nvdaLauncher.nsi", dist], + [ + [ + makensis, + "/V2", + "/DVERSION=$version", + '/DPUBLISHER="$publisher"', + '/DCOPYRIGHT="$copyright"', + '/DVERSION_YEAR="$version_year"', + '/DVERSION_MAJOR="$version_major"', + '/DVERSION_MINOR="$version_minor"', + '/DVERSION_BUILD="$version_build"', + "/DNVDADistDir=${SOURCES[1].abspath}", + "/DLAUNCHEREXE=${TARGET.abspath}", + "$SOURCE", + ] + ], +) if certFile or apiSigningToken: - env.AddPostAction(launcher, [env['signExec']]) + env.AddPostAction(launcher, [env["signExec"]]) env.Alias("launcher", launcher) -clientArchive = env.ZipArchive(outputDir.File("%s_controllerClient.zip" % outFilePrefix), clientDir, relativeTo=clientDir) +clientArchive = env.ZipArchive( + outputDir.File("%s_controllerClient.zip" % outFilePrefix), clientDir, relativeTo=clientDir +) env.Alias("client", clientArchive) outputStylesFile = env.Command( - outputDir.File("styles.css"), - userDocsDir.File("styles.css"), - Copy("$TARGET", "$SOURCE") + outputDir.File("styles.css"), userDocsDir.File("styles.css"), Copy("$TARGET", "$SOURCE") ) outputHeadingStylesFile = env.Command( outputDir.File("numberedHeadings.css"), userDocsDir.File("numberedHeadings.css"), - Copy("$TARGET", "$SOURCE") + Copy("$TARGET", "$SOURCE"), +) +changesFile = env.Command( + outputDir.File("%s_changes.html" % outFilePrefix), + userDocsDir.File("en/changes.html"), + Copy("$TARGET", "$SOURCE"), ) -changesFile=env.Command(outputDir.File("%s_changes.html" % outFilePrefix),userDocsDir.File('en/changes.html'),Copy('$TARGET','$SOURCE')) env.Depends(changesFile, outputStylesFile) -env.Alias('changes',changesFile) +env.Alias("changes", changesFile) -userGuideFile=env.Command(outputDir.File("userGuide.html"),userDocsDir.File('en/userGuide.html'),Copy('$TARGET','$SOURCE')) +userGuideFile = env.Command( + outputDir.File("userGuide.html"), userDocsDir.File("en/userGuide.html"), Copy("$TARGET", "$SOURCE") +) env.Depends(userGuideFile, outputStylesFile) -env.Alias('userGuide', userGuideFile) +env.Alias("userGuide", userGuideFile) keyCommandsFile = env.Command( - outputDir.File("keyCommands.html"), - userDocsDir.File('en/keyCommands.html'), - Copy('$TARGET', '$SOURCE') + outputDir.File("keyCommands.html"), userDocsDir.File("en/keyCommands.html"), Copy("$TARGET", "$SOURCE") ) env.Depends(keyCommandsFile, outputStylesFile) env.Depends(keyCommandsFile, userGuideFile) -env.Alias('keyCommands', keyCommandsFile) +env.Alias("keyCommands", keyCommandsFile) + def makePotSourceFileList(target, sourceFiles, env): - potSourceFiles = [ - os.path.relpath(str(f), str(sourceDir)) for f in sourceFiles - ] + potSourceFiles = [os.path.relpath(str(f), str(sourceDir)) for f in sourceFiles] with open(target.abspath, "w") as fileList: - fileList.writelines([f + '\n' for f in potSourceFiles]) + fileList.writelines([f + "\n" for f in potSourceFiles]) def makePot(target, source, env): potSourceFileList = outputDir.File("potSourceFileList.txt") makePotSourceFileList(potSourceFileList, source, env) # Generate the pot. - if env.Execute([ - [ - "cd", sourceDir, "&&", - XGETTEXT, - "-o", target[0].abspath, - "--package-name", versionInfo.name, "--package-version", version, - "--foreign-user", - "--add-comments=Translators:", - "--keyword=pgettext:1c,2", - "--keyword=npgettext:1c,2,3", - "--from-code", "utf-8", - # Needed because xgettext doesn't recognise the .pyw extension. - "--language=python", - # Too many files to list on commandline, use a file list instead. - f"--files-from={potSourceFileList.abspath}", - ] - ]) != 0: + if ( + env.Execute( + [ + [ + "cd", + sourceDir, + "&&", + XGETTEXT, + "-o", + target[0].abspath, + "--package-name", + versionInfo.name, + "--package-version", + version, + "--foreign-user", + "--add-comments=Translators:", + "--keyword=pgettext:1c,2", + "--keyword=npgettext:1c,2,3", + "--from-code", + "utf-8", + # Needed because xgettext doesn't recognise the .pyw extension. + "--language=python", + # Too many files to list on commandline, use a file list instead. + f"--files-from={potSourceFileList.abspath}", + ] + ] + ) + != 0 + ): raise RuntimeError("xgettext failed") # Tweak the headers. @@ -506,7 +638,8 @@ def getSubDirs(path): potSourceFiles = [ # Don't use sourceDir as the source, as this depends on comInterfaces and nvdaHelper. # We only depend on the Python files. - f for recurseDirs in getSubDirs(sourceDir.path) + f + for recurseDirs in getSubDirs(sourceDir.path) if not ( # Exclude comInterfaces, since these don't contain translatable strings # and they cause unknown encoding warnings. @@ -514,32 +647,36 @@ potSourceFiles = [ # Exclude userConfig folder which does not contain NVDA code but may contain gettext call without # translator comments in add-ons or scratchpad, triggering false positive for checkpot script. or recurseDirs.startswith(r"source\userConfig") - ) + ) for pattern in ("*.py", "*.pyw") for f in env.Glob( os.path.join(recurseDirs, pattern), ) ] -pot = env.Command( - outputDir.File("nvda.pot"), - potSourceFiles, - makePot -) +pot = env.Command(outputDir.File("nvda.pot"), potSourceFiles, makePot) env.Alias("pot", pot) -symbolsList=[] -symbolsList.extend(env.Glob(os.path.join(sourceLibDir.path,'*.pdb'))) -symbolsList.extend(env.Glob(os.path.join(sourceLibDir64.path,'*.pdb'))) +symbolsList = [] +symbolsList.extend(env.Glob(os.path.join(sourceLibDir.path, "*.pdb"))) +symbolsList.extend(env.Glob(os.path.join(sourceLibDir64.path, "*.pdb"))) symbolsArchive = env.ZipArchive(outputDir.File("%s_debugSymbols.zip" % outFilePrefix), symbolsList) env.Alias("symbolsArchive", symbolsArchive) -appx_storeSubmission=env.SConscript("appx/sconscript",exports={'env':env,'isStoreSubmission':True},variant_dir='build\\appx_storeSubmission') -installed_appx_storeSubmission=env.Install('output',appx_storeSubmission) -appx_sideLoadable=env.SConscript("appx/sconscript",exports={'env':env,'isStoreSubmission':False},variant_dir='build\\appx_sideLoadable') -installed_appx_sideLoadable=env.Install('output',appx_sideLoadable) -env.Alias('appx',[installed_appx_storeSubmission,installed_appx_sideLoadable]) +appx_storeSubmission = env.SConscript( + "appx/sconscript", + exports={"env": env, "isStoreSubmission": True}, + variant_dir="build\\appx_storeSubmission", +) +installed_appx_storeSubmission = env.Install("output", appx_storeSubmission) +appx_sideLoadable = env.SConscript( + "appx/sconscript", + exports={"env": env, "isStoreSubmission": False}, + variant_dir="build\\appx_sideLoadable", +) +installed_appx_sideLoadable = env.Install("output", appx_sideLoadable) +env.Alias("appx", [installed_appx_storeSubmission, installed_appx_sideLoadable]) env.Default(dist) diff --git a/site_scons/site_tools/doxygen.py b/site_scons/site_tools/doxygen.py index cc6827f897f..e28d560459b 100644 --- a/site_scons/site_tools/doxygen.py +++ b/site_scons/site_tools/doxygen.py @@ -1,10 +1,10 @@ # # Copyright (C) 2005, 2006 Matthew A. Nicholson # Copyright (C) 2006 Tim Blechmann -#Copyright (C) 2011 Michael Curran -#Copyright (C) 2014 Alberto Buffolino -#Copyright (C) 2016 Babbage B.V. -#Based on code from http://www.scons.org/wiki/DoxygenBuilder +# Copyright (C) 2011 Michael Curran +# Copyright (C) 2014 Alberto Buffolino +# Copyright (C) 2016 Babbage B.V. +# Based on code from http://www.scons.org/wiki/DoxygenBuilder # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public @@ -26,197 +26,242 @@ from functools import reduce import winreg + def fetchDoxygenPath(): try: - with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\doxygen_is1", 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as doxygenKey: - doxygenPath= '"%s"'%os.path.join(winreg.QueryValueEx(doxygenKey, "InstallLocation")[0], "Bin", "doxygen.exe") + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\doxygen_is1", + 0, + winreg.KEY_READ | winreg.KEY_WOW64_64KEY, + ) as doxygenKey: + doxygenPath = '"%s"' % os.path.join( + winreg.QueryValueEx(doxygenKey, "InstallLocation")[0], + "Bin", + "doxygen.exe", + ) except WindowsError: - return 'doxygen' + return "doxygen" return doxygenPath + def DoxyfileParse(file_contents): - """ - Parse a Doxygen source file and return a dictionary of all the values. - Values will be strings and lists of strings. - """ - data = {} - - import shlex - lex = shlex.shlex(instream = file_contents, posix = True) - lex.wordchars += "*+./-:" - lex.whitespace = lex.whitespace.replace("\n", "") - lex.escape = "" - - lineno = lex.lineno # noqa: F841 - token = lex.get_token() - key = token # the first token should be a key - last_token = "" - key_token = False - next_key = False # noqa: F841 - new_data = True - - def append_data(data, key, new_data, token): - if new_data or len(data[key]) == 0: - data[key].append(token) - else: - data[key][-1] += token - - while token: - if token in ['\n']: - if last_token not in ['\\']: - key_token = True - elif token in ['\\']: - pass - elif key_token: - key = token - key_token = False - else: - if token == "+=": - if key not in data: - data[key] = list() - elif token == "=": - data[key] = list() - else: - append_data( data, key, new_data, token) - new_data = True - - last_token = token - token = lex.get_token() - - if last_token == '\\' and token != '\n': - new_data = False - append_data( data, key, new_data, '\\') - - # compress lists of len 1 into single strings - # Wrap items into a list, since we're mutating the dictionary - for (k, v) in list(data.items()): - if len(v) == 0: - data.pop(k) - - # items in the following list will be kept as lists and not converted to strings - if k in ["INPUT", "FILE_PATTERNS", "EXCLUDE_PATTERNS"]: - continue - - if len(v) == 1: - data[k] = v[0] - - return data + """ + Parse a Doxygen source file and return a dictionary of all the values. + Values will be strings and lists of strings. + """ + data = {} + + import shlex + + lex = shlex.shlex(instream=file_contents, posix=True) + lex.wordchars += "*+./-:" + lex.whitespace = lex.whitespace.replace("\n", "") + lex.escape = "" + + lineno = lex.lineno # noqa: F841 + token = lex.get_token() + key = token # the first token should be a key + last_token = "" + key_token = False + next_key = False # noqa: F841 + new_data = True + + def append_data(data, key, new_data, token): + if new_data or len(data[key]) == 0: + data[key].append(token) + else: + data[key][-1] += token + + while token: + if token in ["\n"]: + if last_token not in ["\\"]: + key_token = True + elif token in ["\\"]: + pass + elif key_token: + key = token + key_token = False + else: + if token == "+=": + if key not in data: + data[key] = list() + elif token == "=": + data[key] = list() + else: + append_data(data, key, new_data, token) + new_data = True + + last_token = token + token = lex.get_token() + + if last_token == "\\" and token != "\n": + new_data = False + append_data(data, key, new_data, "\\") + + # compress lists of len 1 into single strings + # Wrap items into a list, since we're mutating the dictionary + for k, v in list(data.items()): + if len(v) == 0: + data.pop(k) + + # items in the following list will be kept as lists and not converted to strings + if k in ["INPUT", "FILE_PATTERNS", "EXCLUDE_PATTERNS"]: + continue + + if len(v) == 1: + data[k] = v[0] + + return data + def DoxySourceScan(node, env, path): - """ - Doxygen Doxyfile source scanner. This should scan the Doxygen file and add - any files used to generate docs to the list of source files. - """ - default_file_patterns = [ - '*.c', '*.cc', '*.cxx', '*.cpp', '*.c++', '*.java', '*.ii', '*.ixx', - '*.ipp', '*.i++', '*.inl', '*.h', '*.hh ', '*.hxx', '*.hpp', '*.h++', - '*.idl', '*.odl', '*.cs', '*.php', '*.php3', '*.inc', '*.m', '*.mm', - '*.py', - ] - - default_exclude_patterns = [ - '*~', - ] - - sources = [] - - with open(node.abspath) as contents: - data = DoxyfileParse(contents) - - if data.get("RECURSIVE", "NO") == "YES": - recursive = True - else: - recursive = False - - file_patterns = data.get("FILE_PATTERNS", default_file_patterns) - exclude_patterns = data.get("EXCLUDE_PATTERNS", default_exclude_patterns) - - for node in data.get("INPUT", []): - if os.path.isfile(node): - sources.append(node) - elif os.path.isdir(node): - if recursive: - for root, dirs, files in os.walk(node): - for f in files: - filename = os.path.join(root, f) - - pattern_check = reduce(lambda x, y: x or bool(fnmatch(filename, y)), file_patterns, False) - exclude_check = reduce(lambda x, y: x and fnmatch(filename, y), exclude_patterns, True) - - if pattern_check and not exclude_check: - sources.append(filename) - else: - for pattern in file_patterns: - sources.extend(glob.glob("/".join([node, pattern]))) - - sources = [env.File(path) for path in sources] - return sources + """ + Doxygen Doxyfile source scanner. This should scan the Doxygen file and add + any files used to generate docs to the list of source files. + """ + default_file_patterns = [ + "*.c", + "*.cc", + "*.cxx", + "*.cpp", + "*.c++", + "*.java", + "*.ii", + "*.ixx", + "*.ipp", + "*.i++", + "*.inl", + "*.h", + "*.hh ", + "*.hxx", + "*.hpp", + "*.h++", + "*.idl", + "*.odl", + "*.cs", + "*.php", + "*.php3", + "*.inc", + "*.m", + "*.mm", + "*.py", + ] + + default_exclude_patterns = [ + "*~", + ] + + sources = [] + + with open(node.abspath) as contents: + data = DoxyfileParse(contents) + + if data.get("RECURSIVE", "NO") == "YES": + recursive = True + else: + recursive = False + + file_patterns = data.get("FILE_PATTERNS", default_file_patterns) + exclude_patterns = data.get("EXCLUDE_PATTERNS", default_exclude_patterns) + + for node in data.get("INPUT", []): + if os.path.isfile(node): + sources.append(node) + elif os.path.isdir(node): + if recursive: + for root, dirs, files in os.walk(node): + for f in files: + filename = os.path.join(root, f) + + pattern_check = reduce( + lambda x, y: x or bool(fnmatch(filename, y)), + file_patterns, + False, + ) + exclude_check = reduce( + lambda x, y: x and fnmatch(filename, y), + exclude_patterns, + True, + ) + + if pattern_check and not exclude_check: + sources.append(filename) + else: + for pattern in file_patterns: + sources.extend(glob.glob("/".join([node, pattern]))) + + sources = [env.File(path) for path in sources] + return sources def DoxySourceScanCheck(node, env): - """Check if we should scan this file""" - return os.path.isfile(node.path) + """Check if we should scan this file""" + return os.path.isfile(node.path) + def DoxyEmitter(source, target, env): - """Doxygen Doxyfile emitter""" - # possible output formats and their default values and output locations - output_formats = { - "HTML": ("YES", "html"), - "LATEX": ("YES", "latex"), - "RTF": ("NO", "rtf"), - "MAN": ("NO", "man"), - "XML": ("NO", "xml"), - } + """Doxygen Doxyfile emitter""" + # possible output formats and their default values and output locations + output_formats = { + "HTML": ("YES", "html"), + "LATEX": ("YES", "latex"), + "RTF": ("NO", "rtf"), + "MAN": ("NO", "man"), + "XML": ("NO", "xml"), + } + + with open(source[0].abspath) as contents: + data = DoxyfileParse(contents) - with open(source[0].abspath) as contents: - data = DoxyfileParse(contents) + targets = [] + out_dir = source[0].Dir(data.get("OUTPUT_DIRECTORY", ".")) - targets = [] - out_dir = source[0].Dir(data.get("OUTPUT_DIRECTORY", ".")) + # add our output locations + for k, v in list(output_formats.items()): + if data.get("GENERATE_" + k, v[0]) == "YES": + targets.append(out_dir.Dir(v[1])) - # add our output locations - for (k, v) in list(output_formats.items()): - if data.get("GENERATE_" + k, v[0]) == "YES": - targets.append(out_dir.Dir(v[1])) + # set up cleaning stuff + for node in targets: + env.Clean(node, node) - # set up cleaning stuff - for node in targets: - env.Clean(node, node) + return (targets, source) - return (targets, source) def generate(env): - """ - Add builders and construction variables for the - Doxygen tool. This is currently for Doxygen 1.4.6. - """ - doxyfile_scanner = env.Scanner( - DoxySourceScan, - "DoxySourceScan", - scan_check = DoxySourceScanCheck, - ) - - import SCons.Builder - doxyfile_builder = SCons.Builder.Builder( - action = "cd ${SOURCE.dir} && ${DOXYGEN} ${SOURCE.file}", - emitter = DoxyEmitter, - single_source = True, - source_scanner = doxyfile_scanner, - ) - - env.Append( - BUILDERS = { - 'Doxygen': doxyfile_builder, - }, - ) - - env.AppendUnique( - DOXYGEN = fetchDoxygenPath(), - ) + """ + Add builders and construction variables for the + Doxygen tool. This is currently for Doxygen 1.4.6. + """ + doxyfile_scanner = env.Scanner( + DoxySourceScan, + "DoxySourceScan", + scan_check=DoxySourceScanCheck, + ) + + import SCons.Builder + + doxyfile_builder = SCons.Builder.Builder( + action="cd ${SOURCE.dir} && ${DOXYGEN} ${SOURCE.file}", + emitter=DoxyEmitter, + single_source=True, + source_scanner=doxyfile_scanner, + ) + + env.Append( + BUILDERS={ + "Doxygen": doxyfile_builder, + }, + ) + + env.AppendUnique( + DOXYGEN=fetchDoxygenPath(), + ) + def exists(env): """ Make sure doxygen exists. """ return bool(fetchDoxygenPath()) - diff --git a/site_scons/site_tools/gettextTool.py b/site_scons/site_tools/gettextTool.py index 3e1d1521bb1..8d21f84ba54 100644 --- a/site_scons/site_tools/gettextTool.py +++ b/site_scons/site_tools/gettextTool.py @@ -1,15 +1,15 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2010-2012 NV Access Limited -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2010-2012 NV Access Limited +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### import os @@ -17,15 +17,17 @@ # Get the path to msgfmt. MSGFMT = os.path.abspath(os.path.join("miscDeps", "tools", "msgfmt.exe")) + def exists(env): return True + def generate(env): - env['BUILDERS']['gettextMoFile']=env.Builder( + env["BUILDERS"]["gettextMoFile"] = env.Builder( action=env.Action( - [[MSGFMT,"-o","$TARGET","$SOURCE"]], - lambda t,s,e: 'Compiling gettext template %s'%s[0].path, - ), - suffix='.mo', - src_suffix='.po', + [[MSGFMT, "-o", "$TARGET", "$SOURCE"]], + lambda t, s, e: "Compiling gettext template %s" % s[0].path, + ), + suffix=".mo", + src_suffix=".po", ) diff --git a/site_scons/site_tools/listModules.py b/site_scons/site_tools/listModules.py index f7ef6665c2f..f390ff3246b 100644 --- a/site_scons/site_tools/listModules.py +++ b/site_scons/site_tools/listModules.py @@ -12,9 +12,9 @@ def _generateModuleList( - target: list[SCons.Node.FS.File], - source: list[SCons.Node.FS.Dir], - env: SCons.Environment.Environment, + target: list[SCons.Node.FS.File], + source: list[SCons.Node.FS.Dir], + env: SCons.Environment.Environment, ) -> None: """ Generate a list of Python modules from compiled '.pyc' files within `library.zip` in the source folder. @@ -42,10 +42,12 @@ def _generateModuleList( # Convert the file paths to python module format # eg: NVDAObjects/IAccessible/__init__.pyc --> NVDAObjects.IAccessible - importedModules = sorted({ - re.sub(r"(.__init__|.__version__|._version)?\.pyc$", "", module_path).replace("/", ".") - for module_path in pycFiles - }) + importedModules = sorted( + { + re.sub(r"(.__init__|.__version__|._version)?\.pyc$", "", module_path).replace("/", ".") + for module_path in pycFiles + }, + ) # Sanity check for something guaranteed to be in library.zip if "NVDAObjects.UIA" not in importedModules: @@ -59,7 +61,7 @@ def _generateModuleList( def generate(env: SCons.Environment.Environment): env["BUILDERS"]["GenerateModuleList"] = SCons.Builder.Builder( action=SCons.Action.Action(_generateModuleList), - ) + ) def exists(env: SCons.Environment.Environment) -> bool: diff --git a/site_scons/site_tools/md2html.py b/site_scons/site_tools/md2html.py index ccfd0168776..929df794782 100644 --- a/site_scons/site_tools/md2html.py +++ b/site_scons/site_tools/md2html.py @@ -13,18 +13,20 @@ import SCons.Node.FS import SCons.Environment -DEFAULT_EXTENSIONS = frozenset({ - # Supports tables, HTML mixed with markdown, code blocks, custom attributes and more - "markdown.extensions.extra", - # Allows TOC with [TOC]" - "markdown.extensions.toc", - # Makes list behaviour better, including 2 space indents by default - "mdx_truly_sane_lists", - # External links will open in a new tab, and title will be set to the link text - "markdown_link_attr_modifier", - # Adds links to GitHub authors, issues and PRs - "mdx_gh_links", -}) +DEFAULT_EXTENSIONS = frozenset( + { + # Supports tables, HTML mixed with markdown, code blocks, custom attributes and more + "markdown.extensions.extra", + # Allows TOC with [TOC]" + "markdown.extensions.toc", + # Makes list behaviour better, including 2 space indents by default + "mdx_truly_sane_lists", + # External links will open in a new tab, and title will be set to the link text + "markdown_link_attr_modifier", + # Adds links to GitHub authors, issues and PRs + "mdx_gh_links", + }, +) EXTENSIONS_CONFIG = { "markdown_link_attr_modifier": { @@ -55,6 +57,7 @@ def _replaceNVDATags(md: str, env: SCons.Environment.Environment) -> str: import versionInfo + # Replace tags in source file md = md.replace("NVDA_VERSION", env["version"]) md = md.replace("NVDA_URL", versionInfo.url) @@ -86,6 +89,7 @@ def _getTitle(mdBuffer: io.StringIO, isKeyCommands: bool = False) -> str: def _createAttributeFilter() -> dict[str, set[str]]: # Create attribute filter exceptions for HTML sanitization import nh3 + allowedAttributes: dict[str, set[str]] = deepcopy(nh3.ALLOWED_ATTRIBUTES) attributesWithAnchors = {"h1", "h2", "h3", "h4", "h5", "h6", "td"} @@ -119,6 +123,7 @@ def _generateSanitizedHTML(md: str, isKeyCommands: bool = False) -> str: extensions = set(DEFAULT_EXTENSIONS) if isKeyCommands: from user_docs.keyCommandsDoc import KeyCommandsExtension + extensions.add(KeyCommandsExtension()) htmlOutput = markdown.markdown( @@ -141,9 +146,9 @@ def _generateSanitizedHTML(md: str, isKeyCommands: bool = False) -> str: def md2html_actionFunc( - target: list[SCons.Node.FS.File], - source: list[SCons.Node.FS.File], - env: SCons.Environment.Environment, + target: list[SCons.Node.FS.File], + source: list[SCons.Node.FS.File], + env: SCons.Environment.Environment, ): isKeyCommands = target[0].path.endswith("keyCommands.html") isUserGuide = target[0].path.endswith("userGuide.html") diff --git a/site_scons/site_tools/msrpc.py b/site_scons/site_tools/msrpc.py index e55cecf4e85..3ecdb6e414f 100644 --- a/site_scons/site_tools/msrpc.py +++ b/site_scons/site_tools/msrpc.py @@ -1,83 +1,92 @@ ### -#This file is a part of the NVDA project. -#URL: http://www.nvda-project.org/ -#Copyright 2006-2010 NVDA contributers. -#This program is free software: you can redistribute it and/or modify -#it under the terms of the GNU General Public License version 2.0, as published by -#the Free Software Foundation. -#This program is distributed in the hope that it will be useful, -#but WITHOUT ANY WARRANTY; without even the implied warranty of -#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -#This license can be found at: -#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html +# This file is a part of the NVDA project. +# URL: http://www.nvda-project.org/ +# Copyright 2006-2010 NVDA contributers. +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2.0, as published by +# the Free Software Foundation. +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# This license can be found at: +# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html ### -#MSRPC tool -#Provides the MSRPCStubs builder which can use MIDL to generate header, client stub, and server stub files from an IDL. +# MSRPC tool +# Provides the MSRPCStubs builder which can use MIDL to generate header, client stub, and server stub files from an IDL. from SCons import Util from SCons.Builder import Builder -#This build emitter tells the builder that a header file, a client stub c file, and a server stub c file will be generated -def MSRPCStubs_buildEmitter(target,source,env): - base,ext=Util.splitext(str(target[0] if len(target)>0 else source[0])) - newTargets=['%s.h'%base] - if not env['MSRPCStubs_noServer']: - newTargets.append('%s_S.c'%base) - if not env['MSRPCStubs_noClient']: - newTargets.append('%s_C.c'%base) - return (newTargets,source) - -def MSRPCStubs_builder_actionGenerator(target,source,env,for_signature): - sources=[] + +# This build emitter tells the builder that a header file, a client stub c file, and a server stub c file will be generated +def MSRPCStubs_buildEmitter(target, source, env): + base, ext = Util.splitext(str(target[0] if len(target) > 0 else source[0])) + newTargets = ["%s.h" % base] + if not env["MSRPCStubs_noServer"]: + newTargets.append("%s_S.c" % base) + if not env["MSRPCStubs_noClient"]: + newTargets.append("%s_C.c" % base) + return (newTargets, source) + + +def MSRPCStubs_builder_actionGenerator(target, source, env, for_signature): + sources = [] for src in source: - src=str(src) - if src.endswith('.acf'): - sources.append('/acf %s'%src) + src = str(src) + if src.endswith(".acf"): + sources.append("/acf %s" % src) else: sources.append(src) - sources=" ".join(sources) - targets=[] + sources = " ".join(sources) + targets = [] for tg in target: - tg=str(tg) - if tg.endswith('.h'): - targets.append('/header %s'%tg) - elif tg.endswith('_S.c'): - targets.append('/sstub %s'%tg) - elif tg.endswith('_C.c'): - targets.append('/cstub %s'%tg) + tg = str(tg) + if tg.endswith(".h"): + targets.append("/header %s" % tg) + elif tg.endswith("_S.c"): + targets.append("/sstub %s" % tg) + elif tg.endswith("_C.c"): + targets.append("/cstub %s" % tg) else: - raise ValueError("Don't know what to do with %s"%tg) - targets=" ".join(targets) - noServer="/server none" if env.get('MSRPCStubs_noServer',False) else "" - noClient="/client none" if env.get('MSRPCStubs_noClient',False) else "" + raise ValueError("Don't know what to do with %s" % tg) + targets = " ".join(targets) + noServer = "/server none" if env.get("MSRPCStubs_noServer", False) else "" + noClient = "/client none" if env.get("MSRPCStubs_noClient", False) else "" - prefix=env.get('MSRPCStubs_prefix',"") + prefix = env.get("MSRPCStubs_prefix", "") if prefix: - prefix="/prefix all %s"%prefix - serverPrefix=env.get('MSRPCStubs_serverPrefix',"") + prefix = "/prefix all %s" % prefix + serverPrefix = env.get("MSRPCStubs_serverPrefix", "") if serverPrefix: - serverPrefix="/prefix server %s"%serverPrefix - clientPrefix=env.get('MSRPCStubs_clientPrefix',"") + serverPrefix = "/prefix server %s" % serverPrefix + clientPrefix = env.get("MSRPCStubs_clientPrefix", "") if clientPrefix: - clientPrefix="/prefix client %s"%clientPrefix + clientPrefix = "/prefix client %s" % clientPrefix + + return " ".join( + ["${MIDL}", "${MIDLFLAGS}", noServer, noClient, prefix, serverPrefix, clientPrefix, targets, sources], + ) - return " ".join(['${MIDL}','${MIDLFLAGS}',noServer,noClient,prefix,serverPrefix,clientPrefix,targets,sources]) -MSRPCStubs_builder=Builder( +MSRPCStubs_builder = Builder( generator=MSRPCStubs_builder_actionGenerator, - src_suffix=['.idl','.acf'], + src_suffix=[".idl", ".acf"], emitter=MSRPCStubs_buildEmitter, ) + def exists(env): from SCons.Tool import midl + return midl.exists(env) + def generate(env): - if 'MIDL' not in env: + if "MIDL" not in env: from SCons.Tool import midl + midl.generate(env) - env['BUILDERS']['MSRPCStubs']=MSRPCStubs_builder - env['MSRPCStubs_noServer']=False - env['MSRPCStubs_noClient']=False + env["BUILDERS"]["MSRPCStubs"] = MSRPCStubs_builder + env["MSRPCStubs_noServer"] = False + env["MSRPCStubs_noClient"] = False diff --git a/site_scons/site_tools/recursiveInstall.py b/site_scons/site_tools/recursiveInstall.py index 913a9ac5d14..f06fdb44de3 100644 --- a/site_scons/site_tools/recursiveInstall.py +++ b/site_scons/site_tools/recursiveInstall.py @@ -1,10 +1,10 @@ -#from http://xtargets.com/2010/04/21/recursive-install-builder-for-scons/ +# from http://xtargets.com/2010/04/21/recursive-install-builder-for-scons/ # This tool adds an # # env.RecursiveInstall( target, path ) # -# This is usefull for doing -# +# This is usefull for doing +# # k = env.RecursiveInstall(dir_target, dir_source) # # and if any thing in dir_source is updated @@ -31,37 +31,41 @@ import os + def recursive_install(env, path): - nodes = env.Glob \ - ( os.path.join(path, '*') - , strings=False, - ) - out = [] - for n in nodes: - if n.isdir(): - out.extend( recursive_install(env, n.abspath)) - else: - out.append(n) + nodes = env.Glob( + os.path.join(path, "*"), + strings=False, + ) + out = [] + for n in nodes: + if n.isdir(): + out.extend(recursive_install(env, n.abspath)) + else: + out.append(n) + + return out - return out def RecursiveInstall(env, target, dir): - nodes = recursive_install(env, dir) + nodes = recursive_install(env, dir) - dir = env.Dir(dir).abspath - target = env.Dir(target).abspath + dir = env.Dir(dir).abspath + target = env.Dir(target).abspath - l = len(dir) + 1 # noqa: E741 + l = len(dir) + 1 # noqa: E741 - relnodes = [ n.abspath[l:] for n in nodes] + relnodes = [n.abspath[l:] for n in nodes] + + for n in relnodes: + t = os.path.join(target, n) + s = os.path.join(dir, n) + env.InstallAs(env.File(t), env.File(s)) - for n in relnodes: - t = os.path.join(target, n) - s = os.path.join(dir, n) - env.InstallAs ( env.File(t), env.File(s)) def generate(env): - env.AddMethod(RecursiveInstall) + env.AddMethod(RecursiveInstall) + def exists(env): - return True + return True diff --git a/source/COMRegistrationFixes/__init__.py b/source/COMRegistrationFixes/__init__.py index cc12f44b60c..cf4785cd17e 100644 --- a/source/COMRegistrationFixes/__init__.py +++ b/source/COMRegistrationFixes/__init__.py @@ -117,8 +117,9 @@ def fixCOMRegistrations() -> None: OSMajorMinor = (winVer.major, winVer.minor) is64bit = winVer.processorArchitecture.endswith("64") log.debug( - f"Fixing COM registrations for Windows {OSMajorMinor[0]}.{OSMajorMinor[1]}, " - "{} bit.".format("64" if is64bit else "32"), + f"Fixing COM registrations for Windows {OSMajorMinor[0]}.{OSMajorMinor[1]}, " "{} bit.".format( + "64" if is64bit else "32", + ), ) # OLEACC (MSAA) proxies apply32bitRegistryPatch(OLEACC_REG_FILE_PATH) diff --git a/source/IAccessibleHandler/__init__.py b/source/IAccessibleHandler/__init__.py index 9834f841173..076b81446af 100644 --- a/source/IAccessibleHandler/__init__.py +++ b/source/IAccessibleHandler/__init__.py @@ -4,6 +4,7 @@ # See the file COPYING for more details. import typing + # F401 imported but unused. RelationType should be exposed from IAccessibleHandler, in future __all__ # should be used to export it. from .types import RelationType # noqa: F401 @@ -248,7 +249,7 @@ def _getStatesSetFromIAccessibleStates( - IAccessibleStates: int, + IAccessibleStates: int, ) -> Set[controlTypes.State]: return set( IAccessibleStatesToNVDAStates[IAState] @@ -270,7 +271,7 @@ def getStatesSetFromIAccessibleAttrs(attrs: "textInfos.ControlField") -> Set[Sta # The value for the state is used in the attribute name. # The attribute value is always 1. # EG IAccessible::state_40="1" - IAccessibleStateAttrName = 'IAccessible::state_{}' + IAccessibleStateAttrName = "IAccessible::state_{}" return set( IAccessibleStatesToNVDAStates[IAState] for IAState in IAccessibleStatesToNVDAStates.keys() @@ -283,7 +284,7 @@ def getStatesSetFromIAccessible2Attrs(attrs: "textInfos.ControlField") -> Set[St # The value for the state is used in the attribute name. # The attribute value is always 1. # EG IAccessible2::state_40="1" - IAccessible2StateAttrName = 'IAccessible2::state_{}' + IAccessible2StateAttrName = "IAccessible2::state_{}" return set( IAccessible2StatesToNVDAStates[IA2State] for IA2State in IAccessible2StatesToNVDAStates.keys() @@ -292,8 +293,7 @@ def getStatesSetFromIAccessible2Attrs(attrs: "textInfos.ControlField") -> Set[St def calculateNvdaRole(IARole: int, IAStates: int) -> Role: - """Convert IARole value into an NVDA role, and apply any required transformations. - """ + """Convert IARole value into an NVDA role, and apply any required transformations.""" role = IAccessibleRolesToNVDARoles.get(IARole, Role.UNKNOWN) states = _getStatesSetFromIAccessibleStates(IAStates) role, states = controlTypes.transformRoleStates(role, states) @@ -301,8 +301,7 @@ def calculateNvdaRole(IARole: int, IAStates: int) -> Role: def calculateNvdaStates(IARole: int, IAStates: int) -> Set[State]: - """Convert IAStates bit set into a Set of NVDA States and apply any required transformations. - """ + """Convert IAStates bit set into a Set of NVDA States and apply any required transformations.""" role = IAccessibleRolesToNVDARoles.get(IARole, Role.UNKNOWN) states = _getStatesSetFromIAccessibleStates(IAStates) role, states = controlTypes.transformRoleStates(role, states) @@ -321,8 +320,8 @@ def NVDARoleFromAttr(accRole: Optional[str]) -> Role: def normalizeIAccessible( - pacc: Union[IUnknown, IA.IAccessible, IA2.IAccessible2], - childID: int = 0, + pacc: Union[IUnknown, IA.IAccessible, IA2.IAccessible2], + childID: int = 0, ) -> Union[IA.IAccessible, IA2.IAccessible2]: if not isinstance(pacc, IA.IAccessible): try: @@ -515,11 +514,11 @@ def accNavigate(pacc, childID, direction): # Note: when working on winEventToNVDAEvent, look for opportunities to simplify # and move logic out into smaller helper functions. def winEventToNVDAEvent( # noqa: C901 - eventID: int, - window: int, - objectID: int, - childID: int, - useCache: bool = True, + eventID: int, + window: int, + objectID: int, + childID: int, + useCache: bool = True, ) -> Optional[Tuple[str, NVDAObjects.IAccessible.IAccessible]]: """Tries to convert a win event ID to an NVDA event name, and instantiate or fetch an NVDAObject for the win event parameters. @@ -586,8 +585,8 @@ def winEventToNVDAEvent( # noqa: C901 # SDM MSAA objects sometimes don't contain enough information to be useful Sometimes there is a real # window that does, so try to get the SDMChild property on the NVDAObject, and if successull use that as # obj instead. - if 'bosa_sdm' in obj.windowClassName: - SDMChild = getattr(obj, 'SDMChild', None) + if "bosa_sdm" in obj.windowClassName: + SDMChild = getattr(obj, "SDMChild", None) if SDMChild: obj = SDMChild if isMSAADebugLoggingEnabled(): @@ -633,6 +632,7 @@ def processGenericWinEvent(eventID, window, objectID, childID): # Seem to rely on MSAA caret events, # as they do not fire their own UIA caret events. from NVDAObjects.UIA.wordDocument import WordDocument + if isinstance(focus, WordDocument): if isMSAADebugLoggingEnabled(): log.debug( @@ -658,10 +658,7 @@ def processGenericWinEvent(eventID, window, objectID, childID): # if the winEvent is for the object with focus, # Ensure that that the event is send to the existing focus instance, # rather than a new instance of the object with focus. - if ( - NVDAEvent[1] is not focus - and NVDAEvent[1] == focus - ): + if NVDAEvent[1] is not focus and NVDAEvent[1] == focus: if isMSAADebugLoggingEnabled(): log.debug( f"Directing winEvent to existing focus object {focus}. " @@ -688,8 +685,7 @@ def processFocusWinEvent(window, objectID, childID, force=False): """ if isMSAADebugLoggingEnabled(): log.debug( - f"Processing focus winEvent: {getWinEventLogInfo(window, objectID, childID)}, " - f"force {force}", + f"Processing focus winEvent: {getWinEventLogInfo(window, objectID, childID)}, " f"force {force}", ) windowClassName = winUser.getClassName(window) # Generally, we must ignore focus on child windows of SDM windows as we only want the SDM MSAA events. @@ -697,8 +693,8 @@ def processFocusWinEvent(window, objectID, childID, force=False): # as this is a child control and the SDM MSAA events don't handle child controls. if ( childID == 0 - and not windowClassName.startswith('bosa_sdm') - and winUser.getClassName(winUser.getAncestor(window, winUser.GA_PARENT)).startswith('bosa_sdm') + and not windowClassName.startswith("bosa_sdm") + and winUser.getClassName(winUser.getAncestor(window, winUser.GA_PARENT)).startswith("bosa_sdm") ): if isMSAADebugLoggingEnabled(): log.debug( @@ -726,9 +722,8 @@ def processFocusWinEvent(window, objectID, childID, force=False): if not NVDAEvent: return False eventName, obj = NVDAEvent - if ( - (childID == 0 and obj.IAccessibleRole == oleacc.ROLE_SYSTEM_LIST) - or (objectID == winUser.OBJID_CLIENT and "SysListView32" in obj.windowClassName) + if (childID == 0 and obj.IAccessibleRole == oleacc.ROLE_SYSTEM_LIST) or ( + objectID == winUser.OBJID_CLIENT and "SysListView32" in obj.windowClassName ): # Some controls incorrectly fire focus on child ID 0, even when there is a child with focus. try: @@ -768,12 +763,13 @@ def processFocusNVDAEvent(obj, force=False): if isMSAADebugLoggingEnabled(): log.debug(f"IAccessible focus event not allowed by {obj}") return False - eventHandler.queueEvent('gainFocus', obj) + eventHandler.queueEvent("gainFocus", obj) return True def processDesktopSwitchWinEvent(window, objectID, childID): from winAPI.secureDesktop import _handleSecureDesktopChange + if isMSAADebugLoggingEnabled(): log.debug( f"Processing desktopSwitch winEvent: {getWinEventLogInfo(window, objectID, childID)}", @@ -796,6 +792,7 @@ def processDesktopSwitchWinEvent(window, objectID, childID): def _handleUserDesktop(): from winAPI.secureDesktop import post_secureDesktopStateChange + eventHandler.queueEvent("gainFocus", api.getDesktopObject().objectWithFocus()) post_secureDesktopStateChange.notify(isSecureDesktop=False) @@ -829,9 +826,9 @@ def processForegroundWinEvent(window, objectID, childID): # If there is a pending gainFocus, it will handle the foreground object. oldFocus = eventHandler.lastQueuedFocusObject # If this foreground win event's window is an ancestor of the existing focus's window, then ignore it - if ( - isinstance(oldFocus, NVDAObjects.window.Window) - and winUser.isDescendantWindow(window, oldFocus.windowHandle) + if isinstance(oldFocus, NVDAObjects.window.Window) and winUser.isDescendantWindow( + window, + oldFocus.windowHandle, ): if isMSAADebugLoggingEnabled(): log.debug( @@ -864,7 +861,13 @@ def processForegroundWinEvent(window, objectID, childID): ) return True # Convert the win event to an NVDA event - NVDAEvent = winEventToNVDAEvent(winUser.EVENT_SYSTEM_FOREGROUND, window, objectID, childID, useCache=False) + NVDAEvent = winEventToNVDAEvent( + winUser.EVENT_SYSTEM_FOREGROUND, + window, + objectID, + childID, + useCache=False, + ) if not NVDAEvent: if isMSAADebugLoggingEnabled(): log.debug( @@ -907,6 +910,7 @@ def processDestroyWinEvent(window, objectID, childID): # so can't use generic focus correction. (#2695) focus = api.getFocusObject() from NVDAObjects.IAccessible.mscandui import BaseCandidateItem + if ( objectID == 0 and childID == 0 @@ -930,9 +934,9 @@ def processMenuStartWinEvent(eventID, window, objectID, childID, validFocus): ) if validFocus: lastFocus = eventHandler.lastQueuedFocusObject - if ( - isinstance(lastFocus, NVDAObjects.IAccessible.IAccessible) - and lastFocus.IAccessibleRole in (oleacc.ROLE_SYSTEM_MENUPOPUP, oleacc.ROLE_SYSTEM_MENUITEM) + if isinstance(lastFocus, NVDAObjects.IAccessible.IAccessible) and lastFocus.IAccessibleRole in ( + oleacc.ROLE_SYSTEM_MENUPOPUP, + oleacc.ROLE_SYSTEM_MENUITEM, ): # Focus has already been set to a menu or menu item, so we don't need to handle the menuStart. return @@ -1015,10 +1019,15 @@ def pumpAll(): # noqa: C901 for winEvent in winEvents: isEventOnCaret = winEvent[2] == winUser.OBJID_CARET - showHideCaretEvent = focus and isEventOnCaret and winEvent[0] in [ - winUser.EVENT_OBJECT_SHOW, - winUser.EVENT_OBJECT_HIDE, - ] + showHideCaretEvent = ( + focus + and isEventOnCaret + and winEvent[0] + in [ + winUser.EVENT_OBJECT_SHOW, + winUser.EVENT_OBJECT_HIDE, + ] + ) # #4001: Ideally, we'd call shouldAcceptEvent in winEventCallback, but this causes focus issues when # starting applications. #7332: If this is a show event, which would normally be dropped by # `shouldAcceptEvent` and this event is for the caret, later it will be mapped to a caret event, @@ -1094,14 +1103,14 @@ def getIAccIdentity(pacc, childID): # comtypes transparently does this for wireHWND. return dict(menuHandle=cast(hmenu, wintypes.HMENU).value, childID=childID) stringPtr = cast(stringPtr, POINTER(c_char * stringSize)) - fields = struct.unpack('IIiI', stringPtr.contents.raw) + fields = struct.unpack("IIiI", stringPtr.contents.raw) d = {} - d['childID'] = fields[3] + d["childID"] = fields[3] if fields[0] & 2: - d['menuHandle'] = fields[2] + d["menuHandle"] = fields[2] else: - d['objectID'] = fields[2] - d['windowHandle'] = fields[1] + d["objectID"] = fields[2] + d["windowHandle"] = fields[1] return d finally: windll.ole32.CoTaskMemFree(stringPtr) @@ -1185,7 +1194,7 @@ def getRecursiveTextFromIAccessibleTextObject(obj, startOffset=0, endOffset=-1): except: # noqa: E722 Bare except pass textList.append(t) - return "".join(textList).replace(' ', ' ') + return "".join(textList).replace(" ", " ") ATTRIBS_STRING_BASE64_PATTERN = re.compile( @@ -1197,7 +1206,7 @@ def getRecursiveTextFromIAccessibleTextObject(obj, startOffset=0, endOffset=-1): # C901: splitIA2Attribs is too complex def splitIA2Attribs( # noqa: C901 - attribsString: str, + attribsString: str, ) -> Dict[str, Union[str, Dict]]: """Split an IAccessible2 attributes string into a dict of attribute keys and values. An invalid attributes string does not cause an error, but strange results may be returned. @@ -1278,10 +1287,14 @@ def isMarshalledIAccessible(IAccessibleObject): if not isinstance(IAccessibleObject, IA.IAccessible): raise TypeError("object should be of type IAccessible, not %s" % IAccessibleObject) buf = create_unicode_buffer(1024) - addr = POINTER(c_void_p).from_address( - super(comtypes._compointer_base, IAccessibleObject).value, - ).contents.value + addr = ( + POINTER(c_void_p) + .from_address( + super(comtypes._compointer_base, IAccessibleObject).value, + ) + .contents.value + ) handle = HANDLE() windll.kernel32.GetModuleHandleExW(6, addr, byref(handle)) windll.kernel32.GetModuleFileNameW(handle, buf, 1024) - return not buf.value.lower().endswith('oleacc.dll') + return not buf.value.lower().endswith("oleacc.dll") diff --git a/source/IAccessibleHandler/internalWinEventHandler.py b/source/IAccessibleHandler/internalWinEventHandler.py index 4baaf896b96..4243d40c138 100644 --- a/source/IAccessibleHandler/internalWinEventHandler.py +++ b/source/IAccessibleHandler/internalWinEventHandler.py @@ -101,7 +101,9 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times # Ignore events with invalid window handles isWindow = winUser.isWindow(window) if window else 0 if window == 0 or ( - not isWindow and eventID in ( + not isWindow + and eventID + in ( winUser.EVENT_SYSTEM_SWITCHSTART, winUser.EVENT_SYSTEM_SWITCHEND, winUser.EVENT_SYSTEM_MENUEND, @@ -189,13 +191,14 @@ def winEventCallback(handle, eventID, window, objectID, childID, threadID, times def initialize( - processDestroyWinEventFunc: Callable[ - [ - c_int, # window - c_int, # objectID - c_int, # childID - ], None, - ], + processDestroyWinEventFunc: Callable[ + [ + c_int, # window + c_int, # objectID + c_int, # childID + ], + None, + ], ): global _processDestroyWinEvent _processDestroyWinEvent = processDestroyWinEventFunc @@ -224,10 +227,7 @@ def _shouldGetEvents(): curForegroundWindow = winUser.getForegroundWindow() curForegroundClassName = winUser.getClassName(curForegroundWindow) futureForegroundClassName = winUser.getClassName(_deferUntilForegroundWindow) - if ( - _foregroundDefers < MAX_FOREGROUND_DEFERS - and curForegroundWindow != _deferUntilForegroundWindow - ): + if _foregroundDefers < MAX_FOREGROUND_DEFERS and curForegroundWindow != _deferUntilForegroundWindow: # Wait a core cycle before handling events to give the foreground window time to update. core.requestPump() _foregroundDefers += 1 diff --git a/source/IAccessibleHandler/orderedWinEventLimiter.py b/source/IAccessibleHandler/orderedWinEventLimiter.py index bb81e807cc0..d58fb5a86c7 100644 --- a/source/IAccessibleHandler/orderedWinEventLimiter.py +++ b/source/IAccessibleHandler/orderedWinEventLimiter.py @@ -42,12 +42,12 @@ def __init__(self, maxFocusItems=4): self._lastMenuEvent = None def addEvent( - self, - eventID: int, - window: int, - objectID: int, - childID: int, - threadID: int, + self, + eventID: int, + window: int, + objectID: int, + childID: int, + threadID: int, ) -> bool: """Adds a winEvent to the limiter. @param eventID: the winEvent type @@ -81,8 +81,8 @@ def addEvent( return True def flushEvents( - self, - alwaysAllowedObjects: Optional[List[IAccessibleObjectIdentifierType]] = None, + self, + alwaysAllowedObjects: Optional[List[IAccessibleObjectIdentifierType]] = None, ) -> List: """Returns a list of winEvents that have been added. Due to limiting, it will not necessarily be all the winEvents that were originally added. @@ -113,7 +113,7 @@ def flushEvents( heapq.heappush(self._eventHeap, (v,) + k) f = self._focusEventCache self._focusEventCache = {} - for k, v in sorted(f.items(), key=lambda item: item[1])[0 - self.maxFocusItems:]: + for k, v in sorted(f.items(), key=lambda item: item[1])[0 - self.maxFocusItems :]: heapq.heappush(self._eventHeap, (v,) + k) e = self._eventHeap self._eventHeap = [] diff --git a/source/IAccessibleHandler/types.py b/source/IAccessibleHandler/types.py index c7c3e5f3428..2d9e81a39ba 100644 --- a/source/IAccessibleHandler/types.py +++ b/source/IAccessibleHandler/types.py @@ -7,6 +7,7 @@ """Types used in IAccessibleHander. Kept here so they can be re-used without having to worry about circular imports. """ + import enum from typing import Tuple diff --git a/source/IAccessibleHandler/utils.py b/source/IAccessibleHandler/utils.py index ad3f9075139..3409d1ccbd4 100644 --- a/source/IAccessibleHandler/utils.py +++ b/source/IAccessibleHandler/utils.py @@ -18,11 +18,11 @@ def getWinEventName(eventID): - """ Looks up the name of an EVENT_* winEvent constant. """ + """Looks up the name of an EVENT_* winEvent constant.""" global _winEventNameCache if not _winEventNameCache: - _winEventNameCache = {y: x for x, y in vars(winUser).items() if x.startswith('EVENT_')} - _winEventNameCache.update({y: x for x, y in vars(IA2).items() if x.startswith('IA2_EVENT_')}) + _winEventNameCache = {y: x for x, y in vars(winUser).items() if x.startswith("EVENT_")} + _winEventNameCache.update({y: x for x, y in vars(IA2).items() if x.startswith("IA2_EVENT_")}) name = _winEventNameCache.get(eventID) if not name: name = "unknown event ({eventID})" @@ -33,10 +33,10 @@ def getWinEventName(eventID): def getObjectIDName(objectID): - """ Looks up the name of an OBJID_* winEvent constant. """ + """Looks up the name of an OBJID_* winEvent constant.""" global _objectIDNameCache if not _objectIDNameCache: - _objectIDNameCache = {y: x for x, y in vars(winUser).items() if x.startswith('OBJID_')} + _objectIDNameCache = {y: x for x, y in vars(winUser).items() if x.startswith("OBJID_")} name = _objectIDNameCache.get(objectID) if not name: name = str(objectID) @@ -70,5 +70,5 @@ def getWinEventLogInfo(window, objectID, childID, eventID=None, threadID=None): def isMSAADebugLoggingEnabled(): - """ Whether the user has configured NVDA to log extra information about MSAA events. """ + """Whether the user has configured NVDA to log extra information about MSAA events.""" return config.conf["debugLog"]["MSAA"] diff --git a/source/JABHandler.py b/source/JABHandler.py index c8198dff662..8c148c454e7 100644 --- a/source/JABHandler.py +++ b/source/JABHandler.py @@ -48,130 +48,142 @@ A11Y_PROPS_PATH = os.path.expanduser(r"~\.accessibility.properties") #: The content of ".accessibility.properties" when JAB is enabled. A11Y_PROPS_CONTENT = ( - "assistive_technologies=com.sun.java.accessibility.AccessBridge\n" - "screen_magnifier_present=true\n" + "assistive_technologies=com.sun.java.accessibility.AccessBridge\n" "screen_magnifier_present=true\n" ) -#Some utility functions to help with function defines +# Some utility functions to help with function defines + def _errcheck(res, func, args): if not res: raise RuntimeError("Result %s" % res) return res -def _fixBridgeFunc(restype,name,*argtypes,**kwargs): + +def _fixBridgeFunc(restype, name, *argtypes, **kwargs): try: - func=getattr(bridgeDll,name) + func = getattr(bridgeDll, name) except AttributeError: - log.warning("%s not found in Java Access Bridge dll"%name) + log.warning("%s not found in Java Access Bridge dll" % name) return - func.restype=restype - func.argtypes=argtypes - if kwargs.get('errcheck'): - func.errcheck=_errcheck + func.restype = restype + func.argtypes = argtypes + if kwargs.get("errcheck"): + func.errcheck = _errcheck bridgeDll = None -#Definitions of access bridge types, structs and prototypes +# Definitions of access bridge types, structs and prototypes -jchar=c_wchar -jint=c_int -jfloat=c_float -jboolean=c_bool +jchar = c_wchar +jint = c_int +jfloat = c_float +jboolean = c_bool class JOBJECT64(c_int64): pass -AccessibleTable=JOBJECT64 -MAX_STRING_SIZE=1024 -SHORT_STRING_SIZE=256 + +AccessibleTable = JOBJECT64 + +MAX_STRING_SIZE = 1024 +SHORT_STRING_SIZE = 256 + class AccessBridgeVersionInfo(Structure): - _fields_=[ - ('VMVersion',WCHAR*SHORT_STRING_SIZE), - ('bridgeJavaClassVersion',WCHAR*SHORT_STRING_SIZE), - ('bridgeJavaDLLVersion',WCHAR*SHORT_STRING_SIZE), - ('bridgeWinDLLVersion',WCHAR*SHORT_STRING_SIZE), + _fields_ = [ + ("VMVersion", WCHAR * SHORT_STRING_SIZE), + ("bridgeJavaClassVersion", WCHAR * SHORT_STRING_SIZE), + ("bridgeJavaDLLVersion", WCHAR * SHORT_STRING_SIZE), + ("bridgeWinDLLVersion", WCHAR * SHORT_STRING_SIZE), ] + class AccessibleContextInfo(Structure): - _fields_=[ - ('name',WCHAR*MAX_STRING_SIZE), - ('description',WCHAR*MAX_STRING_SIZE), - ('role',WCHAR*SHORT_STRING_SIZE), - ('role_en_US',WCHAR*SHORT_STRING_SIZE), - ('states',WCHAR*SHORT_STRING_SIZE), - ('states_en_US',WCHAR*SHORT_STRING_SIZE), - ('indexInParent',jint), - ('childrenCount',jint), - ('x',jint), - ('y',jint), - ('width',jint), - ('height',jint), - ('accessibleComponent',BOOL), - ('accessibleAction',BOOL), - ('accessibleSelection',BOOL), - ('accessibleText',BOOL), - ('accessibleValue',BOOL), + _fields_ = [ + ("name", WCHAR * MAX_STRING_SIZE), + ("description", WCHAR * MAX_STRING_SIZE), + ("role", WCHAR * SHORT_STRING_SIZE), + ("role_en_US", WCHAR * SHORT_STRING_SIZE), + ("states", WCHAR * SHORT_STRING_SIZE), + ("states_en_US", WCHAR * SHORT_STRING_SIZE), + ("indexInParent", jint), + ("childrenCount", jint), + ("x", jint), + ("y", jint), + ("width", jint), + ("height", jint), + ("accessibleComponent", BOOL), + ("accessibleAction", BOOL), + ("accessibleSelection", BOOL), + ("accessibleText", BOOL), + ("accessibleValue", BOOL), ] + class AccessibleTextInfo(Structure): - _fields_=[ - ('charCount',jint), - ('caretIndex',jint), - ('indexAtPoint',jint), + _fields_ = [ + ("charCount", jint), + ("caretIndex", jint), + ("indexAtPoint", jint), ] + class AccessibleTextItemsInfo(Structure): - _fields_=[ - ('letter',WCHAR), - ('word',WCHAR*SHORT_STRING_SIZE), - ('sentence',WCHAR*MAX_STRING_SIZE), + _fields_ = [ + ("letter", WCHAR), + ("word", WCHAR * SHORT_STRING_SIZE), + ("sentence", WCHAR * MAX_STRING_SIZE), ] + class AccessibleTextSelectionInfo(Structure): - _fields_=[ - ('selectionStartIndex',jint), - ('selectionEndIndex',jint), - ('selectedText',WCHAR*MAX_STRING_SIZE), + _fields_ = [ + ("selectionStartIndex", jint), + ("selectionEndIndex", jint), + ("selectedText", WCHAR * MAX_STRING_SIZE), ] + class AccessibleTextRectInfo(Structure): - _fields_=[ - ('x',jint), - ('y',jint), - ('width',jint), - ('height',jint), + _fields_ = [ + ("x", jint), + ("y", jint), + ("width", jint), + ("height", jint), ] + class AccessibleTextAttributesInfo(Structure): - _fields_=[ - ('bold',BOOL), - ('italic',BOOL), - ('underline',BOOL), - ('strikethrough',BOOL), - ('superscript',BOOL), - ('subscript',BOOL), - ('backgroundColor',WCHAR*SHORT_STRING_SIZE), - ('foregroundColor',WCHAR*SHORT_STRING_SIZE), - ('fontFamily',WCHAR*SHORT_STRING_SIZE), - ('fontSize',jint), - ('alignment',jint), - ('bidiLevel',jint), - ('firstLineIndent',jfloat), - ('LeftIndent',jfloat), - ('rightIndent',jfloat), - ('lineSpacing',jfloat), - ('spaceAbove',jfloat), - ('spaceBelow',jfloat), - ('fullAttributesString',WCHAR*MAX_STRING_SIZE), + _fields_ = [ + ("bold", BOOL), + ("italic", BOOL), + ("underline", BOOL), + ("strikethrough", BOOL), + ("superscript", BOOL), + ("subscript", BOOL), + ("backgroundColor", WCHAR * SHORT_STRING_SIZE), + ("foregroundColor", WCHAR * SHORT_STRING_SIZE), + ("fontFamily", WCHAR * SHORT_STRING_SIZE), + ("fontSize", jint), + ("alignment", jint), + ("bidiLevel", jint), + ("firstLineIndent", jfloat), + ("LeftIndent", jfloat), + ("rightIndent", jfloat), + ("lineSpacing", jfloat), + ("spaceAbove", jfloat), + ("spaceBelow", jfloat), + ("fullAttributesString", WCHAR * MAX_STRING_SIZE), ] + MAX_RELATION_TARGETS = 25 MAX_RELATIONS = 5 + class AccessibleRelationInfo(Structure): _fields_ = [ ("key", WCHAR * SHORT_STRING_SIZE), @@ -179,19 +191,21 @@ class AccessibleRelationInfo(Structure): ("targets", JOBJECT64 * MAX_RELATION_TARGETS), ] + class AccessibleRelationSetInfo(Structure): _fields_ = [ ("relationCount", jint), ("relations", AccessibleRelationInfo * MAX_RELATIONS), ] + MAX_ACTION_INFO = 256 MAX_ACTIONS_TO_DO = 32 + class AccessibleActionInfo(Structure): - _fields_ = ( - ("name", c_wchar * SHORT_STRING_SIZE), - ) + _fields_ = (("name", c_wchar * SHORT_STRING_SIZE),) + class AccessibleActions(Structure): _fields_ = ( @@ -199,40 +213,45 @@ class AccessibleActions(Structure): ("actionInfo", AccessibleActionInfo * MAX_ACTION_INFO), ) + class AccessibleActionsToDo(Structure): _fields_ = ( ("actionsCount", jint), ("actions", AccessibleActionInfo * MAX_ACTIONS_TO_DO), ) + class AccessibleTableInfo(Structure): - _fields_=[ - ('caption',JOBJECT64), - ('summary',JOBJECT64), - ('rowCount',jint), - ('columnCount',jint), - ('accessibleContext',JOBJECT64), - ('accessibleTable',JOBJECT64), + _fields_ = [ + ("caption", JOBJECT64), + ("summary", JOBJECT64), + ("rowCount", jint), + ("columnCount", jint), + ("accessibleContext", JOBJECT64), + ("accessibleTable", JOBJECT64), ] + class AccessibleTableCellInfo(Structure): - _fields_=[ - ('accessibleContext',JOBJECT64), - ('index',jint), - ('row',jint), - ('column',jint), - ('rowExtent',jint), - ('columnExtent',jint), - ('isSelected',jboolean), + _fields_ = [ + ("accessibleContext", JOBJECT64), + ("index", jint), + ("row", jint), + ("column", jint), + ("rowExtent", jint), + ("columnExtent", jint), + ("isSelected", jboolean), ] -MAX_KEY_BINDINGS=50 + +MAX_KEY_BINDINGS = 50 class AccessibleKeystroke(IntFlag): """ Defined in the JDK in header include/win32/bridge/AccessBridgePackages.h """ + SHIFT = 1 CONTROL = 2 META = 4 @@ -266,6 +285,7 @@ class AccessibleVK(IntEnum): The supported control code keys related to AccessibleKeystroke.CONTROLCODE. Defined in the JDK in header include/win32/bridge/AccessBridgePackages.h """ + BACK_SPACE = 8 DELETE = 127 DOWN = 40 @@ -284,149 +304,302 @@ class AccessibleVK(IntEnum): class AccessibleKeyBindingInfo(Structure): - _fields_=[ - ('character',jchar), - ('modifiers',jint), + _fields_ = [ + ("character", jchar), + ("modifiers", jint), ] + class AccessibleKeyBindings(Structure): - _fields_=[ - ('keyBindingsCount',c_int), - ('keyBindingInfo',AccessibleKeyBindingInfo*MAX_KEY_BINDINGS), + _fields_ = [ + ("keyBindingsCount", c_int), + ("keyBindingInfo", AccessibleKeyBindingInfo * MAX_KEY_BINDINGS), ] -AccessBridge_FocusGainedFP=CFUNCTYPE(None,c_long,JOBJECT64,JOBJECT64) -AccessBridge_PropertyNameChangeFP=CFUNCTYPE(None,c_long,JOBJECT64,JOBJECT64,c_wchar_p,c_wchar_p) -AccessBridge_PropertyDescriptionChangeFP=CFUNCTYPE(None,c_long,JOBJECT64,JOBJECT64,c_wchar_p,c_wchar_p) -AccessBridge_PropertyValueChangeFP=CFUNCTYPE(None,c_long,JOBJECT64,JOBJECT64,c_wchar_p,c_wchar_p) -AccessBridge_PropertyStateChangeFP=CFUNCTYPE(None,c_long,JOBJECT64,JOBJECT64,c_wchar_p,c_wchar_p) -AccessBridge_PropertyCaretChangeFP=CFUNCTYPE(None,c_long,JOBJECT64,JOBJECT64,c_int,c_int) -AccessBridge_PropertyActiveDescendentChangeFP=CFUNCTYPE(None,c_long,JOBJECT64,JOBJECT64,JOBJECT64,JOBJECT64) + +AccessBridge_FocusGainedFP = CFUNCTYPE(None, c_long, JOBJECT64, JOBJECT64) +AccessBridge_PropertyNameChangeFP = CFUNCTYPE(None, c_long, JOBJECT64, JOBJECT64, c_wchar_p, c_wchar_p) +AccessBridge_PropertyDescriptionChangeFP = CFUNCTYPE(None, c_long, JOBJECT64, JOBJECT64, c_wchar_p, c_wchar_p) +AccessBridge_PropertyValueChangeFP = CFUNCTYPE(None, c_long, JOBJECT64, JOBJECT64, c_wchar_p, c_wchar_p) +AccessBridge_PropertyStateChangeFP = CFUNCTYPE(None, c_long, JOBJECT64, JOBJECT64, c_wchar_p, c_wchar_p) +AccessBridge_PropertyCaretChangeFP = CFUNCTYPE(None, c_long, JOBJECT64, JOBJECT64, c_int, c_int) +AccessBridge_PropertyActiveDescendentChangeFP = CFUNCTYPE( + None, + c_long, + JOBJECT64, + JOBJECT64, + JOBJECT64, + JOBJECT64, +) def _fixBridgeFuncs(): - """Appropriately set the return and argument types of all the access bridge dll functions - """ - _fixBridgeFunc(None,'Windows_run') - _fixBridgeFunc(None,'setFocusGainedFP',c_void_p) - _fixBridgeFunc(None,'setPropertyNameChangeFP',c_void_p) - _fixBridgeFunc(None,'setPropertyDescriptionChangeFP',c_void_p) - _fixBridgeFunc(None,'setPropertyValueChangeFP',c_void_p) - _fixBridgeFunc(None,'setPropertyStateChangeFP',c_void_p) - _fixBridgeFunc(None,'setPropertyCaretChangeFP',c_void_p) - _fixBridgeFunc(None,'setPropertyActiveDescendentChangeFP',c_void_p) - _fixBridgeFunc(None,'releaseJavaObject',c_long,JOBJECT64) - _fixBridgeFunc(BOOL,'getVersionInfo',POINTER(AccessBridgeVersionInfo),errcheck=True) - _fixBridgeFunc(BOOL,'isJavaWindow',HWND) - _fixBridgeFunc(BOOL,'isSameObject',c_long,JOBJECT64,JOBJECT64) - _fixBridgeFunc(BOOL,'getAccessibleContextFromHWND',HWND,POINTER(c_long),POINTER(JOBJECT64),errcheck=True) - _fixBridgeFunc(HWND,'getHWNDFromAccessibleContext',c_long,JOBJECT64,errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleContextAt',c_long,JOBJECT64,jint,jint,POINTER(JOBJECT64),errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleContextWithFocus',HWND,POINTER(c_long),POINTER(JOBJECT64),errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleContextInfo',c_long,JOBJECT64,POINTER(AccessibleContextInfo),errcheck=True) - _fixBridgeFunc(JOBJECT64,'getAccessibleChildFromContext',c_long,JOBJECT64,jint,errcheck=True) - _fixBridgeFunc(JOBJECT64,'getAccessibleParentFromContext',c_long,JOBJECT64) - _fixBridgeFunc(JOBJECT64,'getParentWithRole',c_long,JOBJECT64,POINTER(c_wchar)) - _fixBridgeFunc(BOOL,'getAccessibleRelationSet',c_long,JOBJECT64,POINTER(AccessibleRelationSetInfo),errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleTextInfo',c_long,JOBJECT64,POINTER(AccessibleTextInfo),jint,jint,errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleTextItems',c_long,JOBJECT64,POINTER(AccessibleTextItemsInfo),jint,errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleTextSelectionInfo',c_long,JOBJECT64,POINTER(AccessibleTextSelectionInfo),errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleTextAttributes',c_long,JOBJECT64,jint,POINTER(AccessibleTextAttributesInfo),errcheck=True) + """Appropriately set the return and argument types of all the access bridge dll functions""" + _fixBridgeFunc(None, "Windows_run") + _fixBridgeFunc(None, "setFocusGainedFP", c_void_p) + _fixBridgeFunc(None, "setPropertyNameChangeFP", c_void_p) + _fixBridgeFunc(None, "setPropertyDescriptionChangeFP", c_void_p) + _fixBridgeFunc(None, "setPropertyValueChangeFP", c_void_p) + _fixBridgeFunc(None, "setPropertyStateChangeFP", c_void_p) + _fixBridgeFunc(None, "setPropertyCaretChangeFP", c_void_p) + _fixBridgeFunc(None, "setPropertyActiveDescendentChangeFP", c_void_p) + _fixBridgeFunc(None, "releaseJavaObject", c_long, JOBJECT64) + _fixBridgeFunc(BOOL, "getVersionInfo", POINTER(AccessBridgeVersionInfo), errcheck=True) + _fixBridgeFunc(BOOL, "isJavaWindow", HWND) + _fixBridgeFunc(BOOL, "isSameObject", c_long, JOBJECT64, JOBJECT64) _fixBridgeFunc( BOOL, - 'getAccessibleTextRect', + "getAccessibleContextFromHWND", + HWND, + POINTER(c_long), + POINTER(JOBJECT64), + errcheck=True, + ) + _fixBridgeFunc(HWND, "getHWNDFromAccessibleContext", c_long, JOBJECT64, errcheck=True) + _fixBridgeFunc( + BOOL, + "getAccessibleContextAt", + c_long, + JOBJECT64, + jint, + jint, + POINTER(JOBJECT64), + errcheck=True, + ) + _fixBridgeFunc( + BOOL, + "getAccessibleContextWithFocus", + HWND, + POINTER(c_long), + POINTER(JOBJECT64), + errcheck=True, + ) + _fixBridgeFunc( + BOOL, + "getAccessibleContextInfo", + c_long, + JOBJECT64, + POINTER(AccessibleContextInfo), + errcheck=True, + ) + _fixBridgeFunc(JOBJECT64, "getAccessibleChildFromContext", c_long, JOBJECT64, jint, errcheck=True) + _fixBridgeFunc(JOBJECT64, "getAccessibleParentFromContext", c_long, JOBJECT64) + _fixBridgeFunc(JOBJECT64, "getParentWithRole", c_long, JOBJECT64, POINTER(c_wchar)) + _fixBridgeFunc( + BOOL, + "getAccessibleRelationSet", + c_long, + JOBJECT64, + POINTER(AccessibleRelationSetInfo), + errcheck=True, + ) + _fixBridgeFunc( + BOOL, + "getAccessibleTextInfo", + c_long, + JOBJECT64, + POINTER(AccessibleTextInfo), + jint, + jint, + errcheck=True, + ) + _fixBridgeFunc( + BOOL, + "getAccessibleTextItems", + c_long, + JOBJECT64, + POINTER(AccessibleTextItemsInfo), + jint, + errcheck=True, + ) + _fixBridgeFunc( + BOOL, + "getAccessibleTextSelectionInfo", + c_long, + JOBJECT64, + POINTER(AccessibleTextSelectionInfo), + errcheck=True, + ) + _fixBridgeFunc( + BOOL, + "getAccessibleTextAttributes", + c_long, + JOBJECT64, + jint, + POINTER(AccessibleTextAttributesInfo), + errcheck=True, + ) + _fixBridgeFunc( + BOOL, + "getAccessibleTextRect", c_long, JOBJECT64, POINTER(AccessibleTextRectInfo), jint, errcheck=True, ) - _fixBridgeFunc(BOOL,'getAccessibleTextLineBounds',c_long,JOBJECT64,jint,POINTER(jint),POINTER(jint),errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleTextRange',c_long,JOBJECT64,jint,jint,POINTER(c_char),c_short,errcheck=True) - _fixBridgeFunc(BOOL,'getCurrentAccessibleValueFromContext',c_long,JOBJECT64,POINTER(c_wchar),c_short,errcheck=True) - _fixBridgeFunc(BOOL,'selectTextRange',c_long,JOBJECT64,c_int,c_int,errcheck=True) - _fixBridgeFunc(BOOL,'getTextAttributesInRange',c_long,JOBJECT64,c_int,c_int,POINTER(AccessibleTextAttributesInfo),POINTER(c_short),errcheck=True) - _fixBridgeFunc(JOBJECT64,'getTopLevelObject',c_long,JOBJECT64,errcheck=True) - _fixBridgeFunc(c_int,'getObjectDepth',c_long,JOBJECT64) - _fixBridgeFunc(JOBJECT64,'getActiveDescendent',c_long,JOBJECT64) - _fixBridgeFunc(BOOL,'requestFocus',c_long,JOBJECT64,errcheck=True) - _fixBridgeFunc(BOOL,'setCaretPosition',c_long,JOBJECT64,c_int,errcheck=True) - _fixBridgeFunc(BOOL,'getCaretLocation',c_long,JOBJECT64,POINTER(AccessibleTextRectInfo),jint,errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleActions',c_long,JOBJECT64,POINTER(AccessibleActions),errcheck=True) - _fixBridgeFunc(BOOL,'doAccessibleActions',c_long,JOBJECT64,POINTER(AccessibleActionsToDo),POINTER(jint),errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleTableInfo',c_long,JOBJECT64,POINTER(AccessibleTableInfo)) - _fixBridgeFunc(BOOL,'getAccessibleTableCellInfo',c_long,AccessibleTable,jint,jint,POINTER(AccessibleTableCellInfo),errcheck=True) - _fixBridgeFunc(BOOL,'getAccessibleTableRowHeader',c_long,JOBJECT64,POINTER(AccessibleTableInfo)) - _fixBridgeFunc(BOOL,'getAccessibleTableColumnHeader',c_long,JOBJECT64,POINTER(AccessibleTableInfo)) - _fixBridgeFunc(JOBJECT64,'getAccessibleTableRowDescription',c_long,JOBJECT64,jint) - _fixBridgeFunc(JOBJECT64,'getAccessibleTableColumnDescription',c_long,JOBJECT64,jint) - _fixBridgeFunc(jint,'getAccessibleTableRow',c_long,AccessibleTable,jint) - _fixBridgeFunc(jint,'getAccessibleTableColumn',c_long,AccessibleTable,jint) - _fixBridgeFunc(jint,'getAccessibleTableIndex',c_long,AccessibleTable,jint,jint) - _fixBridgeFunc(BOOL,'getAccessibleKeyBindings',c_long,JOBJECT64,POINTER(AccessibleKeyBindings),errcheck=True) - -#NVDA specific code - -isRunning=False + _fixBridgeFunc( + BOOL, + "getAccessibleTextLineBounds", + c_long, + JOBJECT64, + jint, + POINTER(jint), + POINTER(jint), + errcheck=True, + ) + _fixBridgeFunc( + BOOL, + "getAccessibleTextRange", + c_long, + JOBJECT64, + jint, + jint, + POINTER(c_char), + c_short, + errcheck=True, + ) + _fixBridgeFunc( + BOOL, + "getCurrentAccessibleValueFromContext", + c_long, + JOBJECT64, + POINTER(c_wchar), + c_short, + errcheck=True, + ) + _fixBridgeFunc(BOOL, "selectTextRange", c_long, JOBJECT64, c_int, c_int, errcheck=True) + _fixBridgeFunc( + BOOL, + "getTextAttributesInRange", + c_long, + JOBJECT64, + c_int, + c_int, + POINTER(AccessibleTextAttributesInfo), + POINTER(c_short), + errcheck=True, + ) + _fixBridgeFunc(JOBJECT64, "getTopLevelObject", c_long, JOBJECT64, errcheck=True) + _fixBridgeFunc(c_int, "getObjectDepth", c_long, JOBJECT64) + _fixBridgeFunc(JOBJECT64, "getActiveDescendent", c_long, JOBJECT64) + _fixBridgeFunc(BOOL, "requestFocus", c_long, JOBJECT64, errcheck=True) + _fixBridgeFunc(BOOL, "setCaretPosition", c_long, JOBJECT64, c_int, errcheck=True) + _fixBridgeFunc( + BOOL, + "getCaretLocation", + c_long, + JOBJECT64, + POINTER(AccessibleTextRectInfo), + jint, + errcheck=True, + ) + _fixBridgeFunc(BOOL, "getAccessibleActions", c_long, JOBJECT64, POINTER(AccessibleActions), errcheck=True) + _fixBridgeFunc( + BOOL, + "doAccessibleActions", + c_long, + JOBJECT64, + POINTER(AccessibleActionsToDo), + POINTER(jint), + errcheck=True, + ) + _fixBridgeFunc(BOOL, "getAccessibleTableInfo", c_long, JOBJECT64, POINTER(AccessibleTableInfo)) + _fixBridgeFunc( + BOOL, + "getAccessibleTableCellInfo", + c_long, + AccessibleTable, + jint, + jint, + POINTER(AccessibleTableCellInfo), + errcheck=True, + ) + _fixBridgeFunc(BOOL, "getAccessibleTableRowHeader", c_long, JOBJECT64, POINTER(AccessibleTableInfo)) + _fixBridgeFunc(BOOL, "getAccessibleTableColumnHeader", c_long, JOBJECT64, POINTER(AccessibleTableInfo)) + _fixBridgeFunc(JOBJECT64, "getAccessibleTableRowDescription", c_long, JOBJECT64, jint) + _fixBridgeFunc(JOBJECT64, "getAccessibleTableColumnDescription", c_long, JOBJECT64, jint) + _fixBridgeFunc(jint, "getAccessibleTableRow", c_long, AccessibleTable, jint) + _fixBridgeFunc(jint, "getAccessibleTableColumn", c_long, AccessibleTable, jint) + _fixBridgeFunc(jint, "getAccessibleTableIndex", c_long, AccessibleTable, jint, jint) + _fixBridgeFunc( + BOOL, + "getAccessibleKeyBindings", + c_long, + JOBJECT64, + POINTER(AccessibleKeyBindings), + errcheck=True, + ) + + +# NVDA specific code + +isRunning = False # Cache of the last active window handle for a given JVM ID. In theory, this # cache should not be needed, as it should always be possible to retrieve the # window handle of a given accessible context by calling getTopLevelObject then -# getHWNDFromAccessibleContext. However, getTopLevelObject sometimes returns +# getHWNDFromAccessibleContext. However, getTopLevelObject sometimes returns # accessible contexts that make getHWNDFromAccessibleContext fail. To workaround # the issue, we use this cache as a fallback when either getTopLevelObject or # getHWNDFromAccessibleContext fails. -vmIDsToWindowHandles={} -internalFunctionQueue=queue.Queue(1000) -internalFunctionQueue.__name__="JABHandler.internalFunctionQueue" +vmIDsToWindowHandles = {} +internalFunctionQueue = queue.Queue(1000) +internalFunctionQueue.__name__ = "JABHandler.internalFunctionQueue" -def internalQueueFunction(func,*args,**kwargs): - internalFunctionQueue.put_nowait((func,args,kwargs)) + +def internalQueueFunction(func, *args, **kwargs): + internalFunctionQueue.put_nowait((func, args, kwargs)) core.requestPump() -def internal_getWindowHandleFromAccContext(vmID,accContext): + +def internal_getWindowHandleFromAccContext(vmID, accContext): try: - topAC=bridgeDll.getTopLevelObject(vmID,accContext) + topAC = bridgeDll.getTopLevelObject(vmID, accContext) try: - return bridgeDll.getHWNDFromAccessibleContext(vmID,topAC) + return bridgeDll.getHWNDFromAccessibleContext(vmID, topAC) finally: - bridgeDll.releaseJavaObject(vmID,topAC) + bridgeDll.releaseJavaObject(vmID, topAC) except: # noqa: E722 return None -def getWindowHandleFromAccContext(vmID,accContext): - hwnd=internal_getWindowHandleFromAccContext(vmID,accContext) + +def getWindowHandleFromAccContext(vmID, accContext): + hwnd = internal_getWindowHandleFromAccContext(vmID, accContext) if hwnd: - vmIDsToWindowHandles[vmID]=hwnd + vmIDsToWindowHandles[vmID] = hwnd return hwnd else: return vmIDsToWindowHandles.get(vmID) -class JABContext(object): - def __init__(self,hwnd=None,vmID=None,accContext=None): +class JABContext(object): + def __init__(self, hwnd=None, vmID=None, accContext=None): if hwnd and not vmID: - vmID=c_long() - accContext=JOBJECT64() - bridgeDll.getAccessibleContextFromHWND(hwnd,byref(vmID),byref(accContext)) - #Record this vm ID and window handle for later use with other objects - vmID=vmID.value - vmIDsToWindowHandles[vmID]=hwnd + vmID = c_long() + accContext = JOBJECT64() + bridgeDll.getAccessibleContextFromHWND(hwnd, byref(vmID), byref(accContext)) + # Record this vm ID and window handle for later use with other objects + vmID = vmID.value + vmIDsToWindowHandles[vmID] = hwnd elif vmID and not hwnd: - hwnd = getWindowHandleFromAccContext(vmID,accContext) - self.hwnd=hwnd - self.vmID=vmID - self.accContext=accContext + hwnd = getWindowHandleFromAccContext(vmID, accContext) + self.hwnd = hwnd + self.vmID = vmID + self.accContext = accContext def __del__(self): if isRunning: try: - bridgeDll.releaseJavaObject(self.vmID,self.accContext) + bridgeDll.releaseJavaObject(self.vmID, self.accContext) except: # noqa: E722 - log.debugWarning("Error releasing java object",exc_info=True) - - - def __eq__(self,jabContext): - if self.vmID==jabContext.vmID and bridgeDll.isSameObject(self.vmID,self.accContext,jabContext.accContext): + log.debugWarning("Error releasing java object", exc_info=True) + + def __eq__(self, jabContext): + if self.vmID == jabContext.vmID and bridgeDll.isSameObject( + self.vmID, + self.accContext, + jabContext.accContext, + ): return True else: return False @@ -436,145 +609,173 @@ def __eq__(self,jabContext): def __hash__(self): return super().__hash__() - def __ne__(self,jabContext): - if self.vmID!=jabContext.vmID or not bridgeDll.isSameObject(self.vmID,self.accContext,jabContext.accContext): + def __ne__(self, jabContext): + if self.vmID != jabContext.vmID or not bridgeDll.isSameObject( + self.vmID, + self.accContext, + jabContext.accContext, + ): return True else: return False def getVersionInfo(self): - info=AccessBridgeVersionInfo() - bridgeDll.getVersionInfo(self.vmID,byref(info)) + info = AccessBridgeVersionInfo() + bridgeDll.getVersionInfo(self.vmID, byref(info)) return info def getObjectDepth(self): - return bridgeDll.getObjectDepth(self.vmID,self.accContext) + return bridgeDll.getObjectDepth(self.vmID, self.accContext) def getAccessibleContextInfo(self): - info=AccessibleContextInfo() - bridgeDll.getAccessibleContextInfo(self.vmID,self.accContext,byref(info)) + info = AccessibleContextInfo() + bridgeDll.getAccessibleContextInfo(self.vmID, self.accContext, byref(info)) return info - def getAccessibleTextInfo(self,x,y): - textInfo=AccessibleTextInfo() - bridgeDll.getAccessibleTextInfo(self.vmID,self.accContext,byref(textInfo),x,y) + def getAccessibleTextInfo(self, x, y): + textInfo = AccessibleTextInfo() + bridgeDll.getAccessibleTextInfo(self.vmID, self.accContext, byref(textInfo), x, y) return textInfo - def getAccessibleTextItems(self,index): - textItemsInfo=AccessibleTextItemsInfo() - bridgeDll.getAccessibleTextItems(self.vmID,self.accContext,byref(textItemsInfo),index) + def getAccessibleTextItems(self, index): + textItemsInfo = AccessibleTextItemsInfo() + bridgeDll.getAccessibleTextItems(self.vmID, self.accContext, byref(textItemsInfo), index) return textItemsInfo def getAccessibleTextSelectionInfo(self): - textSelectionInfo=AccessibleTextSelectionInfo() - bridgeDll.getAccessibleTextSelectionInfo(self.vmID,self.accContext,byref(textSelectionInfo)) + textSelectionInfo = AccessibleTextSelectionInfo() + bridgeDll.getAccessibleTextSelectionInfo(self.vmID, self.accContext, byref(textSelectionInfo)) return textSelectionInfo - def getAccessibleTextRange(self,start,end): - length=((end+1)-start) - if length<=0: - return u"" + def getAccessibleTextRange(self, start, end): + length = (end + 1) - start + if length <= 0: + return "" # Use a string buffer, as from an unicode buffer, we can't get the raw data. - buf = create_string_buffer((length +1) * 2) + buf = create_string_buffer((length + 1) * 2) bridgeDll.getAccessibleTextRange(self.vmID, self.accContext, start, end, buf, length) return textUtils.getTextFromRawBytes(buf.raw, numChars=length, encoding=textUtils.WCHAR_ENCODING) - def getAccessibleTextLineBounds(self,index): - index=max(index,0) - log.debug("lineBounds: index %s"%index) - #Java returns end as the last character, not end as past the last character - startIndex=c_int() - endIndex=c_int() - bridgeDll.getAccessibleTextLineBounds(self.vmID,self.accContext,index,byref(startIndex),byref(endIndex)) - start=startIndex.value - end=endIndex.value - log.debug("line bounds: start %s, end %s"%(start,end)) - if end(index+1): + bridgeDll.getAccessibleTextLineBounds( + self.vmID, + self.accContext, + end, + byref(startIndex), + byref(endIndex), + ) + tempStart = max(startIndex.value, 0) + tempEnd = max(endIndex.value, 0) + log.debug("line bounds: tempStart %s, tempEnd %s" % (tempStart, tempEnd)) + if tempStart > (index + 1): # This line starts after the requested index, so set end to point at the line before. - end=tempStart-1 + end = tempStart - 1 else: - ok=True - ok=False + ok = True + ok = False # Try to retract the start. while not ok: - bridgeDll.getAccessibleTextLineBounds(self.vmID,self.accContext,start,byref(startIndex),byref(endIndex)) - tempStart=max(startIndex.value,0) - tempEnd=max(endIndex.value,0) - log.debug("line bounds: tempStart %s, tempEnd %s"%(tempStart,tempEnd)) - if tempEnd<(index-1): + bridgeDll.getAccessibleTextLineBounds( + self.vmID, + self.accContext, + start, + byref(startIndex), + byref(endIndex), + ) + tempStart = max(startIndex.value, 0) + tempEnd = max(endIndex.value, 0) + log.debug("line bounds: tempStart %s, tempEnd %s" % (tempStart, tempEnd)) + if tempEnd < (index - 1): # This line ends before the requested index, so set start to point at the line after. - start=tempEnd+1 + start = tempEnd + 1 else: - ok=True - log.debug("line bounds: returning %s, %s"%(start,end)) - return (start,end) - + ok = True + log.debug("line bounds: returning %s, %s" % (start, end)) + return (start, end) def getAccessibleParentFromContext(self): - accContext=bridgeDll.getAccessibleParentFromContext(self.vmID,self.accContext) + accContext = bridgeDll.getAccessibleParentFromContext(self.vmID, self.accContext) if accContext: - return self.__class__(self.hwnd,self.vmID,accContext) + return self.__class__(self.hwnd, self.vmID, accContext) else: return None def getAccessibleParentWithRole(self, role): - accContext=bridgeDll.getParentWithRole(self.vmID,self.accContext, role) + accContext = bridgeDll.getParentWithRole(self.vmID, self.accContext, role) if accContext: - return self.__class__(self.hwnd,self.vmID,accContext) + return self.__class__(self.hwnd, self.vmID, accContext) else: return None - def getAccessibleChildFromContext(self,index): - accContext=bridgeDll.getAccessibleChildFromContext(self.vmID,self.accContext,index) + def getAccessibleChildFromContext(self, index): + accContext = bridgeDll.getAccessibleChildFromContext(self.vmID, self.accContext, index) if accContext: - return self.__class__(self.hwnd,self.vmID,accContext) + return self.__class__(self.hwnd, self.vmID, accContext) else: return None def getActiveDescendent(self): - accContext=bridgeDll.getActiveDescendent(self.vmID,self.accContext) + accContext = bridgeDll.getActiveDescendent(self.vmID, self.accContext) if accContext: - return self.__class__(self.hwnd,self.vmID,accContext) + return self.__class__(self.hwnd, self.vmID, accContext) else: return None - def getAccessibleContextAt(self,x,y): - newAccContext=JOBJECT64() - res=bridgeDll.getAccessibleContextAt(self.vmID,self.accContext,x,y,byref(newAccContext)) + def getAccessibleContextAt(self, x, y): + newAccContext = JOBJECT64() + res = bridgeDll.getAccessibleContextAt(self.vmID, self.accContext, x, y, byref(newAccContext)) if not res or not newAccContext: return None - if not bridgeDll.isSameObject(self.vmID,newAccContext,self.accContext): - return self.__class__(self.hwnd,self.vmID,newAccContext) - elif newAccContext!=self.accContext: - bridgeDll.releaseJavaObject(self.vmID,newAccContext) + if not bridgeDll.isSameObject(self.vmID, newAccContext, self.accContext): + return self.__class__(self.hwnd, self.vmID, newAccContext) + elif newAccContext != self.accContext: + bridgeDll.releaseJavaObject(self.vmID, newAccContext) return None def getCurrentAccessibleValueFromContext(self): - buf=create_unicode_buffer(SHORT_STRING_SIZE+1) - bridgeDll.getCurrentAccessibleValueFromContext(self.vmID,self.accContext,buf,SHORT_STRING_SIZE) + buf = create_unicode_buffer(SHORT_STRING_SIZE + 1) + bridgeDll.getCurrentAccessibleValueFromContext(self.vmID, self.accContext, buf, SHORT_STRING_SIZE) return buf.value def selectTextRange(self, start: int, end: int) -> None: bridgeDll.selectTextRange(self.vmID, self.accContext, start, end) - def setCaretPosition(self,offset): - bridgeDll.setCaretPosition(self.vmID,self.accContext,offset) + def setCaretPosition(self, offset): + bridgeDll.setCaretPosition(self.vmID, self.accContext, offset) def getTextAttributesInRange(self, startIndex, endIndex): attributes = AccessibleTextAttributesInfo() length = c_short() - bridgeDll.getTextAttributesInRange(self.vmID, self.accContext, startIndex, endIndex, byref(attributes), byref(length)) + bridgeDll.getTextAttributesInRange( + self.vmID, + self.accContext, + startIndex, + endIndex, + byref(attributes), + byref(length), + ) return attributes, length.value def getAccessibleTextRect(self, index): @@ -588,46 +789,74 @@ def getAccessibleRelationSet(self): return relations def getAccessibleTableInfo(self): - info=AccessibleTableInfo() - if bridgeDll.getAccessibleTableInfo(self.vmID,self.accContext,byref(info)): + info = AccessibleTableInfo() + if bridgeDll.getAccessibleTableInfo(self.vmID, self.accContext, byref(info)): # #6992: Querying the hwnd for table related objects can cause the app to crash. # A table is almost certainly contained within a single hwnd, # so just pass the hwnd for the querying object. - info.jabCaption=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.caption) if info.caption else None - info.jabSummary=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.summary) if info.summary else None - info.jabContext=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.accessibleContext) if info.accessibleContext else None - info.jabTable=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.accessibleTable) if info.accessibleTable else None + info.jabCaption = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.caption) if info.caption else None + ) + info.jabSummary = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.summary) if info.summary else None + ) + info.jabContext = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.accessibleContext) + if info.accessibleContext + else None + ) + info.jabTable = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.accessibleTable) + if info.accessibleTable + else None + ) return info - def getAccessibleTableCellInfo(self,row,col): - info=AccessibleTableCellInfo() - if bridgeDll.getAccessibleTableCellInfo(self.vmID,self.accContext,row,col,byref(info)): + def getAccessibleTableCellInfo(self, row, col): + info = AccessibleTableCellInfo() + if bridgeDll.getAccessibleTableCellInfo(self.vmID, self.accContext, row, col, byref(info)): # #6992: Querying the hwnd for table related objects can cause the app to crash. # A table is almost certainly contained within a single hwnd, # so just pass the hwnd for the querying object. - info.jabContext=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.accessibleContext) if info.accessibleContext else None + info.jabContext = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.accessibleContext) + if info.accessibleContext + else None + ) return info - def getAccessibleTableRow(self,index): - return bridgeDll.getAccessibleTableRow(self.vmID,self.accContext,index) + def getAccessibleTableRow(self, index): + return bridgeDll.getAccessibleTableRow(self.vmID, self.accContext, index) - def getAccessibleTableColumn(self,index): - return bridgeDll.getAccessibleTableColumn(self.vmID,self.accContext,index) + def getAccessibleTableColumn(self, index): + return bridgeDll.getAccessibleTableColumn(self.vmID, self.accContext, index) def getAccessibleTableRowHeader(self): - info=AccessibleTableInfo() - if bridgeDll.getAccessibleTableRowHeader(self.vmID,self.accContext,byref(info)): + info = AccessibleTableInfo() + if bridgeDll.getAccessibleTableRowHeader(self.vmID, self.accContext, byref(info)): # #6992: Querying the hwnd for table related objects can cause the app to crash. # A table is almost certainly contained within a single hwnd, # so just pass the hwnd for the querying object. - info.jabCaption=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.caption) if info.caption else None - info.jabSummary=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.summary) if info.summary else None - info.jabContext=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.accessibleContext) if info.accessibleContext else None - info.jabTable=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.accessibleTable) if info.accessibleTable else None + info.jabCaption = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.caption) if info.caption else None + ) + info.jabSummary = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.summary) if info.summary else None + ) + info.jabContext = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.accessibleContext) + if info.accessibleContext + else None + ) + info.jabTable = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.accessibleTable) + if info.accessibleTable + else None + ) return info - def getAccessibleTableRowDescription(self,row): - accContext=bridgeDll.getAccessibleTableRowDescription(self.vmID,self.accContext,row) + def getAccessibleTableRowDescription(self, row): + accContext = bridgeDll.getAccessibleTableRowDescription(self.vmID, self.accContext, row) if accContext: # #6992: Querying the hwnd for table related objects can cause the app to crash. # A table is almost certainly contained within a single hwnd, @@ -635,19 +864,31 @@ def getAccessibleTableRowDescription(self,row): return JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=accContext) def getAccessibleTableColumnHeader(self): - info=AccessibleTableInfo() - if bridgeDll.getAccessibleTableColumnHeader(self.vmID,self.accContext,byref(info)): + info = AccessibleTableInfo() + if bridgeDll.getAccessibleTableColumnHeader(self.vmID, self.accContext, byref(info)): # #6992: Querying the hwnd for table related objects can cause the app to crash. # A table is almost certainly contained within a single hwnd, # so just pass the hwnd for the querying object. - info.jabCaption=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.caption) if info.caption else None - info.jabSummary=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.summary) if info.summary else None - info.jabContext=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.accessibleContext) if info.accessibleContext else None - info.jabTable=JABContext(hwnd=self.hwnd,vmID=self.vmID,accContext=info.accessibleTable) if info.accessibleTable else None + info.jabCaption = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.caption) if info.caption else None + ) + info.jabSummary = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.summary) if info.summary else None + ) + info.jabContext = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.accessibleContext) + if info.accessibleContext + else None + ) + info.jabTable = ( + JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=info.accessibleTable) + if info.accessibleTable + else None + ) return info - def getAccessibleTableColumnDescription(self,column): - accContext=bridgeDll.getAccessibleTableColumnDescription(self.vmID,self.accContext,column) + def getAccessibleTableColumnDescription(self, column): + accContext = bridgeDll.getAccessibleTableColumnDescription(self.vmID, self.accContext, column) if accContext: # #6992: Querying the hwnd for table related objects can cause the app to crash. # A table is almost certainly contained within a single hwnd, @@ -655,27 +896,30 @@ def getAccessibleTableColumnDescription(self,column): return JABContext(hwnd=self.hwnd, vmID=self.vmID, accContext=accContext) def getAccessibleKeyBindings(self): - bindings=AccessibleKeyBindings() - if bridgeDll.getAccessibleKeyBindings(self.vmID,self.accContext,byref(bindings)): + bindings = AccessibleKeyBindings() + if bridgeDll.getAccessibleKeyBindings(self.vmID, self.accContext, byref(bindings)): return bindings + @AccessBridge_FocusGainedFP -def internal_event_focusGained(vmID, event,source): - hwnd=getWindowHandleFromAccContext(vmID,source) - internalQueueFunction(event_gainFocus,vmID,source,hwnd) - bridgeDll.releaseJavaObject(vmID,event) - -def event_gainFocus(vmID,accContext,hwnd): - jabContext=JABContext(hwnd=hwnd,vmID=vmID,accContext=accContext) - if not winUser.isDescendantWindow(winUser.getForegroundWindow(),jabContext.hwnd): +def internal_event_focusGained(vmID, event, source): + hwnd = getWindowHandleFromAccContext(vmID, source) + internalQueueFunction(event_gainFocus, vmID, source, hwnd) + bridgeDll.releaseJavaObject(vmID, event) + + +def event_gainFocus(vmID, accContext, hwnd): + jabContext = JABContext(hwnd=hwnd, vmID=vmID, accContext=accContext) + if not winUser.isDescendantWindow(winUser.getForegroundWindow(), jabContext.hwnd): + return + focus = eventHandler.lastQueuedFocusObject + if isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext: return - focus=eventHandler.lastQueuedFocusObject - if (isinstance(focus,NVDAObjects.JAB.JAB) and focus.jabContext==jabContext): - return - obj=NVDAObjects.JAB.JAB(jabContext=jabContext) - if obj.role==controlTypes.Role.UNKNOWN: + obj = NVDAObjects.JAB.JAB(jabContext=jabContext) + if obj.role == controlTypes.Role.UNKNOWN: return - eventHandler.queueEvent("gainFocus",obj) + eventHandler.queueEvent("gainFocus", obj) + @AccessBridge_PropertyActiveDescendentChangeFP def internal_event_activeDescendantChange(vmID, event, source, oldDescendant, newDescendant): @@ -696,89 +940,109 @@ def internal_hasFocus(sourceContext): @AccessBridge_PropertyNameChangeFP -def event_nameChange(vmID,event,source,oldVal,newVal): +def event_nameChange(vmID, event, source, oldVal, newVal): jabContext = JABContext(vmID=vmID, accContext=source) if jabContext.hwnd: focus = api.getFocusObject() - obj = focus if ( - isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext - ) else NVDAObjects.JAB.JAB(jabContext=jabContext) + obj = ( + focus + if (isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext) + else NVDAObjects.JAB.JAB(jabContext=jabContext) + ) if obj: eventHandler.queueEvent("nameChange", obj) else: log.debugWarning("Unable to obtain window handle for accessible context") - bridgeDll.releaseJavaObject(vmID,event) + bridgeDll.releaseJavaObject(vmID, event) + @AccessBridge_PropertyDescriptionChangeFP -def event_descriptionChange(vmID,event,source,oldVal,newVal): +def event_descriptionChange(vmID, event, source, oldVal, newVal): jabContext = JABContext(vmID=vmID, accContext=source) if jabContext.hwnd: focus = api.getFocusObject() - obj = focus if ( - isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext - ) else NVDAObjects.JAB.JAB(jabContext=jabContext) + obj = ( + focus + if (isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext) + else NVDAObjects.JAB.JAB(jabContext=jabContext) + ) if obj: eventHandler.queueEvent("descriptionChange", obj) else: log.debugWarning("Unable to obtain window handle for accessible context") - bridgeDll.releaseJavaObject(vmID,event) + bridgeDll.releaseJavaObject(vmID, event) + @AccessBridge_PropertyValueChangeFP -def event_valueChange(vmID,event,source,oldVal,newVal): +def event_valueChange(vmID, event, source, oldVal, newVal): jabContext = JABContext(vmID=vmID, accContext=source) if jabContext.hwnd: focus = api.getFocusObject() - obj = focus if ( - isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext - ) else NVDAObjects.JAB.JAB(jabContext=jabContext) + obj = ( + focus + if (isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext) + else NVDAObjects.JAB.JAB(jabContext=jabContext) + ) if obj: eventHandler.queueEvent("valueChange", obj) else: log.debugWarning("Unable to obtain window handle for accessible context") - bridgeDll.releaseJavaObject(vmID,event) + bridgeDll.releaseJavaObject(vmID, event) + @AccessBridge_PropertyStateChangeFP -def internal_event_stateChange(vmID,event,source,oldState,newState): - internalQueueFunction(event_stateChange,vmID,source,oldState,newState) - bridgeDll.releaseJavaObject(vmID,event) +def internal_event_stateChange(vmID, event, source, oldState, newState): + internalQueueFunction(event_stateChange, vmID, source, oldState, newState) + bridgeDll.releaseJavaObject(vmID, event) + -def event_stateChange(vmID,accContext,oldState,newState): +def event_stateChange(vmID, accContext, oldState, newState): jabContext = JABContext(vmID=vmID, accContext=accContext) if not jabContext.hwnd: log.debugWarning("Unable to obtain window handle for accessible context") return focus = api.getFocusObject() - #For broken tabs and menus, we need to watch for things being selected and pretend its a focus change - stateList = newState.split(',') + # For broken tabs and menus, we need to watch for things being selected and pretend its a focus change + stateList = newState.split(",") if "focused" in stateList or "selected" in stateList: obj = NVDAObjects.JAB.JAB(jabContext=jabContext) if not obj: return - if focus!=obj and eventHandler.lastQueuedFocusObject!=obj and obj.role in (controlTypes.Role.MENUITEM,controlTypes.Role.TAB,controlTypes.Role.MENU): - eventHandler.queueEvent("gainFocus",obj) + if ( + focus != obj + and eventHandler.lastQueuedFocusObject != obj + and obj.role in (controlTypes.Role.MENUITEM, controlTypes.Role.TAB, controlTypes.Role.MENU) + ): + eventHandler.queueEvent("gainFocus", obj) return - obj = focus if ( - isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext - ) else NVDAObjects.JAB.JAB(jabContext=jabContext) + obj = ( + focus + if (isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext) + else NVDAObjects.JAB.JAB(jabContext=jabContext) + ) if obj: eventHandler.queueEvent("stateChange", obj) + @AccessBridge_PropertyCaretChangeFP -def internal_event_caretChange(vmID, event,source,oldPos,newPos): - hwnd=getWindowHandleFromAccContext(vmID,source) - if oldPos<0 and newPos>=0: - internalQueueFunction(event_gainFocus,vmID,source,hwnd) +def internal_event_caretChange(vmID, event, source, oldPos, newPos): + hwnd = getWindowHandleFromAccContext(vmID, source) + if oldPos < 0 and newPos >= 0: + internalQueueFunction(event_gainFocus, vmID, source, hwnd) else: - internalQueueFunction(event_caret,vmID,source,hwnd) - bridgeDll.releaseJavaObject(vmID,event) + internalQueueFunction(event_caret, vmID, source, hwnd) + bridgeDll.releaseJavaObject(vmID, event) + def event_caret(vmID, accContext, hwnd): jabContext = JABContext(hwnd=hwnd, vmID=vmID, accContext=accContext) if jabContext.hwnd: focus = api.getFocusObject() - obj = focus if ( - isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext - ) else NVDAObjects.JAB.JAB(jabContext=jabContext) + obj = ( + focus + if (isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == jabContext) + else NVDAObjects.JAB.JAB(jabContext=jabContext) + ) if obj: eventHandler.queueEvent("caret", obj) else: @@ -786,31 +1050,33 @@ def event_caret(vmID, accContext, hwnd): def event_enterJavaWindow(hwnd): - internalQueueFunction(enterJavaWindow_helper,hwnd) + internalQueueFunction(enterJavaWindow_helper, hwnd) + def enterJavaWindow_helper(hwnd): - vmID=c_long() - accContext=JOBJECT64() - timeout=time.time()+0.2 - while time.time() SystemErrorCodes: focus = api.getFocusObject() if focus.sleepMode == focus.SLEEP_FULL: @@ -168,60 +171,85 @@ def markCallable(name: str): @WINFUNCTYPE(c_long) def nvdaController_cancelSpeech(): - focus=api.getFocusObject() - if focus.sleepMode==focus.SLEEP_FULL: + focus = api.getFocusObject() + if focus.sleepMode == focus.SLEEP_FULL: return -1 import speech - queueHandler.queueFunction(queueHandler.eventQueue,speech.cancelSpeech) + + queueHandler.queueFunction(queueHandler.eventQueue, speech.cancelSpeech) return SystemErrorCodes.SUCCESS -@WINFUNCTYPE(c_long,c_wchar_p) +@WINFUNCTYPE(c_long, c_wchar_p) def nvdaController_brailleMessage(text: str) -> SystemErrorCodes: - focus=api.getFocusObject() - if focus.sleepMode==focus.SLEEP_FULL: + focus = api.getFocusObject() + if focus.sleepMode == focus.SLEEP_FULL: return -1 if config.conf["braille"]["reportLiveRegions"]: import braille + queueHandler.queueFunction(queueHandler.eventQueue, braille.handler.message, text) return SystemErrorCodes.SUCCESS def _lookupKeyboardLayoutNameWithHexString(layoutString): - buf=create_unicode_buffer(1024) - bufSize=c_int(2048) - key=HKEY() # noqa: F405 - if windll.advapi32.RegOpenKeyExW(winreg.HKEY_LOCAL_MACHINE,u"SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\"+ layoutString,0,winreg.KEY_QUERY_VALUE,byref(key))==0: # noqa: F405 + buf = create_unicode_buffer(1024) + bufSize = c_int(2048) + key = HKEY() # noqa: F405 + if ( + windll.advapi32.RegOpenKeyExW( + winreg.HKEY_LOCAL_MACHINE, + "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\" + layoutString, + 0, + winreg.KEY_QUERY_VALUE, + byref(key), # noqa: F405 + ) + == 0 + ): # noqa: F405 try: - if windll.advapi32.RegQueryValueExW(key,u"Layout Display Name",0,None,buf,byref(bufSize))==0: # noqa: F405 - windll.shlwapi.SHLoadIndirectString(buf.value,buf,1023,None) + if ( + windll.advapi32.RegQueryValueExW(key, "Layout Display Name", 0, None, buf, byref(bufSize)) # noqa: F405 + == 0 + ): # noqa: F405 + windll.shlwapi.SHLoadIndirectString(buf.value, buf, 1023, None) return buf.value - if windll.advapi32.RegQueryValueExW(key,u"Layout Text",0,None,buf,byref(bufSize))==0: # noqa: F405 + if windll.advapi32.RegQueryValueExW(key, "Layout Text", 0, None, buf, byref(bufSize)) == 0: # noqa: F405 return buf.value finally: windll.advapi32.RegCloseKey(key) -@WINFUNCTYPE(c_long,c_wchar_p) + +@WINFUNCTYPE(c_long, c_wchar_p) def nvdaControllerInternal_requestRegistration(uuidString): - pid=c_long() - windll.rpcrt4.I_RpcBindingInqLocalClientPID(None,byref(pid)) # noqa: F405 - pid=pid.value + pid = c_long() + windll.rpcrt4.I_RpcBindingInqLocalClientPID(None, byref(pid)) # noqa: F405 + pid = pid.value if not pid: log.error("Could not get process ID for RPC call") return -1 - bindingHandle=c_long() - bindingHandle.value=localLib.createRemoteBindingHandle(uuidString) - if not bindingHandle: - log.error("Could not bind to inproc rpc server for pid %d"%pid) + bindingHandle = c_long() + bindingHandle.value = localLib.createRemoteBindingHandle(uuidString) + if not bindingHandle: + log.error("Could not bind to inproc rpc server for pid %d" % pid) return -1 - registrationHandle=c_long() - res=localLib.nvdaInProcUtils_registerNVDAProcess(bindingHandle,byref(registrationHandle)) # noqa: F405 - if res!=0 or not registrationHandle: - log.error("Could not register NVDA with inproc rpc server for pid %d, res %d, registrationHandle %s"%(pid,res,registrationHandle)) + registrationHandle = c_long() + res = localLib.nvdaInProcUtils_registerNVDAProcess(bindingHandle, byref(registrationHandle)) # noqa: F405 + if res != 0 or not registrationHandle: + log.error( + "Could not register NVDA with inproc rpc server for pid %d, res %d, registrationHandle %s" + % (pid, res, registrationHandle), + ) windll.rpcrt4.RpcBindingFree(byref(bindingHandle)) # noqa: F405 return -1 import appModuleHandler - queueHandler.queueFunction(queueHandler.eventQueue,appModuleHandler.update,pid,helperLocalBindingHandle=bindingHandle,inprocRegistrationHandle=registrationHandle) + + queueHandler.queueFunction( + queueHandler.eventQueue, + appModuleHandler.update, + pid, + helperLocalBindingHandle=bindingHandle, + inprocRegistrationHandle=registrationHandle, + ) return 0 @@ -238,10 +266,14 @@ def nvdaControllerInternal_reportLiveRegion(text: str, politeness: str): import braille from aria import AriaLivePoliteness from speech.priorities import Spri + try: politenessValue = AriaLivePoliteness(politeness.lower()) except ValueError: - log.error(f"nvdaControllerInternal_reportLiveRegion got unknown politeness of {politeness}", exc_info=True) + log.error( + f"nvdaControllerInternal_reportLiveRegion got unknown politeness of {politeness}", + exc_info=True, + ) return -1 if politenessValue == AriaLivePoliteness.OFF: log.error(f"nvdaControllerInternal_reportLiveRegion got unexpected politeness of {politeness}") @@ -249,11 +281,7 @@ def nvdaControllerInternal_reportLiveRegion(text: str, politeness: str): queueHandler.eventQueue, speech.speakText, text, - priority=( - Spri.NEXT - if politenessValue == AriaLivePoliteness.ASSERTIVE - else Spri.NORMAL - ), + priority=(Spri.NEXT if politenessValue == AriaLivePoliteness.ASSERTIVE else Spri.NORMAL), ) queueHandler.queueFunction( queueHandler.eventQueue, @@ -262,155 +290,204 @@ def nvdaControllerInternal_reportLiveRegion(text: str, politeness: str): ) return 0 -@WINFUNCTYPE(c_long,c_long,c_long,c_long,c_long,c_long) + +@WINFUNCTYPE(c_long, c_long, c_long, c_long, c_long, c_long) def nvdaControllerInternal_displayModelTextChangeNotify(hwnd, left, top, right, bottom): import displayModel + displayModel.textChangeNotify(hwnd, left, top, right, bottom) return 0 -@WINFUNCTYPE(c_long,c_long,c_long,c_long,c_long,c_long) + +@WINFUNCTYPE(c_long, c_long, c_long, c_long, c_long, c_long) def nvdaControllerInternal_drawFocusRectNotify(hwnd, left, top, right, bottom): import eventHandler from NVDAObjects.window import Window - focus=api.getFocusObject() - if isinstance(focus,Window) and hwnd==focus.windowHandle: - eventHandler.queueEvent("displayModel_drawFocusRectNotify",focus,rect=(left,top,right,bottom)) + + focus = api.getFocusObject() + if isinstance(focus, Window) and hwnd == focus.windowHandle: + eventHandler.queueEvent("displayModel_drawFocusRectNotify", focus, rect=(left, top, right, bottom)) return 0 -@WINFUNCTYPE(c_long,c_long,c_long,c_wchar_p) -def nvdaControllerInternal_logMessage(level,pid,message): + +@WINFUNCTYPE(c_long, c_long, c_long, c_wchar_p) +def nvdaControllerInternal_logMessage(level, pid, message): if not log.isEnabledFor(level): return 0 if pid: from appModuleHandler import getAppNameFromProcessID - codepath="RPC process %s (%s)"%(pid,getAppNameFromProcessID(pid,includeExt=True)) + + codepath = "RPC process %s (%s)" % (pid, getAppNameFromProcessID(pid, includeExt=True)) else: - codepath="NVDAHelperLocal" - log._log(level,message,[],codepath=codepath) + codepath = "NVDAHelperLocal" + log._log(level, message, [], codepath=codepath) return 0 + def handleInputCompositionEnd(result): import speech import characterProcessing from NVDAObjects.inputComposition import InputComposition from NVDAObjects.IAccessible.mscandui import ModernCandidateUICandidateItem - focus=api.getFocusObject() - result=result.lstrip(u'\u3000 ') - curInputComposition=None - if isinstance(focus,InputComposition): - curInputComposition=focus + + focus = api.getFocusObject() + result = result.lstrip("\u3000 ") + curInputComposition = None + if isinstance(focus, InputComposition): + curInputComposition = focus oldSpeechMode = speech.getState().speechMode speech.setSpeechMode(speech.SpeechMode.off) - eventHandler.executeEvent("gainFocus",focus.parent) + eventHandler.executeEvent("gainFocus", focus.parent) speech.setSpeechMode(oldSpeechMode) - elif isinstance(focus.parent,InputComposition): - #Candidate list is still up - curInputComposition=focus.parent - focus.parent=focus.parent.parent + elif isinstance(focus.parent, InputComposition): + # Candidate list is still up + curInputComposition = focus.parent + focus.parent = focus.parent.parent if isinstance(focus, ModernCandidateUICandidateItem): # Correct focus for ModernCandidateUICandidateItem # Find the InputComposition object and # correct focus to its parent if isinstance(focus.container, InputComposition): - curInputComposition=focus.container - newFocus=curInputComposition.parent + curInputComposition = focus.container + newFocus = curInputComposition.parent else: # Sometimes InputCompositon object is gone # Correct to container of CandidateItem - newFocus=focus.container + newFocus = focus.container oldSpeechMode = speech.getState().speechMode speech.setSpeechMode(speech.SpeechMode.off) - eventHandler.executeEvent("gainFocus",newFocus) + eventHandler.executeEvent("gainFocus", newFocus) speech.setSpeechMode(oldSpeechMode) if curInputComposition and not result: - result=curInputComposition.compositionString.lstrip(u'\u3000 ') + result = curInputComposition.compositionString.lstrip("\u3000 ") if result: speech.speakText(result, symbolLevel=characterProcessing.SymbolLevel.ALL) -def handleInputCompositionStart(compositionString,selectionStart,selectionEnd,isReading): + +def handleInputCompositionStart(compositionString, selectionStart, selectionEnd, isReading): import speech from NVDAObjects.inputComposition import InputComposition from NVDAObjects.behaviors import CandidateItem - focus=api.getFocusObject() - if focus.parent and isinstance(focus.parent,InputComposition): - #Candidates infront of existing composition string - announce=not config.conf["inputComposition"]["announceSelectedCandidate"] - focus.parent.compositionUpdate(compositionString,selectionStart,selectionEnd,isReading,announce=announce) + + focus = api.getFocusObject() + if focus.parent and isinstance(focus.parent, InputComposition): + # Candidates infront of existing composition string + announce = not config.conf["inputComposition"]["announceSelectedCandidate"] + focus.parent.compositionUpdate( + compositionString, + selectionStart, + selectionEnd, + isReading, + announce=announce, + ) return 0 - #IME keeps updating input composition while the candidate list is open - #Therefore ignore new composition updates if candidate selections are configured for speaking. - if config.conf["inputComposition"]["announceSelectedCandidate"] and isinstance(focus,CandidateItem): + # IME keeps updating input composition while the candidate list is open + # Therefore ignore new composition updates if candidate selections are configured for speaking. + if config.conf["inputComposition"]["announceSelectedCandidate"] and isinstance(focus, CandidateItem): return 0 - if not isinstance(focus,InputComposition): - parent=api.getDesktopObject().objectWithFocus() + if not isinstance(focus, InputComposition): + parent = api.getDesktopObject().objectWithFocus() # #5640: Although we want to use the most correct focus (I.e. OS, not NVDA), if they are the same, we definitely want to use the original instance, so that state such as auto selection is maintained. - if parent==focus: - parent=focus - curInputComposition=InputComposition(parent=parent) + if parent == focus: + parent = focus + curInputComposition = InputComposition(parent=parent) oldSpeechMode = speech.getState().speechMode speech.setSpeechMode(speech.SpeechMode.off) - eventHandler.executeEvent("gainFocus",curInputComposition) - focus=curInputComposition + eventHandler.executeEvent("gainFocus", curInputComposition) + focus = curInputComposition speech.setSpeechMode(oldSpeechMode) - focus.compositionUpdate(compositionString,selectionStart,selectionEnd,isReading) + focus.compositionUpdate(compositionString, selectionStart, selectionEnd, isReading) -@WINFUNCTYPE(c_long,c_wchar_p,c_int,c_int,c_int) -def nvdaControllerInternal_inputCompositionUpdate(compositionString,selectionStart,selectionEnd,isReading): + +@WINFUNCTYPE(c_long, c_wchar_p, c_int, c_int, c_int) +def nvdaControllerInternal_inputCompositionUpdate(compositionString, selectionStart, selectionEnd, isReading): from NVDAObjects.inputComposition import InputComposition from NVDAObjects.IAccessible.mscandui import ModernCandidateUICandidateItem - if selectionStart==-1: - queueHandler.queueFunction(queueHandler.eventQueue,handleInputCompositionEnd,compositionString) + + if selectionStart == -1: + queueHandler.queueFunction(queueHandler.eventQueue, handleInputCompositionEnd, compositionString) return 0 - focus=api.getFocusObject() - if isinstance(focus,InputComposition): - focus.compositionUpdate(compositionString,selectionStart,selectionEnd,isReading) + focus = api.getFocusObject() + if isinstance(focus, InputComposition): + focus.compositionUpdate(compositionString, selectionStart, selectionEnd, isReading) # Eliminate InputCompositionStart events from Microsoft Pinyin to avoid reading composition string instead of candidates - elif not isinstance(focus,ModernCandidateUICandidateItem): - queueHandler.queueFunction(queueHandler.eventQueue,handleInputCompositionStart,compositionString,selectionStart,selectionEnd,isReading) + elif not isinstance(focus, ModernCandidateUICandidateItem): + queueHandler.queueFunction( + queueHandler.eventQueue, + handleInputCompositionStart, + compositionString, + selectionStart, + selectionEnd, + isReading, + ) return 0 -def handleInputCandidateListUpdate(candidatesString,selectionIndex,inputMethod): - candidateStrings=candidatesString.split('\n') + +def handleInputCandidateListUpdate(candidatesString, selectionIndex, inputMethod): + candidateStrings = candidatesString.split("\n") import speech from NVDAObjects.inputComposition import CandidateItem - focus=api.getFocusObject() - if not (0<=selectionIndex0: - queueHandler.queueFunction(queueHandler.eventQueue,ui.message," ".join(textList)) + if len(textList) > 0: + queueHandler.queueFunction(queueHandler.eventQueue, ui.message, " ".join(textList)) + -@WINFUNCTYPE(c_long,c_long,c_long,c_ulong) -def nvdaControllerInternal_inputConversionModeUpdate(oldFlags,newFlags,lcid): - queueHandler.queueFunction(queueHandler.eventQueue,handleInputConversionModeUpdate,oldFlags,newFlags,lcid) +@WINFUNCTYPE(c_long, c_long, c_long, c_ulong) +def nvdaControllerInternal_inputConversionModeUpdate(oldFlags, newFlags, lcid): + queueHandler.queueFunction( + queueHandler.eventQueue, + handleInputConversionModeUpdate, + oldFlags, + newFlags, + lcid, + ) return 0 -@WINFUNCTYPE(c_long,c_long) + +@WINFUNCTYPE(c_long, c_long) def nvdaControllerInternal_IMEOpenStatusUpdate(opened): if opened: # Translators: a message when the IME open status changes to opened - message=_("IME opened") + message = _("IME opened") else: # Translators: a message when the IME open status changes to closed - message=_("IME closed") + message = _("IME closed") import ui - queueHandler.queueFunction(queueHandler.eventQueue,ui.message,message) + + queueHandler.queueFunction(queueHandler.eventQueue, ui.message, message) return 0 -@WINFUNCTYPE(c_long,c_long,c_ulong,c_wchar_p) -def nvdaControllerInternal_inputLangChangeNotify(threadID,hkl,layoutString): + +@WINFUNCTYPE(c_long, c_long, c_ulong, c_wchar_p) +def nvdaControllerInternal_inputLangChangeNotify(threadID, hkl, layoutString): global lastLanguageID, lastLayoutString - languageID=winUser.LOWORD(hkl) - #Simple case where there is no change - if languageID==lastLanguageID and layoutString==lastLayoutString: + languageID = winUser.LOWORD(hkl) + # Simple case where there is no change + if languageID == lastLanguageID and layoutString == lastLayoutString: return 0 - focus=api.getFocusObject() - #This callback can be called before NVDa is fully initialized - #So also handle focus object being None as well as checking for sleepMode + focus = api.getFocusObject() + # This callback can be called before NVDa is fully initialized + # So also handle focus object being None as well as checking for sleepMode if not focus or focus.sleepMode: return 0 import NVDAObjects.window - #Generally we should not allow input lang changes from threads that are not focused. - #But threadIDs for console windows are always wrong so don't ignore for those. - if not isinstance(focus,NVDAObjects.window.Window) or (threadID!=focus.windowThreadID and focus.windowClassName!="ConsoleWindowClass"): + + # Generally we should not allow input lang changes from threads that are not focused. + # But threadIDs for console windows are always wrong so don't ignore for those. + if not isinstance(focus, NVDAObjects.window.Window) or ( + threadID != focus.windowThreadID and focus.windowClassName != "ConsoleWindowClass" + ): return 0 from speech import sayAll - #Never announce changes while in sayAll (#1676) + + # Never announce changes while in sayAll (#1676) if sayAll.SayAllHandler.isRunning(): return 0 import ui - buf=create_unicode_buffer(1024) - res=windll.kernel32.GetLocaleInfoW(languageID,2,buf,1024) + + buf = create_unicode_buffer(1024) + res = windll.kernel32.GetLocaleInfoW(languageID, 2, buf, 1024) # Translators: the label for an unknown language when switching input methods. - inputLanguageName=buf.value if res else _("unknown language") - layoutStringCodes=[] - inputMethodName=None - #layoutString can either be a real input method name, a hex string for an input method name in the registry, or an empty string. - #If it is a real input method name, then it is used as is. - #If it is a hex string or it is empty, then the method name is looked up by trying: - #The full hex string, the hkl as a hex string, the low word of the hex string or hkl, the high word of the hex string or hkl. + inputLanguageName = buf.value if res else _("unknown language") + layoutStringCodes = [] + inputMethodName = None + # layoutString can either be a real input method name, a hex string for an input method name in the registry, or an empty string. + # If it is a real input method name, then it is used as is. + # If it is a hex string or it is empty, then the method name is looked up by trying: + # The full hex string, the hkl as a hex string, the low word of the hex string or hkl, the high word of the hex string or hkl. if layoutString: try: - int(layoutString,16) + int(layoutString, 16) layoutStringCodes.append(layoutString) except ValueError: - inputMethodName=layoutString + inputMethodName = layoutString if not inputMethodName: - layoutStringCodes.insert(0,hex(hkl)[2:].rstrip('L').upper().rjust(8,'0')) + layoutStringCodes.insert(0, hex(hkl)[2:].rstrip("L").upper().rjust(8, "0")) for stringCode in list(layoutStringCodes): - layoutStringCodes.append(stringCode[4:].rjust(8,'0')) - if stringCode[0]<'D': - layoutStringCodes.append(stringCode[0:4].rjust(8,'0')) + layoutStringCodes.append(stringCode[4:].rjust(8, "0")) + if stringCode[0] < "D": + layoutStringCodes.append(stringCode[0:4].rjust(8, "0")) for stringCode in layoutStringCodes: - inputMethodName=_lookupKeyboardLayoutNameWithHexString(stringCode) - if inputMethodName: break # noqa: E701 + inputMethodName = _lookupKeyboardLayoutNameWithHexString(stringCode) + if inputMethodName: + break # noqa: E701 if not inputMethodName: - log.debugWarning("Could not find layout name for keyboard layout, reporting as unknown") - # Translators: The label for an unknown input method when switching input methods. - inputMethodName=_("unknown input method") - #Remove the language name if it is in the input method name. - if ' - ' in inputMethodName: - inputMethodName="".join(inputMethodName.split(' - ')[1:]) - #Include the language only if it changed. - if languageID!=lastLanguageID: - msg=u"{language} - {layout}".format(language=inputLanguageName,layout=inputMethodName) + log.debugWarning("Could not find layout name for keyboard layout, reporting as unknown") + # Translators: The label for an unknown input method when switching input methods. + inputMethodName = _("unknown input method") + # Remove the language name if it is in the input method name. + if " - " in inputMethodName: + inputMethodName = "".join(inputMethodName.split(" - ")[1:]) + # Include the language only if it changed. + if languageID != lastLanguageID: + msg = "{language} - {layout}".format(language=inputLanguageName, layout=inputMethodName) else: - msg=inputMethodName - lastLanguageID=languageID - lastLayoutString=layoutString - queueHandler.queueFunction(queueHandler.eventQueue,ui.message,msg) + msg = inputMethodName + lastLanguageID = languageID + lastLayoutString = layoutString + queueHandler.queueFunction(queueHandler.eventQueue, ui.message, msg) return 0 @WINFUNCTYPE(c_long, c_wchar) def nvdaControllerInternal_typedCharacterNotify(ch): - focus=api.getFocusObject() - if focus.windowClassName!="ConsoleWindowClass": + focus = api.getFocusObject() + if focus.windowClassName != "ConsoleWindowClass": eventHandler.queueEvent("typedCharacter", focus, ch=ch) return 0 + @WINFUNCTYPE(c_long, c_int, c_int) def nvdaControllerInternal_vbufChangeNotify(rootDocHandle, rootID): import virtualBuffers + virtualBuffers.VirtualBuffer.changeNotify(rootDocHandle, rootID) return 0 + @WINFUNCTYPE(c_long, c_wchar_p) def nvdaControllerInternal_installAddonPackageFromPath(addonPath): if globalVars.appArgs.launcher: @@ -568,6 +667,7 @@ def nvdaControllerInternal_installAddonPackageFromPath(addonPath): return import wx from gui import addonGui + log.debug("Requesting installation of add-on from %s", addonPath) wx.CallAfter(addonGui.handleRemoteAddonInstall, addonPath) return 0 @@ -582,12 +682,12 @@ def nvdaControllerInternal_openConfigDirectory(): log.debugWarning("Unable to open user config directory while Windows is locked.") return import systemUtils + systemUtils.openUserConfigurationDirectory() return 0 class _RemoteLoader: - def __init__(self, loaderDir: str): # Create a pipe so we can write to stdin of the loader process. pipeReadOrig, self._pipeWrite = winKernel.CreatePipe(None, 0) @@ -600,7 +700,12 @@ def __init__(self, loaderDir: str): with open("nul", "wb") as nul: nulHandle = self._duplicateAsInheritable(msvcrt.get_osfhandle(nul.fileno())) # Set the process to start with the appropriate std* handles. - si = winKernel.STARTUPINFO(dwFlags=winKernel.STARTF_USESTDHANDLES, hSTDInput=pipeRead, hSTDOutput=nulHandle, hSTDError=nulHandle) + si = winKernel.STARTUPINFO( + dwFlags=winKernel.STARTF_USESTDHANDLES, + hSTDInput=pipeRead, + hSTDOutput=nulHandle, + hSTDError=nulHandle, + ) pi = winKernel.PROCESS_INFORMATION() # Even if we have uiAccess privileges, they will not be inherited by default. # Therefore, explicitly specify our own process token, which causes them to be inherited. @@ -635,43 +740,56 @@ def initialize() -> None: global _remoteLib, _remoteLoaderAMD64, _remoteLoaderARM64 global localLib, generateBeep, onSsmlMarkReached, VBuf_getTextInRange global lastLanguageID, lastLayoutString - hkl=c_ulong(windll.User32.GetKeyboardLayout(0)).value - lastLanguageID=winUser.LOWORD(hkl) - KL_NAMELENGTH=9 - buf=create_unicode_buffer(KL_NAMELENGTH) - res=windll.User32.GetKeyboardLayoutNameW(buf) + hkl = c_ulong(windll.User32.GetKeyboardLayout(0)).value + lastLanguageID = winUser.LOWORD(hkl) + KL_NAMELENGTH = 9 + buf = create_unicode_buffer(KL_NAMELENGTH) + res = windll.User32.GetKeyboardLayoutNameW(buf) if res: - lastLayoutString=buf.value - localLib=cdll.LoadLibrary(os.path.join(versionedLibPath,'nvdaHelperLocal.dll')) # noqa: F405 - for name,func in [ - ("nvdaController_speakText",nvdaController_speakText), + lastLayoutString = buf.value + localLib = cdll.LoadLibrary(os.path.join(versionedLibPath, "nvdaHelperLocal.dll")) # noqa: F405 + for name, func in [ + ("nvdaController_speakText", nvdaController_speakText), ("nvdaController_speakSsml", nvdaController_speakSsml), - ("nvdaController_cancelSpeech",nvdaController_cancelSpeech), - ("nvdaController_brailleMessage",nvdaController_brailleMessage), - ("nvdaControllerInternal_requestRegistration",nvdaControllerInternal_requestRegistration), + ("nvdaController_cancelSpeech", nvdaController_cancelSpeech), + ("nvdaController_brailleMessage", nvdaController_brailleMessage), + ("nvdaControllerInternal_requestRegistration", nvdaControllerInternal_requestRegistration), ("nvdaControllerInternal_reportLiveRegion", nvdaControllerInternal_reportLiveRegion), - ("nvdaControllerInternal_inputLangChangeNotify",nvdaControllerInternal_inputLangChangeNotify), - ("nvdaControllerInternal_typedCharacterNotify",nvdaControllerInternal_typedCharacterNotify), - ("nvdaControllerInternal_displayModelTextChangeNotify",nvdaControllerInternal_displayModelTextChangeNotify), - ("nvdaControllerInternal_logMessage",nvdaControllerInternal_logMessage), - ("nvdaControllerInternal_inputCompositionUpdate",nvdaControllerInternal_inputCompositionUpdate), - ("nvdaControllerInternal_inputCandidateListUpdate",nvdaControllerInternal_inputCandidateListUpdate), - ("nvdaControllerInternal_IMEOpenStatusUpdate",nvdaControllerInternal_IMEOpenStatusUpdate), - ("nvdaControllerInternal_inputConversionModeUpdate",nvdaControllerInternal_inputConversionModeUpdate), - ("nvdaControllerInternal_vbufChangeNotify",nvdaControllerInternal_vbufChangeNotify), - ("nvdaControllerInternal_installAddonPackageFromPath",nvdaControllerInternal_installAddonPackageFromPath), - ("nvdaControllerInternal_drawFocusRectNotify",nvdaControllerInternal_drawFocusRectNotify), + ("nvdaControllerInternal_inputLangChangeNotify", nvdaControllerInternal_inputLangChangeNotify), + ("nvdaControllerInternal_typedCharacterNotify", nvdaControllerInternal_typedCharacterNotify), + ( + "nvdaControllerInternal_displayModelTextChangeNotify", + nvdaControllerInternal_displayModelTextChangeNotify, + ), + ("nvdaControllerInternal_logMessage", nvdaControllerInternal_logMessage), + ("nvdaControllerInternal_inputCompositionUpdate", nvdaControllerInternal_inputCompositionUpdate), + ("nvdaControllerInternal_inputCandidateListUpdate", nvdaControllerInternal_inputCandidateListUpdate), + ("nvdaControllerInternal_IMEOpenStatusUpdate", nvdaControllerInternal_IMEOpenStatusUpdate), + ( + "nvdaControllerInternal_inputConversionModeUpdate", + nvdaControllerInternal_inputConversionModeUpdate, + ), + ("nvdaControllerInternal_vbufChangeNotify", nvdaControllerInternal_vbufChangeNotify), + ( + "nvdaControllerInternal_installAddonPackageFromPath", + nvdaControllerInternal_installAddonPackageFromPath, + ), + ("nvdaControllerInternal_drawFocusRectNotify", nvdaControllerInternal_drawFocusRectNotify), ("nvdaControllerInternal_openConfigDirectory", nvdaControllerInternal_openConfigDirectory), ]: try: - _setDllFuncPointer(localLib,"_%s"%name,func) + _setDllFuncPointer(localLib, "_%s" % name, func) except AttributeError as e: - log.error("nvdaHelperLocal function pointer for %s could not be found, possibly old nvdaHelperLocal dll"%name,exc_info=True) + log.error( + "nvdaHelperLocal function pointer for %s could not be found, possibly old nvdaHelperLocal dll" + % name, + exc_info=True, + ) raise e localLib.nvdaHelperLocal_initialize(globalVars.appArgs.secure) - generateBeep=localLib.generateBeep - generateBeep.argtypes=[c_char_p,c_float,c_int,c_int,c_int] # noqa: F405 - generateBeep.restype=c_int + generateBeep = localLib.generateBeep + generateBeep.argtypes = [c_char_p, c_float, c_int, c_int, c_int] # noqa: F405 + generateBeep.restype = c_int onSsmlMarkReached = localLib.nvdaController_onSsmlMarkReached onSsmlMarkReached.argtypes = [c_wchar_p] onSsmlMarkReached.restype = c_ulong @@ -680,7 +798,7 @@ def initialize() -> None: VBuf_getTextInRange = CFUNCTYPE(c_int, c_int, c_int, c_int, POINTER(BSTR), c_int)( # noqa: F405 ("VBuf_getTextInRange", localLib), ((1,), (1,), (1,), (2,), (1,)), - ) + ) if config.isAppX: log.info("Remote injection disabled due to running as a Windows Store Application") return @@ -696,17 +814,17 @@ def initialize() -> None: if not h: log.critical("Error loading nvdaHelperRemote.dll: %s" % WinError()) # noqa: F405 return - _remoteLib=CDLL("nvdaHelperRemote",handle=h) # noqa: F405 + _remoteLib = CDLL("nvdaHelperRemote", handle=h) # noqa: F405 if _remoteLib.injection_initialize() == 0: raise RuntimeError("Error initializing NVDAHelperRemote") if not _remoteLib.installIA2Support(): log.error("Error installing IA2 support") - #Manually start the in-process manager thread for this NVDA main thread now, as a slow system can cause this action to confuse WX + # Manually start the in-process manager thread for this NVDA main thread now, as a slow system can cause this action to confuse WX _remoteLib.initInprocManagerThreadIfNeeded() arch = winVersion.getWinVer().processorArchitecture - if arch == 'AMD64': + if arch == "AMD64": _remoteLoaderAMD64 = _RemoteLoader(versionedLibAMD64Path) - elif arch == 'ARM64': + elif arch == "ARM64": _remoteLoaderARM64 = _RemoteLoader(versionedLibARM64Path) # Windows on ARM from Windows 11 supports running AMD64 apps. # Thus we also need to be able to inject into these. @@ -722,25 +840,29 @@ def terminate(): log.debugWarning("Error uninstalling IA2 support") if _remoteLib.injection_terminate() == 0: raise RuntimeError("Error terminating NVDAHelperRemote") - _remoteLib=None + _remoteLib = None if _remoteLoaderAMD64: _remoteLoaderAMD64.terminate() _remoteLoaderAMD64 = None if _remoteLoaderARM64: _remoteLoaderARM64.terminate() _remoteLoaderARM64 = None - generateBeep=None - VBuf_getTextInRange=None + generateBeep = None + VBuf_getTextInRange = None localLib.nvdaHelperLocal_terminate() - localLib=None + localLib = None + + +LOCAL_WIN10_DLL_PATH = os.path.join(versionedLibPath, "nvdaHelperLocalWin10.dll") + -LOCAL_WIN10_DLL_PATH = os.path.join(versionedLibPath,"nvdaHelperLocalWin10.dll") def getHelperLocalWin10Dll(): """Get a ctypes WinDLL instance for the nvdaHelperLocalWin10 dll. This is a C++/CX dll used to provide access to certain UWP functionality. """ return windll[LOCAL_WIN10_DLL_PATH] + def bstrReturn(address): """Handle a BSTR returned from a ctypes function call. This includes freeing the memory. diff --git a/source/NVDAObjects/IAccessible/MSHTML.py b/source/NVDAObjects/IAccessible/MSHTML.py index 8d097d63718..e767708d882 100644 --- a/source/NVDAObjects/IAccessible/MSHTML.py +++ b/source/NVDAObjects/IAccessible/MSHTML.py @@ -1,8 +1,8 @@ -#NVDAObjects/MSHTML.py -#A part of NonVisual Desktop Access (NVDA) -#Copyright (C) 2006-2015 NV Access Limited, Aleksey Sadovoy -#This file is covered by the GNU General Public License. -#See the file COPYING for more details. +# NVDAObjects/MSHTML.py +# A part of NonVisual Desktop Access (NVDA) +# Copyright (C) 2006-2015 NV Access Limited, Aleksey Sadovoy +# This file is covered by the GNU General Public License. +# See the file COPYING for more details. from comtypes import COMError import comtypes.client @@ -29,115 +29,122 @@ from locationHelper import RectLTRB from typing import Dict -IID_IHTMLElement=comtypes.GUID('{3050F1FF-98B5-11CF-BB82-00AA00BDCE0B}') +IID_IHTMLElement = comtypes.GUID("{3050F1FF-98B5-11CF-BB82-00AA00BDCE0B}") -class UIAMSHTMLTextInfo(UIATextInfo): +class UIAMSHTMLTextInfo(UIATextInfo): # #4174: MSHTML's UIAutomation implementation does not handle the insertion point at the end of the control correcly. # Therefore get around it by detecting when the TextInfo is instanciated on it, and ensure that expand and move do the expected thing. - - _atEndOfStory=False - def __init__(self,obj,position,_rangeObj=None): - super(UIAMSHTMLTextInfo,self).__init__(obj,position,_rangeObj) - if position==textInfos.POSITION_CARET: - tempRange=self._rangeObj.clone() + _atEndOfStory = False + + def __init__(self, obj, position, _rangeObj=None): + super(UIAMSHTMLTextInfo, self).__init__(obj, position, _rangeObj) + if position == textInfos.POSITION_CARET: + tempRange = self._rangeObj.clone() tempRange.ExpandToEnclosingUnit(UIAHandler.TextUnit_Character) - if self._rangeObj.CompareEndpoints(UIAHandler.TextPatternRangeEndpoint_Start,tempRange,UIAHandler.TextPatternRangeEndpoint_Start)>0: - self._atEndOfStory=True + if ( + self._rangeObj.CompareEndpoints( + UIAHandler.TextPatternRangeEndpoint_Start, + tempRange, + UIAHandler.TextPatternRangeEndpoint_Start, + ) + > 0 + ): + self._atEndOfStory = True def copy(self): - info=super(UIAMSHTMLTextInfo,self).copy() - info._atEndOfStory=self._atEndOfStory + info = super(UIAMSHTMLTextInfo, self).copy() + info._atEndOfStory = self._atEndOfStory return info - def expand(self,unit): - if unit in (textInfos.UNIT_CHARACTER,textInfos.UNIT_WORD) and self._atEndOfStory: + def expand(self, unit): + if unit in (textInfos.UNIT_CHARACTER, textInfos.UNIT_WORD) and self._atEndOfStory: return - self._atEndOfStory=False - return super(UIAMSHTMLTextInfo,self).expand(unit) + self._atEndOfStory = False + return super(UIAMSHTMLTextInfo, self).expand(unit) - def move(self,unit,direction,endPoint=None): - if direction==0: + def move(self, unit, direction, endPoint=None): + if direction == 0: return 0 - if self._atEndOfStory and direction<0: - direction+=1 - self._atEndOfStory=False - if direction==0: + if self._atEndOfStory and direction < 0: + direction += 1 + self._atEndOfStory = False + if direction == 0: return -1 - return super(UIAMSHTMLTextInfo,self).move(unit,direction,endPoint=endPoint) + return super(UIAMSHTMLTextInfo, self).move(unit, direction, endPoint=endPoint) -class HTMLAttribCache(object): - def __init__(self,HTMLNode): - self.HTMLNode=HTMLNode - self.cache={} - self.containsCache={} +class HTMLAttribCache(object): + def __init__(self, HTMLNode): + self.HTMLNode = HTMLNode + self.cache = {} + self.containsCache = {} - def __getitem__(self,item): + def __getitem__(self, item): try: return self.cache[item] except LookupError: pass try: - value=self.HTMLNode.getAttribute(item) - except (COMError,NameError): - value=None - self.cache[item]=value + value = self.HTMLNode.getAttribute(item) + except (COMError, NameError): + value = None + self.cache[item] = value return value - def __contains__(self,item): + def __contains__(self, item): try: return self.containsCache[item] except LookupError: pass - contains=item in self.cache + contains = item in self.cache if not contains: try: - contains=self.HTMLNode.hasAttribute(item) - except (COMError,NameError): + contains = self.HTMLNode.hasAttribute(item) + except (COMError, NameError): pass - self.containsCache[item]=contains + self.containsCache[item] = contains return contains nodeNamesToNVDARoles: Dict[str, int] = { - "FRAME":controlTypes.Role.FRAME, - "IFRAME":controlTypes.Role.INTERNALFRAME, - "FRAMESET":controlTypes.Role.DOCUMENT, - "BODY":controlTypes.Role.DOCUMENT, - "TH":controlTypes.Role.TABLECELL, - "IMG":controlTypes.Role.GRAPHIC, - "A":controlTypes.Role.LINK, - "LABEL":controlTypes.Role.LABEL, - "#text":controlTypes.Role.STATICTEXT, - "#TEXT":controlTypes.Role.STATICTEXT, - "H1":controlTypes.Role.HEADING, - "H2":controlTypes.Role.HEADING, - "H3":controlTypes.Role.HEADING, - "H4":controlTypes.Role.HEADING, - "H5":controlTypes.Role.HEADING, - "H6":controlTypes.Role.HEADING, - "DIV":controlTypes.Role.SECTION, - "P":controlTypes.Role.PARAGRAPH, - "FORM":controlTypes.Role.FORM, - "UL":controlTypes.Role.LIST, - "OL":controlTypes.Role.LIST, - "DL":controlTypes.Role.LIST, - "LI":controlTypes.Role.LISTITEM, - "DD":controlTypes.Role.LISTITEM, - "DT":controlTypes.Role.LISTITEM, - "TR":controlTypes.Role.TABLEROW, - "THEAD":controlTypes.Role.TABLEHEADER, - "TBODY":controlTypes.Role.TABLEBODY, - "HR":controlTypes.Role.SEPARATOR, - "OBJECT":controlTypes.Role.EMBEDDEDOBJECT, - "APPLET":controlTypes.Role.EMBEDDEDOBJECT, - "EMBED":controlTypes.Role.EMBEDDEDOBJECT, + "FRAME": controlTypes.Role.FRAME, + "IFRAME": controlTypes.Role.INTERNALFRAME, + "FRAMESET": controlTypes.Role.DOCUMENT, + "BODY": controlTypes.Role.DOCUMENT, + "TH": controlTypes.Role.TABLECELL, + "IMG": controlTypes.Role.GRAPHIC, + "A": controlTypes.Role.LINK, + "LABEL": controlTypes.Role.LABEL, + "#text": controlTypes.Role.STATICTEXT, + "#TEXT": controlTypes.Role.STATICTEXT, + "H1": controlTypes.Role.HEADING, + "H2": controlTypes.Role.HEADING, + "H3": controlTypes.Role.HEADING, + "H4": controlTypes.Role.HEADING, + "H5": controlTypes.Role.HEADING, + "H6": controlTypes.Role.HEADING, + "DIV": controlTypes.Role.SECTION, + "P": controlTypes.Role.PARAGRAPH, + "FORM": controlTypes.Role.FORM, + "UL": controlTypes.Role.LIST, + "OL": controlTypes.Role.LIST, + "DL": controlTypes.Role.LIST, + "LI": controlTypes.Role.LISTITEM, + "DD": controlTypes.Role.LISTITEM, + "DT": controlTypes.Role.LISTITEM, + "TR": controlTypes.Role.TABLEROW, + "THEAD": controlTypes.Role.TABLEHEADER, + "TBODY": controlTypes.Role.TABLEBODY, + "HR": controlTypes.Role.SEPARATOR, + "OBJECT": controlTypes.Role.EMBEDDEDOBJECT, + "APPLET": controlTypes.Role.EMBEDDEDOBJECT, + "EMBED": controlTypes.Role.EMBEDDEDOBJECT, "FIELDSET": controlTypes.Role.GROUPING, - "OPTION":controlTypes.Role.LISTITEM, - "BLOCKQUOTE":controlTypes.Role.BLOCKQUOTE, - "MATH":controlTypes.Role.MATH, + "OPTION": controlTypes.Role.LISTITEM, + "BLOCKQUOTE": controlTypes.Role.BLOCKQUOTE, + "MATH": controlTypes.Role.MATH, "NAV": controlTypes.Role.LANDMARK, "HEADER": controlTypes.Role.LANDMARK, "MAIN": controlTypes.Role.LANDMARK, @@ -153,31 +160,33 @@ def __contains__(self,item): def getZoomFactorsFromHTMLDocument(HTMLDocument): try: - scr=HTMLDocument.parentWindow.screen - except (COMError,NameError,AttributeError): + scr = HTMLDocument.parentWindow.screen + except (COMError, NameError, AttributeError): log.debugWarning("no screen object for MSHTML document") - return (1,1) + return (1, 1) try: - devX=float(scr.deviceXDPI) - devY=float(scr.deviceYDPI) - logX=float(scr.logicalXDPI) - logY=float(scr.logicalYDPI) - except (COMError,NameError,AttributeError,TypeError): + devX = float(scr.deviceXDPI) + devY = float(scr.deviceYDPI) + logX = float(scr.logicalXDPI) + logY = float(scr.logicalYDPI) + except (COMError, NameError, AttributeError, TypeError): log.debugWarning("unable to fetch DPI factors") - return (1,1) + return (1, 1) return (devX // logX, devY // logY) + def IAccessibleFromHTMLNode(HTMLNode): try: - s=HTMLNode.QueryInterface(IServiceProvider) - return s.QueryService(oleacc.IAccessible._iid_,oleacc.IAccessible) + s = HTMLNode.QueryInterface(IServiceProvider) + return s.QueryService(oleacc.IAccessible._iid_, oleacc.IAccessible) except COMError: raise NotImplementedError + def HTMLNodeFromIAccessible(IAccessibleObject): try: - s=IAccessibleObject.QueryInterface(IServiceProvider) - i=s.QueryService(IID_IHTMLElement,comtypes.automation.IDispatch) + s = IAccessibleObject.QueryInterface(IServiceProvider) + i = s.QueryService(IID_IHTMLElement, comtypes.automation.IDispatch) if not i: # QueryService should fail if IHTMLElement is not supported, but some applications misbehave and return a null COM pointer. raise NotImplementedError @@ -185,219 +194,229 @@ def HTMLNodeFromIAccessible(IAccessibleObject): except COMError: raise NotImplementedError -def locateHTMLElementByID(document,ID): + +def locateHTMLElementByID(document, ID): try: - elements=document.getElementsByName(ID) + elements = document.getElementsByName(ID) if elements is not None: - element=elements.item(0) - else: #probably IE 10 in standards mode (#3151) + element = elements.item(0) + else: # probably IE 10 in standards mode (#3151) try: - element=document.all.item(ID) + element = document.all.item(ID) except: # noqa: E722 - element=None - if element is None: #getElementsByName doesn't return element with specified ID in IE11 (#5784) + element = None + if element is None: # getElementsByName doesn't return element with specified ID in IE11 (#5784) try: - element=document.getElementByID(ID) + element = document.getElementByID(ID) except COMError as e: - log.debugWarning("document.getElementByID failed with COMError %s"%e) - element=None + log.debugWarning("document.getElementByID failed with COMError %s" % e) + element = None except COMError as e: - log.debugWarning("document.getElementsByName failed with COMError %s"%e) - element=None + log.debugWarning("document.getElementsByName failed with COMError %s" % e) + element = None if element: return element try: - nodeName=document.body.nodeName + nodeName = document.body.nodeName except COMError as e: - log.debugWarning("document.body.nodeName failed with COMError %s"%e) + log.debugWarning("document.body.nodeName failed with COMError %s" % e) return None if nodeName: - nodeName=nodeName.upper() - if nodeName=="FRAMESET": - tag="frame" + nodeName = nodeName.upper() + if nodeName == "FRAMESET": + tag = "frame" else: - tag="iframe" + tag = "iframe" try: - frames=document.getElementsByTagName(tag) + frames = document.getElementsByTagName(tag) except COMError as e: - log.debugWarning("document.getElementsByTagName failed with COMError %s"%e) + log.debugWarning("document.getElementsByTagName failed with COMError %s" % e) return None - if not frames: #frames can be None in IE 10 + if not frames: # frames can be None in IE 10 return None for frame in frames: - childElement=getChildHTMLNodeFromFrame(frame) + childElement = getChildHTMLNodeFromFrame(frame) if not childElement: continue - childElement=locateHTMLElementByID(childElement.document,ID) - if not childElement: continue # noqa: E701 + childElement = locateHTMLElementByID(childElement.document, ID) + if not childElement: + continue # noqa: E701 return childElement + def getChildHTMLNodeFromFrame(frame): try: - pacc=IAccessibleFromHTMLNode(frame) + pacc = IAccessibleFromHTMLNode(frame) except NotImplementedError: # #1569: It's not possible to get an IAccessible from frames marked with an ARIA role of presentation. # In this case, just skip this frame. return - res=IAccessibleHandler.accChild(pacc,1) - if not res: return # noqa: E701 + res = IAccessibleHandler.accChild(pacc, 1) + if not res: + return # noqa: E701 return HTMLNodeFromIAccessible(res[0]) -class MSHTMLTextInfo(textInfos.TextInfo): - def _expandToLine(self,textRange): - #Try to calculate the line range by finding screen coordinates and using moveToPoint - parent=textRange.parentElement() - if not parent.isMultiline: #fastest solution for single line edits () +class MSHTMLTextInfo(textInfos.TextInfo): + def _expandToLine(self, textRange): + # Try to calculate the line range by finding screen coordinates and using moveToPoint + parent = textRange.parentElement() + if not parent.isMultiline: # fastest solution for single line edits () textRange.expand("textEdit") return - parentRect=parent.getBoundingClientRect() - #This can be simplified when comtypes is fixed - lineTop=comtypes.client.dynamic._Dispatch(textRange._comobj).offsetTop - lineLeft=parentRect.left+parent.clientLeft - #editable documents have a different right most boundary to