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 __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE): """Initialize preferences dialog window""" wx.Dialog.__init__(self, parent, id, title, pos, size, style) self.app = wx.GetApp() vboxMain = wx.BoxSizer(wx.VERTICAL) hboxButtons = wx.BoxSizer(wx.HORIZONTAL) grid = wx.FlexGridSizer(2, 2, 1, 1) grid.Add(wx.StaticText(self, -1, _("Default dictionary: ")), 0, wx.ALIGN_CENTER_VERTICAL) dictNames = [] for name, d in self.app.dictionaries.items(): if d.getActive(): dictNames.append(name) dictNames.sort() dictNames.insert(0, "") try: map(enc.toWX, dictNames) except Exception, e: systemLog(ERROR, "Unable to decode titles to UTF-8 (%s)" % e)
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 savePlainConfiguration(dictionary): """Write configuration to disk""" from lib import dicttype if not dictionary.getType() in dicttype.plainTypes: systemLog(ERROR, "Request to write configuration to %s of type %s" \ % (dictionary.getName(), dictionary.getType())) return md5sum = util.getMD5Sum(dictionary.getPath()) dictDir = dictionary.getConfigDir() doc = xmltools.generatePlainDictConfig(name=dictionary.getName(), format=dictionary.getType().getIdName(), version=dictionary.getVersion(), authors=dictionary.getAuthors(), path=dictionary.getPath(), md5=md5sum, encoding=dictionary.getEncoding(), description=dictionary.getDescription(), licence=dictionary.getLicenceFile()) xmltools.writePlainDictConfig(doc, os.path.join(dictDir, 'conf', 'config.xml'))
def getLicence(self): """Return licence text""" filePath = self.licenceFile if filePath: if not os.path.exists(filePath): filePath = os.path.join(self.getConfigDir(), info._PLAIN_DICT_DATA_DIR, self.licenceFile) if not os.path.exists(filePath): filePath = None errMsg = "Error: <i>licence file not found</i>" if not filePath: systemLog(ERROR, "Cannot find defined licence file '%s' for '%s'" \ % (self.licenceFile, self.getName())) return errMsg try: fd = open(filePath) data = fd.read() fd.close() return data except Exception, e: systemLog(ERROR, "Unable to read licence file for %s: %" \ % (self.getName(), e)) return errMsg
def makeIndex(dictionary, currentlySetEncoding): """Index dictionary""" filePath = dictionary.getPath() fd = open(filePath) index = {} count = 0L linenum = -1 for line in fd: linenum += 1 try: literal = unicode(line.strip(), dictionary.getEncoding())[:2].lower() except: try: literal = unicode(line.strip(), currentlySetEncoding)[:2].lower() dictionary.setEncoding(currentlySetEncoding) except: raise Exception, "Unable to encode data in %s nor %s " \ "at line %d" \ % (dictionary.getEncoding(), currentlySetEncoding, linenum) # Ignore if control character found if literal and not literal in index.keys() and literal[0] > u'\x19': try: index[literal] = count except Exception, e: systemLog(ERROR, e) count += len(line)
def savePlainConfiguration(dictionary): """Write configuration to disk""" from lib import dicttype if not dictionary.getType() in dicttype.plainTypes: systemLog(ERROR, "Request to write configuration to %s of type %s" \ % (dictionary.getName(), dictionary.getType())) return md5sum = util.getMD5Sum(dictionary.getPath()) dictDir = dictionary.getConfigDir() doc = xmltools.generatePlainDictConfig( name=dictionary.getName(), format=dictionary.getType().getIdName(), version=dictionary.getVersion(), authors=dictionary.getAuthors(), path=dictionary.getPath(), md5=md5sum, encoding=dictionary.getEncoding(), description=dictionary.getDescription(), licence=dictionary.getLicenceFile()) xmltools.writePlainDictConfig(doc, os.path.join(dictDir, 'conf', 'config.xml'))
def getLicence(self): """Return licence text""" filePath = self.licence if filePath: if not os.path.exists(filePath): filePath = os.path.join(self.directory, info._PLAIN_DICT_DATA_DIR, self.licence) if not os.path.exists(filePath): filePath = None errMsg = "Error: <i>licence file not found</i>" if not filePath: systemLog(ERROR, "Cannot find defined licence file for %s: %" \ % (self.getName(), e)) return errMsg try: fd = open(filePath) data = fd.read() fd.close() return data except Exception, e: systemLog(ERROR, "Unable to read licence file for %s: %" \ % (self.getName(), e)) return errMsg
def __init__(self, parent, id, title, msg, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE): wx.Dialog.__init__(self, parent, id, title, pos, size, style) vbox = wx.BoxSizer(wx.VERTICAL) vboxButtons = wx.BoxSizer(wx.HORIZONTAL) htmlWin = wx.html.HtmlWindow(self, -1, style=wx.SUNKEN_BORDER) htmlWin.SetFonts('Helvetica', 'Fixed', [10] * 5) error = False try: encodedText = enc.toWX(unicode(msg, 'UTF-8')) htmlWin.SetPage(encodedText) except Exception, e: systemLog(ERROR, "Unable to encode/show licence text: %s" % e) htmlWin.SetPage(_("Error: <i>unable to show licence text</i>")) error = True
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 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 __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE): """Initialize preferences dialog window""" wx.Dialog.__init__(self, parent, id, title, pos, size, style) self.app = wx.GetApp() vboxMain = wx.BoxSizer(wx.VERTICAL) hboxButtons = wx.BoxSizer(wx.HORIZONTAL) grid = wx.FlexGridSizer(4, 2, 1, 1) grid.Add(wx.StaticText(self, -1, _("Default dictionary: ")), 0, wx.ALIGN_CENTER_VERTICAL) dictNames = [] for name, d in self.app.dictionaries.items(): if d.getActive(): dictNames.append(name) dictNames.sort() dictNames.insert(0, "") try: map(enc.toWX, dictNames) except Exception, e: systemLog(ERROR, "Unable to decode titles to UTF-8 (%s)" % e)
def load(self): """Load configuration from file to memory""" try: if os.path.exists(self.filePath): self.props.update(xmltools.parseMainConfig(self.filePath)) except Exception, e: systemLog(ERROR, "Unable to read configuration file: %s" % e)
def onPreview(self, event): """This method is invoked when preview menu item is selected""" try: self.printer.PreviewText(self.htmlCode) except Exception as e: systemLog(ERROR, "Unable to preview translation (%s)" % e) self.SetStatusText(_("Page preview failed")) traceback.print_exc()
def onPrint(self, event): """This method is invoked when print menu item is selected""" try: self.printer.PrintText(self.htmlCode) except Exception as e: self.SetStatusText(_("Failed to print")) systemLog(ERROR, "Unable to print translation (%s)" % e) traceback.print_exc()
def changeEncoding(self, name): self.app.config.set('encoding', misc.encodings[name]) if self.activeDictionary: print("Setting encoding %s for dictionary %s" % \ (self.app.config.get('encoding'), self.activeDictionary.name)) self.activeDictionary.setEncoding(self.app.config.get('encoding')) systemLog(INFO, "Dictionary encoding set to %s" \ % self.activeDictionary.getEncoding()) plaindict.savePlainConfiguration(self.activeDictionary)
def _loadDictionaryPlugin(directory): """Load dictionary plugin""" plugin = None try: plugin = DictionaryPlugin(directory) util.correctDictName(plugin) except InvalidPluginException, e: systemLog(ERROR, "Unable to load plugin from %s (%s)" % (directory, e))
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, e: traceback.print_exc() progressDialog.Destroy() error = "Unable to fetch \"%s\" from %s: %s" \ % (dictInfo.getName(), dictInfo.getLocation(), e) systemLog(ERROR, error)
def load(self): """Load configuration from file to memory""" try: if os.path.exists(self.filePath): self.props.update(xmltools.parseMainConfig(self.filePath)) except Exception as e: systemLog(ERROR, "Unable to read configuration file: %s" % e) # Old configurations may still keep outdated entry, rewrite it self.set('repository-list', self.repository)
def getLicence(self): """Return licence text (HTML format required)""" if self.info.licenceFile: try: fd = open(os.path.join(self.getPath(), self.info.licenceFile)) data = fd.read() fd.close() except Exception, e: systemLog(ERROR, "Unable to read licence file: %s" % e) data = 'Error: <i>Licence file not found</i>'
def loadPlugin(self, name): """Sets plugin as currently used dictionary""" systemLog(INFO, "Loading plugin '%s'..." % name) self.entry.Disable() self.dictName = name self.activeDictionary = self.app.dictionaries.get(name) self.checkIfNeedsList() self.SetTitle(titleTemplate % name) self.entry.Enable(1) self.SetStatusText("Done") # TODO: Set something more useful self.htmlWin.SetPage("")
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 onInstall(self, event): """Install button pressed""" name = self.availableList.GetItemText(\ self.currentAvailItemSelection) dictInfo = self.addons.get(name) if not dictInfo: systemLog(ERROR, "Interal Error, add-on %s not found in list" \ % name) return self._fetchAddon(dictInfo)
def unhideWordList(self): """Shows word list""" systemLog(DEBUG, "Showing word list...") self.createListPanel() self.splitter.SplitVertically(self.panelList, self.panelHtml) self.splitter.SetSashPosition(int(self.app.config.get('sashPos'))) self.wlHidden = False # And change the pixmap bmp = wx.Bitmap(os.path.join(info.GLOBAL_HOME, "pixmaps", "hide.png"), wx.BITMAP_TYPE_PNG) self.buttonHide.SetBitmapLabel(bmp) self.buttonHide.SetToolTip(_("Hide word list"))
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 checkEncMenuItem(self, name): """Select menu item defined by name""" ename = "" for key in misc.encodings: if name == misc.encodings[key]: ename = key break if len(ename) == 0: systemLog(ERROR, "Something wrong with encodings (name == None)") return self.menuEncodings.FindItemById( self.menuEncodings.FindItem(ename)).Check(1)
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 hideWordList(self): """Hides word list""" systemLog(DEBUG, "Hiding word list...") self.splitter.SetSashPosition(0) self.splitter.Unsplit(self.panelList) self.wlHidden = True # And change the button pixmap bmp = wx.Bitmap( os.path.join(info.GLOBAL_HOME, "pixmaps", "unhide.png"), wx.BITMAP_TYPE_PNG) self.buttonHide.SetBitmapLabel(bmp) self.buttonHide.SetToolTip(_("Show word list")) self.buttonHide.Show(False)
def __init__(self, parent, id, title, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.CENTRE): wx.Frame.__init__(self, parent, id, title, pos, size, style) vbox = wx.BoxSizer(wx.VERTICAL) # # Read licence file # try: fd = open(os.path.join(info.GLOBAL_HOME, 'copying.html')) data = fd.read() fd.close() except Exception, e: systemLog(ERROR, "Unable to read licence file: %s" % e) data = "Error: <i>licence file not found</i>"
def onShowPluginManager(self, event): """This method is invoked when Dictionaries Manager menu item is selected""" try: self.pmWindow = PluginManagerWindow(self, -1, _("Manage Dictionaries"), size=(500, 500), style=wx.DEFAULT_FRAME_STYLE) self.pmWindow.CentreOnScreen() self.pmWindow.Show(True) except Exception as e: traceback.print_exc() systemLog(ERROR, "Unable to show prefs window: %s" % e) self.SetStatusText("Error occured, please contact developers (%s)" \ % e)
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 savePreferences(self): """Saves window preferences when exiting""" if self.app.config.get('saveWindowSize'): self.app.config.set('windowWidth', self.GetSize()[0]) self.app.config.set('windowHeight', self.GetSize()[1]) if self.app.config.get('saveWindowPos'): self.app.config.set('windowPosX', self.GetPosition()[0]) self.app.config.set('windowPosY', self.GetPosition()[1]) if self.app.config.get('saveSashPos'): if not self.wordListHidden(): self.app.config.set('sashPos', self.splitter.GetSashPosition()) try: self.app.config.save() except Exception as e: systemLog(ERROR, "Unable to save configuration: %s" % e)
def __init__(self, parent, id, title, msg, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE): wx.Dialog.__init__(self, parent, id, title, pos, size, style) vbox = wx.BoxSizer(wx.VERTICAL) vboxButtons = wx.BoxSizer(wx.HORIZONTAL) htmlWin = wx.html.HtmlWindow(self, -1, style=wx.SUNKEN_BORDER) htmlWin.SetFonts('Helvetica', 'Fixed', [10]*5) error = False try: encodedText = enc.toWX(unicode(msg, 'UTF-8')) htmlWin.SetPage(encodedText) except Exception, e: systemLog(ERROR, "Unable to encode/show licence text: %s" % e) htmlWin.SetPage(_("Error: <i>unable to show licence text</i>")) error = True
def prepareForUsing(self): """Prepare MainWindow for displaying data""" systemLog(INFO, "DictConnection: Connected, preparing main window...") db = self.choiceDB.GetValue() if self.choiceDB.FindString(db) == 0: db = "*" db_name = "" else: try: dbs = self.conn.getdbdescs() for d in dbs.keys(): if dbs[d] == db: db = d db_name = dbs[db] except: traceback.print_exc() self.app.window.SetStatusText(misc.errors[4]) return self.app.window.onCloseDict(None) self.app.window.activeDictionary = DictConnection(self.server, int(self.port), db, "") self.app.config.set('dict-server-encoding', self.encoding[0]) self.parent.changeEncoding(self.encoding[1]) if db_name != "": title = "OpenDict - %s (%s)" % (self.server, db_name) else: title = "OpenDict - %s" % self.server self.app.window.SetTitle(title) self.app.window.checkEncMenuItem(self.encoding[0]) if not self.app.window.activeDictionary.getUsesWordList(): self.app.window.hideWordList() self.app.window.SetStatusText("") self.timerUpdateDB.Stop() self.Destroy()
def prepareForUsing(self): """Prepare MainWindow for displaying data""" systemLog(INFO, "DictConnection: Connected, preparing main window...") db = self.choiceDB.GetValue() if self.choiceDB.FindString(db) == 0: db = "*" db_name = "" else: try: dbs = self.conn.getdbdescs() for d in list(dbs.keys()): if dbs[d] == db: db = d db_name = dbs[db] except: traceback.print_exc() self.app.window.SetStatusText(misc.errors[4]) return self.app.window.onCloseDict(None) self.app.window.activeDictionary = DictConnection( self.server, int(self.port), db, "") self.app.config.set('dict-server-encoding', self.encoding[0]) self.parent.changeEncoding(self.encoding[1]) if db_name != "": title = "OpenDict - %s (%s)" % (self.server, db_name) else: title = "OpenDict - %s" % self.server self.app.window.SetTitle(title) self.app.window.checkEncMenuItem(self.encoding[0]) if not self.app.window.activeDictionary.getUsesWordList(): self.app.window.hideWordList() self.app.window.SetStatusText("") self.timerUpdateDB.Stop() self.Destroy()
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)
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)
def __init__(self, filePath): systemLog(WARNING, "***") systemLog(WARNING, "*** WARNING:") systemLog(WARNING, "*** TMX implementation is fuzzy and should " \ "not be used yet!") systemLog(WARNING, "***") self.name = os.path.splitext(os.path.basename(filePath))[0] self.needsList = True self.encoding = None self.mapping = {} self.header = {} self.trans = [] self.inSeg = 0 self.lang = ""
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 makeDirectories(): """Make needed directories if not exist""" if not os.path.exists(info.LOCAL_HOME): os.mkdir(info.LOCAL_HOME) logDir = os.path.join(info.LOCAL_HOME, info.LOG_DIR) if not os.path.exists(logDir): os.mkdir(logDir) plainDir = os.path.join(info.LOCAL_HOME, info.PLAIN_DICT_DIR) pluginDir = os.path.join(info.LOCAL_HOME, info.PLUGIN_DICT_DIR) if not os.path.exists(info.LOCAL_HOME): try: systemLog(DEBUG, "%s does not exist, creating..." \ % info.LOCAL_HOME) os.mkdir(info.LOCAL_HOME) except Exception, e: systemLog(ERROR, "Unable to create %s (%s)" % (info.LOCAL_HOME, e))
def search(self, word): """Lookup word""" _start = time.time() word_lowered = word.lower() encodedIndex = {} for literal in self.index: encodedIndex[literal.encode(self.getEncoding())] = \ self.index.get(literal) # # Seek to the beginning of the block # position = 0L if word_lowered[:2] in encodedIndex.keys(): position = encodedIndex[word_lowered[:2]] debugLog(DEBUG, "Index: %s->%d" % (word_lowered[:2], position)) debugLog(DEBUG, "SlowoParser: Seeking to %d" % position) self.fd.seek(position) html = [] html.append("<html><head>") html.append("<meta http-equiv=\"Content-Type\" " \ "content=\"text/html; charset=%s\">" \ % str(self.getEncoding())) html.append("<head><body>") found = False words = [] result = meta.SearchResult() # DEBUG _linesRead = 0 for line in self.fd.xreadlines(): _linesRead += 1 line = line.strip() try: try: orig, end = line.split('=', 1) except ValueError, e: systemLog(ERROR, '%s (line %s)' % (e, line)) orig = orig.strip() chunks = end.split(';') translation = ["<ul>"] for chunk in chunks: comment = [] trans = chunk.split('//') if len(trans) > 1: comment = trans[1:] trans = trans[:1] trans = "".join(trans).strip() comment = "".join(comment).strip() if len(trans) and len(comment) != 0: translation.append("<li>%s (<i>%s</i>)</li>" \ % (trans, comment)) elif len(trans): translation.append("<li>%s</li>" % trans) translation.append("</ul>") translation = "".join(translation) except:
info.PLAIN_DICT_DIR) pluginDir = os.path.join(info.LOCAL_HOME, info.PLUGIN_DICT_DIR) if not os.path.exists(info.LOCAL_HOME): try: systemLog(DEBUG, "%s does not exist, creating..." \ % info.LOCAL_HOME) os.mkdir(info.LOCAL_HOME) except Exception, e: systemLog(ERROR, "Unable to create %s (%s)" % (info.LOCAL_HOME, e)) if not os.path.exists(os.path.join(info.LOCAL_HOME, info.__DICT_DIR)): try: systemLog(DEBUG, "%s does not exist, creating..." \ % os.path.join(info.LOCAL_HOME, info.__DICT_DIR)) os.mkdir(os.path.join(info.LOCAL_HOME, info.__DICT_DIR)) except Exception, e: systemLog(ERROR, "Unable to create %s (%s)" \ % (os.path.join(info.LOCAL_HOME, info.__DICT_DIR), e)) if not os.path.exists(plainDir): try: systemLog(DEBUG, "%s does not exist, creating..." % plainDir) os.mkdir(plainDir) except Exception, e: systemLog(ERROR, "Unable to create %s (%s)" % (plainDir, e)) if not os.path.exists(pluginDir): try:
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