def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. module.addHeaderCode('#include <wx/cmdproc.h>') c = module.find('wxCommand') assert isinstance(c, etgtools.ClassDef) c.addPrivateCopyCtor() c = module.find('wxCommandProcessor') c.addPrivateCopyCtor() c.find('Submit.command').transfer = True c.find('Store.command').transfer = True module.addItem( tools.wxListWrapperTemplate('wxList', 'wxCommand', module, fakeListClassName='wxCommandList')) c.find('GetCommands').type = 'wxCommandList&' c.find('GetCommands').noCopy = True #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. c = module.find('wxFileHistory') assert isinstance(c, etgtools.ClassDef) c.addPrivateCopyCtor() # There is already a wxMenuList class so we have to name this one something else. module.addItem( tools.wxListWrapperTemplate('wxList', 'wxMenu', module, fakeListClassName='wxFileHistoryMenuList')) c.find('GetMenus').type = 'const wxFileHistoryMenuList&' c.find('GetMenus').noCopy = True #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. c = module.find('wxWindow') assert isinstance(c, etgtools.ClassDef) module.addGlobalStr('wxPanelNameStr', c) # First we need to let the wrapper generator know about wxWindowBase since # AddChild and RemoveChild need to use that type in order to be virtualized. winbase = ClassDef(name='wxWindowBase', bases=['wxEvtHandler'], abstract=True, items=[MethodDef(name='AddChild', isVirtual=True, type='void', protection='public', items=[ParamDef(name='child', type='wxWindowBase*')]), MethodDef(name='RemoveChild', isVirtual=True, type='void', protection='public', items=[ParamDef(name='child', type='wxWindowBase*')]) ]) module.insertItemBefore(c, winbase) # Now change the base class of wxWindow c.bases = ['wxWindowBase'] # And fix the arg types we get from Doxy c.find('AddChild.child').type = 'wxWindowBase*' c.find('RemoveChild.child').type = 'wxWindowBase*' # We now return you to our regularly scheduled programming... c.includeCppCode('src/window_ex.cpp') # ignore some overloads that will be ambiguous afer wrapping c.find('GetChildren').overloads = [] c.find('GetChildren').noCopy = True for name in ['GetVirtualSize', 'GetPosition', 'GetScreenPosition']: c.find(name).findOverload('int *').ignore() # Fix ClientToScreen/ScreenToClient int * overloads for name in ['ClientToScreen', 'ScreenToClient']: c.find(name).findOverload('int *').find('x').inOut = True c.find(name).findOverload('int *').find('y').inOut = True # Like the above, but these also need to transplant the docs from the # ignored item to the non-ignored overload. for name in ['GetClientSize', 'GetSize']: c.find(name).findOverload('int *').ignore() item = c.find(name) ov = item.overloads[0] item.briefDoc = ov.briefDoc item.detailedDoc = ov.detailedDoc # Release the GIL for potentially blocking or long-running functions c.find('PopupMenu').releaseGIL() c.find('ProcessEvent').releaseGIL() c.find('ProcessWindowEvent').releaseGIL() c.find('ProcessWindowEventLocally').releaseGIL() # Add a couple wrapper functions for symmetry with the getters of the same name c.addPyMethod('SetRect', '(self, rect)', 'return self.SetSize(rect)') c.addPyProperty('Rect GetRect SetRect') c.addPyMethod('SetClientRect', '(self, rect)', 'return self.SetClientSize(rect)') c.addPyProperty('ClientRect GetClientRect SetClientRect') m = c.find('GetTextExtent').findOverload('int *') m.pyName = 'GetFullTextExtent' m.find('w').out = True m.find('h').out = True m.find('descent').out = True m.find('externalLeading').out = True c.find('GetHandle').type = 'wxUIntPtr*' c.find('GetHandle').setCppCode("return new wxUIntPtr(wxPyGetWinHandle(self));") c.addCppMethod('void*', 'GetGtkWidget', '()', """\ #ifdef __WXGTK__ return (void*)self->GetHandle(); #else return NULL; #endif """) c.addCppMethod('void', 'AssociateHandle', '(long handle)', doc="Associate the window with a new native handle", body="self->AssociateHandle((WXWidget)handle);") c.addCppMethod('void', 'DissociateHandle', '()', doc="Dissociate the current native handle from the window", body="self->DissociateHandle();") # Add some new methods c.addCppMethod('wxWindow*', 'GetTopLevelParent', '()', 'return wxGetTopLevelParent(self);', briefDoc="Returns the first ancestor of this window which is a top-level window.") c.addCppMethod('bool', 'MacIsWindowScrollbar', '(const wxWindow* sb)', """\ #ifdef __WXMAC__ return self->MacIsWindowScrollbar(sb); #else return false; #endif """, pyArgsString="(sb)", briefDoc="Is the given widget one of this window's built-in scrollbars? Only applicable on Mac.") c.addCppMethod('void', 'SetDimensions', '(int x, int y, int width, int height, int sizeFlags=wxSIZE_AUTO)', pyArgsString="(x, y, width, height, sizeFlags=SIZE_AUTO)", body="""\ self->SetSize(x, y, width, height, sizeFlags); """) c.addPyCode("Window.SetDimensions = wx.deprecated(Window.SetDimensions, 'Use SetSize instead.')") # Make the Register/UnregisterHotKey functions be available on Windows, # and empty stubs otherwise c.find('RegisterHotKey').setCppCode("""\ #if wxUSE_HOTKEY return self->RegisterHotKey(hotkeyId, modifiers, virtualKeyCode); #else return false; #endif """) c.find('UnregisterHotKey').setCppCode("""\ #if wxUSE_HOTKEY return self->UnregisterHotKey(hotkeyId); #else return false; #endif """) c.find('RegisterHotKey').isVirtual = False c.find('UnregisterHotKey').isVirtual = False c.find('SetDoubleBuffered').setCppCode("""\ #if defined(__WXGTK20__) || defined(__WXGTK3__) || defined(__WXMSW__) self->SetDoubleBuffered(on); #endif """) c.addPyMethod('__nonzero__', '(self)', doc="Can be used to test if the C++ part of the window still exists, with \n" "code like this::\n\n" " if theWindow:\n" " doSomething()", body="""\ import wx.siplib return not wx.siplib.isdeleted(self) """) c.addPyCode('Window.__bool__ = Window.__nonzero__') # For Python 3 c.addPyMethod('DestroyLater', '(self)', doc="""\ Schedules the window to be destroyed in the near future. This should be used whenever Destroy could happen too soon, such as when there may still be events for this window or its children waiting in the event queue. """, body="""\ self.Hide() wx.GetApp().ScheduleForDestruction(self) """) # MSW only. Do we want them wrapped? c.find('GetAccessible').ignore() c.find('SetAccessible').ignore() # Make some of the protected methods visible and overridable from Python c.find('SendDestroyEvent').ignore(False) c.find('Destroy').transferThis=True c.addPyMethod('PostCreate', '(self, pre)', 'pass', deprecated='PostCreate is no longer necessary.') # transfer ownership of these parameters to the C++ object c.find('SetCaret.caret').transfer = True c.find('SetToolTip.tip').transfer = True c.find('SetDropTarget.target').transfer = True c.find('SetConstraints.constraints').transfer = True c.find('SetSizer.sizer').transfer = True c.find('SetSizerAndFit.sizer').transfer = True # Define some properties using the getter and setter methods c.addProperty('AcceleratorTable GetAcceleratorTable SetAcceleratorTable') c.addProperty('AutoLayout GetAutoLayout SetAutoLayout') c.addProperty('BackgroundColour GetBackgroundColour SetBackgroundColour') c.addProperty('BackgroundStyle GetBackgroundStyle SetBackgroundStyle') c.addProperty('EffectiveMinSize GetEffectiveMinSize') c.addProperty('BestSize GetBestSize') c.addProperty('BestVirtualSize GetBestVirtualSize') c.addProperty('Border GetBorder') c.addProperty('Caret GetCaret SetCaret') c.addProperty('CharHeight GetCharHeight') c.addProperty('CharWidth GetCharWidth') c.addProperty('Children GetChildren') c.addProperty('ClientAreaOrigin GetClientAreaOrigin') c.addProperty('ClientSize GetClientSize SetClientSize') c.addProperty('Constraints GetConstraints SetConstraints') c.addProperty('ContainingSizer GetContainingSizer SetContainingSizer') c.addProperty('Cursor GetCursor SetCursor') c.addProperty('DefaultAttributes GetDefaultAttributes') c.addProperty('DropTarget GetDropTarget SetDropTarget') c.addProperty('EventHandler GetEventHandler SetEventHandler') c.addProperty('ExtraStyle GetExtraStyle SetExtraStyle') c.addProperty('Font GetFont SetFont') c.addProperty('ForegroundColour GetForegroundColour SetForegroundColour') c.addProperty('GrandParent GetGrandParent') c.addProperty('TopLevelParent GetTopLevelParent') c.addProperty('Handle GetHandle') c.addProperty('HelpText GetHelpText SetHelpText') c.addProperty('Id GetId SetId') c.addProperty('Label GetLabel SetLabel') c.addProperty('LayoutDirection GetLayoutDirection SetLayoutDirection') c.addProperty('MaxHeight GetMaxHeight') c.addProperty('MaxSize GetMaxSize SetMaxSize') c.addProperty('MaxWidth GetMaxWidth') c.addProperty('MinHeight GetMinHeight') c.addProperty('MinSize GetMinSize SetMinSize') c.addProperty('MinWidth GetMinWidth') c.addProperty('Name GetName SetName') c.addProperty('Parent GetParent') c.addProperty('Position GetPosition SetPosition') c.addProperty('ScreenPosition GetScreenPosition') c.addProperty('ScreenRect GetScreenRect') c.addProperty('Size GetSize SetSize') c.addProperty('Sizer GetSizer SetSizer') c.addProperty('ThemeEnabled GetThemeEnabled SetThemeEnabled') c.addProperty('ToolTip GetToolTip SetToolTip') c.addProperty('UpdateClientRect GetUpdateClientRect') c.addProperty('UpdateRegion GetUpdateRegion') c.addProperty('Validator GetValidator SetValidator') c.addProperty('VirtualSize GetVirtualSize SetVirtualSize') c.addProperty('WindowStyle GetWindowStyle SetWindowStyle') c.addProperty('WindowStyleFlag GetWindowStyleFlag SetWindowStyleFlag') c.addProperty('WindowVariant GetWindowVariant SetWindowVariant') c.addProperty('Shown IsShown Show') c.addProperty('Enabled IsEnabled Enable') c.addProperty('TopLevel IsTopLevel') c.addProperty('MinClientSize GetMinClientSize SetMinClientSize') c.addProperty('MaxClientSize GetMaxClientSize SetMaxClientSize') ##c.addProperty('GtkWidget GetGtkWidget') tools.fixWindowClass(c) tools.addSipConvertToSubClassCode(c) # for compatibility with Classic c.addPyMethod('GetPositionTuple', '(self)', 'return self.GetPosition()', deprecated='Use GetPosition instead') c.addPyMethod('MoveXY', '(self, x, y)', 'return self.Move(x, y)', deprecated='Use Move instead.') c.addPyMethod('SetSizeWH', '(self, w, h)', 'return self.SetSize(w,h)', deprecated='Use SetSize instead.') c.addPyMethod('SetVirtualSizeWH', '(self, w, h)', 'return self.SetVirtualSize(w,h)', deprecated='Use SetVirtualSize instead.') c.addPyMethod('GetVirtualSizeTuple', '(self)', 'return self.GetVirtualSize()', deprecated='Use GetVirtualSize instead.') c.addPyMethod('SetToolTipString', '(self, string)', 'return self.SetToolTip(string)', deprecated='Use SetToolTip instead.') c.addPyMethod('ConvertDialogPointToPixels', '(self, point)', 'return self.ConvertDialogToPixels(point)', deprecated='Use ConvertDialogToPixels instead.') c.addPyMethod('ConvertDialogSizeToPixels', '(self, size)', 'return self.ConvertDialogToPixels(point)', deprecated='Use ConvertDialogToPixels instead.') # TODO: the C++ DoEraseBackground is protected in wxMSW. We need a way to # unprotect it, like adding a shim in the sip class... #c.addHeaderCode("""\ # #ifdef __WXMSW__ # #include <wx/msw/dc.h> # #endif # """) #c.addCppMethod('bool', 'DoEraseBackground', '(wxDC* dc)', # doc="Default erase background implementation.", # body="""\ # #ifdef __WXMSW__ # return self->DoEraseBackground(((wxMSWDCImpl*)dc->GetImpl())->GetHDC()); # #else # dc->SetBackground(wxBrush(self->GetBackgroundColour())); # dc->Clear(); # return true; # #endif # """) # this is a nested class c.find('ChildrenRepositioningGuard').addPrivateCopyCtor() module.insertItem(0, etgtools.TypedefDef(type='wxWindow::ChildrenRepositioningGuard', name='ChildrenRepositioningGuard')) #----------------------------------------------------------------------- # Other stuff module.addPyCode('''\ class FrozenWindow(object): """ A context manager to be used with Python 'with' statements that will freeze the given window for the duration of the with block. """ def __init__(self, window): self._win = window def __enter__(self): self._win.Freeze() return self def __exit__(self, exc_type, exc_val, exc_tb): self._win.Thaw() ''') # Add a wrapper for wxWindowList and a new iterator class for it that # makes wxWindowList quack like a read-only Python sequence. module.addItem(tools.wxListWrapperTemplate('wxWindowList', 'wxWindow', module)) module.addCppFunction('wxWindowList*', 'GetTopLevelWindows', '()', noCopy=True, briefDoc="Returns a list-like object of the the application's top-level windows, (frames,dialogs, etc.)", body="return &wxTopLevelWindows;") module.addPyCode("PyWindow = wx.deprecated(Window, 'Use Window instead.')") module.find('wxFindWindowAtPointer.pt').out = True module.addCppFunction('wxWindow*', 'FindWindowById', '(long id, const wxWindow* parent=NULL)', doc="""\ FindWindowById(id, parent=None) -> Window Find the first window in the application with the given id. If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases. """, body="return wxWindow::FindWindowById(id, parent);") module.addCppFunction('wxWindow*', 'FindWindowByName', '(const wxString& name, const wxWindow* parent=NULL)', doc="""\ FindWindowByName(name, parent=None) -> Window Find a window by its name (as given in a window constructor or Create function call). If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases. If no window with the name is found, wx.FindWindowByLabel is called.""", body="return wxWindow::FindWindowByName(*name, parent);") module.addCppFunction('wxWindow*', 'FindWindowByLabel', '(const wxString& label, const wxWindow* parent=NULL)', doc="""\ FindWindowByLabel(label, parent=None) -> Window Find a window by its label. Depending on the type of window, the label may be a window title or panel item label. If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases.""", body="return wxWindow::FindWindowByLabel(*label, parent);") #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. c = module.find('wxVisualAttributes') assert isinstance(c, etgtools.ClassDef) # Mark the stucture memebers as read-only, and make copies of the values # when fetching them. This is to protect against cases where the # VisualAttributes object is transient and may be GC'd while we still are # using a reference to a C++ member value. c.find('colBg').noSetter = True c.find('colBg').getCode = """\ wxColour* clr = new wxColour(sipCpp->colBg); sipPy = wxPyConstructObject((void*)clr, "wxColour", true); """ c.find('colFg').noSetter = True c.find('colFg').getCode = """\ wxColour* clr = new wxColour(sipCpp->colFg); sipPy = wxPyConstructObject((void*)clr, "wxColour", true); """ c.find('font').noSetter = True c.find('font').getCode = """\ wxFont* font = new wxFont(sipCpp->font); sipPy = wxPyConstructObject((void*)font, "wxFont", true); """ c = module.find('wxWindow') assert isinstance(c, etgtools.ClassDef) module.addGlobalStr('wxPanelNameStr', c) c.find('FindFocus').mustHaveApp() c.find('GetCapture').mustHaveApp() # First we need to let the wrapper generator know about wxWindowBase since # AddChild and RemoveChild need to use that type in order to be virtualized. winbase = ClassDef( name='wxWindowBase', bases=['wxEvtHandler'], abstract=True, items=[ MethodDef(name='AddChild', isVirtual=True, type='void', protection='public', items=[ParamDef(name='child', type='wxWindowBase*')]), MethodDef(name='RemoveChild', isVirtual=True, type='void', protection='public', items=[ParamDef(name='child', type='wxWindowBase*')]) ]) module.insertItemBefore(c, winbase) # Now change the base class of wxWindow c.bases = ['wxWindowBase'] # And fix the arg types we get from Doxy c.find('AddChild.child').type = 'wxWindowBase*' c.find('RemoveChild.child').type = 'wxWindowBase*' # We now return you to our regularly scheduled programming... c.includeCppCode('src/window_ex.cpp') # ignore some overloads that will be ambiguous after wrapping c.find('GetChildren').overloads = [] c.find('GetChildren').noCopy = True for name in ['GetVirtualSize', 'GetPosition', 'GetScreenPosition']: c.find(name).findOverload('int *').ignore() # Fix ClientToScreen/ScreenToClient int * overloads for name in ['ClientToScreen', 'ScreenToClient']: c.find(name).findOverload('int *').find('x').inOut = True c.find(name).findOverload('int *').find('y').inOut = True # Like the above, but these also need to transplant the docs from the # ignored item to the non-ignored overload. for name in ['GetClientSize', 'GetSize']: c.find(name).findOverload('int *').ignore() item = c.find(name) ov = item.overloads[0] item.briefDoc = ov.briefDoc item.detailedDoc = ov.detailedDoc # Release the GIL for potentially blocking or long-running functions c.find('PopupMenu').releaseGIL() c.find('ProcessEvent').releaseGIL() c.find('ProcessWindowEvent').releaseGIL() c.find('ProcessWindowEventLocally').releaseGIL() # Add a couple wrapper functions for symmetry with the getters of the same name c.addPyMethod('SetRect', '(self, rect)', 'return self.SetSize(rect)') c.addPyProperty('Rect GetRect SetRect') c.addPyMethod('SetClientRect', '(self, rect)', 'return self.SetClientSize(rect)') c.addPyProperty('ClientRect GetClientRect SetClientRect') # Split the overloaded GetTextExtent into two distinct methods, because the # resulting method signatures are not different enough from the Python # perspective. m1 = c.find('GetTextExtent') #.findOverload('int *') assert len(m1.overloads) == 1 m2 = m1.overloads.pop() c.insertItemAfter(m1, m2) # Now do the needed tweaks for the full GetFullTextExtent m1.pyName = 'GetFullTextExtent' m1.find('w').out = True m1.find('h').out = True m1.find('descent').out = True m1.find('externalLeading').out = True c.find('GetHandle').type = 'wxUIntPtr*' c.find('GetHandle').setCppCode( "return new wxUIntPtr(wxPyGetWinHandle(self));") c.addCppMethod( 'void*', 'GetGtkWidget', '()', """\ #ifdef __WXGTK__ return (void*)self->GetHandle(); #else return NULL; #endif """) c.addCppMethod('void', 'AssociateHandle', '(long handle)', doc="Associate the window with a new native handle", body="self->AssociateHandle((WXWidget)handle);") c.addCppMethod('void', 'DissociateHandle', '()', doc="Dissociate the current native handle from the window", body="self->DissociateHandle();") # Add some new methods c.addCppMethod( 'wxWindow*', 'GetTopLevelParent', '()', 'return wxGetTopLevelParent(self);', briefDoc= "Returns the first ancestor of this window which is a top-level window." ) c.addCppMethod( 'bool', 'MacIsWindowScrollbar', '(const wxWindow* sb)', """\ #ifdef __WXMAC__ return self->MacIsWindowScrollbar(sb); #else return false; #endif """, pyArgsString="(sb)", briefDoc= "Is the given widget one of this window's built-in scrollbars? Only applicable on Mac." ) c.addCppMethod( 'void', 'SetDimensions', '(int x, int y, int width, int height, int sizeFlags=wxSIZE_AUTO)', pyArgsString="(x, y, width, height, sizeFlags=SIZE_AUTO)", body="""\ self->SetSize(x, y, width, height, sizeFlags); """) c.addPyCode( "Window.SetDimensions = wx.deprecated(Window.SetDimensions, 'Use SetSize instead.')" ) # Make the Register/UnregisterHotKey functions be available on Windows, # and empty stubs otherwise c.find('RegisterHotKey').setCppCode("""\ #if wxUSE_HOTKEY return self->RegisterHotKey(hotkeyId, modifiers, virtualKeyCode); #else return false; #endif """) c.find('UnregisterHotKey').setCppCode("""\ #if wxUSE_HOTKEY return self->UnregisterHotKey(hotkeyId); #else return false; #endif """) c.find('RegisterHotKey').isVirtual = False c.find('UnregisterHotKey').isVirtual = False c.find('SetDoubleBuffered').setCppCode("""\ #if defined(__WXGTK20__) || defined(__WXGTK3__) || defined(__WXMSW__) self->SetDoubleBuffered(on); #endif """) c.addPyMethod( '__nonzero__', '(self)', doc= "Can be used to test if the C++ part of the window still exists, with \n" "code like this::\n\n" " if theWindow:\n" " doSomething()", body="""\ import wx.siplib return not wx.siplib.isdeleted(self) """) c.addPyCode('Window.__bool__ = Window.__nonzero__') # For Python 3 c.addPyMethod('DestroyLater', '(self)', doc="""\ Schedules the window to be destroyed in the near future. This should be used whenever Destroy could happen too soon, such as when there may still be events for this window or its children waiting in the event queue. """, body="""\ self.Hide() wx.GetApp().ScheduleForDestruction(self) """) c.addPyMethod('DLG_UNIT', '(self, dlg_unit)', doc="""\ A convenience wrapper for :meth:`ConvertDialogToPixels`. """, body="""\ is_wxType = isinstance(dlg_unit, (wx.Size, wx.Point)) pix = self.ConvertDialogToPixels(dlg_unit) if not is_wxType: pix = tuple(pix) return pix """) # wxAccessbile is MSW only. Provide a NotImplemented fallback for the # other platforms. c.find('GetAccessible').setCppCode("""\ #if wxUSE_ACCESSIBILITY return self->GetAccessible(); #else wxPyRaiseNotImplemented(); return NULL; #endif """) c.find('SetAccessible.accessible').transfer = True c.find('SetAccessible').setCppCode("""\ #if wxUSE_ACCESSIBILITY self->SetAccessible(accessible); #else wxPyRaiseNotImplemented(); #endif """) # Make some of the protected methods visible and overridable from Python c.find('SendDestroyEvent').ignore(False) c.find('Destroy').transferThis = True c.addPyMethod('PostCreate', '(self, pre)', 'pass', deprecated='PostCreate is no longer necessary.') # transfer ownership of these parameters to the C++ object c.find('SetCaret.caret').transfer = True c.find('SetToolTip.tip').transfer = True c.find('SetDropTarget.target').transfer = True c.find('SetConstraints.constraints').transfer = True c.find('SetSizer.sizer').transfer = True c.find('SetSizerAndFit.sizer').transfer = True # Change some =0 default values to =NULL so the docs will make more sense c.find('FindWindowById.parent').default = 'NULL' c.find('FindWindowByLabel.parent').default = 'NULL' c.find('FindWindowByName.parent').default = 'NULL' # Transfer ownership of the wx.EvtHandler when pushing/popping them... c.find('PushEventHandler.handler').transfer = True c.find('PopEventHandler').transferBack = True # ...and for Set/RemoveEventHandler too c.find('SetEventHandler.handler').transfer = True c.find('RemoveEventHandler.handler').transferBack = True # Define some properties using the getter and setter methods c.addProperty('AcceleratorTable GetAcceleratorTable SetAcceleratorTable') c.addProperty('AutoLayout GetAutoLayout SetAutoLayout') c.addProperty('BackgroundColour GetBackgroundColour SetBackgroundColour') c.addProperty('BackgroundStyle GetBackgroundStyle SetBackgroundStyle') c.addProperty('EffectiveMinSize GetEffectiveMinSize') c.addProperty('BestSize GetBestSize') c.addProperty('BestVirtualSize GetBestVirtualSize') c.addProperty('Border GetBorder') c.addProperty('Caret GetCaret SetCaret') c.addProperty('CharHeight GetCharHeight') c.addProperty('CharWidth GetCharWidth') c.addProperty('Children GetChildren') c.addProperty('ClientAreaOrigin GetClientAreaOrigin') c.addProperty('ClientSize GetClientSize SetClientSize') c.addProperty('Constraints GetConstraints SetConstraints') c.addProperty('ContainingSizer GetContainingSizer SetContainingSizer') c.addProperty('Cursor GetCursor SetCursor') c.addProperty('DefaultAttributes GetDefaultAttributes') c.addProperty('DropTarget GetDropTarget SetDropTarget') c.addProperty('EventHandler GetEventHandler SetEventHandler') c.addProperty('ExtraStyle GetExtraStyle SetExtraStyle') c.addProperty('Font GetFont SetFont') c.addProperty('ForegroundColour GetForegroundColour SetForegroundColour') c.addProperty('GrandParent GetGrandParent') c.addProperty('TopLevelParent GetTopLevelParent') c.addProperty('Handle GetHandle') c.addProperty('HelpText GetHelpText SetHelpText') c.addProperty('Id GetId SetId') c.addProperty('Label GetLabel SetLabel') c.addProperty('LayoutDirection GetLayoutDirection SetLayoutDirection') c.addProperty('MaxHeight GetMaxHeight') c.addProperty('MaxSize GetMaxSize SetMaxSize') c.addProperty('MaxWidth GetMaxWidth') c.addProperty('MinHeight GetMinHeight') c.addProperty('MinSize GetMinSize SetMinSize') c.addProperty('MinWidth GetMinWidth') c.addProperty('Name GetName SetName') c.addProperty('Parent GetParent') c.addProperty('Position GetPosition SetPosition') c.addProperty('ScreenPosition GetScreenPosition') c.addProperty('ScreenRect GetScreenRect') c.addProperty('Size GetSize SetSize') c.addProperty('Sizer GetSizer SetSizer') c.addProperty('ThemeEnabled GetThemeEnabled SetThemeEnabled') c.addProperty('ToolTip GetToolTip SetToolTip') c.addProperty('UpdateClientRect GetUpdateClientRect') c.addProperty('UpdateRegion GetUpdateRegion') c.addProperty('Validator GetValidator SetValidator') c.addProperty('VirtualSize GetVirtualSize SetVirtualSize') c.addProperty('WindowStyle GetWindowStyle SetWindowStyle') c.addProperty('WindowStyleFlag GetWindowStyleFlag SetWindowStyleFlag') c.addProperty('WindowVariant GetWindowVariant SetWindowVariant') c.addProperty('Shown IsShown Show') c.addProperty('Enabled IsEnabled Enable') c.addProperty('TopLevel IsTopLevel') c.addProperty('MinClientSize GetMinClientSize SetMinClientSize') c.addProperty('MaxClientSize GetMaxClientSize SetMaxClientSize') ##c.addProperty('GtkWidget GetGtkWidget') tools.fixWindowClass(c) tools.addSipConvertToSubClassCode(c) # for compatibility with Classic c.addPyMethod('GetPositionTuple', '(self)', 'return self.GetPosition()', deprecated='Use GetPosition instead') c.addPyMethod('GetSizeTuple', '(self)', 'return self.GetSize()', deprecated='Use GetSize instead') c.addPyMethod('MoveXY', '(self, x, y)', 'return self.Move(x, y)', deprecated='Use Move instead.') c.addPyMethod('SetSizeWH', '(self, w, h)', 'return self.SetSize(w,h)', deprecated='Use SetSize instead.') c.addPyMethod('SetVirtualSizeWH', '(self, w, h)', 'return self.SetVirtualSize(w,h)', deprecated='Use SetVirtualSize instead.') c.addPyMethod('GetVirtualSizeTuple', '(self)', 'return self.GetVirtualSize()', deprecated='Use GetVirtualSize instead.') c.addPyMethod('SetToolTipString', '(self, string)', 'return self.SetToolTip(string)', deprecated='Use SetToolTip instead.') c.addPyMethod('ConvertDialogPointToPixels', '(self, point)', 'return self.ConvertDialogToPixels(point)', deprecated='Use ConvertDialogToPixels instead.') c.addPyMethod('ConvertDialogSizeToPixels', '(self, size)', 'return self.ConvertDialogToPixels(point)', deprecated='Use ConvertDialogToPixels instead.') c.addPyMethod( 'SetSizeHintsSz', '(self, minSize, maxSize=wx.DefaultSize, incSize=wx.DefaultSize)', 'return self.SetSizeHints(minSize, maxSize, incSize)', deprecated='Use SetSizeHints instead.') # TODO: the C++ DoEraseBackground is protected in wxMSW. We need a way to # unprotect it, like adding a shim in the sip class... #c.addHeaderCode("""\ # #ifdef __WXMSW__ # #include <wx/msw/dc.h> # #endif # """) #c.addCppMethod('bool', 'DoEraseBackground', '(wxDC* dc)', # doc="Default erase background implementation.", # body="""\ # #ifdef __WXMSW__ # return self->DoEraseBackground(((wxMSWDCImpl*)dc->GetImpl())->GetHDC()); # #else # dc->SetBackground(wxBrush(self->GetBackgroundColour())); # dc->Clear(); # return true; # #endif # """) # this is a nested class c.find('ChildrenRepositioningGuard').addPrivateCopyCtor() module.insertItem( 0, etgtools.TypedefDef(type='wxWindow::ChildrenRepositioningGuard', name='ChildrenRepositioningGuard')) #----------------------------------------------------------------------- # Other stuff module.addPyCode('''\ class FrozenWindow(object): """ A context manager to be used with Python 'with' statements that will freeze the given window for the duration of the with block. """ def __init__(self, window): self._win = window def __enter__(self): self._win.Freeze() return self def __exit__(self, exc_type, exc_val, exc_tb): self._win.Thaw() ''') module.addPyCode('''\ def DLG_UNIT(win, dlg_unit, val2=None): """ Convenience function for converting a wx.Point, wx.Size or (x,y) in dialog units to pixels, using the given window as a reference. """ if val2 is not None: dlg_unit = (dlg_unit, val2) is_wxType = isinstance(dlg_unit, (wx.Size, wx.Point)) pix = win.ConvertDialogToPixels(dlg_unit) if not is_wxType: pix = tuple(pix) return pix DLG_PNT = wx.deprecated(DLG_UNIT, "Use DLG_UNIT instead.") DLG_SZE = wx.deprecated(DLG_UNIT, "Use DLG_UNIT instead.") ''') # Add a wrapper for wxWindowList and a new iterator class for it that # makes wxWindowList quack like a read-only Python sequence. module.addItem( tools.wxListWrapperTemplate('wxWindowList', 'wxWindow', module)) module.addCppFunction( 'wxWindowList*', 'GetTopLevelWindows', '()', noCopy=True, briefDoc= "Returns a list-like object of the the application's top-level windows, (frames,dialogs, etc.)", body="return &wxTopLevelWindows;") module.addPyCode("PyWindow = wx.deprecated(Window, 'Use Window instead.')") module.find('wxFindWindowAtPointer.pt').out = True module.find('wxFindWindowAtPointer').mustHaveApp() module.find('wxGetActiveWindow').mustHaveApp() module.find('wxGetTopLevelParent').mustHaveApp() module.addCppFunction('wxWindow*', 'FindWindowById', '(long id, const wxWindow* parent=NULL)', doc="""\ FindWindowById(id, parent=None) -> Window Find the first window in the application with the given id. If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases. """, body="return wxWindow::FindWindowById(id, parent);", mustHaveAppFlag=True) module.addCppFunction( 'wxWindow*', 'FindWindowByName', '(const wxString& name, const wxWindow* parent=NULL)', doc="""\ FindWindowByName(name, parent=None) -> Window Find a window by its name (as given in a window constructor or Create function call). If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases. If no window with the name is found, wx.FindWindowByLabel is called.""", body="return wxWindow::FindWindowByName(*name, parent);", mustHaveAppFlag=True) module.addCppFunction( 'wxWindow*', 'FindWindowByLabel', '(const wxString& label, const wxWindow* parent=NULL)', doc="""\ FindWindowByLabel(label, parent=None) -> Window Find a window by its label. Depending on the type of window, the label may be a window title or panel item label. If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases.""", body="return wxWindow::FindWindowByLabel(*label, parent);", mustHaveAppFlag=True) #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. def addTransferAnnotations(c, arg): for method in c.findAll('Append') + c.findAll('Insert') + \ c.findAll('Replace') + c.findAll('Prepend'): arg_def = method.findItem(arg) if arg_def: arg_def.transfer = True for method in c.findAll('Remove') + c.findAll('Replace'): method.transferBack = True #----------------------------------------------------------------- c = module.find('wxMenu') assert isinstance(c, etgtools.ClassDef) c.mustHaveApp() tools.removeVirtuals(c) c.find('Prepend.item').name = 'menuItem' c.find('Prepend.submenu').name = 'subMenu' addTransferAnnotations(c, 'menuItem') addTransferAnnotations(c, 'subMenu') c.find('AppendSubMenu.submenu').transfer = True # We only need one of these overloads, the non-const/const is not enough # to distinguish a unique Python signature. c.find('GetMenuItems').overloads = [] # Ensure that no copy is made of the list object, so we only wrap the # existing object and keep it owned by C++ c.find('GetMenuItems').noCopy = True c.addPyMethod('AppendMenu', '(self, id, item, subMenu, help="")', deprecated='Use Append instead.', body='return self.Append(id, item, subMenu, help)') c.addPyMethod('AppendItem', '(self, menuItem)', deprecated='Use Append instead.', body='return self.Append(menuItem)') c.addPyMethod('InsertMenu', '(self, pos, id, item, subMenu, help="")', deprecated='Use Insert instead.', body='return self.Insert(pos, id, item, subMenu, help)') c.addPyMethod('InsertItem', '(self, pos, menuItem)', deprecated='Use Insert instead.', body='return self.Insert(pos, menuItem)') c.addPyMethod('PrependMenu', '(self, id, item, subMenu, help="")', deprecated='Use Prepend instead.', body='return self.Prepend(id, item, subMenu, help)') c.addPyMethod('PrependItem', '(self, menuItem)', deprecated='Use Prepend instead.', body='return self.Prepend(menuItem)') c.addPyMethod('RemoveMenu', '(self, id, item, subMenu, help="")', deprecated='Use Remove instead.', body='return self.Remove(id, item, subMenu, help)') c.addPyMethod('RemoveItem', '(self, menuItem)', deprecated='Use Remove instead.', body='return self.Remove(menuItem)') # Don't hide the Destroy inherited from wxObject c.find('Destroy').findOverload('int').pyName = 'DestroyItem' c.find('Destroy').findOverload('wxMenuItem').pyName = 'DestroyItem' c.find('FindChildItem.pos').out = True c.find('FindItem.menu').out = True c.addCppMethod('wxMenuItem*', 'FindItemById', '(int id)', isConst=True, doc="""\ FindItemById(id) -> MenuItem Finds the menu item object associated with the given menu item identifier.""", body="""\ return self->FindItem(id);""") #----------------------------------------------------------------- c = module.find('wxMenuBar') assert isinstance(c, etgtools.ClassDef) c.mustHaveApp() tools.removeVirtuals(c) addTransferAnnotations(c, 'menu') c.find('wxMenuBar').findOverload( 'wxMenu *menus[], const wxString titles[], long style=0)').ignore() c.find('FindItem.menu').out = True c.addCppMethod('wxMenuItem*', 'FindItemById', '(int id)', isConst=True, doc="""\ FindItemById(id) -> MenuItem Finds the menu item object associated with the given menu item identifier.""", body="""\ return self->FindItem(id);""") mac_scmb = c.find('MacSetCommonMenuBar') mac_scmb.setCppCode("""\ #ifdef __WXMAC__ wxMenuBar::MacSetCommonMenuBar(menubar); #endif """) mac_gcmb = c.find('MacGetCommonMenuBar') mac_gcmb.setCppCode("""\ #ifdef __WXMAC__ return wxMenuBar::MacGetCommonMenuBar(); #else return NULL; #endif """) mac_gcmb = c.find('OSXGetAppleMenu') mac_gcmb.setCppCode("""\ #ifdef __WXMAC__ return self->OSXGetAppleMenu(); #else return NULL; #endif """) # don't transfer on other platforms, as this is a no-op there. import sys if sys.platform.startswith('darwin'): mac_scmb.find('menubar').transfer = True c.find('FindItem.menu').out = True c.addPyMethod('GetMenus', '(self)', doc="""\ GetMenus() -> (menu, label)\n Return a list of (menu, label) items for the menus in the :class:`MenuBar`.""", body="""\ return [(self.GetMenu(i), self.GetLabelTop(i)) for i in range(self.GetMenuCount())] """) c.addPyMethod('SetMenus', '(self, items)', doc="""\ SetMenus()\n Clear and add new menus to the :class:`MenuBar` from a list of (menu, label) items.""", body="""\ for i in range(self.GetMenuCount()-1, -1, -1): self.Remove(i) for m, l in items: self.Append(m, l) """) c.addPyProperty('Menus GetMenus SetMenus') module.addItem(tools.wxListWrapperTemplate('wxMenuList', 'wxMenu', module)) #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. c = module.find('wxMenuItem') assert isinstance(c, etgtools.ClassDef) c.addPrivateCopyCtor() tools.removeVirtuals(c) c.find('SetSubMenu.menu').transfer = True # These are MSW only. Make them be empty stubs for the other ports c.find('GetBackgroundColour').type = 'wxColour*' c.find('GetBackgroundColour').setCppCode("""\ #ifdef __WXMSW__ return &self->GetBackgroundColour(); #else return &wxNullColour; #endif """) c.find('SetBackgroundColour').setCppCode("""\ #ifdef __WXMSW__ self->SetBackgroundColour(*colour); #endif """) c.find('GetFont').type = 'wxFont*' c.find('GetFont').setCppCode("""\ #ifdef __WXMSW__ return &self->GetFont(); #else return &wxNullFont; #endif """) c.find('SetFont').setCppCode("""\ #ifdef __WXMSW__ self->SetFont(*font); #endif """) c.find('GetMarginWidth').setCppCode("""\ #ifdef __WXMSW__ return self->GetMarginWidth(); #else return -1; #endif """) c.find('SetMarginWidth').setCppCode("""\ #ifdef __WXMSW__ self->SetMarginWidth(width); #endif """) c.find('GetTextColour').type = 'wxColour*' c.find('GetTextColour').setCppCode("""\ #ifdef __WXMSW__ return &self->GetTextColour(); #else return &wxNullColour; #endif """) c.find('SetTextColour').setCppCode("""\ #ifdef __WXMSW__ self->SetTextColour(*colour); #endif """) c.find('GetBitmap').type = 'const wxBitmap*' c.find('GetBitmap').setCppCode("""\ #ifdef __WXMSW__ return &self->GetBitmap(checked); #else return &self->GetBitmap(); #endif """) c.find('SetBitmap').setCppCode("""\ #ifdef __WXMSW__ self->SetBitmap(*bmp, checked); #else self->SetBitmap(*bmp); // no checked arg in this case #endif """) c.find('SetBitmaps').setCppCode("""\ #ifdef __WXMSW__ self->SetBitmaps(*checked, *unchecked); #else self->SetBitmap(*checked); #endif """) c.find('GetDisabledBitmap').type = 'const wxBitmap*' c.find('GetDisabledBitmap').setCppCode("""\ #ifdef __WXMSW__ return &self->GetDisabledBitmap(); #else return &wxNullBitmap; #endif """) c.find('SetDisabledBitmap').setCppCode("""\ #ifdef __WXMSW__ self->SetDisabledBitmap(*disabled); #endif """) c.find('GetAccel').factory = True c.find('GetAccelFromString').ignore() # Not implemented anywere? module.addItem( tools.wxListWrapperTemplate('wxMenuItemList', 'wxMenuItem', module)) #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. module.addHeaderCode('#include <wx/richtext/richtextbuffer.h>') module.addItem( tools.wxArrayWrapperTemplate('wxRichTextRangeArray', 'wxRichTextRange', module)) module.addItem( tools.wxArrayWrapperTemplate('wxRichTextAttrArray', 'wxRichTextAttr', module)) module.addItem( tools.wxArrayWrapperTemplate('wxRichTextVariantArray', 'wxVariant', module)) module.addItem( tools.wxListWrapperTemplate('wxRichTextObjectList', 'wxRichTextObject', module)) module.addItem( tools.wxListWrapperTemplate('wxRichTextLineList', 'wxRichTextLine', module)) # Can this even work? Apparently it does. module.addItem( tools.wxArrayPtrWrapperTemplate('wxRichTextObjectPtrArray', 'wxRichTextObject', module)) module.addItem( tools.wxArrayWrapperTemplate('wxRichTextObjectPtrArrayArray', 'wxRichTextObjectPtrArray', module)) module.find('wxRICHTEXT_ALL').ignore() module.find('wxRICHTEXT_NONE').ignore() module.find('wxRICHTEXT_NO_SELECTION').ignore() code = etgtools.PyCodeDef("""\ RICHTEXT_ALL = RichTextRange(-2, -2) RICHTEXT_NONE = RichTextRange(-1, -1) RICHTEXT_NO_SELECTION = RichTextRange(-2, -2) """) module.insertItemAfter(module.find('wxRichTextRange'), code) module.insertItem(0, etgtools.WigCode("""\ // forward declarations class wxRichTextFloatCollector; """)) #------------------------------------------------------- c = module.find('wxTextAttrDimension') assert isinstance(c, etgtools.ClassDef) c.find('SetValue').findOverload('units').ignore() c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrDimensions') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrSize') tools.ignoreConstOverloads(c) c.find('SetWidth').findOverload('units').ignore() c.find('SetHeight').findOverload('units').ignore() c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrBorder') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrBorders') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextBoxAttr') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextAttr') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextProperties') tools.ignoreConstOverloads(c) c.find('SetProperty').findOverload('bool').ignore() c.find('operator[]').ignore() #------------------------------------------------------- c = module.find('wxRichTextSelection') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") c.find('operator[]').ignore() #------------------------------------------------------- c = module.find('wxRichTextRange') tools.addAutoProperties(c) # wxRichTextRange typemap c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxRichTextRange') c.addCppMethod('PyObject*', 'Get', '()', """\ wxPyThreadBlocker blocker; return sipBuildResult(0, "(ii)", self->GetStart(), self->GetEnd()); """, pyArgsString="() -> (start, end)", briefDoc="Return the start and end properties as a tuple.") tools.addGetIMMethodTemplate(module, c, ['Start', 'End']) # Add sequence protocol methods and other goodies c.addPyMethod('__str__', '(self)', 'return str(self.Get())') c.addPyMethod('__repr__', '(self)', 'return "RichTextRange"+str(self.Get())') c.addPyMethod('__len__', '(self)', 'return len(self.Get())') c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0)') c.addPyMethod('__reduce__', '(self)', 'return (RichTextRange, self.Get())') c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]') c.addPyMethod('__setitem__', '(self, idx, val)', """\ if idx == 0: self.Start = val elif idx == 1: self.End = val else: raise IndexError """) c.addPyCode('RichTextRange.__safe_for_unpickling__ = True') #------------------------------------------------------- def _fixDrawObject(c, addMissingVirtuals=True): assert isinstance(c, etgtools.ClassDef) if c.findItem('HitTest'): c.find('HitTest.textPosition').out = True c.find('HitTest.obj').out = True c.find('HitTest.contextObj').out = True if c.findItem('FindPosition'): c.find('FindPosition.pt').out = True c.find('FindPosition.height').out = True if c.findItem('GetBoxRects'): c.find('GetBoxRects.marginRect').out = True c.find('GetBoxRects.borderRect').out = True c.find('GetBoxRects.contentRect').out = True c.find('GetBoxRects.paddingRect').out = True c.find('GetBoxRects.outlineRect').out = True if c.findItem('GetTotalMargin'): c.find('GetTotalMargin.leftMargin').out = True c.find('GetTotalMargin.rightMargin').out = True c.find('GetTotalMargin.topMargin').out = True c.find('GetTotalMargin.bottomMargin').out = True if c.findItem('CalculateRange'): c.find('CalculateRange.end').out = True # TODO: should it be an inOut? if c.findItem('Clone'): c.find('Clone').factory = True else: c.addItem(etgtools.WigCode("""\ virtual wxRichTextObject* Clone() const /Factory/; """)) # These are the pure virtuals in the base class. SIP needs to see that # all the derived classes have an implementation, otherwise it will # consider them to be ABCs. if not c.findItem('Draw') and addMissingVirtuals: c.addItem(etgtools.WigCode("""\ virtual bool Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style);""")) if not c.findItem('Layout') and addMissingVirtuals: c.addItem(etgtools.WigCode("""\ virtual bool Layout(wxDC& dc, wxRichTextDrawingContext& context, const wxRect& rect, const wxRect& parentRect, int style);""")) # TODO: Some of these args are output parameters. How should they be dealt with? if not c.findItem('GetRangeSize') and addMissingVirtuals: c.addItem(etgtools.WigCode("""\ virtual bool GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int flags, const wxPoint& position = wxPoint(0,0), const wxSize& parentSize = wxDefaultSize, wxArrayInt* partialExtents = NULL) const;""")) #------------------------------------------------------- c = module.find('wxRichTextObject') #c.find('ImportFromXML').ignore() tools.ignoreConstOverloads(c) _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextCompositeObject') tools.ignoreConstOverloads(c) _fixDrawObject(c, addMissingVirtuals=False) #------------------------------------------------------- c = module.find('wxRichTextParagraphLayoutBox') tools.ignoreConstOverloads(c) _fixDrawObject(c) c.find('MoveAnchoredObjectToParagraph.from').name = 'from_' c.find('MoveAnchoredObjectToParagraph.to').name = 'to_' c.find('DoNumberList.def').name = 'styleDef' c.find('SetListStyle.def').name = 'styleDef' #------------------------------------------------------- c = module.find('wxRichTextBox') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextCell') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextField') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextLine') tools.ignoreConstOverloads(c) c.find('SetRange.from').name = 'from_' c.find('SetRange.to').name = 'to_' c.find('Clone').factory = True #------------------------------------------------------- c = module.find('wxRichTextParagraph') _fixDrawObject(c) # These methods use an untyped wxList, but since we know what is in it # we'll make a fake typed list for wxPython so we can know what kinds of # values to get from it. module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextObject', module, fakeListClassName='wxRichTextObjectList_')) c.find('MoveToList.list').type = 'wxRichTextObjectList_&' c.find('MoveFromList.list').type = 'wxRichTextObjectList_&' #------------------------------------------------------- c = module.find('wxRichTextPlainText') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextImage') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextBuffer') tools.ignoreConstOverloads(c) _fixDrawObject(c) # More untyped wxLists module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextFileHandler', module, fakeListClassName='wxRichTextFileHandlerList')) c.find('GetHandlers').type = 'wxRichTextFileHandlerList&' c.find('GetHandlers').noCopy = True module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextDrawingHandler', module, fakeListClassName='wxRichTextDrawingHandlerList')) c.find('GetDrawingHandlers').type = 'wxRichTextDrawingHandlerList&' c.find('GetDrawingHandlers').noCopy = True # TODO: Need a template to wrap STRING_HASH_MAP c.find('GetFieldTypes').ignore() c.find('AddHandler.handler').transfer = True c.find('InsertHandler.handler').transfer = True c.find('AddDrawingHandler.handler').transfer = True c.find('InsertDrawingHandler.handler').transfer = True c.find('AddFieldType.fieldType').transfer = True # TODO: Transfer ownership with AddEventHandler? TransferBack with Remove? c.find('FindHandler').renameOverload('name', 'FindHandlerByName') c.find('FindHandler').renameOverload('extension', 'FindHandlerByExtension') c.find('FindHandler').pyName = 'FindHandlerByType' c.find('FindHandlerFilenameOrType').pyName = 'FindHandlerByFilename' c.find('GetExtWildcard').ignore() c.addCppMethod('PyObject*', 'GetExtWildcard', '(bool combine=false, bool save=false)', doc="""\ Gets a wildcard string for the file dialog based on all the currently loaded richtext file handlers, and a list that can be used to map those filter types to the file handler type.""", body="""\ wxString wildcards; wxArrayInt types; wildcards = wxRichTextBuffer::GetExtWildcard(combine, save, &types); wxPyThreadBlocker blocker; PyObject* list = PyList_New(0); for (size_t i=0; i < types.GetCount(); i++) { PyObject* number = wxPyInt_FromLong(types[i]); PyList_Append(list, number); Py_DECREF(number); } PyObject* tup = PyTuple_New(2); PyTuple_SET_ITEM(tup, 0, wx2PyString(wildcards)); PyTuple_SET_ITEM(tup, 1, list); return tup; """, isStatic=True) #------------------------------------------------------- c = module.find('wxRichTextTable') tools.ignoreConstOverloads(c) _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextObjectAddress') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextCommand') module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextAction', module, fakeListClassName='wxRichTextActionList')) c.find('GetActions').type = 'wxRichTextActionList&' c.find('GetActions').noCopy = True c.find('AddAction.action').transfer = True #------------------------------------------------------- c = module.find('wxRichTextAction') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextFileHandler') c.find('DoLoadFile').ignore(False) c.find('DoSaveFile').ignore(False) c = module.find('wxRichTextPlainTextHandler') c.find('DoLoadFile').ignore(False) c.find('DoSaveFile').ignore(False) #------------------------------------------------------- # Ignore all Dump() methods since we don't wrap wxTextOutputStream. # TODO: try swithcing the parameter type to wxOutputStream and then in # the wrapper code create a wxTextOutputStream from that to pass on to # Dump. for m in module.findAll('Dump'): if m.findItem('stream'): m.ignore() # Correct the type for this define as it is a float module.find('wxSCRIPT_MUL_FACTOR').type = 'float' #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. c = module.find('wxMenuItem') assert isinstance(c, etgtools.ClassDef) c.addPrivateCopyCtor() tools.removeVirtuals(c) c.find('SetSubMenu.menu').transfer = True # deprecated and removed c.find('GetLabel').ignore() c.find('GetName').ignore() c.find('GetText').ignore() c.find('SetText').ignore() c.find('GetLabelFromText').ignore() # These are MSW only. Make them be empty stubs for the other ports c.find('GetBackgroundColour').type = 'wxColour*' c.find('GetBackgroundColour').setCppCode("""\ #ifdef __WXMSW__ return &self->GetBackgroundColour(); #else return &wxNullColour; #endif """) c.find('SetBackgroundColour').setCppCode("""\ #ifdef __WXMSW__ self->SetBackgroundColour(*colour); #endif """) c.find('GetFont').type = 'wxFont*' c.find('GetFont').setCppCode("""\ #ifdef __WXMSW__ return &self->GetFont(); #else return &wxNullFont; #endif """) c.find('SetFont').setCppCode("""\ #ifdef __WXMSW__ self->SetFont(*font); #endif """) c.find('GetMarginWidth').setCppCode("""\ #ifdef __WXMSW__ return self->GetMarginWidth(); #else return -1; #endif """) c.find('SetMarginWidth').setCppCode("""\ #ifdef __WXMSW__ self->SetMarginWidth(width); #endif """) c.find('GetTextColour').type = 'wxColour*' c.find('GetTextColour').setCppCode("""\ #ifdef __WXMSW__ return &self->GetTextColour(); #else return &wxNullColour; #endif """) c.find('SetTextColour').setCppCode("""\ #ifdef __WXMSW__ self->SetTextColour(*colour); #endif """) c.find('GetBitmap').type = 'const wxBitmap*' c.find('GetBitmap').setCppCode("""\ #ifdef __WXMSW__ return &self->GetBitmap(checked); #else return &self->GetBitmap(); #endif """) c.find('SetBitmap').setCppCode("""\ #ifdef __WXMSW__ self->SetBitmap(*bmp, checked); #else self->SetBitmap(*bmp); // no checked arg in this case #endif """) c.find('SetBitmaps').setCppCode("""\ #ifdef __WXMSW__ self->SetBitmaps(*checked, *unchecked); #else self->SetBitmap(*checked); #endif """) c.find('GetDisabledBitmap').type = 'const wxBitmap*' c.find('GetDisabledBitmap').setCppCode("""\ #ifdef __WXMSW__ return &self->GetDisabledBitmap(); #else return &wxNullBitmap; #endif """) c.find('SetDisabledBitmap').setCppCode("""\ #ifdef __WXMSW__ self->SetDisabledBitmap(*disabled); #endif """) c.find('GetAccel').factory = True c.find('GetAccelFromString').ignore() # Not implemented anywere? module.addItem(tools.wxListWrapperTemplate('wxMenuItemList', 'wxMenuItem', module)) #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. module.addHeaderCode('#include <wx/richtext/richtextbuffer.h>') module.addItem( tools.wxArrayWrapperTemplate('wxRichTextRangeArray', 'wxRichTextRange', module)) module.addItem( tools.wxArrayWrapperTemplate('wxRichTextAttrArray', 'wxRichTextAttr', module)) module.addItem( tools.wxArrayWrapperTemplate('wxRichTextVariantArray', 'wxVariant', module)) module.addItem( tools.wxListWrapperTemplate('wxRichTextObjectList', 'wxRichTextObject', module)) module.addItem( tools.wxListWrapperTemplate('wxRichTextLineList', 'wxRichTextLine', module)) # Can this even work? Apparently it does. module.addItem( tools.wxArrayPtrWrapperTemplate('wxRichTextObjectPtrArray', 'wxRichTextObject', module)) module.addItem( tools.wxArrayWrapperTemplate('wxRichTextObjectPtrArrayArray', 'wxRichTextObjectPtrArray', module)) module.find('wxRICHTEXT_ALL').ignore() module.find('wxRICHTEXT_NONE').ignore() module.find('wxRICHTEXT_NO_SELECTION').ignore() code = etgtools.PyCodeDef("""\ RICHTEXT_ALL = RichTextRange(-2, -2) RICHTEXT_NONE = RichTextRange(-1, -1) RICHTEXT_NO_SELECTION = RichTextRange(-2, -2) """) module.insertItemAfter(module.find('wxRichTextRange'), code) module.insertItem( 0, etgtools.WigCode("""\ // forward declarations class wxRichTextFloatCollector; """)) #------------------------------------------------------- c = module.find('wxTextAttrDimension') assert isinstance(c, etgtools.ClassDef) c.find('SetValue').findOverload('units').ignore() c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrDimensions') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrSize') tools.ignoreConstOverloads(c) c.find('SetWidth').findOverload('units').ignore() c.find('SetHeight').findOverload('units').ignore() c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrBorder') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrBorders') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextBoxAttr') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextAttr') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextProperties') tools.ignoreConstOverloads(c) c.find('SetProperty').findOverload('bool').ignore() c.find('operator[]').ignore() #------------------------------------------------------- c = module.find('wxRichTextSelection') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") c.find('operator[]').ignore() #------------------------------------------------------- def _fixDrawObject(c, addMissingVirtuals=True): assert isinstance(c, etgtools.ClassDef) if c.findItem('HitTest'): c.find('HitTest.textPosition').out = True c.find('HitTest.obj').out = True c.find('HitTest.contextObj').out = True if c.findItem('FindPosition'): c.find('FindPosition.pt').out = True c.find('FindPosition.height').out = True if c.findItem('GetBoxRects'): c.find('GetBoxRects.marginRect').out = True c.find('GetBoxRects.borderRect').out = True c.find('GetBoxRects.contentRect').out = True c.find('GetBoxRects.paddingRect').out = True c.find('GetBoxRects.outlineRect').out = True if c.findItem('GetTotalMargin'): c.find('GetTotalMargin.leftMargin').out = True c.find('GetTotalMargin.rightMargin').out = True c.find('GetTotalMargin.topMargin').out = True c.find('GetTotalMargin.bottomMargin').out = True if c.findItem('CalculateRange'): c.find('CalculateRange.end' ).out = True # TODO: should it be an inOut? # This are the pure virtuals in the base class. SIP needs to see that # all the drived classes have an implementation, otherwise it will # consider them to be ABCs/ if not c.findItem('Draw') and addMissingVirtuals: c.addItem( etgtools.WigCode("""\ virtual bool Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style);""" )) if not c.findItem('Layout') and addMissingVirtuals: c.addItem( etgtools.WigCode("""\ virtual bool Layout(wxDC& dc, wxRichTextDrawingContext& context, const wxRect& rect, const wxRect& parentRect, int style);""")) # TODO: Some of these args are output parameters. How should they be dealt with? if not c.findItem('GetRangeSize') and addMissingVirtuals: c.addItem( etgtools.WigCode("""\ virtual bool GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int flags, const wxPoint& position = wxPoint(0,0), const wxSize& parentSize = wxDefaultSize, wxArrayInt* partialExtents = NULL) const;""")) #------------------------------------------------------- c = module.find('wxRichTextObject') #c.find('ImportFromXML').ignore() tools.ignoreConstOverloads(c) _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextCompositeObject') tools.ignoreConstOverloads(c) _fixDrawObject(c, addMissingVirtuals=False) #------------------------------------------------------- c = module.find('wxRichTextParagraphLayoutBox') tools.ignoreConstOverloads(c) _fixDrawObject(c) c.find('MoveAnchoredObjectToParagraph.from').name = 'from_' c.find('MoveAnchoredObjectToParagraph.to').name = 'to_' c.find('DoNumberList.def').name = 'styleDef' c.find('SetListStyle.def').name = 'styleDef' #------------------------------------------------------- c = module.find('wxRichTextBox') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextField') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextLine') tools.ignoreConstOverloads(c) c.find('SetRange.from').name = 'from_' c.find('SetRange.to').name = 'to_' #------------------------------------------------------- c = module.find('wxRichTextParagraph') _fixDrawObject(c) # These methods use an untyped wxList, but since we know what is in it # we'll make a fake typed list for wxPython so we can know what kinds of # values to get from it. module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextObject', module, fakeListClassName='wxRichTextObjectList_')) c.find('MoveToList.list').type = 'wxRichTextObjectList_&' c.find('MoveFromList.list').type = 'wxRichTextObjectList_&' #------------------------------------------------------- c = module.find('wxRichTextPlainText') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextImage') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextBuffer') tools.ignoreConstOverloads(c) _fixDrawObject(c) # More untyped wxLists module.addItem( tools.wxListWrapperTemplate( 'wxList', 'wxRichTextFileHandler', module, fakeListClassName='wxRichTextFileHandlerList')) c.find('GetHandlers').type = 'wxRichTextFileHandlerList&' c.find('GetHandlers').noCopy = True module.addItem( tools.wxListWrapperTemplate( 'wxList', 'wxRichTextDrawingHandler', module, fakeListClassName='wxRichTextDrawingHandlerList')) c.find('GetDrawingHandlers').type = 'wxRichTextDrawingHandlerList&' c.find('GetDrawingHandlers').noCopy = True # TODO: Need a template to wrap STRING_HASH_MAP c.find('GetFieldTypes').ignore() c.find('AddHandler.handler').transfer = True c.find('InsertHandler.handler').transfer = True c.find('AddDrawingHandler.handler').transfer = True c.find('InsertDrawingHandler.handler').transfer = True c.find('AddFieldType.fieldType').transfer = True # TODO: Transfer ownership with AddEventHandler? TransferBack with Remove? #------------------------------------------------------- c = module.find('wxRichTextTable') tools.ignoreConstOverloads(c) _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextObjectAddress') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextCommand') module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextAction', module, fakeListClassName='wxRichTextActionList')) c.find('GetActions').type = 'wxRichTextActionList&' c.find('GetActions').noCopy = True c.find('AddAction.action').transfer = True #------------------------------------------------------- c = module.find('wxRichTextAction') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextFileHandler') c.find('DoLoadFile').ignore(False) c.find('DoSaveFile').ignore(False) c = module.find('wxRichTextPlainTextHandler') c.find('DoLoadFile').ignore(False) c.find('DoSaveFile').ignore(False) #------------------------------------------------------- # Ignore all Dump() methods since we don't wrap wxTextOutputStream. # TODO: try swithcing the parameter type to wxOutputStream and then in # the wrapper code create a wxTextOutputStream from that to pass on to # Dump. for m in module.findAll('Dump'): if m.findItem('stream'): m.ignore() #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. # ignore some of these enum values e = module.find('wxBitmapType') for i in e: if i.name.endswith('_RESOURCE'): i.ignore() module.addCppCode("""\ #if !defined(__WXMAC__) #define wxCURSOR_COPY_ARROW wxCURSOR_ARROW #endif """) # these are X11 only e = module.find('wxStockCursor') e.find('wxCURSOR_BASED_ARROW_DOWN').ignore() e.find('wxCURSOR_BASED_ARROW_UP').ignore() e.find('wxCURSOR_CROSS_REVERSE').ignore() e.find('wxCURSOR_DOUBLE_ARROW').ignore() module.find('wxClientDisplayRect.x').out = True module.find('wxClientDisplayRect.y').out = True module.find('wxClientDisplayRect.width').out = True module.find('wxClientDisplayRect.height').out = True module.find('wxDisplaySize.width').out = True module.find('wxDisplaySize.height').out = True module.find('wxDisplaySizeMM.width').out = True module.find('wxDisplaySizeMM.height').out = True #--------------------------------------- # wxPoint tweaks c = module.find('wxPoint') tools.addAutoProperties(c) # Some operators are documented within the class that shouldn't be, so just # ignore them all. tools.ignoreAllOperators(c) # Undo a few of those ignores for legitimate items that were # documented correctly for f in c.find('operator+=').all() + c.find('operator-=').all(): f.ignore(False) # Add some method declarations for operators that really do exist. Note # that these actually use C++ global operator functions, but we treat # them as methods to help disambiguate implementations due to how # multiple classes can be converted automatically to/from 2-element # sequences. c.addCppMethod('bool', '__eq__', '(const wxPoint& other)', body="return *self == *other;") c.addCppMethod('bool', '__neq__', '(const wxPoint& other)', body="return *self != *other;") c.addItem(etgtools.WigCode("""\ wxPoint operator+(const wxPoint& other); wxPoint operator-(); wxPoint operator-(const wxPoint& other); wxPoint operator*(int i); wxPoint operator/(int i); """)) # wxPoint typemap c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxPoint') c.addCppMethod('PyObject*', 'Get', '()', """\ return sipBuildResult(0, "(ii)", self->x, self->y); """, pyArgsString="() -> (x,y)", briefDoc="Return the x and y properties as a tuple.") # Add sequence protocol methods and other goodies c.addPyMethod('__str__', '(self)', 'return str(self.Get())') c.addPyMethod('__repr__', '(self)', 'return "wx.Point"+str(self.Get())') c.addPyMethod('__len__', '(self)', 'return len(self.Get())') c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0)') c.addPyMethod('__reduce__', '(self)', 'return (Point, self.Get())') c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]') c.addPyMethod('__setitem__', '(self, idx, val)', """\ if idx == 0: self.x = val elif idx == 1: self.y = val else: raise IndexError """) c.addPyCode('Point.__safe_for_unpickling__ = True') module.addItem( tools.wxListWrapperTemplate('wxPointList', 'wxPoint', module, includeConvertToType=True)) #--------------------------------------- # wxSize tweaks c = module.find('wxSize') tools.addAutoProperties(c) # Used for testing releasing or holding the GIL in giltest.py #c.find('wxSize').findOverload('int width, int height').releaseGIL() #c.find('DecBy').findOverload('int dx, int dy').releaseGIL() #c.find('IncBy').findOverload('int dx, int dy').releaseGIL() c.addProperty("width GetWidth SetWidth") c.addProperty("height GetHeight SetHeight") # TODO: How prevalent is the use of x,y properties on a size object? Can we deprecate them? c.addProperty("x GetWidth SetWidth") c.addProperty("y GetHeight SetHeight") # Take care of the same issues as wxPoint tools.ignoreAllOperators(c) for f in c.find('operator+=').all() + \ c.find('operator-=').all() + \ c.find('operator*=').all() + \ c.find('operator/=').all(): f.ignore(False) c.addCppMethod('bool', '__eq__', '(const wxSize& other)', body="return *self == *other;") c.addCppMethod('bool', '__neq__', '(const wxSize& other)', body="return *self != *other;") c.addItem(etgtools.WigCode("""\ wxSize operator+(const wxSize& other); wxSize operator-(const wxSize& other); wxSize operator*(int i); wxSize operator/(int i); wxPoint operator+(const wxPoint& other); wxPoint operator-(const wxPoint& other); wxRealPoint operator+(const wxRealPoint& other); wxRealPoint operator-(const wxRealPoint& other); """)) # wxSize typemap c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxSize') c.addCppMethod('PyObject*', 'Get', '()', """\ return sipBuildResult(0, "(ii)", self->GetWidth(), self->GetHeight()); """, pyArgsString="() -> (width, height)", briefDoc="Return the width and height properties as a tuple.") # Add sequence protocol methods and other goodies c.addPyMethod('__str__', '(self)', 'return str(self.Get())') c.addPyMethod('__repr__', '(self)', 'return "wx.Size"+str(self.Get())') c.addPyMethod('__len__', '(self)', 'return len(self.Get())') c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0)') c.addPyMethod('__reduce__', '(self)', 'return (Size, self.Get())') c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]') c.addPyMethod('__setitem__', '(self, idx, val)', """\ if idx == 0: self.width = val elif idx == 1: self.height = val else: raise IndexError """) c.addPyCode('Size.__safe_for_unpickling__ = True') #--------------------------------------- # wxRect tweaks c = module.find('wxRect') assert isinstance(c, etgtools.ClassDef) tools.addAutoProperties(c) c.addProperty("left GetLeft SetLeft") c.addProperty("top GetTop SetTop") c.addProperty("right GetRight SetRight") c.addProperty("bottom GetBottom SetBottom") c.addProperty("bottomLeft GetBottomLeft SetBottomLeft") c.addProperty("bottomRight GetBottomRight SetBottomRight") c.addProperty("topLeft GetTopLeft SetTopLeft") c.addProperty("topRight GetTopRight SetTopRight") # take care of the same issues as wxPoint tools.ignoreAllOperators(c) for f in c.find('operator+=').all() + \ c.find('operator*=').all(): f.ignore(False) c.addCppMethod('bool', '__eq__', '(const wxRect& other)', body="return *self == *other;") c.addCppMethod('bool', '__neq__', '(const wxRect& other)', body="return *self != *other;") c.addItem(etgtools.WigCode("""\ wxRect operator+(const wxRect& other); wxRect operator*(const wxRect& other); """)) # Because of our add-ons that make wx.Point and wx.Size act like 2-element # sequences, and also the typecheck code that allows 2-element sequences, then # we end up with a bit of confusion about the (Point,Point) and the # (Point,Size) overloads of the wx.Rect constructor. The confusion can be # dealt with by using keyword args, but I think that the (Point,Size) version # will be used more, so reorder the overloads so it is found first. m = module.find('wxRect.wxRect') mo = m.findOverload('topLeft') del m.overloads[m.overloads.index(mo)] m.overloads.append(mo) # These methods have some overloads that will end up with the same signature # in Python, so we have to remove one. module.find('wxRect.Deflate').findOverload(') const').ignore() module.find('wxRect.Inflate').findOverload(') const').ignore() module.find('wxRect.Union').findOverload(') const').ignore() module.find('wxRect.Intersect').findOverload(') const').ignore() # wxRect typemap c.convertFromPyObject = tools.convertFourIntegersTemplate('wxRect') c.addCppMethod('PyObject*', 'Get', '()', """\ return sipBuildResult(0, "(iiii)", self->x, self->y, self->width, self->height); """, pyArgsString="() -> (x, y, width, height)", briefDoc="Return the rectangle's properties as a tuple.") # Add sequence protocol methods and other goodies c.addPyMethod('__str__', '(self)', 'return str(self.Get())') c.addPyMethod('__repr__', '(self)', 'return "wx.Rect"+str(self.Get())') c.addPyMethod('__len__', '(self)', 'return len(self.Get())') c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0,0,0)') c.addPyMethod('__reduce__', '(self)', 'return (Rect, self.Get())') c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]') c.addPyMethod('__setitem__', '(self, idx, val)', """\ if idx == 0: self.x = val elif idx == 1: self.y = val elif idx == 2: self.width = val elif idx == 3: self.height = val else: raise IndexError """) c.addPyCode('Rect.__safe_for_unpickling__ = True') #--------------------------------------- # wxRealPoint tweaks c = module.find('wxRealPoint') tools.addAutoProperties(c) # take care of the same issues as wxPoint tools.ignoreAllOperators(c) for f in c.find('operator+=').all() + \ c.find('operator-=').all(): f.ignore(False) c.addCppMethod('bool', '__eq__', '(const wxRealPoint& other)', body="return *self == *other;") c.addCppMethod('bool', '__neq__', '(const wxRealPoint& other)', body="return *self != *other;") c.addItem(etgtools.WigCode("""\ wxRealPoint operator+(const wxRealPoint& other); wxRealPoint operator-(const wxRealPoint& other); wxRealPoint operator*(int i); wxRealPoint operator/(int i); """)) # wxRealPoint typemap c.convertFromPyObject = tools.convertTwoDoublesTemplate('wxRealPoint') c.addCppMethod('PyObject*', 'Get', '()', """\ return sipBuildResult(0, "(dd)", self->x, self->y); """, pyArgsString="() -> (x, y)", briefDoc="Return the point's properties as a tuple.") # Add sequence protocol methods and other goodies c.addPyMethod('__str__', '(self)', 'return str(self.Get())') c.addPyMethod('__repr__', '(self)', 'return "wx.RealPoint"+str(self.Get())') c.addPyMethod('__len__', '(self)', 'return len(self.Get())') c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0)') c.addPyMethod('__reduce__', '(self)', 'return (Rect, self.Get())') c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]') c.addPyMethod('__setitem__', '(self, idx, val)', """\ if idx == 0: self.x = val elif idx == 1: self.y = val else: raise IndexError """) c.addPyCode('RealPoint.__safe_for_unpickling__ = True') c = module.find('wxColourDatabase') c.addPyMethod('FindColour', '(self, colour)', 'return self.Find(colour)') module.find('wxTheColourDatabase').ignore() #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. module.addHeaderCode('#include <wx/richtext/richtextbuffer.h>') module.addItem( tools.wxArrayWrapperTemplate('wxRichTextRangeArray', 'wxRichTextRange', module)) module.addItem( tools.wxArrayWrapperTemplate('wxRichTextAttrArray', 'wxRichTextAttr', module)) module.addItem( tools.wxArrayWrapperTemplate('wxRichTextVariantArray', 'wxVariant', module)) module.addItem( tools.wxListWrapperTemplate('wxRichTextObjectList', 'wxRichTextObject', module)) module.addItem( tools.wxListWrapperTemplate('wxRichTextLineList', 'wxRichTextLine', module)) # Can this even work? Apparently it does. module.addItem( tools.wxArrayPtrWrapperTemplate('wxRichTextObjectPtrArray', 'wxRichTextObject', module)) module.addItem( tools.wxArrayWrapperTemplate('wxRichTextObjectPtrArrayArray', 'wxRichTextObjectPtrArray', module)) module.find('wxRICHTEXT_ALL').ignore() module.find('wxRICHTEXT_NONE').ignore() module.find('wxRICHTEXT_NO_SELECTION').ignore() code = etgtools.PyCodeDef("""\ RICHTEXT_ALL = RichTextRange(-2, -2) RICHTEXT_NONE = RichTextRange(-1, -1) RICHTEXT_NO_SELECTION = RichTextRange(-2, -2) """) module.insertItemAfter(module.find('wxRichTextRange'), code) module.insertItem(0, etgtools.WigCode("""\ // forward declarations class wxRichTextFloatCollector; """)) #------------------------------------------------------- c = module.find('wxTextAttrDimension') assert isinstance(c, etgtools.ClassDef) c.find('SetValue').findOverload('units').ignore() c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrDimensions') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrSize') tools.ignoreConstOverloads(c) c.find('SetWidth').findOverload('units').ignore() c.find('SetHeight').findOverload('units').ignore() c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrBorder') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrBorders') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") #------------------------------------------------------- c = module.find('wxTextAttrShadow') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxTextBoxAttr') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextAttr') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextProperties') tools.ignoreConstOverloads(c) c.find('SetProperty').findOverload('bool').ignore() c.find('operator[]').ignore() #------------------------------------------------------- c = module.find('wxRichTextSelection') tools.ignoreConstOverloads(c) c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();") c.find('operator[]').ignore() #------------------------------------------------------- def _fixDrawObject(c, addMissingVirtuals=True): assert isinstance(c, etgtools.ClassDef) if c.findItem('HitTest'): c.find('HitTest.textPosition').out = True c.find('HitTest.obj').out = True c.find('HitTest.contextObj').out = True if c.findItem('FindPosition'): c.find('FindPosition.pt').out = True c.find('FindPosition.height').out = True if c.findItem('GetBoxRects'): c.find('GetBoxRects.marginRect').out = True c.find('GetBoxRects.borderRect').out = True c.find('GetBoxRects.contentRect').out = True c.find('GetBoxRects.paddingRect').out = True c.find('GetBoxRects.outlineRect').out = True if c.findItem('GetTotalMargin'): c.find('GetTotalMargin.leftMargin').out = True c.find('GetTotalMargin.rightMargin').out = True c.find('GetTotalMargin.topMargin').out = True c.find('GetTotalMargin.bottomMargin').out = True if c.findItem('CalculateRange'): c.find('CalculateRange.end').out = True # TODO: should it be an inOut? # This are the pure virtuals in the base class. SIP needs to see that # all the drived classes have an implementation, otherwise it will # consider them to be ABCs/ if not c.findItem('Draw') and addMissingVirtuals: c.addItem(etgtools.WigCode("""\ virtual bool Draw(wxDC& dc, wxRichTextDrawingContext& context, const wxRichTextRange& range, const wxRichTextSelection& selection, const wxRect& rect, int descent, int style);""")) if not c.findItem('Layout') and addMissingVirtuals: c.addItem(etgtools.WigCode("""\ virtual bool Layout(wxDC& dc, wxRichTextDrawingContext& context, const wxRect& rect, const wxRect& parentRect, int style);""")) # TODO: Some of these args are output parameters. How should they be dealt with? if not c.findItem('GetRangeSize') and addMissingVirtuals: c.addItem(etgtools.WigCode("""\ virtual bool GetRangeSize(const wxRichTextRange& range, wxSize& size, int& descent, wxDC& dc, wxRichTextDrawingContext& context, int flags, const wxPoint& position = wxPoint(0,0), const wxSize& parentSize = wxDefaultSize, wxArrayInt* partialExtents = NULL) const;""")) #------------------------------------------------------- c = module.find('wxRichTextObject') #c.find('ImportFromXML').ignore() tools.ignoreConstOverloads(c) _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextCompositeObject') tools.ignoreConstOverloads(c) _fixDrawObject(c, addMissingVirtuals=False) #------------------------------------------------------- c = module.find('wxRichTextParagraphLayoutBox') tools.ignoreConstOverloads(c) _fixDrawObject(c) c.find('MoveAnchoredObjectToParagraph.from').name = 'from_' c.find('MoveAnchoredObjectToParagraph.to').name = 'to_' c.find('DoNumberList.def').name = 'styleDef' c.find('SetListStyle.def').name = 'styleDef' #------------------------------------------------------- c = module.find('wxRichTextBox') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextField') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextLine') tools.ignoreConstOverloads(c) c.find('SetRange.from').name = 'from_' c.find('SetRange.to').name = 'to_' #------------------------------------------------------- c = module.find('wxRichTextParagraph') _fixDrawObject(c) # These methods use an untyped wxList, but since we know what is in it # we'll make a fake typed list for wxPython so we can know what kinds of # values to get from it. module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextObject', module, fakeListClassName='wxRichTextObjectList_')) c.find('MoveToList.list').type = 'wxRichTextObjectList_&' c.find('MoveFromList.list').type = 'wxRichTextObjectList_&' #------------------------------------------------------- c = module.find('wxRichTextPlainText') _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextImage') tools.ignoreConstOverloads(c) _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextBuffer') tools.ignoreConstOverloads(c) _fixDrawObject(c) # More untyped wxLists module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextFileHandler', module, fakeListClassName='wxRichTextFileHandlerList')) c.find('GetHandlers').type = 'wxRichTextFileHandlerList&' c.find('GetHandlers').noCopy = True module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextDrawingHandler', module, fakeListClassName='wxRichTextDrawingHandlerList')) c.find('GetDrawingHandlers').type = 'wxRichTextDrawingHandlerList&' c.find('GetDrawingHandlers').noCopy = True # TODO: Need a template to wrap STRING_HASH_MAP c.find('GetFieldTypes').ignore() c.find('AddHandler.handler').transfer = True c.find('InsertHandler.handler').transfer = True c.find('AddDrawingHandler.handler').transfer = True c.find('InsertDrawingHandler.handler').transfer = True c.find('AddFieldType.fieldType').transfer = True # TODO: Transfer ownership with AddEventHandler? TransferBack with Remove? #------------------------------------------------------- c = module.find('wxRichTextTable') tools.ignoreConstOverloads(c) _fixDrawObject(c) #------------------------------------------------------- c = module.find('wxRichTextObjectAddress') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextCommand') module.addItem( tools.wxListWrapperTemplate('wxList', 'wxRichTextAction', module, fakeListClassName='wxRichTextActionList')) c.find('GetActions').type = 'wxRichTextActionList&' c.find('GetActions').noCopy = True c.find('AddAction.action').transfer = True #------------------------------------------------------- c = module.find('wxRichTextAction') tools.ignoreConstOverloads(c) #------------------------------------------------------- c = module.find('wxRichTextFileHandler') c.find('DoLoadFile').ignore(False) c.find('DoSaveFile').ignore(False) c = module.find('wxRichTextPlainTextHandler') c.find('DoLoadFile').ignore(False) c.find('DoSaveFile').ignore(False) #------------------------------------------------------- # Ignore all Dump() methods since we don't wrap wxTextOutputStream. # TODO: try swithcing the parameter type to wxOutputStream and then in # the wrapper code create a wxTextOutputStream from that to pass on to # Dump. for m in module.findAll('Dump'): if m.findItem('stream'): m.ignore() #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. c = module.find('wxAnimationCtrl') tools.fixWindowClass(c) # Grab some MethodDefs that need to be copied to wxGenericAnimationCtrl play = c.find('Play') play.isVirtual = True others = [ c.find('Stop'), c.find('IsPlaying'), c.find('Load'), c.find('LoadFile'), c.find('GetAnimation'), c.find('SetAnimation'), c.find('SetInactiveBitmap'), c.find('GetInactiveBitmap'), c.find('CreateAnimation'), c.find('CreateCompatibleAnimation'), ] nonvirtual = [ 'GetAnimation', 'GetInactiveBitmap', 'CreateAnimation', 'CreateCompatibleAnimation', ] c = module.find('wxGenericAnimationCtrl') c.bases = ['wxControl'] c.addHeaderCode('#include <wx/generic/animate.h>') tools.fixWindowClass(c) # Insert a copy of the base class Play into this class. It's not in the # interface docs, but sip needs to see it there, since the one that is there # has a different signature. c.find('Play').overloads.append(play) # Since we pretend that the base class is wxControl (because there are # different parents in different builds) then we need to copy in some # methods it will be inheriting from the real base class, which is not # public. for m in others: if m.name not in nonvirtual: m.isVirtual = True c.addItem(m) module.addGlobalStr('wxAnimationCtrlNameStr', c) # move this before wxAnimationCtrl so it can be used for default arg values item = module.find('wxNullAnimation') module.items.remove(item) module.insertItemBefore(c, item) #----------------------------------------------------------------- module.addItem( tools.wxListWrapperTemplate('wxAnimationDecoderList', 'wxAnimationDecoder', module, header_extra='#include <wx/animate.h>')) c = module.find('wxAnimationDecoder') c.find('DoCanRead').ignore(False) c = module.find('wxANIDecoder') c.find('DoCanRead').ignore(False) c = module.find('wxGIFDecoder') c.find('DoCanRead').ignore(False) #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. c = module.find('wxMenuItem') assert isinstance(c, etgtools.ClassDef) c.addPrivateCopyCtor() tools.removeVirtuals(c) c.find('wxMenuItem.subMenu').transfer = True c.find('SetSubMenu.menu').transfer = True # deprecated and removed c.find('GetLabel').ignore() c.find('GetName').ignore() c.find('GetText').ignore() c.find('SetText').ignore() c.find('GetLabelFromText').ignore() # These are MSW only. Make them be empty stubs for the other ports. Several # have incorrect details in the interface docs, so we need to tweak their # return types too. c.find('GetBackgroundColour').type = 'wxColour*' c.find('GetBackgroundColour').factory = True c.find('GetBackgroundColour').setCppCode("""\ #ifdef __WXMSW__ return new wxColor(self->GetBackgroundColour()); #else return new wxColour; #endif """) c.find('SetBackgroundColour').setCppCode("""\ #ifdef __WXMSW__ self->SetBackgroundColour(*colour); #endif """) c.find('GetFont').type = 'wxFont*' c.find('GetFont').factory = True c.find('GetFont').setCppCode("""\ #ifdef __WXMSW__ return new wxFont(self->GetFont()); #else return new wxFont; #endif """) c.find('SetFont').setCppCode("""\ #ifdef __WXMSW__ self->SetFont(*font); #endif """) c.find('GetMarginWidth').setCppCode("""\ #ifdef __WXMSW__ return self->GetMarginWidth(); #else return -1; #endif """) c.find('SetMarginWidth').setCppCode("""\ #ifdef __WXMSW__ self->SetMarginWidth(width); #endif """) c.find('GetTextColour').type = 'wxColour*' c.find('GetTextColour').factory = True c.find('GetTextColour').setCppCode("""\ #ifdef __WXMSW__ return new wxColour(self->GetTextColour()); #else return new wxColour; #endif """) c.find('SetTextColour').setCppCode("""\ #ifdef __WXMSW__ self->SetTextColour(*colour); #endif """) c.find('GetBitmap').type = 'wxBitmap*' c.find('GetBitmap').factory = True c.find('GetBitmap').setCppCode("""\ #ifdef __WXMSW__ return new wxBitmap(self->GetBitmap(checked)); #else return new wxBitmap(self->GetBitmap()); // no checked arg in this case #endif """) c.find('SetBitmap').setCppCode("""\ #ifdef __WXMSW__ self->SetBitmap(*bmp, checked); #else self->SetBitmap(*bmp); // no checked arg in this case #endif """) c.find('SetBitmaps').setCppCode("""\ #ifdef __WXMSW__ self->SetBitmaps(*checked, *unchecked); #else self->SetBitmap(*checked); #endif """) c.find('GetDisabledBitmap').type = 'wxBitmap*' c.find('GetDisabledBitmap').factory = True c.find('GetDisabledBitmap').setCppCode("""\ #ifdef __WXMSW__ return new wxBitmap(self->GetDisabledBitmap()); #else return new wxBitmap; #endif """) c.find('SetDisabledBitmap').setCppCode("""\ #ifdef __WXMSW__ self->SetDisabledBitmap(*disabled); #endif """) c.addAutoProperties() c.addItem(etgtools.PropertyDef('Enabled', 'IsEnabled', 'Enable')) c.find('GetAccel').factory = True c.find('GetAccelFromString').ignore() # Not implemented anywhere? module.addItem( tools.wxListWrapperTemplate('wxMenuItemList', 'wxMenuItem', module)) # Documented wrongly in 3.1.6 c.find('AddExtraAccel.accel').isConst = True c.find('AddExtraAccel.accel').type = 'wxAcceleratorEntry&' #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. c = module.find('wxSizerItem') assert isinstance(c, etgtools.ClassDef) tools.removeVirtuals(c) # ctors taking a sizer transfer ownership for m in c.find('wxSizerItem').all(): if m.findItem('sizer'): m.find('sizer').transfer = True c.find('AssignSizer.sizer').transfer = True # userData args transfer ownership too, and we'll use wxPyUserData # instead of any wxObject for m in c.allItems(): if isinstance(m, etgtools.MethodDef) and m.findItem('userData'): m.find('userData').transfer = True m.find('userData').type = 'wxPyUserData*' gud = c.find('GetUserData') gud.type = 'wxPyUserData*' gud.setCppCode('return dynamic_cast<wxPyUserData*>(self->GetUserData());') # these have been deprecated for a while so go ahead and get rid of them c.find('SetWindow').ignore() c.find('SetSizer').ignore() c.find('SetSpacer').ignore() c.addPrivateCopyCtor() #--------------------------------------------- c = module.find('wxSizer') assert isinstance(c, etgtools.ClassDef) tools.fixSizerClass(c) c.addPrivateCopyCtor() c.addPrivateAssignOp() for func in c.findAll('Add') + c.findAll('Insert') + c.findAll('Prepend'): if func.findItem('sizer'): func.find('sizer').transfer = True if func.findItem('userData'): func.find('userData').transfer = True func.find('userData').type = 'wxPyUserData*' if func.findItem('item'): func.find('item').transfer = True c.find('GetChildren').overloads = [] c.find('GetChildren').noCopy = True # Needs wxWin 2.6 compatibility c.find('Remove').findOverload('(wxWindow *window)').ignore() c.addPyMethod('AddMany', '(self, items)', doc="""\ :meth:`AddMany` is a convenience method for adding several items to a sizer at one time. Simply pass it a list of tuples, where each tuple consists of the parameters that you would normally pass to the :meth:`Add` method. """, body="""\ for item in items: if not isinstance(item, (tuple, list)): item = (item, ) self.Add(*item) """) c.addCppMethod('wxSizerItem*', 'Add', '(const wxSize& size, int proportion=0, int flag=0, ' 'int border=0, wxPyUserData* userData /Transfer/ = NULL)', doc="Add a spacer using a :class:`Size` object.", body="return self->Add(size->x, size->y, proportion, flag, border, userData);") c.addCppMethod('wxSizerItem*', 'Prepend', '(const wxSize& size, int proportion=0, int flag=0, ' 'int border=0, wxPyUserData* userData /Transfer/ = NULL)', doc="Prepend a spacer using a :class:`Size` object.", body="return self->Prepend(size->x, size->y, proportion, flag, border, userData);") c.addCppMethod('wxSizerItem*', 'Insert', '(size_t index, const wxSize& size, int proportion=0, int flag=0, ' 'int border=0, wxPyUserData* userData /Transfer/ = NULL)', doc="Insert a spacer using a :class:`Size` object.", body="return self->Insert(index, size->x, size->y, proportion, flag, border, userData);") c.addCppMethod('wxSizerItem*', 'Add', '(const wxSize& size, const wxSizerFlags& flags)', doc="Add a spacer using a :class:`Size` object.", body="return self->Add(size->x, size->y, *flags);") c.addCppMethod('wxSizerItem*', 'Prepend', '(const wxSize& size, const wxSizerFlags& flags)', doc="Prepend a spacer using a :class:`Size` object.", body="return self->Prepend(size->x, size->y, *flags);") c.addCppMethod('wxSizerItem*', 'Insert', '(size_t index, const wxSize& size, const wxSizerFlags& flags)', doc="Insert a spacer using a :class:`Size` object.", body="return self->Insert(index, size->x, size->y, *flags);") c.addPyMethod('__nonzero__', '(self)', doc="Can be used to test if the C++ part of the sizer still exists, with \n" "code like this::\n\n" " if theSizer:\n" " doSomething()", body="""\ import wx.siplib return not wx.siplib.isdeleted(self) """) c.addPyCode('Sizer.__bool__ = Sizer.__nonzero__') # For Python 3 #--------------------------------------------- c = module.find('wxBoxSizer') tools.fixSizerClass(c) c.find('wxBoxSizer.orient').default = 'wxHORIZONTAL' #--------------------------------------------- c = module.find('wxStaticBoxSizer') tools.fixSizerClass(c) c.find('wxStaticBoxSizer.orient').default = 'wxHORIZONTAL' #--------------------------------------------- c = module.find('wxGridSizer') tools.fixSizerClass(c) c.addPyMethod('CalcRowsCols', '(self)', doc="""\ CalcRowsCols() -> (rows, cols) Calculates how many rows and columns will be in the sizer based on the current number of items and also the rows, cols specified in the constructor. """, body="""\ nitems = len(self.GetChildren()) rows = self.GetRows() cols = self.GetCols() assert rows != 0 or cols != 0, "Grid sizer must have either rows or columns fixed" if cols != 0: rows = (nitems + cols - 1) / cols elif rows != 0: cols = (nitems + rows - 1) / rows return (rows, cols) """) #--------------------------------------------- c = module.find('wxFlexGridSizer') tools.fixSizerClass(c) #--------------------------------------------- c = module.find('wxStdDialogButtonSizer') tools.fixSizerClass(c) module.addPyCode("PySizer = wx.deprecated(Sizer, 'Use Sizer instead.')") module.addItem(tools.wxListWrapperTemplate('wxSizerItemList', 'wxSizerItem', module)) #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. def addTransferAnnotations(c, arg): for method in c.findAll('Append') + c.findAll('Insert') + \ c.findAll('Replace') + c.findAll('Prepend'): arg_def = method.findItem(arg) if arg_def: arg_def.transfer = True for method in c.findAll('Remove') + c.findAll('Replace'): method.transferBack = True #----------------------------------------------------------------- c = module.find('wxMenu') assert isinstance(c, etgtools.ClassDef) c.mustHaveApp() tools.removeVirtuals(c) c.find('Prepend.item').name = 'menuItem' c.find('Prepend.submenu').name = 'subMenu' addTransferAnnotations(c, 'menuItem') addTransferAnnotations(c, 'subMenu') c.find('AppendSubMenu.submenu').transfer = True # We only need one of these overloads, the non-const/const is not enough # to distinguish a unique Python signature. c.find('GetMenuItems').overloads = [] # Ensure that no copy is made of the list object, so we only wrap the # existing object and keep it owned by C++ c.find('GetMenuItems').noCopy = True c.addPyMethod('AppendMenu', '(self, id, item, subMenu, help="")', deprecated='Use Append instead.', body='return self.Append(id, item, subMenu, help)') c.addPyMethod('AppendItem', '(self, menuItem)', deprecated='Use Append instead.', body='return self.Append(menuItem)') c.addPyMethod('InsertMenu', '(self, pos, id, item, subMenu, help="")', deprecated='Use Insert instead.', body='return self.Insert(pos, id, item, subMenu, help)') c.addPyMethod('InsertItem', '(self, pos, menuItem)', deprecated='Use Insert instead.', body='return self.Insert(pos, menuItem)') c.addPyMethod('PrependMenu', '(self, id, item, subMenu, help="")', deprecated='Use Prepend instead.', body='return self.Prepend(id, item, subMenu, help)') c.addPyMethod('PrependItem', '(self, menuItem)', deprecated='Use Prepend instead.', body='return self.Prepend(menuItem)') c.addPyMethod('RemoveMenu', '(self, id, item, subMenu, help="")', deprecated='Use Remove instead.', body='return self.Remove(id, item, subMenu, help)') c.addPyMethod('RemoveItem', '(self, menuItem)', deprecated='Use Remove instead.', body='return self.Remove(menuItem)') # Don't hide the Destroy inherited from wxObject c.find('Destroy').findOverload('int').pyName = 'DestroyItem' c.find('Destroy').findOverload('wxMenuItem').pyName = 'DestroyItem' c.find('FindChildItem.pos').out = True c.find('FindItem.menu').out = True c.addCppMethod('wxMenuItem*', 'FindItemById', '(int id)', isConst=True, doc="""\ FindItemById(id) -> MenuItem Finds the menu item object associated with the given menu item identifier.""", body="""\ return self->FindItem(id);""") #----------------------------------------------------------------- c = module.find('wxMenuBar') assert isinstance(c, etgtools.ClassDef) c.mustHaveApp() tools.removeVirtuals(c) addTransferAnnotations(c, 'menu') c.find('wxMenuBar').findOverload('wxMenu *menus[], const wxString titles[], long style=0)').ignore() c.find('FindItem.menu').out = True c.addCppMethod('wxMenuItem*', 'FindItemById', '(int id)', isConst=True, doc="""\ FindItemById(id) -> MenuItem Finds the menu item object associated with the given menu item identifier.""", body="""\ return self->FindItem(id);""") mac_scmb = c.find('MacSetCommonMenuBar') mac_scmb.setCppCode("""\ #ifdef __WXMAC__ wxMenuBar::MacSetCommonMenuBar(menubar); #endif """) mac_gcmb = c.find('MacGetCommonMenuBar') mac_gcmb.setCppCode("""\ #ifdef __WXMAC__ return wxMenuBar::MacGetCommonMenuBar(); #else return NULL; #endif """) mac_gcmb = c.find('OSXGetAppleMenu') mac_gcmb.setCppCode("""\ #ifdef __WXMAC__ return self->OSXGetAppleMenu(); #else return NULL; #endif """) # don't transfer on other platforms, as this is a no-op there. import sys if sys.platform.startswith('darwin'): mac_scmb.find('menubar').transfer = True c.find('FindItem.menu').out = True c.addPyMethod('GetMenus', '(self)', doc="""\ GetMenus() -> (menu, label)\n Return a list of (menu, label) items for the menus in the :class:`MenuBar`.""", body="""\ return [(self.GetMenu(i), self.GetLabelTop(i)) for i in range(self.GetMenuCount())] """) c.addPyMethod('SetMenus', '(self, items)', doc="""\ SetMenus()\n Clear and add new menus to the :class:`MenuBar` from a list of (menu, label) items.""", body="""\ for i in range(self.GetMenuCount()-1, -1, -1): self.Remove(i) for m, l in items: self.Append(m, l) """) c.addPyProperty('Menus GetMenus SetMenus') module.addItem(tools.wxListWrapperTemplate('wxMenuList', 'wxMenu', module)) #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. # ignore some of these enum values e = module.find('wxBitmapType') for i in e: if i.name.endswith('_RESOURCE'): i.ignore() module.addCppCode("""\ #if !defined(__WXMAC__) #define wxCURSOR_COPY_ARROW wxCURSOR_ARROW #endif """) # these are X11 only e = module.find('wxStockCursor') e.find('wxCURSOR_BASED_ARROW_DOWN').ignore() e.find('wxCURSOR_BASED_ARROW_UP').ignore() e.find('wxCURSOR_CROSS_REVERSE').ignore() e.find('wxCURSOR_DOUBLE_ARROW').ignore() module.find('wxClientDisplayRect.x').out = True module.find('wxClientDisplayRect.y').out = True module.find('wxClientDisplayRect.width').out = True module.find('wxClientDisplayRect.height').out = True module.find('wxDisplaySize.width').out = True module.find('wxDisplaySize.height').out = True module.find('wxDisplaySizeMM.width').out = True module.find('wxDisplaySizeMM.height').out = True #--------------------------------------- # wxPoint tweaks c = module.find('wxPoint') tools.addAutoProperties(c) # Some operators are documented within the class that shouldn't be, so just # ignore them all. tools.ignoreAllOperators(c) # Undo a few of those ignores for legitimate items that were # documented correctly for f in c.find('operator+=').all() + c.find('operator-=').all(): f.ignore(False) # Add some method declarations for operators that really do exist. Note # that these actually use C++ global operator functions, but we treat # them as methods to help disambiguate implementations due to how # multiple classes can be converted automatically to/from 2-element # sequences. c.addCppMethod('bool', '__eq__', '(const wxPoint& other)', body="return *self == *other;") c.addCppMethod('bool', '__ne__', '(const wxPoint& other)', body="return *self != *other;") c.addItem( etgtools.WigCode("""\ wxPoint operator+(const wxPoint& other); wxPoint operator+(const wxSize& other); wxPoint operator-(); wxPoint operator-(const wxPoint& other); wxPoint operator-(const wxSize& other); wxPoint operator*(int i); wxPoint operator/(int i); """)) # wxPoint typemap c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxPoint') c.addCppMethod('PyObject*', 'Get', '()', """\ wxPyThreadBlocker blocker; return sipBuildResult(0, "(ii)", self->x, self->y); """, pyArgsString="() -> (x,y)", briefDoc="Return the x and y properties as a tuple.") tools.addGetIMMethodTemplate(module, c, ['x', 'y']) # Add sequence protocol methods and other goodies c.addPyMethod('__str__', '(self)', 'return str(self.Get())') c.addPyMethod('__repr__', '(self)', 'return "wx.Point"+str(self.Get())') c.addPyMethod('__len__', '(self)', 'return len(self.Get())') c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0)') c.addPyMethod('__reduce__', '(self)', 'return (Point, self.Get())') c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]') c.addPyMethod( '__setitem__', '(self, idx, val)', """\ if idx == 0: self.x = val elif idx == 1: self.y = val else: raise IndexError """) c.addPyCode('Point.__safe_for_unpickling__ = True') module.addItem( tools.wxListWrapperTemplate('wxPointList', 'wxPoint', module, includeConvertToType=True)) #--------------------------------------- # wxSize tweaks c = module.find('wxSize') tools.addAutoProperties(c) # Used for testing releasing or holding the GIL in giltest.py #c.find('wxSize').findOverload('int width, int height').releaseGIL() #c.find('DecBy').findOverload('int dx, int dy').releaseGIL() #c.find('IncBy').findOverload('int dx, int dy').releaseGIL() c.addProperty("width GetWidth SetWidth") c.addProperty("height GetHeight SetHeight") # TODO: How prevalent is the use of x,y properties on a size object? Can we deprecate them? c.addProperty("x GetWidth SetWidth") c.addProperty("y GetHeight SetHeight") # Take care of the same issues as wxPoint tools.ignoreAllOperators(c) for f in c.find('operator+=').all() + \ c.find('operator-=').all() + \ c.find('operator*=').all() + \ c.find('operator/=').all(): f.ignore(False) c.addCppMethod('bool', '__eq__', '(const wxSize& other)', body="return *self == *other;") c.addCppMethod('bool', '__ne__', '(const wxSize& other)', body="return *self != *other;") c.addItem( etgtools.WigCode("""\ wxSize operator+(const wxSize& other); wxSize operator-(const wxSize& other); wxSize operator*(int i); wxSize operator/(int i); wxPoint operator+(const wxPoint& other); wxPoint operator-(const wxPoint& other); wxRealPoint operator+(const wxRealPoint& other); wxRealPoint operator-(const wxRealPoint& other); """)) # wxSize typemap c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxSize') c.addCppMethod( 'PyObject*', 'Get', '()', """\ wxPyThreadBlocker blocker; return sipBuildResult(0, "(ii)", self->GetWidth(), self->GetHeight()); """, pyArgsString="() -> (width, height)", briefDoc="Return the width and height properties as a tuple.") tools.addGetIMMethodTemplate(module, c, ['width', 'height']) # Add sequence protocol methods and other goodies c.addPyMethod('__str__', '(self)', 'return str(self.Get())') c.addPyMethod('__repr__', '(self)', 'return "wx.Size"+str(self.Get())') c.addPyMethod('__len__', '(self)', 'return len(self.Get())') c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0)') c.addPyMethod('__reduce__', '(self)', 'return (Size, self.Get())') c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]') c.addPyMethod( '__setitem__', '(self, idx, val)', """\ if idx == 0: self.width = val elif idx == 1: self.height = val else: raise IndexError """) c.addPyCode('Size.__safe_for_unpickling__ = True') #--------------------------------------- # wxRect tweaks c = module.find('wxRect') assert isinstance(c, etgtools.ClassDef) tools.addAutoProperties(c) c.addProperty("left GetLeft SetLeft") c.addProperty("top GetTop SetTop") c.addProperty("right GetRight SetRight") c.addProperty("bottom GetBottom SetBottom") c.addProperty("bottomLeft GetBottomLeft SetBottomLeft") c.addProperty("bottomRight GetBottomRight SetBottomRight") c.addProperty("topLeft GetTopLeft SetTopLeft") c.addProperty("topRight GetTopRight SetTopRight") # take care of the same issues as wxPoint tools.ignoreAllOperators(c) for f in c.find('operator+=').all() + \ c.find('operator*=').all(): f.ignore(False) c.addCppMethod('bool', '__eq__', '(const wxRect& other)', body="return *self == *other;") c.addCppMethod('bool', '__ne__', '(const wxRect& other)', body="return *self != *other;") c.addItem( etgtools.WigCode("""\ wxRect operator+(const wxRect& other); wxRect operator*(const wxRect& other); """)) # Because of our add-ons that make wx.Point and wx.Size act like 2-element # sequences, and also the typecheck code that allows 2-element sequences, then # we end up with a bit of confusion about the (Point,Point) and the # (Point,Size) overloads of the wx.Rect constructor. The confusion can be # dealt with by using keyword args, but I think that the (Point,Size) version # will be used more, so reorder the overloads so it is found first. m = module.find('wxRect.wxRect') mo = m.findOverload('topLeft') del m.overloads[m.overloads.index(mo)] m.overloads.append(mo) # These methods have some overloads that will end up with the same signature # in Python, so we have to remove one. module.find('wxRect.Deflate').findOverload(') const').ignore() module.find('wxRect.Inflate').findOverload(') const').ignore() module.find('wxRect.Union').findOverload(') const').ignore() module.find('wxRect.Intersect').findOverload(') const').ignore() # wxRect typemap c.convertFromPyObject = tools.convertFourIntegersTemplate('wxRect') c.addCppMethod('PyObject*', 'Get', '()', """\ wxPyThreadBlocker blocker; return sipBuildResult(0, "(iiii)", self->x, self->y, self->width, self->height); """, pyArgsString="() -> (x, y, width, height)", briefDoc="Return the rectangle's properties as a tuple.") tools.addGetIMMethodTemplate(module, c, ['x', 'y', 'width', 'height']) # Add sequence protocol methods and other goodies c.addPyMethod('__str__', '(self)', 'return str(self.Get())') c.addPyMethod('__repr__', '(self)', 'return "wx.Rect"+str(self.Get())') c.addPyMethod('__len__', '(self)', 'return len(self.Get())') c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0,0,0)') c.addPyMethod('__reduce__', '(self)', 'return (Rect, self.Get())') c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]') c.addPyMethod( '__setitem__', '(self, idx, val)', """\ if idx == 0: self.x = val elif idx == 1: self.y = val elif idx == 2: self.width = val elif idx == 3: self.height = val else: raise IndexError """) c.addPyCode('Rect.__safe_for_unpickling__ = True') #--------------------------------------- # wxRealPoint tweaks c = module.find('wxRealPoint') tools.addAutoProperties(c) # take care of the same issues as wxPoint tools.ignoreAllOperators(c) for f in c.find('operator+=').all() + \ c.find('operator-=').all(): f.ignore(False) c.addCppMethod('bool', '__eq__', '(const wxRealPoint& other)', body="return *self == *other;") c.addCppMethod('bool', '__ne__', '(const wxRealPoint& other)', body="return *self != *other;") c.addItem( etgtools.WigCode("""\ wxRealPoint operator+(const wxRealPoint& other); wxRealPoint operator-(const wxRealPoint& other); wxRealPoint operator*(int i); wxRealPoint operator/(int i); """)) # wxRealPoint typemap c.convertFromPyObject = tools.convertTwoDoublesTemplate('wxRealPoint') c.addCppMethod('PyObject*', 'Get', '()', """\ wxPyThreadBlocker blocker; return sipBuildResult(0, "(dd)", self->x, self->y); """, pyArgsString="() -> (x, y)", briefDoc="Return the point's properties as a tuple.") tools.addGetIMMethodTemplate(module, c, ['x', 'y']) # Add sequence protocol methods and other goodies c.addPyMethod('__str__', '(self)', 'return str(self.Get())') c.addPyMethod('__repr__', '(self)', 'return "wx.RealPoint"+str(self.Get())') c.addPyMethod('__len__', '(self)', 'return len(self.Get())') c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0)') c.addPyMethod('__reduce__', '(self)', 'return (Rect, self.Get())') c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]') c.addPyMethod( '__setitem__', '(self, idx, val)', """\ if idx == 0: self.x = val elif idx == 1: self.y = val else: raise IndexError """) c.addPyCode('RealPoint.__safe_for_unpickling__ = True') c = module.find('wxColourDatabase') c.mustHaveApp() c.addPyMethod('FindColour', '(self, colour)', 'return self.Find(colour)') module.find('wxTheColourDatabase').ignore() #----------------------------------------------------------------- module.addCppFunction('PyObject*', 'IntersectRect', '(wxRect* r1, wxRect* r2)', doc="""\ Calculate and return the intersection of r1 and r2. Returns None if there is no intersection.""", body="""\ wxRegion reg1(*r1); wxRegion reg2(*r2); wxRect dest(0,0,0,0); PyObject* obj; reg1.Intersect(reg2); dest = reg1.GetBox(); wxPyThreadBlocker blocker; if (dest != wxRect(0,0,0,0)) { wxRect* newRect = new wxRect(dest); obj = wxPyConstructObject((void*)newRect, wxT("wxRect"), true); return obj; } Py_INCREF(Py_None); return Py_None; """) for funcname in [ 'wxColourDisplay', 'wxDisplayDepth', 'wxDisplaySize', 'wxGetDisplaySize', 'wxDisplaySizeMM', 'wxGetDisplaySizeMM', 'wxGetDisplayPPI', 'wxClientDisplayRect', 'wxGetClientDisplayRect', 'wxSetCursor', #'wxGetXDisplay', ]: c = module.find(funcname) c.mustHaveApp() #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)
def run(): # Parse the XML file(s) building a collection of Extractor objects module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING) etgtools.parseDoxyXML(module, ITEMS) #----------------------------------------------------------------- # Tweak the parsed meta objects in the module object as needed for # customizing the generated code and docstrings. c = module.find('wxWindow') assert isinstance(c, etgtools.ClassDef) module.addGlobalStr('wxPanelNameStr', c) # First we need to let the wrapper generator know about wxWindowBase since # AddChild and RemoveChild need to use that type in order to be virtualized. winbase = ClassDef(name='wxWindowBase', bases=['wxEvtHandler'], abstract=True, items=[MethodDef(name='AddChild', isVirtual=True, type='void', protection='public', items=[ParamDef(name='child', type='wxWindowBase*')]), MethodDef(name='RemoveChild', isVirtual=True, type='void', protection='public', items=[ParamDef(name='child', type='wxWindowBase*')]) ]) module.insertItemBefore(c, winbase) # Now change the base class of wxWindow c.bases = ['wxWindowBase'] # And fix the arg types we get from Doxy c.find('AddChild.child').type = 'wxWindowBase*' c.find('RemoveChild.child').type = 'wxWindowBase*' # We now return you to our regularly scheduled programming... c.includeCppCode('src/window_ex.cpp') # ignore some overloads that will be ambiguous afer wrapping c.find('GetChildren').overloads = [] c.find('GetChildren').noCopy = True c.find('GetClientSize').findOverload('int *').ignore() c.find('GetSize').findOverload('int *').ignore() c.find('GetVirtualSize').findOverload('int *').ignore() c.find('GetPosition').findOverload('int *').ignore() c.find('GetScreenPosition').findOverload('int *').ignore() c.find('ClientToScreen').findOverload('int *').ignore() c.find('ScreenToClient').findOverload('int *').ignore() # Release the GIL for potentially blocking or long-running functions c.find('PopupMenu').releaseGIL() c.find('ProcessEvent').releaseGIL() c.find('ProcessWindowEvent').releaseGIL() c.find('ProcessWindowEventLocally').releaseGIL() # Add a couple wrapper functions for symmetry with the getters of the same name c.addPyMethod('SetRect', '(self, rect)', 'return self.SetSize(rect)') c.addPyProperty('Rect GetRect SetRect') c.addPyMethod('SetClientRect', '(self, rect)', 'return self.SetClientSize(rect)') c.addPyProperty('ClientRect GetClientRect SetClientRect') m = c.find('GetTextExtent').findOverload('int *') m.pyName = 'GetFullTextExtent' m.find('w').out = True m.find('h').out = True m.find('descent').out = True m.find('externalLeading').out = True c.find('GetHandle').type = 'unsigned long' c.find('GetHandle').setCppCode("return wxPyGetWinHandle(self);") c.addCppMethod('void*', 'GetGtkWidget', '()', """\ #ifdef __WXGTK__ return (void*)self->GetHandle(); #else return NULL; #endif """) c.addCppMethod('void', 'AssociateHandle', '(long handle)', doc="Associate the window with a new native handle", body="self->AssociateHandle((WXWidget)handle);") c.addCppMethod('void', 'DissociateHandle', '()', doc="Dissociate the current native handle from the window", body="self->DissociateHandle();") # Add some new methods c.addCppMethod('wxWindow*', 'GetTopLevelParent', '()', 'return wxGetTopLevelParent(self);', briefDoc="Returns the first ancestor of this window which is a top-level window.") c.addCppMethod('bool', 'MacIsWindowScrollbar', '(const wxWindow* sb)', """\ #ifdef __WXMAC__ return self->MacIsWindowScrollbar(sb); #else return false; #endif """, pyArgsString="(sb)", briefDoc="Is the given widget one of this window's built-in scrollbars? Only applicable on Mac.") c.addCppMethod('void', 'SetDimensions', '(int x, int y, int width, int height, int sizeFlags=wxSIZE_AUTO)', pyArgsString="(x, y, width, height, sizeFlags=SIZE_AUTO)", body="""\ self->SetSize(x, y, width, height, sizeFlags); """) c.addPyCode("Window.SetDimensions = wx.deprecated(Window.SetDimensions, 'Use SetSize instead.')") # Make the Register/UnregisterHotKey functions be available on Windows, # and empty stubs otherwise c.find('RegisterHotKey').setCppCode("""\ #if wxUSE_HOTKEY return self->RegisterHotKey(hotkeyId, modifiers, virtualKeyCode); #else return false; #endif """) c.find('UnregisterHotKey').setCppCode("""\ #if wxUSE_HOTKEY return self->UnregisterHotKey(hotkeyId); #else return false; #endif """) c.find('RegisterHotKey').isVirtual = False c.find('UnregisterHotKey').isVirtual = False c.find('SetDoubleBuffered').setCppCode("""\ #if defined(__WXGTK20__) || defined(__WXMSW__) self->SetDoubleBuffered(on); #endif """) c.addPyMethod('__nonzero__', '(self)', doc="Can be used to test if the C++ part of the window still exists, with \n" "code like this::\n\n" " if theWindow:\n" " doSomething()", body="""\ import wx.siplib return not wx.siplib.isdeleted(self) """) c.addPyCode('Window.__bool__ = Window.__nonzero__') # For Python 3 c.addPyMethod('DestroyLater', '(self)', doc="""\ Schedules the window to be destroyed in the near future. This should be used whenever Destroy could happen too soon, such as when there may still be events for this window or its children waiting in the event queue. """, body="""\ self.Hide() wx.GetApp().ScheduleForDestruction(self) """) # MSW only. Do we want them wrapped? c.find('GetAccessible').ignore() c.find('SetAccessible').ignore() # Make some of the protected methods visible and overridable from Python c.find('SendDestroyEvent').ignore(False) c.find('Destroy').transferThis=True c.addPyMethod('PostCreate', '(self, pre)', 'pass', deprecated='PostCreate is no longer necessary.') # transfer ownership of these parameters to the C++ object c.find('SetCaret.caret').transfer = True c.find('SetToolTip.tip').transfer = True c.find('SetDropTarget.target').transfer = True c.find('SetConstraints.constraints').transfer = True c.find('SetSizer.sizer').transfer = True c.find('SetSizerAndFit.sizer').transfer = True # Define some properties using the getter and setter methods c.addProperty('AcceleratorTable GetAcceleratorTable SetAcceleratorTable') c.addProperty('AutoLayout GetAutoLayout SetAutoLayout') c.addProperty('BackgroundColour GetBackgroundColour SetBackgroundColour') c.addProperty('BackgroundStyle GetBackgroundStyle SetBackgroundStyle') c.addProperty('EffectiveMinSize GetEffectiveMinSize') c.addProperty('BestSize GetBestSize') c.addProperty('BestVirtualSize GetBestVirtualSize') c.addProperty('Border GetBorder') c.addProperty('Caret GetCaret SetCaret') c.addProperty('CharHeight GetCharHeight') c.addProperty('CharWidth GetCharWidth') c.addProperty('Children GetChildren') c.addProperty('ClientAreaOrigin GetClientAreaOrigin') c.addProperty('ClientSize GetClientSize SetClientSize') c.addProperty('Constraints GetConstraints SetConstraints') c.addProperty('ContainingSizer GetContainingSizer SetContainingSizer') c.addProperty('Cursor GetCursor SetCursor') c.addProperty('DefaultAttributes GetDefaultAttributes') c.addProperty('DropTarget GetDropTarget SetDropTarget') c.addProperty('EventHandler GetEventHandler SetEventHandler') c.addProperty('ExtraStyle GetExtraStyle SetExtraStyle') c.addProperty('Font GetFont SetFont') c.addProperty('ForegroundColour GetForegroundColour SetForegroundColour') c.addProperty('GrandParent GetGrandParent') c.addProperty('TopLevelParent GetTopLevelParent') c.addProperty('Handle GetHandle') c.addProperty('HelpText GetHelpText SetHelpText') c.addProperty('Id GetId SetId') c.addProperty('Label GetLabel SetLabel') c.addProperty('LayoutDirection GetLayoutDirection SetLayoutDirection') c.addProperty('MaxHeight GetMaxHeight') c.addProperty('MaxSize GetMaxSize SetMaxSize') c.addProperty('MaxWidth GetMaxWidth') c.addProperty('MinHeight GetMinHeight') c.addProperty('MinSize GetMinSize SetMinSize') c.addProperty('MinWidth GetMinWidth') c.addProperty('Name GetName SetName') c.addProperty('Parent GetParent') c.addProperty('Position GetPosition SetPosition') c.addProperty('ScreenPosition GetScreenPosition') c.addProperty('ScreenRect GetScreenRect') c.addProperty('Size GetSize SetSize') c.addProperty('Sizer GetSizer SetSizer') c.addProperty('ThemeEnabled GetThemeEnabled SetThemeEnabled') c.addProperty('ToolTip GetToolTip SetToolTip') c.addProperty('UpdateClientRect GetUpdateClientRect') c.addProperty('UpdateRegion GetUpdateRegion') c.addProperty('Validator GetValidator SetValidator') c.addProperty('VirtualSize GetVirtualSize SetVirtualSize') c.addProperty('WindowStyle GetWindowStyle SetWindowStyle') c.addProperty('WindowStyleFlag GetWindowStyleFlag SetWindowStyleFlag') c.addProperty('WindowVariant GetWindowVariant SetWindowVariant') c.addProperty('Shown IsShown Show') c.addProperty('Enabled IsEnabled Enable') c.addProperty('TopLevel IsTopLevel') c.addProperty('MinClientSize GetMinClientSize SetMinClientSize') c.addProperty('MaxClientSize GetMaxClientSize SetMaxClientSize') ##c.addProperty('GtkWidget GetGtkWidget') tools.fixWindowClass(c) tools.addSipConvertToSubClassCode(c) # for compatibility with Classic c.addPyMethod('GetPositionTuple', '(self)', 'return self.GetPosition()', deprecated='Use GetPosition instead') c.addPyMethod('MoveXY', '(self, x, y)', 'return self.Move(x, y)', deprecated='Use Move instead.') c.addPyMethod('SetSizeWH', '(self, w, h)', 'return self.SetSize(w,h)', deprecated='Use SetSize instead.') c.addPyMethod('SetVirtualSizeWH', '(self, w, h)', 'return self.SetVirtualSize(w,h)', deprecated='Use SetVirtualSize instead.') c.addPyMethod('GetVirtualSizeTuple', '(self)', 'return self.GetVirtualSize()', deprecated='Use GetVirtualSize instead.') c.addPyMethod('SetToolTipString', '(self, string)', 'return self.SetToolTip(string)', deprecated='Use SetToolTip instead.') c.addPyMethod('ConvertDialogPointToPixels', '(self, point)', 'return self.ConvertDialogToPixels(point)', deprecated='Use ConvertDialogToPixels instead.') c.addPyMethod('ConvertDialogSizeToPixels', '(self, size)', 'return self.ConvertDialogToPixels(point)', deprecated='Use ConvertDialogToPixels instead.') # this is a nested class c.find('ChildrenRepositioningGuard').addPrivateCopyCtor() module.insertItem(0, etgtools.TypedefDef(type='wxWindow::ChildrenRepositioningGuard', name='ChildrenRepositioningGuard')) #----------------------------------------------------------------------- # Other stuff module.addPyCode('''\ class FrozenWindow(object): """ A context manager to be used with Python 'with' statements that will freeze the given window for the duration of the with block. """ def __init__(self, window): self._win = window def __enter__(self): self._win.Freeze() return self def __exit__(self, exc_type, exc_val, exc_tb): self._win.Thaw() ''') # Add a wrapper for wxWindowList and a new iterator class for it that # makes wxWindowList quack like a read-only Python sequence. module.addItem(tools.wxListWrapperTemplate('wxWindowList', 'wxWindow', module)) module.addCppFunction('wxWindowList*', 'GetTopLevelWindows', '()', noCopy=True, briefDoc="Returns a list-like object of the the application's top-level windows, (frames,dialogs, etc.)", body="return &wxTopLevelWindows;") module.addPyCode("PyWindow = wx.deprecated(Window, 'Use Window instead.')") module.find('wxFindWindowAtPointer.pt').out = True module.addCppFunction('wxWindow*', 'FindWindowById', '(long id, const wxWindow* parent=NULL)', doc="""\ FindWindowById(id, parent=None) -> Window Find the first window in the application with the given id. If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases. """, body="return wxWindow::FindWindowById(id, parent);") module.addCppFunction('wxWindow*', 'FindWindowByName', '(const wxString& name, const wxWindow* parent=NULL)', doc="""\ FindWindowByName(name, parent=None) -> Window Find a window by its name (as given in a window constructor or Create function call). If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases. If no window with the name is found, wx.FindWindowByLabel is called.""", body="return wxWindow::FindWindowByName(*name, parent);") module.addCppFunction('wxWindow*', 'FindWindowByLabel', '(const wxString& label, const wxWindow* parent=NULL)', doc="""\ FindWindowByLabel(label, parent=None) -> Window Find a window by its label. Depending on the type of window, the label may be a window title or panel item label. If parent is None, the search will start from all top-level frames and dialog boxes; if non-None, the search will be limited to the given window hierarchy. The search is recursive in both cases.""", body="return wxWindow::FindWindowByLabel(*label, parent);") #----------------------------------------------------------------- tools.doCommonTweaks(module) tools.runGenerators(module)