def install(self, filePath): """Install dictionary""" extention = os.path.splitext(filePath)[1][1:] succeeded = False try: if extention.lower() in dicttype.PLUGIN.getFileExtentions(): try: directory, dtype = installPlugin(filePath) if directory: if dtype.lower() == 'plugin': dictionary = newplugin._loadDictionaryPlugin(directory) else: dictionary = plaindict._loadPlainDictionary(directory) self.mainWin.addDictionary(dictionary) succeeded = True except Exception, e: errorwin.showErrorMessage(_("Installation failed"), e.args[0] or '') self.mainWin.SetStatusText(_("Installation failed")) return else:
def onTimerUpdateDB(self, event): systemLog(DEBUG, "DictConnection: [IDLE] Receiving DB list...") if self.update != None: if self.update.isDone(): systemLog(DEBUG, "DictConnection: DB list received") obj = self.update() if type(obj) == type({}): self.timerUpdateDB.Stop() self.update = None self.choiceDB.Clear() self.choiceDB.Append(self.msgSearchInAll) for name in obj.values(): self.choiceDB.Append(name) self.SetStatusText(_("Done")) self.choiceDB.SetValue(self.msgSearchInAll) self.choiceDB.SetInsertionPoint(0) elif obj != None: self.SetStatusText(_("Receiving database list...")) self.update = Process(obj.getdbdescs) else: self.timerUpdateDB.Stop() self.SetStatusText('') title = _("Connection Error") msg = _("Unable to connect to server") errorwin.showErrorMessage(title, msg)
def onPronounce(self, event): """Pronouce word using external software.""" word = self.entry.GetValue().strip() if word: cmd = self.app.config.get( 'pronunciationCommand') or prefswin.PRON_COMMAND if self.app.config.get('pronounceTrans') == 'True': word = html2text(self.htmlCode) import locale localeCharset = locale.getpreferredencoding() try: word = word.replace('(', '').replace(')', '').replace( '\n', '').replace('\r', '').replace('"', '\\"') cmd = (cmd % word).encode(localeCharset) Process(os.system, cmd) except Exception as e: traceback.print_exc() title = _("Error") msg = _("Unable to decode text using your locale charset %s" \ % localeCharset) errorwin.showErrorMessage(title, msg)
def OnLinkClicked(self, linkInfo): global lastLookupWord lastLookupWord = linkInfo.GetHref() wx.BeginBusyCursor() parent = self.GetParent().GetParent().GetParent() word = enc.fromWX(lastLookupWord) try: word = word.encode(parent.activeDictionary.getEncoding()) except Exception as e: # FIXME: Code duplicates traceback.print_exc() parent.buttonStop.Disable() parent.entry.Enable(True) parent.timerSearch.Stop() parent.SetStatusText(_('Stopped')) wx.EndBusyCursor() systemLog(ERROR, "Unable to decode '%s': %s" % (word.encode('UTF-8'), e)) title = _("Encode Failed") msg = _("Unable to encode text \"%s\" in %s for \"%s\".") \ % (enc.toWX(word), parent.activeDictionary.getEncoding(), parent.activeDictionary.getName()) errorwin.showErrorMessage(title, msg) return parent.SetStatusText(_("Searching...")) parent.entry.SetValue(word) parent.timerSearch.Start(parent.delay) parent.search = Process(parent.activeDictionary.search, word)
def install(self, filePath): """Install dictionary""" extention = os.path.splitext(filePath)[1][1:] succeeded = False try: if extention.lower() in dicttype.PLUGIN.getFileExtentions(): try: directory, dtype = installPlugin(filePath) if directory: if dtype.lower() == 'plugin': dictionary = newplugin._loadDictionaryPlugin( directory) else: dictionary = plaindict._loadPlainDictionary( directory) self.mainWin.addDictionary(dictionary) succeeded = True except Exception, e: errorwin.showErrorMessage(_("Installation failed"), e.args[0] or '') self.mainWin.SetStatusText(_("Installation failed")) return else:
def onRemove(self, event): """Remove button pressed""" systemLog( INFO, "Removing %s" % self.installedList.GetString(self.currentInstalledItemSelection)) dictName = self.installedList.GetString( self.currentInstalledItemSelection) dictInstance = self.app.dictionaries.get(dictName) try: if dictInstance.getType() == dicttype.PLUGIN: removeDictionary = installer.removePluginDictionary else: removeDictionary = installer.removePlainDictionary removeDictionary(dictInstance) except Exception, e: traceback.print_exc() title = _("Unable to remove") msg = _("Unable to remove dictionary \"%s\"") % dictName errorwin.showErrorMessage(title, msg) return
def onTimerUpdateDB(self, event): systemLog(DEBUG, "DictConnection: [IDLE] Receiving DB list...") if self.update != None: if self.update.isDone(): systemLog(DEBUG, "DictConnection: DB list received") obj = self.update() if type(obj) == type({}): self.timerUpdateDB.Stop() self.update = None self.choiceDB.Clear() self.choiceDB.Append(self.msgSearchInAll) for name in list(obj.values()): self.choiceDB.Append(name) self.SetStatusText(_("Done")) self.choiceDB.SetValue(self.msgSearchInAll) self.choiceDB.SetInsertionPoint(0) elif obj != None: self.SetStatusText(_("Receiving database list...")) self.update = Process(obj.getdbdescs) else: self.timerUpdateDB.Stop() self.SetStatusText('') title = _("Connection Error") msg = _("Unable to connect to server") errorwin.showErrorMessage(title, msg)
def onRemove(self, event): path = self.dicts[event.GetId()] try: shutil.rmtree(path) self.buttons[event.GetId()].Disable() except Exception, e: traceback.print_exc() title = _("Unable to remove") msg = _("Unable to remove directory \"%s\": %s") % (path, e) errorwin.showErrorMessage(title, msg)
def onRemove(self, event): path = self.dicts[event.GetId()] try: shutil.rmtree(path) self.buttons[event.GetId()].Disable() except Exception as e: traceback.print_exc() title = _("Unable to remove") msg = _("Unable to remove directory \"%s\": %s") % (path, e) errorwin.showErrorMessage(title, msg)
def install(self, filePath): """Install dictionary""" extention = os.path.splitext(filePath)[1][1:] succeeded = False try: if extention.lower() in dicttype.PLUGIN.getFileExtentions(): try: directory, dtype = installPlugin(filePath) if directory: if dtype.lower() == 'plugin': dictionary = newplugin._loadDictionaryPlugin( directory) else: dictionary = plaindict._loadPlainDictionary( directory) self.mainWin.addDictionary(dictionary) succeeded = True except Exception as e: errorwin.showErrorMessage(_("Installation failed"), e.args[0] or '') self.mainWin.SetStatusText(_("Installation failed")) return else: try: directory = installPlainDictionary(filePath) if directory: dictionary = plaindict._loadPlainDictionary(directory) self.mainWin.addDictionary(dictionary) succeeded = True except Exception as e: traceback.print_exc() errorwin.showErrorMessage(_("Installation Error"), e.args[0] or '') self.mainWin.SetStatusText(_("Error: Installation failed")) return except: # Can this happen? self.mainWin.SetStatusText(_("Error: Installation failed")) traceback.print_exc() if succeeded: title = _("Dictionary installed") msg = _("Dictionary successfully installed. You can choose it " \ "from \"Dictionaries\" menu now.") errorwin.showInfoMessage(title, msg)
def onTimerConnect(self, event): if self.connection != None: if self.connection.isDone(): systemLog(INFO, "Connection timer stopped") self.timerConnect.Stop() self.conn = self.connection() if self.conn == None: self.SetStatusText('') title = _("Connection Error") msg = _("Unable to connect to server") errorwin.showErrorMessage(title, msg) else: self.prepareForUsing()
def onShowPrefsWindow(self, event): try: self.prefsWindow = PrefsWindow(self, -1, _("Preferences"), size=(-1, -1), style=wx.DEFAULT_FRAME_STYLE) self.prefsWindow.CentreOnScreen() self.prefsWindow.Show(True) except Exception as e: traceback.print_exc() systemLog(ERROR, "Unable to show preferences window: %s" % e) title = errortype.OPENDICT_BUG.getMessage() msg = errortype.OPENDICT_BUG.getLongMessage() errorwin.showErrorMessage(title, msg)
def onRemove(self, event): """Remove button pressed""" systemLog( INFO, "Removing %s" % self.installedList.GetString(self.currentInstalledItemSelection)) dictName = self.installedList.GetString( self.currentInstalledItemSelection) dictInstance = self.app.dictionaries.get(dictName) try: if dictInstance.getType() == dicttype.PLUGIN: removeDictionary = installer.removePluginDictionary else: removeDictionary = installer.removePlainDictionary removeDictionary(dictInstance) except Exception as e: traceback.print_exc() title = _("Unable to remove") msg = _("Unable to remove dictionary \"%s\"") % dictName errorwin.showErrorMessage(title, msg) return self.installedList.Delete(self.currentInstalledItemSelection) idDictMenuItem = None for iid, dictionary in list(self.app.config.ids.items()): if dictionary == dictName: idDictMenuItem = iid if idDictMenuItem is not None: self.mainWin.menuDict.Delete(idDictMenuItem) parent = self.GetParent() if parent.activeDictionary \ and dictName == parent.activeDictionary.getName(): parent.onCloseDict(None) self.buttonRemove.Disable() del self.app.dictionaries[dictName] self.clearInfo() self.disableInfo()
def open(self): wildCard = "Slowo dictionaries (*.dwa)|*.dwa" dialog = wx.FileDialog(self, message=_("Choose dictionary file"), wildcard=wildCard, style=wx.FD_OPEN | wx.FD_MULTIPLE) if dialog.ShowModal() == wx.ID_OK: name = os.path.split(dialog.GetPaths()[0])[1] self.filePath = dialog.GetPaths()[0] self.name = os.path.split(self.filePath)[1] wx.BeginBusyCursor() try: self.editor.load(self.filePath) except Exception as e: wx.EndBusyCursor() traceback.print_exc() title = _("Open Failed") msg = _("Unable to open dictionary (got message: %s)") % e errorwin.showErrorMessage(title, msg) return self.SetTitle("%s - %s" % (self.priTitle, self.name)) self.list.Clear() words = [] for unit in self.editor.getUnits(): words.append(enc.toWX(unit.getWord())) words.sort() self.list.InsertItems(words, 0) self.checkAllButtons() self.SetStatusText(_("Dictionary loaded")) wx.EndBusyCursor()
def showGUI(self): """Show graphical window for selecting files and formats""" wildCard = "All files (*.*)|*.*|" \ "OpenDict plugins (*.zip)|*.zip|" \ "Slowo dictionaries (*.dwa)|*.dwa|" \ "Mova dictionaries (*.mova)|*.mova|" \ "DICT dictionaries (*.dz)|*.dz" fileDialog = wx.FileDialog(self.mainWin, message=_("Choose dictionary file"), wildcard=wildCard, style=wx.OPEN|wx.CHANGE_DIR) fileDialog.CentreOnScreen() if fileDialog.ShowModal() == wx.ID_OK: filePath = fileDialog.GetPaths()[0] else: fileDialog.Destroy() return fileName = os.path.basename(filePath) extention = os.path.splitext(fileName)[1][1:] extMapping = {} for t in dicttype.supportedTypes: for ext in t.getFileExtentions(): extMapping[ext.lower()] = t if not extention.lower() in extMapping.keys(): title = _("Recognition Error") msg = _("File %s is not supported by OpenDict") % fileName errorwin.showErrorMessage(title, msg) return else: self.install(filePath)
def open(self): wildCard = "Slowo dictionaries (*.dwa)|*.dwa" dialog = wx.FileDialog(self, message=_("Choose dictionary file"), wildcard=wildCard, style=wx.OPEN|wx.MULTIPLE) if dialog.ShowModal() == wx.ID_OK: name = os.path.split(dialog.GetPaths()[0])[1] self.filePath = dialog.GetPaths()[0] self.name = os.path.split(self.filePath)[1] wx.BeginBusyCursor() try: self.editor.load(self.filePath) except Exception, e: wx.EndBusyCursor() traceback.print_exc() title = _("Open Failed") msg = _("Unable to open dictionary (got message: %s)") % e errorwin.showErrorMessage(title, msg) return self.SetTitle("%s - %s" % (self.priTitle, self.name)) self.list.Clear() words = [] for unit in self.editor.getUnits(): words.append(enc.toWX(unit.getWord())) words.sort() self.list.InsertItems(words, 0) self.checkAllButtons() self.SetStatusText(_("Dictionary loaded")) wx.EndBusyCursor()
def onRemove(self, event): """Remove button pressed""" systemLog(INFO, "Removing %s" % self.installedList.GetString( self.currentInstalledItemSelection)) dictName = self.installedList.GetString( self.currentInstalledItemSelection) dictInstance = self.app.dictionaries.get(dictName) try: if dictInstance.getType() == dicttype.PLUGIN: removeDictionary = installer.removePluginDictionary else: removeDictionary = installer.removePlainDictionary removeDictionary(dictInstance) except Exception, e: traceback.print_exc() title = _("Unable to remove") msg = _("Unable to remove dictionary \"%s\"") % dictName errorwin.showErrorMessage(title, msg) return
def showGUI(self): """Show graphical window for selecting files and formats""" wildCard = "All files (*.*)|*.*|" \ "OpenDict plugins (*.zip)|*.zip|" \ "Slowo dictionaries (*.dwa)|*.dwa|" \ "Mova dictionaries (*.mova)|*.mova|" \ "DICT dictionaries (*.dz)|*.dz" fileDialog = wx.FileDialog(self.mainWin, message=_("Choose dictionary file"), wildcard=wildCard, style=wx.FD_OPEN | wx.FD_CHANGE_DIR) fileDialog.CentreOnScreen() if fileDialog.ShowModal() == wx.ID_OK: filePath = fileDialog.GetPaths()[0] else: fileDialog.Destroy() return fileName = os.path.basename(filePath) extention = os.path.splitext(fileName)[1][1:] extMapping = {} for t in dicttype.supportedTypes: for ext in t.getFileExtentions(): extMapping[ext.lower()] = t if not extention.lower() in extMapping.keys(): title = _("Recognition Error") msg = _("File %s is not supported by OpenDict") % fileName errorwin.showErrorMessage(title, msg) return else: self.install(filePath)
def _installNormalPlugin(filePath): """Install 'normal' OpenDict plugin""" zipFile = zipfile.ZipFile(filePath, 'r') topDirectory = zipFile.namelist()[0] pluginsPath = os.path.join(info.LOCAL_HOME, info.PLUGIN_DICT_DIR) # Check if already installed if os.path.exists(os.path.join(info.LOCAL_HOME, info.PLUGIN_DICT_DIR, topDirectory)): raise Exception, _("This dictionary already installed. " \ "If you want to upgrade it, please remove " \ "old version first.") installFile = os.path.join(topDirectory, 'install.py') if installFile in zipFile.namelist(): data = zipFile.read(installFile) try: struct = {} exec data in struct except Exception, e: title = _("Installation Error") msg = _("Installation tool for this dictionary failed to start. " \ "Please report this problem to developers.") errorwin.showErrorMessage(title, msg) return install = struct.get('install') if not install: title = _("Installation Error") msg = _("Installation tool for this dictionary failed to start. " \ "Please report this problem to developers.") errorwin.showErrorMessage(title, msg) return if not install(info.GLOBAL_HOME, info.LOCAL_HOME): title = _("Installation Aborted") msg = _("Dictionary installation has been aborted.") errorwin.showErrorMessage(title, msg) return
def _installNormalPlugin(filePath): """Install 'normal' OpenDict plugin""" zipFile = zipfile.ZipFile(filePath, 'r') topDirectory = zipFile.namelist()[0] pluginsPath = os.path.join(info.LOCAL_HOME, info.PLUGIN_DICT_DIR) # Check if already installed if os.path.exists( os.path.join(info.LOCAL_HOME, info.PLUGIN_DICT_DIR, topDirectory)): raise Exception, _("This dictionary already installed. " \ "If you want to upgrade it, please remove " \ "old version first.") installFile = os.path.join(topDirectory, 'install.py') if installFile in zipFile.namelist(): data = zipFile.read(installFile) try: struct = {} exec data in struct except Exception, e: title = _("Installation Error") msg = _("Installation tool for this dictionary failed to start. " \ "Please report this problem to developers.") errorwin.showErrorMessage(title, msg) return install = struct.get('install') if not install: title = _("Installation Error") msg = _("Installation tool for this dictionary failed to start. " \ "Please report this problem to developers.") errorwin.showErrorMessage(title, msg) return if not install(info.GLOBAL_HOME, info.LOCAL_HOME): title = _("Installation Aborted") msg = _("Dictionary installation has been aborted.") errorwin.showErrorMessage(title, msg) return
def onUpdate(self, event): """Update dictionaries list""" title = _("Downloading List") downloader = util.DownloadThread( self.app.config.get('repository-list')) progressDialog = wx.ProgressDialog(title, '', maximum=100, parent=self, style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL) keepGoing = True error = None try: systemLog(INFO, "Opening %s..." % \ self.app.config.get('repository-list')) downloader.start() xmlData = '' while keepGoing and not downloader.finished(): keepGoing = progressDialog.Update(downloader.getPercentage(), downloader.getMessage()) if not keepGoing: downloader.stop() break xmlData += downloader.getBytes() time.sleep(0.1) progressDialog.Destroy() xmlData += downloader.getBytes() systemLog(INFO, "Finished downloading list") except Exception as e: traceback.print_exc() progressDialog.Destroy() error = _("Unable to download list from %s: %s") \ % (self.app.config.get('repository-list'), e) if not error: error = downloader.getErrorMessage() if error: systemLog(ERROR, error) title = _("Unable to download list") errorwin.showErrorMessage(title, error) return if len(xmlData) == 0: return if hasattr(self, "addons"): del self.addons allAddons = xmltools.parseAddOns(xmlData) self.addons = {} for name, obj in list(allAddons.items()): if name in list(self.app.dictionaries.keys()) \ and obj.getVersion() <= (\ self.app.dictionaries.get(name).getVersion() or ""): continue self.addons[name] = obj app = wx.GetApp() if "addons" in app.cache: del app.cache["addons"] app.cache["addons"] = self.addons self.setAvailDicts(self.addons)
def _fetchAddon(self, dictInfo): """Fetch add-on using progress bar""" downloadsDir = os.path.join(info.LOCAL_HOME, 'downloads') if not os.path.exists(downloadsDir): os.mkdir(downloadsDir) localPath = os.path.join(downloadsDir, os.path.basename(dictInfo.getLocation())) title = _("Downloading %s...") % dictInfo.getName() progressDialog = wx.ProgressDialog(title, '', maximum=100, parent=self, style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL) keepGoing = True error = None downloader = util.DownloadThread(dictInfo.getLocation()) stopped = False try: fd = open(localPath, 'wb') downloader.start() while keepGoing and not downloader.finished(): keepGoing = progressDialog.Update(downloader.getPercentage(), downloader.getMessage()) if not keepGoing: stopped = True break chunk = downloader.getBytes() fd.write(chunk) time.sleep(0.1) bytes = downloader.getBytes() if len(bytes): fd.write(bytes) progressDialog.Destroy() downloader.stop() except Exception as e: traceback.print_exc() progressDialog.Destroy() error = "Unable to fetch \"%s\" from %s: %s" \ % (dictInfo.getName(), dictInfo.getLocation(), e) systemLog(ERROR, error) fd.close() if stopped: return if not error: error = downloader.getErrorMessage() if error: systemLog(ERROR, error) title = _("Unable to download") errorwin.showErrorMessage(title, error) return md5sum = util.getMD5Sum(localPath) # # Check checksum # if md5sum != dictInfo.getChecksum(): title = _("File is damaged") msg = _("Downloaded file is damaged and cannot be installed. " \ "Please try again.") errorwin.showErrorMessage(title, msg) return # # Remove old version if exists # if dictInfo.getName() in list(self.app.dictionaries.keys()): try: dictInstance = self.app.dictionaries.get(dictInfo.getName()) if dictInstance.getType() == dicttype.PLUGIN: installer.removePluginDictionary(dictInstance) else: installer.removePlainDictionary(dictInstance) except Exception as e: traceback.print_exc() title = _("Error") msg = _("Unable to remove old version of \"%s\". " "Error occured: \"<i>%s</i>\". New version " "cannot be installed without removing old one.") \ % (dictInstance.getName(), e) errorwin.showErrorMessage(title, msg) return # # Install # try: inst = installer.Installer(self.mainWin, self.app.config) inst.install(localPath) if self.installedList.FindString( dictInfo.getName()) == wx.NOT_FOUND: index = self.installedList.Insert(dictInfo.getName(), 0) self.installedList.Check(0) self.app.config.activedict.add(dictInfo.getName()) self.app.config.activedict.save() # FIXME: Code-wasting. Separated duplicated code into # functions. except Exception as e: traceback.print_exc() title = _("Unable to install") msg = _("Unable to install dictionary \"%s\".") \ % dictInfo.getName() errorwin.showErrorMessage(title, msg) return self.availableList.DeleteItem(self.currentAvailItemSelection) del self.addons[dictInfo.getName()] self.buttonInstall.Disable() self.clearInfo() self.disableInfo()
class PluginManagerWindow(wx.Frame): """Plugin Manager lets install, remove and view info about installed plugins""" def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE): wx.Frame.__init__(self, parent, id, title, pos, size, style) self.app = wx.GetApp() self.mainWin = parent self.currentInstalledItemSelection = -1 self.currentAvailItemSelection = -1 vboxMain = wx.BoxSizer(wx.VERTICAL) self.installedDictionaries = {} self.availDictionaries = self.app.cache.get('addons') or {} installed = True for dictName in self.app.dictionaries.keys(): self.installedDictionaries[dictName] = installed tabbedPanel = wx.Notebook(self, -1) # Add 'installed' panel panelInstalled = self._makeInstalledPanel(tabbedPanel) tabbedPanel.AddPage(panelInstalled, _("Installed")) # Add 'available' panel panelAvailable = self._makeAvailablePanel(tabbedPanel) tabbedPanel.AddPage(panelAvailable, _("Available")) vboxMain.Add(tabbedPanel, 1, wx.ALL | wx.EXPAND, 2) # Add info panel panelInfo = self._makeInfoPanel() vboxMain.Add(panelInfo, 0, wx.ALL | wx.EXPAND, 2) hboxButtons = wx.BoxSizer(wx.HORIZONTAL) self.buttonClose = wx.Button(self, 163, _("Close")) hboxButtons.Add(self.buttonClose, 0, wx.ALL | wx.ALIGN_RIGHT, 3) vboxMain.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 1) self.SetIcon( wx.Icon( os.path.join(info.GLOBAL_HOME, "pixmaps", "icon-24x24.png"), wx.BITMAP_TYPE_PNG)) self.SetSizer(vboxMain) self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.onPageChanged) wx.EVT_BUTTON(self, 161, self.onInstall) wx.EVT_BUTTON(self, 162, self.onRemove) wx.EVT_BUTTON(self, 163, self.onClose) self.addons = self.app.cache.get("addons", {}) def _makeInstalledPanel(self, tabbedPanel): """Creates panel with for controlling installed dictionaries""" # # Boxes # panelInstalled = wx.Panel(tabbedPanel, -1) vboxInstalled = wx.BoxSizer(wx.VERTICAL) # Help message labelHelp = wx.StaticText(panelInstalled, -1, _("Checked dictionaries are available from the " \ "menu, unchecked dictionaries \nare not available from the menu.")) vboxInstalled.Add(labelHelp, 0, wx.ALL, 3) # # Installed list # idDictList = wx.NewId() self.installedList = wx.CheckListBox(panelInstalled, idDictList, style=wx.LC_REPORT | wx.LC_SINGLE_SEL | wx.SUNKEN_BORDER) self.Bind(wx.EVT_CHECKLISTBOX, self.onDictionaryChecked, self.installedList) self.Bind(wx.EVT_LISTBOX, self.onInstalledSelected, self.installedList) vboxInstalled.Add(self.installedList, 1, wx.ALL | wx.EXPAND, 1) hboxButtons = wx.BoxSizer(wx.HORIZONTAL) # # "Install from file" button # idInstallFile = wx.NewId() self.buttonInstallFile = wx.Button(panelInstalled, idInstallFile, _("Install From File")) hboxButtons.Add(self.buttonInstallFile, 0, wx.ALL | wx.ALIGN_RIGHT, 2) # # "Remove" button # idRemove = wx.NewId() self.buttonRemove = wx.Button(panelInstalled, idRemove, _("Remove")) self.buttonRemove.Disable() hboxButtons.Add(self.buttonRemove, 0, wx.ALL | wx.ALIGN_RIGHT, 2) vboxInstalled.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 2) panelInstalled.SetSizer(vboxInstalled) vboxInstalled.Fit(panelInstalled) # # Make columns # dictNames = self.installedDictionaries.keys() dictNames.sort() self.setInstalledDicts(dictNames) self.Bind(wx.EVT_BUTTON, self.onRemove, self.buttonRemove) self.Bind(wx.EVT_BUTTON, self.onInstallFile, self.buttonInstallFile) return panelInstalled def _makeAvailablePanel(self, tabbedPanel): """Creates panel with for controlling installed dictionaries""" # # Boxes # panelAvailable = wx.Panel(tabbedPanel, -1) vboxAvailable = wx.BoxSizer(wx.VERTICAL) # # List of available dictionaries # idAvailList = wx.NewId() self.availableList = DictListCtrl( panelAvailable, idAvailList, style=wx.LC_REPORT | wx.LC_SINGLE_SEL #| wx.LC_NO_HEADER | wx.SUNKEN_BORDER) vboxAvailable.Add(self.availableList, 1, wx.ALL | wx.EXPAND, 1) # Horizontal box for buttons hboxButtons = wx.BoxSizer(wx.HORIZONTAL) # # "Update" button # idUpdate = wx.NewId() self.buttonUpdate = wx.Button(panelAvailable, idUpdate, _("Update List")) hboxButtons.Add(self.buttonUpdate, 0, wx.ALL | wx.ALIGN_RIGHT, 2) # # "Install" button # idInstall = wx.NewId() self.buttonInstall = wx.Button(panelAvailable, idInstall, _("Install")) self.buttonInstall.Disable() hboxButtons.Add(self.buttonInstall, 0, wx.ALL | wx.ALIGN_RIGHT, 2) vboxAvailable.Add(hboxButtons, 0, wx.ALL | wx.ALIGN_RIGHT, 1) panelAvailable.SetSizer(vboxAvailable) vboxAvailable.Fit(panelAvailable) # # Make columns # self.availableList.InsertColumn(0, _("Name")) self.availableList.InsertColumn(1, _("Size")) addons = self.app.cache.get('addons') if not addons: addons = {} dictNames = addons.keys() dictNames.sort() for dictionary in dictNames: index = self.availableList.InsertStringItem(0, dictionary) sizeString = "%d KB" % addons.get(dictionary).getSize() self.availableList.SetStringItem(index, 1, sizeString) self.availableList.SetItemData(index, index + 1) # Keep wide if list is empty yet if addons: self.availableList.SetColumnWidth(0, wx.LIST_AUTOSIZE) self.availableList.SetColumnWidth(1, wx.LIST_AUTOSIZE) else: self.availableList.SetColumnWidth(0, 200) self.availableList.SetColumnWidth(1, 120) self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onAvailableSelected, self.availableList) self.Bind(wx.EVT_BUTTON, self.onInstall, self.buttonInstall) self.Bind(wx.EVT_BUTTON, self.onUpdate, self.buttonUpdate) return panelAvailable def _makeInfoPanel(self): """Create information panel""" # # Boxes # panelInfo = wx.Panel(self, -1) vboxInfo = wx.BoxSizer(wx.VERTICAL) vboxInfoBox = wx.BoxSizer(wx.VERTICAL) sbSizerInfo = wx.StaticBoxSizer(\ wx.StaticBox(panelInfo, -1, _("Information About Dictionary")), wx.VERTICAL) grid = wx.FlexGridSizer(3, 2, 1, 1) self.labelName = wx.StaticText(panelInfo, -1, "") self.labelVersion = wx.StaticText(panelInfo, -1, "") self.labelFormat = wx.StaticText(panelInfo, -1, "") self.labelAuthor = wx.StaticText(panelInfo, -1, "") self.labelSize = wx.StaticText(panelInfo, -1, "") self.textAbout = wx.TextCtrl(panelInfo, -1, size=(-1, 100), style=wx.TE_MULTILINE | wx.TE_READONLY) self.stName = wx.StaticText(panelInfo, -1, _("Name: ")) self.stName.Disable() grid.Add(self.stName, 0, wx.ALL | wx.ALIGN_RIGHT) grid.Add(self.labelName, 0, wx.ALL) self.stVersion = wx.StaticText(panelInfo, -1, _("Version: ")) self.stVersion.Disable() grid.Add(self.stVersion, 0, wx.ALL | wx.ALIGN_RIGHT) grid.Add(self.labelVersion, 0, wx.ALL) self.stAuthor = wx.StaticText(panelInfo, -1, _("Maintainer: ")) self.stAuthor.Disable() grid.Add(self.stAuthor, 0, wx.ALL | wx.ALIGN_RIGHT) grid.Add(self.labelAuthor, 0, wx.ALL) vboxInfoBox.Add(grid, 1, wx.ALL | wx.EXPAND, 1) vboxInfoBox.Add(self.textAbout, 0, wx.ALL | wx.EXPAND, 1) sbSizerInfo.Add(vboxInfoBox, 1, wx.ALL | wx.EXPAND, 5) vboxInfo.Add(sbSizerInfo, 1, wx.ALL | wx.EXPAND, 5) panelInfo.SetSizer(vboxInfo) vboxInfo.Fit(panelInfo) return panelInfo def onDictionaryChecked(self, event, *args): index = event.GetSelection() label = self.installedList.GetString(index) if self.installedList.IsChecked(index): self._addDictToMenu(label) d = self.app.dictionaries.get(label) d.setActive() else: self._removeDictFromMenu(label) d = self.app.dictionaries.get(label) d.setActive(active=False) self.installedList.SetSelection(index) def _removeDictFromMenu(self, name): self.app.config.activedict.remove(name) self.app.config.activedict.save() self.app.window.removeDictionary(name) def _addDictToMenu(self, name): dict = None for k, v in self.app.dictionaries.items(): if k == name: dict = v if dict: self.app.config.activedict.add(name) self.app.config.activedict.save() self.app.window.addDictionary(dict) def onPageChanged(self, event): _pageInstalled = 0 _pageAvail = 1 sel = event.GetSelection() if sel == _pageInstalled: if self.currentInstalledItemSelection == -1: self.clearInfo() self.disableInfo() else: self.enableInfo() self.showInstalledInfo() elif sel == _pageAvail: if self.currentAvailItemSelection == -1: self.clearInfo() self.disableInfo() else: self.enableInfo() self.showAvailableInfo() def onInstalledSelected(self, event): """Called when list item is selected""" self.currentInstalledItemSelection = event.GetSelection() self.buttonRemove.Enable(1) self.showInstalledInfo() def showInstalledInfo(self): """Show information about selected dictionary""" dictName = self.installedList.GetString(\ self.currentInstalledItemSelection) dictInstance = self.app.dictionaries.get(dictName) self.showInfo(dictInstance) def showAvailableInfo(self): """Show information about selected dictionary""" dictName = self.availableList.GetItemText(\ self.currentAvailItemSelection) dictInstance = self.addons.get(dictName) if not dictInstance: systemLog(ERROR, "BUG: add-on '%s' not found by name" % dictName) return self.showInfo(dictInstance) def showInfo(self, dictInstance): """Show information about dictionary""" self.stName.Enable(1) self.stVersion.Enable(1) self.stAuthor.Enable(1) if dictInstance.getName(): dictName = enc.toWX(dictInstance.getName()) else: dictName = '--' self.labelName.SetLabel(dictName) if dictInstance.getVersion(): dictVersion = enc.toWX(dictInstance.getVersion()) else: dictVersion = '--' self.labelVersion.SetLabel(dictVersion) if dictInstance.getAuthors(): authors = [] for author in dictInstance.getAuthors(): if author: authors.append("%s <%s>" % (author.get('name'), author.get('email'))) dictAuthors = enc.toWX(', '.join(authors)) else: dictAuthors = '--' self.labelAuthor.SetLabel(dictAuthors) if dictInstance.getDescription(): description = enc.toWX(dictInstance.getDescription().strip()) else: description = '' self.textAbout.Clear() self.textAbout.WriteText(description) def onAvailableSelected(self, event): self.currentAvailItemSelection = event.m_itemIndex self.buttonInstall.Enable(1) self.showAvailableInfo() def clearInfo(self): """Clear info fields""" self.labelName.SetLabel('') self.labelVersion.SetLabel('') self.labelAuthor.SetLabel('') self.textAbout.Clear() def disableInfo(self): """Make info widgets inactive""" self.stName.Disable() self.stVersion.Disable() self.stAuthor.Disable() self.textAbout.Disable() def enableInfo(self): """Make info widgets active""" self.stName.Enable(1) self.stVersion.Enable(1) self.stAuthor.Enable(1) self.textAbout.Enable(1) def setInstalledDicts(self, dictNames): """Clear the list of installed dictionaries and set new items""" for i in range(self.installedList.GetCount()): self.installedList.Delete(i) dictNames.sort() i = 0 for dictionary in dictNames: index = self.installedList.Insert(dictionary, i) if self.app.dictionaries[dictionary].getActive(): self.installedList.Check(i) i += 1 def setAvailDicts(self, addons): """Clear the list of available dictionaries and set new items""" self.availableList.DeleteAllItems() names = addons.keys() names.sort() names.reverse() for name in names: addon = addons.get(name) index = self.availableList.InsertStringItem(0, addon.getName()) self.availableList.SetStringItem(index, 1, str(addon.getSize()) + " KB") self.availableList.SetItemData(index, index + 1) if names: self.availableList.SetColumnWidth(0, wx.LIST_AUTOSIZE) else: title = _("List updated") msg = _("All your dictionaries are up to date.") errorwin.showInfoMessage(title, msg) def onUpdate(self, event): """Update dictionaries list""" title = _("Downloading List") downloader = util.DownloadThread( self.app.config.get('repository-list')) progressDialog = wx.ProgressDialog(title, '', maximum=100, parent=self, style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL) keepGoing = True error = None try: systemLog(INFO, "Opening %s..." % \ self.app.config.get('repository-list')) downloader.start() xmlData = '' while keepGoing and not downloader.finished(): keepGoing = progressDialog.Update(downloader.getPercentage(), downloader.getMessage()) if not keepGoing: downloader.stop() break xmlData += downloader.getBytes() time.sleep(0.1) progressDialog.Destroy() xmlData += downloader.getBytes() systemLog(INFO, "Finished downloading list") except Exception, e: traceback.print_exc() progressDialog.Destroy() error = _("Unable to download list from %s: %s") \ % (self.app.config.get('repository-list'), e) if not error: error = downloader.getErrorMessage() if error: systemLog(ERROR, error) title = _("Unable to download list") errorwin.showErrorMessage(title, error) return if len(xmlData) == 0: return if hasattr(self, "addons"): del self.addons allAddons = xmltools.parseAddOns(xmlData) self.addons = {} for name, obj in allAddons.items(): if name in self.app.dictionaries.keys() \ and obj.getVersion() <= (\ self.app.dictionaries.get(name).getVersion() or ""): continue self.addons[name] = obj app = wx.GetApp() if app.cache.has_key("addons"): del app.cache["addons"] app.cache["addons"] = self.addons self.setAvailDicts(self.addons)
error = "Unable to fetch \"%s\" from %s: %s" \ % (dictInfo.getName(), dictInfo.getLocation(), e) systemLog(ERROR, error) fd.close() if stopped: return if not error: error = downloader.getErrorMessage() if error: systemLog(ERROR, error) title = _("Unable to download") errorwin.showErrorMessage(title, error) return md5sum = util.getMD5Sum(localPath) # # Check checksum # if md5sum != dictInfo.getChecksum(): title = _("File is damaged") msg = _("Downloaded file is damaged and cannot be installed. " \ "Please try again.") errorwin.showErrorMessage(title, msg) return #
class OpenDictApp(wx.App): """Top-level class of wxWidgets application""" locale = wx.Locale() def OnInit(self): _ = wx.GetTranslation _start = time.time() wx.Version = [] try: wx.Version = wx.__version__ except Exception, e: try: wx.Version = wx.Python.__version__ except: pass if wx.Version.split('.') < ['2', '8']: from lib.gui import errorwin title = _("wxPython Version Error") msg = _("wxPython %s is installed on this system.\n\n" "OpenDict %s requires wxPython 2.8 or newer to run smoothly.\n\n" "You can find wxPython at " "http://www.wxpython.org or you can " "install it using your system package manager.") \ % (wx.Version, info.VERSION) errorwin.showErrorMessage(title, msg) return False util.makeDirectories() systemLog(DEBUG, "Unicode version: %s" % wx.USE_UNICODE) # Init gettext support wx.Locale_AddCatalogLookupPathPrefix( os.path.join(info.GLOBAL_HOME, 'po')) self.locale.Init(wx.LANGUAGE_DEFAULT) self.locale.AddCatalog('opendict') # Data cache instance self.cache = {} # Dictionaries container # Mapping: name -> object self.dictionaries = {} # Failed dictionaries. # For error message that may be shown after creating main window self.invalidDictionaries = [] self.config = Configuration() self.config.load() self.agreements = util.AgreementsManager( os.path.join(info.LOCAL_HOME, 'agreements.txt')) # Set unique ids for plugin in newplugin.loadDictionaryPlugins( self.dictionaries, self.invalidDictionaries): self.config.ids[wx.NewId()] = plugin.getName() for plain in plaindict.loadPlainDictionaries(self.dictionaries): self.config.ids[wx.NewId()] = plain.getName() for d in self.dictionaries.values(): if not self.config.activedict.init: if not self.config.activedict.enabled(d.getName()): d.setActive(active=False) else: # Fill up with names if not initialized yet self.config.activedict.add(d.getName()) windowPos = (int(self.config.get('windowPosX')), int(self.config.get('windowPosY'))) windowSize = (int(self.config.get('windowWidth')), int(self.config.get('windowHeight'))) self.window = MainWindow(None, -1, "OpenDict", windowPos, windowSize, style=wx.DEFAULT_FRAME_STYLE) try: systemLog(INFO, "OpenDict %s" % info.VERSION) systemLog(INFO, "wxPython %s" % wx.Version) systemLog(INFO, "Global home: %s:" % info.GLOBAL_HOME) systemLog(INFO, "Local home: %s" % info.LOCAL_HOME) systemLog(DEBUG, "Loaded in %f seconds" % (time.time() - _start)) except Exception, e: print "Logger Error: Unable to write to log (%s)" % e
except Exception, e: errorwin.showErrorMessage(_("Installation failed"), e.args[0] or '') self.mainWin.SetStatusText(_("Installation failed")) return else: try: directory = installPlainDictionary(filePath) if directory: dictionary = plaindict._loadPlainDictionary(directory) self.mainWin.addDictionary(dictionary) succeeded = True except Exception, e: traceback.print_exc() errorwin.showErrorMessage(_("Installation Error"), e.args[0] or '') self.mainWin.SetStatusText(_("Error: Installation failed")) return except: # Can this happen? self.mainWin.SetStatusText(_("Error: Installation failed")) traceback.print_exc() if succeeded: title = _("Dictionary installed") msg = _("Dictionary successfully installed. You can choose it " \ "from \"Dictionaries\" menu now.") errorwin.showInfoMessage(title, msg) def installPlainDictionary(filePath):
def _installNormalPlugin(filePath): """Install 'normal' OpenDict plugin""" zipFile = zipfile.ZipFile(filePath, 'r') topDirectory = zipFile.namelist()[0] pluginsPath = os.path.join(info.LOCAL_HOME, info.PLUGIN_DICT_DIR) # Check if already installed if os.path.exists( os.path.join(info.LOCAL_HOME, info.PLUGIN_DICT_DIR, topDirectory)): raise Exception(_("This dictionary already installed. " \ "If you want to upgrade it, please remove " \ "old version first.")) installFile = os.path.join(topDirectory, 'install.py') if installFile in zipFile.namelist(): data = zipFile.read(installFile) try: struct = {} exec(data, struct) except Exception as e: title = _("Installation Error") msg = _("Installation tool for this dictionary failed to start. " \ "Please report this problem to developers.") errorwin.showErrorMessage(title, msg) return install = struct.get('install') if not install: title = _("Installation Error") msg = _("Installation tool for this dictionary failed to start. " \ "Please report this problem to developers.") errorwin.showErrorMessage(title, msg) return if not install(info.GLOBAL_HOME, info.LOCAL_HOME): title = _("Installation Aborted") msg = _("Dictionary installation has been aborted.") errorwin.showErrorMessage(title, msg) return # Install try: for fileInZip in zipFile.namelist(): dirName = os.path.dirname(fileInZip) fileName = os.path.basename(fileInZip) if len(fileName) == 0: dirToCreate = os.path.join(pluginsPath, dirName) if not os.path.exists(dirToCreate): os.mkdir(dirToCreate) else: fileToWrite = os.path.join(pluginsPath, dirName, fileName) fd = open(fileToWrite, 'wb') fd.write(zipFile.read(fileInZip)) fd.close() except Exception as e: try: shutil.rmtree(os.path.join(pluginsPath, topLevelDir)) except Exception as e: raise _("Error while removing created directories after " \ "plugin installation failure. This may be " \ "permission or disk space error.") raise _("Unable to install plugin") return os.path.join(info.LOCAL_HOME, info.PLUGIN_DICT_DIR, topDirectory)
except Exception, e: errorwin.showErrorMessage(_("Installation failed"), e.args[0] or '') self.mainWin.SetStatusText(_("Installation failed")) return else: try: directory = installPlainDictionary(filePath) if directory: dictionary = plaindict._loadPlainDictionary(directory) self.mainWin.addDictionary(dictionary) succeeded = True except Exception, e: traceback.print_exc() errorwin.showErrorMessage(_("Installation Error"), e.args[0] or '') self.mainWin.SetStatusText(_("Error: Installation failed")) return except: # Can this happen? self.mainWin.SetStatusText(_("Error: Installation failed")) traceback.print_exc() if succeeded: title = _("Dictionary installed") msg = _("Dictionary successfully installed. You can choose it " \ "from \"Dictionaries\" menu now.") errorwin.showInfoMessage(title, msg)
def onSearch(self, event): if self.activeDictionary == None: if len(self.app.dictionaries): title = _("No dictionary activated") msg = _("No dictionary activated. Please select one from "\ "\"Dictionaries\" menu and try again.") else: title = _("No dictionaries installed") msg = _("There is no dictionaries installed. You can " \ "install one by selecting Tools > Manage " \ "Dictionaries > Available") errorwin.showErrorMessage(title, msg) return if self.search and not self.search.isDone(): self.onStop(None) word = self.entry.GetValue().strip() if word == "": self.SetStatusText(_("Please enter some text and try again")) self.entry.SetFocus() return global lastLookupWord lastLookupWord = word wx.BeginBusyCursor() self.__searchedBySelecting = 0 self.SetStatusText(_("Searching...")) self.timerSearch.Stop() self.search = None self.buttonStop.Enable(1) self.entry.Disable() self.timerSearch.Start(self.delay) word = enc.fromWX(word) try: word = word.encode(self.activeDictionary.getEncoding()) except Exception as e: # FIXME: Code duplicates self.buttonStop.Disable() self.entry.Enable(True) self.timerSearch.Stop() self.SetStatusText(_('Stopped')) wx.EndBusyCursor() systemLog(ERROR, "Unable to decode '%s': %s" % (word.encode('UTF-8'), e)) title = _("Encode Failed") msg = _("Unable to encode text \"%s\" in %s for \"%s\". " "That logically means the word " "definition does not exist in the dictionary.") \ % (enc.toWX(word), self.activeDictionary.getEncoding(), self.activeDictionary.getName()) errorwin.showErrorMessage(title, msg) return self.search = Process(self.activeDictionary.search, word)
def onTimerSearch(self, event): """Search timer. When finished, sets search results""" if self.search != None and self.search.isDone(): self.timerSearch.Stop() self.search.stop() # # Turn back active interface elements state wx.EndBusyCursor() self.SetStatusText("") self.entry.Enable(1) self.buttonStop.Disable() global lastLookupWord word = lastLookupWord if self.entry.FindString(word) == -1: self.entry.Append(word) result = self.search() # Check if search result is SerachResult object. # SearchResult class is used by new-type plugins. try: assert result.__class__ == meta.SearchResult except: self.SetStatusText(errortype.INTERNAL_ERROR.getMessage()) if self.activeDictionary.getType() == dicttype.PLUGIN: title = errortype.INTERNAL_ERROR.getMessage() message = errortype.INTERNAL_ERROR.getLongMessage() else: title = errortype.OPENDICT_BUG.getMessage() message = errortype.OPENDICT_BUG.getLongMessage() systemLog(ERROR, "%s: %s" % (message, misc.getTraceback())) errorwin.showErrorMessage(title, message) return # Check status code if result.getError() != errortype.OK: systemLog(ERROR, result.getError()) self.htmlWin.SetPage("") self.wordList.Clear() if result.getError() in \ [errortype.INTERNAL_ERROR, errortype.INVALID_ENCODING]: errorwin.showErrorMessage( result.getError().getMessage(), result.getError().getLongMessage()) else: self.SetStatusText(result.getError().getMessage()) return # # If dictionary (plugin) does not use NOT_FOUND notification, # check for translation and show it manually # if not result.getTranslation(): self.SetStatusText(errortype.NOT_FOUND.getMessage()) try: transUnicode = str(result.translation, self.activeDictionary.getEncoding()) except Exception as e: systemLog(ERROR, "Unable to decode translation in %s (%s)" \ % (self.activeDictionary.getEncoding(), e)) title = errortype.INVALID_ENCODING.getMessage() msg = _("Translation cannot be displayed using selected " \ "encoding %s. Please try another encoding from " \ "View > Character Encoding menu.") \ % self.activeDictionary.getEncoding() self.SetStatusText(title) errorwin.showErrorMessage(title, msg) return transPreparedForWX = enc.toWX(transUnicode) self.htmlWin.SetPage(transPreparedForWX) self.history.add(transPreparedForWX) # FIXME: Nasty names # Where it is used? htmlWin.GetPage self.htmlCode = transPreparedForWX if not self.wordListHidden(): if not self.__searchedBySelecting: self.wordList.Clear() toUnicode = lambda s: str( s, self.activeDictionary.getEncoding()) wordsInUnicode = list(map(toUnicode, result.words)) wordsPreparedForWX = list(map(enc.toWX, wordsInUnicode)) self.wordList.InsertItems(wordsPreparedForWX, 0) self.words = wordsPreparedForWX if not self.__searchedBySelecting: matches = self.wordList.GetCount() if matches == 1: self.SetStatusText(_("1 word matches")) elif matches > 1: self.SetStatusText(_("%d words match") % matches) else: self.SetStatusText(_("Done")) if self.history.canBack(): self.buttonBack.Enable(1) self.search = None
def loadDictionary(self, dictInstance): """Prepares main window for using dictionary""" if not dictInstance: systemLog(ERROR, "loadDictionary: dictInstance is False") return # # Check licence agreement # licence = dictInstance.getLicence() if licence \ and not self.app.agreements.getAccepted(dictInstance.getPath()): if not miscwin.showLicenceAgreement(None, licence): from lib.gui import errorwin title = _("Licence Agreement Rejected") msg = _("You cannot use dictionary \"%s\" without accepting "\ "licence agreement") % dictInstance.getName() errorwin.showErrorMessage(title, msg) return else: self.app.agreements.addAgreement(dictInstance.getPath()) self.onCloseDict(None) self.activeDictionary = dictInstance if dictInstance.getType() in dicttype.indexableTypes: if plaindict.indexShouldBeMade(dictInstance): # Notify about indexing from lib.gui import errorwin title = _("Dictionary Index") msg = _("This is the first time you use this dictionary or it " \ "has been changed on disk since last indexing. " \ "Indexing is used to make search more efficient. " \ "The dictionary will be indexed now. It can take a few " \ "or more seconds.\n\n" \ "Press OK to continue...") errorwin.showInfoMessage(title, msg) # Make index try: wx.BeginBusyCursor() plaindict.makeIndex(dictInstance, self.app.config.get('encoding')) wx.EndBusyCursor() except Exception as e: wx.EndBusyCursor() traceback.print_exc() title = _("Index Creation Error") msg = _("Error occured while indexing file. " \ "This may be because of currently selected " \ "character encoding %s is not correct for this " \ "dictionary. Try selecting " \ "another encoding from View > Character Encoding " \ "menu") % self.app.config.get('encoding') from lib.gui import errorwin errorwin.showErrorMessage(title, msg) return # Load index try: wx.BeginBusyCursor() index = plaindict.loadIndex(dictInstance) self.activeDictionary.setIndex(index) wx.EndBusyCursor() except Exception as e: wx.EndBusyCursor() traceback.print_exc() title = _("Error") msg = _("Unable to load dictionary index table. " "Got error: %s") % e from lib.gui import errorwin errorwin.showErrorMessage(title, msg) return wx.BeginBusyCursor() self.activeDictionary.start() self.checkIfNeedsList() self.SetTitle(titleTemplate % dictInstance.getName()) self.SetStatusText(enc.toWX(_("Dictionary \"%s\" loaded") \ % dictInstance.getName())) self.entry.SetFocus() try: self.checkEncMenuItem(self.activeDictionary.getEncoding()) except Exception as e: systemLog(ERROR, "Unable to select encoding menu item: %s" % e) wx.EndBusyCursor()