From 348a6f7d3935f03514f55af53de0b5750ccce8d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9-Abush=20Clause?= Date: Sat, 24 Oct 2020 17:05:11 +0200 Subject: [PATCH] WIP: Code refactoring --- .../globalPlugins/brailleExtender/__init__.py | 74 +++--- .../globalPlugins/brailleExtender/patches.py | 1 - .../globalPlugins/brailleExtender/settings.py | 4 +- .../{dictionaries.py => tabledictionaries.py} | 22 +- .../{brailleTablesExt.py => tablegroups.py} | 249 ++++++------------ .../brailleExtender/tablehelper.py | 63 +++++ .../brailleExtender/undefinedChars.py | 8 +- addon/globalPlugins/brailleExtender/utils.py | 14 +- 8 files changed, 201 insertions(+), 234 deletions(-) rename addon/globalPlugins/brailleExtender/{dictionaries.py => tabledictionaries.py} (96%) rename addon/globalPlugins/brailleExtender/{brailleTablesExt.py => tablegroups.py} (72%) create mode 100644 addon/globalPlugins/brailleExtender/tablehelper.py diff --git a/addon/globalPlugins/brailleExtender/__init__.py b/addon/globalPlugins/brailleExtender/__init__.py index dc1f6f8d..bc3d252a 100644 --- a/addon/globalPlugins/brailleExtender/__init__.py +++ b/addon/globalPlugins/brailleExtender/__init__.py @@ -46,8 +46,8 @@ from . import utils from .updateCheck import * from . import advancedInputMode -from . import brailleTablesExt -from . import dictionaries +from . import tabledictionaries +from . import tablegroups from . import huc from . import patches from . import settings @@ -204,7 +204,7 @@ def __init__(self): if config.conf["brailleExtender"]["reverseScrollBtns"]: self.reverseScrollBtns() self.createMenu() advancedInputMode.initialize() - brailleTablesExt.initializeGroups() + tablegroups.initializeGroups() log.info(f"{addonName} {addonVersion} loaded ({round(time.time()-startTime, 2)}s)") def event_gainFocus(self, obj, nextHandler): @@ -262,13 +262,13 @@ def createMenu(self): lambda event: wx.CallAfter(gui.mainFrame._popupSettingsDialog, settings.AddonSettingsDialog), item ) - dictionariesMenu = wx.Menu() - self.submenu.AppendSubMenu(dictionariesMenu, _("Table &dictionaries"), _("'Braille dictionaries' menu")) - item = dictionariesMenu.Append(wx.ID_ANY, _("&Global dictionary"), _("A dialog where you can set global dictionary by adding dictionary entries to the list.")) + tabledictionariesMenu = wx.Menu() + self.submenu.AppendSubMenu(tabledictionariesMenu, _("Table &dictionaries"), _("'Braille dictionaries' menu")) + item = tabledictionariesMenu.Append(wx.ID_ANY, _("&Global dictionary"), _("A dialog where you can set global dictionary by adding dictionary entries to the list.")) gui.mainFrame.sysTrayIcon.Bind(wx.EVT_MENU, self.onDefaultDictionary, item) - item = dictionariesMenu.Append(wx.ID_ANY, _("&Table dictionary"), _("A dialog where you can set table-specific dictionary by adding dictionary entries to the list.")) + item = tabledictionariesMenu.Append(wx.ID_ANY, _("&Table dictionary"), _("A dialog where you can set table-specific dictionary by adding dictionary entries to the list.")) gui.mainFrame.sysTrayIcon.Bind(wx.EVT_MENU, self.onTableDictionary, item) - item = dictionariesMenu.Append(wx.ID_ANY, _("Te&mporary dictionary"), _("A dialog where you can set temporary dictionary by adding dictionary entries to the list.")) + item = tabledictionariesMenu.Append(wx.ID_ANY, _("Te&mporary dictionary"), _("A dialog where you can set temporary dictionary by adding dictionary entries to the list.")) gui.mainFrame.sysTrayIcon.Bind(wx.EVT_MENU, self.onTemporaryDictionary, item) item = self.submenu.Append(wx.ID_ANY, _("Advanced &input mode dictionary..."), _("Advanced input mode configuration")) @@ -296,8 +296,8 @@ def createMenu(self): self.submenu_item = gui.mainFrame.sysTrayIcon.menu.InsertMenu(2, wx.ID_ANY, "%s (%s)" % (_("&Braille Extender"), addonVersion), self.submenu) def reloadBrailleTables(self): - dictionaries.setDictTables() - dictionaries.notifyInvalidTables() + tabledictionaries.setDictTables() + tabledictionaries.notifyInvalidTables() if config.conf["brailleExtender"]["tabSpace"]: liblouisDef = r"always \t " + ("0-" * configBE.getTabSize()).strip('-') patches.louis.compileString(patches.getCurrentBrailleTables(), bytes(liblouisDef, "ASCII")) @@ -305,16 +305,16 @@ def reloadBrailleTables(self): @staticmethod def onDefaultDictionary(evt): - gui.mainFrame._popupSettingsDialog(dictionaries.DictionaryDlg, _("Global dictionary"), "default") + gui.mainFrame._popupSettingsDialog(tabledictionaries.DictionaryDlg, _("Global dictionary"), "default") @staticmethod def onTableDictionary(evt): - outTable = brailleTablesExt.listTablesDisplayName()[brailleTablesExt.listTablesFileName().index(config.conf["braille"]["translationTable"])] - gui.mainFrame._popupSettingsDialog(dictionaries.DictionaryDlg, _("Table dictionary ({})").format(outTable), "table") + outTable = tablegroups.listTablesDisplayName()[tablegroups.listTablesFileName().index(config.conf["braille"]["translationTable"])] + gui.mainFrame._popupSettingsDialog(tabledictionaries.DictionaryDlg, _("Table dictionary ({})").format(outTable), "table") @staticmethod def onTemporaryDictionary(evt): - gui.mainFrame._popupSettingsDialog(dictionaries.DictionaryDlg, _("Temporary dictionary"), "tmp") + gui.mainFrame._popupSettingsDialog(tabledictionaries.DictionaryDlg, _("Temporary dictionary"), "tmp") def restorReviewCursorTethering(self): if not self.switchedMode: return @@ -618,7 +618,7 @@ def script_reportExtraInfos(self, gesture): def script_getTableOverview(self, gesture): inTable = brailleInput.handler.table.displayName - ouTable = brailleTablesExt.listTablesDisplayName()[brailleTablesExt.listTablesFileName().index(config.conf["braille"]["translationTable"])] + ouTable = tablegroups.listTablesDisplayName()[tablegroups.listTablesFileName().index(config.conf["braille"]["translationTable"])] t = (_(" Input table")+": %s\n"+_("Output table")+": %s\n\n") % (inTable+' (%s)' % (brailleInput.handler.table.fileName), ouTable+' (%s)' % (config.conf["braille"]["translationTable"])) t += utils.getTableOverview() ui.browseableMessage("
%s
" % t, _("Table overview (%s)" % brailleInput.handler.table.displayName), True) @@ -831,19 +831,19 @@ def script_decreaseDelayAutoScroll(self, gesture): script_decreaseDelayAutoScroll.__doc__ = _("Decreases braille autoscroll delay") def script_switchInputBrailleTable(self, gesture): - usableIn = brailleTablesExt.USABLE_INPUT - choices = brailleTablesExt.getPreferredTables()[0] + brailleTablesExt.getGroups(0)[0] + usageIn = tablegroups.USAGE_INPUT + choices = tablegroups.getPreferredTables()[0] + tablegroups.getGroups(0)[0] if len(choices) < 2: return ui.message(_("Please fill at least two tables and/or groups of tables for this feature first")) - newGroup = brailleTablesExt.getGroup( - position=brailleTablesExt.POSITION_NEXT, - usableIn=usableIn + newGroup = tablegroups.getGroup( + position=tablegroups.POSITION_NEXT, + usageIn=usageIn ) - res = brailleTablesExt.setTableOrGroup( - usableIn=usableIn, + res = tablegroups.setTableOrGroup( + usageIn=usageIn, e=newGroup ) - table = brailleTablesExt.getTable(newGroup.members[0] if newGroup else config.conf["braille"]["inputTable"]) + table = tablegroups.get_table_by_file_name(newGroup.members[0] if newGroup else config.conf["braille"]["inputTable"]) if table: brailleInput.handler._table = table if not res: raise RuntimeError("error") self.reloadBrailleTables() @@ -854,23 +854,23 @@ def script_switchInputBrailleTable(self, gesture): script_switchInputBrailleTable.__doc__ = _("Switch between your favorite input braille tables including groups") def script_switchOutputBrailleTable(self, gesture): - usableIn = brailleTablesExt.USABLE_OUTPUT - choices = brailleTablesExt.getPreferredTables()[1] + brailleTablesExt.getGroups(0)[1] + usageIn = tablegroups.USAGE_OUTPUT + choices = tablegroups.getPreferredTables()[1] + tablegroups.getGroups(0)[1] if len(choices) < 2: return ui.message(_("Please fill at least two tables and/or groups of tables for this feature first")) - newGroup = brailleTablesExt.getGroup( - position=brailleTablesExt.POSITION_NEXT, - usableIn=usableIn + newGroup = tablegroups.getGroup( + position=tablegroups.POSITION_NEXT, + usageIn=usageIn ) - res = brailleTablesExt.setTableOrGroup( - usableIn=usableIn, + res = tablegroups.setTableOrGroup( + usageIn=usageIn, e=newGroup ) if not res: raise RuntimeError("error") self.reloadBrailleTables() utils.refreshBD() dictionaries.setDictTables() - desc = (newGroup.name + (" (%s)" % _("group") if len(newGroup.members) > 1 else '') if newGroup else (_("Default") + " (%s)" % brailleTablesExt.fileName2displayName([config.conf["braille"]["translationTable"]])[0])) + desc = (newGroup.name + (" (%s)" % _("group") if len(newGroup.members) > 1 else '') if newGroup else (_("Default") + " (%s)" % tablegroups.fileName2displayName([config.conf["braille"]["translationTable"]])[0])) ui.message(_("Output: %s") % desc) script_switchOutputBrailleTable.__doc__ = _("Switch between your favorite output braille tables including groups") @@ -878,13 +878,13 @@ def script_switchOutputBrailleTable(self, gesture): def script_currentBrailleTable(self, gesture): inTable = None ouTable = None - if brailleTablesExt.groupEnabled(): - i = brailleTablesExt.getGroup(brailleTablesExt.USABLE_INPUT) - o = brailleTablesExt.getGroup(brailleTablesExt.USABLE_OUTPUT) + if tablegroups.groupEnabled(): + i = tablegroups.getGroup(tablegroups.USAGE_INPUT) + o = tablegroups.getGroup(tablegroups.USAGE_OUTPUT) if i: inTable = i.name if o: ouTable = o.name if not inTable: inTable = brailleInput.handler.table.displayName - if not ouTable: ouTable = brailleTablesExt.listTablesDisplayName()[brailleTablesExt.listTablesFileName().index(config.conf["braille"]["translationTable"])] + if not ouTable: ouTable = tablegroups.listTablesDisplayName()[tablegroups.listTablesFileName().index(config.conf["braille"]["translationTable"])] if ouTable == inTable: braille.handler.message(_("I⣿O:{I}").format(I=inTable, O=ouTable)) speech.speakMessage(_("Input and output: {I}.").format(I=inTable, O=ouTable)) @@ -1268,7 +1268,7 @@ def script_autoTest(self, gesture): def script_addDictionaryEntry(self, gesture): curChar = utils.getCurrentChar() - gui.mainFrame._popupSettingsDialog(dictionaries.DictionaryEntryDlg, title=_("Add dictionary entry or see a dictionary"), textPattern=curChar, specifyDict=True) + gui.mainFrame._popupSettingsDialog(tabledictionaries.DictionaryEntryDlg, title=_("Add dictionary entry or see a dictionary"), textPattern=curChar, specifyDict=True) script_addDictionaryEntry.__doc__ = _("Adds an entry in braille dictionary") def script_toggle_blank_line_scroll(self, gesture): @@ -1318,7 +1318,7 @@ def terminate(self): self.autoScrollTimer.Stop() config.conf["braille"]["showCursor"] = self.backupShowCursor if self.autoTestPlayed: self.autoTestTimer.Stop() - dictionaries.removeTmpDict() + tabledictionaries.removeTmpDict() advancedInputMode.terminate() super().terminate() diff --git a/addon/globalPlugins/brailleExtender/patches.py b/addon/globalPlugins/brailleExtender/patches.py index a0ba3c86..bff49f36 100644 --- a/addon/globalPlugins/brailleExtender/patches.py +++ b/addon/globalPlugins/brailleExtender/patches.py @@ -37,7 +37,6 @@ from . import advancedInputMode from . import brailleRegionHelper from . import configBE -from . import dictionaries from . import huc from . import undefinedChars from .oneHandMode import process as processOneHandMode diff --git a/addon/globalPlugins/brailleExtender/settings.py b/addon/globalPlugins/brailleExtender/settings.py index 67f93fbc..e60a9c31 100644 --- a/addon/globalPlugins/brailleExtender/settings.py +++ b/addon/globalPlugins/brailleExtender/settings.py @@ -20,7 +20,7 @@ import ui addonHandler.initTranslation() -from .brailleTablesExt import SettingsDlg as BrailleTablesDlg +from .tablegroups import SettingsDlg as BrailleTablesDlg from . import configBE from . import utils from .advancedInputMode import SettingsDlg as AdvancedInputModeDlg @@ -481,7 +481,7 @@ class AddonSettingsDialog(gui.settingsDialogs.MultiCategorySettingsDialog): categoryClasses=[ GeneralDlg, AttribraDlg, - BrailleTablesDlg, + #BrailleTablesDlg, UndefinedCharsDlg, AdvancedInputModeDlg, OneHandModeDlg, diff --git a/addon/globalPlugins/brailleExtender/dictionaries.py b/addon/globalPlugins/brailleExtender/tabledictionaries.py similarity index 96% rename from addon/globalPlugins/brailleExtender/dictionaries.py rename to addon/globalPlugins/brailleExtender/tabledictionaries.py index 12c79acd..c20b9b84 100644 --- a/addon/globalPlugins/brailleExtender/dictionaries.py +++ b/addon/globalPlugins/brailleExtender/tabledictionaries.py @@ -4,7 +4,7 @@ from logHandler import log from . import huc -from . import brailleTablesExt +from . import tablegroups from .common import configDir from collections import namedtuple import louis @@ -62,19 +62,19 @@ def checkTable(path): return True -def getValidPathsDict(usableIn): +def getValidPathsDict(usageIn): types = ["tmp", "table", "default"] - paths = [getPathDict(type_, usableIn) for type_ in types] + paths = [getPathDict(type_, usageIn) for type_ in types] def valid(path): return os.path.exists( path) and os.path.isfile(path) and checkTable(path) return [path for path in paths if valid(path)] -def getPathDict(type_, usableIn="io"): - groupEnabled = brailleTablesExt.groupEnabled() - g = brailleTablesExt.getGroup(usableIn=usableIn) +def getPathDict(type_, usageIn="io"): + groupEnabled = tablegroups.groupEnabled() + g = tablegroups.getGroup(usageIn=usageIn) table = os.path.join(configDir, "brailleDicts", config.conf["braille"]["inputTable"] - ) if usableIn == brailleTablesExt.USABLE_INPUT else config.conf["braille"]["translationTable"] + ) if usageIn == tablegroups.USAGE_INPUT else config.conf["braille"]["translationTable"] if type_ == "table": if groupEnabled and g and g.members: if len(g.members) == 1: @@ -135,8 +135,8 @@ def saveDict(type_, dict_): def setDictTables(): global inputTables, outTable - inputTables = getValidPathsDict(brailleTablesExt.USABLE_INPUT) - outputTables = getValidPathsDict(brailleTablesExt.USABLE_OUTPUT) + inputTables = getValidPathsDict(tablegroups.USAGE_INPUT) + outputTables = getValidPathsDict(tablegroups.USAGE_OUTPUT) invalidTables.clear() @@ -362,7 +362,7 @@ def __init__(self, parent=None, title=_("Edit Dictionary Entry"), textPattern='' if specifyDict: # Translators: This is a label for an edit field in add dictionary entry dialog. dictText = _("Dictionary") - outTable = brailleTablesExt.fileName2displayName( + outTable = tablegroups.fileName2displayName( config.conf["braille"]["translationTable"]) dictChoices = [_("Global"), _( "Table ({})").format(outTable), _("Temporary")] @@ -418,7 +418,7 @@ def __init__(self, parent=None, title=_("Edit Dictionary Entry"), textPattern='' self.Bind(wx.EVT_BUTTON, self.onOk, id=wx.ID_OK) def onSeeEntriesClick(self, evt): - outTable = brailleTablesExt.fileName2displayName( + outTable = tablegroups.fileName2displayName( config.conf["braille"]["translationTable"]) label = [_("Global dictionary"), _("Table dictionary ({})").format( outTable), _("Temporary dictionary")][self.dictRadioBox.GetSelection()] diff --git a/addon/globalPlugins/brailleExtender/brailleTablesExt.py b/addon/globalPlugins/brailleExtender/tablegroups.py similarity index 72% rename from addon/globalPlugins/brailleExtender/brailleTablesExt.py rename to addon/globalPlugins/brailleExtender/tablegroups.py index faed3700..b0bf4344 100644 --- a/addon/globalPlugins/brailleExtender/brailleTablesExt.py +++ b/addon/globalPlugins/brailleExtender/tablegroups.py @@ -10,13 +10,12 @@ import addonHandler import config -from collections import namedtuple from itertools import permutations from typing import Optional, List, Tuple from brailleTables import listTables from logHandler import log from . import configBE -from .common import addonName, baseDir, configDir +from .common import baseDir, configDir addonHandler.initTranslation() @@ -25,127 +24,25 @@ POSITION_NEXT = "n" POSITIONS = [POSITION_CURRENT, POSITION_PREVIOUS, POSITION_NEXT] -USABLE_INPUT = 0 -USABLE_OUTPUT = 1 -USABLE_BOTH = 2 -USABLE_LIST = [USABLE_INPUT, USABLE_OUTPUT, USABLE_BOTH] +USAGE_INPUT = 0 +USAGE_OUTPUT = 1 +USAGE_BOTH = 2 +USAGES = [USAGE_INPUT, USAGE_OUTPUT, USAGE_BOTH] -USABLE_LIST_LABELS = { - USABLE_INPUT: _("input only"), - USABLE_OUTPUT: _("output only"), - USABLE_BOTH: _("input and output") +USAGE_LABELS = { + USAGE_INPUT: _("input only"), + USAGE_OUTPUT: _("output only"), + USAGE_BOTH: _("input and output") } -GroupTables = namedtuple("GroupTables", ( - "name", "members", "usableIn")) -conf = config.conf["brailleExtender"]["tables"] +class GroupTable: + name = None + members: list = [] + usageIn = None -def listContractedTables(tables=None): - return [table for table in ( - tables or listTables()) if table.contracted] - -def listUncontractedTables(tables=None): - return [table for table in ( - tables or listTables()) if not table.contracted] - - -def listInputTables(tables=None): - return [ - table for table in (tables or listTables()) if table.input] - - -listUncontractedInputTables = listInputTables(listUncontractedTables()) - - -def listOutputTables(tables=None): - return [ - table for table in (tables or listTables()) if table.output] - - -def listTablesFileName(tables=None): - return [ - table.fileName for table in (tables or listTables())] - - -def listTablesDisplayName(tables=None): - return [ - table.displayName for table in (tables or listTables())] - - -def fileName2displayName(l): - allTablesFileName = listTablesFileName() - o = [] - for e in l: - if e in allTablesFileName: - o.append(allTablesFileName.index(e)) - return [listTables()[e].displayName for e in o] - - -def listTablesIndexes(l, tables): - if not tables: - tables = listTables() - tables = listTablesFileName(tables) - return [tables.index(e) for e in l if e in tables] - - -def getPreferredTables() -> Tuple[List[str]]: - allInputTablesFileName = listTablesFileName(listInputTables()) - allOutputTablesFileName = listTablesFileName(listOutputTables()) - preferredInputTablesFileName = conf["preferredInput"].split( - '|') - preferredOutputTablesFileName = conf["preferredOutput"].split( - '|') - inputTables = [ - fn for fn in preferredInputTablesFileName if fn in allInputTablesFileName] - outputTables = [ - fn for fn in preferredOutputTablesFileName if fn in allOutputTablesFileName] - return inputTables, outputTables - - -def getPreferredTablesIndexes() -> List[int]: - preferredInputTables, preferredOutputTables = getPreferredTables() - inputTables = listTablesFileName(listInputTables()) - outputTables = listTablesFileName(listOutputTables()) - o = [] - for a, b in [(preferredInputTables, inputTables), (preferredOutputTables, outputTables)]: - o_ = [] - for e in a: - if e in b: - o_.append(b.index(e)) - o.append(o_) - return o - - -def getCustomBrailleTables(): - return [config.conf["brailleExtender"]["brailleTables"][k].split('|', 3) for k in config.conf["brailleExtender"]["brailleTables"]] - - -def isContractedTable(fileName): - return fileName in listTablesFileName(listContractedTables()) - - -def getTable(fileName, tables=None): - if not tables: - tables = listTables() - for table in tables: - if table.fileName == fileName: - return table - return None - - -def getTablesFilenameByID(l: List[int], tables=None) -> List[int]: - tablesFileName = [table.fileName for table in (tables or listTables())] - o = [] - size = len(tablesFileName) - for i in l: - if i < size: - o.append(tablesFileName[i]) - return o - - -def translateUsableIn(s): - labels = USABLE_LIST_LABELS +def translateUsageIn(s): + labels = USAGE_LABELS return labels[s] if s in labels.keys() else _("None") @@ -168,7 +65,7 @@ def initializeGroups(): for entry in json_: _groups.append( GroupTables( - entry["name"], entry["members"], entry["usableIn"] + entry["name"], entry["members"], entry["usageIn"] ) ) @@ -180,7 +77,7 @@ def saveGroups(entries=None): { "name": entry.name, "members": entry.members, - "usableIn": entry.usableIn, + "usageIn": entry.usageIn, } for entry in entries ] @@ -192,28 +89,29 @@ def getGroups(plain=True): if plain: return _groups if _groups else [] groups = getGroups() - i = [group for group in groups if group.usableIn in ['i', 'io']] - o = [group for group in groups if group.usableIn in ['o', 'io']] + i = [group for group in groups if group.usageIn in [USAGE_INPUT, USAGE_BOTH]] + o = [group for group in groups if group.usageIn in [USAGE_OUTPUT, USAGE_BOTH]] return i, o -def getAllGroups(usableIn): - usableInIndex = USABLE_LIST.index(usableIn) - return [None] + tablesToGroups(getPreferredTables()[usableInIndex], usableIn=usableIn) + getGroups(0)[usableInIndex] +def getAllGroups(usageIn): + return [None] + usageInIndex = USAGES.index(usageIn) + return [None] + tablesToGroups(getPreferredTables()[usageInIndex], usageIn=usageIn) + getGroups(0)[usageInIndex] def getGroup( - usableIn, + usageIn, position=POSITION_CURRENT, choices=None ): global _currentGroup - if position not in POSITIONS or usableIn not in USABLE_LIST: + if position not in POSITIONS or usageIn not in USAGES: return None - usableInIndex = USABLE_LIST.index(usableIn) - currentGroup = _currentGroup[usableInIndex] + usageInIndex = USAGES.index(usageIn) + currentGroup = _currentGroup[usageInIndex] if not choices: - choices = getAllGroups(usableIn) + choices = getAllGroups(usageIn) if currentGroup not in choices: currentGroup = choices[0] curPos = choices.index(currentGroup) @@ -225,25 +123,25 @@ def getGroup( return choices[newPos % len(choices)] -def setTableOrGroup(usableIn, e, choices=None): +def setTableOrGroup(usageIn, e, choices=None): global _currentGroup - if not usableIn in USABLE_LIST: + if not usageIn in USAGES: return False - usableInIndex = USABLE_LIST.index(usableIn) - choices = getAllGroups(usableIn) + usageInIndex = USAGES.index(usageIn) + choices = getAllGroups(usageIn) if not e in choices: return False - _currentGroup[usableInIndex] = e + _currentGroup[usageInIndex] = e return True -def tablesToGroups(tables, usableIn): +def tablesToGroups(tables, usageIn): groups = [] for table in tables: groups.append(GroupTables( - ", ".join(fileName2displayName([table])), + ", ".join(get_file_name_by_display_name([table])), [table], - usableIn + usageIn )) return groups @@ -286,12 +184,14 @@ def makeSettings(self, settingsSizer): label = _("Input braille table to use for keyboard shortcuts") try: selectedItem = 0 if conf["shortcuts"] == '?' else listTablesFileName( - listUncontractedInputTables + get_tables(input=True, contracted=False) ).index(conf["shortcuts"]) + 1 except ValueError: selectedItem = 0 self.inputTableShortcuts = sHelper.addLabeledControl(label, wx.Choice, choices=[ - currentTableLabel] + listTablesDisplayName(listUncontractedInputTables)) + currentTableLabel] + get_display_names( + get_tables(contracted=False, input=True) + )) self.inputTableShortcuts.SetSelection(selectedItem) self.tablesGroupBtn = bHelper1.addButton( @@ -345,19 +245,19 @@ def isValid(self): return super().isValid() def onSave(self): - inputTables = '|'.join(getTablesFilenameByID( + inputTables = '|'.join(get_tables_file_name_by_id( self.inputTables.CheckedItems, - listInputTables() + get_tables(input=True) )) outputTables = '|'.join( - getTablesFilenameByID( + get_tables_file_name_by_id( self.outputTables.CheckedItems, - listOutputTables() + get_tables(output=True) ) ) - tablesShortcuts = getTablesFilenameByID( + tablesShortcuts = get_tables_file_name_by_id( [self.inputTableShortcuts.GetSelection()-1], - listUncontractedInputTables + get_tables(contracted=False, input=True) )[0] if self.inputTableShortcuts.GetSelection() > 0 else '?' conf["preferredInput"] = inputTables conf["preferredOutput"] = outputTables @@ -372,7 +272,7 @@ def postSave(self): class TableGroupsDlg(gui.settingsDialogs.SettingsDialog): # Translators: title of a dialog. - title = f"{addonName} - %s" % _("table groups") + title = _("Table groups") def makeSettings(self, settingsSizer): self.tmpGroups = getGroups() @@ -427,8 +327,8 @@ def onSetEntries(self, evt=None): for group in self.tmpGroups: self.groupsList.Append(( group.name, - ", ".join(fileName2displayName(group.members)), - translateUsableIn(group.usableIn) + ", ".join(FileName2displayName(group.members)), + translateUsageIn(group.usageIn) )) def onAddClick(self, event): @@ -437,8 +337,8 @@ def onAddClick(self, event): entry = entryDialog.groupEntry self.tmpGroups.append(entry) self.groupsList.Append( - (entry.name, ", ".join(fileName2displayName(entry.members)), - translateUsableIn(entry.usableIn)) + (entry.name, ", ".join(FileName2displayName(entry.members)), + translateUsageIn(entry.usageIn)) ) index = self.groupsList.GetFirstSelected() while index >= 0: @@ -457,25 +357,25 @@ def onEditClick(self, event): entryDialog = GroupEntryDlg(self) entryDialog.name.SetValue(self.tmpGroups[editIndex].name) entryDialog.members.CheckedItems = listTablesIndexes( - self.tmpGroups[editIndex].members, listUncontractedInputTables) + self.tmpGroups[editIndex].members, get_tables(contracted=False, input=True)) entryDialog.refreshOrders() selectedItem = 0 try: selectedItem = list(entryDialog.orderPermutations.keys()).index(tuple( - listTablesIndexes(self.tmpGroups[editIndex].members, listUncontractedTables()))) + listTablesIndexes(self.tmpGroups[editIndex].members, get_tables(contracted=False)))) entryDialog.order.SetSelection(selectedItem) except ValueError: pass - entryDialog.usableIn.CheckedItems = translateUsableInIndexes( - self.tmpGroups[editIndex].usableIn) + entryDialog.usageIn.CheckedItems = translateUsageInIndexes( + self.tmpGroups[editIndex].usageIn) if entryDialog.ShowModal() == wx.ID_OK: entry = entryDialog.groupEntry self.tmpGroups[editIndex] = entry self.groupsList.SetItem(editIndex, 0, entry.name) self.groupsList.SetItem(editIndex, 1, ", ".join( - fileName2displayName(entry.members))) + FileName2displayName(entry.members))) self.groupsList.SetItem( - editIndex, 2, translateUsableIn(entry.usableIn)) + editIndex, 2, translateUsageIn(entry.usageIn)) self.groupsList.SetFocus() entryDialog.Destroy() @@ -515,21 +415,23 @@ def __init__(self, parent=None, title=_("Edit Dictionary Entry")): super().__init__(parent, title=title) mainSizer = wx.BoxSizer(wx.VERTICAL) sHelper = gui.guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL) - self.name = sHelper.addLabeledControl(_("Group &name"), wx.TextCtrl) + self.name = sHelper.addLabeledControl(_("Group &name:"), wx.TextCtrl) label = _("Group &members") self.members = sHelper.addLabeledControl( - label, gui.nvdaControls.CustomCheckListBox, choices=listTablesDisplayName(listUncontractedTables())) + label, gui.nvdaControls.CustomCheckListBox, choices=get_display_names( + get_tables(contracted=False) + )) self.members.SetSelection(0) self.members.Bind(wx.EVT_CHECKLISTBOX, lambda s: self.refreshOrders()) - label = _("Table &order") + label = _("Table &order:") self.order = sHelper.addLabeledControl( label, wx.Choice, choices=[]) self.refreshOrders() - label = _("&Usable in") - choices = list(USABLE_LIST_LABELS.values()) - self.usableIn = sHelper.addItem(wx.RadioBox(self, + label = _("&Usable in:") + choices = list(USAGE_LABELS.values()) + self.usageIn = sHelper.addItem(wx.RadioBox(self, label=label, choices=choices)) - self.usableIn.SetSelection(1) + self.usageIn.SetSelection(1) sHelper.addDialogDismissButtons( self.CreateButtonSizer(wx.OK | wx.CANCEL)) mainSizer.Add(sHelper.sizer, border=20, flag=wx.ALL) @@ -539,9 +441,8 @@ def __init__(self, parent=None, title=_("Edit Dictionary Entry")): self.name.SetFocus() def refreshOrders(self, evt=None): - tables = listUncontractedTables() - self.orderPermutations = {e: fileName2displayName(getTablesFilenameByID( - e, tables)) for e in permutations(self.members.CheckedItems) if e} + tables = get_tables(contracted=False) + self.orderPermutations = {e: FileName2displayName(get_tables_file_name_by_id(e, tables)) for e in permutations(self.members.CheckedItems) if e} self.order.SetItems([", ".join(e) for e in self.orderPermutations.values()]) self.order.SetSelection(0) @@ -550,10 +451,10 @@ def onOk(self, evt): name = self.name.Value if not self.orderPermutations: return - members = getTablesFilenameByID(list(self.orderPermutations.keys())[ - self.order.GetSelection()], listUncontractedTables()) - matches = ['i', 'o'] - usableIn = ''.join([matches[e] for e in self.usableIn.CheckedItems]) + members = get_tables_file_name_by_id(list(self.orderPermutations.keys())[ + self.order.GetSelection()], get_tables(contracted=False)) + matches = USAGE_LABELS.keys() + usageIn = ''.join([matches[e] for e in self.usageIn.CheckedItems]) if not name: gui.messageBox( _("Please specify a group name"), @@ -570,14 +471,14 @@ def onOk(self, evt): self ) return self.members.SetFocus() - self.groupEntry = GroupTables(name, members, usableIn) + self.groupEntry = GroupTables(name, members, usageIn) evt.Skip() class CustomBrailleTablesDlg(gui.settingsDialogs.SettingsDialog): # Translators: title of a dialog. - title = f"{addonName} - %s" % _("Custom braille tables") + title = _("Custom braille tables") providedTablesPath = "%s/res/json" % baseDir userTablesPath = "%s/json" % configDir @@ -648,7 +549,7 @@ def onBrowseBtn(self, event): if dlg.ShowModal() != wx.ID_OK: dlg.Destroy() return self.path.SetFocus() - self.path.SetValue(dlg.GetDirectory() + '\\' + dlg.GetFilename()) + self.path.SetValue(dlg.GetDirectory() + '\\' + dlg.GetFileName()) dlg.Destroy() self.path.SetFocus() diff --git a/addon/globalPlugins/brailleExtender/tablehelper.py b/addon/globalPlugins/brailleExtender/tablehelper.py new file mode 100644 index 00000000..0f924e8a --- /dev/null +++ b/addon/globalPlugins/brailleExtender/tablehelper.py @@ -0,0 +1,63 @@ +# tablehelper.py +# Part of BrailleExtender addon for NVDA +# Copyright 2016-2020 André-Abush CLAUSE, released under GPL. +from brailleTables import listTables +from typing import List + +def get_tables(tables=None, contracted=None, output=None, input=None): + if not tables: + tables = listTables() + if isinstance(contracted, bool): + tables = filter(lambda e: e.contracted == contracted, tables) + if isinstance(input, bool): + tables = filter(lambda e: e.input == input, tables) + if isinstance(output, bool): + tables = filter(lambda e: e.output == output, tables) + return list(tables) + + +def get_file_names(tables=None): + if not tables: + tables = listTables() + return [table.fileName for table in tables] + + +def get_file_names_by_display_names(l): + file_names = get_file_names() + o = [] + for e in l: + if e in file_names: + o.append(file_names.index(e)) + return [listTables()[e].displayName for e in o] + + +def get_display_names(tables=None): + if not tables: + tables = listTables() + return [table.displayName for table in tables] + + +def get_indexes(l, tables): + if not tables: + tables = listTables() + tables = get_file_names(tables) + return [tables.index(e) for e in l if e in tables] + + +def get_table_by_file_name(FileName, tables=None): + if not tables: + tables = listTables() + for table in tables: + if table.fileName == FileName: + return table + return None + + +def get_tables_file_name_by_id(l: List[int], tables=None) -> List[int]: + file_names = get_file_names(tables or listTables()) + o = [] + size = len(file_names) + for i in l: + if i < size: + o.append(file_names[i]) + return o diff --git a/addon/globalPlugins/brailleExtender/undefinedChars.py b/addon/globalPlugins/brailleExtender/undefinedChars.py index 5f9d7951..000c6561 100644 --- a/addon/globalPlugins/brailleExtender/undefinedChars.py +++ b/addon/globalPlugins/brailleExtender/undefinedChars.py @@ -6,7 +6,7 @@ import wx import addonHandler -from . import brailleTablesExt +from . import tablehelper import characterProcessing import config import gui @@ -309,8 +309,8 @@ def makeSettings(self, settingsSizer): _("&Language"), wx.Choice, choices=values ) self.undefinedCharLang.SetSelection(undefinedCharLangID) - values = [_("Use the current output table")] + brailleTablesExt.listTablesDisplayName(brailleTablesExt.listOutputTables()) - keys = ["current"] + brailleTablesExt.listTablesFileName(brailleTablesExt.listOutputTables()) + values = [_("Use the current output table")] + tablehelper.get_display_names(tablehelper.get_tables(output=True)) + keys = ["current"] + tablehelper.get_file_names(tablehelper.get_tables(output=True)) undefinedCharTable = config.conf["brailleExtender"]["undefinedCharsRepr"][ "table" ] @@ -404,7 +404,7 @@ def onSave(self): 0 ] undefinedCharTable = self.undefinedCharTable.GetSelection() - keys = ["current"] + brailleTablesExt.listTablesFileName(brailleTablesExt.listOutputTables()) + keys = ["current"] + tablehelper.get_file_names(tablehelper.get_tables(output=True)) config.conf["brailleExtender"]["undefinedCharsRepr"]["table"] = keys[ undefinedCharTable ] diff --git a/addon/globalPlugins/brailleExtender/utils.py b/addon/globalPlugins/brailleExtender/utils.py index ebc6fd1c..c42126e8 100644 --- a/addon/globalPlugins/brailleExtender/utils.py +++ b/addon/globalPlugins/brailleExtender/utils.py @@ -22,12 +22,13 @@ addonHandler.initTranslation() import treeInterceptorHandler import unicodedata -from . import brailleTablesExt +from . import tablegroups from .configBE import CHOICE_braille,CHOICE_speech , CHOICE_speechAndBraille from .common import INSERT_AFTER, INSERT_BEFORE, REPLACE_TEXT, baseDir from . import huc -from . import dictionaries +from . import tabledictionaries from . import volume_helper +from logHandler import log get_mute = volume_helper.get_mute get_volume_level = volume_helper.get_volume_level @@ -143,6 +144,9 @@ def getTextInBraille(t=None, table=[]): if not t.strip(): return '' if not table or "current" in table: table = getCurrentBrailleTables() + for i, e in enumerate(table): + if '\\' not in e and '/' not in e: + table[i] = "%s\\%s" % (brailleTables.TABLES_DIR, e) nt = [] res = '' t = t.split("\n") @@ -332,13 +336,13 @@ def getCurrentBrailleTables(input_=False, brf=False): else: tables = [] app = appModuleHandler.getAppModuleForNVDAObject(api.getNavigatorObject()) - if brailleInput.handler._table.fileName == config.conf["braille"]["translationTable"] and app and app.appName != "nvda": tables += dictionaries.inputTables if input_ else dictionaries.outputTables + if brailleInput.handler._table.fileName == config.conf["braille"]["translationTable"] and app and app.appName != "nvda": tables += tabledictionaries.inputTables if input_ else tabledictionaries.outputTables if input_: mainTable = os.path.join(brailleTables.TABLES_DIR, brailleInput.handler._table.fileName) - group = brailleTablesExt.getGroup(usableIn='i') + group = tablegroups.getGroup(usageIn=tablegroups.USAGE_OUTPUT) else: mainTable = os.path.join(brailleTables.TABLES_DIR, config.conf["braille"]["translationTable"]) - group = brailleTablesExt.getGroup(usableIn='o') + group = tablegroups.getGroup(usageIn=tablegroups.USAGE_OUTPUT) if group: group = group.members group = [f if '\\' in f else os.path.join(r"louis\tables", f) for f in group]