From 7604c334a9b727ee9632c265dd24403fdaab5758 Mon Sep 17 00:00:00 2001 From: Sean Budd Date: Thu, 27 Jun 2024 13:47:21 +1000 Subject: [PATCH 1/2] Run Ruff --fix --- appveyor/mozillaSyms.py | 1 - include/cldr | 1 + include/microsoft-ui-uiautomation | 1 + site_scons/site_tools/gettextTool.py | 1 - site_scons/site_tools/msrpc.py | 2 +- source/NVDAHelper.py | 6 +++--- source/NVDAObjects/IAccessible/MSHTML.py | 1 - source/NVDAObjects/IAccessible/msOffice.py | 1 - source/NVDAObjects/IAccessible/mscandui.py | 1 - source/NVDAObjects/IAccessible/qt.py | 1 - source/NVDAObjects/UIA/__init__.py | 4 ++-- source/NVDAObjects/UIA/wordDocument.py | 1 - source/NVDAObjects/window/edit.py | 4 ++-- source/NVDAObjects/window/excel.py | 5 +---- source/NVDAObjects/window/winConsole.py | 2 +- source/NVDAObjects/window/winword.py | 3 --- source/UIAHandler/browseMode.py | 1 - source/addonStore/dataManager.py | 2 +- source/addonStore/network.py | 2 +- source/appModules/azardi20.py | 1 - source/appModules/excel.py | 1 - source/appModules/javaw.py | 1 - source/appModules/miranda32.py | 1 - source/appModules/msimn.py | 1 - source/appModules/nvda.py | 1 - source/appModules/outlook.py | 2 -- source/appModules/powerpnt.py | 4 +--- source/bdDetect.py | 2 -- source/braille.py | 1 - source/brailleDisplayDrivers/albatross/driver.py | 1 - source/brailleDisplayDrivers/alva.py | 2 +- source/brailleDisplayDrivers/ecoBraille.py | 4 +--- source/brailleDisplayDrivers/papenmeier.py | 2 +- source/brailleDisplayDrivers/seikantk.py | 2 +- source/browseMode.py | 1 - source/colors.py | 1 - source/compoundDocuments.py | 3 --- source/config/__init__.py | 2 +- source/config/profileUpgrader.py | 2 +- source/cursorManager.py | 1 - source/displayModel.py | 1 - source/globalCommands.py | 3 +-- source/globalPluginHandler.py | 1 - source/gui/__init__.py | 3 ++- source/gui/addonStoreGui/viewModels/addonList.py | 4 ++-- source/gui/configProfiles.py | 1 - source/gui/inputGestures.py | 6 +++--- source/gui/settingsDialogs.py | 3 +-- source/hwIo/base.py | 1 - source/keyboardHandler.py | 2 +- source/languageHandler.py | 2 +- source/locationHelper.py | 1 - source/nvda.pyw | 3 +-- source/nvda_slave.pyw | 2 +- source/nvwave.py | 6 +++--- source/oleTypes.py | 9 --------- source/oleacc.py | 2 -- source/queueHandler.py | 1 - source/speech/commands.py | 1 - source/speech/manager.py | 10 ++++------ source/speech/speech.py | 4 ++-- source/synthDrivers/_espeak.py | 2 -- source/synthDrivers/espeak.py | 1 - source/synthDrivers/oneCore.py | 1 - source/textInfos/offsets.py | 3 +-- source/tones.py | 3 +-- source/touchHandler.py | 1 - source/touchTracker.py | 1 - source/ui.py | 2 -- source/updateCheck.py | 6 +----- source/virtualBuffers/MSHTML.py | 4 ---- source/virtualBuffers/adobeAcrobat.py | 1 - source/virtualBuffers/lotusNotes.py | 1 - source/virtualBuffers/webKit.py | 5 +---- source/winConsoleHandler.py | 2 -- source/windowUtils.py | 2 +- tests/system/libraries/ChromeLib.py | 1 - .../libraries/SystemTestSpy/speechSpyGlobalPlugin.py | 1 - tests/system/libraries/SystemTestSpy/windows.py | 2 +- tests/system/libraries/WindowsLib.py | 2 +- tests/system/robot/chromeTests.py | 8 ++++---- tests/system/robot/symbolPronunciationTests.py | 2 +- tests/unit/test_baseObject.py | 3 +-- .../test_speechManager/speechManagerTestHarness.py | 2 +- tests/unit/test_speechXml.py | 1 - 85 files changed, 57 insertions(+), 142 deletions(-) create mode 160000 include/cldr create mode 160000 include/microsoft-ui-uiautomation diff --git a/appveyor/mozillaSyms.py b/appveyor/mozillaSyms.py index 9072f453e20..30a1dc1fcc2 100644 --- a/appveyor/mozillaSyms.py +++ b/appveyor/mozillaSyms.py @@ -6,7 +6,6 @@ To update the list of symbols uploaded to Mozilla, see the DLL_NAMES constant below. """ -import argparse import os import subprocess import sys diff --git a/include/cldr b/include/cldr new file mode 160000 index 00000000000..443ca2332af --- /dev/null +++ b/include/cldr @@ -0,0 +1 @@ +Subproject commit 443ca2332af0c0f0836e6e008cdae875381bc5af diff --git a/include/microsoft-ui-uiautomation b/include/microsoft-ui-uiautomation new file mode 160000 index 00000000000..224b22f3bf9 --- /dev/null +++ b/include/microsoft-ui-uiautomation @@ -0,0 +1 @@ +Subproject commit 224b22f3bf9e6bcd7326e471d1e134fe739bf4ff diff --git a/site_scons/site_tools/gettextTool.py b/site_scons/site_tools/gettextTool.py index 6bf860af041..71d10d078e2 100644 --- a/site_scons/site_tools/gettextTool.py +++ b/site_scons/site_tools/gettextTool.py @@ -13,7 +13,6 @@ ### import os -import sys # Get the path to msgfmt. MSGFMT = os.path.abspath(os.path.join("miscDeps", "tools", "msgfmt.exe")) diff --git a/site_scons/site_tools/msrpc.py b/site_scons/site_tools/msrpc.py index e3674e9c4e9..a6f02e39da6 100644 --- a/site_scons/site_tools/msrpc.py +++ b/site_scons/site_tools/msrpc.py @@ -75,7 +75,7 @@ def exists(env): return midl.exists(env) def generate(env): - if not 'MIDL' in env: + if 'MIDL' not in env: from SCons.Tool import midl midl.generate(env) env['BUILDERS']['MSRPCStubs']=MSRPCStubs_builder diff --git a/source/NVDAHelper.py b/source/NVDAHelper.py index 0f916ea0e07..9e59638442e 100755 --- a/source/NVDAHelper.py +++ b/source/NVDAHelper.py @@ -208,7 +208,7 @@ def nvdaControllerInternal_requestRegistration(uuidString): pid=pid.value if not pid: log.error("Could not get process ID for RPC call") - return -1; + return -1 bindingHandle=c_long() bindingHandle.value=localLib.createRemoteBindingHandle(uuidString) if not bindingHandle: @@ -275,7 +275,7 @@ def nvdaControllerInternal_drawFocusRectNotify(hwnd, 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; + return 0 @WINFUNCTYPE(c_long,c_long,c_long,c_wchar_p) def nvdaControllerInternal_logMessage(level,pid,message): @@ -373,7 +373,7 @@ def nvdaControllerInternal_inputCompositionUpdate(compositionString,selectionSta def handleInputCandidateListUpdate(candidatesString,selectionIndex,inputMethod): candidateStrings=candidatesString.split('\n') import speech - from NVDAObjects.inputComposition import InputComposition, CandidateList, CandidateItem + from NVDAObjects.inputComposition import CandidateItem focus=api.getFocusObject() if not (0<=selectionIndex=2007 exposes MSAA on its embedded objects thus we can use accName as the label import oleacc try: - label=o.QueryInterface(oleacc.IAccessible).accName(0); + label=o.QueryInterface(oleacc.IAccessible).accName(0) except comtypes.COMError: pass if label: @@ -666,7 +666,7 @@ def _getEmbeddedObjectLabel(self,embedRangeObj): dataObj=None if dataObj: text=comtypes.BSTR() - res=NVDAHelper.localLib.getOleClipboardText(dataObj,ctypes.byref(text)); + res=NVDAHelper.localLib.getOleClipboardText(dataObj,ctypes.byref(text)) label=text.value if label: return label diff --git a/source/NVDAObjects/window/excel.py b/source/NVDAObjects/window/excel.py index 9d3c3b97e0c..558ae3481a8 100755 --- a/source/NVDAObjects/window/excel.py +++ b/source/NVDAObjects/window/excel.py @@ -20,12 +20,11 @@ import winsound import re import uuid -import collections import NVDAHelper import oleacc import ui import speech -from tableUtils import HeaderCellInfo, HeaderCellTracker +from tableUtils import HeaderCellTracker import config from config.configFlags import ReportCellBorders import textInfos @@ -47,8 +46,6 @@ import scriptHandler from scriptHandler import script import browseMode -import inputCore -import ctypes import vision from utils.displayString import DisplayStringIntEnum import NVDAState diff --git a/source/NVDAObjects/window/winConsole.py b/source/NVDAObjects/window/winConsole.py index 0cdde0b67c3..83007adff63 100644 --- a/source/NVDAObjects/window/winConsole.py +++ b/source/NVDAObjects/window/winConsole.py @@ -5,7 +5,7 @@ import winConsoleHandler from . import Window -from ..behaviors import Terminal, EditableTextWithoutAutoSelectDetection, KeyboardHandlerBasedTypedCharSupport +from ..behaviors import Terminal, EditableTextWithoutAutoSelectDetection import api import core from scriptHandler import script diff --git a/source/NVDAObjects/window/winword.py b/source/NVDAObjects/window/winword.py index eefa33f5e09..b7c52c59d79 100755 --- a/source/NVDAObjects/window/winword.py +++ b/source/NVDAObjects/window/winword.py @@ -37,9 +37,6 @@ from controlTypes.formatFields import TextAlign import treeInterceptorHandler import browseMode -import review -from cursorManager import CursorManager, ReviewCursorManager -from tableUtils import HeaderCellInfo, HeaderCellTracker from . import Window from ..behaviors import EditableTextWithoutAutoSelectDetection from . import _msOfficeChart diff --git a/source/UIAHandler/browseMode.py b/source/UIAHandler/browseMode.py index 1d932bfea3d..04435dc6308 100644 --- a/source/UIAHandler/browseMode.py +++ b/source/UIAHandler/browseMode.py @@ -20,7 +20,6 @@ ) import documentBase import treeInterceptorHandler -import cursorManager import textInfos import browseMode from logHandler import log diff --git a/source/addonStore/dataManager.py b/source/addonStore/dataManager.py index ced86a4bcf5..1bd59846c8b 100644 --- a/source/addonStore/dataManager.py +++ b/source/addonStore/dataManager.py @@ -179,7 +179,7 @@ def _getCachedAddonData(self, cacheFilePath: str) -> Optional[CachedAddonsModel] with open(cacheFilePath, 'r', encoding='utf-8') as cacheFile: cacheData = json.load(cacheFile) except Exception: - log.exception(f"Invalid add-on store cache") + log.exception("Invalid add-on store cache") if NVDAState.shouldWriteToDisk(): os.remove(cacheFilePath) return None diff --git a/source/addonStore/network.py b/source/addonStore/network.py index ebf061d2147..9a998fe4989 100644 --- a/source/addonStore/network.py +++ b/source/addonStore/network.py @@ -133,7 +133,7 @@ def _done(self, downloadAddonFuture: Future[Optional[os.PathLike]]): cacheFilePath = None from gui.message import DisplayableError if not isinstance(downloadAddonFutureException, DisplayableError): - log.error(f"Unhandled exception in _download", exc_info=downloadAddonFuture.exception()) + log.error("Unhandled exception in _download", exc_info=downloadAddonFuture.exception()) else: callLater( delay=0, diff --git a/source/appModules/azardi20.py b/source/appModules/azardi20.py index fdcb024ea53..4d413a117f6 100644 --- a/source/appModules/azardi20.py +++ b/source/appModules/azardi20.py @@ -6,7 +6,6 @@ import appModuleHandler import controlTypes -import winUser import mouseHandler import api from NVDAObjects.IAccessible.mozilla import Document diff --git a/source/appModules/excel.py b/source/appModules/excel.py index 82c58beab7f..7a0fbffcbda 100644 --- a/source/appModules/excel.py +++ b/source/appModules/excel.py @@ -17,7 +17,6 @@ from NVDAObjects.window import DisplayModelEditableText from NVDAObjects.window.edit import UnidentifiedEdit from NVDAObjects.window import Window -from NVDAObjects.window.excel import ExcelCell from NVDAObjects.IAccessible import IAccessible diff --git a/source/appModules/javaw.py b/source/appModules/javaw.py index 3d1a2b88ec4..93fa8b986cb 100644 --- a/source/appModules/javaw.py +++ b/source/appModules/javaw.py @@ -10,7 +10,6 @@ import os import shlex import appModuleHandler -from appModuleHandler import AppModule def _getEntryPoint(cmd): cmd = iter(shlex.split(cmd)) diff --git a/source/appModules/miranda32.py b/source/appModules/miranda32.py index 85d5d92d877..f4145a98842 100644 --- a/source/appModules/miranda32.py +++ b/source/appModules/miranda32.py @@ -17,7 +17,6 @@ import controlTypes from scriptHandler import isScriptWaiting, script import api -import mouseHandler import oleacc from keyboardHandler import KeyboardInputGesture import watchdog diff --git a/source/appModules/msimn.py b/source/appModules/msimn.py index e4e0702e0c4..5a8812ca92a 100644 --- a/source/appModules/msimn.py +++ b/source/appModules/msimn.py @@ -14,7 +14,6 @@ from NVDAObjects.window import Window from NVDAObjects.IAccessible import IAccessible, sysListView32 import watchdog -from NVDAObjects.behaviors import _FakeTableCell messageListImageLabels={ # Translators: This Outlook Express message has an attachment diff --git a/source/appModules/nvda.py b/source/appModules/nvda.py index d23ff4a476d..432a213db89 100755 --- a/source/appModules/nvda.py +++ b/source/appModules/nvda.py @@ -18,7 +18,6 @@ import speech import textInfos import config -from logHandler import log import ui if typing.TYPE_CHECKING: diff --git a/source/appModules/outlook.py b/source/appModules/outlook.py index e7b30c05aa1..d470b60f560 100644 --- a/source/appModules/outlook.py +++ b/source/appModules/outlook.py @@ -10,8 +10,6 @@ import comtypes.automation import ctypes import winVersion -from hwPortUtils import SYSTEMTIME -import scriptHandler from scriptHandler import script import winKernel import comHelper diff --git a/source/appModules/powerpnt.py b/source/appModules/powerpnt.py index 6f3a22e12db..78f8e8d0007 100644 --- a/source/appModules/powerpnt.py +++ b/source/appModules/powerpnt.py @@ -15,12 +15,10 @@ import oleacc import comHelper import ui -import queueHandler import colors import api import speech from speech import sayAll -import NVDAHelper import winUser import msoAutoShapeTypes from treeInterceptorHandler import DocumentTreeInterceptor @@ -29,7 +27,7 @@ import textInfos.offsets import eventHandler import appModuleHandler -from NVDAObjects.IAccessible import IAccessible, getNVDAObjectFromEvent +from NVDAObjects.IAccessible import IAccessible from NVDAObjects.window import Window from NVDAObjects.behaviors import EditableTextWithoutAutoSelectDetection, EditableText import braille diff --git a/source/bdDetect.py b/source/bdDetect.py index 9f213464691..48629a61d7e 100644 --- a/source/bdDetect.py +++ b/source/bdDetect.py @@ -27,10 +27,8 @@ NamedTuple, Optional, OrderedDict, - Set, Tuple, Type, - Union, ) import hwPortUtils import NVDAState diff --git a/source/braille.py b/source/braille.py index b1c7039f6a4..be49d8dd545 100644 --- a/source/braille.py +++ b/source/braille.py @@ -5,7 +5,6 @@ # Leonard de Ruijter, Burman's Computer and Education Ltd., Julien Cochuyt import itertools -import os import typing from typing import ( TYPE_CHECKING, diff --git a/source/brailleDisplayDrivers/albatross/driver.py b/source/brailleDisplayDrivers/albatross/driver.py index 86adf23ad72..2fd50a92c05 100644 --- a/source/brailleDisplayDrivers/albatross/driver.py +++ b/source/brailleDisplayDrivers/albatross/driver.py @@ -28,7 +28,6 @@ from typing import ( List, Optional, - Tuple, ) import braille diff --git a/source/brailleDisplayDrivers/alva.py b/source/brailleDisplayDrivers/alva.py index dc627e9d5bd..b0b4491c236 100644 --- a/source/brailleDisplayDrivers/alva.py +++ b/source/brailleDisplayDrivers/alva.py @@ -12,7 +12,7 @@ import inputCore import brailleInput import hwIo -from hwIo import intToByte, boolToByte, Serial +from hwIo import intToByte, boolToByte from globalCommands import SCRCAT_BRAILLE import ui from baseObject import ScriptableObject diff --git a/source/brailleDisplayDrivers/ecoBraille.py b/source/brailleDisplayDrivers/ecoBraille.py index 07902783a92..ccb27b1f6c7 100644 --- a/source/brailleDisplayDrivers/ecoBraille.py +++ b/source/brailleDisplayDrivers/ecoBraille.py @@ -4,16 +4,14 @@ #This file is covered by the GNU General Public License. #See the file COPYING for more details. #Copyright (C) 2014-2015 ONCE-CIDAT -from typing import List, Tuple +from typing import List import inputCore import braille import hwPortUtils -from hwIo import intToByte from collections import OrderedDict from logHandler import log import serial -import struct import wx ECO_KEY_F1 = 0x01 diff --git a/source/brailleDisplayDrivers/papenmeier.py b/source/brailleDisplayDrivers/papenmeier.py index 67d3e926ebf..129bbf1e003 100644 --- a/source/brailleDisplayDrivers/papenmeier.py +++ b/source/brailleDisplayDrivers/papenmeier.py @@ -7,7 +7,7 @@ #minor changes by Halim Sahin (nvda@lists.thm.de), Ali-Riza Ciftcioglu , James Teh and Davy Kager import time -from typing import List, Union, Tuple, Optional +from typing import List, Union, Optional import wx import braille diff --git a/source/brailleDisplayDrivers/seikantk.py b/source/brailleDisplayDrivers/seikantk.py index b6e60b95801..215e59528d8 100644 --- a/source/brailleDisplayDrivers/seikantk.py +++ b/source/brailleDisplayDrivers/seikantk.py @@ -137,7 +137,7 @@ def __init__(self, port: typing.Union[None, str, DeviceMatch]): self.isSerial = match.type == bdDetect.DeviceType.SERIAL try: if self.isHid: - log.info(f"Trying Seika notetaker on USB-HID") + 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 diff --git a/source/browseMode.py b/source/browseMode.py index 3f3582fd990..1a9f933025e 100644 --- a/source/browseMode.py +++ b/source/browseMode.py @@ -47,7 +47,6 @@ import speech from speech import sayAll import treeInterceptorHandler -import inputCore import api import gui.guiHelper from gui.dpiScalingHelper import DpiScalingHelperMixinWithoutInit diff --git a/source/colors.py b/source/colors.py index a9f127f5896..22dbafb7887 100644 --- a/source/colors.py +++ b/source/colors.py @@ -4,7 +4,6 @@ # See the file COPYING for more details. from collections import namedtuple -import math import colorsys from ctypes.wintypes import COLORREF import re diff --git a/source/compoundDocuments.py b/source/compoundDocuments.py index 829794adfeb..22043fbdd59 100644 --- a/source/compoundDocuments.py +++ b/source/compoundDocuments.py @@ -20,12 +20,9 @@ import speech import braille from NVDAObjects import behaviors -import api -import config import review import vision from logHandler import log -from locationHelper import RectLTWH class CompoundTextInfo(textInfos.TextInfo): diff --git a/source/config/__init__.py b/source/config/__init__.py index 83aec236e30..c600178e992 100644 --- a/source/config/__init__.py +++ b/source/config/__init__.py @@ -614,7 +614,7 @@ def _loadConfig(self, fn, fileError=False): # if debug level logging is enabled. try: logLevelName = profile["general"]["loggingLevel"] - except KeyError as e: + except KeyError: logLevelName = None if log.isEnabledFor(log.DEBUG) or (logLevelName and DEBUG >= logging.getLevelName(logLevelName)): # Log at level info to ensure that the profile is logged. diff --git a/source/config/profileUpgrader.py b/source/config/profileUpgrader.py index cf57023a6ee..66cdaa5e13a 100644 --- a/source/config/profileUpgrader.py +++ b/source/config/profileUpgrader.py @@ -67,7 +67,7 @@ def _ensureVersionProperty(profile): if isEmptyProfile: log.debug("Empty profile, triggering default schema version") profile[SCHEMA_VERSION_KEY] = latestSchemaVersion - elif not SCHEMA_VERSION_KEY in profile: + elif SCHEMA_VERSION_KEY not in profile: # this must be a "before schema versions" config file. log.debug("No schema version found, setting to zero.") profile[SCHEMA_VERSION_KEY] = 0 diff --git a/source/cursorManager.py b/source/cursorManager.py index 12e6341b64f..8cdab47be6a 100644 --- a/source/cursorManager.py +++ b/source/cursorManager.py @@ -20,7 +20,6 @@ import review from scriptHandler import willSayAllResume, script import textInfos -import api import speech import config import braille diff --git a/source/displayModel.py b/source/displayModel.py index 3d7c5e03b16..78c8bc12412 100644 --- a/source/displayModel.py +++ b/source/displayModel.py @@ -24,7 +24,6 @@ from locationHelper import RectLTRB, RectLTWH import textUtils from typing import ( - Union, List, Tuple, Optional, diff --git a/source/globalCommands.py b/source/globalCommands.py index 4dba7f9fd3f..04119afb564 100755 --- a/source/globalCommands.py +++ b/source/globalCommands.py @@ -9,7 +9,6 @@ import itertools from typing import ( - List, Optional, Tuple, Union, @@ -2512,7 +2511,7 @@ def _getNvdaObjWithAnnotationUnderCaret(self) -> Optional[NVDAObject]: if objAtStart.annotations: if _isDebugLogCatEnabled: - log.debug(f"NVDAObjectAtStart of caret has details") + log.debug("NVDAObjectAtStart of caret has details") return objAtStart elif api.getFocusObject(): # If fetching from the caret position fails, try via the focus object diff --git a/source/globalPluginHandler.py b/source/globalPluginHandler.py index 911c1d91fd9..c23d7410c63 100644 --- a/source/globalPluginHandler.py +++ b/source/globalPluginHandler.py @@ -7,7 +7,6 @@ import sys import pkgutil import importlib -import config import baseObject from logHandler import log import globalPlugins diff --git a/source/gui/__init__.py b/source/gui/__init__.py index c2264bfaf97..c74cbc5775c 100644 --- a/source/gui/__init__.py +++ b/source/gui/__init__.py @@ -424,7 +424,8 @@ def onAddonStoreUpdatableCommand(self, evt: wx.MenuEvent | None): self.popupSettingsDialog(AddonStoreDialog, _storeVM, openToTab=_StatusFilterKey.UPDATE) def onReloadPluginsCommand(self, evt): - import appModuleHandler, globalPluginHandler + import appModuleHandler + import globalPluginHandler from NVDAObjects import NVDAObject appModuleHandler.reloadAppModules() globalPluginHandler.reloadGlobalPlugins() diff --git a/source/gui/addonStoreGui/viewModels/addonList.py b/source/gui/addonStoreGui/viewModels/addonList.py index a37cb6170a6..13aa26a41ea 100644 --- a/source/gui/addonStoreGui/viewModels/addonList.py +++ b/source/gui/addonStoreGui/viewModels/addonList.py @@ -377,7 +377,7 @@ def _tryPersistSelection( log.debug(f"Selected Id in new order {selectedId}") return selectedId elif not newOrder: - log.debug(f"No entries in new order") + log.debug("No entries in new order") # no entries after filter, select None return None elif selectedIndex is not None: @@ -402,7 +402,7 @@ def _tryPersistSelection( # if there is any addon select it. return newOrder[0] else: - log.debug(f"No selection") + log.debug("No selection") # no selection. return None diff --git a/source/gui/configProfiles.py b/source/gui/configProfiles.py index 41663d71e9b..03f7655e8b4 100644 --- a/source/gui/configProfiles.py +++ b/source/gui/configProfiles.py @@ -8,7 +8,6 @@ import api import gui from logHandler import log -import appModuleHandler import globalVars from . import guiHelper import gui.contextHelp diff --git a/source/gui/inputGestures.py b/source/gui/inputGestures.py index 4cee868cd8e..d8f59e23a1f 100644 --- a/source/gui/inputGestures.py +++ b/source/gui/inputGestures.py @@ -81,7 +81,7 @@ class _PendingGesture: canRemove = False def __repr__(self): - return f"Pending Gesture" + return "Pending Gesture" class _ScriptVM: @@ -165,7 +165,7 @@ class _EmulatedGestureVM(_ScriptVM): def __init__(self, emuGestureInfo: inputCore.AllGesturesScriptInfo): if not isinstance(emuGestureInfo, inputCore.KbEmuScriptInfo): - raise ValueError(f"Unexpected script type.") + raise ValueError("Unexpected script type.") # Translators: An gesture that will be emulated by some other new gesture. The token {emulateGesture} # will be replaced by the gesture that can be triggered by a mapped gesture. # E.G. Emulate key press: NVDA+b @@ -705,7 +705,7 @@ def addGestureCaptor(gesture: inputCore.InputGesture): inputCore.manager._captureFunc = addGestureCaptor else: - log.error(f"unable to do 'add' action for selected item") + log.error("unable to do 'add' action for selected item") def _addCaptured(self, catVM: _CategoryVMTypes, scriptVM: _ScriptVMTypes, gesture): gids = gesture.normalizedIdentifiers diff --git a/source/gui/settingsDialogs.py b/source/gui/settingsDialogs.py index a30d0934406..21c1dca30eb 100644 --- a/source/gui/settingsDialogs.py +++ b/source/gui/settingsDialogs.py @@ -77,7 +77,6 @@ import winVersion import weakref import time -import keyLabels from .dpiScalingHelper import DpiScalingHelperMixinWithoutInit #: The size that settings panel text descriptions should be wrapped at. @@ -4647,7 +4646,7 @@ def onDiscard(self): self._providerSettings.onDiscard() def onSave(self): - log.debug(f"calling VisionProviderSubPanel_Wrapper") + log.debug("calling VisionProviderSubPanel_Wrapper") if self._providerSettings: self._providerSettings.onSave() diff --git a/source/hwIo/base.py b/source/hwIo/base.py index f783ceba598..2beb7064eda 100644 --- a/source/hwIo/base.py +++ b/source/hwIo/base.py @@ -21,7 +21,6 @@ import serial from serial.win32 import OVERLAPPED, FILE_FLAG_OVERLAPPED, INVALID_HANDLE_VALUE, ERROR_IO_PENDING, COMMTIMEOUTS, CreateFile, SetCommTimeouts import winKernel -import braille from logHandler import log import config import time diff --git a/source/keyboardHandler.py b/source/keyboardHandler.py index 8f884c77b49..6ad4957a31e 100644 --- a/source/keyboardHandler.py +++ b/source/keyboardHandler.py @@ -264,7 +264,7 @@ def internal_keyDownEvent(vkCode,scanCode,extended,injected): # And we only want to do this if the gesture did not result in an executed action and not gestureExecuted # and not if this gesture is a modifier key - and not isNVDAModifierKey(vkCode,extended) and not vkCode in KeyboardInputGesture.NORMAL_MODIFIER_KEYS + and not isNVDAModifierKey(vkCode,extended) and vkCode not in KeyboardInputGesture.NORMAL_MODIFIER_KEYS ): keyStates=(ctypes.c_byte*256)() for k in range(256): diff --git a/source/languageHandler.py b/source/languageHandler.py index b24ecb1e5f1..0c65c8bca69 100644 --- a/source/languageHandler.py +++ b/source/languageHandler.py @@ -440,7 +440,7 @@ def setLocale(localeName: str) -> None: if originalLocaleName == getLanguage(): # reset to system locale default if we can't set the current lang's locale locale.setlocale(locale.LC_ALL, "") - log.debugWarning(f"set python locale to system default") + log.debugWarning("set python locale to system default") else: log.debugWarning(f"setting python locale to the current language {getLanguage()}") # fallback and try to reset the locale to the current lang diff --git a/source/locationHelper.py b/source/locationHelper.py index dc5d4ee154b..38bf82e34f7 100644 --- a/source/locationHelper.py +++ b/source/locationHelper.py @@ -6,7 +6,6 @@ """Classes and helper functions for working with rectangles and coordinates.""" from collections import namedtuple -from collections.abc import Sequence import windowUtils import winUser from ctypes.wintypes import RECT, POINT, DWORD diff --git a/source/nvda.pyw b/source/nvda.pyw index 9c82b5ab229..b089f15a5ef 100755 --- a/source/nvda.pyw +++ b/source/nvda.pyw @@ -45,7 +45,6 @@ if NVDAState.isRunningAsSource(): ) sys.exit(1) customVenvDetected = nvdaVenv != virtualEnv - import sourceEnv #We should always change directory to the location of this module (nvda.pyw), don't rely on sys.path[0] appDir = os.path.normpath(os.path.dirname(__file__)) else: @@ -423,7 +422,7 @@ except Exception as e: _log.error(f"Unable to acquire mutex: {e}") sys.exit(1) if mutex is None: - _log.error(f"Unknown mutex acquisition error. Exiting") + _log.error("Unknown mutex acquisition error. Exiting") sys.exit(1) diff --git a/source/nvda_slave.pyw b/source/nvda_slave.pyw index 88f97091725..4663377b624 100755 --- a/source/nvda_slave.pyw +++ b/source/nvda_slave.pyw @@ -115,7 +115,7 @@ def main(): except installer.RetriableFailure: logHandler.log.error("Task failed, try again",exc_info=True) sys.exit(2) - except Exception as e: + except Exception: logHandler.log.error("slave error",exc_info=True) sys.exit(1) diff --git a/source/nvwave.py b/source/nvwave.py index e521ea9d4c4..4455d678d08 100644 --- a/source/nvwave.py +++ b/source/nvwave.py @@ -36,7 +36,7 @@ UINT, LPUINT ) -from comtypes import HRESULT, BSTR +from comtypes import HRESULT from comtypes.hresult import S_OK import atexit import weakref @@ -343,11 +343,11 @@ def open(self): self._handleWinmmError(message="Error opening") if lastOutputDeviceID != WAVE_MAPPER: if _isDebugForNvWave(): - log.debug(f"Falling back to WAVE_MAPPER") + log.debug("Falling back to WAVE_MAPPER") self._setCurrentDevice(WAVE_MAPPER) self.open() else: - log.warning(f"Unable to open WAVE_MAPPER device, there may be no audio devices.") + log.warning("Unable to open WAVE_MAPPER device, there may be no audio devices.") WavePlayer.audioDeviceError_static = True raise # can't open the default device. return diff --git a/source/oleTypes.py b/source/oleTypes.py index 17d048703e4..d4c1d305078 100755 --- a/source/oleTypes.py +++ b/source/oleTypes.py @@ -5,19 +5,10 @@ from comtypes import IUnknown LONG_PTR = c_int from comtypes import GUID -from comtypes import IUnknown from ctypes import HRESULT -from comtypes import helpstring from comtypes import COMMETHOD -from comtypes import dispid -from comtypes.persist import IPersist from comtypes import wireHWND -from comtypes import GUID -from comtypes import _COAUTHIDENTITY UINT_PTR = c_ulong -from comtypes import _COSERVERINFO -from comtypes import _COAUTHINFO -from comtypes import tagBIND_OPTS2 from objidl import IBindCtx, IMoniker class tagDVTARGETDEVICE(Structure): diff --git a/source/oleacc.py b/source/oleacc.py index 260470df755..ac04459dc78 100644 --- a/source/oleacc.py +++ b/source/oleacc.py @@ -1,10 +1,8 @@ -import time from ctypes import * from ctypes.wintypes import * from comtypes import * from comtypes.automation import * import comtypes.client -import winKernel import winUser # Include functions from oleacc.dll in the module namespace. m=comtypes.client.GetModule('oleacc.dll') diff --git a/source/queueHandler.py b/source/queueHandler.py index c91c392739a..433a88e2cba 100644 --- a/source/queueHandler.py +++ b/source/queueHandler.py @@ -6,7 +6,6 @@ import types from queue import SimpleQueue -import globalVars from logHandler import log import watchdog import core diff --git a/source/speech/commands.py b/source/speech/commands.py index fc1d5645b59..bf6fe4c7579 100644 --- a/source/speech/commands.py +++ b/source/speech/commands.py @@ -15,7 +15,6 @@ import config from synthDriverHandler import getSynth -from logHandler import log class SpeechCommand(object): """The base class for objects that can be inserted between strings of text to perform actions, diff --git a/source/speech/manager.py b/source/speech/manager.py index 54c8b89172a..1d55df55998 100644 --- a/source/speech/manager.py +++ b/source/speech/manager.py @@ -4,7 +4,6 @@ # See the file COPYING for more details. # Copyright (C) 2006-2021 NV Access Limited import typing -from languageHandler import normalizeLanguage import queueHandler import synthDriverHandler @@ -13,7 +12,6 @@ from .commands import ( # Commands that are used in this file. EndUtteranceCommand, - LangChangeCommand, SuppressUnicodeNormalizationCommand, SynthParamCommand, BaseCallbackCommand, @@ -50,7 +48,7 @@ def _speechManagerDebug(msg, *args, **kwargs) -> None: """ if not log.isEnabledFor(log.DEBUG) or not _shouldDoSpeechManagerLogging(): return - log._log(log.DEBUG, f"SpeechManager- " + msg, args, **kwargs) + log._log(log.DEBUG, "SpeechManager- " + msg, args, **kwargs) #: Turns on unit test logging, logs the key interactions that happen with speech manager. When False, @@ -69,9 +67,9 @@ def _speechManagerUnitTest(msg, *args, **kwargs) -> None: # one stack higher. The codepath argument for _log could also be used to resolve this, but duplication # simpler. if log.isEnabledFor(log.DEBUG) and _shouldDoSpeechManagerLogging(): - log._log(log.DEBUG, f"SpeechManager- " + msg, args, **kwargs) + log._log(log.DEBUG, "SpeechManager- " + msg, args, **kwargs) return - log._log(log.INFO, f"SpeechManUnitTest- " + msg, args, **kwargs) + log._log(log.INFO, "SpeechManUnitTest- " + msg, args, **kwargs) # Install the custom log handlers. #: For extra debug level logging, this is a category that must be enabled in the advanced settings panel. @@ -563,7 +561,7 @@ def _doRemoveCancelledSpeechCommands(self): latestCancelledUtteranceIndex = self._getMostRecentlyCancelledUtterance() log._speechManagerDebug(f"Last index: {latestCancelledUtteranceIndex}") if latestCancelledUtteranceIndex is not None: - log._speechManagerDebug(f"Cancel and push speech") + log._speechManagerDebug("Cancel and push speech") # Minimise the number of calls to _removeCompletedFromQueue by using the most recently cancelled # utterance index. This will remove all older queued speech also. self._removeCompletedFromQueue(latestCancelledUtteranceIndex) diff --git a/source/speech/speech.py b/source/speech/speech.py index 33bbc67746b..16559db0345 100644 --- a/source/speech/speech.py +++ b/source/speech/speech.py @@ -28,7 +28,7 @@ from textUtils import unicodeNormalize from . import manager from .extensions import speechCanceled, pre_speechCanceled, pre_speech -from .extensions import filter_speechSequence, speechCanceled +from .extensions import filter_speechSequence from .commands import ( # Commands that are used in this file. BreakCommand, @@ -2124,7 +2124,7 @@ def _shouldSpeakContentFirst( presCat != attrs.PRESCAT_CONTAINER or role == controlTypes.Role.ARTICLE ) - and not (role in _neverSpeakContentFirstRoles) + and role not in _neverSpeakContentFirstRoles and not tableID and controlTypes.State.EDITABLE not in states ) diff --git a/source/synthDrivers/_espeak.py b/source/synthDrivers/_espeak.py index 192a78cc729..8dfc2155083 100755 --- a/source/synthDrivers/_espeak.py +++ b/source/synthDrivers/_espeak.py @@ -4,7 +4,6 @@ # This file is covered by the GNU General Public License. # See the file COPYING for more details. -import time import nvwave import threading import queue @@ -14,7 +13,6 @@ import globalVars from logHandler import log import os -import codecs isSpeaking = False onIndexReached = None diff --git a/source/synthDrivers/espeak.py b/source/synthDrivers/espeak.py index 8e2da27b113..f795e53ff0e 100644 --- a/source/synthDrivers/espeak.py +++ b/source/synthDrivers/espeak.py @@ -19,7 +19,6 @@ stripLocaleFromLangCode, ) from synthDriverHandler import SynthDriver, VoiceInfo, synthIndexReached, synthDoneSpeaking -import speech from logHandler import log from speech.types import SpeechSequence diff --git a/source/synthDrivers/oneCore.py b/source/synthDrivers/oneCore.py index 994830610c6..d534b562b76 100644 --- a/source/synthDrivers/oneCore.py +++ b/source/synthDrivers/oneCore.py @@ -35,7 +35,6 @@ import nvwave import queueHandler from speech.types import SpeechSequence -import speech import speechXml import languageHandler import winVersion diff --git a/source/textInfos/offsets.py b/source/textInfos/offsets.py index 97384050ef4..aa16a4ee30a 100755 --- a/source/textInfos/offsets.py +++ b/source/textInfos/offsets.py @@ -13,7 +13,6 @@ import textInfos import locationHelper from treeInterceptorHandler import TreeInterceptor -import api import textUtils from dataclasses import dataclass from typing import ( @@ -609,7 +608,7 @@ def unitCount(self,unit): def move(self,unit,direction,endPoint=None): if direction==0: - return 0; + return 0 if endPoint=="end": offset=self._endOffset elif endPoint=="start": diff --git a/source/tones.py b/source/tones.py index beab94ca458..61366b3e170 100644 --- a/source/tones.py +++ b/source/tones.py @@ -8,9 +8,8 @@ import atexit import nvwave import config -import globalVars from logHandler import log -from ctypes import create_string_buffer, byref +from ctypes import create_string_buffer import extensionPoints SAMPLE_RATE = 44100 diff --git a/source/touchHandler.py b/source/touchHandler.py index 5e70329ebda..10d76c81768 100644 --- a/source/touchHandler.py +++ b/source/touchHandler.py @@ -14,7 +14,6 @@ from ctypes.wintypes import * import re import gui -import winVersion import config import winUser import inputCore diff --git a/source/touchTracker.py b/source/touchTracker.py index fd77a5773b2..ea78e229c38 100644 --- a/source/touchTracker.py +++ b/source/touchTracker.py @@ -6,7 +6,6 @@ import threading import time from collections import OrderedDict -from logHandler import log #Possible actions (single trackers) action_tap="tap" diff --git a/source/ui.py b/source/ui.py index 686d3db1be8..80444a7f2ee 100644 --- a/source/ui.py +++ b/source/ui.py @@ -11,10 +11,8 @@ """ import os -import sys from ctypes import ( windll, - oledll, byref, POINTER ) diff --git a/source/updateCheck.py b/source/updateCheck.py index 6f2d4dc16b9..de267030fb9 100644 --- a/source/updateCheck.py +++ b/source/updateCheck.py @@ -26,10 +26,9 @@ import versionInfo if not versionInfo.updateVersionType: raise RuntimeError("No update version type, update checking not supported") -import addonAPIVersion # Avoid a E402 'module level import not at top of file' warning, because several checks are performed above. import gui.contextHelp # noqa: E402 -from gui.dpiScalingHelper import DpiScalingHelperMixin, DpiScalingHelperMixinWithoutInit # noqa: E402 +from gui.dpiScalingHelper import DpiScalingHelperMixinWithoutInit # noqa: E402 import sys # noqa: E402 import os import inspect @@ -58,10 +57,7 @@ ) from logHandler import log, isPathExternalToNVDA import config -import shellapi -import winUser import winKernel -import fileUtils from utils.tempFile import _createEmptyTempFileForDeletingFile #: The URL to use for update checks. diff --git a/source/virtualBuffers/MSHTML.py b/source/virtualBuffers/MSHTML.py index 062c6ac70f5..58af2321d83 100644 --- a/source/virtualBuffers/MSHTML.py +++ b/source/virtualBuffers/MSHTML.py @@ -4,21 +4,17 @@ # Copyright (C) 2009-2023 NV Access Limited, Babbage B.V., Accessolutions, Julien Cochuyt, Cyrille Bougot from comtypes import COMError -import eventHandler from . import VirtualBuffer, VirtualBufferTextInfo, VBufStorage_findMatch_word, VBufStorage_findMatch_notEmpty import controlTypes from controlTypes import TextPosition, TextAlign from controlTypes.formatFields import FontSize import NVDAObjects.IAccessible.MSHTML import winUser -import NVDAHelper -import ctypes import IAccessibleHandler import languageHandler import oleacc from logHandler import log import textInfos -import api import aria import config import exceptions diff --git a/source/virtualBuffers/adobeAcrobat.py b/source/virtualBuffers/adobeAcrobat.py index 465c555e93b..a9da260982a 100644 --- a/source/virtualBuffers/adobeAcrobat.py +++ b/source/virtualBuffers/adobeAcrobat.py @@ -11,7 +11,6 @@ import winUser import IAccessibleHandler import oleacc -from logHandler import log import textInfos import languageHandler diff --git a/source/virtualBuffers/lotusNotes.py b/source/virtualBuffers/lotusNotes.py index 9eba68ae8bd..3415803b56f 100644 --- a/source/virtualBuffers/lotusNotes.py +++ b/source/virtualBuffers/lotusNotes.py @@ -12,7 +12,6 @@ import IAccessibleHandler import oleacc from logHandler import log -import textInfos from virtualBuffers import VirtualBufferTextInfo class LotusNotesRichText_TextInfo(VirtualBufferTextInfo): diff --git a/source/virtualBuffers/webKit.py b/source/virtualBuffers/webKit.py index 502018ac568..807ab4358e9 100644 --- a/source/virtualBuffers/webKit.py +++ b/source/virtualBuffers/webKit.py @@ -3,10 +3,8 @@ # This file is covered by the GNU General Public License. # See the file COPYING for more details. -import ctypes -import typing -from . import VirtualBuffer, VirtualBufferTextInfo, VBufRemote_nodeHandle_t +from . import VirtualBuffer, VirtualBufferTextInfo import controlTypes import NVDAObjects.IAccessible import winUser @@ -15,7 +13,6 @@ import oleacc from logHandler import log import textInfos -import NVDAHelper class WebKit_TextInfo(VirtualBufferTextInfo): diff --git a/source/winConsoleHandler.py b/source/winConsoleHandler.py index b7ed73376f5..e0c096c3168 100755 --- a/source/winConsoleHandler.py +++ b/source/winConsoleHandler.py @@ -11,9 +11,7 @@ from colors import RGB import eventHandler from logHandler import log -import speech import textInfos -import api import config import locationHelper from typing import ( diff --git a/source/windowUtils.py b/source/windowUtils.py index df2bfc493aa..e6057c70e55 100644 --- a/source/windowUtils.py +++ b/source/windowUtils.py @@ -12,7 +12,7 @@ import ctypes import weakref import winUser -from winUser import WNDCLASSEXW, WNDPROC, LRESULT +from winUser import WNDCLASSEXW, WNDPROC from logHandler import log from abc import abstractmethod from baseObject import AutoPropertyObject diff --git a/tests/system/libraries/ChromeLib.py b/tests/system/libraries/ChromeLib.py index a1ad4fcfb47..f5c94b433a7 100644 --- a/tests/system/libraries/ChromeLib.py +++ b/tests/system/libraries/ChromeLib.py @@ -19,7 +19,6 @@ from SystemTestSpy.windows import ( CloseWindow, GetWindowWithTitle, - GetForegroundWindowTitle, Window, ) import _chromeArgs diff --git a/tests/system/libraries/SystemTestSpy/speechSpyGlobalPlugin.py b/tests/system/libraries/SystemTestSpy/speechSpyGlobalPlugin.py index e39a7c42dbc..7b441f82bda 100644 --- a/tests/system/libraries/SystemTestSpy/speechSpyGlobalPlugin.py +++ b/tests/system/libraries/SystemTestSpy/speechSpyGlobalPlugin.py @@ -16,7 +16,6 @@ ) import core -import extensionPoints import globalPluginHandler import threading from .blockUntilConditionMet import ( diff --git a/tests/system/libraries/SystemTestSpy/windows.py b/tests/system/libraries/SystemTestSpy/windows.py index c24ac95d030..3f16e09eeb3 100644 --- a/tests/system/libraries/SystemTestSpy/windows.py +++ b/tests/system/libraries/SystemTestSpy/windows.py @@ -6,7 +6,7 @@ """This module provides functions to interact with the Windows system. """ -from ctypes.wintypes import HWND, LPARAM +from ctypes.wintypes import LPARAM from ctypes import ( c_bool, c_int, diff --git a/tests/system/libraries/WindowsLib.py b/tests/system/libraries/WindowsLib.py index 15f24bd7f21..f009e6d8cd5 100644 --- a/tests/system/libraries/WindowsLib.py +++ b/tests/system/libraries/WindowsLib.py @@ -141,7 +141,7 @@ def taskSwitchToItemMatching(targetWindowNamePattern: _re.Pattern, maxWindowsToT "See NVDA log for dump of all speech." ) else: - builtIn.log(f"Found, attempting to select.", level="DEBUG") + builtIn.log("Found, attempting to select.", level="DEBUG") nextIndex = spy.get_next_speech_index() spy.emulateKeyPress("enter") if not spy.wait_for_speech_to_finish(speechStartedIndex=nextIndex, errorMessage=None): diff --git a/tests/system/robot/chromeTests.py b/tests/system/robot/chromeTests.py index 234aa813ce1..c388ce9a2ad 100644 --- a/tests/system/robot/chromeTests.py +++ b/tests/system/robot/chromeTests.py @@ -1020,18 +1020,18 @@ def test_i12147(): New focus target should be announced if the triggering element is removed when activated. """ _chrome.prepareChrome( - f""" + """

target 0

""" ) @@ -1472,7 +1472,7 @@ def test_i10840(): Chrome self-references a header cell as its own header, which used to cause the name to be announced twice """ _chrome.prepareChrome( - f""" + """ diff --git a/tests/system/robot/symbolPronunciationTests.py b/tests/system/robot/symbolPronunciationTests.py index 7318088c230..a0709992fbe 100644 --- a/tests/system/robot/symbolPronunciationTests.py +++ b/tests/system/robot/symbolPronunciationTests.py @@ -301,7 +301,7 @@ def _testDelayedDescription(expectDescription: bool = True) -> None: """ spoken = _NvdaLib.getSpeechAfterKey(Move.CARET_CHAR.value).split("\n") if not spoken: - raise AssertionError(f"Nothing spoken after character press") + 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]}'" diff --git a/tests/unit/test_baseObject.py b/tests/unit/test_baseObject.py index eba89c5af6c..b0539a2d74f 100644 --- a/tests/unit/test_baseObject.py +++ b/tests/unit/test_baseObject.py @@ -7,10 +7,9 @@ """Unit tests for the baseObject module, its classes and their derivatives.""" import unittest -from baseObject import AutoPropertyObject, ScriptableObject +from baseObject import AutoPropertyObject from .objectProvider import PlaceholderNVDAObject from scriptHandler import script -from abc import abstractmethod class NVDAObjectWithDecoratedScript(PlaceholderNVDAObject): """An object with a decorated script.""" diff --git a/tests/unit/test_speechManager/speechManagerTestHarness.py b/tests/unit/test_speechManager/speechManagerTestHarness.py index 835066d6f7c..cabd584c73c 100644 --- a/tests/unit/test_speechManager/speechManagerTestHarness.py +++ b/tests/unit/test_speechManager/speechManagerTestHarness.py @@ -570,7 +570,7 @@ def _assertStrictIndexOrder(self, expectedToBecomeIndex): self._testCase.assertEqual( expectedToBecomeIndex, indexCommandIndex, - msg=f"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_speechXml.py b/tests/unit/test_speechXml.py index cb78422615b..b5272e09459 100644 --- a/tests/unit/test_speechXml.py +++ b/tests/unit/test_speechXml.py @@ -9,7 +9,6 @@ import unittest import speechXml from speechXml import REPLACEMENT_CHAR -import speech from speech.commands import ( PitchCommand, From 0057dd93e2f89da38963cc6d756d2569c0de272d Mon Sep 17 00:00:00 2001 From: Sean Budd Date: Thu, 27 Jun 2024 13:49:49 +1000 Subject: [PATCH 2/2] run ruff --add-noqa --- include/cldr | 1 - include/microsoft-ui-uiautomation | 1 - site_scons/site_tools/doxygen.py | 4 +- site_scons/site_tools/recursiveInstall.py | 2 +- source/JABHandler.py | 8 +- source/NVDAHelper.py | 36 +- source/NVDAObjects/IAccessible/MSHTML.py | 24 +- source/NVDAObjects/IAccessible/__init__.py | 12 +- source/NVDAObjects/IAccessible/msOffice.py | 4 +- source/NVDAObjects/IAccessible/mscandui.py | 12 +- .../NVDAObjects/IAccessible/sysListView32.py | 160 ++--- .../NVDAObjects/IAccessible/sysTreeView32.py | 4 +- source/NVDAObjects/IAccessible/winword.py | 8 +- source/NVDAObjects/JAB/__init__.py | 26 +- source/NVDAObjects/UIA/__init__.py | 14 +- source/NVDAObjects/__init__.py | 6 +- source/NVDAObjects/behaviors.py | 16 +- source/NVDAObjects/inputComposition.py | 6 +- source/NVDAObjects/window/__init__.py | 12 +- source/NVDAObjects/window/_msOfficeChart.py | 12 +- source/NVDAObjects/window/edit.py | 22 +- source/NVDAObjects/window/excel.py | 36 +- source/NVDAObjects/window/scintilla.py | 2 +- source/NVDAObjects/window/winword.py | 18 +- source/UIAHandler/__init__.py | 92 +-- source/addonHandler/__init__.py | 8 +- source/api.py | 6 +- source/appModuleHandler.py | 6 +- source/appModules/eclipse.py | 4 +- source/appModules/javaw.py | 2 +- source/appModules/kindle.py | 2 +- source/appModules/logonui.py | 2 +- source/appModules/miranda32.py | 8 +- source/appModules/msimn.py | 4 +- source/appModules/nlnotes.py | 2 +- source/appModules/outlook.py | 14 +- source/appModules/poedit.py | 2 +- source/appModules/powerpnt.py | 20 +- source/appModules/thunderbird.py | 2 +- source/appModules/utorrent.py | 2 +- source/appModules/winamp.py | 18 +- source/audioDucking.py | 2 +- source/braille.py | 8 +- source/brailleDisplayDrivers/alva.py | 2 +- source/brailleDisplayDrivers/brltty.py | 6 +- source/brailleDisplayDrivers/ecoBraille.py | 6 +- source/brailleDisplayDrivers/lilli.py | 6 +- source/brailleDisplayDrivers/papenmeier.py | 90 +-- .../papenmeier_serial.py | 58 +- source/brailleInput.py | 2 +- source/browseMode.py | 18 +- source/buildVersion.py | 4 +- source/characterProcessing.py | 8 +- source/config/__init__.py | 10 +- source/core.py | 18 +- source/displayModel.py | 30 +- source/editableText.py | 20 +- source/extensionPoints/__init__.py | 8 +- source/fileUtils.py | 2 +- source/globalCommands.py | 16 +- source/globalPluginHandler.py | 6 +- source/gui/__init__.py | 2 +- source/gui/addonGui.py | 6 +- source/gui/configProfiles.py | 12 +- source/gui/installerGui.py | 4 +- source/gui/settingsDialogs.py | 26 +- source/gui/speechDict.py | 2 +- source/hwIo/base.py | 2 +- source/inputCore.py | 8 +- source/installer.py | 2 +- source/keyboardHandler.py | 4 +- source/logHandler.py | 2 +- source/mathPres/__init__.py | 2 +- source/mouseHandler.py | 16 +- source/nvda.pyw | 18 +- source/nvwave.py | 8 +- source/objbase.py | 10 +- source/oleTypes.py | 624 +++++++++--------- source/oleacc.py | 122 ++-- source/pythonConsole.py | 38 +- source/queueHandler.py | 4 +- source/remotePythonConsole.py | 2 +- source/review.py | 2 +- source/screenExplorer.py | 2 +- source/scriptHandler.py | 4 +- source/setup.py | 10 +- source/shellapi.py | 66 +- source/speech/commands.py | 4 +- source/speech/manager.py | 10 +- source/speech/speech.py | 8 +- source/speechDictHandler/__init__.py | 4 +- source/synthDriverHandler.py | 2 +- source/synthDrivers/_espeak.py | 52 +- source/synthDrivers/espeak.py | 4 +- source/synthDrivers/sapi4.py | 4 +- source/synthDrivers/sapi5.py | 2 +- source/synthSettingsRing.py | 4 +- source/touchHandler.py | 70 +- source/touchTracker.py | 6 +- source/updateCheck.py | 10 +- source/versionInfo.py | 2 +- source/virtualBuffers/MSHTML.py | 2 +- source/virtualBuffers/__init__.py | 30 +- source/virtualBuffers/lotusNotes.py | 6 +- source/virtualBuffers/webKit.py | 4 +- source/vision/__init__.py | 2 +- source/watchdog.py | 4 +- source/winConsoleHandler.py | 4 +- source/winInputHook.py | 54 +- source/winUser.py | 120 ++-- source/wincon.py | 68 +- source/windowUtils.py | 4 +- tests/unit/__init__.py | 22 +- tests/unit/test_extensionPoints.py | 6 +- tests/unit/test_javaAccessBridge.py | 6 +- tests/unit/test_languageHandler.py | 2 +- 116 files changed, 1236 insertions(+), 1238 deletions(-) delete mode 160000 include/cldr delete mode 160000 include/microsoft-ui-uiautomation diff --git a/include/cldr b/include/cldr deleted file mode 160000 index 443ca2332af..00000000000 --- a/include/cldr +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 443ca2332af0c0f0836e6e008cdae875381bc5af diff --git a/include/microsoft-ui-uiautomation b/include/microsoft-ui-uiautomation deleted file mode 160000 index 224b22f3bf9..00000000000 --- a/include/microsoft-ui-uiautomation +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 224b22f3bf9e6bcd7326e471d1e134fe739bf4ff diff --git a/site_scons/site_tools/doxygen.py b/site_scons/site_tools/doxygen.py index f99021dbfd6..af6d276bf52 100644 --- a/site_scons/site_tools/doxygen.py +++ b/site_scons/site_tools/doxygen.py @@ -47,12 +47,12 @@ def DoxyfileParse(file_contents): lex.whitespace = lex.whitespace.replace("\n", "") lex.escape = "" - lineno = lex.lineno + 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 + next_key = False # noqa: F841 new_data = True def append_data(data, key, new_data, token): diff --git a/site_scons/site_tools/recursiveInstall.py b/site_scons/site_tools/recursiveInstall.py index 8efe7b016e3..4fe71f6eb51 100644 --- a/site_scons/site_tools/recursiveInstall.py +++ b/site_scons/site_tools/recursiveInstall.py @@ -51,7 +51,7 @@ def RecursiveInstall(env, target, dir): dir = env.Dir(dir).abspath target = env.Dir(target).abspath - l = len(dir) + 1 + l = len(dir) + 1 # noqa: E741 relnodes = [ n.abspath[l:] for n in nodes ] diff --git a/source/JABHandler.py b/source/JABHandler.py index 63033040571..0667ece57ee 100644 --- a/source/JABHandler.py +++ b/source/JABHandler.py @@ -390,7 +390,7 @@ def internal_getWindowHandleFromAccContext(vmID,accContext): return bridgeDll.getHWNDFromAccessibleContext(vmID,topAC) finally: bridgeDll.releaseJavaObject(vmID,topAC) - except: + except: # noqa: E722 return None def getWindowHandleFromAccContext(vmID,accContext): @@ -421,7 +421,7 @@ def __del__(self): if isRunning: try: bridgeDll.releaseJavaObject(self.vmID,self.accContext) - except: + except: # noqa: E722 log.debugWarning("Error releasing java object",exc_info=True) @@ -795,7 +795,7 @@ def enterJavaWindow_helper(hwnd): while time.time() SystemErrorCodes: def _lookupKeyboardLayoutNameWithHexString(layoutString): buf=create_unicode_buffer(1024) bufSize=c_int(2048) - key=HKEY() - if windll.advapi32.RegOpenKeyExW(winreg.HKEY_LOCAL_MACHINE,u"SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts\\"+ layoutString,0,winreg.KEY_QUERY_VALUE,byref(key))==0: + 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 try: - if windll.advapi32.RegQueryValueExW(key,u"Layout Display Name",0,None,buf,byref(bufSize))==0: + 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) return buf.value - if windll.advapi32.RegQueryValueExW(key,u"Layout Text",0,None,buf,byref(bufSize))==0: + if windll.advapi32.RegQueryValueExW(key,u"Layout Text",0,None,buf,byref(bufSize))==0: # noqa: F405 return buf.value finally: windll.advapi32.RegCloseKey(key) @@ -204,7 +204,7 @@ def _lookupKeyboardLayoutNameWithHexString(layoutString): @WINFUNCTYPE(c_long,c_wchar_p) def nvdaControllerInternal_requestRegistration(uuidString): pid=c_long() - windll.rpcrt4.I_RpcBindingInqLocalClientPID(None,byref(pid)) + 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") @@ -215,10 +215,10 @@ def nvdaControllerInternal_requestRegistration(uuidString): 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)) + 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)) + windll.rpcrt4.RpcBindingFree(byref(bindingHandle)) # noqa: F405 return -1 import appModuleHandler queueHandler.queueFunction(queueHandler.eventQueue,appModuleHandler.update,pid,helperLocalBindingHandle=bindingHandle,inprocRegistrationHandle=registrationHandle) @@ -452,7 +452,7 @@ def handleInputConversionModeUpdate(oldFlags,newFlags,lcid): for x in range(32): x=2**x msgs=inputConversionModeMessages.get(x) - if not msgs: continue + if not msgs: continue # noqa: E701 newOn=bool(newFlags&x) oldOn=bool(oldFlags&x) if newOn!=oldOn: @@ -523,7 +523,7 @@ def nvdaControllerInternal_inputLangChangeNotify(threadID,hkl,layoutString): layoutStringCodes.append(stringCode[0:4].rjust(8,'0')) for stringCode in layoutStringCodes: inputMethodName=_lookupKeyboardLayoutNameWithHexString(stringCode) - if inputMethodName: break + 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. @@ -642,7 +642,7 @@ def initialize() -> None: res=windll.User32.GetKeyboardLayoutNameW(buf) if res: lastLayoutString=buf.value - localLib=cdll.LoadLibrary(os.path.join(versionedLibPath,'nvdaHelperLocal.dll')) + localLib=cdll.LoadLibrary(os.path.join(versionedLibPath,'nvdaHelperLocal.dll')) # noqa: F405 for name,func in [ ("nvdaController_speakText",nvdaController_speakText), ("nvdaController_speakSsml", nvdaController_speakSsml), @@ -670,14 +670,14 @@ def initialize() -> None: raise e localLib.nvdaHelperLocal_initialize(globalVars.appArgs.secure) generateBeep=localLib.generateBeep - generateBeep.argtypes=[c_char_p,c_float,c_int,c_int,c_int] + 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 # The rest of this function (to do with injection) only applies if NVDA is not running as a Windows store application # 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)( + 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: @@ -693,9 +693,9 @@ def initialize() -> None: winKernel.LOAD_WITH_ALTERED_SEARCH_PATH ) if not h: - log.critical("Error loading nvdaHelperRemote.dll: %s" % WinError()) + log.critical("Error loading nvdaHelperRemote.dll: %s" % WinError()) # noqa: F405 return - _remoteLib=CDLL("nvdaHelperRemote",handle=h) + _remoteLib=CDLL("nvdaHelperRemote",handle=h) # noqa: F405 if _remoteLib.injection_initialize() == 0: raise RuntimeError("Error initializing NVDAHelperRemote") if not _remoteLib.installIA2Support(): @@ -749,6 +749,6 @@ def bstrReturn(address): # Just access the string ourselves. # This will terminate at a null character, even though BSTR allows nulls. # We're only using this for normal, null-terminated strings anyway. - val = wstring_at(address) + val = wstring_at(address) # noqa: F405 windll.oleaut32.SysFreeString(address) return val diff --git a/source/NVDAObjects/IAccessible/MSHTML.py b/source/NVDAObjects/IAccessible/MSHTML.py index 1aa73ecced9..23a69c9be4a 100644 --- a/source/NVDAObjects/IAccessible/MSHTML.py +++ b/source/NVDAObjects/IAccessible/MSHTML.py @@ -193,7 +193,7 @@ def locateHTMLElementByID(document,ID): else: #probably IE 10 in standards mode (#3151) try: element=document.all.item(ID) - except: + except: # noqa: E722 element=None if element is None: #getElementsByName doesn't return element with specified ID in IE11 (#5784) try: @@ -229,7 +229,7 @@ def locateHTMLElementByID(document,ID): if not childElement: continue childElement=locateHTMLElementByID(childElement.document,ID) - if not childElement: continue + if not childElement: continue # noqa: E701 return childElement def getChildHTMLNodeFromFrame(frame): @@ -240,7 +240,7 @@ def getChildHTMLNodeFromFrame(frame): # In this case, just skip this frame. return res=IAccessibleHandler.accChild(pacc,1) - if not res: return + if not res: return # noqa: E701 return HTMLNodeFromIAccessible(res[0]) class MSHTMLTextInfo(textInfos.TextInfo): @@ -297,7 +297,7 @@ def __init__(self,obj,position,_rangeObj=None): return try: editableBody=self.obj.HTMLNodeName=="BODY" and self.obj.isContentEditable - except: + except: # noqa: E722 editableBody=False if editableBody: self._rangeObj=self.obj.HTMLNode.document.selection.createRange() @@ -442,7 +442,7 @@ def suspendCaretEvents(self): self._ignoreCaretEvents=oldVal def event_caret(self): - if self._ignoreCaretEvents: return + if self._ignoreCaretEvents: return # noqa: E701 if self.TextInfo is not MSHTMLTextInfo and not self._UIAControl: return try: @@ -474,7 +474,7 @@ def kwargsFromSuper(cls,kwargs,relation=None): while True: try: HTMLNode=HTMLNode.document.activeElement - except: + except: # noqa: E722 log.exception("Error getting activeElement") break nodeName=HTMLNode.nodeName or "" @@ -495,7 +495,7 @@ def kwargsFromSuper(cls,kwargs,relation=None): xFactor,yFactor=getZoomFactorsFromHTMLDocument(HTMLNode.document) try: HTMLNode=HTMLNode.document.elementFromPoint(p.x // xFactor, p.y // yFactor) - except: + except: # noqa: E722 HTMLNode=None if not HTMLNode: log.debugWarning("Error getting HTMLNode with elementFromPoint") @@ -846,7 +846,7 @@ def _get_states(self): def _get_isContentEditable(self): try: return bool(self.HTMLNode.isContentEditable) - except: + except: # noqa: E722 return False def _get_parent(self): @@ -935,7 +935,7 @@ def _get_columnNumber(self): raise NotImplementedError try: return self.HTMLNode.cellIndex+1 - except: + except: # noqa: E722 raise NotImplementedError def _get_rowNumber(self): @@ -945,7 +945,7 @@ def _get_rowNumber(self): while HTMLNode: try: return HTMLNode.rowIndex+1 - except: + except: # noqa: E722 pass HTMLNode=HTMLNode.parentNode raise NotImplementedError @@ -955,7 +955,7 @@ def _get_rowCount(self): raise NotImplementedError try: return len([x for x in self.HTMLNode.rows]) - except: + except: # noqa: E722 raise NotImplementedError def scrollIntoView(self): @@ -1007,7 +1007,7 @@ def _get_table(self): nodeName=HTMLNode.nodeName if nodeName: nodeName=nodeName.upper() - if nodeName=="TABLE": return MSHTML(HTMLNode=HTMLNode) + if nodeName=="TABLE": return MSHTML(HTMLNode=HTMLNode) # noqa: E701 HTMLNode=HTMLNode.parentNode return None diff --git a/source/NVDAObjects/IAccessible/__init__.py b/source/NVDAObjects/IAccessible/__init__.py index 274480b6d86..10ceaa2af4d 100644 --- a/source/NVDAObjects/IAccessible/__init__.py +++ b/source/NVDAObjects/IAccessible/__init__.py @@ -31,18 +31,18 @@ from comInterfaces.tom import ITextDocument from comInterfaces import Accessibility as IA from comInterfaces import IAccessible2Lib as IA2 -import tones +import tones # noqa: F401 import languageHandler import textInfos.offsets import textUtils import colors -import time +import time # noqa: F401 import displayModel import IAccessibleHandler import oleacc import JABHandler import winUser -import globalVars +import globalVars # noqa: F401 from logHandler import log import speech import braille @@ -52,10 +52,10 @@ from controlTypes import TextPosition from controlTypes.formatFields import FontSize, TextAlign from NVDAObjects.window import Window -from NVDAObjects import NVDAObject, NVDAObjectTextInfo, InvalidNVDAObject +from NVDAObjects import NVDAObject, NVDAObjectTextInfo, InvalidNVDAObject # noqa: F401 import NVDAObjects.JAB import eventHandler -from NVDAObjects.behaviors import ProgressBar, Dialog, EditableTextWithAutoSelectDetection, FocusableUnfocusableContainer, ToolTip, Notification +from NVDAObjects.behaviors import ProgressBar, Dialog, EditableTextWithAutoSelectDetection, FocusableUnfocusableContainer, ToolTip, Notification # noqa: F401 from locationHelper import RectLTWH import NVDAHelper @@ -2139,7 +2139,7 @@ def _get_name(self): if name: #Remove any data after the null character i=name.find('\0') - if i>=0: name=name[:i] + if i>=0: name=name[:i] # noqa: E701 return name class TaskList(IAccessible): diff --git a/source/NVDAObjects/IAccessible/msOffice.py b/source/NVDAObjects/IAccessible/msOffice.py index 7dabc9b6bb8..d68d06040b9 100755 --- a/source/NVDAObjects/IAccessible/msOffice.py +++ b/source/NVDAObjects/IAccessible/msOffice.py @@ -65,7 +65,7 @@ def _get_SDMChild(self): hwndFocus=winUser.getGUIThreadInfo(0).hwndFocus if hwndFocus and hwndFocus!=self.windowHandle and winUser.isDescendantWindow(self.windowHandle,hwndFocus) and not winUser.getClassName(hwndFocus).startswith('bosa_sdm'): obj=getNVDAObjectFromEvent(hwndFocus,winUser.OBJID_CLIENT,0) - if not obj: return None + if not obj: return None # noqa: E701 if getattr(obj,'parentSDMCanOverrideName',True): obj.name=self.name obj.keyboardShortcut=self.keyboardShortcut @@ -149,7 +149,7 @@ def _get_description(self): name, matchRGB = self.rgbNameAndMatch if matchRGB: import colors - rgb=colors.RGB.fromString(name) + rgb=colors.RGB.fromString(name) # noqa: F841 # Translators: a color, broken down into its RGB red, green, blue parts. return _("RGB red {rgb.red}, green {rgb.green}, blue {rgb.blue}").format(rgb=colors.RGB.fromString(name)) else: diff --git a/source/NVDAObjects/IAccessible/mscandui.py b/source/NVDAObjects/IAccessible/mscandui.py index b80b76e0b94..c3738f05b7b 100755 --- a/source/NVDAObjects/IAccessible/mscandui.py +++ b/source/NVDAObjects/IAccessible/mscandui.py @@ -74,17 +74,17 @@ class MSCandUI21_candidateMenuItem(BaseCandidateItem): def _get_previous(self): item=super(MSCandUI21_candidateMenuItem,self).previous - if not item or controlTypes.State.INVISIBLE in item.states: return + if not item or controlTypes.State.INVISIBLE in item.states: return # noqa: E701 return MSCandUI21_candidateMenuItem(IAccessibleObject=item.IAccessibleObject,IAccessibleChildID=item.IAccessibleChildID) def _get_next(self): item=super(MSCandUI21_candidateMenuItem,self).next - if not item or controlTypes.State.INVISIBLE in item.states: return + if not item or controlTypes.State.INVISIBLE in item.states: return # noqa: E701 return MSCandUI21_candidateMenuItem(IAccessibleObject=item.IAccessibleObject,IAccessibleChildID=item.IAccessibleChildID) def doAction(self,index=None): if not index: - l=self.location + l=self.location # noqa: E741 if l: x=l[0] y=l[1] @@ -97,12 +97,12 @@ def doAction(self,index=None): def script_nextItem(self,gesture): item=self.next - if not item or not isinstance(item.candidateNumber,int): return + if not item or not isinstance(item.candidateNumber,int): return # noqa: E701 reportSelectedCandidate(item) def script_previousItem(self,gesture): item=self.previous - if not item or not isinstance(item.candidateNumber,int): return + if not item or not isinstance(item.candidateNumber,int): return # noqa: E701 reportSelectedCandidate(item) def script_changePage(self,gesture): @@ -147,7 +147,7 @@ def _get_isPresentableFocusAncestor(self): def event_show(self): candidateList=self.simpleFirstChild - if not candidateList: return + if not candidateList: return # noqa: E701 role=candidateList.role if role==controlTypes.Role.LIST: item=candidateList.firstChild diff --git a/source/NVDAObjects/IAccessible/sysListView32.py b/source/NVDAObjects/IAccessible/sysListView32.py index a0041de51e2..024a47a5590 100644 --- a/source/NVDAObjects/IAccessible/sysListView32.py +++ b/source/NVDAObjects/IAccessible/sysListView32.py @@ -4,9 +4,9 @@ # See the file COPYING for more details. import time -from ctypes import * +from ctypes import * # noqa: F403 import ctypes -from ctypes.wintypes import * +from ctypes.wintypes import * # noqa: F403 from comtypes import BSTR import NVDAHelper import watchdog @@ -87,72 +87,72 @@ HDM_FIRST=0x1200 HDM_GETITEMCOUNT=HDM_FIRST -class LVITEM(Structure): +class LVITEM(Structure): # noqa: F405 _fields_=[ - ('mask',c_uint), - ('iItem',c_int), - ('iSubItem',c_int), - ('state',c_uint), - ('stateMask',c_uint), - ('pszText',c_void_p), - ('cchTextMax',c_int), - ('iImage',c_int), - ('lParam',LPARAM), - ('iIndent',c_int), - ('iGroupID',c_int), - ('cColumns',c_uint), - ('puColumns',c_uint), - ('piColFmt',POINTER(c_int)), - ('iGroup',c_int), + ('mask',c_uint), # noqa: F405 + ('iItem',c_int), # noqa: F405 + ('iSubItem',c_int), # noqa: F405 + ('state',c_uint), # noqa: F405 + ('stateMask',c_uint), # noqa: F405 + ('pszText',c_void_p), # noqa: F405 + ('cchTextMax',c_int), # noqa: F405 + ('iImage',c_int), # noqa: F405 + ('lParam',LPARAM), # noqa: F405 + ('iIndent',c_int), # noqa: F405 + ('iGroupID',c_int), # noqa: F405 + ('cColumns',c_uint), # noqa: F405 + ('puColumns',c_uint), # noqa: F405 + ('piColFmt',POINTER(c_int)), # noqa: F405 + ('iGroup',c_int), # noqa: F405 ] -class LVITEM64(Structure): +class LVITEM64(Structure): # noqa: F405 _fields_=[ - ('mask',c_uint), - ('iItem',c_int), - ('iSubItem',c_int), - ('state',c_uint), - ('stateMask',c_uint), - ('pszText',c_ulonglong), - ('cchTextMax',c_int), - ('iImage',c_int), - ('lParam',c_ulonglong), - ('iIndent',c_int), - ('iGroupID',c_int), - ('cColumns',c_uint), - ('puColumns',c_uint), - ('piColFmt',c_ulonglong), - ('iGroup',c_int), + ('mask',c_uint), # noqa: F405 + ('iItem',c_int), # noqa: F405 + ('iSubItem',c_int), # noqa: F405 + ('state',c_uint), # noqa: F405 + ('stateMask',c_uint), # noqa: F405 + ('pszText',c_ulonglong), # noqa: F405 + ('cchTextMax',c_int), # noqa: F405 + ('iImage',c_int), # noqa: F405 + ('lParam',c_ulonglong), # noqa: F405 + ('iIndent',c_int), # noqa: F405 + ('iGroupID',c_int), # noqa: F405 + ('cColumns',c_uint), # noqa: F405 + ('puColumns',c_uint), # noqa: F405 + ('piColFmt',c_ulonglong), # noqa: F405 + ('iGroup',c_int), # noqa: F405 ] -class LVCOLUMN(Structure): +class LVCOLUMN(Structure): # noqa: F405 _fields_=[ - ('mask',c_uint), - ('fmt',c_int), - ('cx',c_int), - ('pszText',c_void_p), - ('cchTextMax',c_int), - ('iSubItem',c_int), - ('iImage',c_int), - ('iOrder',c_int), - ('cxMin',c_int), - ('cxDefault',c_int), - ('cxIdeal',c_int), + ('mask',c_uint), # noqa: F405 + ('fmt',c_int), # noqa: F405 + ('cx',c_int), # noqa: F405 + ('pszText',c_void_p), # noqa: F405 + ('cchTextMax',c_int), # noqa: F405 + ('iSubItem',c_int), # noqa: F405 + ('iImage',c_int), # noqa: F405 + ('iOrder',c_int), # noqa: F405 + ('cxMin',c_int), # noqa: F405 + ('cxDefault',c_int), # noqa: F405 + ('cxIdeal',c_int), # noqa: F405 ] -class LVCOLUMN64(Structure): +class LVCOLUMN64(Structure): # noqa: F405 _fields_=[ - ('mask',c_uint), - ('fmt',c_int), - ('cx',c_int), - ('pszText',c_ulonglong), - ('cchTextMax',c_int), - ('iSubItem',c_int), - ('iImage',c_int), - ('iOrder',c_int), - ('cxMin',c_int), - ('cxDefault',c_int), - ('cxIdeal',c_int), + ('mask',c_uint), # noqa: F405 + ('fmt',c_int), # noqa: F405 + ('cx',c_int), # noqa: F405 + ('pszText',c_ulonglong), # noqa: F405 + ('cchTextMax',c_int), # noqa: F405 + ('iSubItem',c_int), # noqa: F405 + ('iImage',c_int), # noqa: F405 + ('iOrder',c_int), # noqa: F405 + ('cxMin',c_int), # noqa: F405 + ('cxDefault',c_int), # noqa: F405 + ('cxIdeal',c_int), # noqa: F405 ] @@ -178,8 +178,8 @@ class List(List): def getListGroupInfo(self,groupIndex): header=AutoFreeBSTR() footer=AutoFreeBSTR() - state=c_int() - if watchdog.cancellableExecute(NVDAHelper.localLib.nvdaInProcUtils_sysListView32_getGroupInfo,self.appModule.helperLocalBindingHandle,self.windowHandle,groupIndex,byref(header),byref(footer),byref(state))!=0: + state=c_int() # noqa: F405 + if watchdog.cancellableExecute(NVDAHelper.localLib.nvdaInProcUtils_sysListView32_getGroupInfo,self.appModule.helperLocalBindingHandle,self.windowHandle,groupIndex,byref(header),byref(footer),byref(state))!=0: # noqa: F405 return None return dict(header=header.value,footer=footer.value,state=state.value,groupIndex=groupIndex) @@ -258,9 +258,9 @@ def _getColumnOrderArrayRawOutProc(self, columnCount: int) -> Optional[ctypes.Ar """ coa = (ctypes.c_int * columnCount)() processHandle=self.processHandle - internalCoa=winKernel.virtualAllocEx(processHandle,None,sizeof(coa),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) + internalCoa=winKernel.virtualAllocEx(processHandle,None,sizeof(coa),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) # noqa: F405 try: - winKernel.writeProcessMemory(processHandle,internalCoa,byref(coa),sizeof(coa),None) + winKernel.writeProcessMemory(processHandle,internalCoa,byref(coa),sizeof(coa),None) # noqa: F405 # The meaning of the return value depends on the message sent, for LVM_GETCOLUMNORDERARRAY, # it returns nonzero if successful, or 0 otherwise. # https://docs.microsoft.com/en-us/windows/win32/controls/lvm-getcolumnorderarray#return-value @@ -271,7 +271,7 @@ def _getColumnOrderArrayRawOutProc(self, columnCount: int) -> Optional[ctypes.Ar internalCoa ) if res: - winKernel.readProcessMemory(processHandle,internalCoa,byref(coa),sizeof(coa),None) + winKernel.readProcessMemory(processHandle,internalCoa,byref(coa),sizeof(coa),None) # noqa: F405 else: coa = None log.debugWarning( @@ -422,16 +422,16 @@ def _getColumnLocationRawOutProc(self, index: int) -> ctypes.wintypes.RECT: """ processHandle=self.processHandle # LVM_GETSUBITEMRECT requires a pointer to a RECT structure that will receive the subitem bounding rectangle information. - localRect=RECT( + localRect=RECT( # noqa: F405 # Returns the bounding rectangle of the entire item, including the icon and label. 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 ) - internalRect=winKernel.virtualAllocEx(processHandle,None,sizeof(localRect),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) + internalRect=winKernel.virtualAllocEx(processHandle,None,sizeof(localRect),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) # noqa: F405 try: - winKernel.writeProcessMemory(processHandle,internalRect,byref(localRect),sizeof(localRect),None) + winKernel.writeProcessMemory(processHandle,internalRect,byref(localRect),sizeof(localRect),None) # noqa: F405 res = watchdog.cancellableSendMessage( self.windowHandle, LVM_GETSUBITEMRECT, @@ -508,17 +508,17 @@ def _getColumnContentRawOutProc(self, index: int) -> Optional[str]: """ buffer=None processHandle=self.processHandle - internalItem=winKernel.virtualAllocEx(processHandle,None,sizeof(self.LVITEM),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) + internalItem=winKernel.virtualAllocEx(processHandle,None,sizeof(self.LVITEM),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) # noqa: F405 try: internalText=winKernel.virtualAllocEx(processHandle,None,CBEMAXSTRLEN*2,winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) try: item=self.LVITEM(iItem=self.IAccessibleChildID-1,mask=LVIF_TEXT|LVIF_COLUMNS,iSubItem=index,pszText=internalText,cchTextMax=CBEMAXSTRLEN) - winKernel.writeProcessMemory(processHandle,internalItem,byref(item),sizeof(self.LVITEM),None) + winKernel.writeProcessMemory(processHandle,internalItem,byref(item),sizeof(self.LVITEM),None) # noqa: F405 len = watchdog.cancellableSendMessage(self.windowHandle,LVM_GETITEMTEXTW, (self.IAccessibleChildID-1), internalItem) if len: - winKernel.readProcessMemory(processHandle,internalItem,byref(item),sizeof(self.LVITEM),None) - buffer=create_unicode_buffer(len) - winKernel.readProcessMemory(processHandle,item.pszText,buffer,sizeof(buffer),None) + winKernel.readProcessMemory(processHandle,internalItem,byref(item),sizeof(self.LVITEM),None) # noqa: F405 + buffer=create_unicode_buffer(len) # noqa: F405 + winKernel.readProcessMemory(processHandle,item.pszText,buffer,sizeof(buffer),None) # noqa: F405 finally: winKernel.virtualFreeEx(processHandle,internalText,0,winKernel.MEM_RELEASE) finally: @@ -538,14 +538,14 @@ def _getColumnContent(self, column: int) -> Optional[str]: def _getColumnImageIDRaw(self, index): processHandle=self.processHandle - internalItem=winKernel.virtualAllocEx(processHandle,None,sizeof(self.LVITEM),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) + internalItem=winKernel.virtualAllocEx(processHandle,None,sizeof(self.LVITEM),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) # noqa: F405 try: item=self.LVITEM(iItem=self.IAccessibleChildID-1,mask=LVIF_IMAGE|LVIF_COLUMNS,iSubItem=index) - winKernel.writeProcessMemory(processHandle,internalItem,byref(item),sizeof(self.LVITEM),None) + winKernel.writeProcessMemory(processHandle,internalItem,byref(item),sizeof(self.LVITEM),None) # noqa: F405 item.mask=LVIF_IMAGE|LVIF_COLUMNS - winKernel.writeProcessMemory(processHandle,internalItem,byref(item),sizeof(self.LVITEM),None) + winKernel.writeProcessMemory(processHandle,internalItem,byref(item),sizeof(self.LVITEM),None) # noqa: F405 watchdog.cancellableSendMessage(self.windowHandle,LVM_GETITEMW, 0, internalItem) - winKernel.readProcessMemory(processHandle,internalItem,byref(item),sizeof(item),None) + winKernel.readProcessMemory(processHandle,internalItem,byref(item),sizeof(item),None) # noqa: F405 finally: winKernel.virtualFreeEx(processHandle,internalItem,0,winKernel.MEM_RELEASE) return item.iImage @@ -565,17 +565,17 @@ def _getColumnHeaderRawOutProc(self, index: int) -> Optional[str]: """ buffer=None processHandle=self.processHandle - internalColumn=winKernel.virtualAllocEx(processHandle,None,sizeof(self.LVCOLUMN),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) + internalColumn=winKernel.virtualAllocEx(processHandle,None,sizeof(self.LVCOLUMN),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) # noqa: F405 try: internalText=winKernel.virtualAllocEx(processHandle,None,CBEMAXSTRLEN*2,winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) try: column=self.LVCOLUMN(mask=LVCF_TEXT,iSubItem=index,pszText=internalText,cchTextMax=CBEMAXSTRLEN) - winKernel.writeProcessMemory(processHandle,internalColumn,byref(column),sizeof(self.LVCOLUMN),None) + winKernel.writeProcessMemory(processHandle,internalColumn,byref(column),sizeof(self.LVCOLUMN),None) # noqa: F405 res = watchdog.cancellableSendMessage(self.windowHandle,LVM_GETCOLUMNW, index, internalColumn) if res: - winKernel.readProcessMemory(processHandle,internalColumn,byref(column),sizeof(self.LVCOLUMN),None) - buffer=create_unicode_buffer(column.cchTextMax) - winKernel.readProcessMemory(processHandle,column.pszText,buffer,sizeof(buffer),None) + winKernel.readProcessMemory(processHandle,internalColumn,byref(column),sizeof(self.LVCOLUMN),None) # noqa: F405 + buffer=create_unicode_buffer(column.cchTextMax) # noqa: F405 + winKernel.readProcessMemory(processHandle,column.pszText,buffer,sizeof(buffer),None) # noqa: F405 finally: winKernel.virtualFreeEx(processHandle,internalText,0,winKernel.MEM_RELEASE) finally: diff --git a/source/NVDAObjects/IAccessible/sysTreeView32.py b/source/NVDAObjects/IAccessible/sysTreeView32.py index feaccbb4533..5a2a3f281e1 100755 --- a/source/NVDAObjects/IAccessible/sysTreeView32.py +++ b/source/NVDAObjects/IAccessible/sysTreeView32.py @@ -39,7 +39,7 @@ class TreeView(IAccessible): def _get_firstChild(self): try: return super(TreeView, self).firstChild - except: + except: # noqa: E722 # Broken commctrl 5 tree view. return BrokenCommctrl5Item.getFirstItem(self) @@ -273,7 +273,7 @@ def getFirstItem(cls, treeObj): kwargs = {"windowHandle": treeObj.windowHandle} UIA.kwargsFromSuper(kwargs) uiaObj = UIA(**kwargs) - except: + except: # noqa: E722 log.debugWarning("Error retrieving UIA object for tree view", exc_info=True) return None # Get the first tree item. diff --git a/source/NVDAObjects/IAccessible/winword.py b/source/NVDAObjects/IAccessible/winword.py index c9c13834e50..def8825f14a 100644 --- a/source/NVDAObjects/IAccessible/winword.py +++ b/source/NVDAObjects/IAccessible/winword.py @@ -365,7 +365,7 @@ def _moveInTable(self,row=True,forward=True): ui.message(_("Not in table")) return False _cell=table.cell - getCell=lambda thisIndex,otherIndex: _cell(thisIndex,otherIndex) if row else _cell(otherIndex,thisIndex) + getCell=lambda thisIndex,otherIndex: _cell(thisIndex,otherIndex) if row else _cell(otherIndex,thisIndex) # noqa: E731 thisIndex=rowNumber if row else columnNumber otherIndex=columnNumber if row else rowNumber thisLimit=(rowCount if row else columnCount) if forward else 1 @@ -380,9 +380,9 @@ def _moveInTable(self,row=True,forward=True): foundCell=getCell(curThisIndex,curOtherIndex).range except COMError: pass - if foundCell: break + if foundCell: break # noqa: E701 curThisIndex=incdecFunc(curThisIndex,1) - if foundCell: break + if foundCell: break # noqa: E701 curOtherIndex-=1 if not foundCell: ui.message(_("Edge of table")) @@ -489,7 +489,7 @@ def _get_errorText(self): textList=[] for field in fields: if isinstance(field,str): - if inBold: textList.append(field) + if inBold: textList.append(field) # noqa: E701 elif field.field: inBold=field.field.get('bold',False) if not inBold and len(textList)>0: diff --git a/source/NVDAObjects/JAB/__init__.py b/source/NVDAObjects/JAB/__init__.py index 9cf5025f3b4..f9b18cb97ba 100644 --- a/source/NVDAObjects/JAB/__init__.py +++ b/source/NVDAObjects/JAB/__init__.py @@ -279,7 +279,7 @@ def _get_TextInfo(self): def _isEqual(self,other): try: return self.jabContext==other.jabContext - except: + except: # noqa: E722 return False def _get_keyboardShortcut(self): @@ -304,7 +304,7 @@ def _get_keyboardShortcut(self): modifiers |= JABHandler.AccessibleKeystroke.ALT keyList = [ keyLabels.localizedKeyLabels.get(l, l) - for l in JABHandler._getKeyLabels(modifiers, binding.character) + for l in JABHandler._getKeyLabels(modifiers, binding.character) # noqa: E741 ] shortcutsList.append("+".join(keyList)) return ", ".join(shortcutsList) @@ -393,7 +393,7 @@ def _get_positionInfo(self): selfDepth=self.jabContext.getObjectDepth() if selfDepth > treeDepth: info['level']=selfDepth-treeDepth - except: + except: # noqa: E722 pass targets=self._getJABRelationTargets('memberOf') @@ -585,13 +585,13 @@ def _get_activeDescendant(self): while jabContext: try: tempContext=jabContext.getActiveDescendent() - except: + except: # noqa: E722 break if not tempContext: break try: depth=tempContext.getObjectDepth() - except: + except: # noqa: E722 depth=-1 if depth<=0 or tempContext==jabContext: break @@ -680,13 +680,13 @@ def _get_rowHeaderText(self): cellInfo=headerTableInfo.jabTable.getAccessibleTableCellInfo(row,col) if cellInfo and cellInfo.jabContext: obj=JAB(jabContext=cellInfo.jabContext) - if obj.name: textList.append(obj.name) - if obj.description: textList.append(obj.description) + if obj.name: textList.append(obj.name) # noqa: E701 + if obj.description: textList.append(obj.description) # noqa: E701 jabContext=self.table._jabTableInfo.jabTable.getAccessibleTableRowDescription(row) if jabContext: obj=JAB(jabContext=jabContext) - if obj.name: textList.append(obj.name) - if obj.description: textList.append(obj.description) + if obj.name: textList.append(obj.name) # noqa: E701 + if obj.description: textList.append(obj.description) # noqa: E701 return " ".join(textList) def _get_columnHeaderText(self): @@ -698,11 +698,11 @@ def _get_columnHeaderText(self): cellInfo=headerTableInfo.jabTable.getAccessibleTableCellInfo(row,col) if cellInfo and cellInfo.jabContext: obj=JAB(jabContext=cellInfo.jabContext) - if obj.name: textList.append(obj.name) - if obj.description: textList.append(obj.description) + if obj.name: textList.append(obj.name) # noqa: E701 + if obj.description: textList.append(obj.description) # noqa: E701 jabContext=self.table._jabTableInfo.jabTable.getAccessibleTableColumnDescription(col) if jabContext: obj=JAB(jabContext=jabContext) - if obj.name: textList.append(obj.name) - if obj.description: textList.append(obj.description) + if obj.name: textList.append(obj.name) # noqa: E701 + if obj.description: textList.append(obj.description) # noqa: E701 return " ".join(textList) diff --git a/source/NVDAObjects/UIA/__init__.py b/source/NVDAObjects/UIA/__init__.py index f59810e324d..152a833573b 100644 --- a/source/NVDAObjects/UIA/__init__.py +++ b/source/NVDAObjects/UIA/__init__.py @@ -341,7 +341,7 @@ def _getFormatFieldAtRange( # noqa: C901 if cultureVal and isinstance(cultureVal,int): try: formatField['language']=languageHandler.windowsLCIDToLocaleName(cultureVal) - except: + except: # noqa: E722 log.debugWarning("language error",exc_info=True) pass return textInfos.FieldCommand("formatChange",formatField) @@ -460,7 +460,7 @@ def __init__( # noqa: C901 except COMError: raise LookupError # sometimes rangeFromChild can return a NULL range - if not self._rangeObj: raise LookupError + if not self._rangeObj: raise LookupError # noqa: E701 elif isinstance(position,locationHelper.Point): self._rangeObj: IUIAutomationTextRangeT = self.obj.UIATextPattern.RangeFromPoint(position.toPOINT()) elif isinstance(position, UIAHandler.IUIAutomationTextRange): @@ -470,8 +470,8 @@ def __init__( # noqa: C901 raise ValueError("Unknown position %s"%position) def __eq__(self, other: "UIATextInfo"): - if self is other: return True - if self.__class__ is not other.__class__: return False + if self is other: return True # noqa: E701 + if self.__class__ is not other.__class__: return False # noqa: E701 return bool(self._rangeObj.compare(other._rangeObj)) # As __eq__ was defined on this class, we must provide __hash__ to remain hashable. @@ -1374,7 +1374,7 @@ def _isEqual(self,other): return False try: return UIAHandler.handler.clientObject.CompareElements(self.UIAElement,other.UIAElement) - except: + except: # noqa: E722 return False def event_gainFocus(self): @@ -2294,7 +2294,7 @@ def _get_positionInfo(self): info['indexInGroup']=itemIndex try: e=self._getUIACacheablePropertyValue(UIAHandler.UIA_SelectionItemSelectionContainerPropertyId) - if e: e=e.QueryInterface(UIAHandler.IUIAutomationElement) + if e: e=e.QueryInterface(UIAHandler.IUIAutomationElement) # noqa: E701 except COMError: e=None if e: @@ -2328,7 +2328,7 @@ def _get_description(self): desc = self.UIAHelpText try: i=desc.find('\n') - except: + except: # noqa: E722 i=None if i: desc=desc[i+1:] diff --git a/source/NVDAObjects/__init__.py b/source/NVDAObjects/__init__.py index 48f46b050cf..a99960f9d6a 100644 --- a/source/NVDAObjects/__init__.py +++ b/source/NVDAObjects/__init__.py @@ -81,7 +81,7 @@ class DynamicNVDAObjectType(baseObject.ScriptableObject.__class__): def __call__(self,chooseBestAPI=True,**kwargs): if chooseBestAPI: APIClass=self.findBestAPIClass(kwargs) - if not APIClass: return None + if not APIClass: return None # noqa: E701 else: APIClass=self @@ -988,7 +988,7 @@ def _get_simpleFirstChild(self): if not child: return None presType=child.presentationType - if presType!=self.presType_content: return child._findSimpleNext(useChild=(presType!=self.presType_unavailable),useParent=False) + if presType!=self.presType_content: return child._findSimpleNext(useChild=(presType!=self.presType_unavailable),useParent=False) # noqa: E701 return child def _get_simpleLastChild(self): @@ -996,7 +996,7 @@ def _get_simpleLastChild(self): if not child: return None presType=child.presentationType - if presType!=self.presType_content: return child._findSimpleNext(useChild=(presType!=self.presType_unavailable),useParent=False,goPrevious=True) + if presType!=self.presType_content: return child._findSimpleNext(useChild=(presType!=self.presType_unavailable),useParent=False,goPrevious=True) # noqa: E701 return child def _get_childCount(self): diff --git a/source/NVDAObjects/behaviors.py b/source/NVDAObjects/behaviors.py index daefd4ffa3a..6380b694990 100755 --- a/source/NVDAObjects/behaviors.py +++ b/source/NVDAObjects/behaviors.py @@ -53,7 +53,7 @@ def event_valueChange(self): return try: left,top,width,height=self.location - except: + except: # noqa: E722 left=top=width=height=0 x = left + (width // 2) y = top+ (height // 2) @@ -420,7 +420,7 @@ def _reportNewText(self, line): def _monitor(self): try: oldText = self._getText() - except: + except: # noqa: E722 log.exception("Error getting initial text") oldText = "" @@ -448,7 +448,7 @@ def _monitor(self): if outLines: queueHandler.queueFunction(queueHandler.eventQueue, self._reportNewLines, outLines, _immediate=True) oldText = newText - except: + except: # noqa: E722 log.exception("Error getting or calculating new text") def _calculateNewText(self, newText: str, oldText: str) -> List[str]: @@ -602,9 +602,9 @@ def getFormattedCandidateName(self,number,candidate): return _(u"{number} {candidate}").format(number=number,candidate=candidate) def getFormattedCandidateDescription(self,candidate): - descriptions=[] + descriptions=[] # noqa: F841 numSymbols=len(candidate) if candidate else 0 - if numSymbols!=1: return u"" + if numSymbols!=1: return u"" # noqa: E701 symbol=candidate[0] try: symbolDescriptions=characterProcessing.getCharacterDescription(speech.getCurrentLanguage(),symbol) or [] @@ -612,11 +612,11 @@ def getFormattedCandidateDescription(self,candidate): symbolDescriptions=[] if config.conf["inputComposition"]["alwaysIncludeShortCharacterDescriptionInCandidateName"]: symbolDescriptions=symbolDescriptions[1:] - if len(symbolDescriptions)<1: return u"" + if len(symbolDescriptions)<1: return u"" # noqa: E701 return u", ".join(symbolDescriptions) def reportFocus(self): - if not config.conf["inputComposition"]["announceSelectedCandidate"]: return + if not config.conf["inputComposition"]["announceSelectedCandidate"]: return # noqa: E701 text=self.name desc=self.description if desc: @@ -634,7 +634,7 @@ def _get_visibleCandidateItemsText(self): while isinstance(obj,CandidateItem) and isinstance(obj.candidateNumber,int) and controlTypes.State.INVISIBLE not in obj.states: textList.append(obj.name) obj=obj.next - if len(textList)<=1: return None + if len(textList)<=1: return None # noqa: E701 self.visibleCandidateItemsText=(u", ".join(textList))+u", " return self.visibleCandidateItemsText diff --git a/source/NVDAObjects/inputComposition.py b/source/NVDAObjects/inputComposition.py index e473ed3b731..901a54574ef 100644 --- a/source/NVDAObjects/inputComposition.py +++ b/source/NVDAObjects/inputComposition.py @@ -80,9 +80,9 @@ def reportNewText(self,oldString,newString): ) def compositionUpdate(self,compositionString,selectionStart,selectionEnd,isReading,announce=True): - if isReading and not config.conf["inputComposition"]["reportReadingStringChanges"]: return - if not isReading and not config.conf["inputComposition"]["reportCompositionStringChanges"]: return - if announce: self.reportNewText((self.readingString if isReading else self.compositionString),compositionString) + if isReading and not config.conf["inputComposition"]["reportReadingStringChanges"]: return # noqa: E701 + if not isReading and not config.conf["inputComposition"]["reportCompositionStringChanges"]: return # noqa: E701 + if announce: self.reportNewText((self.readingString if isReading else self.compositionString),compositionString) # noqa: E701 hasChanged=False if isReading: self.readingString=compositionString diff --git a/source/NVDAObjects/window/__init__.py b/source/NVDAObjects/window/__init__.py index 982ae9300ad..29f26bbbdb2 100644 --- a/source/NVDAObjects/window/__init__.py +++ b/source/NVDAObjects/window/__init__.py @@ -8,12 +8,12 @@ import ctypes.wintypes import winKernel import winUser -from logHandler import log +from logHandler import log # noqa: F401 import controlTypes -import api -import config +import api # noqa: F401 +import config # noqa: F401 import displayModel -import eventHandler +import eventHandler # noqa: F401 from NVDAObjects import NVDAObject from NVDAObjects.behaviors import EditableText, EditableTextWithoutAutoSelectDetection, LiveText import watchdog @@ -148,11 +148,11 @@ def kwargsFromSuper(cls,kwargs,relation=None): windowHandle=None if relation in ('focus','foreground'): windowHandle=winUser.getForegroundWindow() - if not windowHandle: windowHandle=winUser.getDesktopWindow() + if not windowHandle: windowHandle=winUser.getDesktopWindow() # noqa: E701 if windowHandle and relation=="focus": threadID=winUser.getWindowThreadProcessID(windowHandle)[1] threadInfo=winUser.getGUIThreadInfo(threadID) - if threadInfo.hwndFocus: windowHandle=threadInfo.hwndFocus + if threadInfo.hwndFocus: windowHandle=threadInfo.hwndFocus # noqa: E701 elif isinstance(relation,tuple): windowHandle=_windowFromPoint(ctypes.wintypes.POINT(relation[0],relation[1])) if not windowHandle: diff --git a/source/NVDAObjects/window/_msOfficeChart.py b/source/NVDAObjects/window/_msOfficeChart.py index 2d65fa01e2f..be5afe38e70 100644 --- a/source/NVDAObjects/window/_msOfficeChart.py +++ b/source/NVDAObjects/window/_msOfficeChart.py @@ -494,10 +494,10 @@ def navigateToElement(self, direction): if len(self.elementList) == 0: ui.message(self.name) else: - if self.activeElement == None: self.activeElement = self.elementList[0] + if self.activeElement == None: self.activeElement = self.elementList[0] # noqa: E701, E711 else: - if direction=="previous": self.activeElement = self.activeElement.previous - elif direction=="next": self.activeElement = self.activeElement.next + if direction=="previous": self.activeElement = self.activeElement.previous # noqa: E701 + elif direction=="next": self.activeElement = self.activeElement.next # noqa: E701 self.activeElement.select() eventHandler.queueEvent("gainFocus", self.activeElement) @@ -527,7 +527,7 @@ def __init__(self,windowHandle, officeApplicationObject, officeChartObject, init self.officeApplicationObject=officeApplicationObject try: seriesCount=self.officeChartObject.SeriesCollection().Count - except: + except: # noqa: E722 seriesCount=None if seriesCount: for i in range(seriesCount): @@ -536,7 +536,7 @@ def __init__(self,windowHandle, officeApplicationObject, officeChartObject, init self.addElement( OfficeChartElementCollection(windowHandle=self.windowHandle, officeChartObject = self.officeChartObject ) , self ) try: self.officeChartObject.Select() - except: + except: # noqa: E722 pass def _get_name(self): @@ -664,7 +664,7 @@ def __init__(self,windowHandle, officeChartObject , elementID , arg1 = None , ar 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) + 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 ) return seriesText diff --git a/source/NVDAObjects/window/edit.py b/source/NVDAObjects/window/edit.py index 660b9b5e858..436b097f6d2 100644 --- a/source/NVDAObjects/window/edit.py +++ b/source/NVDAObjects/window/edit.py @@ -259,16 +259,16 @@ def _getFormatFieldAndOffsets(self, offset, formatConfig, calculateOffsets=True) formatField=textInfos.FormatField() charFormat=None if formatConfig["reportFontName"]: - if charFormat is None: charFormat=self._getCharFormat(offset) + if charFormat is None: charFormat=self._getCharFormat(offset) # noqa: E701 formatField["font-name"]=charFormat.szFaceName if formatConfig["reportFontSize"]: - if charFormat is None: charFormat=self._getCharFormat(offset) + if charFormat is None: charFormat=self._getCharFormat(offset) # noqa: E701 # Font size is supposed to be an integral value fontSize = charFormat.yHeight // 20 # Translators: Abbreviation for points, a measurement of font size. formatField["font-size"] = pgettext("font size", "%s pt") % fontSize if formatConfig["reportFontAttributes"]: - if charFormat is None: charFormat=self._getCharFormat(offset) + if charFormat is None: charFormat=self._getCharFormat(offset) # noqa: E701 formatField["bold"]=bool(charFormat.dwEffects&CFE_BOLD) formatField["italic"]=bool(charFormat.dwEffects&CFE_ITALIC) formatField["underline"]=bool(charFormat.dwEffects&CFE_UNDERLINE) @@ -283,12 +283,12 @@ def _getFormatFieldAndOffsets(self, offset, formatConfig, calculateOffsets=True) else: formatField["text-position"] = TextPosition.BASELINE if formatConfig["reportColor"]: - if charFormat is None: charFormat=self._getCharFormat(offset) + if charFormat is None: charFormat=self._getCharFormat(offset) # noqa: E701 self._setFormatFieldColor(charFormat, formatField) if formatConfig["reportLineNumber"]: formatField["line-number"]=self._getLineNumFromOffset(offset)+1 if formatConfig["reportLinks"]: - if charFormat is None: charFormat=self._getCharFormat(offset) + if charFormat is None: charFormat=self._getCharFormat(offset) # noqa: E701 formatField["link"]=bool(charFormat.dwEffects&CFM_LINK) return formatField,(startOffset,endOffset) @@ -330,7 +330,7 @@ def _getSelectionOffsets(self): else: start=ctypes.c_uint() end=ctypes.c_uint() - res=watchdog.cancellableSendMessage(self.obj.windowHandle,winUser.EM_GETSEL,ctypes.byref(start),ctypes.byref(end)) + res=watchdog.cancellableSendMessage(self.obj.windowHandle,winUser.EM_GETSEL,ctypes.byref(start),ctypes.byref(end)) # noqa: F841 return start.value,end.value def _setSelectionOffsets(self,start,end): @@ -573,7 +573,7 @@ def _getFormatFieldAtRange(self, textRange, formatConfig): # noqa: C901 langId = fontObj.languageID if langId: formatField['language']=languageHandler.windowsLCIDToLocaleName(langId) - except: + except: # noqa: E722 log.debugWarning("language error",exc_info=True) pass return formatField @@ -666,7 +666,7 @@ def _getEmbeddedObjectLabel(self,embedRangeObj): dataObj=None if dataObj: text=comtypes.BSTR() - res=NVDAHelper.localLib.getOleClipboardText(dataObj,ctypes.byref(text)) + res=NVDAHelper.localLib.getOleClipboardText(dataObj,ctypes.byref(text)) # noqa: F841 label=text.value if label: return label @@ -693,7 +693,7 @@ def _getTextAtRange(self,rangeObj): start=rangeObj.start for offset in range(len(bufText)): if ord(bufText[offset]) == ord(textUtils.OBJ_REPLACEMENT_CHAR): - if embedRangeObj is None: embedRangeObj=rangeObj.duplicate + if embedRangeObj is None: embedRangeObj=rangeObj.duplicate # noqa: E701 embedRangeObj.setRange(start+offset,start+offset+1) label=self._getEmbeddedObjectLabel(embedRangeObj) if label: @@ -880,7 +880,7 @@ def _get_ITextDocumentObject(self): ptr=ctypes.POINTER(comInterfaces.tom.ITextDocument)() ctypes.windll.oleacc.AccessibleObjectFromWindow(self.windowHandle,-16,ctypes.byref(ptr._iid_),ctypes.byref(ptr)) self._ITextDocumentObject=ptr - except: + except: # noqa: E722 log.error("Error getting ITextDocument",exc_info=True) self._ITextDocumentObject=None return self._ITextDocumentObject @@ -889,7 +889,7 @@ def _get_ITextSelectionObject(self): if not hasattr(self,'_ITextSelectionObject'): try: self._ITextSelectionObject=self.ITextDocumentObject.selection - except: + except: # noqa: E722 self._ITextSelectionObject=None return self._ITextSelectionObject diff --git a/source/NVDAObjects/window/excel.py b/source/NVDAObjects/window/excel.py index 558ae3481a8..71e2bc2bb71 100755 --- a/source/NVDAObjects/window/excel.py +++ b/source/NVDAObjects/window/excel.py @@ -283,7 +283,7 @@ def __getattr__(attrName: str) -> Any: xlPatternRectangularGradient:_("rectangular gradient"), } -from .excelCellBorder import getCellBorderStyleDescription +from .excelCellBorder import getCellBorderStyleDescription # noqa: E402 re_RC=re.compile(r'R(?:\[(\d+)\])?C(?:\[(\d+)\])?') re_absRC=re.compile(r'^R(\d+)C(\d+)(?::R(\d+)C(\d+))?$') @@ -1865,7 +1865,7 @@ def _get_selection(self): def script_selectionChange(self,gesture): gesture.send() newFocus=self.selection or self - if eventHandler.lastQueuedFocusObject is newFocus: return + if eventHandler.lastQueuedFocusObject is newFocus: return # noqa: E701 eventHandler.queueEvent("gainFocus",newFocus) @script(gestures=("kb:escape", "kb:enter", "kb:space"), canPropagate=True) @@ -1926,7 +1926,7 @@ def _get_role(self): formControlType=self.excelFormControlObject.FormControlType else: formControlType=None - except: + except: # noqa: E722 return None return self._roleMap[formControlType] @@ -2022,7 +2022,7 @@ def __init__( self , nodeType , document , formControlObject , formControlCollec _label=None @property def label(self): - if self._label: return self._label + if self._label: return self._label # noqa: E701 alternativeText=self.excelItemObject.AlternativeText if alternativeText: self._label=alternativeText+" "+self.excelItemObject.Name+" " + self.excelItemObject.TopLeftCell.address(False,False,1,False) + "-" + self.excelItemObject.BottomRightCell.address(False,False,1,False) @@ -2033,7 +2033,7 @@ def label(self): _nvdaObj=None @property def nvdaObj(self): - if self._nvdaObj: return self._nvdaObj + if self._nvdaObj: return self._nvdaObj # noqa: E701 formControlType=self.excelItemObject.formControlType if formControlType ==xlListBox: self._nvdaObj=ExcelFormControlListBox(windowHandle=self.treeInterceptorObj.rootNVDAObject.windowHandle,parent=self.treeInterceptorObj.rootNVDAObject,excelFormControlObject=self.excelItemObject) @@ -2133,21 +2133,21 @@ def __init__(self,windowHandle=None,parent=None,excelFormControlObject=None): super(ExcelFormControlListBox,self).__init__(windowHandle=windowHandle, parent=parent, excelFormControlObject=excelFormControlObject) try: self.listSize=int(self.excelControlFormatObject.ListCount) - except: + except: # noqa: E722 self.listSize=0 try: self.selectedItemIndex= int(self.excelControlFormatObject.ListIndex) - except: + except: # noqa: E722 self.selectedItemIndex=0 try: self.isMultiSelectable= self.excelControlFormatObject.multiSelect!=xlNone - except: + except: # noqa: E722 self.isMultiSelectable=False def getChildAtIndex(self,index): name=str(self.excelOLEFormatObject.List(index+1)) states=set([controlTypes.State.SELECTABLE]) - if self.excelOLEFormatObject.Selected[index+1]==True: + if self.excelOLEFormatObject.Selected[index+1]==True: # noqa: E712 states.add(controlTypes.State.SELECTED) return ExcelDropdownItem(parent=self,name=name,states=states,index=index) @@ -2169,7 +2169,7 @@ def script_moveUp(self, gesture): if not self.isMultiSelectable: try: self.excelOLEFormatObject.Selected[self.selectedItemIndex] = True - except: + except: # noqa: E722 pass child=self.getChildAtIndex(self.selectedItemIndex-1) if child: @@ -2182,7 +2182,7 @@ def script_moveDown(self, gesture): if not self.isMultiSelectable: try: self.excelOLEFormatObject.Selected[self.selectedItemIndex] = True - except: + except: # noqa: E722 pass child=self.getChildAtIndex(self.selectedItemIndex-1) if child: @@ -2193,7 +2193,7 @@ def doAction(self): try: lb=self.excelOLEFormatObject lb.Selected[self.selectedItemIndex] =not lb.Selected[self.selectedItemIndex] - except: + except: # noqa: E722 return child=self.getChildAtIndex(self.selectedItemIndex-1) eventHandler.queueEvent("gainFocus",child) @@ -2204,11 +2204,11 @@ def __init__(self,windowHandle=None,parent=None,excelFormControlObject=None): super(ExcelFormControlDropDown,self).__init__(windowHandle=windowHandle, parent=parent, excelFormControlObject=excelFormControlObject) try: self.listSize=self.excelControlFormatObject.ListCount - except: + except: # noqa: E722 self.listSize=0 try: self.selectedItemIndex=self.excelControlFormatObject.ListIndex - except: + except: # noqa: E722 self.selectedItemIndex=0 @script(gesture="kb:upArrow", canPropagate=True) @@ -2235,19 +2235,19 @@ def __init__(self,windowHandle=None,parent=None,excelFormControlObject=None): super(ExcelFormControlScrollBar,self).__init__(windowHandle=windowHandle, parent=parent, excelFormControlObject=excelFormControlObject) try: self.minValue=self.excelControlFormatObject.min - except: + except: # noqa: E722 self.minValue=0 try: self.maxValue=self.excelControlFormatObject.max - except: + except: # noqa: E722 self.maxValue=0 try: self.smallChange=self.excelControlFormatObject.smallChange - except: + except: # noqa: E722 self.smallChange=0 try: self.largeChange=self.excelControlFormatObject.largeChange - except: + except: # noqa: E722 self.largeChange=0 def _get_value(self): diff --git a/source/NVDAObjects/window/scintilla.py b/source/NVDAObjects/window/scintilla.py index b618a57f553..a6a4ad98857 100755 --- a/source/NVDAObjects/window/scintilla.py +++ b/source/NVDAObjects/window/scintilla.py @@ -232,7 +232,7 @@ def _getParagraphOffsets(self,offset): return self._getLineOffsets(offset) def _getCharacterOffsets(self,offset): - if offset>=self._getStoryLength(): return offset,offset+1 + if offset>=self._getStoryLength(): return offset,offset+1 # noqa: E701 end=watchdog.cancellableSendMessage(self.obj.windowHandle,SCI_POSITIONAFTER,offset,0) start=offset tempOffset=offset-1 diff --git a/source/NVDAObjects/window/winword.py b/source/NVDAObjects/window/winword.py index b7c52c59d79..383925ac3be 100755 --- a/source/NVDAObjects/window/winword.py +++ b/source/NVDAObjects/window/winword.py @@ -785,7 +785,7 @@ def getTextWithFields( # noqa: C901 self, formatConfig: Optional[Dict] = None ) -> textInfos.TextInfo.TextWithFieldsT: - if self.isCollapsed: return [] + if self.isCollapsed: return [] # noqa: E701 if self.obj.ignoreFormatting: return [self.text] extraDetail=formatConfig.get('extraDetail',False) if formatConfig else False @@ -882,7 +882,7 @@ def _normalizeControlField(self,field): if fieldTitle: field['name']=fieldTitle field['alwaysReportName']=True - if role is not None: field['role']=role + if role is not None: field['role']=role # noqa: E701 if role==controlTypes.Role.TABLE and field.get('longdescription'): field['states']=set([controlTypes.State.HASLONGDESC]) storyType=int(field.pop('wdStoryType',0)) @@ -963,12 +963,12 @@ def _normalizeFormatField(self,field,extraDetail=False): languageId = int(field.pop('wdLanguageId',0)) if languageId: field['language']=languageHandler.windowsLCIDToLocaleName(languageId) - except: + except: # noqa: E722 log.debugWarning("language error",exc_info=True) pass for x in ("first-line-indent","left-indent","right-indent","hanging-indent"): v=field.get(x) - if not v: continue + if not v: continue # noqa: E701 v=float(v) if abs(v)<0.001: v=None @@ -1146,14 +1146,14 @@ def updateSelection(self): def getMathMl(self, field): try: import mathType - except: + except: # noqa: E722 raise LookupError("MathType not installed") rangeObj = self._rangeObj.Duplicate rangeObj.Start = int(field["shapeoffset"]) obj = rangeObj.InlineShapes[0].OLEFormat try: return mathType.getMathMl(obj) - except: + except: # noqa: E722 log.debugWarning("Error fetching math with mathType", exc_info=True) raise LookupError("Couldn't get MathML from MathType") @@ -1327,7 +1327,7 @@ def _get_WinwordWindowObject(self): def _get_WinwordDocumentObject(self): if not getattr(self,'_WinwordDocumentObject',None): windowObject=self.WinwordWindowObject - if not windowObject: return None + if not windowObject: return None # noqa: E701 self._WinwordDocumentObject=windowObject.document return self._WinwordDocumentObject @@ -1339,7 +1339,7 @@ def _get_WinwordApplicationObject(self): def _get_WinwordSelectionObject(self): if not getattr(self,'_WinwordSelectionObject',None): windowObject=self.WinwordWindowObject - if not windowObject: return None + if not windowObject: return None # noqa: E701 self._WinwordSelectionObject=windowObject.selection return self._WinwordSelectionObject @@ -1679,7 +1679,7 @@ def _get_documentWindowHandle(self): def _get_WinwordWindowObject(self): window=super(WordDocument_WwN,self).WinwordWindowObject - if not window: return None + if not window: return None # noqa: E701 try: return window.application.activeWindow.activePane except COMError: diff --git a/source/UIAHandler/__init__.py b/source/UIAHandler/__init__.py index 21a11dbeb3d..d1e9fa2d102 100644 --- a/source/UIAHandler/__init__.py +++ b/source/UIAHandler/__init__.py @@ -10,8 +10,8 @@ oledll, windll, POINTER, - CFUNCTYPE, - c_voidp, + CFUNCTYPE, # noqa: F401 + c_voidp, # noqa: F401 ) import comtypes.client @@ -145,45 +145,45 @@ } UIAControlTypesToNVDARoles={ - UIA_ButtonControlTypeId:controlTypes.Role.BUTTON, - UIA_CalendarControlTypeId:controlTypes.Role.CALENDAR, - UIA_CheckBoxControlTypeId:controlTypes.Role.CHECKBOX, - UIA_ComboBoxControlTypeId:controlTypes.Role.COMBOBOX, - UIA_EditControlTypeId:controlTypes.Role.EDITABLETEXT, - UIA_HyperlinkControlTypeId:controlTypes.Role.LINK, - UIA_ImageControlTypeId:controlTypes.Role.GRAPHIC, - UIA_ListItemControlTypeId:controlTypes.Role.LISTITEM, - UIA_ListControlTypeId:controlTypes.Role.LIST, - UIA_MenuControlTypeId:controlTypes.Role.POPUPMENU, - UIA_MenuBarControlTypeId:controlTypes.Role.MENUBAR, - UIA_MenuItemControlTypeId:controlTypes.Role.MENUITEM, - UIA_ProgressBarControlTypeId:controlTypes.Role.PROGRESSBAR, - UIA_RadioButtonControlTypeId:controlTypes.Role.RADIOBUTTON, - UIA_ScrollBarControlTypeId:controlTypes.Role.SCROLLBAR, - UIA_SliderControlTypeId:controlTypes.Role.SLIDER, - UIA_SpinnerControlTypeId:controlTypes.Role.SPINBUTTON, - UIA_StatusBarControlTypeId:controlTypes.Role.STATUSBAR, - UIA_TabControlTypeId:controlTypes.Role.TABCONTROL, - UIA_TabItemControlTypeId:controlTypes.Role.TAB, - UIA_TextControlTypeId:controlTypes.Role.STATICTEXT, - UIA_ToolBarControlTypeId:controlTypes.Role.TOOLBAR, - UIA_ToolTipControlTypeId:controlTypes.Role.TOOLTIP, - UIA_TreeControlTypeId:controlTypes.Role.TREEVIEW, - UIA_TreeItemControlTypeId:controlTypes.Role.TREEVIEWITEM, - UIA_CustomControlTypeId:controlTypes.Role.UNKNOWN, - UIA_GroupControlTypeId:controlTypes.Role.GROUPING, - UIA_ThumbControlTypeId:controlTypes.Role.THUMB, - UIA_DataGridControlTypeId:controlTypes.Role.DATAGRID, - UIA_DataItemControlTypeId:controlTypes.Role.DATAITEM, - UIA_DocumentControlTypeId:controlTypes.Role.DOCUMENT, - UIA_SplitButtonControlTypeId:controlTypes.Role.SPLITBUTTON, - UIA_WindowControlTypeId:controlTypes.Role.WINDOW, - UIA_PaneControlTypeId:controlTypes.Role.PANE, - UIA_HeaderControlTypeId:controlTypes.Role.HEADER, - UIA_HeaderItemControlTypeId:controlTypes.Role.HEADERITEM, - UIA_TableControlTypeId:controlTypes.Role.TABLE, - UIA_TitleBarControlTypeId:controlTypes.Role.TITLEBAR, - UIA_SeparatorControlTypeId:controlTypes.Role.SEPARATOR, + UIA_ButtonControlTypeId:controlTypes.Role.BUTTON, # noqa: F405 + UIA_CalendarControlTypeId:controlTypes.Role.CALENDAR, # noqa: F405 + UIA_CheckBoxControlTypeId:controlTypes.Role.CHECKBOX, # noqa: F405 + UIA_ComboBoxControlTypeId:controlTypes.Role.COMBOBOX, # noqa: F405 + UIA_EditControlTypeId:controlTypes.Role.EDITABLETEXT, # noqa: F405 + UIA_HyperlinkControlTypeId:controlTypes.Role.LINK, # noqa: F405 + UIA_ImageControlTypeId:controlTypes.Role.GRAPHIC, # noqa: F405 + UIA_ListItemControlTypeId:controlTypes.Role.LISTITEM, # noqa: F405 + UIA_ListControlTypeId:controlTypes.Role.LIST, # noqa: F405 + UIA_MenuControlTypeId:controlTypes.Role.POPUPMENU, # noqa: F405 + UIA_MenuBarControlTypeId:controlTypes.Role.MENUBAR, # noqa: F405 + UIA_MenuItemControlTypeId:controlTypes.Role.MENUITEM, # noqa: F405 + UIA_ProgressBarControlTypeId:controlTypes.Role.PROGRESSBAR, # noqa: F405 + UIA_RadioButtonControlTypeId:controlTypes.Role.RADIOBUTTON, # noqa: F405 + UIA_ScrollBarControlTypeId:controlTypes.Role.SCROLLBAR, # noqa: F405 + UIA_SliderControlTypeId:controlTypes.Role.SLIDER, # noqa: F405 + UIA_SpinnerControlTypeId:controlTypes.Role.SPINBUTTON, # noqa: F405 + UIA_StatusBarControlTypeId:controlTypes.Role.STATUSBAR, # noqa: F405 + UIA_TabControlTypeId:controlTypes.Role.TABCONTROL, # noqa: F405 + UIA_TabItemControlTypeId:controlTypes.Role.TAB, # noqa: F405 + UIA_TextControlTypeId:controlTypes.Role.STATICTEXT, # noqa: F405 + UIA_ToolBarControlTypeId:controlTypes.Role.TOOLBAR, # noqa: F405 + UIA_ToolTipControlTypeId:controlTypes.Role.TOOLTIP, # noqa: F405 + UIA_TreeControlTypeId:controlTypes.Role.TREEVIEW, # noqa: F405 + UIA_TreeItemControlTypeId:controlTypes.Role.TREEVIEWITEM, # noqa: F405 + UIA_CustomControlTypeId:controlTypes.Role.UNKNOWN, # noqa: F405 + UIA_GroupControlTypeId:controlTypes.Role.GROUPING, # noqa: F405 + UIA_ThumbControlTypeId:controlTypes.Role.THUMB, # noqa: F405 + UIA_DataGridControlTypeId:controlTypes.Role.DATAGRID, # noqa: F405 + UIA_DataItemControlTypeId:controlTypes.Role.DATAITEM, # noqa: F405 + UIA_DocumentControlTypeId:controlTypes.Role.DOCUMENT, # noqa: F405 + UIA_SplitButtonControlTypeId:controlTypes.Role.SPLITBUTTON, # noqa: F405 + UIA_WindowControlTypeId:controlTypes.Role.WINDOW, # noqa: F405 + UIA_PaneControlTypeId:controlTypes.Role.PANE, # noqa: F405 + UIA_HeaderControlTypeId:controlTypes.Role.HEADER, # noqa: F405 + UIA_HeaderItemControlTypeId:controlTypes.Role.HEADERITEM, # noqa: F405 + UIA_TableControlTypeId:controlTypes.Role.TABLE, # noqa: F405 + UIA_TitleBarControlTypeId:controlTypes.Role.TITLEBAR, # noqa: F405 + UIA_SeparatorControlTypeId:controlTypes.Role.SEPARATOR, # noqa: F405 } UIALiveSettingtoNVDAAriaLivePoliteness: Dict[str, aria.AriaLivePoliteness] = { @@ -257,7 +257,7 @@ globalEventHandlerGroupUIAEventIds = set(UIAEventIdsToNVDAEventNames) - localEventHandlerGroupUIAEventIds ignoreWinEventsMap = { - UIA_AutomationPropertyChangedEventId: list(UIAPropertyIdsToNVDAEventNames.keys()), + UIA_AutomationPropertyChangedEventId: list(UIAPropertyIdsToNVDAEventNames.keys()), # noqa: F405 } for id in UIAEventIdsToNVDAEventNames.keys(): ignoreWinEventsMap[id] = [0] @@ -511,15 +511,15 @@ def MTAThreadFunc(self): self.clientObject.CoalesceEvents = UIA.CoalesceEventsOptions_Enabled self.clientObject.ConnectionRecoveryBehavior = UIA.ConnectionRecoveryBehaviorOptions_Enabled log.info(f"UIAutomation: {self.clientObject.__class__.__mro__[1].__name__}") - self.windowTreeWalker=self.clientObject.createTreeWalker(self.clientObject.CreateNotCondition(self.clientObject.CreatePropertyCondition(UIA_NativeWindowHandlePropertyId,0))) + self.windowTreeWalker=self.clientObject.createTreeWalker(self.clientObject.CreateNotCondition(self.clientObject.CreatePropertyCondition(UIA_NativeWindowHandlePropertyId,0))) # noqa: F405 self.windowCacheRequest=self.clientObject.CreateCacheRequest() - self.windowCacheRequest.AddProperty(UIA_NativeWindowHandlePropertyId) + self.windowCacheRequest.AddProperty(UIA_NativeWindowHandlePropertyId) # noqa: F405 self.UIAWindowHandleCache={} self.baseTreeWalker=self.clientObject.RawViewWalker self.baseCacheRequest=self.windowCacheRequest.Clone() for propertyId in baseCachePropertyIDs: self.baseCacheRequest.addProperty(propertyId) - self.baseCacheRequest.addPattern(UIA_TextPatternId) + self.baseCacheRequest.addPattern(UIA_TextPatternId) # noqa: F405 self.rootElement=self.clientObject.getRootElementBuildCache(self.baseCacheRequest) self.reservedNotSupportedValue=self.clientObject.ReservedNotSupportedValue self.ReservedMixedAttributeValue=self.clientObject.ReservedMixedAttributeValue @@ -731,7 +731,7 @@ def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if _isDebug(): log.debug("HandleAutomationEvent: event received while not fully initialized") return - if eventID==UIA_MenuOpenedEventId and eventHandler.isPendingEvents("gainFocus"): + if eventID==UIA_MenuOpenedEventId and eventHandler.isPendingEvents("gainFocus"): # noqa: F405 # We don't need the menuOpened event if focus has been fired, # as focus should be more correct. if _isDebug(): diff --git a/source/addonHandler/__init__.py b/source/addonHandler/__init__.py index c5edf9568c4..443ade71625 100644 --- a/source/addonHandler/__init__.py +++ b/source/addonHandler/__init__.py @@ -395,7 +395,7 @@ def _getAvailableAddonsFromPath( log.debugWarning("Add-on %s is considered incompatible", name) state[AddonStateCategory.BLOCKED].add(a.name) yield a - except: + except: # noqa: E722 log.error("Error loading Addon from path: %s", addon_path, exc_info=True) _availableAddons = collections.OrderedDict() @@ -568,7 +568,7 @@ def completeRemove(self, runUninstallTask: bool = True) -> None: # translations can be used in installTasks module. _availableAddons[self.path] = self self.runInstallTask("onUninstall") - except: + except: # noqa: E722 log.error("task 'onUninstall' on addon '%s' failed"%self.name,exc_info=True) finally: del _availableAddons[self.path] @@ -1027,9 +1027,9 @@ def __init__(self, input, translatedInput=None): self._errors = None val = Validator({"apiVersion":validate_apiVersionString}) result = self.validate(val, copy=True, preserve_errors=True) - if result != True: + if result != True: # noqa: E712 self._errors = result - elif True != self._validateApiVersionRange(): + elif True != self._validateApiVersionRange(): # noqa: E712 self._errors = "Constraint not met: minimumNVDAVersion ({}) <= lastTestedNVDAVersion ({})".format( self.get("minimumNVDAVersion"), self.get("lastTestedNVDAVersion") diff --git a/source/api.py b/source/api.py index 9ffb3116e2a..85a8ab9a802 100644 --- a/source/api.py +++ b/source/api.py @@ -118,7 +118,7 @@ def setFocusObject(obj: NVDAObjects.NVDAObject) -> bool: # noqa: C901 f" window class {tempObj.windowClassName if isinstance(tempObj, Window) else type(tempObj)}, " f"application name {tempObj.appModule.appName}" ) - except: + except: # noqa: E722 pass tempObj=getDesktopObject() # Scan backwards through the old ancestors looking for a match. @@ -161,7 +161,7 @@ def setFocusObject(obj: NVDAObjects.NVDAObject) -> bool: # noqa: C901 for o in ancestors[focusDifferenceLevel:]+[obj]: try: treeInterceptorObject=treeInterceptorHandler.update(o) - except: + except: # noqa: E722 log.error("Error updating tree interceptor", exc_info=True) #Always make sure that the focus object's treeInterceptor is forced to either the found treeInterceptor (if its in it) or to None #This is to make sure that the treeInterceptor does not have to be looked up, which can cause problems for winInputHook @@ -271,7 +271,7 @@ def setReviewPosition( globalVars.reviewPosition=reviewPosition.copy() globalVars.reviewPositionObj=reviewPosition.obj - if clearNavigatorObject: globalVars.navigatorObject=None + if clearNavigatorObject: globalVars.navigatorObject=None # noqa: E701 # When the review cursor follows the caret and braille is auto tethered to review, # we should not update braille with the new review position as a tether to focus is due. if not (braille.handler.shouldAutoTether and isCaret): diff --git a/source/appModuleHandler.py b/source/appModuleHandler.py index ae04d83347a..8b1f6288cf0 100644 --- a/source/appModuleHandler.py +++ b/source/appModuleHandler.py @@ -255,7 +255,7 @@ def cleanup(): eventHandler.handleAppTerminate(deadMod) try: deadMod.terminate() - except: + except: # noqa: E722 log.exception("Error terminating app module %r" % deadMod) @@ -346,7 +346,7 @@ def terminate(): for processID, app in runningTable.items(): try: app.terminate() - except: + except: # noqa: E722 log.exception("Error terminating app module %r" % app) runningTable.clear() @@ -813,6 +813,6 @@ def getWmiProcessInfo(processId): "where ProcessId = %d" % processId) for result in results: return result - except: + except: # noqa: E722 raise LookupError("Couldn't get process information using WMI") raise LookupError("No such process") diff --git a/source/appModules/eclipse.py b/source/appModules/eclipse.py index 2af1fee2f10..7ed083bd266 100644 --- a/source/appModules/eclipse.py +++ b/source/appModules/eclipse.py @@ -39,7 +39,7 @@ def event_caret(self): try: if self.appModule.selectedItem and not self.appModule.selectedItem.name: self.event_suggestionsClosed() - except: + except: # noqa: E722 pass @script( @@ -194,5 +194,5 @@ def chooseNVDAObjectOverlayClasses(self, obj, clsList): ) ): clsList.insert(0, AutocompletionListItem) - except: + except: # noqa: E722 pass diff --git a/source/appModules/javaw.py b/source/appModules/javaw.py index 93fa8b986cb..2ab09008873 100644 --- a/source/appModules/javaw.py +++ b/source/appModules/javaw.py @@ -48,5 +48,5 @@ def getAppNameFromHost(processId): raise LookupError try: return "javaw_" + _getEntryPoint(cmd).replace(".", "_") - except: + except: # noqa: E722 raise LookupError diff --git a/source/appModules/kindle.py b/source/appModules/kindle.py index 58418542558..751b5f92e1a 100644 --- a/source/appModules/kindle.py +++ b/source/appModules/kindle.py @@ -168,7 +168,7 @@ def _iterEmbeddedObjs(self, hypertext, startIndex, direction): yield obj try: objHt = obj.iaHypertext - except: + except: # noqa: E722 # This is a graphic, etc. which doesn't support text. continue log.debug("Object has hypertext. Recursing") diff --git a/source/appModules/logonui.py b/source/appModules/logonui.py index c0ff9800bb0..0e03450ea5b 100644 --- a/source/appModules/logonui.py +++ b/source/appModules/logonui.py @@ -59,7 +59,7 @@ def _get_name(self): try: self.parent.invalidateCache() return self.parent.name - except: + except: # noqa: E722 return super(XPPasswordField, self).name def script_changeUser(self, gesture): diff --git a/source/appModules/miranda32.py b/source/appModules/miranda32.py index f4145a98842..00f669bf117 100644 --- a/source/appModules/miranda32.py +++ b/source/appModules/miranda32.py @@ -6,8 +6,8 @@ import ui import config -from ctypes import * -from ctypes.wintypes import * +from ctypes import * # noqa: F403 +from ctypes.wintypes import * # noqa: F403 import winKernel from NVDAObjects.IAccessible import IAccessible, ContentGenericClient from NVDAObjects.behaviors import Dialog @@ -133,12 +133,12 @@ def _get_name(self): internalBuf=winKernel.virtualAllocEx(self.processHandle,None,MAXITEMTEXTLEN,winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) try: watchdog.cancellableSendMessage(self.windowHandle,CLM_GETITEMTEXT,hItem,internalBuf) - buf=create_unicode_buffer(MAXITEMTEXTLEN) + buf=create_unicode_buffer(MAXITEMTEXTLEN) # noqa: F405 winKernel.readProcessMemory(self.processHandle,internalBuf,buf,MAXITEMTEXTLEN,None) text=buf.value statusMsgPtr=watchdog.cancellableSendMessage(self.windowHandle,CLM_GETSTATUSMSG,hItem,0) if statusMsgPtr>0: - buf2=create_unicode_buffer(MAXSTATUSMSGLEN) + buf2=create_unicode_buffer(MAXSTATUSMSGLEN) # noqa: F405 winKernel.readProcessMemory(self.processHandle,statusMsgPtr,buf2,MAXSTATUSMSGLEN,None) text="%s %s"%(text,buf2.value) finally: diff --git a/source/appModules/msimn.py b/source/appModules/msimn.py index 5a8812ca92a..2c286612407 100644 --- a/source/appModules/msimn.py +++ b/source/appModules/msimn.py @@ -57,7 +57,7 @@ class AppModule(appModuleHandler.AppModule): def event_NVDAObject_init(self,obj): - if not isinstance(obj,Window): return + if not isinstance(obj,Window): return # noqa: E701 controlID=obj.windowControlID windowHandle=obj.windowHandle parentWindow=winUser.getAncestor(windowHandle,winUser.GA_PARENT) @@ -110,7 +110,7 @@ def _get_isUnread(self): fields=info.getTextWithFields() try: isUnread=fields[0].field['bold'] - except: + except: # noqa: E722 isUnread=False return isUnread diff --git a/source/appModules/nlnotes.py b/source/appModules/nlnotes.py index abb70e18d74..b40167be630 100644 --- a/source/appModules/nlnotes.py +++ b/source/appModules/nlnotes.py @@ -44,7 +44,7 @@ class AppModule(appModuleHandler.AppModule): def chooseNVDAObjectOverlayClasses(self,obj,clsList): windowClassName=obj.windowClassName role=obj.role - states=obj.states + states=obj.states # noqa: F841 if windowClassName=="NotesSubprog" and role==controlTypes.Role.DOCUMENT: clsList.insert(0,NotesSubprog) elif windowClassName=="NotesRichText" and role in (controlTypes.Role.DOCUMENT,controlTypes.Role.EDITABLETEXT): diff --git a/source/appModules/outlook.py b/source/appModules/outlook.py index d470b60f560..845f19ebc5e 100644 --- a/source/appModules/outlook.py +++ b/source/appModules/outlook.py @@ -216,7 +216,7 @@ def chooseNVDAObjectOverlayClasses(self, obj, clsList): clsList.remove(Dialog) if WordDocument in clsList: clsList.insert(0,OutlookWordDocument) - states=obj.states + states=obj.states # noqa: F841 controlID=obj.windowControlID # Support the date picker in Outlook Meeting / Appointment creation forms if controlID==4352 and role==controlTypes.Role.BUTTON: @@ -455,7 +455,7 @@ def _get_name(self): except COMError: unread=False # Translators: when an email is unread - if unread: textList.append(_("unread")) + if unread: textList.append(_("unread")) # noqa: E701 try: mapiObject=selection.mapiObject except COMError: @@ -478,13 +478,13 @@ def _get_name(self): except COMError: attachmentCount=0 # Translators: when an email has attachments - if attachmentCount>0: textList.append(_("has attachment")) + if attachmentCount>0: textList.append(_("has attachment")) # noqa: E701 try: importance=selection.importance except COMError: importance=1 importanceLabel=importanceLabels.get(importance) - if importanceLabel: textList.append(importanceLabel) + if importanceLabel: textList.append(importanceLabel) # noqa: E701 try: messageClass=selection.messageClass except COMError: @@ -513,14 +513,14 @@ def _get_name(self): # Stops us from reporting "unflagged" which is too verbose. if selection and UIAClassName=="FlagField": try: - if not selection.flagIcon and not selection.flagStatus: continue + if not selection.flagIcon and not selection.flagStatus: continue # noqa: E701 except COMError: continue # the category field should only be reported if the objectModel's categories property actually contains a valid string. # Stops us from reporting "no categories" which is too verbose. elif selection and UIAClassName=="CategoryField": try: - if not selection.categories: continue + if not selection.categories: continue # noqa: E701 except COMError: continue # And we don't care about anything else that is not a text element. @@ -557,7 +557,7 @@ def _get_name(self): def _get_positionInfo(self): info=super(UIAGridRow,self).positionInfo - if info is None: info={} + if info is None: info={} # noqa: E701 UIAClassName=self.UIAElement.cachedClassName if UIAClassName=="ThreadHeader": info['level']=1 diff --git a/source/appModules/poedit.py b/source/appModules/poedit.py index aba5549c6a3..d6b0fdddee6 100644 --- a/source/appModules/poedit.py +++ b/source/appModules/poedit.py @@ -293,7 +293,7 @@ def _get_name(self) -> str: # These rich edit controls are incorrectly labeled. # Oleacc doesn't return any name, and UIA defaults to RichEdit Control. # The label object is positioned just above the field on the screen. - l, t, w, h = self.location + l, t, w, h = self.location # noqa: E741 try: self.name = NVDAObjects.NVDAObject.objectFromPoint(l + 10, t - 10).name except AttributeError: diff --git a/source/appModules/powerpnt.py b/source/appModules/powerpnt.py index 78f8e8d0007..e0008af9f0e 100644 --- a/source/appModules/powerpnt.py +++ b/source/appModules/powerpnt.py @@ -313,7 +313,7 @@ def _get_name(self): return label def _get_currentSlide(self): - if self.ppActivePaneViewType in (ppViewSlideSorter,ppViewThumbnails,ppViewMasterThumbnails): return None + if self.ppActivePaneViewType in (ppViewSlideSorter,ppViewThumbnails,ppViewMasterThumbnails): return None # noqa: E701 return super(DocumentWindow,self).currentSlide def _get_ppSelection(self): @@ -530,8 +530,8 @@ def __init__(self, **kwargs): self.role = controlTypes.Role.MATH def _get__overlapInfo(self): - slideWidth=self.appModule._ppApplication.activePresentation.pageSetup.slideWidth - slideHeight=self.appModule._ppApplication.activePresentation.pageSetup.slideHeight + slideWidth=self.appModule._ppApplication.activePresentation.pageSetup.slideWidth # noqa: F841 + slideHeight=self.appModule._ppApplication.activePresentation.pageSetup.slideHeight # noqa: F841 left=self.ppObject.left top=self.ppObject.top right=left+self.ppObject.width @@ -886,14 +886,14 @@ def _get_states(self): def _get_mathMl(self): try: import mathType - except: + except: # noqa: E722 raise LookupError("MathType not installed") obj = self.ppObject.OLEFormat try: # Don't call RunForConversion, as this seems to make focus bounce. # We don't seem to need it for PowerPoint anyway. return mathType.getMathMl(obj, runForConversion=False) - except: + except: # noqa: E722 raise LookupError("Couldn't get MathML from MathType") __gestures={ @@ -1134,13 +1134,13 @@ def getTextWithFields(self, formatConfig: Optional[Dict] = None) -> textInfos.Te def getMathMl(self, field): try: import mathType - except: + except: # noqa: E722 raise LookupError("MathType not installed") try: # Don't call RunForConversion, as this seems to make focus bounce. # We don't seem to need it for PowerPoint anyway. return mathType.getMathMl(field["oleFormat"], runForConversion=False) - except: + except: # noqa: E722 raise LookupError("Couldn't get MathML from MathType") class SlideShowTreeInterceptor(DocumentTreeInterceptor): @@ -1240,7 +1240,7 @@ def _getShapeText(self,shape,cellShape=False): if text and not text.isspace(): yield text return - if cellShape: return + if cellShape: return # noqa: E701 shapeType=shape.type if shapeType==msoGroup: for childShape in shape.groupItems: @@ -1360,7 +1360,7 @@ def _getPpObjectModelFromWindow(self,windowHandle): try: pDispatch=oleacc.AccessibleObjectFromWindow(windowHandle,winUser.OBJID_NATIVEOM,interface=comtypes.automation.IDispatch) return comtypes.client.dynamic.Dispatch(pDispatch) - except: + except: # noqa: E722 log.debugWarning("Could not get MS Powerpoint object model",exc_info=True) return None @@ -1370,7 +1370,7 @@ def _getPpObjectModelFromROT(self,useRPC=False): if not self._ppApplicationFromROT: try: self._ppApplicationFromROT=comHelper.getActiveObject(u'powerPoint.application',dynamic=True,appModule=self if useRPC else None) - except: + except: # noqa: E722 log.debugWarning("Could not get active object via RPC") return None try: diff --git a/source/appModules/thunderbird.py b/source/appModules/thunderbird.py index 9beb9548bca..ae6fb9d08a3 100755 --- a/source/appModules/thunderbird.py +++ b/source/appModules/thunderbird.py @@ -24,7 +24,7 @@ def event_gainFocus(self, obj, nextHandler): try: # The document loading status is contained in the second field of the status bar. statusText = statusBar.firstChild.next.name - except: + except: # noqa: E722 # Fall back to reading the entire status bar. statusText = api.getStatusBarText(statusBar) speech.speakMessage(controlTypes.State.BUSY.displayString) diff --git a/source/appModules/utorrent.py b/source/appModules/utorrent.py index f4a1ae1dd1a..b84171cc0dc 100644 --- a/source/appModules/utorrent.py +++ b/source/appModules/utorrent.py @@ -48,7 +48,7 @@ def _getColumnContent(self, column): left, top, width, height = self._getColumnLocation(column) return displayModel.DisplayModelTextInfo(self, locationHelper.RectLTRB( left, top, left + width, top + height)).text - except: + except: # noqa: E722 log.debugWarning("Error retrieving name using display model", exc_info=True) return superContent diff --git a/source/appModules/winamp.py b/source/appModules/winamp.py index cde5398e973..d27dd1cbd6e 100644 --- a/source/appModules/winamp.py +++ b/source/appModules/winamp.py @@ -3,8 +3,8 @@ # This file is covered by the GNU General Public License. # See the file COPYING for more details. -from ctypes import * -from ctypes.wintypes import * +from ctypes import * # noqa: F403 +from ctypes.wintypes import * # noqa: F403 import winKernel import winUser from scriptHandler import isScriptWaiting @@ -35,11 +35,11 @@ # in_process ONLY IPC_PE_GETINDEXTITLE=200 # lParam = pointer to fileinfo2 structure -class fileinfo2(Structure): +class fileinfo2(Structure): # noqa: F405 _fields_=[ - ('fileindex',c_int), - ('filetitle',c_char*256), - ('filelength',c_char*16), + ('fileindex',c_int), # noqa: F405 + ('filetitle',c_char*256), # noqa: F405 + ('filelength',c_char*16), # noqa: F405 ] hwndWinamp=0 @@ -107,11 +107,11 @@ def _get_name(self): return None info=fileinfo2() info.fileindex=curIndex - internalInfo=winKernel.virtualAllocEx(self.processHandle,None,sizeof(info),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) + internalInfo=winKernel.virtualAllocEx(self.processHandle,None,sizeof(info),winKernel.MEM_COMMIT,winKernel.PAGE_READWRITE) # noqa: F405 try: - winKernel.writeProcessMemory(self.processHandle,internalInfo,byref(info),sizeof(info),None) + winKernel.writeProcessMemory(self.processHandle,internalInfo,byref(info),sizeof(info),None) # noqa: F405 watchdog.cancellableSendMessage(self.windowHandle,WM_WA_IPC,IPC_PE_GETINDEXTITLE,internalInfo) - winKernel.readProcessMemory(self.processHandle,internalInfo,byref(info),sizeof(info),None) + winKernel.readProcessMemory(self.processHandle,internalInfo,byref(info),sizeof(info),None) # noqa: F405 finally: winKernel.virtualFreeEx(self.processHandle,internalInfo,0,winKernel.MEM_RELEASE) # file title is fetched in the current locale encoding. diff --git a/source/audioDucking.py b/source/audioDucking.py index d8355c77553..c857bc00b4e 100644 --- a/source/audioDucking.py +++ b/source/audioDucking.py @@ -148,7 +148,7 @@ def setAudioDuckingMode(mode): with _duckingRefCountLock: oldMode=_audioDuckingMode _audioDuckingMode=mode - if _modeChangeEvent: windll.kernel32.SetEvent(_modeChangeEvent) + if _modeChangeEvent: windll.kernel32.SetEvent(_modeChangeEvent) # noqa: E701 _modeChangeEvent=AutoEvent() if _isDebug(): log.debug("Switched modes from %s, to %s"%(oldMode,mode)) diff --git a/source/braille.py b/source/braille.py index be49d8dd545..4cd13761606 100644 --- a/source/braille.py +++ b/source/braille.py @@ -428,7 +428,7 @@ def getDisplayList(excludeNegativeChecks=True) -> List[Tuple[str, str]]: displayList.append((display.name, display.description)) else: log.debugWarning(f"Braille display driver {display.name} reports as unavailable, excluding") - except: + except: # noqa: E722 log.error("", exc_info=True) displayList.sort(key=lambda d: strxfrm(d[1])) if lastDisplay: @@ -1133,7 +1133,7 @@ def _getSelection(self): """ try: return self.obj.makeTextInfo(textInfos.POSITION_SELECTION) - except: + except: # noqa: E722 return self.obj.makeTextInfo(textInfos.POSITION_FIRST) def _setCursor(self, info: textInfos.TextInfo): @@ -2421,7 +2421,7 @@ def _writeCells(self, cells: List[int]): if not self.display.isThreadSafe: try: self.display.display(cells) - except: + except: # noqa: E722 log.error("Error displaying cells. Disabling display", exc_info=True) self.handleDisplayUnavailable() return @@ -2832,7 +2832,7 @@ def _bgThreadExecutor(self, param: int): return try: self.display.display(data) - except: + except: # noqa: E722 log.error("Error displaying cells. Disabling display", exc_info=True) self.handleDisplayUnavailable() else: diff --git a/source/brailleDisplayDrivers/alva.py b/source/brailleDisplayDrivers/alva.py index b0b4491c236..dc63e73cd0c 100644 --- a/source/brailleDisplayDrivers/alva.py +++ b/source/brailleDisplayDrivers/alva.py @@ -145,7 +145,7 @@ def _updateSettings(self): timeBytes: bytes = self._dev.getFeature(ALVA_RTC_REPORT)[1:ALVA_RTC_STR_LENGTH+1] try: self._handleTime(timeBytes) - except: + except: # noqa: E722 log.debugWarning("Getting time from ALVA display failed", exc_info=True) keySettings = self._dev.getFeature(ALVA_KEY_SETTINGS_REPORT)[ALVA_KEY_SETTINGS_POS] self._rawKeyboardInput = bool(keySettings & ALVA_KEY_RAW_INPUT_MASK) diff --git a/source/brailleDisplayDrivers/brltty.py b/source/brailleDisplayDrivers/brltty.py index d04c08f1144..e6ef7dcd796 100644 --- a/source/brailleDisplayDrivers/brltty.py +++ b/source/brailleDisplayDrivers/brltty.py @@ -70,13 +70,13 @@ def terminate(self): try: self._keyCheckTimer.Stop() self._keyCheckTimer = None - except: + except: # noqa: E722 pass try: # Give BRLTTY a chance to write the last piece of data to the display. time.sleep(0.05) self._con.leaveTtyMode() - except: + except: # noqa: E722 pass def _get_numCols(self) -> int: @@ -99,7 +99,7 @@ def _handleKeyPresses(self): while True: try: key = self._con.readKey(False) - except: + except: # noqa: E722 log.error("Error reading key press from brlapi", exc_info=True) return if not key: diff --git a/source/brailleDisplayDrivers/ecoBraille.py b/source/brailleDisplayDrivers/ecoBraille.py index ccb27b1f6c7..a29fff991f2 100644 --- a/source/brailleDisplayDrivers/ecoBraille.py +++ b/source/brailleDisplayDrivers/ecoBraille.py @@ -93,7 +93,7 @@ def eco_in_init(dev: serial.Serial) -> int: def eco_in(dev: serial.Serial) -> int: try: msg: bytes = dev.read(9) - except: + except: # noqa: E722 log.debug("unpacking error", exc_info=True) return 0 # Command message from EcoBraille is something like that: @@ -210,7 +210,7 @@ def _get_numCells(self): def display(self, cells: List[int]): try: self._dev.write(eco_out(cells)) - except: + except: # noqa: E722 log.debug("error writing to the display", exc_info=True) def _handleResponses(self): @@ -230,7 +230,7 @@ def _handleResponse(self, command: int): # Routing try: inputCore.manager.executeGesture(InputGestureRouting(((command - ECO_START_ROUTING) >> 24) + 1)) - except: + except: # noqa: E722 log.debug("EcoBraille: No function associated with this routing key {key}".format(key=command)) elif command > 0: # Button diff --git a/source/brailleDisplayDrivers/lilli.py b/source/brailleDisplayDrivers/lilli.py index e94c85a1cd4..12056a6806f 100644 --- a/source/brailleDisplayDrivers/lilli.py +++ b/source/brailleDisplayDrivers/lilli.py @@ -15,7 +15,7 @@ try: lilliDll = windll.LoadLibrary(os.path.join(globalVars.appDir, "brailleDisplayDrivers", "lilli.dll")) -except: +except: # noqa: E722 lilliDll=None lilliCellsMap: List[int] = [] @@ -67,7 +67,7 @@ def terminate(self): try: self._keyCheckTimer.Stop() self._keyCheckTimer = None - except: + except: # noqa: E722 pass lilliDll.Close408USB() @@ -82,7 +82,7 @@ def _handleKeyPresses(self): # The code seems to assume this returns an int. # I haven't confirmed this. key = lilliDll.ReadBuf() - except: + except: # noqa: E722 log.debug("", exc_info=True) pass if not key: diff --git a/source/brailleDisplayDrivers/papenmeier.py b/source/brailleDisplayDrivers/papenmeier.py index 129bbf1e003..e697bf545aa 100644 --- a/source/brailleDisplayDrivers/papenmeier.py +++ b/source/brailleDisplayDrivers/papenmeier.py @@ -19,7 +19,7 @@ try: import ftdi2 -except: +except: # noqa: E722 ftdi2 = None #for bluetooth import hwPortUtils @@ -54,14 +54,14 @@ def brl_auto_id() -> bytes: def _swapDotBits(d: int) -> List[int]: # swap dot bits d2 = 0 - if(d & 1): d2|=128 - if(d & 2): d2|=64 - if(d & 4): d2|=32 - if(d & 8): d2|=16 - if(d & 16): d2|=8 - if(d & 32): d2|=4 - if(d & 64): d2|=2 - if(d & 128): d2|=1 + if(d & 1): d2|=128 # noqa: E701 + if(d & 2): d2|=64 # noqa: E701 + if(d & 4): d2|=32 # noqa: E701 + if(d & 8): d2|=16 # noqa: E701 + if(d & 16): d2|=8 # noqa: E701 + if(d & 32): d2|=4 # noqa: E701 + if(d & 64): d2|=2 # noqa: E701 + if(d & 128): d2|=1 # noqa: E701 a = 0x30|(d2 & 0x0F) b = 0x30|(d2 >> 4) return [b, a] @@ -129,13 +129,13 @@ def connectBluetooth(self): if(self._baud == 0 and self._dev is None): for portInfo in sorted(hwPortUtils.listComPorts(onlyAvailable=True), key=lambda item: "bluetoothName" in item): port = portInfo["port"] - hwID = portInfo["hardwareID"] + hwID = portInfo["hardwareID"] # noqa: F841 if "bluetoothName" in portInfo: if portInfo["bluetoothName"][0:14] == "braillex trio " or portInfo["bluetoothName"][0:13] == "braillex live": try: self._dev = serial.Serial(port, baudrate = 57600,timeout = BLUETOOTH_TIMEOUT, writeTimeout = BLUETOOTH_TIMEOUT) log.info("connectBluetooth success") - except: + except: # noqa: E722 log.debugWarning("connectBluetooth failed") def connectUSB(self, devlist: List[bytes]): @@ -146,7 +146,7 @@ def connectUSB(self, devlist: List[bytes]): self._dev.set_baud_rate(self._baud) self._dev.inWaiting = self._dev.get_queue_status log.info("connectUSB success") - except: + except: # noqa: E722 log.debugWarning("connectUSB failed") def __init__(self): @@ -276,9 +276,9 @@ def __init__(self): else: log.debugWarning('UNKNOWN BRAILLE') - except: + except: # noqa: E722 log.debugWarning('BROKEN PIPE - THIS SHOULD NEVER HAPPEN') - if(self.numCells == 0): raise Exception('no device found') + if(self.numCells == 0): raise Exception('no device found') # noqa: E701 #start keycheck timer self.startTimer() @@ -298,7 +298,7 @@ def stopTimer(self): try: self._keyCheckTimer.Stop() self._bluetoothTimer.Stop() - except: + except: # noqa: E722 pass self._keyCheckTimer = None @@ -321,23 +321,23 @@ def terminate(self): try: super(BrailleDisplayDriver, self).terminate() self.stopTimer() - if(self._dev is not None): self._dev.close() + if(self._dev is not None): self._dev.close() # noqa: E701 self._dev=None - except: + except: # noqa: E722 self._dev=None def display(self, cells: List[int]): """write to braille display""" - if(self._dev is None): return + if(self._dev is None): return # noqa: E701 try: self._dev.write(brl_out(cells, self._nlk, self._nrk, self._voffset)) - except: + except: # noqa: E722 self._dev.close() self._dev=None def executeGesture(self,gesture): """executes a gesture""" - if gesture.id or (gesture.dots or gesture.space): inputCore.manager.executeGesture(gesture) + if gesture.id or (gesture.dots or gesture.space): inputCore.manager.executeGesture(gesture) # noqa: E701 def _handleKeyPresses(self): """handles key presses and performs a gesture""" @@ -347,7 +347,7 @@ def _handleKeyPresses(self): devlist: List[bytes] = ftdi2.list_devices() if(len(devlist)>0): self.connectUSB(devlist) - except: + except: # noqa: E722 return s: bytes = brl_poll(self._dev) if s: @@ -358,8 +358,8 @@ def _handleKeyPresses(self): if(len(self.decodedkeys)): ig = InputGesture(None,self) self.executeGesture(ig) - except: - if(self._dev!=None): self._dev.close() + except: # noqa: E722 + if(self._dev!=None): self._dev.close() # noqa: E701, E711 self._dev=None #global gestures @@ -452,10 +452,10 @@ def brl_decode_trio(keys: bytes)->List[int]: for k in keys: a = k & 0x0F #convert bitstream to list of indexes - if(a & 1): j.append(i+3) - if(a & 2): j.append(i+2) - if(a & 4): j.append(i+1) - if(a & 8): j.append(i) + if(a & 1): j.append(i+3) # noqa: E701 + if(a & 2): j.append(i+2) # noqa: E701 + if(a & 4): j.append(i+1) # noqa: E701 + if(a & 8): j.append(i) # noqa: E701 i +=4 return j return [] @@ -470,15 +470,15 @@ def brl_decode_keys_A(data: bytes, start: int, voffset: int) -> List[int]: a = value & 0x0F # n+4,n+3 b = data[i+1] & 0x0F # n+2,n+1 #convert bitstream to list of indexes - if(n > 26): shift=voffset - if(b & 1): j.append(n+0-shift) - if(b & 2): j.append(n+1-shift) - if(b & 4): j.append(n+2-shift) - if(b & 8): j.append(n+3-shift) - if(a & 1): j.append(n+4-shift) - if(a & 2): j.append(n+5-shift) - if(a & 4): j.append(n+6-shift) - if(a & 8): j.append(n+7-shift) + if(n > 26): shift=voffset # noqa: E701 + if(b & 1): j.append(n+0-shift) # noqa: E701 + if(b & 2): j.append(n+1-shift) # noqa: E701 + if(b & 4): j.append(n+2-shift) # noqa: E701 + if(b & 8): j.append(n+3-shift) # noqa: E701 + if(a & 1): j.append(n+4-shift) # noqa: E701 + if(a & 2): j.append(n+5-shift) # noqa: E701 + if(a & 4): j.append(n+6-shift) # noqa: E701 + if(a & 8): j.append(n+7-shift) # noqa: E701 n+=8 return j @@ -493,7 +493,7 @@ def brl_decode_key_names_repeat(driver: BrailleDisplayDriver) -> List[str]: for key in driver.decodedkeys: try: dec.append(driver._keynamesrepeat[key]) - except: + except: # noqa: E722 pass return dec @@ -504,17 +504,17 @@ def brl_decode_key_names(driver: BrailleDisplayDriver) -> List[str]: for key in keys: try: dec.append(driver._keynames[key]) - except: + except: # noqa: E722 pass return dec def brl_join_keys(dec: List[str]) -> str: """join key names with comma, this is used for key combinations""" - if(len(dec) == 1): return dec[0] - elif(len(dec) == 3 and dec[0] == dec[1]): return dec[0] + "," + dec[2] - elif(len(dec) == 3 and dec[0] == dec[2]): return dec[0] + "," + dec[1] - elif(len(dec) == 2): return dec[1] + "," + dec[0] - else: return '' + if(len(dec) == 1): return dec[0] # noqa: E701 + elif(len(dec) == 3 and dec[0] == dec[1]): return dec[0] + "," + dec[2] # noqa: E701 + elif(len(dec) == 3 and dec[0] == dec[2]): return dec[0] + "," + dec[1] # noqa: E701 + elif(len(dec) == 2): return dec[1] + "," + dec[0] # noqa: E701 + else: return '' # noqa: E701 class InputGesture(braille.BrailleDisplayGesture, brailleInput.BrailleInputGesture): @@ -556,8 +556,8 @@ def __init__(self, keys: Optional[Union[bytes, int]], driver: BrailleDisplayDriv self.id = "d7" elif dots == 128: self.id = "d8" - elif thumbs == 2: self.space = True - else:self.dots = dots + elif thumbs == 2: self.space = True # noqa: E701 + else:self.dots = dots # noqa: E701 return if(driver._proto == 'A'):#non trio diff --git a/source/brailleDisplayDrivers/papenmeier_serial.py b/source/brailleDisplayDrivers/papenmeier_serial.py index c542a66d3c5..219de4adf3c 100644 --- a/source/brailleDisplayDrivers/papenmeier_serial.py +++ b/source/brailleDisplayDrivers/papenmeier_serial.py @@ -48,7 +48,7 @@ def brl_out(offset: int, data: List[int]) -> bytes: def brl_poll(dev: serial.Serial) -> bytes: """read data from braille display, used by keypress handler""" - if dev.in_waiting < 10: return b"" + if dev.in_waiting < 10: return b"" # noqa: E701 ret = dev.read(dev.in_waiting) if ret[0] == STX and ret[9] == ETX: return ret @@ -93,8 +93,8 @@ def __init__(self, port): if(self._dev is None): self._dev = serial.Serial(self._port, baudrate = baud, timeout=TIMEOUT, writeTimeout=TIMEOUT) self._dev.write(brl_auto_id()) - if (baud == 19200): time.sleep(0.2) - else: time.sleep(0.03) + if (baud == 19200): time.sleep(0.2) # noqa: E701 + else: time.sleep(0.03) # noqa: E701 displaytype = brl_poll(self._dev) dic = -1 if len(displaytype) == 10 and displaytype[0] == STX and displaytype[1] == ord(b'I'): @@ -153,33 +153,33 @@ def terminate(self): """free resources""" super(BrailleDisplayDriver, self).terminate() try: - if(self._dev!=None): + if(self._dev!=None): # noqa: E711 self._dev.close() self._dev = None self._keyCheckTimer.Stop() self._keyCheckTimer = None - except: + except: # noqa: E722 pass def display(self, cells: List[int]): """write data to braille display""" - if(self._dev!=None): + if(self._dev!=None): # noqa: E711 try: self._dev.write(brl_out(self._offsetHorizontal, cells)) - except: + except: # noqa: E722 self._dev = None def executeGesture(self,gesture): """execute a gesture""" #here you can add other gesture types try: - if gesture.id: inputCore.manager.executeGesture(gesture) + if gesture.id: inputCore.manager.executeGesture(gesture) # noqa: E701 except inputCore.NoInputGestureAction: pass def _handleKeyPresses(self): #called by the keycheck timer """if a button was pressed an input gesture is executed""" - if(self._dev!=None): + if(self._dev!=None): # noqa: E711 data = brl_poll(self._dev) if len(data) == 10 and data[1] == ord(b'K'): pos = (data[2] << 8) + data[3] @@ -190,7 +190,7 @@ def _handleKeyPresses(self): #called by the keycheck timer self.executeGesture(InputGesture(pos, pressed, keys, self)) elif(len(data) == 0): if(self._repeatcount==50): - if(len(self._lastkey)): self.executeGesture(InputGesture(None, None, None, self)) + if(len(self._lastkey)): self.executeGesture(InputGesture(None, None, None, self)) # noqa: E701 self._repeatcount = 0 else: self._repeatcount += 1 @@ -222,30 +222,30 @@ def _handleKeyPresses(self): #called by the keycheck timer def brl_keyname2(keys: int) -> str: """returns keyname for key index on displays with eab""" - if(keys & 4 == 4): return 'l1' - if(keys & 8 == 8): return 'l2' - if(keys & 16 == 16): return 'r1' - if(keys & 32 == 32): return 'r2' + if(keys & 4 == 4): return 'l1' # noqa: E701 + if(keys & 8 == 8): return 'l2' # noqa: E701 + if(keys & 16 == 16): return 'r1' # noqa: E701 + if(keys & 32 == 32): return 'r2' # noqa: E701 return '' def brl_keyname(keyindex: int, driver: BrailleDisplayDriver) -> str: """returns keyname for key index""" if(driver._eab): - if(keyindex==-255): return "left" - if(keyindex==-254): return "left2" - if(keyindex==-253): return "up" - if(keyindex==-252): return "up2" - if(keyindex==-251): return "right" - if(keyindex==-250): return "right2" - if(keyindex==-249): return "dn" - if(keyindex==-248): return "dn2" + if(keyindex==-255): return "left" # noqa: E701 + if(keyindex==-254): return "left2" # noqa: E701 + if(keyindex==-253): return "up" # noqa: E701 + if(keyindex==-252): return "up2" # noqa: E701 + if(keyindex==-251): return "right" # noqa: E701 + if(keyindex==-250): return "right2" # noqa: E701 + if(keyindex==-249): return "dn" # noqa: E701 + if(keyindex==-248): return "dn2" # noqa: E701 return '' else: #display does not have an eab, so the display specific table is used keyindex = keyindex+255 if(keyindex>=0 and keyindex Generator[TextInfoQuickNavItem, None, None]: return self._iterTextStyle(itemType, direction, info) else: - iterFactory=lambda direction,info: self._iterNodesByType(itemType,direction,info) + iterFactory=lambda direction,info: self._iterNodesByType(itemType,direction,info) # noqa: E731 info=self.selection try: item = next(iterFactory(direction, info)) @@ -554,7 +554,7 @@ def addQuickNav( scriptSuffix = itemType[0].upper() + itemType[1:] scriptName = "next%s" % scriptSuffix funcName = "script_%s" % scriptName - script = lambda self,gesture: self._quickNavScript(gesture, itemType, "next", nextError, readUnit) + script = lambda self,gesture: self._quickNavScript(gesture, itemType, "next", nextError, readUnit) # noqa: E731 script.__doc__ = nextDoc script.__name__ = funcName script.resumeSayAllMode = sayAll.CURSOR.CARET @@ -563,7 +563,7 @@ def addQuickNav( cls.__gestures["kb:%s" % key] = scriptName scriptName = "previous%s" % scriptSuffix funcName = "script_%s" % scriptName - script = lambda self,gesture: self._quickNavScript(gesture, itemType, "previous", prevError, readUnit) + script = lambda self,gesture: self._quickNavScript(gesture, itemType, "previous", prevError, readUnit) # noqa: E731 script.__doc__ = prevDoc script.__name__ = funcName script.resumeSayAllMode = sayAll.CURSOR.CARET @@ -1281,7 +1281,7 @@ def filter(self, filterText, newElementType=False): # #8753: wxPython 4 returns "invalid tree item" when the tree view is empty, so use initial element if appropriate. try: defaultElement = self._initialElement if newElementType else self.tree.GetItemData(self.tree.GetSelection()) - except: + except: # noqa: E722 defaultElement = self._initialElement # Clear the tree. self.tree.DeleteChildren(self.treeRoot) @@ -1346,7 +1346,7 @@ def onTreeChar(self, evt): elif key == wx.WXK_F2: item=self.tree.GetSelection() if item: - selectedItemType=self.tree.GetItemData(item).item + selectedItemType=self.tree.GetItemData(item).item # noqa: F841 self.tree.EditLabel(item) evt.Skip() @@ -1718,7 +1718,7 @@ def _tabOverride(self, direction): focus = api.getFocusObject() try: focusInfo = self.makeTextInfo(focus) - except: + except: # noqa: E722 return False # We only want to override the tab order if the caret is not within the focused node. caretInfo=self.makeTextInfo(textInfos.POSITION_CARET) @@ -1789,7 +1789,7 @@ def _replayFocusEnteredEvents(self): for parent in api.getFocusAncestors()[api.getFocusDifferenceLevel():]: try: parent.event_focusEntered() - except: + except: # noqa: E722 log.exception("Error executing focusEntered event: %s" % parent) def event_gainFocus(self, obj, nextHandler): @@ -1842,7 +1842,7 @@ def event_gainFocus(self, obj, nextHandler): try: focusInfo = self.makeTextInfo(obj) - except: + except: # noqa: E722 # This object is not in the treeInterceptor, even though it resides beneath the document. # Automatic pass through should be enabled in certain circumstances where this occurs. if not self.passThrough and self.shouldPassThrough(obj, reason=OutputReason.FOCUS): diff --git a/source/buildVersion.py b/source/buildVersion.py index 87ef9aafc06..dc0ff17a0f6 100644 --- a/source/buildVersion.py +++ b/source/buildVersion.py @@ -31,7 +31,7 @@ def _updateVersionFromVCS(): version = "source-%s-%s" % ( os.path.basename(ref), commit[:7]) - except: + except: # noqa: E722 pass @@ -73,7 +73,7 @@ def formatVersionForGUI(year, major, minor): publisher="unknown" updateVersionType=None try: - from _buildVersion import version, publisher, updateVersionType, version_build + from _buildVersion import version, publisher, updateVersionType, version_build # noqa: F401 except ImportError: _updateVersionFromVCS() diff --git a/source/characterProcessing.py b/source/characterProcessing.py index f947e20d6f5..1cffc337a12 100644 --- a/source/characterProcessing.py +++ b/source/characterProcessing.py @@ -53,14 +53,14 @@ def fetchLocaleData(self, locale: str, fallback: bool = True) -> _LocaleDataT: localeList=[locale] if fallback and '_' in locale: localeList.append(locale.split('_')[0]) - for l in localeList: + for l in localeList: # noqa: E741 data=self._dataMap.get(l) - if data: return data + if data: return data # noqa: E701 try: data=self._localeDataFactory(l) except LookupError: data=None - if not data: continue + if not data: continue # noqa: E701 self._dataMap[l]=data return data raise LookupError(locale) @@ -127,7 +127,7 @@ def getCharacterDescription(locale: str, character: str) -> Optional[List[str]]: @return: the found description for the given character """ try: - l=_charDescLocaleDataMap.fetchLocaleData(locale) + l=_charDescLocaleDataMap.fetchLocaleData(locale) # noqa: E741 except LookupError: if not locale.startswith('en'): return getCharacterDescription('en',character) diff --git a/source/config/__init__.py b/source/config/__init__.py index c600178e992..f05ec181357 100644 --- a/source/config/__init__.py +++ b/source/config/__init__.py @@ -115,7 +115,7 @@ def saveOnExit(): if conf["general"]["saveConfigurationOnExit"]: try: conf.save() - except: + except: # noqa: E722 pass @@ -563,7 +563,7 @@ def _initBaseConf(self, factoryDefaults=False): try: profile = self._loadConfig(fn) # a blank config returned if fn does not exist self.baseConfigError = False - except: + except: # noqa: E722 backupFileName = fn + '.corrupted.bak' log.error( "Error loading base configuration; the base configuration file will be reinitialized." @@ -986,7 +986,7 @@ def _loadProfileTriggers(self): fn = WritePaths.profileTriggersFile try: cobj = ConfigObj(fn, indent_type="\t", encoding="UTF-8") - except: + except: # noqa: E722 log.error("Error loading profile triggers", exc_info=True) cobj = ConfigObj(None, indent_type="\t", encoding="UTF-8") cobj.filename = fn @@ -1358,7 +1358,7 @@ def enter(self): return try: conf._triggerProfileEnter(self) - except: + except: # noqa: E722 log.error("Error entering trigger %s, profile %s" % (self.spec, self.profileName), exc_info=True) __enter__ = enter @@ -1371,7 +1371,7 @@ def exit(self): return try: conf._triggerProfileExit(self) - except: + except: # noqa: E722 log.error("Error exiting trigger %s, profile %s" % (self.spec, self.profileName), exc_info=True) diff --git a/source/core.py b/source/core.py index 5363fcd0960..29ed64082c1 100644 --- a/source/core.py +++ b/source/core.py @@ -185,7 +185,7 @@ def onResult(ID): if ID in (wx.ID_YES,wx.ID_NO): try: config.conf.save() - except: + except: # noqa: E722 pass # Ask the user if usage stats can be collected. gui.runScriptModalDialog(gui.startupDialogs.AskAllowUsageStatsDialog(None), onResult) @@ -357,7 +357,7 @@ def _setInitialFocus(): focus = api.getDesktopObject().objectWithFocus() if focus: eventHandler.queueEvent('gainFocus', focus) - except: + except: # noqa: E722 log.exception("Error retrieving initial focus") @@ -744,7 +744,7 @@ def main(): if wxLang: try: wxLocaleObj.Init(wxLang.Language) - except: + except: # noqa: E722 log.error("Failed to initialize wx locale",exc_info=True) finally: # Revert wx's changes to the python locale @@ -762,7 +762,7 @@ def main(): log.info("Java Access Bridge support initialized") except NotImplementedError: log.warning("Java Access Bridge not available") - except: + except: # noqa: E722 log.error("Error initializing Java Access Bridge support", exc_info=True) import winConsoleHandler log.debug("Initializing legacy winConsole support") @@ -773,7 +773,7 @@ def main(): UIAHandler.initialize() except RuntimeError: log.warning("UIA disabled in configuration") - except: + except: # noqa: E722 log.error("Error initializing UIA support", exc_info=True) import IAccessibleHandler log.debug("Initializing IAccessible support") @@ -817,7 +817,7 @@ def main(): try: # Translators: This is shown on a braille display (if one is connected) when NVDA starts. braille.handler.message(_("NVDA started")) - except: + except: # noqa: E722 log.error("", exc_info=True) if globalVars.appArgs.launcher: from gui.startupDialogs import LauncherDialog @@ -944,7 +944,7 @@ def _doPostNvdaStartupAction(): try: speech.cancelSpeech() - except: + except: # noqa: E722 pass import treeInterceptorHandler @@ -985,7 +985,7 @@ def _doPostNvdaStartupAction(): os.path.join(globalVars.appDir, "waves", "exit.wav"), asynchronous=False ) - except: + except: # noqa: E722 pass # We cannot terminate nvwave until after we perform nvwave.playWaveFile _terminate(nvwave) @@ -1001,7 +1001,7 @@ def _terminate(module, name=None): log.debug("Terminating %s" % name) try: module.terminate() - except: + except: # noqa: E722 log.exception("Error terminating %s" % name) diff --git a/source/displayModel.py b/source/displayModel.py index 78c8bc12412..3efae4f058a 100644 --- a/source/displayModel.py +++ b/source/displayModel.py @@ -4,7 +4,7 @@ # Copyright (C) 2006-2022 NV Access Limited, Babbage B.V., Joseph Lee, Cyrille Bougot import ctypes -from ctypes import * +from ctypes import * # noqa: F403 from comtypes import BSTR import unicodedata import math @@ -36,17 +36,17 @@ def wcharToInt(c): i=ord(c) - return c_short(i).value + return c_short(i).value # noqa: F405 def detectStringDirection(s): direction=0 for b in (unicodedata.bidirectional(ch) for ch in s): - if b=='L': direction+=1 - if b in ('R','AL'): direction-=1 + if b=='L': direction+=1 # noqa: E701 + if b in ('R','AL'): direction-=1 # noqa: E701 return direction def normalizeRtlString(s): - l=[] + l=[] # noqa: E741 for c in s: #If this is an arabic presentation form b character (commenly given by Windows when converting from glyphs) #Decompose it to its original basic arabic (non-presentational_ character. @@ -58,7 +58,7 @@ def normalizeRtlString(s): l.append(c) return u"".join(l) -def yieldListRange(l,start,stop): +def yieldListRange(l,start,stop): # noqa: E741 for x in range(start,stop): yield l[x] @@ -100,11 +100,11 @@ def processFieldsAndRectsRangeReadingdirection(commandList,rects,startIndex,star if not containsRtl: # As no rtl text was ever seen, then there is nothing else to do return - if overallDirection==0: overallDirection=1 + if overallDirection==0: overallDirection=1 # noqa: E701 # following the calculated over all reading direction of the passage, correct all weak/neutral fields to have the same reading direction as the field preceeding them lastDirection=overallDirection for index in range(startIndex,endIndex): - if overallDirection<0: index=endIndex-index-1 + if overallDirection<0: index=endIndex-index-1 # noqa: E701 item=commandList[index] if isinstance(item,textInfos.FieldCommand) and isinstance(item.field,textInfos.FormatField): direction=item.field['direction'] @@ -171,7 +171,7 @@ def processFieldsAndRectsRangeReadingdirection(commandList,rects,startIndex,star def initialize(): global _getWindowTextInRect,_requestTextChangeNotificationsForWindow, _getFocusRect - _getWindowTextInRect=CFUNCTYPE(c_long,c_long,c_long,c_bool,c_int,c_int,c_int,c_int,c_int,c_int,c_bool,POINTER(BSTR),POINTER(BSTR))(('displayModel_getWindowTextInRect',NVDAHelper.localLib),((1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(2,),(2,))) + _getWindowTextInRect=CFUNCTYPE(c_long,c_long,c_long,c_bool,c_int,c_int,c_int,c_int,c_int,c_int,c_bool,POINTER(BSTR),POINTER(BSTR))(('displayModel_getWindowTextInRect',NVDAHelper.localLib),((1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(1,),(2,),(2,))) # noqa: F405 _requestTextChangeNotificationsForWindow=NVDAHelper.localLib.displayModel_requestTextChangeNotificationsForWindow def getCaretRect(obj): @@ -217,11 +217,11 @@ def getWindowTextInRect(bindingHandle, windowHandle, left, top, right, bottom,mi return text, characterLocations def getFocusRect(obj): - left=c_long() - top=c_long() - right=c_long() - bottom=c_long() - if NVDAHelper.localLib.displayModel_getFocusRect(obj.appModule.helperLocalBindingHandle,obj.windowHandle,byref(left),byref(top),byref(right),byref(bottom))==0: + left=c_long() # noqa: F405 + top=c_long() # noqa: F405 + right=c_long() # noqa: F405 + bottom=c_long() # noqa: F405 + if NVDAHelper.localLib.displayModel_getFocusRect(obj.appModule.helperLocalBindingHandle,obj.windowHandle,byref(left),byref(top),byref(right),byref(bottom))==0: # noqa: F405 return left.value,top.value,right.value,bottom.value return None @@ -493,7 +493,7 @@ def _getNVDAObjectFromOffset(self,offset): return obj def _getOffsetsFromNVDAObject(self,obj): - l=obj.location + l=obj.location # noqa: E741 if not l: log.debugWarning("object has no location") raise LookupError diff --git a/source/editableText.py b/source/editableText.py index e94cf4559af..3dcba77de4e 100755 --- a/source/editableText.py +++ b/source/editableText.py @@ -158,7 +158,7 @@ def _caretScriptPostMovedHelper(self, speakUnit, gesture, info=None): if not info: try: info = self.makeTextInfo(textInfos.POSITION_CARET) - except: + except: # noqa: E722 return # Forget the word currently being typed as the user has moved the caret somewhere else. speech.clearTypedWordBuffer() @@ -171,7 +171,7 @@ def _caretScriptPostMovedHelper(self, speakUnit, gesture, info=None): def _caretMovementScriptHelper(self, gesture, unit): try: info=self.makeTextInfo(textInfos.POSITION_CARET) - except: + except: # noqa: E722 gesture.send() return bookmark=info.bookmark @@ -198,7 +198,7 @@ def _get_caretMovementDetectionUsesEvents(self) -> bool: def script_caret_newLine(self,gesture): try: info=self.makeTextInfo(textInfos.POSITION_CARET) - except: + except: # noqa: E722 gesture.send() return bookmark=info.bookmark @@ -235,7 +235,7 @@ def _caretMoveBySentenceHelper(self, gesture, direction): info.move(textInfos.UNIT_SENTENCE, direction) info.updateCaret() self._caretScriptPostMovedHelper(textInfos.UNIT_SENTENCE,gesture,info) - except: + except: # noqa: E722 gesture.send() return @@ -264,7 +264,7 @@ def script_caret_nextSentence(self,gesture): def _backspaceScriptHelper(self,unit,gesture): try: oldInfo=self.makeTextInfo(textInfos.POSITION_CARET) - except: + except: # noqa: E722 gesture.send() return oldBookmark=oldInfo.bookmark @@ -300,7 +300,7 @@ def script_caret_backspaceWord(self,gesture): def _deleteScriptHelper(self, unit, gesture): try: info=self.makeTextInfo(textInfos.POSITION_CARET) - except: + except: # noqa: E722 gesture.send() return bookmark=info.bookmark @@ -386,7 +386,7 @@ def initAutoSelectDetection(self): """ try: self._lastSelectionPos=self.makeTextInfo(textInfos.POSITION_SELECTION) - except: + except: # noqa: E722 self._lastSelectionPos=None self.isTextSelectionAnchoredAtStart=True self.hasContentChangedSinceLastSelection=False @@ -399,7 +399,7 @@ def detectPossibleSelectionChange(self): return try: newInfo=self.makeTextInfo(textInfos.POSITION_SELECTION) - except: + except: # noqa: E722 # Just leave the old selection, which is usually better than nothing. return oldInfo=getattr(self,'_lastSelectionPos',None) @@ -446,7 +446,7 @@ def reportSelectionChange(self, oldTextInfo): def script_caret_changeSelection(self,gesture): try: oldInfo=self.makeTextInfo(textInfos.POSITION_SELECTION) - except: + except: # noqa: E722 gesture.send() return gesture.send() @@ -454,7 +454,7 @@ def script_caret_changeSelection(self,gesture): return try: self.reportSelectionChange(oldInfo) - except: + except: # noqa: E722 return __changeSelectionGestures = ( diff --git a/source/extensionPoints/__init__.py b/source/extensionPoints/__init__.py index d0c409fc70a..74408baf54a 100644 --- a/source/extensionPoints/__init__.py +++ b/source/extensionPoints/__init__.py @@ -11,7 +11,7 @@ See the L{Action}, L{Filter}, L{Decider} and L{AccumulatingDecider} classes. """ from logHandler import log -from .util import HandlerRegistrar, callWithSupportedKwargs, BoundMethodWeakref +from .util import HandlerRegistrar, callWithSupportedKwargs, BoundMethodWeakref # noqa: F401 from typing import ( Callable, Generator, @@ -53,7 +53,7 @@ def notify(self, **kwargs): for handler in self.handlers: try: callWithSupportedKwargs(handler, **kwargs) - except: + except: # noqa: E722 log.exception("Error running handler %r for %r" % (handler, self)) def notifyOnce(self, **kwargs): @@ -114,7 +114,7 @@ def apply(self, value: FilterValueT, **kwargs) -> FilterValueT: for handler in self.handlers: try: value = callWithSupportedKwargs(handler, value, **kwargs) - except: + except: # noqa: E722 log.exception("Error running handler %r for %r" % (handler, self)) return value @@ -162,7 +162,7 @@ def decide(self, **kwargs): for handler in self.handlers: try: decision = callWithSupportedKwargs(handler, **kwargs) - except: + except: # noqa: E722 log.exception("Error running handler %r for %r" % (handler, self)) continue if not decision: diff --git a/source/fileUtils.py b/source/fileUtils.py index 46e7293246f..8ed45d6a8ef 100644 --- a/source/fileUtils.py +++ b/source/fileUtils.py @@ -85,7 +85,7 @@ def getFileVersionInfo(name, *attributes): # Load file informations into buffer res ctypes.windll.version.GetFileVersionInfoW(name, None, size, res) r = ctypes.c_uint() - l = 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)) diff --git a/source/globalCommands.py b/source/globalCommands.py index 04119afb564..6f4aa13ea3a 100755 --- a/source/globalCommands.py +++ b/source/globalCommands.py @@ -1146,7 +1146,7 @@ def script_moveMouseToNavigatorObject(self, gesture: inputCore.InputGesture): try: (left, top, width, height) = navigatorObject.location - except: + except: # noqa: E722 # Translators: Reported when the object has no location for the mouse to move to it. ui.message(_("Object has no location")) return @@ -1625,7 +1625,7 @@ def script_review_activate(self, gesture: inputCore.InputGesture): realActionName=actionName try: realActionName=obj.getActionName() - except: + except: # noqa: E722 pass try: obj.doAction() @@ -2234,7 +2234,7 @@ def script_toggleVirtualBufferPassThrough(self,gesture): for obj in itertools.chain((api.getFocusObject(),), reversed(api.getFocusAncestors())): try: obj.treeInterceptorClass - except: + except: # noqa: E722 continue break else: @@ -3503,7 +3503,7 @@ def script_braille_toggleFocusContextPresentation(self, gesture): labels = [x[1] for x in braille.focusContextPresentations] try: index = values.index(config.conf["braille"]["focusContextPresentation"]) - except: + except: # noqa: E722 index=0 newIndex = (index+1) % len(values) config.conf["braille"]["focusContextPresentation"] = values[newIndex] @@ -3551,7 +3551,7 @@ def script_braille_cycleCursorShape(self, gesture): cursorShape = "cursorShapeReview" try: index = shapes.index(config.conf["braille"][cursorShape]) + 1 - except: + except: # noqa: E722 index = 1 if index >= len(braille.CURSOR_SHAPES): index = 0 @@ -3648,7 +3648,7 @@ def script_braille_cycleUnicodeNormalization(self, gesture: inputCore.InputGestu def script_reportClipboardText(self,gesture): try: text = api.getClipData() - except: + except: # noqa: E722 text = None if not text or not isinstance(text,str) or text.isspace(): # Translators: Presented when there is no text on the clipboard. @@ -4658,7 +4658,7 @@ def addScriptForProfile(cls, name): @param name: The name of the profile to add a script for. @type name: str """ - script = lambda self, gesture: cls._profileScript(name) + script = lambda self, gesture: cls._profileScript(name) # noqa: E731 funcName = script.__name__ = "script_%s" % cls._getScriptNameForProfile(name) # Just set the doc string of the script, using the decorator is overkill here. # Translators: The description shown in input help for a script that @@ -4697,7 +4697,7 @@ def _moveGesturesForProfileActivationScript(cls, oldScriptName, newScriptName=No gestureMap.add(gesture, moduleName, className, newScriptName) try: gestureMap.save() - except: + except: # noqa: E722 log.debugWarning("Couldn't save user gesture map after renaming profile script", exc_info=True) @classmethod diff --git a/source/globalPluginHandler.py b/source/globalPluginHandler.py index c23d7410c63..8a026204ee6 100644 --- a/source/globalPluginHandler.py +++ b/source/globalPluginHandler.py @@ -20,7 +20,7 @@ def listPlugins(): continue try: plugin = importlib.import_module("globalPlugins.%s" % name, package="globalPlugins").GlobalPlugin - except: + except: # noqa: E722 log.error("Error importing global plugin %s" % name, exc_info=True) continue yield plugin @@ -29,7 +29,7 @@ def initialize(): for plugin in listPlugins(): try: runningPlugins.add(plugin()) - except: + except: # noqa: E722 log.error("Error initializing global plugin %r" % plugin, exc_info=True) def terminate(): @@ -37,7 +37,7 @@ def terminate(): runningPlugins.discard(plugin) try: plugin.terminate() - except: + except: # noqa: E722 log.exception("Error terminating global plugin %r" % plugin) def reloadGlobalPlugins(): diff --git a/source/gui/__init__.py b/source/gui/__init__.py index c74cbc5775c..6cfc3674436 100644 --- a/source/gui/__init__.py +++ b/source/gui/__init__.py @@ -470,7 +470,7 @@ def onRunCOMRegistrationFixesCommand(self, evt): ) try: systemUtils.execElevated(config.SLAVE_FILENAME, ["fixCOMRegistrations"]) - except: + except: # noqa: E722 log.error("Could not execute fixCOMRegistrations command",exc_info=True) progressDialog.done() del progressDialog diff --git a/source/gui/addonGui.py b/source/gui/addonGui.py index 2fbde777594..b2e3cebfbac 100644 --- a/source/gui/addonGui.py +++ b/source/gui/addonGui.py @@ -135,7 +135,7 @@ def installAddon(parentWindow: wx.Window, addonPath: str) -> bool: # noqa: C901 ) try: bundle = addonHandler.AddonBundle(addonPath) - except: + except: # noqa: E722 log.error("Error opening addon bundle from %s" % addonPath, exc_info=True) gui.messageBox( # Translators: The message displayed when an error occurs when opening an add-on package for adding. @@ -227,7 +227,7 @@ def doneAndDestroy(window): addonDataManager._deleteCacheInstalledAddon(prevAddon.name) prevAddon.requestRemove() return True - except: + except: # noqa: E722 log.error("Error installing addon bundle from %s" % addonPath, exc_info=True) gui.messageBox( # Translators: The message displayed when an error occurs when installing an add-on package. @@ -383,7 +383,7 @@ def refreshAddonsList(self): def onAbout(self, evt: wx.EVT_BUTTON): index: int = self.addonsList.GetFirstSelected() - if index<0: return + if index<0: return # noqa: E701 addon = self.curAddons[index] from gui.addonStoreGui.controls.messageDialogs import _showAddonInfo _showAddonInfo(addon._addonGuiModel) diff --git a/source/gui/configProfiles.py b/source/gui/configProfiles.py index 03f7655e8b4..6aa04bab4d3 100644 --- a/source/gui/configProfiles.py +++ b/source/gui/configProfiles.py @@ -169,7 +169,7 @@ def onChangeState(self, evt): profile = None try: config.conf.manualActivateProfile(profile) - except: + except: # noqa: E722 log.debugWarning("", exc_info=True) # Translators: An error displayed when activating a configuration profile fails. gui.messageBox(_("Error activating profile."), @@ -195,7 +195,7 @@ def onDelete(self, evt): return try: config.conf.deleteProfile(name) - except: + except: # noqa: E722 log.debugWarning("", exc_info=True) # Translators: An error displayed when deleting a configuration profile fails. gui.messageBox(_("Error deleting profile."), @@ -262,7 +262,7 @@ def onRename(self, evt): gui.messageBox(_("That profile already exists. Please choose a different name."), _("Error"), wx.OK | wx.ICON_ERROR, self) return - except: + except: # noqa: E722 log.debugWarning("", exc_info=True) gui.messageBox(_("Error renaming profile."), _("Error"), wx.OK | wx.ICON_ERROR, self) @@ -298,7 +298,7 @@ def onClose(self, evt): def saveTriggers(self, parentWindow=None): try: config.conf.saveProfileTriggers() - except: + 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."), @@ -416,7 +416,7 @@ def __init__(self, parent): mainSizer = wx.BoxSizer(wx.VERTICAL) sHelper = guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL) - sizer = wx.BoxSizer(wx.HORIZONTAL) + sizer = wx.BoxSizer(wx.HORIZONTAL) # noqa: F841 # Translators: The label of a field to enter the name of a new configuration profile. profileNameText = _("Profile name:") self.profileName = sHelper.addLabeledControl(profileNameText, wx.TextCtrl) @@ -477,7 +477,7 @@ def onOk(self, evt): gui.messageBox(_("That profile already exists. Please choose a different name."), _("Error"), wx.OK | wx.ICON_ERROR, self) return - except: + 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."), diff --git a/source/gui/installerGui.py b/source/gui/installerGui.py index df78705f2aa..8c49a6c7483 100644 --- a/source/gui/installerGui.py +++ b/source/gui/installerGui.py @@ -67,7 +67,7 @@ def doInstall( wait=True, handleAlreadyElevated=True ) - if res==2: raise installer.RetriableFailure + if res==2: raise installer.RetriableFailure # noqa: E701 if copyPortableConfig: installedUserConfigPath=config.getInstalledUserConfigPath() if installedUserConfigPath: @@ -307,7 +307,7 @@ def __init__(self): contentSizer.addItem(text) buttonHelper = guiHelper.ButtonHelper(orientation=wx.HORIZONTAL) - okButton = buttonHelper.addButton( + okButton = buttonHelper.addButton( # noqa: F841 parent=self, id=wx.ID_OK, # Translators: The label of a button to proceed with installation, diff --git a/source/gui/settingsDialogs.py b/source/gui/settingsDialogs.py index 21c1dca30eb..d6b0c642fa0 100644 --- a/source/gui/settingsDialogs.py +++ b/source/gui/settingsDialogs.py @@ -105,7 +105,7 @@ class SettingsDialog( @type title: str """ - class MultiInstanceError(RuntimeError): pass + class MultiInstanceError(RuntimeError): pass # noqa: E701 class MultiInstanceErrorWithDialog(MultiInstanceError): dialog: 'SettingsDialog' @@ -491,7 +491,7 @@ class MultiCategorySettingsDialog(SettingsDialog): title="" categoryClasses: typing.List[typing.Type[SettingsPanel]] = [] - class CategoryUnavailableError(RuntimeError): pass + class CategoryUnavailableError(RuntimeError): pass # noqa: E701 def __init__(self, parent, initialCategory=None): """ @@ -966,7 +966,7 @@ def onCopySettings(self,evt): continue res=False break - except: + except: # noqa: E722 log.debugWarning("Error when copying settings to system config",exc_info=True) res=False break @@ -1160,7 +1160,7 @@ def updateSynthesizerList(self): try: index=self.synthNames.index(getSynth().name) self.synthList.SetSelection(index) - except: + except: # noqa: E722 pass def onOk(self, evt): @@ -1811,7 +1811,7 @@ def makeSettings(self, settingsSizer): try: index=self.kbdNames.index(config.conf['keyboard']['keyboardLayout']) self.kbdList.SetSelection(index) - except: + except: # noqa: E722 log.debugWarning("Could not set Keyboard layout list to current layout",exc_info=True) #Translators: This is the label for a list of checkboxes @@ -1958,7 +1958,7 @@ def makeSettings(self, settingsSizer): self.bindHelpEvent("MouseSettingsTextUnit", self.textUnitComboBox) try: index=self.textUnits.index(config.conf["mouse"]["mouseTextUnit"]) - except: + except: # noqa: E722 index=0 self.textUnitComboBox.SetSelection(index) @@ -3382,7 +3382,7 @@ def __init__(self, parent): # Advanced settings panel label = _("Audio") audio = wx.StaticBoxSizer(wx.VERTICAL, self, label=label) - audioBox = audio.GetStaticBox() + audioBox = audio.GetStaticBox() # noqa: F841 audioGroup = guiHelper.BoxSizerHelper(self, sizer=audio) sHelper.addItem(audioGroup) @@ -3810,7 +3810,7 @@ def updateBrailleDisplayLists(self): else: selection = self.displayNames.index(braille.handler.display.name) self.displayList.SetSelection(selection) - except: + except: # noqa: E722 pass import bdDetect @@ -3927,7 +3927,7 @@ def makeSettings(self, settingsSizer): try: selection = self.outTables.index(braille.handler.table) self.outTableList.SetSelection(selection) - except: + except: # noqa: E722 log.exception() if shouldDebugGui: timePassed = time.time() - startTime @@ -3944,7 +3944,7 @@ def makeSettings(self, settingsSizer): try: selection = self.inTables.index(brailleInput.handler.table) self.inTableList.SetSelection(selection) - except: + except: # noqa: E722 log.exception() if shouldDebugGui: timePassed = time.time() - startTime @@ -4026,7 +4026,7 @@ def makeSettings(self, settingsSizer): try: selection = self.cursorShapes.index(config.conf["braille"]["cursorShapeFocus"]) self.cursorShapeFocusList.SetSelection(selection) - except: + except: # noqa: E722 pass if not self.showCursorCheckBox.GetValue(): self.cursorShapeFocusList.Disable() @@ -4042,7 +4042,7 @@ def makeSettings(self, settingsSizer): try: selection = self.cursorShapes.index(config.conf["braille"]["cursorShapeReview"]) self.cursorShapeReviewList.SetSelection(selection) - except: + except: # noqa: E722 pass if not self.showCursorCheckBox.GetValue(): self.cursorShapeReviewList.Disable() @@ -4141,7 +4141,7 @@ def makeSettings(self, settingsSizer): self.bindHelpEvent("BrailleSettingsFocusContextPresentation", self.focusContextPresentationList) try: index=self.focusContextPresentationValues.index(config.conf["braille"]["focusContextPresentation"]) - except: + except: # noqa: E722 index=0 self.focusContextPresentationList.SetSelection(index) diff --git a/source/gui/speechDict.py b/source/gui/speechDict.py index e564bb0de34..870cd7d1ac2 100644 --- a/source/gui/speechDict.py +++ b/source/gui/speechDict.py @@ -151,7 +151,7 @@ class DictionaryDialog( To use this dialog, override L{__init__} calling super().__init__. """ - TYPE_LABELS = {t: l.replace("&", "") for t, l in DictionaryEntryDialog.TYPE_LABELS.items()} + TYPE_LABELS = {t: l.replace("&", "") for t, l in DictionaryEntryDialog.TYPE_LABELS.items()} # noqa: E741 helpId = "SpeechDictionaries" @abstractmethod diff --git a/source/hwIo/base.py b/source/hwIo/base.py index 2beb7064eda..28f4052b6f7 100644 --- a/source/hwIo/base.py +++ b/source/hwIo/base.py @@ -201,7 +201,7 @@ def _notifyReceive(self, data: bytes): log.debug("Read: %r" % data) try: self._onReceive(data) - except: + except: # noqa: E722 log.error("", exc_info=True) diff --git a/source/inputCore.py b/source/inputCore.py index 434927c6ff1..f06d200016c 100644 --- a/source/inputCore.py +++ b/source/inputCore.py @@ -341,7 +341,7 @@ def update(self, entries: FlattenedGestureMapT): for locationName, location in entries.items(): try: module, className = locationName.rsplit(".", 1) - except: + except: # noqa: E722 log.error("Invalid module/class specification: %s" % locationName) self.lastUpdateContainedError = True continue @@ -355,7 +355,7 @@ def update(self, entries: FlattenedGestureMapT): for gesture in gestures: try: self.add(gesture, module, className, script) - except: + except: # noqa: E722 log.error("Invalid gesture: %s" % gesture) self.lastUpdateContainedError = True continue @@ -555,7 +555,7 @@ def suppressCancelSpeech(): try: if self._captureFunc(gesture) is False: return - except: + except: # noqa: E722 log.error("Error in capture function, disabling", exc_info=True) self._captureFunc = None @@ -575,7 +575,7 @@ def suppressCancelSpeech(): # #2953: if an intercepted command Script (script that sends a gesture) is queued # then queue all following gestures (that don't have a script) with a fake script so that they remain in order. if not script and scriptHandler._numIncompleteInterceptedCommandScripts: - script=lambda gesture: gesture.send() + script=lambda gesture: gesture.send() # noqa: E731 if script: diff --git a/source/installer.py b/source/installer.py index 36d1bfb7898..25be6ffc2b1 100644 --- a/source/installer.py +++ b/source/installer.py @@ -130,7 +130,7 @@ def getDocFilePath(fileName,installDir): def copyProgramFiles(destPath): sourcePath = globalVars.appDir detectUserConfig=True - detectNVDAExe=True + detectNVDAExe=True # noqa: F841 for curSourceDir,subDirs,files in os.walk(sourcePath): if detectUserConfig: detectUserConfig=False diff --git a/source/keyboardHandler.py b/source/keyboardHandler.py index 6ad4957a31e..70974ac04f2 100644 --- a/source/keyboardHandler.py +++ b/source/keyboardHandler.py @@ -251,7 +251,7 @@ def internal_keyDownEvent(vkCode,scanCode,extended,injected): # Never pass the NVDA modifier key to the OS. trappedKeys.add(keyCode) return False - except: + except: # noqa: E722 log.error("internal_keyDownEvent", exc_info=True) finally: if _watchdogObserver.isAttemptingRecovery: @@ -321,7 +321,7 @@ def internal_keyUpEvent(vkCode,scanCode,extended,injected): if keyCode in trappedKeys: trappedKeys.remove(keyCode) return False - except: + except: # noqa: E722 log.error("", exc_info=True) return True diff --git a/source/logHandler.py b/source/logHandler.py index 0d49ef3b1e3..56495d3e711 100755 --- a/source/logHandler.py +++ b/source/logHandler.py @@ -371,7 +371,7 @@ def handle(self,record): if record.levelno>=logging.CRITICAL: try: winsound.PlaySound("SystemHand", winsound.SND_ALIAS | winsound.SND_ASYNC) - except: + except: # noqa: E722 pass elif record.levelno >= logging.ERROR and shouldPlayErrorSound(): getOnErrorSoundRequested().notify() diff --git a/source/mathPres/__init__.py b/source/mathPres/__init__.py index 226128a85dd..1b55dba55f8 100644 --- a/source/mathPres/__init__.py +++ b/source/mathPres/__init__.py @@ -85,7 +85,7 @@ def initialize() -> None: from . import mathPlayer try: provider = mathPlayer.MathPlayer() - except: + except: # noqa: E722 log.warning("MathPlayer 4 not available") else: registerProvider(provider, speech=not speechProvider, diff --git a/source/mouseHandler.py b/source/mouseHandler.py index c97f04bf665..b1d797bde99 100644 --- a/source/mouseHandler.py +++ b/source/mouseHandler.py @@ -115,7 +115,7 @@ def internal_mouseEvent(msg,x,y,injected): core.requestPump() elif msg in (WM_LBUTTONDOWN,WM_RBUTTONDOWN): queueHandler.queueFunction(queueHandler.eventQueue,speech.cancelSpeech) - except: + except: # noqa: E722 log.error("", exc_info=True) return True @@ -165,7 +165,7 @@ def getMouseRestrictedToScreens(x, y, displays): max(min(scrCenterToMouse.y, halfWidth.y), -halfWidth.y)) edgeToMouse = mpos - mouseLimitedToScreen distFromRectToMouseSqd = abs(edgeToMouse.x) + abs(edgeToMouse.y) - if closestDistValue == None or closestDistValue > distFromRectToMouseSqd: + if closestDistValue == None or closestDistValue > distFromRectToMouseSqd: # noqa: E711 closestDistValue = distFromRectToMouseSqd newXY = mouseLimitedToScreen @@ -189,10 +189,10 @@ def getTotalWidthAndHeightAndMinimumPosition(displays): smallestX, smallestY, largestX, largestY = (None, None, None, None) for screenRect in displays: (screenMin, screenMax) = getMinMaxPoints(screenRect) - if smallestX == None or screenMin.x < smallestX: smallestX = screenMin.x - if smallestY == None or screenMin.y < smallestY: smallestY = screenMin.y - if largestX == None or screenMax.x > largestX: largestX = screenMax.x - if largestY == None or screenMax.y > largestY: largestY = screenMax.y + if smallestX == None or screenMin.x < smallestX: smallestX = screenMin.x # noqa: E701, E711 + if smallestY == None or screenMin.y < smallestY: smallestY = screenMin.y # noqa: E701, E711 + if largestX == None or screenMax.x > largestX: largestX = screenMax.x # noqa: E701, E711 + if largestY == None or screenMax.y > largestY: largestY = screenMax.y # noqa: E701, E711 # get full range, including any "blank space" between monitors totalWidth = largestX - smallestX @@ -225,7 +225,7 @@ def executeMouseMoveEvent(x,y): try: eventHandler.executeEvent("mouseMove",mouseObject,x=x,y=y) oldMouseObject=mouseObject - except: + except: # noqa: E722 log.error("api.notifyMouseMoved", exc_info=True) #Register internal mouse event @@ -237,7 +237,7 @@ def initialize(): desktopObject=api.getDesktopObject() try: mouseObject=desktopObject.objectFromPoint(x,y) - except: + except: # noqa: E722 log.exception("Error retrieving initial mouse object") mouseObject=None if not mouseObject: diff --git a/source/nvda.pyw b/source/nvda.pyw index b089f15a5ef..153070e5300 100755 --- a/source/nvda.pyw +++ b/source/nvda.pyw @@ -58,12 +58,12 @@ globalVars.appDir = appDir globalVars.appPid = os.getpid() -import argparse -import config -import logHandler -from logHandler import log -import winUser -import winKernel +import argparse # noqa: E402 +import config # noqa: E402 +import logHandler # noqa: E402 +from logHandler import log # noqa: E402 +import winUser # noqa: E402 +import winKernel # noqa: E402 # Find out if NVDA is running as a Windows Store application bufLen=ctypes.c_int() @@ -120,7 +120,7 @@ NVDAState._initializeStartTime() # Check OS version requirements -import winVersion +import winVersion # noqa: E402 if not winVersion.isSupportedOS(): winUser.MessageBox(0, ctypes.FormatError(winUser.ERROR_OLD_WIN_VERSION), None, winUser.MB_ICONERROR) sys.exit(1) @@ -447,7 +447,7 @@ _log = None logHandler.initialize() if logHandler.log.getEffectiveLevel() is log.DEBUG: log.debug("Provided arguments: {}".format(sys.argv[1:])) -import buildVersion +import buildVersion # noqa: E402 log.info(f"Starting NVDA version {buildVersion.version} {os.environ['PROCESSOR_ARCHITECTURE']}") log.debug("Debug level logging enabled") if customVenvDetected: @@ -467,7 +467,7 @@ if not isRunningOnSecureDesktop() and not config.isAppX: try: import core core.main() -except: +except: # noqa: E722 log.critical("core failure",exc_info=True) sys.exit(1) finally: diff --git a/source/nvwave.py b/source/nvwave.py index 4455d678d08..70442db9afb 100644 --- a/source/nvwave.py +++ b/source/nvwave.py @@ -468,7 +468,7 @@ def sync(self): if self._prevOnDone not in (None, self.STOPPING): try: self._prevOnDone() - except: + except: # noqa: E722 log.exception("Error calling onDone") self._prevOnDone = None @@ -524,12 +524,12 @@ def _idleUnbuffered(self): self._close() # Idle so no need to call stop. self._setCurrentDevice(self._preferredDeviceName) self.open() - if self._audioDucker: self._audioDucker.disable() + if self._audioDucker: self._audioDucker.disable() # noqa: E701 def stop(self): """Stop playback. """ - if self._audioDucker: self._audioDucker.disable() + if self._audioDucker: self._audioDucker.disable() # noqa: E701 if self._minBufferSize: self._buffer = b"" with self._waveout_lock: @@ -685,7 +685,7 @@ def playWaveFile( """ global fileWavePlayer, fileWavePlayerThread f = wave.open(fileName,"r") - if f is None: raise RuntimeError("can not open file %s"%fileName) + if f is None: raise RuntimeError("can not open file %s"%fileName) # noqa: E701 if fileWavePlayer is not None: # There are several race conditions where the background thread might feed # audio after we call stop here in the main thread. Some of these are diff --git a/source/objbase.py b/source/objbase.py index 4b23dacb845..a23b3551408 100644 --- a/source/objbase.py +++ b/source/objbase.py @@ -3,15 +3,15 @@ #This file is covered by the GNU General Public License. #See the file COPYING for more details. -from ctypes import * +from ctypes import * # noqa: F403 import objidl def GetRunningObjectTable(): - rot = POINTER(objidl.IRunningObjectTable)() - oledll.ole32.GetRunningObjectTable(0, byref(rot)) + rot = POINTER(objidl.IRunningObjectTable)() # noqa: F405 + oledll.ole32.GetRunningObjectTable(0, byref(rot)) # noqa: F405 return rot def CreateBindCtx(): - bctx = POINTER(objidl.IBindCtx)() - oledll.ole32.CreateBindCtx(0, byref(bctx)) + bctx = POINTER(objidl.IBindCtx)() # noqa: F405 + oledll.ole32.CreateBindCtx(0, byref(bctx)) # noqa: F405 return bctx diff --git a/source/oleTypes.py b/source/oleTypes.py index d4c1d305078..6b800da57b6 100755 --- a/source/oleTypes.py +++ b/source/oleTypes.py @@ -1,123 +1,123 @@ # typelib _lcid = 0 # change this if required -from ctypes import * -WSTRING = c_wchar_p -from comtypes import IUnknown -LONG_PTR = c_int -from comtypes import GUID -from ctypes import HRESULT -from comtypes import COMMETHOD -from comtypes import wireHWND -UINT_PTR = c_ulong -from objidl import IBindCtx, IMoniker +from ctypes import * # noqa: E402, F403 +WSTRING = c_wchar_p # noqa: F405 +from comtypes import IUnknown # noqa: E402 +LONG_PTR = c_int # noqa: F405 +from comtypes import GUID # noqa: E402 +from ctypes import HRESULT # noqa: E402 +from comtypes import COMMETHOD # noqa: E402 +from comtypes import wireHWND # noqa: E402 +UINT_PTR = c_ulong # noqa: F405 +from objidl import IBindCtx, IMoniker # noqa: E402 -class tagDVTARGETDEVICE(Structure): +class tagDVTARGETDEVICE(Structure): # noqa: F405 pass tagDVTARGETDEVICE._fields_ = [ - ('tdSize', c_ulong), - ('tdDriverNameOffset', c_ushort), - ('tdDeviceNameOffset', c_ushort), - ('tdPortNameOffset', c_ushort), - ('tdExtDevmodeOffset', c_ushort), - ('tdData', POINTER(c_ubyte)), + ('tdSize', c_ulong), # noqa: F405 + ('tdDriverNameOffset', c_ushort), # noqa: F405 + ('tdDeviceNameOffset', c_ushort), # noqa: F405 + ('tdPortNameOffset', c_ushort), # noqa: F405 + ('tdExtDevmodeOffset', c_ushort), # noqa: F405 + ('tdData', POINTER(c_ubyte)), # noqa: F405 ] -assert sizeof(tagDVTARGETDEVICE) == 16, sizeof(tagDVTARGETDEVICE) -assert alignment(tagDVTARGETDEVICE) == 4, alignment(tagDVTARGETDEVICE) -class _BYTE_BLOB(Structure): +assert sizeof(tagDVTARGETDEVICE) == 16, sizeof(tagDVTARGETDEVICE) # noqa: F405 +assert alignment(tagDVTARGETDEVICE) == 4, alignment(tagDVTARGETDEVICE) # noqa: F405 +class _BYTE_BLOB(Structure): # noqa: F405 pass _BYTE_BLOB._fields_ = [ - ('clSize', c_ulong), - ('abData', POINTER(c_ubyte)), + ('clSize', c_ulong), # noqa: F405 + ('abData', POINTER(c_ubyte)), # noqa: F405 ] -assert sizeof(_BYTE_BLOB) == 8, sizeof(_BYTE_BLOB) -assert alignment(_BYTE_BLOB) == 4, alignment(_BYTE_BLOB) -class tagRECT(Structure): +assert sizeof(_BYTE_BLOB) == 8, sizeof(_BYTE_BLOB) # noqa: F405 +assert alignment(_BYTE_BLOB) == 4, alignment(_BYTE_BLOB) # noqa: F405 +class tagRECT(Structure): # noqa: F405 pass tagRECT._fields_ = [ - ('left', c_int), - ('top', c_int), - ('right', c_int), - ('bottom', c_int), + ('left', c_int), # noqa: F405 + ('top', c_int), # noqa: F405 + ('right', c_int), # noqa: F405 + ('bottom', c_int), # noqa: F405 ] -assert sizeof(tagRECT) == 16, sizeof(tagRECT) -assert alignment(tagRECT) == 4, alignment(tagRECT) -class __MIDL_IWinTypes_0003(Union): +assert sizeof(tagRECT) == 16, sizeof(tagRECT) # noqa: F405 +assert alignment(tagRECT) == 4, alignment(tagRECT) # noqa: F405 +class __MIDL_IWinTypes_0003(Union): # noqa: F405 pass -class _FLAGGED_BYTE_BLOB(Structure): +class _FLAGGED_BYTE_BLOB(Structure): # noqa: F405 pass __MIDL_IWinTypes_0003._fields_ = [ - ('hInproc', c_int), - ('hRemote', POINTER(_FLAGGED_BYTE_BLOB)), - ('hInproc64', c_longlong), + ('hInproc', c_int), # noqa: F405 + ('hRemote', POINTER(_FLAGGED_BYTE_BLOB)), # noqa: F405 + ('hInproc64', c_longlong), # noqa: F405 ] -assert sizeof(__MIDL_IWinTypes_0003) == 8, sizeof(__MIDL_IWinTypes_0003) -assert alignment(__MIDL_IWinTypes_0003) == 8, alignment(__MIDL_IWinTypes_0003) -class _userSTGMEDIUM(Structure): +assert sizeof(__MIDL_IWinTypes_0003) == 8, sizeof(__MIDL_IWinTypes_0003) # noqa: F405 +assert alignment(__MIDL_IWinTypes_0003) == 8, alignment(__MIDL_IWinTypes_0003) # noqa: F405 +class _userSTGMEDIUM(Structure): # noqa: F405 pass -class _STGMEDIUM_UNION(Structure): +class _STGMEDIUM_UNION(Structure): # noqa: F405 pass -class __MIDL_IAdviseSink_0003(Union): +class __MIDL_IAdviseSink_0003(Union): # noqa: F405 pass -class _userHMETAFILEPICT(Structure): +class _userHMETAFILEPICT(Structure): # noqa: F405 pass -class _userHENHMETAFILE(Structure): +class _userHENHMETAFILE(Structure): # noqa: F405 pass -class _GDI_OBJECT(Structure): +class _GDI_OBJECT(Structure): # noqa: F405 pass -class _userHGLOBAL(Structure): +class _userHGLOBAL(Structure): # noqa: F405 pass __MIDL_IAdviseSink_0003._fields_ = [ - ('hMetaFilePict', POINTER(_userHMETAFILEPICT)), - ('hHEnhMetaFile', POINTER(_userHENHMETAFILE)), - ('hGdiHandle', POINTER(_GDI_OBJECT)), - ('hGlobal', POINTER(_userHGLOBAL)), + ('hMetaFilePict', POINTER(_userHMETAFILEPICT)), # noqa: F405 + ('hHEnhMetaFile', POINTER(_userHENHMETAFILE)), # noqa: F405 + ('hGdiHandle', POINTER(_GDI_OBJECT)), # noqa: F405 + ('hGlobal', POINTER(_userHGLOBAL)), # noqa: F405 ('lpszFileName', WSTRING), - ('pstm', POINTER(_BYTE_BLOB)), - ('pstg', POINTER(_BYTE_BLOB)), + ('pstm', POINTER(_BYTE_BLOB)), # noqa: F405 + ('pstg', POINTER(_BYTE_BLOB)), # noqa: F405 ] -assert sizeof(__MIDL_IAdviseSink_0003) == 4, sizeof(__MIDL_IAdviseSink_0003) -assert alignment(__MIDL_IAdviseSink_0003) == 4, alignment(__MIDL_IAdviseSink_0003) +assert sizeof(__MIDL_IAdviseSink_0003) == 4, sizeof(__MIDL_IAdviseSink_0003) # noqa: F405 +assert alignment(__MIDL_IAdviseSink_0003) == 4, alignment(__MIDL_IAdviseSink_0003) # noqa: F405 _STGMEDIUM_UNION._fields_ = [ - ('tymed', c_ulong), + ('tymed', c_ulong), # noqa: F405 ('u', __MIDL_IAdviseSink_0003), ] -assert sizeof(_STGMEDIUM_UNION) == 8, sizeof(_STGMEDIUM_UNION) -assert alignment(_STGMEDIUM_UNION) == 4, alignment(_STGMEDIUM_UNION) +assert sizeof(_STGMEDIUM_UNION) == 8, sizeof(_STGMEDIUM_UNION) # noqa: F405 +assert alignment(_STGMEDIUM_UNION) == 4, alignment(_STGMEDIUM_UNION) # noqa: F405 _userSTGMEDIUM._fields_ = [ ('__MIDL__IAdviseSink0003', _STGMEDIUM_UNION), - ('pUnkForRelease', POINTER(IUnknown)), + ('pUnkForRelease', POINTER(IUnknown)), # noqa: F405 ] -assert sizeof(_userSTGMEDIUM) == 12, sizeof(_userSTGMEDIUM) -assert alignment(_userSTGMEDIUM) == 4, alignment(_userSTGMEDIUM) -class tagLOGPALETTE(Structure): +assert sizeof(_userSTGMEDIUM) == 12, sizeof(_userSTGMEDIUM) # noqa: F405 +assert alignment(_userSTGMEDIUM) == 4, alignment(_userSTGMEDIUM) # noqa: F405 +class tagLOGPALETTE(Structure): # noqa: F405 pass -class tagPALETTEENTRY(Structure): +class tagPALETTEENTRY(Structure): # noqa: F405 pass tagLOGPALETTE._pack_ = 2 tagLOGPALETTE._fields_ = [ - ('palVersion', c_ushort), - ('palNumEntries', c_ushort), - ('palPalEntry', POINTER(tagPALETTEENTRY)), + ('palVersion', c_ushort), # noqa: F405 + ('palNumEntries', c_ushort), # noqa: F405 + ('palPalEntry', POINTER(tagPALETTEENTRY)), # noqa: F405 ] -assert sizeof(tagLOGPALETTE) == 8, sizeof(tagLOGPALETTE) -assert alignment(tagLOGPALETTE) == 2, alignment(tagLOGPALETTE) -wireASYNC_STGMEDIUM = POINTER(_userSTGMEDIUM) +assert sizeof(tagLOGPALETTE) == 8, sizeof(tagLOGPALETTE) # noqa: F405 +assert alignment(tagLOGPALETTE) == 2, alignment(tagLOGPALETTE) # noqa: F405 +wireASYNC_STGMEDIUM = POINTER(_userSTGMEDIUM) # noqa: F405 class IEnumOLEVERB(IUnknown): _case_insensitive_ = True _iid_ = GUID('{00000104-0000-0000-C000-000000000046}') _idlflags_ = [] -class tagOLEVERB(Structure): +class tagOLEVERB(Structure): # noqa: F405 pass IEnumOLEVERB._methods_ = [ COMMETHOD([], HRESULT, 'RemoteNext', - ( ['in'], c_ulong, 'celt' ), - ( ['out'], POINTER(tagOLEVERB), 'rgelt' ), - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), + ( ['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' )), + ( ['in'], c_ulong, 'celt' )), # noqa: F405 COMMETHOD([], HRESULT, 'Reset'), COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumOLEVERB)), 'ppenum' )), + ( ['out'], POINTER(POINTER(IEnumOLEVERB)), 'ppenum' )), # noqa: F405 ] class IEnumUnknown(IUnknown): _case_insensitive_ = True @@ -125,77 +125,77 @@ class IEnumUnknown(IUnknown): _idlflags_ = [] IEnumUnknown._methods_ = [ COMMETHOD([], HRESULT, 'RemoteNext', - ( ['in'], c_ulong, 'celt' ), - ( ['out'], POINTER(POINTER(IUnknown)), 'rgelt' ), - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), + ( ['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' )), + ( ['in'], c_ulong, 'celt' )), # noqa: F405 COMMETHOD([], HRESULT, 'Reset'), COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumUnknown)), 'ppenum' )), + ( ['out'], POINTER(POINTER(IEnumUnknown)), 'ppenum' )), # noqa: F405 ] -class _RemotableHandle(Structure): +class _RemotableHandle(Structure): # noqa: F405 pass -class __MIDL_IWinTypes_0009(Union): +class __MIDL_IWinTypes_0009(Union): # noqa: F405 pass __MIDL_IWinTypes_0009._fields_ = [ - ('hInproc', c_int), - ('hRemote', c_int), + ('hInproc', c_int), # noqa: F405 + ('hRemote', c_int), # noqa: F405 ] -assert sizeof(__MIDL_IWinTypes_0009) == 4, sizeof(__MIDL_IWinTypes_0009) -assert alignment(__MIDL_IWinTypes_0009) == 4, alignment(__MIDL_IWinTypes_0009) +assert sizeof(__MIDL_IWinTypes_0009) == 4, sizeof(__MIDL_IWinTypes_0009) # noqa: F405 +assert alignment(__MIDL_IWinTypes_0009) == 4, alignment(__MIDL_IWinTypes_0009) # noqa: F405 _RemotableHandle._fields_ = [ - ('fContext', c_int), + ('fContext', c_int), # noqa: F405 ('u', __MIDL_IWinTypes_0009), ] -assert sizeof(_RemotableHandle) == 8, sizeof(_RemotableHandle) -assert alignment(_RemotableHandle) == 4, alignment(_RemotableHandle) -class _userHMETAFILE(Structure): +assert sizeof(_RemotableHandle) == 8, sizeof(_RemotableHandle) # noqa: F405 +assert alignment(_RemotableHandle) == 4, alignment(_RemotableHandle) # noqa: F405 +class _userHMETAFILE(Structure): # noqa: F405 pass -class __MIDL_IWinTypes_0004(Union): +class __MIDL_IWinTypes_0004(Union): # noqa: F405 pass __MIDL_IWinTypes_0004._fields_ = [ - ('hInproc', c_int), - ('hRemote', POINTER(_BYTE_BLOB)), - ('hInproc64', c_longlong), + ('hInproc', c_int), # noqa: F405 + ('hRemote', POINTER(_BYTE_BLOB)), # noqa: F405 + ('hInproc64', c_longlong), # noqa: F405 ] -assert sizeof(__MIDL_IWinTypes_0004) == 8, sizeof(__MIDL_IWinTypes_0004) -assert alignment(__MIDL_IWinTypes_0004) == 8, alignment(__MIDL_IWinTypes_0004) +assert sizeof(__MIDL_IWinTypes_0004) == 8, sizeof(__MIDL_IWinTypes_0004) # noqa: F405 +assert alignment(__MIDL_IWinTypes_0004) == 8, alignment(__MIDL_IWinTypes_0004) # noqa: F405 _userHMETAFILE._fields_ = [ - ('fContext', c_int), + ('fContext', c_int), # noqa: F405 ('u', __MIDL_IWinTypes_0004), ] -assert sizeof(_userHMETAFILE) == 16, sizeof(_userHMETAFILE) -assert alignment(_userHMETAFILE) == 8, alignment(_userHMETAFILE) -wireSTGMEDIUM = POINTER(_userSTGMEDIUM) -class _userHPALETTE(Structure): +assert sizeof(_userHMETAFILE) == 16, sizeof(_userHMETAFILE) # noqa: F405 +assert alignment(_userHMETAFILE) == 8, alignment(_userHMETAFILE) # noqa: F405 +wireSTGMEDIUM = POINTER(_userSTGMEDIUM) # noqa: F405 +class _userHPALETTE(Structure): # noqa: F405 pass -class __MIDL_IWinTypes_0008(Union): +class __MIDL_IWinTypes_0008(Union): # noqa: F405 pass __MIDL_IWinTypes_0008._fields_ = [ - ('hInproc', c_int), - ('hRemote', POINTER(tagLOGPALETTE)), - ('hInproc64', c_longlong), + ('hInproc', c_int), # noqa: F405 + ('hRemote', POINTER(tagLOGPALETTE)), # noqa: F405 + ('hInproc64', c_longlong), # noqa: F405 ] -assert sizeof(__MIDL_IWinTypes_0008) == 8, sizeof(__MIDL_IWinTypes_0008) -assert alignment(__MIDL_IWinTypes_0008) == 8, alignment(__MIDL_IWinTypes_0008) +assert sizeof(__MIDL_IWinTypes_0008) == 8, sizeof(__MIDL_IWinTypes_0008) # noqa: F405 +assert alignment(__MIDL_IWinTypes_0008) == 8, alignment(__MIDL_IWinTypes_0008) # noqa: F405 _userHPALETTE._fields_ = [ - ('fContext', c_int), + ('fContext', c_int), # noqa: F405 ('u', __MIDL_IWinTypes_0008), ] -assert sizeof(_userHPALETTE) == 16, sizeof(_userHPALETTE) -assert alignment(_userHPALETTE) == 8, alignment(_userHPALETTE) -class __MIDL_IWinTypes_0007(Union): +assert sizeof(_userHPALETTE) == 16, sizeof(_userHPALETTE) # noqa: F405 +assert alignment(_userHPALETTE) == 8, alignment(_userHPALETTE) # noqa: F405 +class __MIDL_IWinTypes_0007(Union): # noqa: F405 pass -class _userBITMAP(Structure): +class _userBITMAP(Structure): # noqa: F405 pass __MIDL_IWinTypes_0007._fields_ = [ - ('hInproc', c_int), - ('hRemote', POINTER(_userBITMAP)), - ('hInproc64', c_longlong), + ('hInproc', c_int), # noqa: F405 + ('hRemote', POINTER(_userBITMAP)), # noqa: F405 + ('hInproc64', c_longlong), # noqa: F405 ] -assert sizeof(__MIDL_IWinTypes_0007) == 8, sizeof(__MIDL_IWinTypes_0007) -assert alignment(__MIDL_IWinTypes_0007) == 8, alignment(__MIDL_IWinTypes_0007) +assert sizeof(__MIDL_IWinTypes_0007) == 8, sizeof(__MIDL_IWinTypes_0007) # noqa: F405 +assert alignment(__MIDL_IWinTypes_0007) == 8, alignment(__MIDL_IWinTypes_0007) # noqa: F405 class IParseDisplayName(IUnknown): _case_insensitive_ = True _iid_ = GUID('{0000011A-0000-0000-C000-000000000046}') @@ -206,17 +206,17 @@ class IOleContainer(IParseDisplayName): _idlflags_ = [] IParseDisplayName._methods_ = [ COMMETHOD([], HRESULT, 'ParseDisplayName', - ( ['in'], POINTER(IBindCtx), 'pbc' ), + ( ['in'], POINTER(IBindCtx), 'pbc' ), # noqa: F405 ( ['in'], WSTRING, 'pszDisplayName' ), - ( ['out'], POINTER(c_ulong), 'pchEaten' ), - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkOut' )), + ( ['out'], POINTER(c_ulong), 'pchEaten' ), # noqa: F405 + ( ['out'], POINTER(POINTER(IMoniker)), 'ppmkOut' )), # noqa: F405 ] IOleContainer._methods_ = [ COMMETHOD([], HRESULT, 'EnumObjects', - ( ['in'], c_ulong, 'grfFlags' ), - ( ['out'], POINTER(POINTER(IEnumUnknown)), 'ppenum' )), + ( ['in'], c_ulong, 'grfFlags' ), # noqa: F405 + ( ['out'], POINTER(POINTER(IEnumUnknown)), 'ppenum' )), # noqa: F405 COMMETHOD([], HRESULT, 'LockContainer', - ( ['in'], c_int, 'fLock' )), + ( ['in'], c_int, 'fLock' )), # noqa: F405 ] class IOleObject(IUnknown): _case_insensitive_ = True @@ -230,9 +230,9 @@ class IDataObject(IUnknown): _case_insensitive_ = True _iid_ = GUID('{0000010E-0000-0000-C000-000000000046}') _idlflags_ = [] -class tagMSG(Structure): +class tagMSG(Structure): # noqa: F405 pass -class tagSIZEL(Structure): +class tagSIZEL(Structure): # noqa: F405 pass class IAdviseSink(IUnknown): _case_insensitive_ = True @@ -244,329 +244,329 @@ class IEnumSTATDATA(IUnknown): _idlflags_ = [] IOleObject._methods_ = [ COMMETHOD([], HRESULT, 'SetClientSite', - ( ['in'], POINTER(IOleClientSite), 'pClientSite' )), + ( ['in'], POINTER(IOleClientSite), 'pClientSite' )), # noqa: F405 COMMETHOD([], HRESULT, 'GetClientSite', - ( ['out'], POINTER(POINTER(IOleClientSite)), 'ppClientSite' )), + ( ['out'], POINTER(POINTER(IOleClientSite)), 'ppClientSite' )), # noqa: F405 COMMETHOD([], HRESULT, 'SetHostNames', ( ['in'], WSTRING, 'szContainerApp' ), ( ['in'], WSTRING, 'szContainerObj' )), COMMETHOD([], HRESULT, 'Close', - ( ['in'], c_ulong, 'dwSaveOption' )), + ( ['in'], c_ulong, 'dwSaveOption' )), # noqa: F405 COMMETHOD([], HRESULT, 'SetMoniker', - ( ['in'], c_ulong, 'dwWhichMoniker' ), - ( ['in'], POINTER(IMoniker), 'pmk' )), + ( ['in'], c_ulong, 'dwWhichMoniker' ), # noqa: F405 + ( ['in'], POINTER(IMoniker), 'pmk' )), # noqa: F405 COMMETHOD([], HRESULT, 'GetMoniker', - ( ['in'], c_ulong, 'dwAssign' ), - ( ['in'], c_ulong, 'dwWhichMoniker' ), - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmk' )), + ( ['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' ), - ( ['in'], c_int, 'fCreation' ), - ( ['in'], c_ulong, 'dwReserved' )), + ( ['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' ), - ( ['out'], POINTER(POINTER(IDataObject)), 'ppDataObject' )), + ( ['in'], c_ulong, 'dwReserved' ), # noqa: F405 + ( ['out'], POINTER(POINTER(IDataObject)), 'ppDataObject' )), # noqa: F405 COMMETHOD([], HRESULT, 'DoVerb', - ( ['in'], c_int, 'iVerb' ), - ( ['in'], POINTER(tagMSG), 'lpmsg' ), - ( ['in'], POINTER(IOleClientSite), 'pActiveSite' ), - ( ['in'], c_int, 'lindex' ), + ( ['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' )), + ( ['in'], POINTER(tagRECT), 'lprcPosRect' )), # noqa: F405 COMMETHOD([], HRESULT, 'EnumVerbs', - ( ['out'], POINTER(POINTER(IEnumOLEVERB)), 'ppEnumOleVerb' )), + ( ['out'], POINTER(POINTER(IEnumOLEVERB)), 'ppEnumOleVerb' )), # noqa: F405 COMMETHOD([], HRESULT, 'Update'), COMMETHOD([], HRESULT, 'IsUpToDate'), COMMETHOD([], HRESULT, 'GetUserClassID', - ( ['out'], POINTER(GUID), 'pClsid' )), + ( ['out'], POINTER(GUID), 'pClsid' )), # noqa: F405 COMMETHOD([], HRESULT, 'GetUserType', - ( ['in'], c_ulong, 'dwFormOfType' ), - ( ['out'], POINTER(WSTRING), 'pszUserType' )), + ( ['in'], c_ulong, 'dwFormOfType' ), # noqa: F405 + ( ['out'], POINTER(WSTRING), 'pszUserType' )), # noqa: F405 COMMETHOD([], HRESULT, 'SetExtent', - ( ['in'], c_ulong, 'dwDrawAspect' ), - ( ['in'], POINTER(tagSIZEL), 'psizel' )), + ( ['in'], c_ulong, 'dwDrawAspect' ), # noqa: F405 + ( ['in'], POINTER(tagSIZEL), 'psizel' )), # noqa: F405 COMMETHOD([], HRESULT, 'GetExtent', - ( ['in'], c_ulong, 'dwDrawAspect' ), - ( ['out'], POINTER(tagSIZEL), 'psizel' )), + ( ['in'], c_ulong, 'dwDrawAspect' ), # noqa: F405 + ( ['out'], POINTER(tagSIZEL), 'psizel' )), # noqa: F405 COMMETHOD([], HRESULT, 'Advise', - ( ['in'], POINTER(IAdviseSink), 'pAdvSink' ), - ( ['out'], POINTER(c_ulong), 'pdwConnection' )), + ( ['in'], POINTER(IAdviseSink), 'pAdvSink' ), # noqa: F405 + ( ['out'], POINTER(c_ulong), 'pdwConnection' )), # noqa: F405 COMMETHOD([], HRESULT, 'Unadvise', - ( ['in'], c_ulong, 'dwConnection' )), + ( ['in'], c_ulong, 'dwConnection' )), # noqa: F405 COMMETHOD([], HRESULT, 'EnumAdvise', - ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenumAdvise' )), + ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenumAdvise' )), # noqa: F405 COMMETHOD([], HRESULT, 'GetMiscStatus', - ( ['in'], c_ulong, 'dwAspect' ), - ( ['out'], POINTER(c_ulong), 'pdwStatus' )), + ( ['in'], c_ulong, 'dwAspect' ), # noqa: F405 + ( ['out'], POINTER(c_ulong), 'pdwStatus' )), # noqa: F405 COMMETHOD([], HRESULT, 'SetColorScheme', - ( ['in'], POINTER(tagLOGPALETTE), 'pLogpal' )), + ( ['in'], POINTER(tagLOGPALETTE), 'pLogpal' )), # noqa: F405 ] -class __MIDL_IWinTypes_0005(Union): +class __MIDL_IWinTypes_0005(Union): # noqa: F405 pass -class _remoteMETAFILEPICT(Structure): +class _remoteMETAFILEPICT(Structure): # noqa: F405 pass __MIDL_IWinTypes_0005._fields_ = [ - ('hInproc', c_int), - ('hRemote', POINTER(_remoteMETAFILEPICT)), - ('hInproc64', c_longlong), + ('hInproc', c_int), # noqa: F405 + ('hRemote', POINTER(_remoteMETAFILEPICT)), # noqa: F405 + ('hInproc64', c_longlong), # noqa: F405 ] -assert sizeof(__MIDL_IWinTypes_0005) == 8, sizeof(__MIDL_IWinTypes_0005) -assert alignment(__MIDL_IWinTypes_0005) == 8, alignment(__MIDL_IWinTypes_0005) +assert sizeof(__MIDL_IWinTypes_0005) == 8, sizeof(__MIDL_IWinTypes_0005) # noqa: F405 +assert alignment(__MIDL_IWinTypes_0005) == 8, alignment(__MIDL_IWinTypes_0005) # noqa: F405 _userHMETAFILEPICT._fields_ = [ - ('fContext', c_int), + ('fContext', c_int), # noqa: F405 ('u', __MIDL_IWinTypes_0005), ] -assert sizeof(_userHMETAFILEPICT) == 16, sizeof(_userHMETAFILEPICT) -assert alignment(_userHMETAFILEPICT) == 8, alignment(_userHMETAFILEPICT) +assert sizeof(_userHMETAFILEPICT) == 16, sizeof(_userHMETAFILEPICT) # noqa: F405 +assert alignment(_userHMETAFILEPICT) == 8, alignment(_userHMETAFILEPICT) # noqa: F405 tagOLEVERB._fields_ = [ - ('lVerb', c_int), + ('lVerb', c_int), # noqa: F405 ('lpszVerbName', WSTRING), - ('fuFlags', c_ulong), - ('grfAttribs', c_ulong), + ('fuFlags', c_ulong), # noqa: F405 + ('grfAttribs', c_ulong), # noqa: F405 ] -assert sizeof(tagOLEVERB) == 16, sizeof(tagOLEVERB) -assert alignment(tagOLEVERB) == 4, alignment(tagOLEVERB) -class _userCLIPFORMAT(Structure): +assert sizeof(tagOLEVERB) == 16, sizeof(tagOLEVERB) # noqa: F405 +assert alignment(tagOLEVERB) == 4, alignment(tagOLEVERB) # noqa: F405 +class _userCLIPFORMAT(Structure): # noqa: F405 pass -class __MIDL_IWinTypes_0001(Union): +class __MIDL_IWinTypes_0001(Union): # noqa: F405 pass __MIDL_IWinTypes_0001._fields_ = [ - ('dwValue', c_ulong), + ('dwValue', c_ulong), # noqa: F405 ('pwszName', WSTRING), ] -assert sizeof(__MIDL_IWinTypes_0001) == 4, sizeof(__MIDL_IWinTypes_0001) -assert alignment(__MIDL_IWinTypes_0001) == 4, alignment(__MIDL_IWinTypes_0001) +assert sizeof(__MIDL_IWinTypes_0001) == 4, sizeof(__MIDL_IWinTypes_0001) # noqa: F405 +assert alignment(__MIDL_IWinTypes_0001) == 4, alignment(__MIDL_IWinTypes_0001) # noqa: F405 _userCLIPFORMAT._fields_ = [ - ('fContext', c_int), + ('fContext', c_int), # noqa: F405 ('u', __MIDL_IWinTypes_0001), ] -assert sizeof(_userCLIPFORMAT) == 8, sizeof(_userCLIPFORMAT) -assert alignment(_userCLIPFORMAT) == 4, alignment(_userCLIPFORMAT) -wireCLIPFORMAT = POINTER(_userCLIPFORMAT) -class __MIDL_IWinTypes_0006(Union): +assert sizeof(_userCLIPFORMAT) == 8, sizeof(_userCLIPFORMAT) # noqa: F405 +assert alignment(_userCLIPFORMAT) == 4, alignment(_userCLIPFORMAT) # noqa: F405 +wireCLIPFORMAT = POINTER(_userCLIPFORMAT) # noqa: F405 +class __MIDL_IWinTypes_0006(Union): # noqa: F405 pass __MIDL_IWinTypes_0006._fields_ = [ - ('hInproc', c_int), - ('hRemote', POINTER(_BYTE_BLOB)), - ('hInproc64', c_longlong), + ('hInproc', c_int), # noqa: F405 + ('hRemote', POINTER(_BYTE_BLOB)), # noqa: F405 + ('hInproc64', c_longlong), # noqa: F405 ] -assert sizeof(__MIDL_IWinTypes_0006) == 8, sizeof(__MIDL_IWinTypes_0006) -assert alignment(__MIDL_IWinTypes_0006) == 8, alignment(__MIDL_IWinTypes_0006) +assert sizeof(__MIDL_IWinTypes_0006) == 8, sizeof(__MIDL_IWinTypes_0006) # noqa: F405 +assert alignment(__MIDL_IWinTypes_0006) == 8, alignment(__MIDL_IWinTypes_0006) # noqa: F405 _userHENHMETAFILE._fields_ = [ - ('fContext', c_int), + ('fContext', c_int), # noqa: F405 ('u', __MIDL_IWinTypes_0006), ] -assert sizeof(_userHENHMETAFILE) == 16, sizeof(_userHENHMETAFILE) -assert alignment(_userHENHMETAFILE) == 8, alignment(_userHENHMETAFILE) -class tagFORMATETC(Structure): +assert sizeof(_userHENHMETAFILE) == 16, sizeof(_userHENHMETAFILE) # noqa: F405 +assert alignment(_userHENHMETAFILE) == 8, alignment(_userHENHMETAFILE) # noqa: F405 +class tagFORMATETC(Structure): # noqa: F405 pass tagFORMATETC._fields_ = [ ('cfFormat', wireCLIPFORMAT), - ('ptd', POINTER(tagDVTARGETDEVICE)), - ('dwAspect', c_ulong), - ('lindex', c_int), - ('tymed', c_ulong), + ('ptd', POINTER(tagDVTARGETDEVICE)), # noqa: F405 + ('dwAspect', c_ulong), # noqa: F405 + ('lindex', c_int), # noqa: F405 + ('tymed', c_ulong), # noqa: F405 ] -assert sizeof(tagFORMATETC) == 20, sizeof(tagFORMATETC) -assert alignment(tagFORMATETC) == 4, alignment(tagFORMATETC) +assert sizeof(tagFORMATETC) == 20, sizeof(tagFORMATETC) # noqa: F405 +assert alignment(tagFORMATETC) == 4, alignment(tagFORMATETC) # noqa: F405 _userHGLOBAL._fields_ = [ - ('fContext', c_int), + ('fContext', c_int), # noqa: F405 ('u', __MIDL_IWinTypes_0003), ] -assert sizeof(_userHGLOBAL) == 16, sizeof(_userHGLOBAL) -assert alignment(_userHGLOBAL) == 8, alignment(_userHGLOBAL) +assert sizeof(_userHGLOBAL) == 16, sizeof(_userHGLOBAL) # noqa: F405 +assert alignment(_userHGLOBAL) == 8, alignment(_userHGLOBAL) # noqa: F405 IOleClientSite._methods_ = [ COMMETHOD([], HRESULT, 'SaveObject'), COMMETHOD([], HRESULT, 'GetMoniker', - ( ['in'], c_ulong, 'dwAssign' ), - ( ['in'], c_ulong, 'dwWhichMoniker' ), - ( ['out'], POINTER(POINTER(IMoniker)), 'ppmk' )), + ( ['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' )), + ( ['out'], POINTER(POINTER(IOleContainer)), 'ppContainer' )), # noqa: F405 COMMETHOD([], HRESULT, 'ShowObject'), COMMETHOD([], HRESULT, 'OnShowWindow', - ( ['in'], c_int, 'fShow' )), + ( ['in'], c_int, 'fShow' )), # noqa: F405 COMMETHOD([], HRESULT, 'RequestNewObjectLayout'), ] -class __MIDL_IAdviseSink_0002(Union): +class __MIDL_IAdviseSink_0002(Union): # noqa: F405 pass -class _userHBITMAP(Structure): +class _userHBITMAP(Structure): # noqa: F405 pass __MIDL_IAdviseSink_0002._fields_ = [ - ('hBitmap', POINTER(_userHBITMAP)), - ('hPalette', POINTER(_userHPALETTE)), - ('hGeneric', POINTER(_userHGLOBAL)), + ('hBitmap', POINTER(_userHBITMAP)), # noqa: F405 + ('hPalette', POINTER(_userHPALETTE)), # noqa: F405 + ('hGeneric', POINTER(_userHGLOBAL)), # noqa: F405 ] -assert sizeof(__MIDL_IAdviseSink_0002) == 4, sizeof(__MIDL_IAdviseSink_0002) -assert alignment(__MIDL_IAdviseSink_0002) == 4, alignment(__MIDL_IAdviseSink_0002) +assert sizeof(__MIDL_IAdviseSink_0002) == 4, sizeof(__MIDL_IAdviseSink_0002) # noqa: F405 +assert alignment(__MIDL_IAdviseSink_0002) == 4, alignment(__MIDL_IAdviseSink_0002) # noqa: F405 _GDI_OBJECT._fields_ = [ - ('ObjectType', c_ulong), + ('ObjectType', c_ulong), # noqa: F405 ('u', __MIDL_IAdviseSink_0002), ] -assert sizeof(_GDI_OBJECT) == 8, sizeof(_GDI_OBJECT) -assert alignment(_GDI_OBJECT) == 4, alignment(_GDI_OBJECT) -class _userFLAG_STGMEDIUM(Structure): +assert sizeof(_GDI_OBJECT) == 8, sizeof(_GDI_OBJECT) # noqa: F405 +assert alignment(_GDI_OBJECT) == 4, alignment(_GDI_OBJECT) # noqa: F405 +class _userFLAG_STGMEDIUM(Structure): # noqa: F405 pass -wireFLAG_STGMEDIUM = POINTER(_userFLAG_STGMEDIUM) +wireFLAG_STGMEDIUM = POINTER(_userFLAG_STGMEDIUM) # noqa: F405 class IEnumFORMATETC(IUnknown): _case_insensitive_ = True _iid_ = GUID('{00000103-0000-0000-C000-000000000046}') _idlflags_ = [] IDataObject._methods_ = [ COMMETHOD([], HRESULT, 'GetData', - ( ['in'], POINTER(tagFORMATETC), 'pformatetcIn' ), - ( ['out'], POINTER(wireSTGMEDIUM), 'pmedium' )), + ( ['in'], POINTER(tagFORMATETC), 'pformatetcIn' ), # noqa: F405 + ( ['out'], POINTER(wireSTGMEDIUM), 'pmedium' )), # noqa: F405 COMMETHOD([], HRESULT, 'RemoteGetData', - ( ['in'], POINTER(tagFORMATETC), 'pformatetcIn' ), - ( ['out'], POINTER(wireSTGMEDIUM), 'pRemoteMedium' )), + ( ['in'], POINTER(tagFORMATETC), 'pformatetcIn' ), # noqa: F405 + ( ['out'], POINTER(wireSTGMEDIUM), 'pRemoteMedium' )), # noqa: F405 COMMETHOD([], HRESULT, 'RemoteGetDataHere', - ( ['in'], POINTER(tagFORMATETC), 'pformatetc' ), - ( ['in', 'out'], POINTER(wireSTGMEDIUM), 'pRemoteMedium' )), + ( ['in'], POINTER(tagFORMATETC), 'pformatetc' ), # noqa: F405 + ( ['in', 'out'], POINTER(wireSTGMEDIUM), 'pRemoteMedium' )), # noqa: F405 COMMETHOD([], HRESULT, 'QueryGetData', - ( ['in'], POINTER(tagFORMATETC), 'pformatetc' )), + ( ['in'], POINTER(tagFORMATETC), 'pformatetc' )), # noqa: F405 COMMETHOD([], HRESULT, 'GetCanonicalFormatEtc', - ( ['in'], POINTER(tagFORMATETC), 'pformatectIn' ), - ( ['out'], POINTER(tagFORMATETC), 'pformatetcOut' )), + ( ['in'], POINTER(tagFORMATETC), 'pformatectIn' ), # noqa: F405 + ( ['out'], POINTER(tagFORMATETC), 'pformatetcOut' )), # noqa: F405 COMMETHOD([], HRESULT, 'RemoteSetData', - ( ['in'], POINTER(tagFORMATETC), 'pformatetc' ), - ( ['in'], POINTER(wireFLAG_STGMEDIUM), 'pmedium' ), - ( ['in'], c_int, 'fRelease' )), + ( ['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' ), - ( ['out'], POINTER(POINTER(IEnumFORMATETC)), 'ppenumFormatEtc' )), + ( ['in'], c_ulong, 'dwDirection' ), # noqa: F405 + ( ['out'], POINTER(POINTER(IEnumFORMATETC)), 'ppenumFormatEtc' )), # noqa: F405 COMMETHOD([], HRESULT, 'DAdvise', - ( ['in'], POINTER(tagFORMATETC), 'pformatetc' ), - ( ['in'], c_ulong, 'advf' ), - ( ['in'], POINTER(IAdviseSink), 'pAdvSink' ), - ( ['out'], POINTER(c_ulong), 'pdwConnection' )), + ( ['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' )), + ( ['in'], c_ulong, 'dwConnection' )), # noqa: F405 COMMETHOD([], HRESULT, 'EnumDAdvise', - ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenumAdvise' )), + ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenumAdvise' )), # noqa: F405 ] -class tagPOINT(Structure): +class tagPOINT(Structure): # noqa: F405 pass tagPOINT._fields_ = [ - ('x', c_int), - ('y', c_int), + ('x', c_int), # noqa: F405 + ('y', c_int), # noqa: F405 ] -assert sizeof(tagPOINT) == 8, sizeof(tagPOINT) -assert alignment(tagPOINT) == 4, alignment(tagPOINT) +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' ), - ( ['in'], POINTER(wireASYNC_STGMEDIUM), 'pStgmed' )), + ( ['in'], POINTER(tagFORMATETC), 'pformatetc' ), # noqa: F405 + ( ['in'], POINTER(wireASYNC_STGMEDIUM), 'pStgmed' )), # noqa: F405 COMMETHOD([], HRESULT, 'RemoteOnViewChange', - ( ['in'], c_ulong, 'dwAspect' ), - ( ['in'], c_int, 'lindex' )), + ( ['in'], c_ulong, 'dwAspect' ), # noqa: F405 + ( ['in'], c_int, 'lindex' )), # noqa: F405 COMMETHOD([], HRESULT, 'RemoteOnRename', - ( ['in'], POINTER(IMoniker), 'pmk' )), + ( ['in'], POINTER(IMoniker), 'pmk' )), # noqa: F405 COMMETHOD([], HRESULT, 'RemoteOnSave'), COMMETHOD([], HRESULT, 'RemoteOnClose'), ] -class __MIDL___MIDL_itf_oleTypes_0005_0001_0001(Structure): +class __MIDL___MIDL_itf_oleTypes_0005_0001_0001(Structure): # noqa: F405 pass __MIDL___MIDL_itf_oleTypes_0005_0001_0001._fields_ = [ - ('Data1', c_ulong), - ('Data2', c_ushort), - ('Data3', c_ushort), - ('Data4', c_ubyte * 8), + ('Data1', c_ulong), # noqa: F405 + ('Data2', c_ushort), # noqa: F405 + ('Data3', c_ushort), # noqa: F405 + ('Data4', c_ubyte * 8), # noqa: F405 ] -assert sizeof(__MIDL___MIDL_itf_oleTypes_0005_0001_0001) == 16, sizeof(__MIDL___MIDL_itf_oleTypes_0005_0001_0001) -assert alignment(__MIDL___MIDL_itf_oleTypes_0005_0001_0001) == 4, alignment(__MIDL___MIDL_itf_oleTypes_0005_0001_0001) +assert sizeof(__MIDL___MIDL_itf_oleTypes_0005_0001_0001) == 16, sizeof(__MIDL___MIDL_itf_oleTypes_0005_0001_0001) # noqa: F405 +assert alignment(__MIDL___MIDL_itf_oleTypes_0005_0001_0001) == 4, alignment(__MIDL___MIDL_itf_oleTypes_0005_0001_0001) # noqa: F405 _userFLAG_STGMEDIUM._fields_ = [ - ('ContextFlags', c_int), - ('fPassOwnership', c_int), + ('ContextFlags', c_int), # noqa: F405 + ('fPassOwnership', c_int), # noqa: F405 ('Stgmed', _userSTGMEDIUM), ] -assert sizeof(_userFLAG_STGMEDIUM) == 20, sizeof(_userFLAG_STGMEDIUM) -assert alignment(_userFLAG_STGMEDIUM) == 4, alignment(_userFLAG_STGMEDIUM) -class tagSTATDATA(Structure): +assert sizeof(_userFLAG_STGMEDIUM) == 20, sizeof(_userFLAG_STGMEDIUM) # noqa: F405 +assert alignment(_userFLAG_STGMEDIUM) == 4, alignment(_userFLAG_STGMEDIUM) # noqa: F405 +class tagSTATDATA(Structure): # noqa: F405 pass IEnumSTATDATA._methods_ = [ COMMETHOD([], HRESULT, 'RemoteNext', - ( ['in'], c_ulong, 'celt' ), - ( ['out'], POINTER(tagSTATDATA), 'rgelt' ), - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), + ( ['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' )), + ( ['in'], c_ulong, 'celt' )), # noqa: F405 COMMETHOD([], HRESULT, 'Reset'), COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenum' )), + ( ['out'], POINTER(POINTER(IEnumSTATDATA)), 'ppenum' )), # noqa: F405 ] tagSIZEL._fields_ = [ - ('cx', c_int), - ('cy', c_int), + ('cx', c_int), # noqa: F405 + ('cy', c_int), # noqa: F405 ] -assert sizeof(tagSIZEL) == 8, sizeof(tagSIZEL) -assert alignment(tagSIZEL) == 4, alignment(tagSIZEL) +assert sizeof(tagSIZEL) == 8, sizeof(tagSIZEL) # noqa: F405 +assert alignment(tagSIZEL) == 4, alignment(tagSIZEL) # noqa: F405 tagMSG._fields_ = [ ('hwnd', wireHWND), - ('message', c_uint), + ('message', c_uint), # noqa: F405 ('wParam', UINT_PTR), ('lParam', LONG_PTR), - ('time', c_ulong), + ('time', c_ulong), # noqa: F405 ('pt', tagPOINT), ] -assert sizeof(tagMSG) == 28, sizeof(tagMSG) -assert alignment(tagMSG) == 4, alignment(tagMSG) +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' ), - ( ['out'], POINTER(tagFORMATETC), 'rgelt' ), - ( ['out'], POINTER(c_ulong), 'pceltFetched' )), + ( ['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' )), + ( ['in'], c_ulong, 'celt' )), # noqa: F405 COMMETHOD([], HRESULT, 'Reset'), COMMETHOD([], HRESULT, 'Clone', - ( ['out'], POINTER(POINTER(IEnumFORMATETC)), 'ppenum' )), + ( ['out'], POINTER(POINTER(IEnumFORMATETC)), 'ppenum' )), # noqa: F405 ] _FLAGGED_BYTE_BLOB._fields_ = [ - ('fFlags', c_ulong), - ('clSize', c_ulong), - ('abData', POINTER(c_ubyte)), + ('fFlags', c_ulong), # noqa: F405 + ('clSize', c_ulong), # noqa: F405 + ('abData', POINTER(c_ubyte)), # noqa: F405 ] -assert sizeof(_FLAGGED_BYTE_BLOB) == 12, sizeof(_FLAGGED_BYTE_BLOB) -assert alignment(_FLAGGED_BYTE_BLOB) == 4, alignment(_FLAGGED_BYTE_BLOB) +assert sizeof(_FLAGGED_BYTE_BLOB) == 12, sizeof(_FLAGGED_BYTE_BLOB) # noqa: F405 +assert alignment(_FLAGGED_BYTE_BLOB) == 4, alignment(_FLAGGED_BYTE_BLOB) # noqa: F405 _userBITMAP._fields_ = [ - ('bmType', c_int), - ('bmWidth', c_int), - ('bmHeight', c_int), - ('bmWidthBytes', c_int), - ('bmPlanes', c_ushort), - ('bmBitsPixel', c_ushort), - ('cbSize', c_ulong), - ('pBuffer', POINTER(c_ubyte)), -] -assert sizeof(_userBITMAP) == 28, sizeof(_userBITMAP) -assert alignment(_userBITMAP) == 4, alignment(_userBITMAP) + ('bmType', c_int), # noqa: F405 + ('bmWidth', c_int), # noqa: F405 + ('bmHeight', c_int), # noqa: F405 + ('bmWidthBytes', c_int), # noqa: F405 + ('bmPlanes', c_ushort), # noqa: F405 + ('bmBitsPixel', c_ushort), # noqa: F405 + ('cbSize', c_ulong), # noqa: F405 + ('pBuffer', POINTER(c_ubyte)), # noqa: F405 +] +assert sizeof(_userBITMAP) == 28, sizeof(_userBITMAP) # noqa: F405 +assert alignment(_userBITMAP) == 4, alignment(_userBITMAP) # noqa: F405 _remoteMETAFILEPICT._fields_ = [ - ('mm', c_int), - ('xExt', c_int), - ('yExt', c_int), - ('hMF', POINTER(_userHMETAFILE)), + ('mm', c_int), # noqa: F405 + ('xExt', c_int), # noqa: F405 + ('yExt', c_int), # noqa: F405 + ('hMF', POINTER(_userHMETAFILE)), # noqa: F405 ] -assert sizeof(_remoteMETAFILEPICT) == 16, sizeof(_remoteMETAFILEPICT) -assert alignment(_remoteMETAFILEPICT) == 4, alignment(_remoteMETAFILEPICT) +assert sizeof(_remoteMETAFILEPICT) == 16, sizeof(_remoteMETAFILEPICT) # noqa: F405 +assert alignment(_remoteMETAFILEPICT) == 4, alignment(_remoteMETAFILEPICT) # noqa: F405 tagSTATDATA._fields_ = [ ('formatetc', tagFORMATETC), - ('advf', c_ulong), - ('pAdvSink', POINTER(IAdviseSink)), - ('dwConnection', c_ulong), + ('advf', c_ulong), # noqa: F405 + ('pAdvSink', POINTER(IAdviseSink)), # noqa: F405 + ('dwConnection', c_ulong), # noqa: F405 ] -assert sizeof(tagSTATDATA) == 32, sizeof(tagSTATDATA) -assert alignment(tagSTATDATA) == 4, alignment(tagSTATDATA) +assert sizeof(tagSTATDATA) == 32, sizeof(tagSTATDATA) # noqa: F405 +assert alignment(tagSTATDATA) == 4, alignment(tagSTATDATA) # noqa: F405 _userHBITMAP._fields_ = [ - ('fContext', c_int), + ('fContext', c_int), # noqa: F405 ('u', __MIDL_IWinTypes_0007), ] -assert sizeof(_userHBITMAP) == 16, sizeof(_userHBITMAP) -assert alignment(_userHBITMAP) == 8, alignment(_userHBITMAP) +assert sizeof(_userHBITMAP) == 16, sizeof(_userHBITMAP) # noqa: F405 +assert alignment(_userHBITMAP) == 8, alignment(_userHBITMAP) # noqa: F405 tagPALETTEENTRY._fields_ = [ - ('peRed', c_ubyte), - ('peGreen', c_ubyte), - ('peBlue', c_ubyte), - ('peFlags', c_ubyte), + ('peRed', c_ubyte), # noqa: F405 + ('peGreen', c_ubyte), # noqa: F405 + ('peBlue', c_ubyte), # noqa: F405 + ('peFlags', c_ubyte), # noqa: F405 ] -assert sizeof(tagPALETTEENTRY) == 4, sizeof(tagPALETTEENTRY) -assert alignment(tagPALETTEENTRY) == 1, alignment(tagPALETTEENTRY) +assert sizeof(tagPALETTEENTRY) == 4, sizeof(tagPALETTEENTRY) # noqa: F405 +assert alignment(tagPALETTEENTRY) == 1, alignment(tagPALETTEENTRY) # noqa: F405 diff --git a/source/oleacc.py b/source/oleacc.py index ac04459dc78..3744ee4ce5b 100644 --- a/source/oleacc.py +++ b/source/oleacc.py @@ -1,7 +1,7 @@ -from ctypes import * -from ctypes.wintypes import * -from comtypes import * -from comtypes.automation import * +from ctypes import * # noqa: F403 +from ctypes.wintypes import * # noqa: F403 +from comtypes import * # noqa: F403 +from comtypes.automation import * # noqa: F403 import comtypes.client import winUser # Include functions from oleacc.dll in the module namespace. @@ -130,27 +130,27 @@ # GUIDS for IAccessible properties that can be overridden by means of annotation. #Use these to look up the GUID needed when implementing a server. #Number of digits Format: "{8-4-4-4-12}" -PROPID_ACC_NAME = GUID("{608d3df8-8128-4aa7-a428-f55e49267291}") -PROPID_ACC_VALUE = GUID("{123fe443-211a-4615-9527-c45a7e93717a}") -PROPID_ACC_DESCRIPTION = GUID("{4d48dfe4-bd3f-491f-a648-492d6f20c588}") -PROPID_ACC_ROLE = GUID("{CB905FF2-7BD1-4C05-B3C8-E6C241364D70}") -PROPID_ACC_STATE = GUID("{A8D4D5B0-0A21-42D0-A5C0-514E984F457B}") -PROPID_ACC_HELP = GUID("{c831e11f-44db-4a99-9768-cb8f978b7231}") -PROPID_ACC_KEYBOARDSHORTCUT = GUID("{7d9bceee-7d1e-4979-9382-5180f4172c34}") -PROPID_ACC_DEFAULTACTION = GUID("{180c072b-c27f-43c7-9922-f63562a4632b}") -PROPID_ACC_VALUEMAP = GUID("{da1c3d79-fc5c-420e-b399-9d1533549e75}") -PROPID_ACC_ROLEMAP = GUID("{f79acda2-140d-4fe6-8914-208476328269}") -PROPID_ACC_STATEMAP = GUID("{43946c5e-0ac0-4042-b525-07bbdbe17fa7}") -PROPID_ACC_FOCUS = GUID("{6eb335df-1c29-4127-b12c-dee9fd157f2b}") -PROPID_ACC_SELECTION = GUID("{b99d073c-d731-405b-9061-d95e8f842984}") -PROPID_ACC_PARENT = GUID("{474c22b6-ffc2-467a-b1b5-e958b4657330}") -PROPID_ACC_NAV_UP = GUID("{016e1a2b-1a4e-4767-8612-3386f66935ec}") -PROPID_ACC_NAV_LEFT = GUID("{228086cb-82f1-4a39-8705-dcdc0fff92f5}") -PROPID_ACC_NAV_RIGHT = GUID("{cd211d9f-e1cb-4fe5-a77c-920b884d095b}") -PROPID_ACC_NAV_PREV = GUID("{776d3891-c73b-4480-b3f6-076a16a15af6}") -PROPID_ACC_NAV_NEXT = GUID("{1cdc5455-8cd9-4c92-a371-3939a2fe3eee}") -PROPID_ACC_NAV_FIRSTCHILD = GUID("{cfd02558-557b-4c67-84f9-2a09fce40749}") -PROPID_ACC_NAV_LASTCHILD = GUID("{302ecaa5-48d5-4f8d-b671-1a8d20a77832}") +PROPID_ACC_NAME = GUID("{608d3df8-8128-4aa7-a428-f55e49267291}") # noqa: F405 +PROPID_ACC_VALUE = GUID("{123fe443-211a-4615-9527-c45a7e93717a}") # noqa: F405 +PROPID_ACC_DESCRIPTION = GUID("{4d48dfe4-bd3f-491f-a648-492d6f20c588}") # noqa: F405 +PROPID_ACC_ROLE = GUID("{CB905FF2-7BD1-4C05-B3C8-E6C241364D70}") # noqa: F405 +PROPID_ACC_STATE = GUID("{A8D4D5B0-0A21-42D0-A5C0-514E984F457B}") # noqa: F405 +PROPID_ACC_HELP = GUID("{c831e11f-44db-4a99-9768-cb8f978b7231}") # noqa: F405 +PROPID_ACC_KEYBOARDSHORTCUT = GUID("{7d9bceee-7d1e-4979-9382-5180f4172c34}") # noqa: F405 +PROPID_ACC_DEFAULTACTION = GUID("{180c072b-c27f-43c7-9922-f63562a4632b}") # noqa: F405 +PROPID_ACC_VALUEMAP = GUID("{da1c3d79-fc5c-420e-b399-9d1533549e75}") # noqa: F405 +PROPID_ACC_ROLEMAP = GUID("{f79acda2-140d-4fe6-8914-208476328269}") # noqa: F405 +PROPID_ACC_STATEMAP = GUID("{43946c5e-0ac0-4042-b525-07bbdbe17fa7}") # noqa: F405 +PROPID_ACC_FOCUS = GUID("{6eb335df-1c29-4127-b12c-dee9fd157f2b}") # noqa: F405 +PROPID_ACC_SELECTION = GUID("{b99d073c-d731-405b-9061-d95e8f842984}") # noqa: F405 +PROPID_ACC_PARENT = GUID("{474c22b6-ffc2-467a-b1b5-e958b4657330}") # noqa: F405 +PROPID_ACC_NAV_UP = GUID("{016e1a2b-1a4e-4767-8612-3386f66935ec}") # noqa: F405 +PROPID_ACC_NAV_LEFT = GUID("{228086cb-82f1-4a39-8705-dcdc0fff92f5}") # noqa: F405 +PROPID_ACC_NAV_RIGHT = GUID("{cd211d9f-e1cb-4fe5-a77c-920b884d095b}") # noqa: F405 +PROPID_ACC_NAV_PREV = GUID("{776d3891-c73b-4480-b3f6-076a16a15af6}") # noqa: F405 +PROPID_ACC_NAV_NEXT = GUID("{1cdc5455-8cd9-4c92-a371-3939a2fe3eee}") # noqa: F405 +PROPID_ACC_NAV_FIRSTCHILD = GUID("{cfd02558-557b-4c67-84f9-2a09fce40749}") # noqa: F405 +PROPID_ACC_NAV_LASTCHILD = GUID("{302ecaa5-48d5-4f8d-b671-1a8d20a77832}") # noqa: F405 def LresultFromObject(wParam,obj): """ @@ -164,7 +164,7 @@ def LresultFromObject(wParam,obj): @rtype: int """ objIID=obj._iid_ - return oledll.oleacc.LresultFromObject(byref(objIID),wParam,obj) + return oledll.oleacc.LresultFromObject(byref(objIID),wParam,obj) # noqa: F405 def ObjectFromLresult(res,wParam,interface): """ @@ -179,11 +179,11 @@ def ObjectFromLresult(res,wParam,interface): @return: the object. @rtype: COMObject """ - p=POINTER(interface)() - oledll.oleacc.ObjectFromLresult(res,byref(interface._iid_),wParam,byref(p)) + p=POINTER(interface)() # noqa: F405 + oledll.oleacc.ObjectFromLresult(res,byref(interface._iid_),wParam,byref(p)) # noqa: F405 return p -def CreateStdAccessibleProxy(hwnd,className,objectID,interface=IAccessible): +def CreateStdAccessibleProxy(hwnd,className,objectID,interface=IAccessible): # noqa: F405 """ creates an accessible object using a specific window class, with the methods and properties of the specified type of system-provided user interface element. @@ -198,11 +198,11 @@ def CreateStdAccessibleProxy(hwnd,className,objectID,interface=IAccessible): @return: the created object. @rtype: COMObject """ - p=POINTER(interface)() - oledll.oleacc.CreateStdAccessibleProxyW(hwnd,className,objectID,byref(interface._iid_),byref(p)) + p=POINTER(interface)() # noqa: F405 + oledll.oleacc.CreateStdAccessibleProxyW(hwnd,className,objectID,byref(interface._iid_),byref(p)) # noqa: F405 return p -def CreateStdAccessibleObject(hwnd,objectID,interface=IAccessible): +def CreateStdAccessibleObject(hwnd,objectID,interface=IAccessible): # noqa: F405 """ creates an accessible object with the methods and properties of the specified type of system-provided user interface element. @@ -215,11 +215,11 @@ def CreateStdAccessibleObject(hwnd,objectID,interface=IAccessible): @return: the created object. @rtype: COMObject """ - p=POINTER(interface)() - oledll.oleacc.CreateStdAccessibleObject(hwnd,objectID,byref(interface._iid_),byref(p)) + p=POINTER(interface)() # noqa: F405 + oledll.oleacc.CreateStdAccessibleObject(hwnd,objectID,byref(interface._iid_),byref(p)) # noqa: F405 return p -def AccessibleObjectFromWindow(hwnd,objectID,interface=IAccessible): +def AccessibleObjectFromWindow(hwnd,objectID,interface=IAccessible): # noqa: F405 """ Retreaves a COM object from the given window, with the given object ID. @param hwnd: the handle of the window to retreave the object from. @@ -231,15 +231,15 @@ def AccessibleObjectFromWindow(hwnd,objectID,interface=IAccessible): @return: the retreaved object. @rtype: COMObject """ - p=POINTER(interface)() - oledll.oleacc.AccessibleObjectFromWindow(hwnd,objectID,byref(p._iid_),byref(p)) + p=POINTER(interface)() # noqa: F405 + oledll.oleacc.AccessibleObjectFromWindow(hwnd,objectID,byref(p._iid_),byref(p)) # noqa: F405 return p -def AccessibleObjectFromWindow_safe(hwnd,objectID,interface=IAccessible,timeout=2): +def AccessibleObjectFromWindow_safe(hwnd,objectID,interface=IAccessible,timeout=2): # noqa: F405 if not hwnd: raise ValueError("Invalid window") - wmResult=c_long() - res=windll.user32.SendMessageTimeoutW(hwnd,winUser.WM_GETOBJECT,0,objectID,winUser.SMTO_ABORTIFHUNG,int(timeout*1000),byref(wmResult))==0 + wmResult=c_long() # noqa: F405 + res=windll.user32.SendMessageTimeoutW(hwnd,winUser.WM_GETOBJECT,0,objectID,winUser.SMTO_ABORTIFHUNG,int(timeout*1000),byref(wmResult))==0 # noqa: F405 if res: raise OSError("WM_GETOBJECT failed") if wmResult.value: @@ -258,10 +258,10 @@ def AccessibleObjectFromEvent(hwnd,objectID,childID): @return: the retreaved object. @rtype: COMObject """ - p=POINTER(IAccessible)() - varChild=VARIANT() - oledll.oleacc.AccessibleObjectFromEvent(hwnd,objectID,childID,byref(p),byref(varChild)) - if varChild.vt==VT_I4: + p=POINTER(IAccessible)() # noqa: F405 + varChild=VARIANT() # noqa: F405 + oledll.oleacc.AccessibleObjectFromEvent(hwnd,objectID,childID,byref(p),byref(varChild)) # noqa: F405 + if varChild.vt==VT_I4: # noqa: F405 childID=varChild.value return (p,childID) @@ -272,7 +272,7 @@ def AccessibleObjectFromEvent_safe(hwnd,objectID,childID,timeout=2): if childID!=0: try: childObj=obj.accChild(childID) - except COMError: + except COMError: # noqa: F405 childObj=None if childObj: obj=childObj @@ -287,15 +287,15 @@ def WindowFromAccessibleObject(pacc): @return: the window handle. @rtype: int """ - hwnd=c_int() - oledll.oleacc.WindowFromAccessibleObject(pacc,byref(hwnd)) + hwnd=c_int() # noqa: F405 + oledll.oleacc.WindowFromAccessibleObject(pacc,byref(hwnd)) # noqa: F405 return hwnd.value def AccessibleObjectFromPoint(x,y): - point=POINT(x,y) - pacc=POINTER(IAccessible)() - varChild=VARIANT() - oledll.oleacc.AccessibleObjectFromPoint(point,byref(pacc),byref(varChild)) + point=POINT(x,y) # noqa: F405 + pacc=POINTER(IAccessible)() # noqa: F405 + varChild=VARIANT() # noqa: F405 + oledll.oleacc.AccessibleObjectFromPoint(point,byref(pacc),byref(varChild)) # noqa: F405 if not isinstance(varChild.value,int): child=0 else: @@ -303,9 +303,9 @@ def AccessibleObjectFromPoint(x,y): return (pacc,child) def AccessibleChildren(pacc,iChildStart,cChildren): - varChildren=(VARIANT*cChildren)() - pcObtained=c_int() - oledll.oleacc.AccessibleChildren(pacc,iChildStart,cChildren,byref(varChildren),byref(pcObtained)) + varChildren=(VARIANT*cChildren)() # noqa: F405 + pcObtained=c_int() # noqa: F405 + oledll.oleacc.AccessibleChildren(pacc,iChildStart,cChildren,byref(varChildren),byref(pcObtained)) # noqa: F405 return [x.value for x in varChildren[0:pcObtained.value]] def GetProcessHandleFromHwnd(windowHandle): @@ -316,22 +316,22 @@ def GetProcessHandleFromHwnd(windowHandle): @returns: a process handle with read, write and operation access @rtype: integer """ - return oledll.oleacc.GetProcessHandleFromHwnd(windowHandle) + return oledll.oleacc.GetProcessHandleFromHwnd(windowHandle) # noqa: F405 def GetRoleText(role): - textLen=oledll.oleacc.GetRoleTextW(role,0,0) + textLen=oledll.oleacc.GetRoleTextW(role,0,0) # noqa: F405 if textLen: - buf=create_unicode_buffer(textLen+2) - oledll.oleacc.GetRoleTextW(role,buf,textLen+1) + buf=create_unicode_buffer(textLen+2) # noqa: F405 + oledll.oleacc.GetRoleTextW(role,buf,textLen+1) # noqa: F405 return buf.value else: return None def GetStateText(state): - textLen=oledll.oleacc.GetStateTextW(state,0,0) + textLen=oledll.oleacc.GetStateTextW(state,0,0) # noqa: F405 if textLen: - buf=create_unicode_buffer(textLen+2) - oledll.oleacc.GetStateTextW(state,buf,textLen+1) + buf=create_unicode_buffer(textLen+2) # noqa: F405 + oledll.oleacc.GetStateTextW(state,buf,textLen+1) # noqa: F405 return buf.value else: return None diff --git a/source/pythonConsole.py b/source/pythonConsole.py index 7cb76ae1ddc..84cc66c0def 100755 --- a/source/pythonConsole.py +++ b/source/pythonConsole.py @@ -10,25 +10,25 @@ To use, call L{initialize} to create a singleton instance of the console GUI. This can then be accessed externally as L{consoleUI}. """ -import builtins -import os -from typing import Sequence -import code -import codeop -import sys -import pydoc -import re -import itertools -import rlcompleter -import wx -from baseObject import AutoPropertyObject -import speech -import queueHandler -import api -import gui -from logHandler import log -import braille -import gui.contextHelp +import builtins # noqa: E402 +import os # noqa: E402 +from typing import Sequence # noqa: E402 +import code # noqa: E402 +import codeop # noqa: E402 +import sys # noqa: E402 +import pydoc # noqa: E402 +import re # noqa: E402 +import itertools # noqa: E402 +import rlcompleter # noqa: E402 +import wx # noqa: E402 +from baseObject import AutoPropertyObject # noqa: E402 +import speech # noqa: E402 +import queueHandler # noqa: E402 +import api # noqa: E402 +import gui # noqa: E402 +from logHandler import log # noqa: E402 +import braille # noqa: E402 +import gui.contextHelp # noqa: E402 class HelpCommand(object): """ diff --git a/source/queueHandler.py b/source/queueHandler.py index 433a88e2cba..8d806290e4e 100644 --- a/source/queueHandler.py +++ b/source/queueHandler.py @@ -61,7 +61,7 @@ def flushQueue(queue): watchdog.alive() try: func(*args,**kwargs) - except: + except: # noqa: E722 log.exception(f"Error in func {func.__qualname__}") def isPendingItems(queue): @@ -86,7 +86,7 @@ def pumpAll(): except StopIteration: log.debug("generator %s finished"%ID) del generators[ID] - except: + except: # noqa: E722 log.exception("error in generator %d"%ID) del generators[ID] # Lose our reference so Python can destroy the generator if appropriate. diff --git a/source/remotePythonConsole.py b/source/remotePythonConsole.py index eb6be491f21..473ea924eaa 100644 --- a/source/remotePythonConsole.py +++ b/source/remotePythonConsole.py @@ -64,7 +64,7 @@ def handle(self): self._execDoneEvt.wait() self._execDoneEvt.clear() - except: + except: # noqa: E722 log.exception("Error handling remote Python console request") finally: # Clean up the console. diff --git a/source/review.py b/source/review.py index 538160f55e2..2daa7aaaf2b 100644 --- a/source/review.py +++ b/source/review.py @@ -66,7 +66,7 @@ def getScreenPosition(obj): focus=api.getFocusObject() while focus and not isinstance(focus,Window): focus=focus.parent - if not focus: return None + if not focus: return None # noqa: E701 w=winUser.getAncestor(focus.windowHandle,winUser.GA_ROOT) or focus.windowHandle s=Window(windowHandle=w) if s: diff --git a/source/screenExplorer.py b/source/screenExplorer.py index 57313326529..15515696a6b 100644 --- a/source/screenExplorer.py +++ b/source/screenExplorer.py @@ -61,7 +61,7 @@ def moveTo( # noqa: C901 pos=obj.makeTextInfo(locationHelper.Point(x,y)) except (NotImplementedError,LookupError): pass - if pos: pos.expand(unit) + if pos: pos.expand(unit) # noqa: E701 if pos and self.updateReview: api.setReviewPosition(pos) speechCanceled=False diff --git a/source/scriptHandler.py b/source/scriptHandler.py index 6c34dfc36c1..d34b0928d69 100644 --- a/source/scriptHandler.py +++ b/source/scriptHandler.py @@ -49,7 +49,7 @@ def _makeKbEmulateScript(scriptName): import keyboardHandler keyName = scriptName[3:] emuGesture = keyboardHandler.KeyboardInputGesture.fromName(keyName) - func = lambda gesture: inputCore.manager.emulateGesture(emuGesture) + func = lambda gesture: inputCore.manager.emulateGesture(emuGesture) # noqa: E731 func.__name__ = "script_%s" % scriptName func.__doc__ = _("Emulates pressing %s on the system keyboard") % emuGesture.displayName return func @@ -293,7 +293,7 @@ def executeScript(script,gesture): _lastScriptRef=scriptRef _lastScriptTime=scriptTime script(gesture) - except: + except: # noqa: E722 log.exception("error executing script: %s with gesture %r"%(script,gesture.displayName)) finally: _isScriptRunning=False diff --git a/source/setup.py b/source/setup.py index 3bef5c63343..5e03c76c60d 100755 --- a/source/setup.py +++ b/source/setup.py @@ -9,11 +9,11 @@ import sys import gettext gettext.install("nvda") -from glob import glob -import fnmatch +from glob import glob # noqa: E402 +import fnmatch # noqa: E402 # versionInfo names must be imported after Gettext # Suppress E402 (module level import not at top of file) -from versionInfo import ( +from versionInfo import ( # noqa: E402 copyright as NVDAcopyright, # copyright is a reserved python keyword description, formatBuildVersionString, @@ -23,8 +23,8 @@ ) # noqa: E402 from py2exe import freeze # noqa: E402 from py2exe.dllfinder import DllFinder # noqa: E402 -import wx -import importlib.machinery +import wx # noqa: E402 +import importlib.machinery # noqa: E402 # Explicitly put the nvda_dmp dir on the build path so the DMP library is included sys.path.append(os.path.join("..", "include", "nvda_dmp")) diff --git a/source/shellapi.py b/source/shellapi.py index becd59e7cb1..51be24743a8 100644 --- a/source/shellapi.py +++ b/source/shellapi.py @@ -3,33 +3,33 @@ #This file is covered by the GNU General Public License. #See the file COPYING for more details. -from ctypes import * -from ctypes.wintypes import * +from ctypes import * # noqa: F403 +from ctypes.wintypes import * # noqa: F403 from typing import Optional -shell32 = windll.shell32 +shell32 = windll.shell32 # noqa: F405 -class SHELLEXECUTEINFOW(Structure): +class SHELLEXECUTEINFOW(Structure): # noqa: F405 _fields_ = ( - ("cbSize", DWORD), - ("fMask", ULONG), - ("hwnd", HWND), - ("lpVerb", LPCWSTR), - ("lpFile", LPCWSTR), - ("lpParameters", LPCWSTR), - ("lpDirectory", LPCWSTR), - ("nShow", c_int), - ("hInstApp", HINSTANCE), - ("lpIDList", LPVOID), - ("lpClass", LPCWSTR), - ("hkeyClass", HKEY), - ("dwHotKey", DWORD), - ("hIconOrMonitor", HANDLE), - ("hProcess", HANDLE), + ("cbSize", DWORD), # noqa: F405 + ("fMask", ULONG), # noqa: F405 + ("hwnd", HWND), # noqa: F405 + ("lpVerb", LPCWSTR), # noqa: F405 + ("lpFile", LPCWSTR), # noqa: F405 + ("lpParameters", LPCWSTR), # noqa: F405 + ("lpDirectory", LPCWSTR), # noqa: F405 + ("nShow", c_int), # noqa: F405 + ("hInstApp", HINSTANCE), # noqa: F405 + ("lpIDList", LPVOID), # noqa: F405 + ("lpClass", LPCWSTR), # noqa: F405 + ("hkeyClass", HKEY), # noqa: F405 + ("dwHotKey", DWORD), # noqa: F405 + ("hIconOrMonitor", HANDLE), # noqa: F405 + ("hProcess", HANDLE), # noqa: F405 ) def __init__(self, **kwargs): - super(SHELLEXECUTEINFOW, self).__init__(cbSize=sizeof(self), **kwargs) + super(SHELLEXECUTEINFOW, self).__init__(cbSize=sizeof(self), **kwargs) # noqa: F405 SHELLEXECUTEINFO = SHELLEXECUTEINFOW SEE_MASK_NOCLOSEPROCESS = 0x00000040 @@ -46,14 +46,14 @@ def ShellExecute( if not file: raise RuntimeError("file cannot be None") if shell32.ShellExecuteW(hwnd, operation, file, parameters, directory, showCmd) <= 32: - raise WinError() + raise WinError() # noqa: F405 def ShellExecuteEx(execInfo): - if not shell32.ShellExecuteExW(byref(execInfo)): - raise WinError() + if not shell32.ShellExecuteExW(byref(execInfo)): # noqa: F405 + raise WinError() # noqa: F405 -FILEOP_FLAGS=WORD +FILEOP_FLAGS=WORD # noqa: F405 FO_MOVE=1 FO_COPY=2 @@ -62,22 +62,22 @@ def ShellExecuteEx(execInfo): FOF_NOCONFIRMMKDIR=0x200 -class SHFILEOPSTRUCT(Structure): +class SHFILEOPSTRUCT(Structure): # noqa: F405 _fields_=[ - ('hwnd',HWND), - ('wFunc',c_uint), - ('pFrom',c_wchar_p), - ('pTo',c_wchar_p), + ('hwnd',HWND), # noqa: F405 + ('wFunc',c_uint), # noqa: F405 + ('pFrom',c_wchar_p), # noqa: F405 + ('pTo',c_wchar_p), # noqa: F405 ('fFlags',FILEOP_FLAGS), - ('fAnyOperationsAborted',BOOL), - ('hNameMapping',c_void_p), - ('lpszProgressTitle',c_wchar_p), + ('fAnyOperationsAborted',BOOL), # noqa: F405 + ('hNameMapping',c_void_p), # noqa: F405 + ('lpszProgressTitle',c_wchar_p), # noqa: F405 ] SHCNE_ASSOCCHANGED=0x08000000 SHCNF_IDLIST=0x0 -shell32.SHChangeNotify.argtypes = [c_long, c_uint, c_void_p, c_void_p] +shell32.SHChangeNotify.argtypes = [c_long, c_uint, c_void_p, c_void_p] # noqa: F405 shell32.SHChangeNotify.restype = None def SHChangeNotify(wEventId, uFlags, dwItem1, dwItem2): shell32.SHChangeNotify(wEventId, uFlags, dwItem1, dwItem2) diff --git a/source/speech/commands.py b/source/speech/commands.py index bf6fe4c7579..19291abd69e 100644 --- a/source/speech/commands.py +++ b/source/speech/commands.py @@ -101,7 +101,7 @@ def __init__(self,index): @param index: the value of this index @type index: integer """ - if not isinstance(index,int): raise ValueError("index must be int, not %s"%type(index)) + if not isinstance(index,int): raise ValueError("index must be int, not %s"%type(index)) # noqa: E701 self.index=index def __repr__(self): @@ -132,7 +132,7 @@ def __init__(self,state): @param state: if true character mode is on, if false its turned off. @type state: boolean """ - if not isinstance(state,bool): raise ValueError("state must be boolean, not %s"%type(state)) + if not isinstance(state,bool): raise ValueError("state must be boolean, not %s"%type(state)) # noqa: E701 self.state=state self.isDefault = not state diff --git a/source/speech/manager.py b/source/speech/manager.py index 1d55df55998..6a179b27002 100644 --- a/source/speech/manager.py +++ b/source/speech/manager.py @@ -326,7 +326,7 @@ def _processSpeechSequence(self, inSeq: SpeechSequence): enteredTriggers = [] outSeqs = [] paramsToReplay = [] - currentSynth = getSynth() + currentSynth = getSynth() # noqa: F841 outSeq = [] for command in inSeq: @@ -722,13 +722,13 @@ def _switchProfile(self): if command.enter: try: command.trigger.enter() - except: + except: # noqa: E722 log.exception("Error entering new trigger %r" % command.trigger.spec) self._curPriQueue.enteredProfileTriggers.append(command.trigger) else: try: command.trigger.exit() - except: + except: # noqa: E722 log.exception("Error exiting active trigger %r" % command.trigger.spec) self._curPriQueue.enteredProfileTriggers.remove(command.trigger) synthDriverHandler.handlePostConfigProfileSwitch(resetSpeechIfNeeded=False) @@ -737,7 +737,7 @@ def _exitProfileTriggers(self, triggers): for trigger in reversed(triggers): try: trigger.exit() - except: + except: # noqa: E722 log.exception("Error exiting profile trigger %r" % trigger.spec) synthDriverHandler.handlePostConfigProfileSwitch(resetSpeechIfNeeded=False) @@ -745,7 +745,7 @@ def _restoreProfileTriggers(self, triggers): for trigger in triggers: try: trigger.enter() - except: + except: # noqa: E722 log.exception("Error entering profile trigger %r" % trigger.spec) synthDriverHandler.handlePostConfigProfileSwitch(resetSpeechIfNeeded=False) diff --git a/source/speech/speech.py b/source/speech/speech.py index 16559db0345..c73f4e1887d 100644 --- a/source/speech/speech.py +++ b/source/speech/speech.py @@ -1082,7 +1082,7 @@ def speak( # noqa: C901 speechSequence=[] for item in oldSpeechSequence: if isinstance(item,LangChangeCommand): - if not autoLanguageSwitching: continue + if not autoLanguageSwitching: continue # noqa: E701 curLanguage=item.lang if not curLanguage or (not autoDialectSwitching and curLanguage.split('_')[0]==defaultLanguageRoot): curLanguage=defaultLanguage @@ -1090,7 +1090,7 @@ def speak( # noqa: C901 if not unicodeNormalization: continue elif isinstance(item,str): - if not item: continue + if not item: continue # noqa: E701 if autoLanguageSwitching and curLanguage!=prevLanguage: speechSequence.append(LangChangeCommand(curLanguage)) prevLanguage=curLanguage @@ -1751,7 +1751,7 @@ def getTextInfoSpeech( # noqa: C901 speechSequence.append(langChange) else: speechSequence.extend(indentationSpeech) - if speakTextInfoState: speakTextInfoState.indentationCache=allIndentation + if speakTextInfoState: speakTextInfoState.indentationCache=allIndentation # noqa: E701 # Don't add this text if it is blank. relativeBlank=True for x in relativeSpeechSequence: @@ -2510,7 +2510,7 @@ def getFormatFieldSpeech( # noqa: C901 # but not if the columnCount is 1 or less and there is no old columnCount. if (((textColumnNumber and textColumnNumber!=oldTextColumnNumber) or (textColumnCount and textColumnCount!=oldTextColumnCount)) and not - (textColumnCount and int(textColumnCount) <=1 and oldTextColumnCount == None)) : + (textColumnCount and int(textColumnCount) <=1 and oldTextColumnCount == None)) : # noqa: E711 if textColumnNumber and textColumnCount: # Translators: Indicates the text column number in a document. # {0} will be replaced with the text column number. diff --git a/source/speechDictHandler/__init__.py b/source/speechDictHandler/__init__.py index 7393748fc3b..b598d7b3742 100644 --- a/source/speechDictHandler/__init__.py +++ b/source/speechDictHandler/__init__.py @@ -41,7 +41,7 @@ class SpeechDictEntry: def __init__(self, pattern, replacement,comment,caseSensitive=True,type=ENTRY_TYPE_ANYWHERE): self.pattern = pattern flags = re.U - if not caseSensitive: flags|=re.IGNORECASE + if not caseSensitive: flags|=re.IGNORECASE # noqa: E701 if type == ENTRY_TYPE_REGEXP: tempPattern = pattern elif type == ENTRY_TYPE_WORD: @@ -149,7 +149,7 @@ def loadVoiceDict(synth): """ try: dictFormatUpgrade.doAnyUpgrades(synth) - except: + except: # noqa: E722 log.error("error trying to upgrade dictionaries", exc_info=True) pass if synth.isSupported("voice"): diff --git a/source/synthDriverHandler.py b/source/synthDriverHandler.py index 9f46a2fb836..01277596e9f 100644 --- a/source/synthDriverHandler.py +++ b/source/synthDriverHandler.py @@ -348,7 +348,7 @@ def loadSettings(self, onlyChanged=False): if not onlyChanged or self.voice != voice: try: changeVoice(self, voice) - except: + except: # noqa: E722 log.warning("Invalid voice: %s" % voice) # Update the configuration with the correct voice. c["voice"] = self.voice diff --git a/source/synthDrivers/_espeak.py b/source/synthDrivers/_espeak.py index 8dfc2155083..01e09ee0573 100755 --- a/source/synthDrivers/_espeak.py +++ b/source/synthDrivers/_espeak.py @@ -8,7 +8,7 @@ import threading import queue from ctypes import cdll, CFUNCTYPE, c_int, c_void_p, POINTER, sizeof, c_short -from ctypes import * +from ctypes import * # noqa: F403 import config import globalVars from logHandler import log @@ -86,17 +86,17 @@ # eSpeak initialization flags espeakINITIALIZE_DONT_EXIT = 0x8000 -class espeak_EVENT_id(Union): +class espeak_EVENT_id(Union): # noqa: F405 _fields_=[ ('number',c_int), - ('name',c_char_p), - ('string',c_char*8), + ('name',c_char_p), # noqa: F405 + ('string',c_char*8), # noqa: F405 ] -class espeak_EVENT(Structure): +class espeak_EVENT(Structure): # noqa: F405 _fields_=[ ('type',c_int), - ('unique_identifier',c_uint), + ('unique_identifier',c_uint), # noqa: F405 ('text_position',c_int), ('length',c_int), ('audio_position',c_int), @@ -105,21 +105,21 @@ class espeak_EVENT(Structure): ('id',espeak_EVENT_id), ] -class espeak_VOICE(Structure): +class espeak_VOICE(Structure): # noqa: F405 _fields_=[ - ('name',c_char_p), - ('languages',c_char_p), - ('identifier',c_char_p), - ('gender',c_byte), - ('age',c_byte), - ('variant',c_byte), - ('xx1',c_byte), + ('name',c_char_p), # noqa: F405 + ('languages',c_char_p), # noqa: F405 + ('identifier',c_char_p), # noqa: F405 + ('gender',c_byte), # noqa: F405 + ('age',c_byte), # noqa: F405 + ('variant',c_byte), # noqa: F405 + ('xx1',c_byte), # noqa: F405 ('score',c_int), ('spare',c_void_p), ] def __eq__(self, other): - return isinstance(other, type(self)) and addressof(self) == addressof(other) + return isinstance(other, type(self)) and addressof(self) == addressof(other) # noqa: F405 # As __eq__ was defined on this class, we must provide __hash__ to remain hashable. # The default hash implementation is fine for our purposes. @@ -185,7 +185,7 @@ def callback(wav,numsamples,event): player.feed(c_void_p(wav + prevByte), size=length - prevByte) _numBytesPushed += length return CALLBACK_CONTINUE_SYNTHESIS - except: + except: # noqa: E722 log.error("callback", exc_info=True) class BgThread(threading.Thread): @@ -201,7 +201,7 @@ def run(self): break try: func(*args, **kwargs) - except: + except: # noqa: E722 log.error("Error running function from queue", exc_info=True) bgQueue.task_done() @@ -227,7 +227,7 @@ def _speak(text): # eSpeak can only process compound emojis when using a UTF8 encoding text=text.encode('utf8',errors='ignore') flags = espeakCHARS_UTF8 | espeakSSML | espeakPHONEMES - return espeakDLL.espeak_Synth(text,0,0,0,0,flags,byref(uniqueID),0) + return espeakDLL.espeak_Synth(text,0,0,0,0,flags,byref(uniqueID),0) # noqa: F405 def speak(text): global bgQueue @@ -266,7 +266,7 @@ def getVoiceList(): voices=espeakDLL.espeak_ListVoices(None) voiceList=[] for voice in voices: - if not voice: break + if not voice: break # noqa: E701 voiceList.append(voice.contents) return voiceList @@ -299,7 +299,7 @@ def _setVoiceAndVariant(voice=None, variant=None): else: try: espeakDLL.espeak_SetVoiceByName(encodeEspeakString("%s+%s" % (voice, variant))) - except: + except: # noqa: E722 espeakDLL.espeak_SetVoiceByName(encodeEspeakString(voice)) def setVoiceAndVariant(voice=None, variant=None): @@ -310,10 +310,10 @@ def _setVoiceByLanguage(lang): lang=lang.replace('_','-') v.languages=encodeEspeakString(lang) try: - espeakDLL.espeak_SetVoiceByProperties(byref(v)) - except: + espeakDLL.espeak_SetVoiceByProperties(byref(v)) # noqa: F405 + except: # noqa: E722 v.languages=encodeEspeakString("en") - espeakDLL.espeak_SetVoiceByProperties(byref(v)) + espeakDLL.espeak_SetVoiceByProperties(byref(v)) # noqa: F405 def setVoiceByLanguage(lang): _execWhenDone(_setVoiceByLanguage, lang) @@ -331,7 +331,7 @@ def initialize(indexCallback=None): """ global espeakDLL, bgThread, bgQueue, player, onIndexReached espeakDLL = cdll.LoadLibrary(os.path.join(globalVars.appDir, "synthDrivers", "espeak.dll")) - espeakDLL.espeak_Info.restype=c_char_p + espeakDLL.espeak_Info.restype=c_char_p # noqa: F405 espeakDLL.espeak_Synth.errcheck=espeak_errcheck espeakDLL.espeak_SetVoiceByName.errcheck=espeak_errcheck espeakDLL.espeak_SetVoiceByProperties.errcheck=espeak_errcheck @@ -339,7 +339,7 @@ def initialize(indexCallback=None): espeakDLL.espeak_Terminate.errcheck=espeak_errcheck espeakDLL.espeak_ListVoices.restype=POINTER(POINTER(espeak_VOICE)) espeakDLL.espeak_GetCurrentVoice.restype=POINTER(espeak_VOICE) - espeakDLL.espeak_SetVoiceByName.argtypes=(c_char_p,) + espeakDLL.espeak_SetVoiceByName.argtypes=(c_char_p,) # noqa: F405 eSpeakPath = os.path.join(globalVars.appDir, "synthDrivers") sampleRate = espeakDLL.espeak_Initialize( AUDIO_OUTPUT_SYNCHRONOUS, 300, @@ -399,7 +399,7 @@ def getVariantDict(): name=temp[1].rstrip() break name=None - except: + except: # noqa: E722 log.error("Couldn't parse espeak variant file %s" % fileName, exc_info=True) continue if name is not None: diff --git a/source/synthDrivers/espeak.py b/source/synthDrivers/espeak.py index f795e53ff0e..f204f3823ef 100644 --- a/source/synthDrivers/espeak.py +++ b/source/synthDrivers/espeak.py @@ -430,7 +430,7 @@ def _set_volume(self, volume: int): def _getAvailableVoices(self): voices=OrderedDict() for v in _espeak.getVoiceList(): - l=_espeak.decodeEspeakString(v.languages[1:]) + l=_espeak.decodeEspeakString(v.languages[1:]) # noqa: E741 # #7167: Some languages names contain unicode characters EG: Norwegian Bokmål name=_espeak.decodeEspeakString(v.name) # #5783: For backwards compatibility, voice identifies should always be lowercase @@ -440,7 +440,7 @@ def _getAvailableVoices(self): def _get_voice(self): curVoice=getattr(self,'_voice',None) - if curVoice: return curVoice + if curVoice: return curVoice # noqa: E701 curVoice = _espeak.getCurrentVoice() if not curVoice: return "" diff --git a/source/synthDrivers/sapi4.py b/source/synthDrivers/sapi4.py index 5b7c51174d8..079ba206037 100755 --- a/source/synthDrivers/sapi4.py +++ b/source/synthDrivers/sapi4.py @@ -103,7 +103,7 @@ def _fetchEnginesList(self): fetched=c_ulong() try: self._ttsEngines.Next(1,byref(mode),byref(fetched)) - except: + except: # noqa: E722 log.error("can't get next engine",exc_info=True) break if fetched.value==0: @@ -224,7 +224,7 @@ def removeSetting(self,name): def _set_voice(self,val): try: val=GUID(val) - except: + except: # noqa: E722 val=self._enginesList[0].gModeID mode=None for mode in self._enginesList: diff --git a/source/synthDrivers/sapi5.py b/source/synthDrivers/sapi5.py index 7354af70d53..3636a01baaf 100644 --- a/source/synthDrivers/sapi5.py +++ b/source/synthDrivers/sapi5.py @@ -115,7 +115,7 @@ def check(cls): r=winreg.OpenKey(winreg.HKEY_CLASSES_ROOT,cls.COM_CLASS) r.Close() return True - except: + except: # noqa: E722 return False ttsAudioStream=None #: Holds the ISPAudio interface for the current voice, to aid in stopping and pausing audio diff --git a/source/synthSettingsRing.py b/source/synthSettingsRing.py index dfdf3b39540..46a9f494cd2 100644 --- a/source/synthSettingsRing.py +++ b/source/synthSettingsRing.py @@ -204,9 +204,9 @@ def updateSupportedSettings(self,synth): if self._current is not None and hasattr(self,'settings') else None ) - list: list[SynthSetting] = [] + list: list[SynthSetting] = [] # noqa: F823 for s in synth.supportedSettings: - if not s.availableInSettingsRing: continue + if not s.availableInSettingsRing: continue # noqa: E701 if prevID == s.id: #restore the last setting self._current=len(list) if isinstance(s, NumericDriverSetting): diff --git a/source/touchHandler.py b/source/touchHandler.py index 10d76c81768..0eb5dea848f 100644 --- a/source/touchHandler.py +++ b/source/touchHandler.py @@ -9,9 +9,9 @@ """ import threading -from ctypes import * +from ctypes import * # noqa: F403 from ctypes import windll -from ctypes.wintypes import * +from ctypes.wintypes import * # noqa: F403 import re import gui import config @@ -65,34 +65,34 @@ POINTER_MESSAGE_FLAG_CONFIDENCE=0x200 POINTER_MESSAGE_FLAG_CANCELED=0x400 -class POINTER_INFO(Structure): +class POINTER_INFO(Structure): # noqa: F405 _fields_=[ - ('pointerType',DWORD), - ('pointerId',c_uint32), - ('frameId',c_uint32), - ('pointerFlags',c_uint32), - ('sourceDevice',HANDLE), - ('hwndTarget',HWND), - ('ptPixelLocation',POINT), - ('ptHimetricLocation',POINT), - ('ptPixelLocationRaw',POINT), - ('ptHimetricLocationRaw',POINT), - ('dwTime',DWORD), - ('historyCount',c_uint32), - ('inputData',c_int), - ('dwKeyStates',DWORD), - ('PerformanceCount',c_uint64), + ('pointerType',DWORD), # noqa: F405 + ('pointerId',c_uint32), # noqa: F405 + ('frameId',c_uint32), # noqa: F405 + ('pointerFlags',c_uint32), # noqa: F405 + ('sourceDevice',HANDLE), # noqa: F405 + ('hwndTarget',HWND), # noqa: F405 + ('ptPixelLocation',POINT), # noqa: F405 + ('ptHimetricLocation',POINT), # noqa: F405 + ('ptPixelLocationRaw',POINT), # noqa: F405 + ('ptHimetricLocationRaw',POINT), # noqa: F405 + ('dwTime',DWORD), # noqa: F405 + ('historyCount',c_uint32), # noqa: F405 + ('inputData',c_int), # noqa: F405 + ('dwKeyStates',DWORD), # noqa: F405 + ('PerformanceCount',c_uint64), # noqa: F405 ] -class POINTER_TOUCH_INFO(Structure): +class POINTER_TOUCH_INFO(Structure): # noqa: F405 _fields_=[ ('pointerInfo',POINTER_INFO), - ('touchFlags',c_uint32), - ('touchMask',c_uint32), - ('rcContact',RECT), - ('rcContactRaw',RECT), - ('orientation',c_uint32), - ('pressure',c_uint32), + ('touchFlags',c_uint32), # noqa: F405 + ('touchMask',c_uint32), # noqa: F405 + ('rcContact',RECT), # noqa: F405 + ('rcContactRaw',RECT), # noqa: F405 + ('orientation',c_uint32), # noqa: F405 + ('pressure',c_uint32), # noqa: F405 ] ANRUS_TOUCH_MODIFICATION_ACTIVE=2 @@ -134,7 +134,7 @@ class TouchInputGesture(inputCore.InputGesture): } def _get_speechEffectWhenExecuted(self): - if self.tracker.action in (touchTracker.action_hover,touchTracker.action_hoverUp): return None + if self.tracker.action in (touchTracker.action_hover,touchTracker.action_hoverUp): return None # noqa: E701 return super(TouchInputGesture,self).speechEffectWhenExecuted def _get_reportInInputHelp(self): @@ -231,11 +231,11 @@ def run(self): try: self._appInstance=windll.kernel32.GetModuleHandleW(None) self._cInputTouchWindowProc=winUser.WNDPROC(self.inputTouchWndProc) - self._wc=winUser.WNDCLASSEXW(cbSize=sizeof(winUser.WNDCLASSEXW),lpfnWndProc=self._cInputTouchWindowProc,hInstance=self._appInstance,lpszClassName="inputTouchWindowClass") - self._wca=windll.user32.RegisterClassExW(byref(self._wc)) + self._wc=winUser.WNDCLASSEXW(cbSize=sizeof(winUser.WNDCLASSEXW),lpfnWndProc=self._cInputTouchWindowProc,hInstance=self._appInstance,lpszClassName="inputTouchWindowClass") # noqa: F405 + self._wca=windll.user32.RegisterClassExW(byref(self._wc)) # noqa: F405 self._touchWindow=windll.user32.CreateWindowExW(0,self._wca,u"NVDA touch input",0,0,0,0,0,HWND_MESSAGE,None,self._appInstance,None) windll.user32.RegisterPointerInputTarget(self._touchWindow,PT_TOUCH) - oledll.oleacc.AccSetRunningUtilityState(self._touchWindow,ANRUS_TOUCH_MODIFICATION_ACTIVE,ANRUS_TOUCH_MODIFICATION_ACTIVE) + oledll.oleacc.AccSetRunningUtilityState(self._touchWindow,ANRUS_TOUCH_MODIFICATION_ACTIVE,ANRUS_TOUCH_MODIFICATION_ACTIVE) # noqa: F405 self.trackerManager=touchTracker.TrackerManager() self.screenExplorer=screenExplorer.ScreenExplorer() self.screenExplorer.updateReview=True @@ -243,11 +243,11 @@ def run(self): self.threadExc=e finally: self.initializedEvent.set() - msg=MSG() - while windll.user32.GetMessageW(byref(msg),None,0,0): - windll.user32.TranslateMessage(byref(msg)) - windll.user32.DispatchMessageW(byref(msg)) - oledll.oleacc.AccSetRunningUtilityState(self._touchWindow,ANRUS_TOUCH_MODIFICATION_ACTIVE,0) + msg=MSG() # noqa: F405 + while windll.user32.GetMessageW(byref(msg),None,0,0): # noqa: F405 + windll.user32.TranslateMessage(byref(msg)) # noqa: F405 + windll.user32.DispatchMessageW(byref(msg)) # noqa: F405 + oledll.oleacc.AccSetRunningUtilityState(self._touchWindow,ANRUS_TOUCH_MODIFICATION_ACTIVE,0) # noqa: F405 windll.user32.UnregisterPointerInputTarget(self._touchWindow,PT_TOUCH) windll.user32.DestroyWindow(self._touchWindow) windll.user32.UnregisterClassW(self._wca,self._appInstance) @@ -294,7 +294,7 @@ 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, + oledll.oleacc.AccNotifyTouchInteraction(gui.mainFrame.Handle, obj.windowHandle, # noqa: F405 obj.location.center.toPOINT()) handler=None diff --git a/source/touchTracker.py b/source/touchTracker.py index ea78e229c38..c60838ae341 100644 --- a/source/touchTracker.py +++ b/source/touchTracker.py @@ -191,7 +191,7 @@ def __init__( self.pluralTimeout = pluralTimeout def iterAllRawSingleTouchTrackers(self): - if self.rawSingleTouchTracker: yield self.rawSingleTouchTracker + if self.rawSingleTouchTracker: yield self.rawSingleTouchTracker # noqa: E701 for child in self.childTrackers: for i in child.iterAllRawSingleTouchTrackers(): yield i @@ -223,8 +223,8 @@ def __init__(self): def makePreheldTrackerFromSingleTouchTrackers(self,trackers): childTrackers=[MultiTouchTracker(action_hold,tracker.x,tracker.y,tracker.startTime,time.time()) for tracker in trackers if tracker.action==action_hover] numFingers=len(childTrackers) - if numFingers==0: return - if numFingers==1: return childTrackers[0] + if numFingers==0: return # noqa: E701 + if numFingers==1: return childTrackers[0] # noqa: E701 avgX: int = sum(t.x for t in childTrackers) // numFingers avgY: int = sum(t.y for t in childTrackers) // numFingers tracker=MultiTouchTracker(action_hold,avgX,avgY,childTrackers[0].startTime,time.time(),numFingers) diff --git a/source/updateCheck.py b/source/updateCheck.py index de267030fb9..11065a3ac2b 100644 --- a/source/updateCheck.py +++ b/source/updateCheck.py @@ -273,7 +273,7 @@ def _bg(self): state["id"] = uuid4().hex try: info = checkForUpdate(self.AUTO) - except: + except: # noqa: E722 log.debugWarning("Error checking for update", exc_info=True) self._error() return @@ -568,7 +568,7 @@ def onPostponeButton(self, evt): # Therefore use kernel32::MoveFileEx with copy allowed (0x2) flag set. # TODO: consider moving to shutil.move, which supports moves across filesystems. winKernel.moveFileEx(self.destPath, finalDest, winKernel.MOVEFILE_COPY_ALLOWED) - except: + except: # noqa: E722 log.debugWarning("Unable to rename the file from {} to {}".format(self.destPath, finalDest), exc_info=True) gui.messageBox( # Translators: The message when a downloaded update file could not be preserved. @@ -647,7 +647,7 @@ def _bg(self): for url in self.urls: try: self._download(url) - except: + except: # noqa: E722 log.error("Error downloading %s" % url, exc_info=True) else: #Successfully downloaded or canceled if not self._shouldCancel: @@ -798,7 +798,7 @@ def saveState(): # #9038: Python 3 requires binary format when working with pickles. with open(WritePaths.updateCheckStateFile, "wb") as f: pickle.dump(state, f, protocol=0) - except: + except: # noqa: E722 log.debugWarning("Error saving state", exc_info=True) def initialize(): @@ -807,7 +807,7 @@ def initialize(): # #9038: Python 3 requires binary format when working with pickles. with open(WritePaths.updateCheckStateFile, "rb") as f: state = pickle.load(f) - except: + except: # noqa: E722 log.debugWarning("Couldn't retrieve update state", exc_info=True) state = None diff --git a/source/versionInfo.py b/source/versionInfo.py index 3ae1c363c86..d5c1a85f91c 100644 --- a/source/versionInfo.py +++ b/source/versionInfo.py @@ -9,7 +9,7 @@ To access version information for programmatic version checks before languageHandler.initialize, use the buildVersion module which contains all the non-localizable version information such as major and minor version, and version string etc. """ -from buildVersion import * +from buildVersion import * # noqa: F403 longName = _("NonVisual Desktop Access") description = _("A free and open source screen reader for Microsoft Windows") diff --git a/source/virtualBuffers/MSHTML.py b/source/virtualBuffers/MSHTML.py index 58af2321d83..7d478ee4d91 100644 --- a/source/virtualBuffers/MSHTML.py +++ b/source/virtualBuffers/MSHTML.py @@ -150,7 +150,7 @@ def _normalizeControlField(self, attrs: textInfos.ControlField): # noqa: C901 if descNode: try: description=description+" "+self.obj.makeTextInfo(NVDAObjects.IAccessible.MSHTML.MSHTML(HTMLNode=descNode)).text - except: + except: # noqa: E722 pass ariaSort=attrs.get('HTMLAttrib::aria-sort') state=aria.ariaSortValuesToNVDAStates.get(ariaSort) diff --git a/source/virtualBuffers/__init__.py b/source/virtualBuffers/__init__.py index 1f76f4a2403..d9cd6dd125b 100644 --- a/source/virtualBuffers/__init__.py +++ b/source/virtualBuffers/__init__.py @@ -7,35 +7,35 @@ import time import threading import ctypes -import collections -import itertools +import collections # noqa: F401 +import itertools # noqa: F401 from typing import ( Optional, Dict, ) import weakref import wx -import review +import review # noqa: F401 import NVDAHelper import XMLFormatting import scriptHandler from scriptHandler import script -import speech -import NVDAObjects +import speech # noqa: F401 +import NVDAObjects # noqa: F401 import api import controlTypes import textInfos.offsets import config -import cursorManager +import cursorManager # noqa: F401 import browseMode -import gui -import eventHandler +import gui # noqa: F401 +import eventHandler # noqa: F401 import braille import queueHandler from logHandler import log import ui -import aria -import treeInterceptorHandler +import aria # noqa: F401 +import treeInterceptorHandler # noqa: F401 import watchdog from abc import abstractmethod import documentBase @@ -61,7 +61,7 @@ class VBufStorage_findMatch_word(str): FINDBYATTRIBS_ESCAPE_TABLE.update({(ord(s), u"\\" + s) for s in u"^$.*+?()[]{}|"}) def _prepareForFindByAttributes(attribs): # A lambda that coerces a value to a string and escapes characters suitable for a regular expression. - escape = lambda val: str(val).translate(FINDBYATTRIBS_ESCAPE_TABLE) + escape = lambda val: str(val).translate(FINDBYATTRIBS_ESCAPE_TABLE) # noqa: E731 reqAttrs = [] regexp = [] if isinstance(attribs, dict): @@ -480,7 +480,7 @@ def _loadBuffer(self): ) if not self.VBufHandle: raise RuntimeError("Could not remotely create virtualBuffer") - except: + except: # noqa: E722 log.error("", exc_info=True) queueHandler.queueFunction(queueHandler.eventQueue, self._loadBufferDone, success=False) return @@ -632,7 +632,7 @@ def _iterNodesByAttribs(self, attribs, direction="next", pos=None,nodeType=None) try: node=VBufRemote_nodeHandle_t() NVDAHelper.localLib.VBuf_findNodeByAttributes(self.VBufHandle,offset,direction,reqAttrs,regexp,ctypes.byref(startOffset),ctypes.byref(endOffset),ctypes.byref(node)) - except: + except: # noqa: E722 return if not node: return @@ -736,7 +736,7 @@ def getEnclosingContainerRange(self, textRange): if field.getPresentationCategory(controlFields,formatConfig)==field.PRESCAT_CONTAINER or field.get("landmark"): containerField=field break - if not containerField: return None + if not containerField: return None # noqa: E701 docHandle=int(containerField['controlIdentifier_docHandle']) ID=int(containerField['controlIdentifier_ID']) offsets = textRange._getOffsetsFromFieldIdentifier(docHandle,ID) @@ -778,7 +778,7 @@ def _isNVDAObjectInApplication_noWalk(self, obj): # If the object is in the buffer, it's definitely not in an application. try: docHandle, objId = self.getIdentifierFromNVDAObject(obj) - except: + except: # noqa: E722 log.debugWarning("getIdentifierFromNVDAObject failed. " "Object probably died while walking ancestors.", exc_info=True) return None diff --git a/source/virtualBuffers/lotusNotes.py b/source/virtualBuffers/lotusNotes.py index 3415803b56f..45e71b62679 100644 --- a/source/virtualBuffers/lotusNotes.py +++ b/source/virtualBuffers/lotusNotes.py @@ -12,7 +12,7 @@ import IAccessibleHandler import oleacc from logHandler import log -from virtualBuffers import VirtualBufferTextInfo +from virtualBuffers import VirtualBufferTextInfo # noqa: F811 class LotusNotesRichText_TextInfo(VirtualBufferTextInfo): @@ -79,11 +79,11 @@ def _activateNVDAObject(self, obj): try: obj.doAction() return - except: + except: # noqa: E722 pass log.debugWarning("could not programmatically activate field, trying mouse") - l=obj.location + l=obj.location # noqa: E741 if not l: log.debugWarning("no location for field") return diff --git a/source/virtualBuffers/webKit.py b/source/virtualBuffers/webKit.py index 807ab4358e9..147a1658ebe 100644 --- a/source/virtualBuffers/webKit.py +++ b/source/virtualBuffers/webKit.py @@ -117,11 +117,11 @@ def _activateNVDAObject(self, obj): try: obj.doAction() return - except: + except: # noqa: E722 pass log.debugWarning("could not programmatically activate field, trying mouse") - l=obj.location + l=obj.location # noqa: E741 if not l: log.debugWarning("no location for field") return diff --git a/source/vision/__init__.py b/source/vision/__init__.py index 88235f6b534..ecdd71adcc9 100644 --- a/source/vision/__init__.py +++ b/source/vision/__init__.py @@ -11,7 +11,7 @@ using modules in the visionEnhancementProviders package containing a L{VisionEnhancementProvider} class. """ from .visionHandler import VisionHandler -import visionEnhancementProviders +import visionEnhancementProviders # noqa: F401 import config from typing import Optional diff --git a/source/watchdog.py b/source/watchdog.py index acc748e6c66..bf8b9912bc3 100644 --- a/source/watchdog.py +++ b/source/watchdog.py @@ -217,7 +217,7 @@ def _shouldRecoverAfterMinTimeout(): def _recoverAttempt(): try: oledll.ole32.CoCancelCall(core.mainThreadId,0) - except: + except: # noqa: E722 pass class MINIDUMP_EXCEPTION_INFORMATION(ctypes.Structure): @@ -252,7 +252,7 @@ def _crashHandler(exceptionInfo): None ): raise ctypes.WinError() - except: + except: # noqa: E722 log.critical("NVDA crashed! Error writing minidump", exc_info=True) else: log.critical("NVDA crashed! Minidump written to %s" % dumpPath) diff --git a/source/winConsoleHandler.py b/source/winConsoleHandler.py index e0c096c3168..0d9a3710909 100755 --- a/source/winConsoleHandler.py +++ b/source/winConsoleHandler.py @@ -94,7 +94,7 @@ def disconnectConsole(): #Unregister any win events we are using for handle in consoleWinEventHookHandles: winUser.unhookWinEvent(handle) - consoleEventHookHandles=[] + consoleEventHookHandles=[] # noqa: F841 consoleObject.stopMonitoring() winKernel.closeHandle(consoleOutputHandle) consoleOutputHandle=None @@ -122,7 +122,7 @@ def _checkDead(): if isConsoleDead(): # We must disconnect NVDA from this console so it can close. disconnectConsole() - except: + except: # noqa: E722 log.exception() def getConsoleVisibleLines(): diff --git a/source/winInputHook.py b/source/winInputHook.py index a22fcd92d05..1f728af31dc 100755 --- a/source/winInputHook.py +++ b/source/winInputHook.py @@ -8,8 +8,8 @@ """ import threading -from ctypes import * -from ctypes.wintypes import * +from ctypes import * # noqa: F403 +from ctypes.wintypes import * # noqa: F403 import watchdog import winUser @@ -22,32 +22,32 @@ WH_MOUSE_LL = 14 LLMHF_INJECTED = 1 -class KBDLLHOOKSTRUCT(Structure): +class KBDLLHOOKSTRUCT(Structure): # noqa: F405 _fields_=[ - ('vkCode',DWORD), - ('scanCode',DWORD), - ('flags',DWORD), - ('time',DWORD), - ('dwExtraInfo',DWORD), + ('vkCode',DWORD), # noqa: F405 + ('scanCode',DWORD), # noqa: F405 + ('flags',DWORD), # noqa: F405 + ('time',DWORD), # noqa: F405 + ('dwExtraInfo',DWORD), # noqa: F405 ] -class MSLLHOOKSTRUCT(Structure): +class MSLLHOOKSTRUCT(Structure): # noqa: F405 _fields_=[ - ('pt',POINT), - ('mouseData',DWORD), - ('flags',DWORD), - ('time',DWORD), - ('dwExtraInfo',DWORD), + ('pt',POINT), # noqa: F405 + ('mouseData',DWORD), # noqa: F405 + ('flags',DWORD), # noqa: F405 + ('time',DWORD), # noqa: F405 + ('dwExtraInfo',DWORD), # noqa: F405 ] keyDownCallback=None keyUpCallback=None mouseCallback=None -@WINFUNCTYPE(c_long,c_int,WPARAM,LPARAM) +@WINFUNCTYPE(c_long,c_int,WPARAM,LPARAM) # noqa: F405 def keyboardHook(code,wParam,lParam): if code != HC_ACTION: - return windll.user32.CallNextHookEx(0,code,wParam,lParam) + return windll.user32.CallNextHookEx(0,code,wParam,lParam) # noqa: F405 kbd=KBDLLHOOKSTRUCT.from_address(lParam) if keyUpCallback and kbd.flags&LLKHF_UP: if not keyUpCallback(kbd.vkCode,kbd.scanCode,bool(kbd.flags&LLKHF_EXTENDED),bool(kbd.flags&LLKHF_INJECTED)): @@ -55,34 +55,34 @@ def keyboardHook(code,wParam,lParam): elif keyDownCallback: if not keyDownCallback(kbd.vkCode,kbd.scanCode,bool(kbd.flags&LLKHF_EXTENDED),bool(kbd.flags&LLKHF_INJECTED)): return 1 - return windll.user32.CallNextHookEx(0,code,wParam,lParam) + return windll.user32.CallNextHookEx(0,code,wParam,lParam) # noqa: F405 -@WINFUNCTYPE(c_long,c_int,WPARAM,LPARAM) +@WINFUNCTYPE(c_long,c_int,WPARAM,LPARAM) # noqa: F405 def mouseHook(code,wParam,lParam): if watchdog.isAttemptingRecovery or code!=HC_ACTION: - return windll.user32.CallNextHookEx(0,code,wParam,lParam) + return windll.user32.CallNextHookEx(0,code,wParam,lParam) # noqa: F405 msll=MSLLHOOKSTRUCT.from_address(lParam) if mouseCallback: if not mouseCallback(wParam,msll.pt.x,msll.pt.y,msll.flags&LLMHF_INJECTED): return 1 - return windll.user32.CallNextHookEx(0,code,wParam,lParam) + return windll.user32.CallNextHookEx(0,code,wParam,lParam) # noqa: F405 hookThread=None hookThreadRefCount=0 def hookThreadFunc(): - keyHookID=windll.user32.SetWindowsHookExW(WH_KEYBOARD_LL,keyboardHook,windll.kernel32.GetModuleHandleW(None),0) + keyHookID=windll.user32.SetWindowsHookExW(WH_KEYBOARD_LL,keyboardHook,windll.kernel32.GetModuleHandleW(None),0) # noqa: F405 if keyHookID==0: raise OSError("Could not register keyboard hook") - mouseHookID=windll.user32.SetWindowsHookExW(WH_MOUSE_LL,mouseHook,windll.kernel32.GetModuleHandleW(None),0) + mouseHookID=windll.user32.SetWindowsHookExW(WH_MOUSE_LL,mouseHook,windll.kernel32.GetModuleHandleW(None),0) # noqa: F405 if mouseHookID==0: raise OSError("Could not register mouse hook") - msg=MSG() - while windll.user32.GetMessageW(byref(msg),None,0,0): + msg=MSG() # noqa: F405 + while windll.user32.GetMessageW(byref(msg),None,0,0): # noqa: F405 pass - if windll.user32.UnhookWindowsHookEx(keyHookID)==0: + if windll.user32.UnhookWindowsHookEx(keyHookID)==0: # noqa: F405 raise OSError("could not unregister key hook %s"%keyHookID) - if windll.user32.UnhookWindowsHookEx(mouseHookID)==0: + if windll.user32.UnhookWindowsHookEx(mouseHookID)==0: # noqa: F405 raise OSError("could not unregister mouse hook %s"%mouseHookID) def initialize(): @@ -111,6 +111,6 @@ def terminate(): raise RuntimeError("winInputHook not running") hookThreadRefCount-=1 if hookThreadRefCount==0: - windll.user32.PostThreadMessageW(hookThread.ident,winUser.WM_QUIT,0,0) + windll.user32.PostThreadMessageW(hookThread.ident,winUser.WM_QUIT,0,0) # noqa: F405 hookThread.join() hookThread=None diff --git a/source/winUser.py b/source/winUser.py index 69f42ed3c47..c71c8eeb3b7 100644 --- a/source/winUser.py +++ b/source/winUser.py @@ -10,9 +10,9 @@ """ import contextlib -from ctypes import * +from ctypes import * # noqa: F403 from ctypes import byref, WinError, Structure, c_int, c_char -from ctypes.wintypes import * +from ctypes.wintypes import * # noqa: F403 from ctypes.wintypes import HWND, RECT, DWORD from typing import ( Any, @@ -26,14 +26,14 @@ from logHandler import log #dll handles -user32=windll.user32 +user32=windll.user32 # noqa: F405 # rather than using the ctypes.c_void_p type, which may encourage attempting to dereference # what may be an invalid or illegal pointer, we'll treat it as an opaque value. HWNDVal = int -LRESULT=c_long -HCURSOR=c_long +LRESULT=c_long # noqa: F405 +HCURSOR=c_long # noqa: F405 #Standard window class stuff #: Redraws the entire window if a movement or size adjustment changes the width of the client area. @@ -41,7 +41,7 @@ #: Redraws the entire window if a movement or size adjustment changes the height of the client area. CS_VREDRAW = 0x0001 -WNDPROC=WINFUNCTYPE(LRESULT,HWND,c_uint,WPARAM,LPARAM) +WNDPROC=WINFUNCTYPE(LRESULT,HWND,c_uint,WPARAM,LPARAM) # noqa: F405 def __getattr__(attrName: str) -> Any: @@ -68,25 +68,25 @@ def __getattr__(attrName: str) -> Any: class WNDCLASSEXW(Structure): _fields_=[ - ('cbSize',c_uint), - ('style',c_uint), + ('cbSize',c_uint), # noqa: F405 + ('style',c_uint), # noqa: F405 ('lpfnWndProc',WNDPROC), ('cbClsExtra',c_int), ('cbWndExtra',c_int), - ('hInstance',HINSTANCE), - ('hIcon',HICON), + ('hInstance',HINSTANCE), # noqa: F405 + ('hIcon',HICON), # noqa: F405 ('HCURSOR',HCURSOR), - ('hbrBackground',HBRUSH), - ('lpszMenuName',LPWSTR), - ('lpszClassName',LPWSTR), - ('hIconSm',HICON), + ('hbrBackground',HBRUSH), # noqa: F405 + ('lpszMenuName',LPWSTR), # noqa: F405 + ('lpszClassName',LPWSTR), # noqa: F405 + ('hIconSm',HICON), # noqa: F405 ] class NMHdrStruct(Structure): _fields_=[ ('hwndFrom',HWND), - ('idFrom',c_uint), - ('code',c_uint), + ('idFrom',c_uint), # noqa: F405 + ('code',c_uint), # noqa: F405 ] class GUITHREADINFO(Structure): @@ -424,7 +424,7 @@ def setSystemScreenReaderFlag(val): user32.SystemParametersInfoW(SPI_SETSCREENREADER,val,0,SPIF_UPDATEINIFILE|SPIF_SENDCHANGE) def getSystemScreenReaderFlag(): - val = BOOL() + val = BOOL() # noqa: F405 user32.SystemParametersInfoW(SPI_GETSCREENREADER, 0, byref(val), 0) return bool(val.value) @@ -444,10 +444,10 @@ def HIWORD(long): return long>>16 def GET_X_LPARAM(lp): - return c_short(LOWORD(lp)).value + return c_short(LOWORD(lp)).value # noqa: F405 def GET_Y_LPARAM(lp): - return c_short(HIWORD(lp)).value + return c_short(HIWORD(lp)).value # noqa: F405 def MAKELONG(lo,hi): return (hi<<16)+lo @@ -469,7 +469,7 @@ def dispatchMessage(*args): def peekMessage(*args): try: res=user32.PeekMessageW(*args) - except: + except: # noqa: E722 res=0 return res @@ -516,9 +516,9 @@ def getClientRect(hwnd): raise WinError() return r -HWINEVENTHOOK=HANDLE +HWINEVENTHOOK=HANDLE # noqa: F405 -WINEVENTPROC=WINFUNCTYPE(None,HWINEVENTHOOK,DWORD,HWND,c_long,c_long,DWORD,DWORD) +WINEVENTPROC=WINFUNCTYPE(None,HWINEVENTHOOK,DWORD,HWND,c_long,c_long,DWORD,DWORD) # noqa: F405 def setWinEventHook(*args): return user32.SetWinEventHook(*args) @@ -538,7 +538,7 @@ def getWindowThreadProcessID(hwnd: HWNDVal) -> Tuple[int, int]: def getClassName(window: HWNDVal) -> str: - buf=create_unicode_buffer(256) + buf=create_unicode_buffer(256) # noqa: F405 user32.GetClassNameW(window,buf,255) return buf.value @@ -568,12 +568,12 @@ def setCursorPos(x,y): _setCursorPos(x,y) def getCursorPos(): - point=POINT() + point=POINT() # noqa: F405 _getCursorPos(byref(point)) return [point.x,point.y] def getCaretPos(): - point=POINT() + point=POINT() # noqa: F405 user32.GetCaretPos(byref(point)) return [point.x,point.y] @@ -581,7 +581,7 @@ def getTopWindow(hwnd): return user32.GetTopWindow(hwnd) def getWindowText(hwnd): - buf=create_unicode_buffer(1024) + buf=create_unicode_buffer(1024) # noqa: F405 user32.InternalGetWindowText(hwnd,buf,1023) return buf.value @@ -595,7 +595,7 @@ def isWindowEnabled(window): return bool(user32.IsWindowEnabled(window)) def getGUIThreadInfo(threadID): - info=GUITHREADINFO(cbSize=sizeof(GUITHREADINFO)) + info=GUITHREADINFO(cbSize=sizeof(GUITHREADINFO)) # noqa: F405 user32.GetGUIThreadInfo(threadID,byref(info)) return info @@ -627,7 +627,7 @@ def RedrawWindow(hwnd, rcUpdate, rgnUpdate, flags): return user32.RedrawWindow(hwnd, byref(rcUpdate), rgnUpdate, flags) def getKeyNameText(scanCode,extended): - buf=create_unicode_buffer(32) + buf=create_unicode_buffer(32) # noqa: F405 user32.GetKeyNameTextW((scanCode<<16)|(extended<<24),buf,31) return buf.value @@ -655,20 +655,20 @@ def PostMessage(hwnd, msg, wParam, lParam): if not user32.PostMessageW(hwnd, msg, wParam, lParam): raise WinError() -user32.VkKeyScanExW.restype = SHORT +user32.VkKeyScanExW.restype = SHORT # noqa: F405 def VkKeyScanEx(ch, hkl): - res = user32.VkKeyScanExW(WCHAR(ch), hkl) + res = user32.VkKeyScanExW(WCHAR(ch), hkl) # noqa: F405 if res == -1: raise LookupError return res >> 8, res & 0xFF def ScreenToClient(hwnd, x, y): - point = POINT(x, y) + point = POINT(x, y) # noqa: F405 user32.ScreenToClient(hwnd, byref(point)) return point.x, point.y def ClientToScreen(hwnd, x, y): - point = POINT(x, y) + point = POINT(x, y) # noqa: F405 user32.ClientToScreen(hwnd, byref(point)) return point.x, point.y @@ -681,7 +681,7 @@ class STICKYKEYS(Structure): ("dwFlags", DWORD), ) def __init__(self, **kwargs): - super(STICKYKEYS, self).__init__(cbSize=sizeof(self), **kwargs) + super(STICKYKEYS, self).__init__(cbSize=sizeof(self), **kwargs) # noqa: F405 SKF_STICKYKEYSON = 0x00000001 SKF_AUDIBLEFEEDBACK = 0x00000040 SKF_TRISTATE = 0x00000080 @@ -694,34 +694,34 @@ def getSystemStickyKeys(): # START SENDINPUT TYPE DECLARATIONS -PUL = POINTER(c_ulong) +PUL = POINTER(c_ulong) # noqa: F405 class KeyBdInput(Structure): - _fields_ = [("wVk", c_ushort), - ("wScan", c_ushort), - ("dwFlags", c_ulong), - ("time", c_ulong), + _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), - ("wParamL", c_short), - ("wParamH", c_ushort)] + _fields_ = [("uMsg", c_ulong), # noqa: F405 + ("wParamL", c_short), # noqa: F405 + ("wParamH", c_ushort)] # noqa: F405 class MouseInput(Structure): - _fields_ = [("dx", c_long), - ("dy", c_long), - ("mouseData", c_ulong), - ("dwFlags", c_ulong), - ("time",c_ulong), + _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): +class Input_I(Union): # noqa: F405 _fields_ = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(Structure): - _fields_ = [("type", c_ulong), + _fields_ = [("type", c_ulong), # noqa: F405 ("ii", Input_I)] @@ -734,7 +734,7 @@ class Input(Structure): def SendInput(inputs): n = len(inputs) arr = (Input * n)(*inputs) - user32.SendInput(n, arr, sizeof(Input)) + user32.SendInput(n, arr, sizeof(Input)) # noqa: F405 class PAINTSTRUCT(Structure): @@ -808,31 +808,31 @@ def openClipboard(hwndOwner=None): A context manager version of OpenClipboard from user32. Use as the expression of a 'with' statement, and CloseClipboard will automatically be called at the end. """ - if not windll.user32.OpenClipboard(hwndOwner): - raise ctypes.WinError() + if not windll.user32.OpenClipboard(hwndOwner): # noqa: F405 + raise ctypes.WinError() # noqa: F405 try: yield finally: - windll.user32.CloseClipboard() + windll.user32.CloseClipboard() # noqa: F405 def emptyClipboard(): - if not windll.user32.EmptyClipboard(): - raise ctypes.WinError() + if not windll.user32.EmptyClipboard(): # noqa: F405 + raise ctypes.WinError() # noqa: F405 def getClipboardData(format): # We only support unicode text for now if format!=CF_UNICODETEXT: raise ValueError("Unsupported format") # Fetch the data from the clipboard as a global memory handle - h=windll.user32.GetClipboardData(format) + h=windll.user32.GetClipboardData(format) # noqa: F405 if not h: - raise ctypes.WinError() + raise ctypes.WinError() # noqa: F405 # Lock the global memory while we fetch the unicode string # But make sure not to free the memory accidentally -- it is not ours h=winKernel.HGLOBAL(h,autoFree=False) with h.lock() as addr: # Read the string from the local memory address - return wstring_at(addr) + return wstring_at(addr) # noqa: F405 def setClipboardData(format,data): # For now only unicode is a supported format @@ -845,10 +845,10 @@ def setClipboardData(format,data): # Acquire a lock to the global memory receiving a local memory address with h.lock() as addr: # Write the text into the allocated memory - buf=(c_wchar*bufLen).from_address(addr) + buf=(c_wchar*bufLen).from_address(addr) # noqa: F405 buf.value=text # Set the clipboard data with the global memory - if not windll.user32.SetClipboardData(format,h): - raise ctypes.WinError() + if not windll.user32.SetClipboardData(format,h): # noqa: F405 + raise ctypes.WinError() # noqa: F405 # NULL the global memory handle so that it is not freed at the end of scope as the clipboard now has it. h.forget() diff --git a/source/wincon.py b/source/wincon.py index c38b10f4266..b5be8f79909 100755 --- a/source/wincon.py +++ b/source/wincon.py @@ -1,5 +1,5 @@ -from ctypes import * -from ctypes.wintypes import * +from ctypes import * # noqa: F403 +from ctypes.wintypes import * # noqa: F403 import textUtils """ @@ -9,35 +9,35 @@ CONSOLE_REAL_OUTPUT_HANDLE=-2 -class COORD(Structure): +class COORD(Structure): # noqa: F405 _fields_=[ - ('x',c_short), - ('y',c_short), + ('x',c_short), # noqa: F405 + ('y',c_short), # noqa: F405 ] -class CONSOLE_SCREEN_BUFFER_INFO(Structure): +class CONSOLE_SCREEN_BUFFER_INFO(Structure): # noqa: F405 _fields_=[ ('dwSize',COORD), ('dwCursorPosition',COORD), - ('wAttributes',WORD), - ('srWindow',SMALL_RECT), + ('wAttributes',WORD), # noqa: F405 + ('srWindow',SMALL_RECT), # noqa: F405 ('dwMaximumWindowSize',COORD), ] -class CONSOLE_SELECTION_INFO(Structure): +class CONSOLE_SELECTION_INFO(Structure): # noqa: F405 _fields_=[ - ('dwFlags',DWORD), + ('dwFlags',DWORD), # noqa: F405 ('dwSelectionAnchor',COORD), - ('srSelection',SMALL_RECT), + ('srSelection',SMALL_RECT), # noqa: F405 ] -class CHAR_INFO(Structure): +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 - ('Attributes', WORD) + ('Char', c_wchar), #union of char and wchar_t isn't needed since we deal only with unicode # noqa: F405 + ('Attributes', WORD) # noqa: F405 ] -PHANDLER_ROUTINE=WINFUNCTYPE(BOOL,DWORD) +PHANDLER_ROUTINE=WINFUNCTYPE(BOOL,DWORD) # noqa: F405 CTRL_C_EVENT=0 CTRL_BREAK_EVENT=1 @@ -51,48 +51,48 @@ class CHAR_INFO(Structure): def GetConsoleSelectionInfo(): info=CONSOLE_SELECTION_INFO() - if windll.kernel32.GetConsoleSelectionInfo(byref(info))==0: - raise WinError() + if windll.kernel32.GetConsoleSelectionInfo(byref(info))==0: # noqa: F405 + raise WinError() # noqa: F405 return info def ReadConsoleOutputCharacter(handle,length,x,y): # Use a string buffer, as from an unicode buffer, we can't get the raw data. - buf=create_string_buffer(length * 2) - numCharsRead=c_int() - if windll.kernel32.ReadConsoleOutputCharacterW(handle,buf,length,COORD(x,y),byref(numCharsRead))==0: - raise WinError() + buf=create_string_buffer(length * 2) # noqa: F405 + numCharsRead=c_int() # noqa: F405 + if windll.kernel32.ReadConsoleOutputCharacterW(handle,buf,length,COORD(x,y),byref(numCharsRead))==0: # noqa: F405 + raise WinError() # noqa: F405 return textUtils.getTextFromRawBytes(buf.raw, numChars=numCharsRead.value, encoding=textUtils.WCHAR_ENCODING) def ReadConsoleOutput(handle, length, rect): BufType=CHAR_INFO*length buf=BufType() #rect=SMALL_RECT(x, y, x+length-1, y) - if windll.kernel32.ReadConsoleOutputW(handle, buf, COORD(rect.Right-rect.Left+1, rect.Bottom-rect.Top+1), COORD(0,0), byref(rect))==0: - raise WinError() + if windll.kernel32.ReadConsoleOutputW(handle, buf, COORD(rect.Right-rect.Left+1, rect.Bottom-rect.Top+1), COORD(0,0), byref(rect))==0: # noqa: F405 + raise WinError() # noqa: F405 return buf def GetConsoleScreenBufferInfo(handle): info=CONSOLE_SCREEN_BUFFER_INFO() - if windll.kernel32.GetConsoleScreenBufferInfo(handle,byref(info))==0: - raise WinError() + if windll.kernel32.GetConsoleScreenBufferInfo(handle,byref(info))==0: # noqa: F405 + raise WinError() # noqa: F405 return info def FreeConsole(): - if windll.kernel32.FreeConsole()==0: - raise WinError() + if windll.kernel32.FreeConsole()==0: # noqa: F405 + raise WinError() # noqa: F405 def AttachConsole(processID): - if windll.kernel32.AttachConsole(processID)==0: - raise WinError() + if windll.kernel32.AttachConsole(processID)==0: # noqa: F405 + raise WinError() # noqa: F405 def GetConsoleWindow(): - return windll.kernel32.GetConsoleWindow() + return windll.kernel32.GetConsoleWindow() # noqa: F405 def GetConsoleProcessList(maxProcessCount): - processList=(c_int*maxProcessCount)() - num=windll.kernel32.GetConsoleProcessList(processList,maxProcessCount) + processList=(c_int*maxProcessCount)() # noqa: F405 + num=windll.kernel32.GetConsoleProcessList(processList,maxProcessCount) # noqa: F405 return processList[0:num] def SetConsoleCtrlHandler(handler,add): - if windll.kernel32.SetConsoleCtrlHandler(handler,add)==0: - raise WinError() + if windll.kernel32.SetConsoleCtrlHandler(handler,add)==0: # noqa: F405 + raise WinError() # noqa: F405 diff --git a/source/windowUtils.py b/source/windowUtils.py index e6057c70e55..b779ee99c6d 100644 --- a/source/windowUtils.py +++ b/source/windowUtils.py @@ -115,7 +115,7 @@ def getWindowScalingFactor(window: int) -> int: user32 = ctypes.windll.user32 try: winDpi: int = user32.GetDpiForWindow(window) - except: + except: # noqa: E722 log.debug("GetDpiForWindow failed, using GetDeviceCaps instead") dc = user32.GetDC(window) winDpi: int = ctypes.windll.gdi32.GetDeviceCaps(dc, LOGPIXELSX) @@ -274,6 +274,6 @@ def _rawWindowProc(hwnd, msg, wParam, lParam): res = inst.windowProc(hwnd, msg, wParam, lParam) if res is not None: return res - except: + except: # noqa: E722 log.exception("Error in wndProc") return ctypes.windll.user32.DefWindowProcW(hwnd, msg, wParam, lParam) diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py index 65a36a13f60..99400c84d3e 100644 --- a/tests/unit/__init__.py +++ b/tests/unit/__init__.py @@ -26,7 +26,7 @@ sys.path.insert(1, SOURCE_DIR) # Suppress Flake8 warning F401 (module imported but unused) # as this module is imported to expand the system path. -import sourceEnv # noqa: F401 +import sourceEnv # noqa: E402, F401 # Apply several monkey patches to comtypes to make sure that it would search for generated interfaces # rather than creating them on the fly. Also stop module being never than typelib error, seen when # virtual environment has been created under different version of Windows than the one used for unit tests. @@ -35,7 +35,7 @@ import monkeyPatches.comtypesMonkeyPatches # noqa: E402 monkeyPatches.comtypesMonkeyPatches.replace_check_version() monkeyPatches.comtypesMonkeyPatches.appendComInterfacesToGenSearchPath() -import globalVars +import globalVars # noqa: E402 # Tell NvDA where its application directory is @@ -58,21 +58,21 @@ __path__[0] = UNIT_DIR # We don't want logging for now, # though we may optionally want this in future; see #7045. -import logging -from logHandler import log +import logging # noqa: E402 +from logHandler import log # noqa: E402 log.addHandler(logging.NullHandler()) # There's no point in logging anything at all, since it'll go nowhere. log.setLevel(100) # Much of this should eventually be replaced by stuff which gets reset before each test # so the tests are isolated. -import config +import config # noqa: E402 config.initialize() # Initialize languageHandler so that translatable strings work. -import languageHandler +import languageHandler # noqa: E402 languageHandler.setLanguage("en") # NVDAObjects need appModuleHandler to be initialized. -import appModuleHandler +import appModuleHandler # noqa: E402 appModuleHandler.initialize() # Anything which notifies of cursor updates requires braille and vision to be initialized. # Suppress Flake8 warning E402 (Module level import not at top of file) @@ -83,7 +83,7 @@ speech.initialize() -import braille +import braille # noqa: E402 # Disable auto detection of braille displays when unit testing. config.conf['braille']['display'] = "noBraille" braille.initialize() @@ -129,15 +129,15 @@ def _patched_handleReviewMove(shouldAutoTether=True): os.path.join(NVDAHelper.versionedLibPath, 'nvdaHelperLocal.dll') ) # The focus and navigator objects need to be initialized to something. -from .objectProvider import PlaceholderNVDAObject,NVDAObjectWithRole +from .objectProvider import PlaceholderNVDAObject,NVDAObjectWithRole # noqa: E402, F401 phObj = PlaceholderNVDAObject() -import api +import api # noqa: E402 api.setFocusObject(phObj) api.setNavigatorObject(phObj) api.setDesktopObject(phObj) # Stub speech functions to make them no-ops. # Eventually, these should keep track of calls so we can make assertions. -import speech +import speech # noqa: E402 speech.speak = lambda speechSequence, symbolLevel=None, priority=None: None speech.speakSpelling = lambda text, locale=None, useCharacterDescriptions=False, priority=None: None diff --git a/tests/unit/test_extensionPoints.py b/tests/unit/test_extensionPoints.py index 091664c57f3..6becdc0928c 100644 --- a/tests/unit/test_extensionPoints.py +++ b/tests/unit/test_extensionPoints.py @@ -476,7 +476,7 @@ def test_lambdaHandler(self): Note: the lambda must be kept alive, since register uses a weak reference to it. """ calledKwargs = {} - l = lambda a: calledKwargs.update({'a': a}) + l = lambda a: calledKwargs.update({'a': a}) # noqa: E731, E741 self.action.register(l) self.action.notify(a='a value') self.assertEqual(calledKwargs, {'a': 'a value'}) @@ -604,7 +604,7 @@ def recordKwarg(a): calledKwargs.update({'a': a}) return 'lambda value' - l = lambda a: recordKwarg(a) + l = lambda a: recordKwarg(a) # noqa: E731, E741 self.filter.register(l) self.filter.apply('a value') self.assertEqual(calledKwargs, {'a': 'a value'}) @@ -714,7 +714,7 @@ def test_lambdaHandler(self): Note: the lambda must be kept alive, since register uses a weak reference to it. """ calledKwargs = {} - l = lambda a: calledKwargs.update({'a': a}) + l = lambda a: calledKwargs.update({'a': a}) # noqa: E731, E741 self.decider.register(l) self.decider.decide(a='a value') self.assertEqual(calledKwargs, {'a': 'a value'}) diff --git a/tests/unit/test_javaAccessBridge.py b/tests/unit/test_javaAccessBridge.py index 2f39eb5bde9..1f2761825e3 100644 --- a/tests/unit/test_javaAccessBridge.py +++ b/tests/unit/test_javaAccessBridge.py @@ -69,7 +69,7 @@ def testBasicShortcut(self): for modifierCombination in MODIFIER_COMBINATIONS: modifiers = 0 modLabels = [] - for m, l in modifierCombination.items(): + for m, l in modifierCombination.items(): # noqa: E741 modifiers |= m modLabels.append(l) with self.subTest(character=c, modifiers=modifiers, modLabels=modLabels): @@ -81,7 +81,7 @@ def testFKeyShortcut(self): for modifierCombination in MODIFIER_COMBINATIONS: modifiers = AccessibleKeystroke.FKEY modLabels = [] - for m, l in modifierCombination.items(): + for m, l in modifierCombination.items(): # noqa: E741 modifiers |= m modLabels.append(l) with self.subTest(fkey=ord(c), modifiers=modifiers, modLabels=modLabels): @@ -93,7 +93,7 @@ def testControlCodeShortcut(self): for modifierCombination in MODIFIER_COMBINATIONS: modifiers = AccessibleKeystroke.CONTROLCODE modLabels = [] - for m, l in modifierCombination.items(): + for m, l in modifierCombination.items(): # noqa: E741 modifiers |= m modLabels.append(l) with self.subTest(controlCode=c, label=v, modifiers=modifiers, modLabels=modLabels): diff --git a/tests/unit/test_languageHandler.py b/tests/unit/test_languageHandler.py index 1812aba39f0..0d45f211b25 100644 --- a/tests/unit/test_languageHandler.py +++ b/tests/unit/test_languageHandler.py @@ -28,7 +28,7 @@ def generateUnsupportedWindowsLocales(): LCID_ENGLISH_US = 0x0409 UNSUPPORTED_WIN_LANGUAGES = generateUnsupportedWindowsLocales() -TRANSLATABLE_LANGS = set(l[0] for l in languageHandler.getAvailableLanguages()) - {"Windows"} +TRANSLATABLE_LANGS = set(l[0] for l in languageHandler.getAvailableLanguages()) - {"Windows"} # noqa: E741 WINDOWS_LANGS = set(locale.windows_locale.values()).union(LCIDS_TO_TRANSLATED_LOCALES.values())