def EncodeText(text, encoding='<Default Encoding>', returnEncoding=False): etext = None if encoding != '<Default Encoding>': etext = EncodeTextWithCode(text, encoding) if etext is not None: if returnEncoding: return etext, encoding else: return etext defaultencoding = len(config.prefs.defaultencoding) > 0 enco = CheckForEncodingComment(text) if enco is not None: etext = EncodeTextWithCode(text, enco) if etext is not None: if returnEncoding: return etext, enco else: return etext if utf8Detect(text): etext = EncodeTextWithCode(text, 'utf-8') if etext is not None: if returnEncoding: return etext, 'utf-8' else: return etext if defaultencoding: etext = EncodeTextWithCode(text, config.prefs.defaultencoding) if etext is None: utils.ShowMessage('There was an error using the encoding "%s".' % (config.prefs.defaultencoding), 'Encoding Error') else: if returnEncoding: return etext, config.prefs.defaultencoding else: return etext if CheckAscii(text): if returnEncoding: return text, 'ascii' else: return text if etext is None: etext = EncodeTextWithCode(text, wx.GetDefaultPyEncoding()) if etext is None: # Patch by knuger, Jan 2007: added "Please try..." to error message raise Exception, \ 'Encoding Error! Please try another Default Encoding (See Options -> Preferences -> General)' else: if returnEncoding: return text, wx.GetDefaultPyEncoding() else: return text
def EnvironmentInfo(): """ Returns a string of the systems information. **Returns:** * System information string **Note:** * from Editra.dev_tool """ info = "---- Notes ----\n" info += "Please provide additional information about the crash here \n" info += "---- System Information ----\n" info += "Operating System: %s\n" % wx.GetOsDescription() if sys.platform == 'darwin': info += "Mac OSX: %s\n" % platform.mac_ver()[0] info += "Python Version: %s\n" % sys.version info += "wxPython Version: %s\n" % wx.version() info += "wxPython Info: (%s)\n" % ", ".join(wx.PlatformInfo) info += "Python Encoding: Default=%s File=%s\n" % \ (sys.getdefaultencoding(), sys.getfilesystemencoding()) info += "wxPython Encoding: %s\n" % wx.GetDefaultPyEncoding( ) if wx.VERSION_STRING < '4.0' else str(wx.Font.GetDefaultEncoding()) info += "System Architecture: %s %s\n" % (platform.architecture()[0], \ platform.machine()) info += "Byte order: %s\n" % sys.byteorder info += "Frozen: %s\n" % str(getattr(sys, 'frozen', 'False')) info += "---- End System Information ----" return info
def LogError(exception): global error if error: return error = True details = "".join(traceback.format_exception(*exception)) dialog = wx.MessageDialog(None, _("An error has occurred in the application."), _("Error"), wx.ICON_ERROR | wx.YES_NO | wx.CANCEL) ##dialog.SetExtendedMessage(details) ##dialog.SetYesNoCancelLabels(_("Report"), _("Ignore"), _("Abort")) button = dialog.ShowModal() if button == wx.ID_YES: mac = "" if sys.platform == "darwin": mac = "\n Mac version: " + platform.mac_ver()[0] message = text % ( "*" * 40, "*" * 40, details, "*" * 40, wx.GetOsDescription(), mac, platform.architecture()[0], platform.machine(), sys.byteorder, sys.version, sys.getdefaultencoding(), sys.getfilesystemencoding(), wx.VERSION_STRING, ", ".join(wx.PlatformInfo), wx.GetDefaultPyEncoding(), _version, hasattr(sys, "frozen")) if wx.Platform != "__WXMAC__": message = urllib.parse.quote(message) webbrowser.open( "mailto:[email protected]?subject=Write++ Error Report&body=%s" % message.replace("'", "")) elif button == wx.ID_CANCEL: sys.exit(1) dialog.Destroy() error = False
def push(self, command): """Send command to the interpreter to be executed. Because this may be called recursively, we append a new list onto the commandBuffer list and then append commands into that. If the passed in command is part of a multi-line command we keep appending the pieces to the last list in commandBuffer until we have a complete command. If not, we delete that last list.""" # In case the command is unicode try encoding it if type(command) == unicode: try: command = command.encode(wx.GetDefaultPyEncoding()) except UnicodeEncodeError: pass # otherwise leave it alone if not self.more: try: del self.commandBuffer[-1] except IndexError: pass if not self.more: self.commandBuffer.append([]) self.commandBuffer[-1].append(command) source = '\n'.join(self.commandBuffer[-1]) more = self.more = self.runsource(source) dispatcher.send(signal='Interpreter.push', sender=self, command=command, more=more, source=source) return more
def OnExportSurface(self, pubsub_evt): filename, filetype = pubsub_evt.data if (filetype == const.FILETYPE_STL) or\ (filetype == const.FILETYPE_VTP) or\ (filetype == const.FILETYPE_PLY) or\ (filetype == const.FILETYPE_STL_ASCII): # First we identify all surfaces that are selected # (if any) proj = prj.Project() polydata_list = [] for index in proj.surface_dict: surface = proj.surface_dict[index] if surface.is_shown: polydata_list.append(surface.polydata) if len(polydata_list) == 0: utl.debug("oops - no polydata") return elif len(polydata_list) == 1: polydata = polydata_list[0] else: polydata = pu.Merge(polydata_list) # Having a polydata that represents all surfaces # selected, we write it, according to filetype if filetype == const.FILETYPE_STL: writer = vtk.vtkSTLWriter() writer.SetFileTypeToBinary() elif filetype == const.FILETYPE_STL_ASCII: writer = vtk.vtkSTLWriter() writer.SetFileTypeToASCII() elif filetype == const.FILETYPE_VTP: writer = vtk.vtkXMLPolyDataWriter() #elif filetype == const.FILETYPE_IV: # writer = vtk.vtkIVWriter() elif filetype == const.FILETYPE_PLY: writer = vtk.vtkPLYWriter() writer.SetFileTypeToASCII() writer.SetColorModeToOff() #writer.SetDataByteOrderToLittleEndian() #writer.SetColorModeToUniformCellColor() #writer.SetColor(255, 0, 0) if filetype in (const.FILETYPE_STL, const.FILETYPE_PLY): # Invert normals normals = vtk.vtkPolyDataNormals() normals.SetInputData(polydata) normals.SetFeatureAngle(80) normals.AutoOrientNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.UpdateInformation() normals.Update() polydata = normals.GetOutput() filename = filename.encode(wx.GetDefaultPyEncoding()) writer.SetFileName(filename) writer.SetInputData(polydata) writer.Write()
def OnSaveScanBtn(self, evt): defenc = wx.GetDefaultPyEncoding() # Get values of ScanLine, TextLine, and NotesWindow. scansion = self.ScanLine.GetValue() textline = self.TextLine.GetValue() scanNotes = self.NotesWindow.GetValue() # Make a divider for the scanned line based on line length. divider = max(len(scansion), len(textline)) * '-' # Sandwich the scansion and textline between two dividers. scannedLine = '\n'.join([divider, scansion, textline, divider]) # Concatenate everything to form one string that will be written. textToWrite = (scannedLine + scanNotes + '\n\n').encode(defenc) filename = str(datetime.now().date()) + '-Scansions.txt' pathname = os.path.join(os.getcwd(), filename) try: with open(pathname, 'a') as f: f.write(textToWrite) self.E.Explain("\n\nScansion and notes " + "written to " + pathname + "\n") except: self.E.Explain("\n\nERROR: The Scandroid could not automatically" + " save the scansion and notes. You will need to" + " to manually copy the information and save" + " it to a file.\n") self.GetButton('Save Scansion').Enable(False) self.GetMenuItem('Save scansion and notes').Enable(False)
def OnSaveTextBtn(self, evt): if not self.savePath: dir = os.getcwd() else: dir = self.savePath dlg = wx.FileDialog(self, message="File to save scanned text", defaultDir=dir, defaultFile='*.txt', wildcard="*.txt", style=wx.SAVE | wx.CHANGE_DIR | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: defenc = wx.GetDefaultPyEncoding() textToWrite = self.WholeText.GetText().encode(defenc) self.savePath = dlg.GetPath() try: with open(self.savePath, 'w') as f: f.write(textToWrite) self.E.Explain("\n\nTyped text written to " + self.savePath + "\n") except: self.E.Explain("\n\nERROR: The Scandroid could not save the" + " text to the file you have specified. You" + " may need to manually copy the information" + " and save it to a file.\n") dlg.Destroy()
def __LocalInit(self): try: self.ROM = self.Current_Ctrl.Get_ROM( self.Current_Ctrl.GetFocusedItem()) except: self.Close() self.Orig_Encoding = wx.GetDefaultPyEncoding() wx.SetDefaultPyEncoding("cp437") self.SetSize(Config.Config["NFO_Size"]) if Config.Config["NFO_Position"][0] == -1: self.CentreOnScreen() else: self.SetPosition(Config.Config["NFO_Position"]) self.Bind(wx.EVT_SIZE, self.On_Window_Size) self.Bind(wx.EVT_MOVE, self.On_Window_Move) # font = wx.Font( Config.Config ["NFO_Zoom"], wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, "Lucida Console", wx.FONTENCODING_CP437 ) font = wx.Font(Config.Config["NFO_Zoom"], Config.Config["NFO_Family"], Config.Config["NFO_Style"], Config.Config["NFO_Weight"], False, Config.Config["NFO_Face"], wx.FONTENCODING_CP437) self.NFO_Text.SetFont(font) Data = Utils.Get_NFO(self.ROM) if Data != "": self.NFO_Text.AppendText(Data) else: self.NFO_Text.AppendText("None Available\n") self.NFO_Text.ShowPosition(0) self.Zoom_Size_Text.SetLabel(" Zoom Size : %d" % Config.Config["NFO_Zoom"])
def getTokens(command): """Return list of token tuples for command.""" # In case the command is unicode try encoding it if type(command) == unicode: try: command = command.encode(wx.GetDefaultPyEncoding()) except UnicodeEncodeError: pass # otherwise leave it alone f = cStringIO.StringIO(command) # tokens is a list of token tuples, each looking like: # (type, string, (srow, scol), (erow, ecol), line) tokens = [] # Can't use list comprehension: # tokens = [token for token in tokenize.generate_tokens(f.readline)] # because of need to append as much as possible before TokenError. try: ## This code wasn't backward compatible with Python 2.1.3. ## ## for token in tokenize.generate_tokens(f.readline): ## tokens.append(token) # This works with Python 2.1.3 (with nested_scopes). def eater(*args): tokens.append(args) tokenize.tokenize_loop(f.readline, eater) except tokenize.TokenError: # This is due to a premature EOF, which we expect since we are # feeding in fragments of Python code. pass return tokens
def GetEnvironmentInfo(self): """Get the environmental info / Header of error report @return: string """ info = list() info.append("#---- Notes ----#") info.append("Please provide additional information about the crash here") info.extend(["", ""]) info.append("#---- System Information ----#") info.append(self.GetProgramName()) info.append("Operating System: %s" % wx.GetOsDescription()) if sys.platform == 'darwin': info.append("Mac OSX: %s" % platform.mac_ver()[0]) info.append("Python Version: %s" % sys.version) info.append("wxPython Version: %s" % wx.version()) info.append("wxPython Info: (%s)" % ", ".join(wx.PlatformInfo)) info.append("Python Encoding: Default=%s File=%s" % \ (sys.getdefaultencoding(), sys.getfilesystemencoding())) info.append("wxPython Encoding: %s" % wx.GetDefaultPyEncoding()) info.append("System Architecture: %s %s" % (platform.architecture()[0], \ platform.machine())) info.append("Byte order: %s" % sys.byteorder) info.append("Frozen: %s" % str(getattr(sys, 'frozen', 'False'))) info.append("#---- End System Information ----#") info.append("") return os.linesep.join(info)
def EnvironmentInfo(): """Returns a string of the systems information @return: System information string """ info = list() info.append("#---- Notes ----#") info.append("Please provide additional information about the crash here") info.extend(["", ""]) info.append("#---- System Information ----#") info.append("%s Version: %s" % (ed_glob.PROG_NAME, ed_glob.VERSION)) info.append("Operating System: %s" % wx.GetOsDescription()) if sys.platform == 'darwin': info.append("Mac OSX: %s" % platform.mac_ver()[0]) info.append("Python Version: %s" % sys.version) info.append("wxPython Version: %s" % wx.version()) info.append("wxPython Info: (%s)" % ", ".join(wx.PlatformInfo)) info.append("Python Encoding: Default=%s File=%s" % \ (sys.getdefaultencoding(), sys.getfilesystemencoding())) info.append("wxPython Encoding: %s" % wx.GetDefaultPyEncoding()) info.append("System Architecture: %s %s" % (platform.architecture()[0], \ platform.machine())) info.append("Byte order: %s" % sys.byteorder) info.append("Frozen: %s" % str(getattr(sys, 'frozen', 'False'))) info.append("#---- End System Information ----#") info.append("") return os.linesep.join(info)
def Import(filename): reader = vtk.vtkXMLPolyDataReader() if isinstance(filename, unicode): reader.SetFileName(filename.encode(wx.GetDefaultPyEncoding())) else: reader.SetFileName(filename) reader.Update() return reader.GetOutput()
def Import(filename): reader = vtkXMLPolyDataReader() try: reader.SetFileName(filename.encode(wx.GetDefaultPyEncoding())) except AttributeError: reader.SetFileName(filename) reader.Update() return reader.GetOutput()
def Compress(folder, filename, filelist): tmpdir, tmpdir_ = os.path.split(folder) current_dir = os.path.abspath(".") #os.chdir(tmpdir) #file_list = glob.glob(os.path.join(tmpdir_,"*")) tar_filename = tmpdir_ + ".inv3" tar = tarfile.open(filename.encode(wx.GetDefaultPyEncoding()), "w:gz") for name in filelist: tar.add(name, arcname=os.path.join(tmpdir_, filelist[name])) tar.close()
def EnvironmentInfo(): """Returns a string of the systems information @return: System information string """ info = list() info.append("#---- Notes ----#") info.append("Please provide additional information about the crash here") info.extend(["", "", ""]) info.append("#---- System Information ----#") info.append("%s Version: %s" % (ed_glob.PROG_NAME, ed_glob.VERSION)) info.append("Operating System: %s" % wx.GetOsDescription()) if sys.platform == 'darwin': info.append("Mac OSX: %s" % platform.mac_ver()[0]) info.append("Python Version: %s" % sys.version) info.append("wxPython Version: %s" % wx.version()) info.append("wxPython Info: (%s)" % ", ".join(wx.PlatformInfo)) info.append("Python Encoding: Default=%s File=%s" % \ (sys.getdefaultencoding(), sys.getfilesystemencoding())) info.append("wxPython Encoding: %s" % wx.GetDefaultPyEncoding()) info.append("System Architecture: %s %s" % (platform.architecture()[0], \ platform.machine())) info.append("Byte order: %s" % sys.byteorder) info.append("Frozen: %s" % str(getattr(sys, 'frozen', 'False'))) info.append("#---- End System Information ----#") info.append("#---- Runtime Variables ----#") from profiler import Profile ftypes = list() for key in sorted(Profile().keys()): # Exclude "private" information val = Profile().Get(key) if key.startswith('FILE') or 'proxy' in key.lower(): continue elif key == 'LAST_SESSION' or key == 'FHIST': for fname in val: if '.' in fname: ext = fname.split('.')[-1] if ext not in ftypes: ftypes.append(ext) else: try: info.append(u"%s=%s" % (key, str(val))) except UnicodeDecodeError: continue info.append(u"FTYPES=%s" % str(ftypes)) info.append("#---- End Runtime Variables ----#") return os.linesep.join(info)
def SaveHistory(self): if self.dataDir: try: name = os.path.join(self.dataDir, 'history') f = file(name, 'w') hist = [] enc = wx.GetDefaultPyEncoding() for h in self.shell.history: if isinstance(h, unicode): h = h.encode(enc) hist.append(h) hist = '\x00\n'.join(hist) f.write(hist) f.close() except: d = wx.MessageDialog(self, "Error saving history file.", "Error", wx.ICON_EXCLAMATION) d.ShowModal() d.Destroy() raise
def EnvironmentInfo(): """Returns a string of the systems information @return: System information string """ info = list() info.append("#---- System Information ----#") info.append("%s Version: %s" % (ed_glob.PROG_NAME, ed_glob.VERSION)) info.append("Operating System: %s" % wx.GetOsDescription()) if sys.platform == 'darwin': info.append("Mac OSX: %s" % platform.mac_ver()[0]) info.append("Python Version: %s" % sys.version) info.append("wxPython Version: %s" % wx.version()) info.append("wxPython Info: %s" % "\n\t\t".join(wx.PlatformInfo)) info.append("Python Encoding: Default=%s File=%s" % \ (sys.getdefaultencoding(), sys.getfilesystemencoding())) info.append("wxPython Encoding: %s" % wx.GetDefaultPyEncoding()) info.append("System Architecture: %s %s" % (platform.architecture()[0], \ platform.machine())) info.append("Byte order: %s" % sys.byteorder) info.append("Frozen: %s" % str(getattr(sys, 'frozen', 'False'))) info.append("#---- End System Information ----#") info.append("#---- Runtime Variables ----#") from profiler import Profile ftypes = list() for key, val in Profile().iteritems(): # Exclude "private" information if key.startswith('FILE'): continue elif key == 'LAST_SESSION' or key == 'FHIST': for fname in val: if u'.' in fname: ext = fname.split('.')[-1] if ext not in ftypes: ftypes.append(ext) else: info.append(u"%s=%s" % (key, str(val))) info.append(u"FTYPES=%s" % str(ftypes)) info.append("#---- End Runtime Variables ----#") return u"\n".join(info)
def EnvironmentInfo(version): info = list() info.append("#---- Notas ----#") info.append("Porfavor informe de cualquier dato adicional del error:") info.extend(["", "", ""]) info.append("#---- System Information ----#") info.append("%s Version: %s" % (APLICACION, version)) info.append("Operating System: %s" % wx.GetOsDescription()) if sys.platform == 'darwin': info.append("Mac OSX: %s" % platform.mac_ver()[0]) info.append("Python Version: %s" % sys.version) info.append("wxPython Version: %s" % wx.version()) info.append("wxPython Info: (%s)" % ", ".join(wx.PlatformInfo)) info.append("Python Encoding: Default=%s File=%s" % (sys.getdefaultencoding(), sys.getfilesystemencoding())) info.append("wxPython Encoding: %s" % wx.GetDefaultPyEncoding()) info.append("System Architecture: %s %s" % (platform.architecture()[0], platform.machine())) info.append("Byte order: %s" % sys.byteorder) info.append("Frozen: %s" % str(getattr(sys, 'frozen', 'False'))) info.append("#---- End System Information ----#") return os.linesep.join(info)
def ReplaceInFile(self, filename, pattern, replacement): fileobj = open(filename, 'r+b') text = fileobj.read() if not len(text): fileobj.close() return 0 encoding = wx.GetDefaultPyEncoding() for bom in encodings: if text.startswith(bom): encoding = encodings[bom] text = text[len(bom):] break try: text = text.decode(encoding) except UnicodeDecodeError: # If default encoding fails, Latin1 seems to work text = text.decode("latin_1") encoding = "latin_1" text, replaces = pattern.subn(replacement, text) if replaces > 0: # Don't edit the file if nothing was replaced fileobj.seek(0) fileobj.write(text.encode(encoding)) fileobj.truncate() fileobj.close() return replaces
def callback_load_source(self, r, exc_info, filename, callback, args, fComplain): (t, v, tb) = exc_info if self.m_session_manager.get_state() == rpdb2.STATE_DETACHED: return if t == None: _time = 0 _filename = r[rpdb2.DICT_KEY_FILENAME] source_lines = r[rpdb2.DICT_KEY_LINES] source = string.join(source_lines, '') if not g_fUnicode: source = rpdb2.as_string(source, wx.GetDefaultPyEncoding()) elif t == rpdb2.NotPythonSource and fComplain: dlg = wx.MessageDialog(None, MSG_ERROR_FILE_NOT_PYTHON % (filename, ), MSG_WARNING_TITLE, wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() return elif t in (IOError, socket.error, rpdb2.NotPythonSource) or isinstance( v, rpdb2.CConnectionException): if fComplain: dlg = wx.MessageDialog(None, STR_FILE_LOAD_ERROR % (filename, ), MSG_WARNING_TITLE, wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() return if t == IOError and rpdb2.BLENDER_SOURCE_NOT_AVAILABLE in v.args and not self.is_in_files( filename): dlg = wx.MessageDialog(None, STR_BLENDER_SOURCE_WARNING, MSG_WARNING_TITLE, wx.OK | wx.ICON_WARNING) dlg.ShowModal() dlg.Destroy() _time = time.time() _filename = filename source = STR_FILE_LOAD_ERROR2 % (filename, ) if not g_fUnicode: source = rpdb2.as_string(source, wx.GetDefaultPyEncoding()) else: rpdb2.print_debug( 'get_source_file() returned the following error: %s' % repr(t)) _time = time.time() _filename = filename source = STR_FILE_LOAD_ERROR2 % (filename, ) if not g_fUnicode: source = rpdb2.as_string(source, wx.GetDefaultPyEncoding()) try: self.m_lock.acquire() fNotify = not self.is_in_files(_filename) self.m_files[_filename] = (_time, source) finally: self.m_lock.release() _args = (_filename, ) + args + (fNotify, ) callback(*_args)
def copy(): return INFO.copy() def dirname(fileName): fileName = os.path.dirname(fileName) if PYTHON_COM: return win32api.GetShortPathName(fileName) else: return fileName def imageFile(fileName): return os.path.join(INFO['skinLocation'], fileName) #---wx try: import wx INFO['wxVersionC'] = wx.VERSION_STRING ## if INFO['wxVersionC']!=INFO['wxVersion']: ## print '\nSpe Warning: Spe was developped on wxPython v%s, but v%s was found.'%(INFO['wxVersion'],INFO['wxVersionC']) ## print 'If you experience any problems please install wxPython v%s\n'%INFO['wxVersion'] INFO['encoding'] = wx.GetDefaultPyEncoding() WX_ERROR = False except ImportError, message: print "Spe Error: Please install the right version of wxPython: %s" % INFO[ 'wxVersion'] print message WX_ERROR = True
def OpenFile(self, filename, oldDoc=None): filename = os.path.abspath(filename).replace("\\", '/') if type(filename) != unicode: filename = filename.decode(wx.GetDefaultPyEncoding()) if not os.path.isfile(filename): utils.ShowMessage(u"文件[%s]不存在!" % filename, "EasyPython Error") return wx.BeginBusyCursor() encoding = 'utf-8' try: cfile = file(filename, 'rb') except: utils.ShowMessage("Error Opening: " + filename, "EasyPython Error") wx.EndBusyCursor() return ''' if editrecentfiles: self.DestroyRecentFileMenu() if EpyGlob.RecentFiles.count(filename) != 0: EpyGlob.RecentFiles.remove(filename) if len(EpyGlob.RecentFiles) == config.prefs.recentfileslimit: EpyGlob.RecentFiles.pop() EpyGlob.RecentFiles.insert(0, filename) self.WriteRecentFiles() ''' if oldDoc != None: newDoc = oldDoc else: newDoc = DrText(self.frame) newDoc.filename = filename newDoc.untitlednumber = -1 self.docs.append(newDoc) EpyGlob.EventMgr.PostFileLoadingEvent(newDoc) self.docbook.AddPage(newDoc, newDoc.GetFileNameTitle()) try: oof = cfile.read() #Encoding try: oof, e = drEncoding.EncodeText(oof, encoding, True) newDoc.SetText(oof) newDoc.SetEncoding(e) except: utils.ShowMessage( 'There was an error opening the document %s.' % (filename), 'Open Error') wx.EndBusyCursor() self.frame.OnCloseFile(None) return cfile.close() newDoc.EmptyUndoBuffer() newDoc.SetSavePoint() newDoc.SetupPrefsDocument() newDoc.SetupLineNumbersMargin() newDoc.indentationtype = newDoc.CheckIndentation() self.CheckIndentation(newDoc, oof) newDoc.mtime = int(os.stat(filename).st_mtime) newDoc.SetScrollWidth(1) self.CheckLineEnding(newDoc, oof) #Scrolling lines = oof.split(newDoc.GetEndOfLineCharacter()) spaces = "\t".expandtabs(config.prefs.doctabwidth[newDoc.filetype]) line = '' length = 0 x = 0 for l in lines: if len(l) > length: line = l length = len(l) x += 1 line = line.replace('\t', spaces) + '000' scrollwidth = newDoc.TextWidth(wx.stc.STC_STYLE_DEFAULT, line) newDoc.SetScrollWidth(scrollwidth) newDoc.SetXOffset(0) #/End Scrolling except: utils.ShowMessage( "Error Opening: " + filename + "Processing failed", "EasyPython Error") #self.frame.CreateRecentFileMenu() index = self.docs.index(newDoc) self.SelectDoc(index) EpyGlob.EventMgr.PostFileLoadedEvent(newDoc) wx.EndBusyCursor()
# VyV (= a test for consonantal 'y'). This also screws up the old single- # vowel-group shortcut, so I took it out. # I did a lot of testing to try out new suffixes (and new kinds: ones with # more than one syllable; ones that force stress to the preceding syllable); # most didn't work well, but a couple make noticeable differences. Word-end # indications are omitted from *most* suffixes so as to handle multiple-suffix # word endings. The ones that remain are found only at word-end or, as in the # case of '-er', cause too much trouble if we allow them earlier. # A note on "vowels": there's always an ambiguity about 'y', # which I've resolved more or less by hunch individually in each place. import sre import wx # need ONLY for: defaultEncoding = wx.GetDefaultPyEncoding() # for DivideCV only! SIBILANTS = '40xzjgsc' # weird ones are encoded, 7th bit set MIDS = 'bdfgklmnpstw%0245' MULTISUFFIX = ('ible', 'able') STRESSSUFFIX = ('tion', 'sion', 'tiou', 'ciou', 'tious', 'cious', 'cion', 'gion', 'giou', 'gious') PREFIXES = ('a', 'as', 'be', 'con', 'de', 'di', 'ex', 're', 'un', 'en') # out-of-class functions to handle encoding of special-combination characters def encode(ch): return chr(ord(ch) & 0x3F) def decode(ch): return chr(ord(ch) | 0x40) def handleCiV(match): # encode [st] and i but not following vowel c1 = encode(match.group()[0]) c2 = encode(match.group()[1]) return c1 + c2 + match.group()[2]
except ImportError: def thunar_exists(): return False try: from lib.linux.nautilusExtension import nautilus_exists, \ create_nautilus_extension except ImportError: def nautilus_exists(): return False WX_ENCODING = wx.GetDefaultPyEncoding() #---general def menu_action(self, program, comment, method, *args, **keyw): try: success = method(*args, **keyw) self.show_info( _('If you restart %s, ' 'the action will appear in the context menu.') % program + comment) except Exception, details: reason = exception_to_unicode(details, WX_ENCODING) self.show_error(_('Phatch could not install the action in %s:')\ % program + '\n\n' + reason)
'//': 'spondee', 'xx/x': '3rd paeon', 'x/x': 'amphibrach', '///': 'molossus', '/x%': '(cretic)', '//x': 'palimbacchius' } ## 'xx':'pyrrhic', 'xxx':'tribrach' } # experiment! lineLengthName = [ '', '', 'DIMETER', 'TRIMETER', 'TETRAMETER', 'PENTAMETER', 'HEXAMETER', 'HEPTAMETER', 'OCTAMETER', 'NONAMETER' ] import wx # only for default encoding! defaultEncoding = wx.GetDefaultPyEncoding() class Explainer: """Send pedagogically useful (?) notes to the Notes frame about each step. The top-level ScandroidFrame owns an instance of this, and sends it as an argument to any function in the ScansionMachine that needs to print notes through some member of this class. """ def __init__(self, target): self.Target = target def Explain(self, str): # doesn't add newlines unless told to """All-purpose print statement for Notes""" self.Target.AppendText(str)
def ProcessMediaFile(self, inputFile): """ Process a Media File to see what it's made of, a pre-requisite to converting it. This process also populates the form's options. """ # If we're messing with wxProcess, we need to define a function to clean up if we shut down! def __del__(self): # If a process has been defined ... if self.process is not None: # ... detach it self.process.Detach() # ... Close its output self.process.CloseOutput() # ... and de-reference it self.process = None # Reset (re-initialize) all media file variables self.process = None # Clear the Information box self.memo.Clear() # Be prepared to capture the wxProcess' EVT_END_PROCESS self.Bind(wx.EVT_END_PROCESS, self.OnEndProcess) # Windows requires that we change the default encoding for Python for the audio extraction code to work # properly with Unicode files (!!!) This isn't needed on OS X, as its default file system encoding is utf-8. # See python's documentation for sys.getfilesystemencoding() if 'wxMSW' in wx.PlatformInfo: # Set the Python Encoding to match the File System Encoding wx.SetDefaultPyEncoding(sys.getfilesystemencoding()) # Just use the File Name, no encoding needed tempMediaFilename = inputFile self.memo.AppendText("wx version: %s\n" % wx.VERSION_STRING) self.memo.AppendText( "Encoding Information:\n defaultPyEncoding: %s, filesystemencoding: %s\n\n" % (wx.GetDefaultPyEncoding(), sys.getfilesystemencoding())) self.memo.AppendText( "Locale: %s %s %s\n\n" % (self.locale.Locale, self.locale.Name, self.locale.Language)) process = '"echo" "%s"' # Create a wxProcess object self.process = wx.Process(self) # Call the wxProcess Object's Redirect method. This allows us to capture the process's output! self.process.Redirect() # Encode the filenames to UTF8 so that unicode files are handled properly process = process.encode('utf8') self.memo.AppendText("Media Filename:\n") self.memo.AppendText("%s (%s)\n" % (tempMediaFilename, type(tempMediaFilename))) self.memo.AppendText("Process call:\n") self.memo.AppendText("%s (%s - %s)\n\n" % (process % tempMediaFilename, type(process), type(process % tempMediaFilename))) line = tempMediaFilename.encode('utf8') for tmpX in range(len(line)): self.memo.AppendText("%02d\t%03d" % (tmpX, ord(line[tmpX]))) if ord(line[tmpX]) < 255: self.memo.AppendText(u"\t'%s'" % (unichr(ord(line[tmpX])))) self.memo.AppendText("\n") try: self.memo.AppendText("%02d %s (%s)\n\n" % (len(line), line, type(line))) except: self.memo.AppendText("EXCEPTION RAISED:\n%s\n%s\n\n" % (sys.exc_info()[0], sys.exc_info()[1])) # Call the Audio Extraction program using wxExecute, capturing the output via wxProcess. This call MUST be asynchronous. self.pid = wx.Execute(process % tempMediaFilename.encode('utf8'), wx.EXEC_ASYNC, self.process) # On Windows, we need to reset the encoding to UTF-8 if 'wxMSW' in wx.PlatformInfo: wx.SetDefaultPyEncoding('utf_8')