def createTempFile(content, suffix, path=None, relativeTo=None, textMode=False): """ Specialized function. Creates a file in directory path, fills it with content (byte string), closes it and returns its full path. relativeTo -- path relative to which the path should be or None for absolute path textMode -- Convert lineEndings """ if path is None: path = getDefaultTempFilePath() fd, fullPath = tempfile.mkstemp(suffix=pathEnc(suffix), dir=pathEnc(path), text=textMode) try: try: if isinstance(content, unicode): # assert textMode content = content.encode("utf-8") os.write(fd, BOM_UTF8) os.write(fd, content) elif isinstance(content, str): os.write(fd, content) else: # content is a sequence try: iCont = iter(content) firstContent = iCont.next() unic = False if isinstance(firstContent, unicode): firstContent = firstContent.encode("utf-8") os.write(fd, BOM_UTF8) unic = True assert isinstance(firstContent, str) os.write(fd, firstContent) while True: content = iCont.next() if unic: assert isinstance(content, unicode) content = content.encode("utf-8") assert isinstance(content, str) os.write(fd, content) except StopIteration: pass finally: os.close(fd) except Exception, e: traceback.print_exc() # Something went wrong -> try to remove temporary file try: os.unlink(fullPath) except: traceback.print_exc() raise e
def createTempFile(self, content, suffix, path=None, relativeTo=None): """ Specialized function. Creates a file in directory path, fills it with content (byte string), closes it and returns its full path. relativeTo -- path relative to which the path should be or None for preferred relativeTo path or "" for absolute path """ if path is None: path = self.preferredPath if path is None: path = getDefaultTempFilePath() if path is not None and not os.path.exists(pathEnc(path)): try: os.makedirs(path) except OSError: path = None fullPath = createTempFile(content, suffix, path, textMode=isinstance(content, unicode)) self.fileSet.add(fullPath) return self.getRelativePath(relativeTo, fullPath)
def close(self): self.setLayerVisible(False) try: os.remove(pathEnc(self.htpaths[0])) except: pass try: os.remove(pathEnc(self.htpaths[1])) except: pass # TODO: Option to show also these exceptions # traceback.print_exc() self.presenterListener.disconnect() self.__sinkApp.disconnect() self.__sinkDocPage.disconnect()
def clear(self): """ Delete all files of which the path is stored in the set """ for fullPath in self.fileSet: try: os.remove(pathEnc(fullPath)) except: pass # TODO: Option to show also these exceptions # traceback.print_exc() self.fileSet.clear()
def mkstemp(self, suffix=None, prefix=None, path=None, text=False): """ Same as tempfile.mkstemp from standard library, but stores returned path also in the set and does automatic path encoding. """ if path is None: path = self.preferredPath if path is None: path = getDefaultTempFilePath() if path is not None and not os.path.exists(pathEnc(path)): try: os.makedirs(pathEnc(path)) except OSError: path = None fd, fullPath = tempfile.mkstemp(pathEnc(suffix), pathEnc(prefix), pathEnc(path), text) self.fileSet.add(fullPath) return fd, fullPath
def loadI18nDict(appDir, locStr=None): """ Load and install the dictionary for the locale locStr appDir -- Application directory of WikidPad. """ global i18nDict, i18nPoPath, i18nLocale if not locStr: locStr = locale.getdefaultlocale()[0] if locStr is None: locStr = "" locList = _expand_lang(locStr) for locEntry in locList: if locEntry.upper() == "C": # No translation i18nDict = {} __builtins__["_"] = getI18nEntryDummy i18nPoPath = None i18nLocale = "C" return if findLangListIndex(locEntry) == -1: continue path = os.path.join(appDir, "WikidPad_" + locEntry + ".po") if not os.path.exists(pathEnc(path)): continue try: md = buildMessageDict(path) i18nDict = md __builtins__["_"] = getI18nEntry i18nPoPath = path i18nLocale = locEntry return except IOError: traceback.print_exc() continue # No translation i18nDict = {} __builtins__["_"] = getI18nEntryDummy i18nPoPath = None i18nLocale = "C"
def buildMessageDict(filename): messages = {} def add(id, ustr, fuzzy): "Add a non-fuzzy translation to the dictionary." if not fuzzy and ustr: messages[id] = ustr if filename.endswith('.po') or filename.endswith('.pot'): infile = filename else: infile = filename + '.po' try: lines = codecs.open(pathEnc(infile), "r", "utf-8").readlines() except IOError, msg: # print >> sys.stderr, msg raise
def getI18nXrcData(appDir, globalConfigSubDir, baseXrcName): """ Returns the XML data of translated XRC file. This function assumes that loadI18nDict() was previously called with same appDir. """ global i18nPoPath, i18nLocale if i18nPoPath is None: # No translation return loadEntireFile(os.path.join(appDir, baseXrcName + ".xrc"), True) # Retrieve modification time of .po and .xrc file to compare with cache # Cache is only valid if newer than both poModTime = os.stat(pathEnc(i18nPoPath)).st_mtime poModTime2 = os.stat(pathEnc(os.path.join(appDir, baseXrcName + ".xrc"))).st_mtime poModTime = max(poModTime, poModTime2) # First test for cache in appDir try: cachePath = os.path.join(appDir, baseXrcName + "_" + i18nLocale + ".xrc") if os.path.exists(pathEnc(cachePath)) and \ os.stat(pathEnc(cachePath)).st_mtime > poModTime: data = _stripI18nXrcCache(loadEntireFile(cachePath, True)) if data is not None: # Valid cache found return data except: traceback.print_exc() # Really? # then test for cache in globalConfigSubDir try: cachePath = os.path.join(globalConfigSubDir, baseXrcName + "_" + i18nLocale + ".xrc") if os.path.exists(pathEnc(cachePath)) and \ os.stat(pathEnc(cachePath)).st_mtime > poModTime: # Valid cache found data = _stripI18nXrcCache(loadEntireFile(cachePath, True)) if data is not None: # Valid cache found return data except: traceback.print_exc() # Really? # No valid cache -> build content untranslated = loadEntireFile( os.path.join(appDir, baseXrcName + ".xrc"), True) xmlDoc = minidom.parseString(untranslated) elementsContainingText = xmlDoc.getElementsByTagName("label") + \ xmlDoc.getElementsByTagName("title") + \ xmlDoc.getElementsByTagName("item") for le in elementsContainingText: childs = le.childNodes if len(childs) != 1: continue child = childs[0] if child.nodeType != child.TEXT_NODE: continue child.data = _(child.data) translated = xmlDoc.toxml("utf-8") xmlDoc.unlink() # The following conversion is only needed when running a Windows # binary created by py2exe with wxPython 2.6. # Otherwise some mysterious unicode error may ocurr. translated = translated.decode("utf-8") result = [] for c in translated: o = ord(c) if o > 127: result.append("&#%i;" % o) else: result.append(chr(o)) translated = "".join(result) # Add version tag to ensure valid cache toCache = Consts.VERSION_STRING + "\n" + translated # Try to store content as cache in appDir try: cachePath = os.path.join(appDir, baseXrcName + "_" + i18nLocale + ".xrc") writeEntireFile(cachePath, toCache, True) return translated except: pass # Try to store content as cache in globalConfigSubDir try: cachePath = os.path.join(globalConfigSubDir, baseXrcName + "_" + i18nLocale + ".xrc") writeEntireFile(cachePath, toCache, True) return translated except: pass # Cache saving failed return translated
def getI18nXrcData(appDir, globalConfigSubDir, baseXrcName): """ Returns the XML data of translated XRC file. This function assumes that loadI18nDict() was previously called with same appDir. """ global i18nPoPath, i18nLocale if i18nPoPath is None: # No translation return loadEntireFile(os.path.join(appDir, baseXrcName + ".xrc"), True) # Retrieve modification time of .po and .xrc file to compare with cache # Cache is only valid if newer than both poModTime = os.stat(pathEnc(i18nPoPath)).st_mtime poModTime2 = os.stat(pathEnc(os.path.join(appDir, baseXrcName + ".xrc"))).st_mtime poModTime = max(poModTime, poModTime2) # First test for cache in appDir try: cachePath = os.path.join(appDir, baseXrcName + "_" + i18nLocale + ".xrc") if os.path.exists(pathEnc(cachePath)) and \ os.stat(pathEnc(cachePath)).st_mtime > poModTime: data = _stripI18nXrcCache(loadEntireFile(cachePath, True)) if data is not None: # Valid cache found return data except: traceback.print_exc() # Really? # then test for cache in globalConfigSubDir try: cachePath = os.path.join(globalConfigSubDir, baseXrcName + "_" + i18nLocale + ".xrc") if os.path.exists(pathEnc(cachePath)) and \ os.stat(pathEnc(cachePath)).st_mtime > poModTime: # Valid cache found data = _stripI18nXrcCache(loadEntireFile(cachePath, True)) if data is not None: # Valid cache found return data except: traceback.print_exc() # Really? # No valid cache -> build content untranslated = loadEntireFile(os.path.join(appDir, baseXrcName + ".xrc"), True) xmlDoc = minidom.parseString(untranslated) elementsContainingText = xmlDoc.getElementsByTagName("label") + \ xmlDoc.getElementsByTagName("title") + \ xmlDoc.getElementsByTagName("item") for le in elementsContainingText: childs = le.childNodes if len(childs) != 1: continue child = childs[0] if child.nodeType != child.TEXT_NODE: continue child.data = _(child.data) translated = xmlDoc.toxml("utf-8") xmlDoc.unlink() # The following conversion is only needed when running a Windows # binary created by py2exe with wxPython 2.6. # Otherwise some mysterious unicode error may ocurr. translated = translated.decode("utf-8") result = [] for c in translated: o = ord(c) if o > 127: result.append("&#%i;" % o) else: result.append(chr(o)) translated = "".join(result) # Add version tag to ensure valid cache toCache = Consts.VERSION_STRING + "\n" + translated # Try to store content as cache in appDir try: cachePath = os.path.join(appDir, baseXrcName + "_" + i18nLocale + ".xrc") writeEntireFile(cachePath, toCache, True) return translated except: pass # Try to store content as cache in globalConfigSubDir try: cachePath = os.path.join(globalConfigSubDir, baseXrcName + "_" + i18nLocale + ".xrc") writeEntireFile(cachePath, toCache, True) return translated except: pass # Cache saving failed return translated