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 RespondDebuggerState(self, state): if state == self.debuggerState: return if state == DBGSTATE_NOT_DEBUGGING: # Debugger exists, but not doing anything title = "" elif state == DBGSTATE_RUNNING: # Code is running under the debugger. title = " - running" elif state == DBGSTATE_BREAK: # We are at a breakpoint or stepping or whatever. if self.bAtException: if self.bAtPostMortem: title = " - post mortem exception" else: title = " - exception" else: title = " - break" else: raise error("Invalid debugger state passed!") win32ui.GetMainFrame().SetWindowText( win32ui.LoadString(win32ui.IDR_MAINFRAME) + title) if self.debuggerState == DBGSTATE_QUITTING and state != DBGSTATE_NOT_DEBUGGING: print "Ignoring state change cos Im trying to stop!", state return self.debuggerState = state try: frame = win32ui.GetMainFrame() except win32ui.error: frame = None if frame is not None: for id, klass, float in DebuggerDialogInfos: cb = win32ui.GetMainFrame().GetControlBar(id).dialog cb.RespondDebuggerState(state) # Tell each open editor window about the state transition for doc in editor.editorTemplate.GetDocumentList(): doc.OnDebuggerStateChange(state) self.ShowCurrentLine()
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 _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 OnPrint(self, dc, pInfo): metrics = dc.GetTextMetrics() # print "dev", w, h, l, metrics['tmAscent'], metrics['tmDescent'] if self.starts is None: self.CalculatePageRanges(dc, pInfo) pageNum = pInfo.GetCurPage() - 1 # Setup the header of the page - docname on left, pagenum on right. doc = self.GetDocument() cxChar = metrics['tmAveCharWidth'] cyChar = metrics['tmHeight'] left, top, right, bottom = pInfo.GetDraw() dc.TextOut(0, 2*cyChar, doc.GetTitle()) pagenum_str = win32ui.LoadString(afxres.AFX_IDS_PRINTPAGENUM) % (pageNum+1,) dc.SetTextAlign(win32con.TA_RIGHT) dc.TextOut(right, 2*cyChar, pagenum_str) dc.SetTextAlign(win32con.TA_LEFT) top = top + int((7*cyChar)/2) dc.MoveTo(left, top) dc.LineTo(right, top) top = top + cyChar rc = (left, top, right, bottom) nextPageStart = self.FormatRange(dc, self.starts[pageNum], self.starts[pageNum+1], rc, 1)
def InitInstance(self): # Use a registry path of "Python\Pythonwin Debugger win32ui.SetAppName(win32ui.LoadString(win32ui.IDR_DEBUGGER)) win32ui.SetRegistryKey("Python %s" % (sys.winver,)) # We _need_ the Scintilla color editor. # (and we _always_ get it now :-) numMRU = win32ui.GetProfileVal("Settings","Recent File List Size", 10) win32ui.LoadStdProfileSettings(numMRU) self.LoadMainFrame() # Display the interactive window if the user wants it. from pywin.framework import interact interact.CreateInteractiveWindowUserPreference() # Load the modules we use internally. self.LoadSystemModules() # Load additional module the user may want. self.LoadUserModules() # win32ui.CreateDebuggerThread() win32ui.EnableControlContainer()
def ProcessEnterEvent(self, event): #If autocompletion has been triggered, complete and do not process event if self.SCIAutoCActive(): self.SCIAutoCComplete() self.SCICancel() return self.SCICancel() # First, check for an error message haveGrabbedOutput = 0 if self.HandleSpecialLine(): return 0 lineNo = self.LineFromChar() start, end, isCode = self.GetBlockBoundary(lineNo) # If we are not in a code block just go to the prompt (or create a new one) if not isCode: self.AppendToPrompt([]) win32ui.SetStatusText( win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE)) return lines = self.ExtractCommand((start, end)) # If we are in a code-block, but it isnt at the end of the buffer # then copy it to the end ready for editing and subsequent execution if end != self.GetLineCount() - 1: win32ui.SetStatusText('Press ENTER to execute command') self.AppendToPrompt(lines) self.SetSel(-2) return # If SHIFT held down, we want new code here and now! bNeedIndent = win32api.GetKeyState( win32con.VK_SHIFT) < 0 or win32api.GetKeyState( win32con.VK_CONTROL) < 0 if bNeedIndent: self.ReplaceSel("\n") else: self.SetSel(-2) self.ReplaceSel("\n") source = '\n'.join(lines) while source and source[-1] in '\t ': source = source[:-1] self.OutputGrab() # grab the output for the command exec. try: if self.interp.runsource( source, "<interactive input>"): # Need more input! bNeedIndent = 1 else: # If the last line isnt empty, append a newline if self.history is not None: self.history.history_store(source) self.AppendToPrompt([]) win32ui.SetStatusText( win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE)) # win32ui.SetStatusText('Successfully executed statement') finally: self.OutputRelease() if bNeedIndent: win32ui.SetStatusText('Ready to continue the command') # Now attempt correct indentation (should use IDLE?) curLine = self.DoGetLine(lineNo)[len(sys.ps2):] pos = 0 indent = '' while len(curLine) > pos and curLine[pos] in string.whitespace: indent = indent + curLine[pos] pos = pos + 1 if _is_block_opener(curLine): indent = indent + '\t' elif _is_block_closer(curLine): indent = indent[:-1] # use ReplaceSel to ensure it goes at the cursor rather than end of buffer. self.ReplaceSel(sys.ps2 + indent) return 0
def _FindIt(control, searchParams): global lastSearch, defaultSearch control = _GetControl(control) if control is None: return FOUND_NOTHING # Move to the next char, so we find the next one. flags = 0 if searchParams.matchWords: flags = flags | win32con.FR_WHOLEWORD if searchParams.matchCase: flags = flags | win32con.FR_MATCHCASE if searchParams.sel == (-1, -1): sel = control.GetSel() # If the position is the same as we found last time, # then we assume it is a "FindNext" if sel == lastSearch.sel: sel = sel[0] + 1, sel[0] + 1 else: sel = searchParams.sel if sel[0] == sel[1]: sel = sel[0], control.GetTextLength() rc = FOUND_NOTHING # (Old edit control will fail here!) posFind, foundSel = control.FindText(flags, sel, searchParams.findText) lastSearch = SearchParams(searchParams) if posFind >= 0: rc = FOUND_NORMAL lineno = control.LineFromChar(posFind) control.SCIEnsureVisible(lineno) control.SetSel(foundSel) control.SetFocus() win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE)) if rc == FOUND_NOTHING and lastSearch.acrossFiles: # Loop around all documents. First find this document. try: try: doc = control.GetDocument() except AttributeError: try: doc = control.GetParent().GetDocument() except AttributeError: print "Cant find a document for the control!" doc = None if doc is not None: template = doc.GetDocTemplate() alldocs = template.GetDocumentList() mypos = lookpos = alldocs.index(doc) while 1: lookpos = (lookpos + 1) % len(alldocs) if lookpos == mypos: break view = alldocs[lookpos].GetFirstView() posFind, foundSel = view.FindText( flags, (0, view.GetTextLength()), searchParams.findText) if posFind >= 0: nChars = foundSel[1] - foundSel[0] lineNo = view.LineFromChar(posFind) # zero based. lineStart = view.LineIndex(lineNo) colNo = posFind - lineStart # zero based. scriptutils.JumpToDocument( alldocs[lookpos].GetPathName(), lineNo + 1, colNo + 1, nChars) rc = FOUND_NEXT_FILE break except win32ui.error: pass if rc == FOUND_NOTHING: # Loop around this control - attempt to find from the start of the control. posFind, foundSel = control.FindText(flags, (0, sel[0] - 1), searchParams.findText) if posFind >= 0: control.SCIEnsureVisible(control.LineFromChar(foundSel[0])) control.SetSel(foundSel) control.SetFocus() win32ui.SetStatusText( "Not found! Searching from the top of the file.") rc = FOUND_LOOPED_BACK else: lastSearch.sel = -1, -1 win32ui.SetStatusText("Can not find '%s'" % searchParams.findText) if rc != FOUND_NOTHING: lastSearch.sel = foundSel if lastSearch.remember: defaultSearch = lastSearch return rc
def RunScript(defName=None, defArgs=None, bShowDialog = 1, debuggingType=None): global lastScript, lastArgs, lastDebuggingType _debugger_stop_frame_ = 1 # Magic variable so the debugger will hide me! # Get the debugger - may be None! debugger = GetDebugger() if defName is None: try: pathName = GetActiveFileName() except KeyboardInterrupt: return # User cancelled save. else: pathName = defName if not pathName: pathName = lastScript if defArgs is None: args = '' if pathName==lastScript: args = lastArgs else: args = defArgs if debuggingType is None: debuggingType = lastDebuggingType if not pathName or bShowDialog: dlg = DlgRunScript(debugger is not None) dlg['script'] = pathName dlg['args'] = args dlg['debuggingType'] = debuggingType if dlg.DoModal() != win32con.IDOK: return script=dlg['script'] args=dlg['args'] debuggingType = dlg['debuggingType'] if not script: return if debuggingType == RS_DEBUGGER_GO and debugger is not None: # This may surprise users - they select "Run under debugger", but # it appears not to! Only warn when they pick from the dialog! # First - ensure the debugger is activated to pickup any break-points # set in the editor. try: # Create the debugger, but _dont_ init the debugger GUI. rd = debugger._GetCurrentDebugger() except AttributeError: rd = None if rd is not None and len(rd.breaks)==0: msg = "There are no active break-points.\r\n\r\nSelecting this debug option without any\r\nbreak-points is unlikely to have the desired effect\r\nas the debugger is unlikely to be invoked..\r\n\r\nWould you like to step-through in the debugger instead?" rc = win32ui.MessageBox(msg, win32ui.LoadString(win32ui.IDR_DEBUGGER), win32con.MB_YESNOCANCEL | win32con.MB_ICONINFORMATION) if rc == win32con.IDCANCEL: return if rc == win32con.IDYES: debuggingType = RS_DEBUGGER_STEP lastDebuggingType = debuggingType lastScript = script lastArgs = args else: script = pathName # try and open the script. if len(os.path.splitext(script)[1])==0: # check if no extension supplied, and give one. script = script + '.py' # If no path specified, try and locate the file path, fnameonly = os.path.split(script) if len(path)==0: try: os.stat(fnameonly) # See if it is OK as is... script = fnameonly except os.error: fullScript = app.LocatePythonFile(script) if fullScript is None: win32ui.MessageBox("The file '%s' can not be located" % script ) return script = fullScript else: path = win32ui.FullPath(path) if not IsOnPythonPath(path): sys.path.append(path) try: f = open(script) except IOError, (code, msg): win32ui.MessageBox("The file could not be opened - %s (%d)" % (msg, code)) return
def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): global lastScript, lastArgs, lastDebuggingType _debugger_stop_frame_ = 1 # Magic variable so the debugger will hide me! # Get the debugger - may be None! debugger = GetDebugger() if defName is None: try: pathName = GetActiveFileName() except KeyboardInterrupt: return # User cancelled save. else: pathName = defName if not pathName: pathName = lastScript if defArgs is None: args = "" if pathName == lastScript: args = lastArgs else: args = defArgs if debuggingType is None: debuggingType = lastDebuggingType if not pathName or bShowDialog: dlg = DlgRunScript(debugger is not None) dlg["script"] = pathName dlg["args"] = args dlg["debuggingType"] = debuggingType if dlg.DoModal() != win32con.IDOK: return script = dlg["script"] args = dlg["args"] debuggingType = dlg["debuggingType"] if not script: return if debuggingType == RS_DEBUGGER_GO and debugger is not None: # This may surprise users - they select "Run under debugger", but # it appears not to! Only warn when they pick from the dialog! # First - ensure the debugger is activated to pickup any break-points # set in the editor. try: # Create the debugger, but _dont_ init the debugger GUI. rd = debugger._GetCurrentDebugger() except AttributeError: rd = None if rd is not None and len(rd.breaks) == 0: msg = "There are no active break-points.\r\n\r\nSelecting this debug option without any\r\nbreak-points is unlikely to have the desired effect\r\nas the debugger is unlikely to be invoked..\r\n\r\nWould you like to step-through in the debugger instead?" rc = win32ui.MessageBox( msg, win32ui.LoadString(win32ui.IDR_DEBUGGER), win32con.MB_YESNOCANCEL | win32con.MB_ICONINFORMATION, ) if rc == win32con.IDCANCEL: return if rc == win32con.IDYES: debuggingType = RS_DEBUGGER_STEP lastDebuggingType = debuggingType lastScript = script lastArgs = args else: script = pathName # try and open the script. if (len(os.path.splitext(script)[1]) == 0 ): # check if no extension supplied, and give one. script = script + ".py" # If no path specified, try and locate the file path, fnameonly = os.path.split(script) if len(path) == 0: try: os.stat(fnameonly) # See if it is OK as is... script = fnameonly except os.error: fullScript = LocatePythonFile(script) if fullScript is None: win32ui.MessageBox("The file '%s' can not be located" % script) return script = fullScript else: path = win32ui.FullPath(path) if not IsOnPythonPath(path): sys.path.append(path) # py3k fun: If we use text mode to open the file, we get \r\n # translated so Python allows the syntax (good!), but we get back # text already decoded from the default encoding (bad!) and Python # ignores any encoding decls (bad!). If we use binary mode we get # the raw bytes and Python looks at the encoding (good!) but \r\n # chars stay in place so Python throws a syntax error (bad!). # So: so the binary thing and manually normalize \r\n. try: f = open(script, "rb") except IOError as exc: win32ui.MessageBox("The file could not be opened - %s (%d)" % (exc.strerror, exc.errno)) return # Get the source-code - as above, normalize \r\n code = f.read().replace(byte_crlf, byte_lf).replace(byte_cr, byte_lf) + byte_lf # Remember and hack sys.argv for the script. oldArgv = sys.argv sys.argv = ParseArgs(args) sys.argv.insert(0, script) # sys.path[0] is the path of the script oldPath0 = sys.path[0] newPath0 = os.path.split(script)[0] if not oldPath0: # if sys.path[0] is empty sys.path[0] = newPath0 insertedPath0 = 0 else: sys.path.insert(0, newPath0) insertedPath0 = 1 bWorked = 0 win32ui.DoWaitCursor(1) base = os.path.split(script)[1] # Allow windows to repaint before starting. win32ui.PumpWaitingMessages() win32ui.SetStatusText("Running script %s..." % base, 1) exitCode = 0 from pywin.framework import interact # Check the debugger flags if debugger is None and (debuggingType != RS_DEBUGGER_NONE): win32ui.MessageBox( "No debugger is installed. Debugging options have been ignored!") debuggingType = RS_DEBUGGER_NONE # Get a code object - ignore the debugger for this, as it is probably a syntax error # at this point try: codeObject = compile(code, script, "exec") except: # Almost certainly a syntax error! _HandlePythonFailure("run script", script) # No code object which to run/debug. return __main__.__file__ = script try: if debuggingType == RS_DEBUGGER_STEP: debugger.run(codeObject, __main__.__dict__, start_stepping=1) elif debuggingType == RS_DEBUGGER_GO: debugger.run(codeObject, __main__.__dict__, start_stepping=0) else: # Post mortem or no debugging exec(codeObject, __main__.__dict__) bWorked = 1 except bdb.BdbQuit: # Dont print tracebacks when the debugger quit, but do print a message. print("Debugging session cancelled.") exitCode = 1 bWorked = 1 except SystemExit as code: exitCode = code bWorked = 1 except KeyboardInterrupt: # Consider this successful, as we dont want the debugger. # (but we do want a traceback!) if interact.edit and interact.edit.currentView: interact.edit.currentView.EnsureNoPrompt() traceback.print_exc() if interact.edit and interact.edit.currentView: interact.edit.currentView.AppendToPrompt([]) bWorked = 1 except: if interact.edit and interact.edit.currentView: interact.edit.currentView.EnsureNoPrompt() traceback.print_exc() if interact.edit and interact.edit.currentView: interact.edit.currentView.AppendToPrompt([]) if debuggingType == RS_DEBUGGER_PM: debugger.pm() del __main__.__file__ sys.argv = oldArgv if insertedPath0: del sys.path[0] else: sys.path[0] = oldPath0 f.close() if bWorked: win32ui.SetStatusText("Script '%s' returned exit code %s" % (script, exitCode)) else: win32ui.SetStatusText("Exception raised while running script %s" % base) try: sys.stdout.flush() except AttributeError: pass win32ui.DoWaitCursor(0)