def SearchFile(self, handler, count): self.fndx = self.fndx + 1 if self.fndx < len(self.flist): f = self.flist[self.fndx] if self.verbose: self.GetFirstView().Append('# ..'+f+'\n') # Directories may match the file type pattern, and files may be removed # while grep is running if os.path.isfile(f): win32ui.SetStatusText("Searching "+f, 0) lines = open(f, 'r').readlines() for i in range(len(lines)): line = lines[i] if self.pat.search(line) != None: self.GetFirstView().Append(f+'('+repr(i+1) + ') '+line) else: self.fndx = -1 self.fpndx = self.fpndx + 1 if self.fpndx < len(self.fplist): self.flist = glob.glob(self.dp[self.dpndx] + '\\' + self.fplist[self.fpndx]) else: self.fpndx = 0 self.dpndx = self.dpndx + 1 if self.dpndx < len(self.dp): self.flist = glob.glob(self.dp[self.dpndx] + '\\' + self.fplist[self.fpndx]) else: win32ui.SetStatusText("Search complete.", 0) self.SetModifiedFlag(0) # default to not modified. try: win32ui.GetApp().DeleteIdleHandler(self.SearchFile) except: pass return 0 return 1
def GetSubList(self): mod, path = pywin.framework.scriptutils.GetPackageModuleName(self.path) win32ui.SetStatusText("Building class list - please wait...", 1) win32ui.DoWaitCursor(1) try: try: reader = pyclbr.readmodule_ex # Post 1.5.2 interface. extra_msg = " or functions" except AttributeError: reader = pyclbr.readmodule extra_msg = "" data = reader(mod, [path]) if data: ret = [] for item in data.values(): # ie, it is a pyclbr Function instance (only introduced # post 1.5.2) if item.__class__ != pyclbr.Class: ret.append(HLICLBRFunction(item, " (function)")) else: ret.append(HLICLBRClass(item, " (class)")) ret.sort() return ret else: return [ HLIErrorItem("No Python classes%s in module." % (extra_msg, )) ] finally: win32ui.DoWaitCursor(0) win32ui.SetStatusText( win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
def OnAdd(self, msg, code): doc, view = scriptutils.GetActiveEditorDocument() if doc is None: ## Don't do a messagebox, as this could be triggered from the app's ## idle loop whenever the debug toolbar is visible, giving a never-ending ## series of dialogs. This can happen when the OnUpdate handler ## for the toolbar button IDC_DBG_ADD fails, since MFC falls back to ## sending a normal command if the UI update command fails. ## win32ui.MessageBox('There is no active window - no breakpoint can be added') warnings.warn( 'There is no active window - no breakpoint can be added') return None pathName = doc.GetPathName() lineNo = view.LineFromChar(view.GetSel()[0]) + 1 # If I have a debugger, then tell it, otherwise just add a marker d = self._GetDebugger() if d is None: import pywin.framework.editor.color.coloreditor doc.MarkerToggle( lineNo, pywin.framework.editor.color.coloreditor.MARKER_BREAKPOINT) else: if d.get_break(pathName, lineNo): win32ui.SetStatusText('Clearing breakpoint', 1) rc = d.clear_break(pathName, lineNo) else: win32ui.SetStatusText('Setting breakpoint', 1) rc = d.set_break(pathName, lineNo) if rc: win32ui.MessageBox(rc) d.GUIRespondDebuggerData()
def _MakeRoot(self): path = self.GetDocument().GetPathName() if not path: return HierListCLBRErrorRoot( "Error: Can not browse a file until it is saved") else: mod, path = pywin.framework.scriptutils.GetPackageModuleName(path) if self.bDirty: what = "Refreshing" # Hack for pyclbr being too smart try: del pyclbr._modules[mod] except (KeyError, AttributeError): pass else: what = "Building" win32ui.SetStatusText("%s class list - please wait..." % (what, ), 1) win32ui.DoWaitCursor(1) try: reader = pyclbr.readmodule_ex # new version post 1.5.2 except AttributeError: reader = pyclbr.readmodule try: data = reader(mod, [path]) if data: return HierListCLBRModule(mod, data) else: return HierListCLBRErrorRoot( "No Python classes in module.") finally: win32ui.DoWaitCursor(0) win32ui.SetStatusText( win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
def _inactive_idleHandler(self, handler, count): self.fndx = self.fndx + 1 if self.fndx < len(self.flist): f = self.flist[self.fndx] if self.verbose: self.GetFirstView().Append('# ..'+f+'\n') win32ui.SetStatusText("Searching "+f, 0) lines = open(f, 'r').readlines() for i in range(len(lines)): line = lines[i] if self.pat.search(line) != None: self.GetFirstView().Append(f+'('+repr(i+1) + ') '+line) else: self.fndx = -1 self.fpndx = self.fpndx + 1 if self.fpndx < len(self.fplist): self.flist = glob.glob(self.dp[self.dpndx] + '\\' + self.fplist[self.fpndx]) else: self.fpndx = 0 self.dpndx = self.dpndx + 1 if self.dpndx < len(self.dp): self.flist = glob.glob(self.dp[self.dpndx] + '\\' + self.fplist[self.fpndx]) else: win32ui.SetStatusText("Search complete.", 0) self.SetModifiedFlag(0) # default to not modified. try: win32ui.GetApp().DeleteIdleHandler(self.idleHandler) except: pass return 0 return 1
def CheckFile(): """This code looks for the current window, and gets Python to check it without actually executing any code (ie, by compiling only) """ try: pathName = GetActiveFileName() except KeyboardInterrupt: return what = "check" win32ui.SetStatusText(what.capitalize() + "ing module...", 1) win32ui.DoWaitCursor(1) try: f = open(pathName) except IOError as details: print("Cant open file '%s' - %s" % (pathName, details)) return try: code = f.read() + "\n" finally: f.close() try: codeObj = compile(code, pathName, "exec") if RunTabNanny(pathName): win32ui.SetStatusText( "Python and the TabNanny successfully checked the file '" + os.path.basename(pathName) + "'") except SyntaxError: _HandlePythonFailure(what, pathName) except: traceback.print_exc() _HandlePythonFailure(what) win32ui.DoWaitCursor(0)
def HandleToolCommand(cmd, code): import traceback import re global tools (menuString, pyCmd, desc) = tools[cmd] win32ui.SetStatusText("Executing tool %s" % desc, 1) pyCmd = re.sub('\\\\n', '\n', pyCmd) win32ui.DoWaitCursor(1) oldFlag = None try: oldFlag = sys.stdout.template.writeQueueing sys.stdout.template.writeQueueing = 0 except (NameError, AttributeError): pass try: exec("%s\n" % pyCmd) worked = 1 except SystemExit: # The program raised a SystemExit - ignore it. worked = 1 except: print("Failed to execute command:\n%s" % pyCmd) traceback.print_exc() worked = 0 if oldFlag is not None: sys.stdout.template.writeQueueing = oldFlag win32ui.DoWaitCursor(0) if worked: text = "Completed successfully." else: text = "Error executing %s." % desc win32ui.SetStatusText(text, 1)
def OnSaveDocument(self, fileName): win32ui.SetStatusText("Saving file...", 1) # rename to bak if required. dir, basename = os.path.split(fileName) if self.bakFileType == BAK_DOT_BAK: bakFileName = dir + '\\' + os.path.splitext(basename)[0] + '.bak' elif self.bakFileType == BAK_DOT_BAK_TEMP_DIR: bakFileName = win32api.GetTempPath() + '\\' + os.path.splitext( basename)[0] + '.bak' elif self.bakFileType == BAK_DOT_BAK_BAK_DIR: tempPath = os.path.join(win32api.GetTempPath(), 'bak') try: os.mkdir(tempPath, 0) except os.error: pass bakFileName = os.path.join(tempPath, basename) try: os.unlink(bakFileName) # raise NameError if no bakups wanted. except (os.error, NameError): pass try: # Do a copy as it might be on different volumes, # and the file may be a hard-link, causing the link # to follow the backup. shutil.copy2(fileName, bakFileName) except (os.error, NameError, IOError): pass try: self.SaveFile(fileName) except IOError as details: win32ui.MessageBox("Error - could not save file\r\n\r\n%s" % details) return 0 except (UnicodeEncodeError, LookupError) as details: rc = win32ui.MessageBox( "Encoding failed: \r\n%s" % details + '\r\nPlease add desired source encoding as first line of file, eg \r\n' + '# -*- coding: mbcs -*-\r\n\r\n' + 'If you continue, the file will be saved as binary and will\r\n' + 'not be valid in the declared encoding.\r\n\r\n' + 'Save the file as binary with an invalid encoding?', "File save failed", win32con.MB_YESNO | win32con.MB_DEFBUTTON2) if rc == win32con.IDYES: try: self.SaveFile(fileName, encoding="latin-1") except IOError as details: win32ui.MessageBox( "Error - could not save file\r\n\r\n%s" % details) return 0 else: return 0 self.SetModifiedFlag(0) # No longer dirty self.bDeclinedReload = 0 # They probably want to know if it changes again! win32ui.AddToRecentFileList(fileName) self.SetPathName(fileName) win32ui.SetStatusText("Ready") self._DocumentStateChanged() return 1
def OnSaveDocument( self, fileName ): win32ui.SetStatusText("Saving file...",1) try: self.SaveFile(fileName) except IOError as details: win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details) return 0 win32ui.SetStatusText("Ready") return 1
def _HandlePythonFailure(what, syntaxErrorPathName = None): typ, details, tb = sys.exc_info() if typ == SyntaxError: try: msg, (fileName, line, col, text) = details if (not fileName or fileName =="<string>") and syntaxErrorPathName: fileName = syntaxErrorPathName _JumpToPosition(fileName, line, col) except (TypeError, ValueError): msg = str(details) win32ui.SetStatusText('Failed to ' + what + ' - syntax error - %s' % msg) else: traceback.print_exc() win32ui.SetStatusText('Failed to ' + what + ' - ' + str(details) )
def RunTabNanny(filename): import cStringIO tabnanny = FindTabNanny() if tabnanny is None: win32ui.MessageBox("The TabNanny is not around, so the children can run amok!" ) return # Capture the tab-nanny output newout = cStringIO.StringIO() old_out = sys.stderr, sys.stdout sys.stderr = sys.stdout = newout try: tabnanny.check(filename) finally: # Restore output sys.stderr, sys.stdout = old_out data = newout.getvalue() if data: try: lineno = string.split(data)[1] lineno = int(lineno) _JumpToPosition(filename, lineno) try: # Try and display whitespace GetActiveEditControl().SCISetViewWS(1) except: pass win32ui.SetStatusText("The TabNanny found trouble at line %d" % lineno) except (IndexError, TypeError, ValueError): print "The tab nanny complained, but I cant see where!" print data return 0 return 1
def doSearch(self): self.dp = dirpath(self.dirpattern, self.recurse) self.SetTitle("Pychecker Run '%s' (options: %s)" % (self.filpattern, self.greppattern)) #self.text = [] self.GetFirstView().Append('#Pychecker Run in ' + self.dirpattern + ' %s\n' % time.asctime()) if self.verbose: self.GetFirstView().Append('# =' + repr(self.dp.dirs) + '\n') self.GetFirstView().Append('# Files ' + self.filpattern + '\n') self.GetFirstView().Append('# Options ' + self.greppattern + '\n') self.fplist = self.filpattern.split(';') self.GetFirstView().Append( '# Running... ( double click on result lines in order to jump to the source code ) \n' ) win32ui.SetStatusText("Pychecker running. Please wait...", 0) self.dpndx = self.fpndx = 0 self.fndx = -1 if not self.dp: self.GetFirstView().Append( "# ERROR: '%s' does not resolve to any search locations" % self.dirpattern) self.SetModifiedFlag(0) else: ##self.flist = glob.glob(self.dp[0]+'\\'+self.fplist[0]) import operator self.flist = reduce(operator.add, list(map(glob.glob, self.fplist))) #import pywin.debugger;pywin.debugger.set_trace() self.startPycheckerRun()
def TakeDefaultAction(self): if self.file: pywin.framework.scriptutils.JumpToDocument( self.file, self.lineno, bScrollToTop=1 ) else: win32ui.SetStatusText("Can not locate the source code for this object.")
def PerformItemSelected(self): if self.file is None: msg = "%s - source can not be located." % (self.name, ) else: msg = "%s defined at line %d of %s" % (self.name, self.lineno, self.file) win32ui.SetStatusText(msg)
def OnFileSaveAll(self, id, code): # Only attempt to save editor documents. from pywin.framework.editor import editorTemplate docs = filter(lambda doc: doc.IsModified() and doc.GetPathName(), editorTemplate.GetDocumentList()) map(lambda doc: doc.OnSaveDocument(doc.GetPathName()), docs) win32ui.SetStatusText("%d documents saved" % len(docs), 1)
def OnOpenDocument(self, filename): # # handle Unix and PC text file format. # # Get the "long name" of the file name, as it may have been translated # to short names by the shell. self.SetPathName(filename) # Must set this early! # Now do the work! self.BeginWaitCursor() win32ui.SetStatusText("Loading file...",1) try: f = open(filename,"rb") except IOError: win32ui.MessageBox(filename + '\nCan not find this file\nPlease verify that the correct path and file name are given') self.EndWaitCursor() return 0 raw=f.read() f.close() contents = self.TranslateLoadedData(raw) rc = 0 if win32ui.IsWin32s() and len(contents)>62000: # give or take a few bytes win32ui.MessageBox("This file is too big for Python on Windows 3.1\r\nPlease use another editor to view this file.") else: try: self.GetFirstView().SetWindowText(contents) rc = 1 except TypeError: # Null byte in file. win32ui.MessageBox("This file contains NULL bytes, and can not be edited") rc = 0 self.EndWaitCursor() self.SetModifiedFlag(0) # No longer dirty self._DocumentStateChanged() return rc
def OnSaveDocument( self, fileName ): win32ui.SetStatusText("Saving file...",1) # rename to bak if required. dir, basename = os.path.split(fileName) if self.bakFileType==BAK_DOT_BAK: bakFileName=dir+'\\'+os.path.splitext(basename)[0]+'.bak' elif self.bakFileType==BAK_DOT_BAK_TEMP_DIR: bakFileName=win32api.GetTempPath()+'\\'+os.path.splitext(basename)[0]+'.bak' elif self.bakFileType==BAK_DOT_BAK_BAK_DIR: tempPath=os.path.join(win32api.GetTempPath(),'bak') try: os.mkdir(tempPath,0) except os.error: pass bakFileName=os.path.join(tempPath,basename) try: os.unlink(bakFileName) # raise NameError if no bakups wanted. except (os.error, NameError): pass try: # Do a copy as it might be on different volumes, # and the file may be a hard-link, causing the link # to follow the backup. shutil.copy2(fileName, bakFileName) except (os.error, NameError, IOError): pass try: self.SaveFile(fileName) except IOError, details: win32ui.MessageBox("Error - could not save file\r\n\r\n%s"%details) return 0
def WindowBackEvent(self, event): parent = self.GetParentFrame() if parent == win32ui.GetMainFrame(): # It is docked. try: wnd, isactive = parent.MDIGetActive() wnd.SetFocus() except win32ui.error: # No MDI window active! pass else: # Normal Window try: lastActive = self.GetParentFrame().lastActive # If the window is invalid, reset it. if lastActive is not None and (lastActive._obj_ is None or lastActive.GetSafeHwnd() == 0): lastActive = self.GetParentFrame().lastActive = None win32ui.SetStatusText( "The last active Window has been closed.") except AttributeError: print "Can't find the last active window!" lastActive = None if lastActive is not None: lastActive.MDIActivate()
def doSearch(self): self.dp = dirpath(self.dirpattern, self.recurse) self.SetTitle("Grep for %s in %s" % (self.greppattern, self.filpattern)) #self.text = [] self.GetFirstView().Append('#Search ' + self.dirpattern + '\n') if self.verbose: self.GetFirstView().Append('# =' + repr(self.dp.dirs) + '\n') self.GetFirstView().Append('# Files ' + self.filpattern + '\n') self.GetFirstView().Append('# For ' + self.greppattern + '\n') self.fplist = self.filpattern.split(';') if self.casesensitive: self.pat = re.compile(self.greppattern) else: self.pat = re.compile(self.greppattern, re.IGNORECASE) win32ui.SetStatusText("Searching. Please wait...", 0) self.dpndx = self.fpndx = 0 self.fndx = -1 if not self.dp: self.GetFirstView().Append( "# ERROR: '%s' does not resolve to any search locations" % self.dirpattern) self.SetModifiedFlag(0) else: self.flist = glob.glob(self.dp[0] + '\\' + self.fplist[0]) win32ui.GetApp().AddIdleHandler(self.SearchFile)
def TakeDefaultAction(self): if self.file: pywin.framework.scriptutils.JumpToDocument(self.file, self.lineno, bScrollToTop=1) else: win32ui.SetStatusText("The source of this object is unknown")
def ProcessEscEvent(self, event): # Implement a cancel. if self.SCIAutoCActive() or self.SCICallTipActive(): self.SCICancel() else: win32ui.SetStatusText('Cancelled.') self.AppendToPrompt(('', )) return 0
def TranslateLoadedData(self, data): """Given raw data read from a file, massage it suitable for the edit window""" # if a CR in the first 250 chars, then perform the expensive translate if data[:250].find('\r')==-1: win32ui.SetStatusText("Translating from Unix file format - please wait...",1) return re.sub('\r*\n','\r\n',data) else: return data
def _HandlePythonFailure(what, syntaxErrorPathName=None): typ, details, tb = sys.exc_info() if isinstance(details, SyntaxError): try: msg, (fileName, line, col, text) = details if (not fileName or fileName == "<string>") and syntaxErrorPathName: fileName = syntaxErrorPathName _JumpToPosition(fileName, line, col) except (TypeError, ValueError): msg = str(details) win32ui.SetStatusText("Failed to " + what + " - syntax error - %s" % msg) else: traceback.print_exc() win32ui.SetStatusText("Failed to " + what + " - " + str(details)) tb = None # Clean up a cycle.
def HandleSpecialLine(self): import scriptutils line = self.GetLine() if line[:11]=="com_error: ": # An OLE Exception - pull apart the exception # and try and locate a help file. try: import win32api, win32con det = eval(line[line.find(":")+1:].strip()) win32ui.SetStatusText("Opening help file on OLE error..."); import help help.OpenHelpFile(det[2][3],win32con.HELP_CONTEXT, det[2][4]) return 1 except win32api.error, details: win32ui.SetStatusText("The help file could not be opened - %s" % details.strerror) return 1 except:
def OnOK(self): self.UpdateData(1) for id, name in [(101,'greppattern'), (102,'dirpattern'), (103,'filpattern')]: if not self[name]: self.GetDlgItem(id).SetFocus() win32api.MessageBeep() win32ui.SetStatusText("Please enter a value") return self._obj_.OnOK()
def OnFileSaveAll(self, id, code): # Only attempt to save editor documents. from pywin.framework.editor import editorTemplate num = 0 for doc in editorTemplate.GetDocumentList(): if doc.IsModified() and doc.GetPathName(): num = num = 1 doc.OnSaveDocument(doc.GetPathName()) win32ui.SetStatusText("%d documents saved" % num, 1)
def HandleSpecialLine(self): from . import scriptutils line = self.GetLine() if line[:11] == "com_error: ": # An OLE Exception - pull apart the exception # and try and locate a help file. try: import win32api import win32con det = eval(line[line.find(":") + 1:].strip()) win32ui.SetStatusText("Opening help file on OLE error...") from . import help help.OpenHelpFile(det[2][3], win32con.HELP_CONTEXT, det[2][4]) return 1 except win32api.error as details: win32ui.SetStatusText( "The help file could not be opened - %s" % details.strerror) return 1 except: win32ui.SetStatusText( "Line is a COM error, but no WinHelp details can be parsed") # Look for a Python traceback. matchResult = self.patErrorMessage.match(line) if matchResult is None: # No match - try the previous line lineNo = self.LineFromChar() if lineNo > 0: line = self.GetLine(lineNo - 1) matchResult = self.patErrorMessage.match(line) if matchResult is not None: # we have an error line. fileName = matchResult.group(1) if fileName[0] == "<": win32ui.SetStatusText("Can not load this file") return 1 # still was an error message. else: lineNoString = matchResult.group(2) # Attempt to locate the file (in case it is a relative spec) fileNameSpec = fileName fileName = scriptutils.LocatePythonFile(fileName) if fileName is None: # Dont force update, so it replaces the idle prompt. win32ui.SetStatusText( "Cant locate the file '%s'" % (fileNameSpec), 0) return 1 win32ui.SetStatusText( "Jumping to line " + lineNoString + " of file " + fileName, 1) if not scriptutils.JumpToDocument(fileName, int(lineNoString)): win32ui.SetStatusText("Could not open %s" % fileName) return 1 # still was an error message. return 1 return 0 # not an error line
def _ReplaceIt(control): control = _GetControl(control) statusText = "Can not find '%s'." % lastSearch.findText rc = FOUND_NOTHING if control is not None and lastSearch.sel != (-1, -1): control.ReplaceSel(lastSearch.replaceText) rc = FindNext() if rc != FOUND_NOTHING: statusText = win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE) win32ui.SetStatusText(statusText) return rc
def OnCmdLocateFile(self, cmd, code): modName = patImport.group('name') if not modName: return 0 import pywin.framework.scriptutils fileName = pywin.framework.scriptutils.LocatePythonFile(modName) if fileName is None: win32ui.SetStatusText("Can't locate module %s" % modName) else: win32ui.GetApp().OpenDocumentFile(fileName) return 0
def ReloadDocument(self): """Reloads the document from disk. Assumes the file has been saved and user has been asked if necessary - it just does it! """ win32ui.SetStatusText("Reloading document. Please wait...", 1) self.SetModifiedFlag(0) # Loop over all views, saving their state, then reload the document views = self.GetAllViews() states = [] for view in views: try: info = view._PrepareUserStateChange() except AttributeError: # Not our editor view? info = None states.append(info) self.OnOpenDocument(self.GetPathName()) for view, info in zip(views, states): if info is not None: view._EndUserStateChange(info) self._DocumentStateChanged() win32ui.SetStatusText("Document reloaded.")