Skip to content

Commit

Permalink
Apply various fixes suggested by pyupgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
AAClause committed Aug 1, 2020
1 parent 12d08ad commit c6dbb2a
Show file tree
Hide file tree
Showing 14 changed files with 39 additions and 53 deletions.
5 changes: 2 additions & 3 deletions addon/globalPlugins/brailleExtender/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# BrailleExtender Addon for NVDA
# This file is covered by the GNU General Public License.
# See the file LICENSE for more details.
Expand Down Expand Up @@ -1175,7 +1174,7 @@ def script_logFieldsAtCursor(self, gesture):

def script_saveCurrentBrailleView(self, gesture):
if scriptHandler.getLastScriptRepeatCount() == 0:
config.conf["brailleExtender"]["viewSaved"] = ''.join(chr((c | 0x2800)) for c in braille.handler.mainBuffer.brailleCells)
config.conf["brailleExtender"]["viewSaved"] = ''.join(chr(c | 0x2800) for c in braille.handler.mainBuffer.brailleCells)
ui.message(_("Current braille view saved"))
else:
config.conf["brailleExtender"]["viewSaved"] = configBE.NOVIEWSAVED
Expand Down Expand Up @@ -1342,7 +1341,7 @@ def terminate(self):
if self.autoTestPlayed: self.autoTestTimer.Stop()
dictionaries.removeTmpDict()
advancedInputMode.terminate()
super(GlobalPlugin, self).terminate()
super().terminate()

def removeMenu(self):
gui.mainFrame.sysTrayIcon.menu.DestroyItem(self.submenu_item)
Expand Down
13 changes: 6 additions & 7 deletions addon/globalPlugins/brailleExtender/addonDoc.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# addonDoc.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down Expand Up @@ -183,7 +182,7 @@ def __init__(self, instanceGP):
doc += self.translateLst(mW)
doc += ("<h3>" + _("Standard NVDA commands") + " (%d)</h3>") % len(mNV)
doc += self.translateLst(mNV)
doc += "<h3>{0} ({1})</h3>".format(
doc += "<h3>{} ({})</h3>".format(
_("Modifier keys"), len(configBE.iniProfile["modifierKeys"])
)
doc += self.translateLst(configBE.iniProfile["modifierKeys"])
Expand Down Expand Up @@ -211,13 +210,13 @@ def __init__(self, instanceGP):
]
)
)
doc += "<h3>{0} ({1})</h3>".format(
doc += "<h3>{} ({})</h3>".format(
_("Shortcuts defined outside add-on"),
len(braille.handler.display.gestureMap._map),
)
doc += "<ul>"
for g in braille.handler.display.gestureMap._map:
doc += ("<li>{0}{1}: {2}{3};</li>").format(
doc += ("<li>{}{}: {}{};</li>").format(
utils.beautifulSht(g),
punctuationSeparator,
utils.uncapitalize(
Expand Down Expand Up @@ -271,7 +270,7 @@ def __init__(self, instanceGP):
"kb:volumedown",
"kb:volumemute",
] and gestures[g] not in ["logFieldsAtCursor"]:
doc += ("<li>{0}{1}: {2}{3};</li>").format(
doc += ("<li>{}{}: {}{};</li>").format(
utils.getKeysTranslation(g),
punctuationSeparator,
re.sub(
Expand Down Expand Up @@ -393,7 +392,7 @@ def translateLst(self, lst):
)
else:
if isinstance(lst[g], list):
doc += "<li>{0}{1}: {2}{3};</li>".format(
doc += "<li>{}{}: {}{};</li>".format(
utils.beautifulSht(lst[g]),
punctuationSeparator,
re.sub(
Expand All @@ -404,7 +403,7 @@ def translateLst(self, lst):
punctuationSeparator,
)
else:
doc += "<li>{0}{1}: {2}{3};</li>".format(
doc += "<li>{}{}: {}{};</li>".format(
utils.beautifulSht(lst[g]),
punctuationSeparator,
re.sub(
Expand Down
5 changes: 2 additions & 3 deletions addon/globalPlugins/brailleExtender/advancedInputMode.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# advancedInputMode.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down Expand Up @@ -238,13 +237,13 @@ def postInit(self):
def onOk(self, evt):
saveDict(self.tmpDict)
setDict(self.tmpDict)
super(AdvancedInputModeDlg, self).onOk(evt)
super().onOk(evt)


class DictionaryEntryDlg(wx.Dialog):
# Translators: This is the label for the edit dictionary entry dialog.
def __init__(self, parent=None, title=_("Edit Dictionary Entry")):
super(DictionaryEntryDlg, self).__init__(parent, title=title)
super().__init__(parent, title=title)
mainSizer = wx.BoxSizer(wx.VERTICAL)
sHelper = gui.guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
# Translators: This is a label for an edit field in add dictionary entry dialog.
Expand Down
1 change: 0 additions & 1 deletion addon/globalPlugins/brailleExtender/brailleRegionHelper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# brailleRegionHelper.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down
1 change: 0 additions & 1 deletion addon/globalPlugins/brailleExtender/common.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# common.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down
1 change: 0 additions & 1 deletion addon/globalPlugins/brailleExtender/configBE.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# configBE.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down
15 changes: 7 additions & 8 deletions addon/globalPlugins/brailleExtender/dictionaries.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# dictionaries.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down Expand Up @@ -90,7 +89,7 @@ def saveDict(type_, dict_):
direction = entry.direction if entry.direction != "both" else ''
line = ("%s %s %s %s %s" % (direction, entry.opcode, entry.textPattern, entry.braillePattern, entry.comment)).strip()+"\n"
f.write(line.encode("UTF-8"))
f.write('\n'.encode("UTF-8"))
f.write(b'\n')
f.close()
return True

Expand Down Expand Up @@ -122,7 +121,7 @@ def __init__(self, parent, title, type_):
self.title = title
self.type_ = type_
self.tmpDict = getDictionary(type_)[1]
super(DictionaryDlg, self).__init__(parent, hasApplyButton=True)
super().__init__(parent, hasApplyButton=True)

def makeSettings(self, settingsSizer):
sHelper = gui.guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
Expand Down Expand Up @@ -207,7 +206,7 @@ def getReprTextPattern(textPattern, equiv=True):

@staticmethod
def getReprBraillePattern(braillePattern, equiv=True):
if equiv and re.match("^[0-8\-]+$", braillePattern):
if equiv and re.match(r"^[0-8\-]+$", braillePattern):
return "%s (%s)" % (huc.cellDescriptionsToUnicodeBraille(braillePattern), braillePattern)
braillePattern = braillePattern.replace(r"\s", " ").replace(r"\t", " ")
return braillePattern
Expand Down Expand Up @@ -269,7 +268,7 @@ def onApply(self, evt):
res = saveDict(self.type_, self.tmpDict)
setDictTables()
braille.handler.setDisplayByName(braille.handler.display.name)
if res: super(DictionaryDlg, self).onApply(evt)
if res: super().onApply(evt)
else: notImplemented("Error during writing file, more info in log.")
notifyInvalidTables()
self.dictList.SetFocus()
Expand All @@ -279,14 +278,14 @@ def onOk(self, evt):
setDictTables()
braille.handler.setDisplayByName(braille.handler.display.name)
notifyInvalidTables()
if res: super(DictionaryDlg, self).onOk(evt)
if res: super().onOk(evt)
else: notImplemented("Error during writing file, more info in log.")
notifyInvalidTables()

class DictionaryEntryDlg(wx.Dialog):
# Translators: This is the label for the edit dictionary entry dialog.
def __init__(self, parent=None, title=_("Edit Dictionary Entry"), textPattern='', specifyDict=False):
super(DictionaryEntryDlg, self).__init__(parent, title=title)
super().__init__(parent, title=title)
mainSizer=wx.BoxSizer(wx.VERTICAL)
sHelper = gui.guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
if specifyDict:
Expand Down Expand Up @@ -377,7 +376,7 @@ def onOk(self, evt):
msg = _("'Braille representation' field is empty. You must specify something with this opcode. E.g.: %s") % egBRLRepr
gui.messageBox(msg, _("Braille Extender"), wx.OK|wx.ICON_ERROR)
return self.braillePatternTextCtrl.SetFocus()
if not re.match("^[0-8\-]+$", braillePattern):
if not re.match(r"^[0-8\-]+$", braillePattern):
msg = _("Invalid value for 'braille representation' field. You must enter dot patterns with this opcode. E.g.: %s") % egBRLRepr
gui.messageBox(msg, _("Braille Extender"), wx.OK|wx.ICON_ERROR)
return self.braillePatternTextCtrl.SetFocus()
Expand Down
3 changes: 1 addition & 2 deletions addon/globalPlugins/brailleExtender/huc.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# coding: UTF-8
import re
import sys
import struct
Expand Down Expand Up @@ -188,7 +187,7 @@ def translate(t, HUC6=False, unicodeBraille=True, debug=False):
j = int(l, 16)
if i % 2:
end = translateHUC8(hexVals[j], debug)
cleanCell = ''.join(sorted((beg + end))).replace('0', '')
cleanCell = ''.join(sorted(beg + end)).replace('0', '')
if not cleanCell:
cleanCell = '0'
if debug:
Expand Down
1 change: 0 additions & 1 deletion addon/globalPlugins/brailleExtender/oneHandMode.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# oneHandMode.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down
9 changes: 4 additions & 5 deletions addon/globalPlugins/brailleExtender/patches.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# patches.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down Expand Up @@ -429,10 +428,10 @@ def _translate(self, endWord):
assert not self.useContractedForCurrentFocus or endWord, "Must only translate contracted at end of word"
if self.useContractedForCurrentFocus:
# self.bufferText has been used by _reportContractedCell, so clear it.
self.bufferText = u""
self.bufferText = ""
oldTextLen = len(self.bufferText)
pos = self.untranslatedStart + self.untranslatedCursorPos
data = u"".join([chr(cell | brailleInput.LOUIS_DOTS_IO_START) for cell in self.bufferBraille[:pos]])
data = "".join([chr(cell | brailleInput.LOUIS_DOTS_IO_START) for cell in self.bufferBraille[:pos]])
mode = louis.dotsIO | louis.noUndefinedDots
if (not self.currentFocusIsTextObj or self.currentModifiers) and self._table.contracted:
mode |= louis.partialTrans
Expand All @@ -454,7 +453,7 @@ def _translate(self, endWord):
if len(newText)>1:
# Emulation of multiple characters at once is unsupported
# Clear newText, so this function returns C{False} if not at end of word
newText = u""
newText = ""
else:
self.emulateKey(newText)
else:
Expand All @@ -464,7 +463,7 @@ def _translate(self, endWord):
# We only need to buffer one word.
# Clear the previous word (anything before the cursor) from the buffer.
del self.bufferBraille[:pos]
self.bufferText = u""
self.bufferText = ""
self.cellsWithText.clear()
if not instanceGP.modifiersLocked:
self.currentModifiers.clear()
Expand Down
23 changes: 11 additions & 12 deletions addon/globalPlugins/brailleExtender/settings.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# settings.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down Expand Up @@ -499,7 +498,7 @@ def getBrailleTablesFromJSON(path):
if not os.path.exists(path):
path = "%s/%s" % (configBE.baseDir, path)
if not os.path.exists(path): return {}
f = open(path, "r")
f = open(path)
return json.load(f)

def onAddBrailleTablesBtn(self, evt):
Expand All @@ -509,7 +508,7 @@ def onAddBrailleTablesBtn(self, evt):
def postInit(self): self.inTable.SetFocus()

def onOk(self, event):
super(CustomBrailleTablesDlg, self).onOk(evt)
super().onOk(evt)


class AddBrailleTablesDlg(gui.settingsDialogs.SettingsDialog):
Expand Down Expand Up @@ -560,7 +559,7 @@ def onOk(self, event):
)
k = hashlib.md5(path).hexdigest()[:15]
config.conf["brailleExtender"]["brailleTables"][k] = v
super(AddBrailleTablesDlg, self).onOk(evt)
super().onOk(evt)

@staticmethod
def getAvailableBrailleTables():
Expand Down Expand Up @@ -611,12 +610,12 @@ def onOk(self, evt):
for gesture, location in zip(self.quickLaunchGestures, self.quickLaunchLocations):
config.conf["brailleExtender"]["quickLaunches"][gesture] = location
instanceGP.loadQuickLaunchesGes()
super(QuickLaunchesDlg, self).onOk(evt)
super().onOk(evt)

def onCancel(self, evt):
if inputCore.manager._captureFunc:
inputCore.manager._captureFunc = None
super(QuickLaunchesDlg, self).onCancel(evt)
super().onCancel(evt)

def captureNow(self):
def getCaptured(gesture):
Expand All @@ -632,7 +631,7 @@ def getCaptured(gesture):
inputCore.manager._captureFunc = None
queueHandler.queueFunction(queueHandler.eventQueue, ui.message, _("Out of capture"))
elif gesture.normalizedIdentifiers[0].startswith("kb") and not gesture.normalizedIdentifiers[0].endswith(":escape"):
queueHandler.queueFunction(queueHandler.eventQueue, ui.message, _("Please enter a gesture from your {NAME_BRAILLE_DISPLAY} braille display. Press space to cancel.".format(NAME_BRAILLE_DISPLAY=configBE.curBD)))
queueHandler.queueFunction(queueHandler.eventQueue, ui.message, _(f"Please enter a gesture from your {configBE.curBD} braille display. Press space to cancel."))
return False
elif not gesture.normalizedIdentifiers[0].endswith(":escape"):
self.quickLaunchGestures.append(gesture.normalizedIdentifiers[0])
Expand Down Expand Up @@ -666,7 +665,7 @@ def confirmed():
listQuickLaunches = self.getQuickLaunchList()
self.quickKeys.SetItems(listQuickLaunches)
if len(listQuickLaunches) > 0: self.quickKeys.SetSelection(i-1 if i > 0 else 0)
queueHandler.queueFunction(queueHandler.eventQueue, ui.message, _('{BRAILLEGESTURE} removed'.format(BRAILLEGESTURE=g)))
queueHandler.queueFunction(queueHandler.eventQueue, ui.message, _(f'{g} removed'))
self.onQuickKeys(None)
wx.CallAfter(askConfirmation)
self.quickKeys.SetFocus()
Expand Down Expand Up @@ -735,11 +734,11 @@ class AddonSettingsDialog(gui.settingsDialogs.MultiCategorySettingsDialog):
def __init__(self, parent, initialCategory=None):
# Translators: title of add-on settings dialog.
self.title = _("Braille Extender settings")
super(AddonSettingsDialog,self).__init__(parent, initialCategory)
super().__init__(parent, initialCategory)

def makeSettings(self, settingsSizer):
# Ensure that after the settings dialog is created the name is set correctly
super(AddonSettingsDialog, self).makeSettings(settingsSizer)
super().makeSettings(settingsSizer)
self._doOnCategoryChange()
global addonSettingsDialogWindowHandle
addonSettingsDialogWindowHandle = self.GetHandle()
Expand All @@ -753,14 +752,14 @@ def _doOnCategoryChange(self):
self.SetTitle(self._getDialogTitle())

def _getDialogTitle(self):
return u"{dialogTitle}: {panelTitle} ({configProfile})".format(
return "{dialogTitle}: {panelTitle} ({configProfile})".format(
dialogTitle=self.title,
panelTitle=self.currentCategory.title,
configProfile=addonSettingsDialogActiveConfigProfile
)

def onCategoryChange(self,evt):
super(AddonSettingsDialog,self).onCategoryChange(evt)
super().onCategoryChange(evt)
if evt.Skipped:
return
self._doOnCategoryChange()
5 changes: 2 additions & 3 deletions addon/globalPlugins/brailleExtender/undefinedChars.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# undefinedChars.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down Expand Up @@ -388,8 +387,8 @@ def onSave(self):
] = self.undefinedCharReprList.GetSelection()
repr_ = self.undefinedCharReprEdit.Value
if self.undefinedCharReprList.GetSelection() == CHOICE_otherDots:
repr_ = re.sub("[^0-8\-]", "", repr_).strip("-")
repr_ = re.sub("\-+", "-", repr_)
repr_ = re.sub(r"[^0-8\-]", "", repr_).strip("-")
repr_ = re.sub(r"\-+", "-", repr_)
config.conf["brailleExtender"]["undefinedCharsRepr"][
"hardDotPatternValue"
] = repr_
Expand Down
1 change: 0 additions & 1 deletion addon/globalPlugins/brailleExtender/updateCheck.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# updateCheck.py
# Part of BrailleExtender addon for NVDA
# Copyright 2020 André-Abush Clause, released under GPL.
Expand Down
9 changes: 4 additions & 5 deletions addon/globalPlugins/brailleExtender/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# coding: utf-8
# utils.py
# Part of BrailleExtender addon for NVDA
# Copyright 2016-2020 André-Abush CLAUSE, released under GPL.
Expand Down Expand Up @@ -327,8 +326,8 @@ def beautifulSht(t, curBD="noBraille", model=True, sep=" / "):
gesture = re.sub(r'.+:', '', gesture)
gesture = '+'.join(sorted(gesture.split('+')))
for rep in reps:
gesture = re.sub("(\+|^)%s([0-9]\+|$)" % rep, r"\1%s\2" % reps[rep], gesture)
gesture = re.sub("(\+|^)%s([0-9]\+|$)" % rep, r"\1%s\2" % reps[rep], gesture)
gesture = re.sub(r"(\+|^)%s([0-9]\+|$)" % rep, r"\1%s\2" % reps[rep], gesture)
gesture = re.sub(r"(\+|^)%s([0-9]\+|$)" % rep, r"\1%s\2" % reps[rep], gesture)
out.append(_('{gesture} on {brailleDisplay}').format(gesture=gesture, brailleDisplay=mdl) if mdl != '' else gesture)
return out if not sep else sep.join(out)

Expand Down Expand Up @@ -402,8 +401,8 @@ def getTextPosition():
def uncapitalize(s): return s[:1].lower() + s[1:] if s else ''


translatePercent = lambda p, q = braille.handler.displaySize - 4: u'⣦%s⣴' % ''.join(
[u'⢼' if k <= int(float(p) / 100. * float(q - 2)) - 1 else u'⠤' for k in range(q - 2)])
translatePercent = lambda p, q = braille.handler.displaySize - 4: '⣦%s⣴' % ''.join(
['⢼' if k <= int(float(p) / 100. * float(q - 2)) - 1 else '⠤' for k in range(q - 2)])

def refreshBD():
obj = api.getFocusObject()
Expand Down

0 comments on commit c6dbb2a

Please sign in to comment.