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 RecreateWindow(self): try: dockbar = win32ui.GetMainFrame().GetControlBar( ID_DOCKED_INTERACTIVE_CONTROLBAR) win32ui.GetMainFrame().ShowControlBar(dockbar, 1, 1) except win32ui.error: CreateDockedInteractiveWindow()
def DockablePathBrowser(): import pywin.docking.DockingBar bar = pywin.docking.DockingBar.DockingBar() bar.CreateWindow(win32ui.GetMainFrame(), DockableBrowserCreator, "Path Browser", 0x8e0a) bar.SetBarStyle( bar.GetBarStyle()|afxres.CBRS_TOOLTIPS|afxres.CBRS_FLYBY|afxres.CBRS_SIZE_DYNAMIC) bar.EnableDocking(afxres.CBRS_ALIGN_ANY) win32ui.GetMainFrame().DockControlBar(bar)
def GUIAboutToFinishInteract(self): """Called as the GUI is about to finish any interaction with the user Returns non zero if we are allowed to stop interacting""" if self.oldForeground is not None: try: win32ui.GetMainFrame().EnableWindow(self.oldFrameEnableState) self.oldForeground.EnableWindow(1) except win32ui.error: # old window may be dead. pass # self.oldForeground.SetForegroundWindow() - fails?? if not self.inForcedGUI: return 1 # Never a problem, and nothing else to do. # If we are running a forced GUI, we may never get an opportunity # to interact again. Therefore we perform a "SaveAll", to makesure that # any documents are saved before leaving. for template in win32ui.GetApp().GetDocTemplateList(): for doc in template.GetDocumentList(): if not doc.SaveModified(): return 0 # All documents saved - now hide the app and debugger. if self.get_option(OPT_HIDE): frame = win32ui.GetMainFrame() frame.ShowWindow(win32con.SW_HIDE) return 1
def setInitParams(self, paramstr): if paramstr is None: paramstr = win32ui.GetProfileVal("Pychecker", "Params", '\t\t\t1\t0\t0') params = paramstr.split('\t') if len(params) < 3: params = params + ['']*(3-len(params)) if len(params) < 6: params = params + [0]*(6-len(params)) self.dirpattern = params[0] self.filpattern = params[1] self.greppattern = params[2] or '-#1000 --only' self.casesensitive = int(params[3]) self.recurse = int(params[4]) self.verbose = int(params[5]) # setup some reasonable defaults. if not self.dirpattern: try: editor=win32ui.GetMainFrame().MDIGetActive()[0].GetEditorView() self.dirpattern=os.path.abspath(os.path.dirname(editor.GetDocument().GetPathName())) except (AttributeError,win32ui.error): self.dirpattern = os.getcwd() if not self.filpattern: try: editor=win32ui.GetMainFrame().MDIGetActive()[0].GetEditorView() self.filpattern=editor.GetDocument().GetPathName() except AttributeError: self.filpattern = "*.py"
def test(): global bar bar = DockingBar() creator = EditCreator bar.CreateWindow(win32ui.GetMainFrame(), creator, "Coolbar Demo", 0xfffff) # win32ui.GetMainFrame().ShowControlBar(bar, 1, 0) bar.SetBarStyle(bar.GetBarStyle() | afxres.CBRS_TOOLTIPS | afxres.CBRS_FLYBY | afxres.CBRS_SIZE_DYNAMIC) bar.EnableDocking(afxres.CBRS_ALIGN_ANY) win32ui.GetMainFrame().DockControlBar(bar, afxres.AFX_IDW_DOCKBAR_BOTTOM)
def CreateDockedInteractiveWindow(): # Later, the DockingBar should be capable of hosting multiple # children. from pywin.docking.DockingBar import DockingBar bar = DockingBar() creator = InteractiveViewCreator bar.CreateWindow(win32ui.GetMainFrame(), creator, "Interactive Window", ID_DOCKED_INTERACTIVE_CONTROLBAR) bar.SetBarStyle( bar.GetBarStyle()|afxres.CBRS_TOOLTIPS|afxres.CBRS_FLYBY|afxres.CBRS_SIZE_DYNAMIC) bar.EnableDocking(afxres.CBRS_ALIGN_ANY) win32ui.GetMainFrame().DockControlBar(bar, afxres.AFX_IDW_DOCKBAR_BOTTOM)
def CloseInteractiveWindow(): """Close the interactive window, allowing it to be re-created on demand.""" global edit if edit is not None and edit.currentView is not None: if edit.currentView.GetParentFrame() == win32ui.GetMainFrame(): # It is docked, just hide the dock bar. frame = win32ui.GetMainFrame() cb = frame.GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR) frame.ShowControlBar(cb, 0, 1) else: # It is a standard window - destroy the frame/view, allowing the object itself to remain. edit.currentView.GetParentFrame().DestroyWindow()
def OnDestroy(self, msg): newSize = self.GetWindowPlacement()[4] pywin.framework.app.SaveWindowSize("Interactive Window", newSize, "docked") try: if self.GetParentFrame().GetActiveView==self: self.GetParentFrame().SetActiveView(None) except win32ui.error: pass try: if win32ui.GetMainFrame().GetActiveView()==self: win32ui.GetMainFrame().SetActiveView(None) except win32ui.error: pass return DockedInteractiveViewParent.OnDestroy(self, msg)
def ShowInteractiveWindow(): """Shows (or creates if necessary) an interactive window""" if edit is None: CreateInteractiveWindow() else: if edit.NeedRecreateWindow(): edit.RecreateWindow() else: parent = edit.currentView.GetParentFrame() if parent == win32ui.GetMainFrame(): # It is docked. edit.currentView.SetFocus() else: # It is a "normal" window edit.currentView.GetParentFrame().AutoRestore() win32ui.GetMainFrame().MDIActivate(edit.currentView.GetParentFrame())
def Activate(self): # Bring to the foreground. Mainly used when another app starts up, it asks # this one to activate itself, then it terminates. frame = win32ui.GetMainFrame() frame.SetForegroundWindow() if frame.GetWindowPlacement()[1] == win32con.SW_SHOWMINIMIZED: frame.ShowWindow(win32con.SW_RESTORE)
def OnDebuggerBar(self, id, code): name = IdToBarNames.get(id)[0] d = self._GetDebugger() if d is not None and name is not None: bar = d.GetDebuggerBar(name) newState = not bar.IsWindowVisible() win32ui.GetMainFrame().ShowControlBar(bar, newState, 1)
def HandleOutput(self, message): # debug("QueueOutput on thread %d, flags %d with '%s'...\n" % (win32api.GetCurrentThreadId(), self.writeQueueing, message )) self.outputQueue.put(message) if win32api.GetCurrentThreadId() != self.mainThreadId: pass # debug("not my thread - ignoring queue options!\n") elif self.writeQueueing == flags.WQ_LINE: pos = string.rfind(message, '\n') if pos >= 0: # debug("Line queueing - forcing flush\n") self.QueueFlush() return elif self.writeQueueing == flags.WQ_NONE: # debug("WQ_NONE - flushing!\n") self.QueueFlush() return # Let our idle handler get it - wake it up try: win32ui.GetMainFrame().PostMessage( win32con.WM_USER) # Kick main thread off. except win32ui.error: # This can happen as the app is shutting down, so we send it to the C++ debugger win32api.OutputDebugString(message)
def copy(args): """copy src [src ...], dest Copy files to/from the CE device """ bRecurse = bVerbose = 0 bMaintainDir = 1 try: opts, args = getopt.getopt(args, "rv") except getopt.error as details: raise InvalidUsage(details) for o, v in opts: if o == "-r": bRecuse = 1 elif o == '-v': bVerbose = 1 if len(args) < 2: raise InvalidUsage("Must specify a source and destination") src = args[:-1] dest = args[-1] # See if WCE: leading anywhere indicates a direction. if string.find(src[0], "WCE:") == 0: bToDevice = 0 elif string.find(dest, "WCE:") == 0: bToDevice = 1 else: # Assume copy to device. bToDevice = 1 if not isdir(dest, not bToDevice): print("%s does not indicate a directory") files = [] # List of FQ (from_name, to_name) num_files = 0 num_bytes = 0 dialog = FileCopyProgressDialog("Copying files") dialog.CreateWindow(win32ui.GetMainFrame()) if bToDevice: for spec in src: new = BuildFileList(spec, 1, bRecurse, _copyfilter, bMaintainDir) if not new: print("Warning: '%s' did not match any files" % (spec)) files = files + new for full_src, src_info, dest_info in files: dest_name = os.path.join(dest, dest_info) size = src_info[5] print("Size=", size) if bVerbose: print(full_src, "->", dest_name, "- ", end=' ') dialog.SetText(dest_name) dialog.Set(0, size / 1024) bytes = CopyFileToCe(full_src, dest_name, dialog.CopyProgress) num_bytes = num_bytes + bytes if bVerbose: print(bytes, "bytes") num_files = num_files + 1 dialog.Close() print("%d files copied (%d bytes)" % (num_files, num_bytes))
def SetHelpMenuOtherHelp(mainMenu): """Modifies the main Help Menu to handle all registered help files. mainMenu -- The main menu to modify - usually from docTemplate.GetSharedMenu() """ # Load all help files from the registry. if helpIDMap is None: global helpIDMap helpIDMap = {} cmdID = win32ui.ID_HELP_OTHER excludeList = ['Main Python Documentation', 'Pythonwin Reference'] firstList = ListAllHelpFiles() helpDescs = [] for desc, fname in firstList: if desc not in excludeList: helpIDMap[cmdID] = (desc, fname) win32ui.GetMainFrame().HookCommand(HandleHelpOtherCommand, cmdID) cmdID = cmdID + 1 helpMenu = mainMenu.GetSubMenu(mainMenu.GetMenuItemCount() - 1) # Help menu always last. otherHelpMenuPos = 2 # cant search for ID, as sub-menu has no ID. otherMenu = helpMenu.GetSubMenu(otherHelpMenuPos) while otherMenu.GetMenuItemCount(): otherMenu.DeleteMenu(0, win32con.MF_BYPOSITION) if helpIDMap: for id, (desc, fname) in helpIDMap.items(): otherMenu.AppendMenu(win32con.MF_ENABLED | win32con.MF_STRING, id, desc) else: helpMenu.EnableMenuItem(otherHelpMenuPos, win32con.MF_BYPOSITION | win32con.MF_GRAYED)
def OnInitDialog(self): rc = dialog.Dialog.OnInitDialog(self) self.itemsControl = self.GetDlgItem(win32ui.IDC_LIST1) self.butOK = self.GetDlgItem(win32con.IDOK) self.butCancel = self.GetDlgItem(win32con.IDCANCEL) self.numbersControl = self.GetDlgItem(IDC_NUMBERS) self.numbersControl.EnableWindow(0) w = self.numbersControl.GetStringWidth('22') + 6 itemDetails = (commctrl.LVCFMT_LEFT, w, '', 0) self.numbersControl.InsertColumn(0, itemDetails) self.SelItems = [] self.MoveWindow((0, 0, self.size[0], self.size[1])) self.CenterWindow() size = self.GetWindowRect() self.LayoutControls(size[2] - size[0], size[3] - size[1]) self.FillList() #Select First Item self.itemsControl.SetItemState( 0, commctrl.LVNI_SELECTED + commctrl.LVNI_FOCUSED, 255) #ShowWindow(win32con.SW_RESTORE) try: parent = win32ui.GetMainFrame() except: parent = None if parent: parent.ShowWindow(win32con.SW_RESTORE) return rc
def OnCreateClient(self, createparams, context): borderX = win32api.GetSystemMetrics(win32con.SM_CXFRAME) borderY = win32api.GetSystemMetrics(win32con.SM_CYFRAME) titleY = win32api.GetSystemMetrics( win32con.SM_CYCAPTION) # includes border # try and maintain default window pos, else adjust if cant fit # get the main client window dimensions. mdiClient = win32ui.GetMainFrame().GetWindow(win32con.GW_CHILD) clientWindowRect = mdiClient.ScreenToClient(mdiClient.GetWindowRect()) clientWindowSize = (clientWindowRect[2] - clientWindowRect[0], clientWindowRect[3] - clientWindowRect[1]) left, top, right, bottom = mdiClient.ScreenToClient( self.GetWindowRect()) # width, height=context.doc.size[0], context.doc.size[1] # width = width+borderX*2 # height= height+titleY+borderY*2-1 # if (left+width)>clientWindowSize[0]: # left = clientWindowSize[0] - width # if left<0: # left = 0 # width = clientWindowSize[0] # if (top+height)>clientWindowSize[1]: # top = clientWindowSize[1] - height # if top<0: # top = 0 # height = clientWindowSize[1] # self.frame.MoveWindow((left, top, left+width, top+height),0) window.MDIChildWnd.OnCreateClient(self, createparams, context) return 1
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 Boot(what=0): # Locate the GRiNSRes.dll file. This is presumably in the same directory as # the extensionmodules, or if frozen, in the main directory # This call allows Pythonwin to automatically find resources in it. import win32ui dllPath = os.path.split(win32ui.__file__)[0] try: global resdll resdll = win32ui.LoadLibrary(os.path.join(dllPath, "GRiNSRes.dll")) resdll.AttachToMFC() except win32ui.error: win32ui.MessageBox( "The application resource DLL 'GRiNSRes.dll' can not be located\r\n\r\nPlease correct this problem, and restart the application" ) # For now just continue!?!?! # run the given cmif file try: if what == PLAYER: import grins elif what == SUBSYSTEM: exec 'import %s\n' % subsystemModuleName else: import cmifed except SystemExit, rc: win32ui.GetMainFrame().PostMessage(WM_CLOSE)
def GetSimpleInput(prompt, defValue='', title=None): """ displays a dialog, and returns a string, or None if cancelled. args prompt, defValue='', title=main frames title """ # uses a simple dialog to return a string object. if title is None: title = win32ui.GetMainFrame().GetWindowText() # 2to3 insists on converting 'Dialog.__init__' to 'tkinter.dialog...' DlgBaseClass = Dialog class DlgSimpleInput(DlgBaseClass): def __init__(self, prompt, defValue, title): self.title = title DlgBaseClass.__init__(self, win32ui.IDD_SIMPLE_INPUT) self.AddDDX(win32ui.IDC_EDIT1, 'result') self.AddDDX(win32ui.IDC_PROMPT1, 'prompt') self._obj_.data['result'] = defValue self._obj_.data['prompt'] = prompt def OnInitDialog(self): self.SetWindowText(self.title) return DlgBaseClass.OnInitDialog(self) dlg = DlgSimpleInput(prompt, defValue, title) if dlg.DoModal() != win32con.IDOK: return None return dlg['result']
def TakeDefaultAction(self): fname, ctx = self.myobject if ctx: cmd = win32con.HELP_CONTEXT else: cmd = win32con.HELP_FINDER win32api.WinHelp(win32ui.GetMainFrame().GetSafeHwnd(), fname, cmd, ctx)
def close(self, frameShutdown=0): # abortClose indicates if we have total shutdown # (ie, main window is dieing) if self.pumping: # Can stop pump here, as it only posts a message, and # returns immediately. if not self.StopDebuggerPump(): # User cancelled close. return 0 # NOTE - from this point on the close can not be # stopped - the WM_QUIT message is already in the queue. self.frameShutdown = frameShutdown if not self.inited: return 1 self.inited = 0 SetInteractiveContext(None, None) frame = win32ui.GetMainFrame() # Hide the debuger toolbars (as they wont normally form part of the main toolbar state. for id, klass, float in DebuggerDialogInfos: try: tb = frame.GetControlBar(id) if tb.dialog is not None: # We may never have actually been shown. tb.dialog.SaveState() frame.ShowControlBar(tb, 0, 1) except win32ui.error: pass self._UnshowCurrentLine() self.set_quit() return 1
def GetActiveView(): """Gets the edit control (eg, EditView) with the focus, or None""" try: childFrame, bIsMaximised = win32ui.GetMainFrame().MDIGetActive() return childFrame.GetActiveView() except win32ui.error: return None
def GUIRespondDebuggerData(self): if not self.inited: # GUI not inited - no toolbars etc. return for id, klass, float in DebuggerDialogInfos: cb = win32ui.GetMainFrame().GetControlBar(id).dialog cb.RespondDebuggerData()
def GetActiveFileName(bAutoSave = 1): """Gets the file name for the active frame, saving it if necessary. Returns None if it cant be found, or raises KeyboardInterrupt. """ pathName = None try: active = win32ui.GetMainFrame().GetWindow(win32con.GW_CHILD).GetWindow(win32con.GW_CHILD) doc = active.GetActiveDocument() pathName = doc.GetPathName() if bAutoSave and \ (len(pathName)>0 or \ doc.GetTitle()[:8]=="Untitled" or \ doc.GetTitle()[:6]=="Script"): # if not a special purpose window if doc.IsModified(): try: doc.OnSaveDocument(pathName) pathName = doc.GetPathName() # clear the linecache buffer linecache.clearcache() except win32ui.error: raise KeyboardInterrupt except (win32ui.error, AttributeError): pass if not pathName: return None return pathName
def OpenHelpFile(fileName, helpCmd=None, helpArg=None): "Open a help file, given a full path" # default help arg. win32ui.DoWaitCursor(1) try: if helpCmd is None: helpCmd = win32con.HELP_CONTENTS ext = os.path.splitext(fileName)[1].lower() if ext == ".hlp": win32api.WinHelp(win32ui.GetMainFrame().GetSafeHwnd(), fileName, helpCmd, helpArg) # XXX - using the htmlhelp API wreaks havoc with keyboard shortcuts # so we disable it, forcing ShellExecute, which works fine (but # doesn't close the help file when Pythonwin is closed. # Tom Heller also points out http://www.microsoft.com/mind/0499/faq/faq0499.asp, # which may or may not be related. elif 0 and ext == ".chm": import win32help global htmlhelp_handle helpCmd = html_help_command_translators.get(helpCmd, helpCmd) #frame = win32ui.GetMainFrame().GetSafeHwnd() frame = 0 # Dont want it overlapping ours! if htmlhelp_handle is None: htmlhelp_hwnd, htmlhelp_handle = win32help.HtmlHelp( frame, None, win32help.HH_INITIALIZE) win32help.HtmlHelp(frame, fileName, helpCmd, helpArg) else: # Hope that the extension is registered, and we know what to do! win32api.ShellExecute(0, "open", fileName, None, "", win32con.SW_SHOW) return fileName finally: win32ui.DoWaitCursor(-1)
def SetToolsMenu(menu, menuPos=None): global tools global idPos # todo - check the menu does not already exist. # Create the new menu toolsMenu = win32ui.CreatePopupMenu() # Load from the ini file. items = LoadToolMenuItems() for menuString, cmd in items: tools[idPos] = (menuString, cmd, menuString) toolsMenu.AppendMenu(win32con.MF_ENABLED | win32con.MF_STRING, idPos, menuString) win32ui.GetMainFrame().HookCommand(HandleToolCommand, idPos) idPos = idPos + 1 # Find the correct spot to insert the new tools menu. if menuPos is None: menuPos = menu.GetMenuItemCount() - 2 if menuPos < 0: menuPos = 0 menu.InsertMenu( menuPos, win32con.MF_BYPOSITION | win32con.MF_ENABLED | win32con.MF_STRING | win32con.MF_POPUP, toolsMenu.GetHandle(), '&Tools')
def OnItemRightClick(self, notify_data, extra): # First select the item we right-clicked on. pt = self.ScreenToClient(win32api.GetCursorPos()) flags, hItem, subitem = self.HitTest(pt) if hItem == -1 or commctrl.TVHT_ONITEM & flags == 0: return None self.SetItemState( hItem, commctrl.LVIS_SELECTED, commctrl.LVIS_SELECTED) menu = win32ui.CreatePopupMenu() menu.AppendMenu( win32con.MF_STRING | win32con.MF_ENABLED, 1000, "Edit item") menu.AppendMenu( win32con.MF_STRING | win32con.MF_ENABLED, 1001, "Delete item") dockbar = self.GetParent() if dockbar.IsFloating(): hook_parent = win32ui.GetMainFrame() else: hook_parent = self.GetParentFrame() hook_parent.HookCommand(self.OnEditItem, 1000) hook_parent.HookCommand(self.OnDeleteItem, 1001) # track at mouse position. menu.TrackPopupMenu(win32api.GetCursorPos()) return None
def __init__(self): import win32ui hwnd = win32ui.GetMainFrame().GetSafeHwnd() self._dsound = dsound.CreateDirectSound() self._dsound.SetCooperativeLevel(hwnd, dsound.DSSCL_NORMAL) dsbdesc = dsound.CreateDSBufferDesc() dsbdesc.SetFlags(dsound.DSBCAPS_PRIMARYBUFFER) self._primarysb = self._dsound.CreateSoundBuffer(dsbdesc)
def NeedApp(): import win32ui rc = win32ui.MessageBox(NeedAppMsg % sys.argv[0], "Demos", win32con.MB_YESNO) if rc==win32con.IDYES: try: parent = win32ui.GetMainFrame().GetSafeHwnd() win32api.ShellExecute(parent, None, 'pythonwin.exe', '/app "%s"' % sys.argv[0], None, 1) except win32api.error as details: win32ui.MessageBox("Error executing command - %s" % (details), "Demos")