def on_paint(self, event): self._update_scroll() self.keep_cursor_on_screen() pdc = wx.PaintDC(self) pdc.SetAxisOrientation(True, False) if self.factory.device.buffering: dc = wx.BufferedDC(pdc) if not dc.IsOk(): return else: dc = pdc dc.SetBackgroundMode(wx.SOLID) dc.SetBackground(wx.WHITE_BRUSH) dc.Clear() styler = DCStyler(dc) region = self.GetUpdateRegion() x, y, w, h = region.Box dc.SetClippingRegion(x-1, y-1, w+2, h+2) x, y = self.CalcScrolledPosition((0,0)) layout = self.updater.layout layout.draw(x, y, dc, styler) if wx.Window_FindFocus() is self: layout.draw_cursor(self.index, x, y, dc, defaultstyle) for j1, j2 in self.get_selected(): layout.draw_selection(j1, j2, x, y, dc) styler = None dc = None
def ProcessEvent(self, event): if not hasattr(self, "_pyCrust") or not self._pyCrust: return wx.lib.docview.View.ProcessEvent(self, event) stcControl = wx.Window_FindFocus() if not isinstance(stcControl, wx.stc.StyledTextCtrl): return wx.lib.docview.View.ProcessEvent(self, event) id = event.GetId() if id == wx.ID_UNDO: stcControl.Undo() return True elif id == wx.ID_REDO: stcControl.Redo() return True elif id == wx.ID_CUT: stcControl.Cut() return True elif id == wx.ID_COPY: stcControl.Copy() return True elif id == wx.ID_PASTE: stcControl.Paste() return True elif id == wx.ID_CLEAR: stcControl.Clear() return True elif id == wx.ID_SELECTALL: stcControl.SetSelection(0, -1) return True else: return wx.lib.docview.View.ProcessEvent(self, event)
def ProcessUpdateUIEvent(self, event): if not hasattr(self, "_pyCrust") or not self._pyCrust: return wx.lib.docview.View.ProcessUpdateUIEvent(self, event) stcControl = wx.Window_FindFocus() if not isinstance(stcControl, wx.stc.StyledTextCtrl): return wx.lib.docview.View.ProcessUpdateUIEvent(self, event) id = event.GetId() if id == wx.ID_UNDO: event.Enable(stcControl.CanUndo()) return True elif id == wx.ID_REDO: event.Enable(stcControl.CanRedo()) return True elif id == wx.ID_CUT: event.Enable(stcControl.CanCut()) return True elif id == wx.ID_COPY: event.Enable(stcControl.CanCopy()) return True elif id == wx.ID_PASTE: event.Enable(stcControl.CanPaste()) return True elif id == wx.ID_CLEAR: event.Enable( True ) # wxBug: should be stcControl.CanCut()) but disabling clear item means del key doesn't work in control as expected return True elif id == wx.ID_SELECTALL: event.Enable(stcControl.GetTextLength() > 0) return True else: return wx.lib.docview.View.ProcessUpdateUIEvent(self, event)
def getFocusBlock(theClass): focusWindow = wx.Window_FindFocus() while (focusWindow): try: return focusWindow.blockItem except AttributeError: focusWindow = focusWindow.GetParent() return Globals.views[0]
def testFocus(self): if '__WXMAC__' not in wx.PlatformInfo and ( '__WXMSW__' not in wx.PlatformInfo or sys.version_info < (2, 5)): wx.Yield() # pragma: no cover # pylint: disable-msg=W0212 self.assertEqual(self.editor._interior[0]._subjectEntry, wx.Window_FindFocus())
def closeFrame(self, event): win = wx.Window_FindFocus() if win is not None: win.Disconnect(-1, -1, wx.wxEVT_KILL_FOCUS) if self._closeHandler is not None: self._closeHandler(event) else: event.Skip()
def OnSetFocus(self, event): # called by EVT_SET_FOCUS. sets bgcolor to match focus w = wx.Window_FindFocus() if w: curr_id = w.GetId() if curr_id == self.cal_id: self.Focus('cal') elif curr_id == self.lc_id: self.Focus('lc') event.Skip()
def onRunSelectedScriptEvent(self, event): # Triggered from "Tests | Run an Item" item = self._SelectedItemScript() if item: # in case the user was just editing the script, # ask the focus to finish changes, if it can focusedWidget = wx.Window_FindFocus() try: focusedWidget.blockItem.finishSelectionChanges() except AttributeError: pass # run the script from the item's body CPIAScript.RunScript(item.bodyString, self.itsView)
def _isFocused(self, control): """ Return True if the control is in the cluster of widgets within a single block. """ focus = wx.Window_FindFocus() while control != None: if control == focus: return True if hasattr(control, 'blockItem'): break control = control.GetParent() return False
def emulate_typing(string, ctrlFlag=False, altFlag=False, shiftFlag=False): """ emulate_typing the string into the current focused widget """ success = True def set_event_info(event): # setup event info for a keypress event event.m_keyCode = keyCode event.m_rawCode = keyCode event.m_shiftDown = char.isupper() or shiftFlag event.m_controlDown = event.m_metaDown = ctrlFlag event.m_altDown = altFlag event.SetEventObject(widget) # for each key, check for specials, then try several approaches for char in string: keyCode = ord(char) if keyCode == wx.WXK_RETURN: emulate_return() elif keyCode == wx.WXK_TAB: emulate_tab(shiftFlag=shiftFlag) else: # in case the focus has changed, get the new focused widget widget = wx.Window_FindFocus() if widget is None: success = False else: # try calling any bound key handler keyPress = wx.KeyEvent(wx.wxEVT_KEY_DOWN) set_event_info(keyPress) downWorked = widget.ProcessEvent(keyPress) keyUp = wx.KeyEvent(wx.wxEVT_KEY_UP) set_event_info(keyUp) upWorked = widget.ProcessEvent(keyUp) if not (downWorked or upWorked): # key handler worked? # try calling EmulateKeyPress emulateMethod = getattr(widget, 'EmulateKeyPress', lambda k: False) if (wx.Platform == "__WXMSW__" or not emulateMethod(keyPress)): # emulate worked? # try calling WriteText writeMethod = getattr(widget, 'WriteText', None) if writeMethod: writeMethod(char) else: success = False # remember we had a failure if success: wx.GetApp().Yield(True) return success
def editor_has_focus(self): """indicates whether the editor window has the focus **INPUTS** *none* **OUTPUTS** *BOOL* -- True if editor window has the focus """ return 1 current = wx.Window_FindFocus() if current and current.GetId() == self.editor_window().GetId(): return 1 return 0
def OnIdle(self, event): """ Adding a handler for catching a set focus event doesn't catch every change to the focus. It's difficult to preprocess every event so we check for focus changes in OnIdle. Also call UpdateUI when focus changes """ def updateOnIdle(): """ This function is used to generate notifications of items that were changed in the current (repository) view since the last time through the idle loop """ the_view = self.repository.view # cache the view for performance the_view.refresh() # pickup changes from other threads changes = [] def mapChangesCallable(item, version, status, literals, references): """ closure to be passed to mapChanges that will produce a list of changed items in the same format needed by repository.query.Query.queryCallback """ changes.append((item.itsUUID, "changed", {})) # call mapChanges with flag that prevents seeing changes we've seen before the_view.mapChanges(mapChangesCallable, True) # grab the list of subscribed callbacks and notify them. if changes: for i in self.repository._notifications: i(the_view, changes, "changeonly") focus = wx.Window_FindFocus() if self.focus != focus: self.focus = focus self.needsUpdateUI = True try: updateOnIdle() except MergeError, e: if e.getReasonCode() == MergeError.BUG: logger.warning("Changes cancelled due to merge error: %s", e) self.repository.view.cancel() self.needsUpdateUI = True else: raise
def OnActivate(self, event): if self.closing: return current = wx.Window_FindFocus() if event.GetActive(): # window is being activated # if activated by mouse, some control of this application may already # be focused, and we don't want to override that, but otherwise # we want to set the focus back to the control which had it last if self.most_recent_focus and not current: self.most_recent_focus.SetFocus() self.on_activate(1) else: self.most_recent_focus = current self.on_activate(0)
def Type(string, ctrlFlag=False, altFlag=False, shiftFlag=False): """ Types the string into the current focused widget, returns True if successful """ stringSuccess = True for char in string: try: keyPressMethod = _wx.Window_FindFocus().EmulateKeyPress except AttributeError: return False else: keyCode = ord(char) # returns ASCII value of char keyPress = _wx.KeyEvent(_wx.wxEVT_KEY_DOWN) keyPress.m_keyCode = keyCode keyPress.m_shiftDown = char.isupper() or shiftFlag keyPress.m_controlDown = keyPress.m_metaDown = ctrlFlag keyPress.m_altDown = altFlag charSuccess = keyPressMethod(keyPress) stringSuccess = stringSuccess and charSuccess return stringSuccess
def emulate_return(block=None): """ Simulates a return-key event in the given block """ try: if block: widget = block.widget else: widget = wx.Window_FindFocus() except AttributeError: return False else: # return-key down ret_d = wx.KeyEvent(wx.wxEVT_KEY_DOWN) ret_d.m_keyCode = wx.WXK_RETURN ret_d.SetEventObject(widget) # return-key up ret_up = wx.KeyEvent(wx.wxEVT_KEY_UP) ret_up.m_keyCode = wx.WXK_RETURN ret_up.SetEventObject(widget) # text updated event tu = wx.CommandEvent(wx.wxEVT_COMMAND_TEXT_UPDATED) tu.SetEventObject(widget) # kill focus event kf = wx.FocusEvent(wx.wxEVT_KILL_FOCUS) kf.SetEventObject(widget) # Text enter ent = wx.CommandEvent(wx.wxEVT_COMMAND_TEXT_ENTER) ent.SetEventObject(widget) #work around for mac bug if widget is not None: widget.ProcessEvent(tu) #for start/end time and location field #work around for canvasItem if widget is not None: widget.ProcessEvent(kf) #for canvasItem title # events processing widget.ProcessEvent(ret_d) widget.ProcessEvent(ret_up) # Give Yield & Idle to the App idle() return True
def OnUseAA(self, event): win = wx.Window_FindFocus() win.SetUseAntiAliasing(event.IsChecked())
def OnWrap(self, event): win = wx.Window_FindFocus() win.SetWrapMode(event.IsChecked())
def OnCallTipsShow(self, event): win = wx.Window_FindFocus() win.autoCallTip = event.IsChecked()
def OnAutoCompleteDouble(self, event): win = wx.Window_FindFocus() win.autoCompleteIncludeDouble = event.IsChecked()
def OnAutoCompleteMagic(self, event): win = wx.Window_FindFocus() win.autoCompleteIncludeMagic = event.IsChecked()
def OnAutoCompleteShow(self, event): win = wx.Window_FindFocus() win.autoComplete = event.IsChecked()
def OnPastePlus(self, event): win = wx.Window_FindFocus() win.PasteAndRun()
def OnPaste(self, event): win = wx.Window_FindFocus() win.Paste()
def FilterEvent (self, event): def widgetToName (widget): """ Given a widget, returns a name that can be used to find the same widget during playback. """ if isinstance (widget, wx.Button): name = {wx.ID_OK: "__wxID_OK__", wx.ID_CANCEL: "__wxID_CANCEL__", wx.ID_YES: "__wxID_YES__", wx.ID_NO: "__wxID_NO__"}.get (widget.GetId(), None) if name is not None: return name if isinstance (widget, wx.Window): return widget.GetName() elif widget is None: return "__none__" else: return "__block__" + widget.blockItem.blockName def writeComment (): if eventType in commentTheseEventTypes: if eventType == "wx.EVT_CHAR": if self.typingSequence is None: self.typingSequence = unicode (unichr (event.UnicodeKey)) self.startTypingLineNumber = self.lineNumber else: self.typingSequence += unichr (event.UnicodeKey) else: if self.typingSequence is not None: self.comments += " Type %s (%d)%s" % \ (self.valueToString (self.typingSequence), self.startTypingLineNumber, os.linesep) self.typingSequence = None if eventType == "wx.EVT_MENU": widget = associatedBlock.widget if isinstance (widget, wx.MenuItem): # Find the menu name using wx.Widgets menu APIs that are carefully #optimized for maximum pain and inefficiency. Blocks eliminate the #wxWidgets non-orthoganality, but they are going away so do it the hard way. menuName = widget.GetLabel() menu = widget.GetMenu() while True: widget = menu menu = widget.GetParent() if menu is not None: for item in menu.GetMenuItems(): if item.IsSubMenu() and item.GetSubMenu() is widget: menuName = menu.GetLabelText (item.GetId()) + " > " + menuName break else: assert False, "Didn't find expected sub menu in menu item" else: break menuBar = widget.GetMenuBar() if menuBar is None: menuName = "Context Menu" + " > " + menuName else: for index in xrange (menuBar.GetMenuCount()): if menuBar.GetMenu (index) is widget: menuName = menuBar.GetLabelTop (index) + " > " + menuName break else: assert False, "Didn't find expected menu in menuBar" self.comments += " Choose menu '%s' (%d)%s" % \ (menuName, self.lineNumber, os.linesep) elif isinstance (widget, wx.ToolBarTool): toolBar = widget.GetToolBar() toolIndex = toolBar.GetToolPos (widget.GetId()) self.comments += " Choose toolbar button '%s' (%d)%s" % \ (widget.GetLabel(), self.lineNumber, os.linesep) elif eventType == "wx.EVT_LEFT_DOWN": self.comments += " Left Mouse Down in %s (%d)%s" % (sentToName, self.lineNumber, os.linesep) elif eventType == "wx.EVT_RIGHT_DOWN": self.comments += " Right Mouse Down in %s (%d)%s" % (sentToName, self.lineNumber, os.linesep) elif eventType == "wx.EVT_LEFT_DCLICK": self.comments += " Left Mouse Double Click in %s (%d)%s" % (sentToName, self.lineNumber, os.linesep) def lookupMenuAccelerator (event): """ wxWidgets has this functionality but doesn't expose it correctly """ def getNextMenuItem (menu): for menuItem in menu.GetMenuItems(): if menuItem.IsSubMenu(): for subMenuItem in getNextMenuItem (menuItem.GetSubMenu()): yield subMenuItem yield menuItem flags = 0 keyCode = event.m_keyCode if event.m_controlDown: flags |= wx.ACCEL_CTRL keyCode += 64 # convert to non control character if event.m_altDown: flags |= wx.ACCEL_ALT if event.m_shiftDown: flags |= wx.ACCEL_SHIFT if flags != 0: menuBar = wx.GetApp().mainFrame.GetMenuBar() for index in xrange (menuBar.GetMenuCount()): for menuItem in getNextMenuItem (menuBar.GetMenu (index)): accel = menuItem.GetAccel() if (accel is not None and accel.GetKeyCode() == keyCode and accel.GetFlags() == flags): return menuItem return None if event.__class__ in wxEventClasseInfo: eventType = wxEventTypeReverseMapping.get (event.GetEventType(), None) if eventType is not None: # Save dictionary of properties of the event values = [] if eventType == "wx.EVT_CHAR": # Translate command keys to menu commands menuItem = lookupMenuAccelerator (event) if menuItem is not None: id = menuItem.GetId() senttoWidget = event.GetEventObject() event = wx.CommandEvent (commandType = wx.EVT_MENU.evtType[0], winid = id) eventType = "wx.EVT_MENU" event.SetEventObject (senttoWidget) # Special feature when using a command key to paste, we keep track of the # clipboard so that playing back uses the clipboard that was recorded if id == wx.ID_PASTE: data = wx.TextDataObject() if wx.TheClipboard.Open(): if wx.TheClipboard.GetData (data): values.append ("'clipboard':" + self.valueToString (data.GetText())) wx.TheClipboard.Close() sentToWidget = event.GetEventObject() # Ignore events on widgets that are being deleted. Also ignore if (not getattr (sentToWidget, "widgetIsBeingDeleted", False) and # Ignore focus events on generic buttons since not all platforms can set the focus to them. not (eventType == "wx.EVT_SET_FOCUS" and isinstance (sentToWidget, GenButton))): # Find the name of the block that the event was sent to # Translate events in wx.Grid's GridWindow to wx.Grid sentToName = widgetToName (sentToWidget) hint = getattr(event.GetEventObject(), 'blockItem', None) associatedBlock = self.findBlockById(event.GetId(), hint) if associatedBlock is not None: associatedBlockName = associatedBlock.blockName values.append ("'associatedBlock':" + self.valueToString (associatedBlockName)) else: associatedBlockName = "" # Don't record the stop recording event if associatedBlockName not in ignoreEventsToAssociatedBlocks: values.append ("'eventType':" + eventType) values.append ("'sentTo':" + self.valueToString (sentToName)) # Track selection of choice controls so we can set them on playback if (eventType == "wx.EVT_CHOICE" or eventType == "wx.EVT_LISTBOX"): values.append ("'selectedItem':" + self.valueToString (sentToWidget.GetSelection())) # Use mouse up events in text controls to set selection during playback if (eventType == 'wx.EVT_LEFT_UP' and isinstance (sentToWidget, wx.TextCtrl)): (start, end) = sentToWidget.GetSelection() # On windows GetValue uses "\n" for end of lines, but the widget stores # "\n\r" for end of lines and SetSelection uses offsets that include # the extra "\r" characters if wx.Platform == "__WXMSW__": value = sentToWidget.GetValue() value = value.replace ('\n', '\n\r') start = start - value.count ('\n', 0, start) end = end - value.count ('\n',0, end) values.append ("'selectionRange': (" + self.valueToString (start) + "," + self.valueToString (end) + ')') focusWindow = wx.Window_FindFocus() # Record the focus for verification on playback only for certain # types of events if (eventType in checkFocusEventTypes): if not hasattr (self, "lastFocus"): self.lastFocus = focusWindow if self.lastFocus != focusWindow: # Keep track of the focus window changes self.lastFocus = focusWindow # Don't verify focus changes when they are GenButtons, which some platforms # can't set the focus to. if not isinstance (focusWindow, GenButton): values.append ("'recordedFocusWindow':" + self.valueToString (widgetToName(focusWindow))) values.append ("'recordedFocusWindowClass':" + getClassName (focusWindow.__class__)) # Record the state of the last widget so we can check that the state is the same # afer the event is played back. Don't record if # - we don't have a valid lastSentToWidget. # - we've got a command key since playing back command key events doesn't update # the widget's value. # - we have a type or widget in our ignore list. lastSentToWidget = getattr (self, "lastSentToWidget", None) if (lastSentToWidget is not None and not isinstance (lastSentToWidget, wx._core._wxPyDeadObject)): method = getattr (lastSentToWidget, "GetValue", None) if (method is not None and not (eventType == "wx.EVT_CHAR" and event.m_controlDown) and not eventType in ignoreValueCheckEventTypes and not lastSentToWidget.GetName() in ignoreValueCheckForWidgets): values.append ("'lastWidgetValue':" + self.valueToString (method())) # Keep track of the last widget so we can record the change in Value and # verify it during playbeck. self.lastSentToWidget = sentToWidget properties = "{" + ", ".join (values) + "}" values = [] classInfo = wxEventClasseInfo [event.__class__] for (attribute, defaultValue) in zip (classInfo["attributes"], classInfo["defaultValues"]): value = getattr (event, attribute) if value != defaultValue: values.append ("'%s':%s" % (attribute, self.valueToString (value))) attributes = "{" + ", ".join (values) + "}" # We only record the last SetFocus event in a sequence of SetFocus events # to avoid sending focus to items that no longer exist. thisEventIsSetFocus = eventType == "wx.EVT_SET_FOCUS" if self.lastEventWasSetFocus and thisEventIsSetFocus: self.commands = self.commands [:self.lastOffset] self.lineNumber -= 1 else: self.lastOffset = len(self.commands) self.lastEventWasSetFocus = thisEventIsSetFocus self.commands += (" (%s, %s, %s, %s),%s" % (self.lineNumber, classInfo ["className"], properties , attributes, os.linesep)) writeComment() self.lineNumber += 1
def OnUpdateMenu(self, event): """Update menu items based on current status and context.""" win = wx.Window_FindFocus() id = event.GetId() event.Enable(True) try: #seb 20051102 # if id == ID_NEW: # event.Enable(hasattr(self, 'bufferNew')) # elif id == ID_OPEN: # event.Enable(hasattr(self, 'bufferOpen')) # elif id == ID_REVERT: # event.Enable(hasattr(self, 'bufferRevert') # and self.hasBuffer()) # elif id == ID_CLOSE: # event.Enable(hasattr(self, 'bufferClose') # and self.hasBuffer()) # elif id == ID_SAVE: # event.Enable(hasattr(self, 'bufferSave') # and self.bufferHasChanged()) # elif id == ID_SAVEAS: # event.Enable(hasattr(self, 'bufferSaveAs') # and self.hasBuffer()) # elif id == ID_NAMESPACE: # event.Enable(hasattr(self, 'updateNamespace') # and self.hasBuffer()) # elif id == ID_PRINT: # event.Enable(hasattr(self, 'bufferPrint') # and self.hasBuffer()) if 0: pass elif id == ID_UNDO: event.Enable(win.CanUndo()) elif id == ID_REDO: event.Enable(win.CanRedo()) # elif id == ID_CUT: # event.Enable(win.CanCut()) elif id == ID_COPY: event.Enable(win.CanCopy()) elif id == ID_COPY_PLUS: event.Enable(win.CanCopy() and hasattr(win, 'CopyWithPrompts')) elif id == ID_PASTE: event.Enable(win.CanPaste()) elif id == ID_PASTE_PLUS: event.Enable(win.CanPaste() and hasattr(win, 'PasteAndRun')) # elif id == ID_CLEAR: # event.Enable(win.CanCut()) # elif id == ID_SELECTALL: # event.Enable(hasattr(win, 'SelectAll')) elif id == ID_AUTOCOMP_SHOW: event.Check(win.autoComplete) elif id == ID_AUTOCOMP_MAGIC: event.Check(win.autoCompleteIncludeMagic) elif id == ID_AUTOCOMP_SINGLE: event.Check(win.autoCompleteIncludeSingle) elif id == ID_AUTOCOMP_DOUBLE: event.Check(win.autoCompleteIncludeDouble) elif id == ID_CALLTIPS_SHOW: event.Check(win.autoCallTip) elif id == ID_WRAP: event.Check(win.GetWrapMode()) elif id == ID_USEAA: event.Check(win.GetUseAntiAliasing()) elif id == ID_OSXBUG: from Priithon.viewer import bugXiGraphics event.Check(bugXiGraphics) else: event.Enable(False) except AttributeError: # This menu option is not supported in the current context. event.Enable(False)
def emulate_tab(shiftFlag=False): if shiftFlag: flags = wx.NavigationKeyEvent.IsBackward else: flags = wx.NavigationKeyEvent.IsForward wx.Window_FindFocus().Navigate(flags)
def testFocus(self): # pylint: disable=W0212 self.assertNotEqual(self.editor._interior[0]._subjectEntry, wx.Window_FindFocus())
def OnCopy(self, event): win = wx.Window_FindFocus() win.Copy()
def OnRedo(self, event): win = wx.Window_FindFocus() win.Redo()
def OnCopyPlus(self, event): win = wx.Window_FindFocus() win.CopyWithPrompts()