Exemple #1
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)
    module.addHeaderCode('#include "wx/mediactrl.h"')

    #-----------------------------------------------------------------
    # Tweak the parsed meta objects in the module object as needed for
    # customizing the generated code and docstrings.

    c = module.find('wxMediaCtrl')
    c.addPrivateCopyCtor()

    c.find('wxMediaCtrl.id').default = '-1'
    c.find('Create.id').default = '-1'

    # the C++ class has three overloaded Load(...) methods
    # for now we ignore all than the first one for loading a filename
    for item in c.findAll("Load"):
        if not "fileName" in item.argsString:
            # ignore e.g. the Load with args '(const wxURI &uri)'
            # keep e.g. '(const wxString &fileName)'
            item.ignore()

            # Transplant the docstrings from the ignored Load methods into the
            # appropriate compatibility method
            if 'proxy' in item.argsString:
                m = c.find('LoadURIWithProxy')
            else:
                m = c.find('LoadURI')
            m.briefDoc = item.briefDoc
            m.detailedDoc = item.detailedDoc


    c = module.find('wxMediaEvent')
    tools.fixEventClass(c)

    module.addPyCode("""\
                EVT_MEDIA_LOADED = wx.PyEventBinder( wxEVT_MEDIA_LOADED )
                EVT_MEDIA_STOP = wx.PyEventBinder( wxEVT_MEDIA_STOP )
                EVT_MEDIA_FINISHED = wx.PyEventBinder( wxEVT_MEDIA_FINISHED )
                EVT_MEDIA_STATECHANGED = wx.PyEventBinder( wxEVT_MEDIA_STATECHANGED )
                EVT_MEDIA_PLAY = wx.PyEventBinder( wxEVT_MEDIA_PLAY )
                EVT_MEDIA_PAUSE = wx.PyEventBinder( wxEVT_MEDIA_PAUSE )
                """)


    # See mediactrl.h:
    module.addPyCode("""\
                MEDIABACKEND_DIRECTSHOW = "wxAMMediaBackend"
                MEDIABACKEND_MCI        = "wxMCIMediaBackend"
                MEDIABACKEND_QUICKTIME  = "wxQTMediaBackend"
                MEDIABACKEND_GSTREAMER  = "wxGStreamerMediaBackend"
                MEDIABACKEND_REALPLAYER = "wxRealPlayerMediaBackend"
                MEDIABACKEND_WMP10      = "wxWMP10MediaBackend"
                """)

    #-----------------------------------------------------------------
    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('wxHtmlDCRenderer')
    assert isinstance(c, etgtools.ClassDef)
    c.addPrivateCopyCtor()
    tools.fixHtmlSetFonts(c)
    
    c.find('Render.from').name = 'from_'
    c.find('Render.to').name = 'to_'
    
    c = module.find('wxHtmlEasyPrinting')
    c.addPrivateCopyCtor()
    
    c = module.find('wxHtmlPrintout')
    c.addPrivateCopyCtor()
    
    
    #-----------------------------------------------------------------
    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('wxRichTextHeaderFooterData')
    assert isinstance(c, etgtools.ClassDef)
    tools.ignoreAllOperators(c)
    
    
    c = module.find('wxRichTextPrintout')
    assert isinstance(c, etgtools.ClassDef)
    c.find('GetPageInfo.minPage').out = True
    c.find('GetPageInfo.maxPage').out = True
    c.find('GetPageInfo.selPageFrom').out = True
    c.find('GetPageInfo.selPageTo').out = True
    
    
    c = module.find('wxRichTextPrinting')
    assert isinstance(c, etgtools.ClassDef)
    c.addPrivateCopyCtor()
    
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #4
0
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/textdlg.h>")
    module.find('wxGetTextFromUserPromptStr').ignore()
    module.find('wxGetPasswordFromUserPromptStr').ignore()
    
    
    c = module.find('wxTextEntryDialog')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixTopLevelWindowClass(c)
    
    # We don't wrap wxTextValidator
    for m in c.find('SetTextValidator').all():
        m.ignore()    
    
    module.addGlobalStr('wxGetTextFromUserPromptStr', c)
    module.addGlobalStr('wxGetPasswordFromUserPromptStr', c)
        
    
    c = module.find('wxPasswordEntryDialog')
    tools.fixTopLevelWindowClass(c)
    
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #5
0
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('wxPopupWindow')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixWindowClass(c)
    c.find('Position').isVirtual = True
    

    c = module.find('wxPopupTransientWindow')
    tools.fixWindowClass(c)
    c.find('Dismiss').isVirtual = True
    c.find('ProcessLeftDown').isVirtual = True
    c.find('OnDismiss').ignore(False)
    c.find('OnDismiss').isVirtual = True
    
            
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #6
0
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('wxCheckBox')
    assert isinstance(c, etgtools.ClassDef)
    c.find('wxCheckBox.label').default = 'wxEmptyString'
    c.find('Create.label').default = 'wxEmptyString'

    module.addGlobalStr('wxCheckBoxNameStr', c)

    # Workaround warning for the property name starting with a digit
    c.find('Get3StateValue').ignore()
    c.addAutoProperties()
    c.find('Get3StateValue').ignore(False)
    c.addProperty('ThreeStateValue Get3StateValue Set3StateValue')

    tools.fixWindowClass(c)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #7
0
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('wxMDIClientWindow')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixWindowClass(c)
    c.find('CreateClient').isVirtual = True


    c = module.find('wxMDIParentFrame')
    tools.fixTopLevelWindowClass(c)
    c.find('OnCreateClient').isVirtual = True

    m = c.find('GetClientWindow')
    assert isinstance(m, etgtools.MethodDef)
    m.type = 'wxMDIClientWindow *'
    m.setCppCode("return static_cast<wxMDIClientWindow*>(self->GetClientWindow());")
    

    c = module.find('wxMDIChildFrame')
    tools.fixTopLevelWindowClass(c)
    
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #8
0
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/datectrl.h>")

    dpc = module.find('wxDatePickerCtrl')
    assert isinstance(dpc, etgtools.ClassDef)

    # Make a copy and call it wxDatePickerCtrlGeneric so we can generate
    # wrappers for both classes
    gdpc = tools.copyClassDef(dpc, 'wxDatePickerCtrlGeneric')
    assert isinstance(gdpc, etgtools.ClassDef)
    module.insertItemAfter(dpc, gdpc)
    # and give it a new Python name to match Classic
    gdpc.pyName = 'GenericDatePickerCtrl'

    # now back to our regular tweaking
    for c in [dpc, gdpc]:
        tools.fixWindowClass(c)
        c.find('GetRange.dt1').out = True
        c.find('GetRange.dt2').out = True

    gdpc.addHeaderCode("#include <wx/generic/datectrl.h>")

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #9
0
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('wxHtmlHelpController')
    assert isinstance(c, etgtools.ClassDef)
    c.addPrivateCopyCtor()

    c.find('CreateHelpDialog').ignore(False)
    c.find('CreateHelpFrame').ignore(False)

    c.addItem(etgtools.WigCode("""\
        // Add implementations for the pure virtuals in the base class
        virtual bool DisplayBlock(long blockNo);
        virtual bool DisplaySection(int sectionNo);
        virtual bool LoadFile(const wxString& file = wxEmptyString);
        virtual bool Quit();
        """))
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #10
0
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/timectrl.h>')
    
    c = module.find('wxTimePickerCtrl')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixWindowClass(c)
    
    
    # ignore the return value and set the parameters to be outputs
    c.find('GetTime').type = 'void'
    c.find('GetTime.hour').out = True
    c.find('GetTime.min').out = True
    c.find('GetTime.sec').out = True
    
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #11
0
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/dcbuffer.h>")

    c = module.find('wxBufferedDC')
    c.addPrivateCopyCtor()
    for m in c.find('wxBufferedDC').all() + c.find('Init').all():
        if m.findItem('dc'):
            m.findItem('dc').keepReference = True
        if m.findItem('buffer'):
            m.findItem('buffer').keepReference = True

    
    c = module.find('wxBufferedPaintDC')
    c.addPrivateCopyCtor()
    c.find('wxBufferedPaintDC').findOverload('wxBitmap').find('buffer').keepReference = True
    
    c = module.find('wxAutoBufferedPaintDC')
    c.addPrivateCopyCtor()


    module.find('wxAutoBufferedPaintDCFactory').factory = 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.

    module.addHeaderCode('#include <wx/ribbon/control.h>')

    # Not sure why these are showing up in this module as they are in core, so
    # let's just turn them off here...
    module.find('wxEllipsizeFlags').ignore()
    module.find('wxEllipsizeMode').ignore()


    c = module.find('wxRibbonControl')
    assert isinstance(c, etgtools.ClassDef)
    c.find('DoGetNextSmallerSize').ignore(False)
    c.find('DoGetNextLargerSize').ignore(False)
    tools.fixWindowClass(c)

    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #13
0
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('wxNativeFontInfo')
    assert isinstance(c, etgtools.ClassDef)
    c.addCppMethod('wxString*', '__str__', '()', """\
        return new wxString(self->ToString());
        """)

    # linker errors on all but MSW...
    c.find('GetPixelSize').ignore()
    c.find('SetPixelSize').ignore()

    c.addAutoProperties()


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #14
0
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('wxTimer')
    assert isinstance(c, etgtools.ClassDef)

    c = module.find('wxTimerRunner')
    c.addPrivateCopyCtor()
    
    module.addPyCode('EVT_TIMER = wx.PyEventBinder( wxEVT_TIMER )')

    module.addPyCode("""\
    class PyTimer(Timer):
        '''This timer class is passed the callable object to be called when the timer expires.'''
        def __init__(self, notify):
            Timer.__init__(self)
            self.notify = notify

        def Notify(self):
            if self.notify:
                self.notify()
    """)
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #15
0
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('wxFindDialogEvent')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixEventClass(c)

    module.addPyCode("""\
        EVT_FIND = wx.PyEventBinder( wxEVT_FIND, 1 )
        EVT_FIND_NEXT = wx.PyEventBinder( wxEVT_FIND_NEXT, 1 )
        EVT_FIND_REPLACE = wx.PyEventBinder( wxEVT_FIND_REPLACE, 1 )
        EVT_FIND_REPLACE_ALL = wx.PyEventBinder( wxEVT_FIND_REPLACE_ALL, 1 )
        EVT_FIND_CLOSE = wx.PyEventBinder( wxEVT_FIND_CLOSE, 1 )

        # deprecated wxEVT aliases
        wxEVT_COMMAND_FIND              = wxEVT_FIND
        wxEVT_COMMAND_FIND_NEXT         = wxEVT_FIND_NEXT
        wxEVT_COMMAND_FIND_REPLACE      = wxEVT_FIND_REPLACE
        wxEVT_COMMAND_FIND_REPLACE_ALL  = wxEVT_FIND_REPLACE_ALL
        wxEVT_COMMAND_FIND_CLOSE        = wxEVT_FIND_CLOSE
        """)

    c = module.find('wxFindReplaceDialog')
    tools.fixTopLevelWindowClass(c)


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #16
0
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/rawbmp.h>")
    
    addPixelDataBaseClass(module)
    
    addPixelDataClass(module, 'wxNativePixelData', 'wxBitmap', bpp=24,
        doc="""\
        A class providing direct access to a :class:`wx.Bitmap`'s
        internal data without alpha channel (RGB). 
        """)
    addPixelDataClass(module, 'wxAlphaPixelData', 'wxBitmap', bpp=32,
        doc="""\
        A class providing direct access to a :class:`wx.Bitmap`'s
        internal data including the alpha channel (RGBA). 
        """)
    #addPixelDataClass(module, 'wxImagePixelData', 'wxImage', bpp=32,
    #    doc="""\
    #    ImagePixelData: A class providing direct access to a wx.Image's
    #    internal data usign the same api as the other PixelData classes. 
    #    """)
    
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #17
0
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('wxWizardPage')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixWindowClass(c, False)
    module.addPyCode("PyWizardPage = wx.deprecated(WizardPage, 'Use WizardPage instead.')")


    c = module.find('wxWizardPageSimple')
    tools.fixWindowClass(c, False)
    c.addItem(etgtools.WigCode("""\
        virtual wxWizardPage* GetNext() const;
        virtual wxWizardPage* GetPrev() const;
        """))


    c = module.find('wxWizard')
    tools.fixWindowClass(c, False)

    # ShowPage is undocumented and labeled "implementation only" but it seems
    # too useful to ignore, so add a MethodDef for it here.
    m = MethodDef(name='ShowPage', type='bool', isVirtual=True,
            briefDoc="Show the given wizard page.",
            detailedDoc=["""\
                Calls TransferDataFromWindow on the current page first, and
                returns false without changing the page if it returned false.
                Returns True/False to indicate if the page was actually
                changed."""],
            items=[ParamDef(name='page', type='wxWizardPage*'),
                   ParamDef(name='goingForward', type='bool', default='true')])
    c.addItem(m)

    # Same for IsRunning
    m = MethodDef(name='IsRunning', type='bool', isConst=True)
    c.addItem(m)


    c = module.find('wxWizardEvent')
    tools.fixEventClass(c)
    module.addPyCode("""\
        EVT_WIZARD_BEFORE_PAGE_CHANGED  = wx.PyEventBinder( wxEVT_WIZARD_BEFORE_PAGE_CHANGED, 1)
        EVT_WIZARD_PAGE_CHANGED  = wx.PyEventBinder( wxEVT_WIZARD_PAGE_CHANGED, 1)
        EVT_WIZARD_PAGE_CHANGING = wx.PyEventBinder( wxEVT_WIZARD_PAGE_CHANGING, 1)
        EVT_WIZARD_CANCEL        = wx.PyEventBinder( wxEVT_WIZARD_CANCEL, 1)
        EVT_WIZARD_HELP          = wx.PyEventBinder( wxEVT_WIZARD_HELP, 1)
        EVT_WIZARD_FINISHED      = wx.PyEventBinder( wxEVT_WIZARD_FINISHED, 1)
        EVT_WIZARD_PAGE_SHOWN    = wx.PyEventBinder( wxEVT_WIZARD_PAGE_SHOWN, 1)
        """)


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #18
0
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('wxNotificationMessage')
    assert isinstance(c, etgtools.ClassDef)

    # take care of some methods only available on MSW
    c.find('UseTaskBarIcon').setCppCode("""\
        #ifdef __WXMSW__
            return wxNotificationMessage::UseTaskBarIcon(icon);
        #else
            wxPyRaiseNotImplemented();
            return NULL;
        #endif
        """)

    c.find('MSWUseToasts').setCppCode("""\
        #ifdef __WXMSW__
            return wxNotificationMessage::MSWUseToasts(*shortcutPath, *appId);
        #else
            wxPyRaiseNotImplemented();
            return false;
        #endif
        """)


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #19
0
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('wxAuiMDIParentFrame')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixTopLevelWindowClass(c)
    c.find('SetMenuBar.menuBar').transfer = True
    c.find('SetArtProvider.provider').transfer = True


    c = module.find('wxAuiMDIChildFrame')
    tools.fixTopLevelWindowClass(c)
    tools.fixSetStatusWidths(c.find('SetStatusWidths'))
    c.find('SetMenuBar.menuBar').transfer = True
    c.find('Show').isVirtual = True

    c = module.find('wxAuiMDIClientWindow')
    tools.fixWindowClass(c)


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #20
0
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('wxMessageDialog')
    assert isinstance(c, etgtools.ClassDef)

    module.addGlobalStr('wxMessageBoxCaptionStr', c)

    # Several of the wxMessageDIalog methods take a
    # wxMessageDialog::ButtonLabel parameter, which enables either a string or
    # a Stock ID to be passed. To facilitate this same ability for Python the
    # SIP types are changed to a custom type which is a MappedType which
    # handles converting from the two types for us. See msgdlg_btnlabel.sip
    c.find('ButtonLabel').ignore()
    for item in c.allItems():
        if isinstance(item, ParamDef) and item.type == 'const ButtonLabel &':
            item.type = 'const wxMessageDialogButtonLabel &'


    tools.fixTopLevelWindowClass(c)



    # Make a copy of wxMessageDialog so we can generate code for
    # wxGenericMessageDialog too.
    gmd = copy.deepcopy(c)
    assert isinstance(gmd, etgtools.ClassDef)
    gmd.name = 'wxGenericMessageDialog'
    gmd.find('wxMessageDialog').name = 'wxGenericMessageDialog'  # the ctor

    m = gmd.addItem(etgtools.MethodDef(
        protection='protected', type='void', name='AddMessageDialogCheckBox',
        briefDoc="Can be overridden to provide more contents for the dialog",
        className=gmd.name))
    m.addItem(etgtools.ParamDef(type='wxSizer*', name='sizer'))

    m = gmd.addItem(etgtools.MethodDef(
        protection='protected', type='void', name='AddMessageDialogDetails',
        briefDoc="Can be overridden to provide more contents for the dialog",
        className=gmd.name))
    m.addItem(etgtools.ParamDef(type='wxSizer*', name='sizer'))

    module.addItem(gmd)


    module.find('wxMessageBox').releaseGIL()

    c = module.find('wxMessageBox')
    c.mustHaveApp()


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #21
0
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('wxAppTraits')
    assert isinstance(c, etgtools.ClassDef)
    c.abstract = True


    # TODO: Enable these as etg scripts for their return types are added
    for name in [ 'CreateFontMapper',
                  'CreateMessageOutput',
                  'CreateRenderer',
                  ]:
        c.find(name).ignore()

    for name in [ 'CreateConfig',
                  'CreateEventLoop',
                  'CreateLogTarget',
                  #'GetStandardPaths',
                  ]:
        c.find(name).factory = True

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #22
0
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/dateevt.h>")

    c = module.find('wxDateEvent')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixEventClass(c)

    c.addPyCode("""\
        EVT_DATE_CHANGED = wx.PyEventBinder( wxEVT_DATE_CHANGED, 1 )
        EVT_TIME_CHANGED = wx.PyEventBinder( wxEVT_TIME_CHANGED, 1 )
        """)

    c.addPyCode("""\
        DateEvent.PyGetDate = wx.deprecated(DateEvent.GetDate, 'Use GetDate instead.')
        DateEvent.PySetDate = wx.deprecated(DateEvent.SetDate, 'Use SetDate instead.')
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #23
0
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/laywin.h>')

    c = module.find('wxSashLayoutWindow')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixWindowClass(c)


    c = module.find('wxQueryLayoutInfoEvent')
    tools.fixEventClass(c)


    c = module.find('wxCalculateLayoutEvent')
    tools.fixEventClass(c)

    module.addPyCode("""\
        EVT_QUERY_LAYOUT_INFO = wx.PyEventBinder( wxEVT_QUERY_LAYOUT_INFO )
        EVT_CALCULATE_LAYOUT = wx.PyEventBinder( wxEVT_CALCULATE_LAYOUT )
        """)


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #24
0
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/unichar.h>')

    c = module.find('wxUniChar')
    assert isinstance(c, etgtools.ClassDef)

    m = c.find('wxUniChar').findOverload('long int')
    m.find('c').type = 'long'

    m = c.find('wxUniChar').findOverload('unsigned long int')
    m.find('c').type = 'unsigned long'

    for m in c.find('wxUniChar').all():
        p = m.find('c')
        if 'long' not in p.type:
            m.ignore()


    tools.ignoreAllOperators(c)


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #25
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING, 
                                check4unittest=False  # wxEventLoop is well tested in 
                                                      # myYield used by other tests...
                                )
    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('wxEventLoopBase')
    assert isinstance(c, etgtools.ClassDef)
    c.abstract = True

    c.find('Yield').releaseGIL()
    c.find('YieldFor').releaseGIL()
    c.find('OnExit').ignore(False)
    
    
    c = module.find('wxEventLoopActivator')
    c.addPrivateAssignOp()
    c.addPrivateCopyCtor()
       
    # context manager methods
    c.addPyMethod('__enter__', '(self)', 'return self')
    c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)', 'return False')


        
    c = module.find('wxGUIEventLoop')
    c.addPrivateCopyCtor()
    
    # Add declaration of the base class pure virtuals so sip knows they have
    # implementations here
    c.addItem(etgtools.WigCode("""\
        public:
        virtual int Run();
        virtual void Exit(int rc = 0);
        virtual bool Pending() const;
        virtual bool Dispatch();
        virtual int DispatchTimeout(unsigned long timeout);
        virtual void WakeUp();

        virtual bool ProcessIdle();        
        """))
    
    module.addPyCode("""\
        @wx.deprecatedMsg('Use GUIEventLoop instead.')
        class EventLoop(GUIEventLoop):
            '''Class using the old name for compatibility.'''
            def __init__(self):
                GUIEventLoop.__init__(self)
        """)
    
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #26
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)
    module.check4unittest = False

    #-----------------------------------------------------------------
    # Tweak the parsed meta objects in the module object as needed for
    # customizing the generated code and docstrings.
    
    module.addHeaderCode('#include <wxpy_api.h>')
    module.addImport('_core')
    module.addPyCode("import wx", order=10)
    module.addInclude(INCLUDES)
       
    module.addCppCode("""\
        #include <wx/html/htmlwin.h>
        #include <wx/html/htmprint.h>
        #include <wx/html/helpctrl.h>
        #include <wx/html/helpwnd.h>
        #include <wx/html/helpfrm.h>
        #include <wx/html/helpdlg.h>
        """)
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #27
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING,
                                check4unittest = False)
    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 <wxPython/wxpy_api.h>')
    module.addImport('_core')
    module.addPyCode("import wx", order=10)
    module.addImport('_xml')
    module.addImport('_html')
    module.addImport('_adv')

    module.addInclude(INCLUDES)

    # Redo the initialization of wxModules in the case where this extension
    # module is not imported until *after* the wx.App has been created.
    module.addInitializerCode("""\
        wxPyReinitializeModules();
        """)


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #28
0
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('wxPlatformInfo')
    assert isinstance(c, etgtools.ClassDef)

    # to avoid conflicts with wxPython's wx.PlatformInfo
    c.renameClass('PlatformInformation')

    c.find('GetEndianness').findOverload('end').ignore()
    c.find('GetArchName').findOverload('arch').ignore()
    c.find('GetOperatingSystemId').findOverload('name').ignore()
    c.find('GetPortId').findOverload('portname').ignore()
    c.find('GetEndiannessName').findOverload('end').ignore()
    c.find('GetOperatingSystemIdName').findOverload('os').ignore()
    c.find('GetOperatingSystemFamilyName').findOverload('os').ignore()
    c.find('GetPortIdName').findOverload('port').ignore()
    c.find('GetPortIdShortName').findOverload('port').ignore()


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #29
0
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.find('wxPG_LABEL').ignore()
    module.find('wxPG_LABEL_STRING').ignore()
    module.find('wxPG_NULL_BITMAP').ignore()
    module.find('wxPG_COLOUR_BLACK').ignore()
    module.find('wxPG_COLOUR').ignore()
    module.find('wxPG_DEFAULT_IMAGE_SIZE').ignore()
    module.find('wxPGSortCallback').ignore()

    module.addPyCode(
        code="""\
        PG_LABEL = "@!"
        PG_LABEL_STRING = PG_LABEL
        PG_NULL_BITMAP = wx.NullBitmap
        PG_COLOUR_BLACK = wx.BLACK
        PG_DEFAULT_IMAGE_SIZE = wx.Size(-1, -1)
        """,
        order=15)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #30
0
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.addItem(
        tools.wxArrayWrapperTemplate('wxHtmlBookRecArray', 'wxHtmlBookRecord', module))

    module.addItem(
        tools.wxArrayWrapperTemplate('wxHtmlHelpDataItems', 'wxHtmlHelpDataItem', module))


    c = module.find('wxHtmlHelpData')
    assert isinstance(c, etgtools.ClassDef)
    c.addPrivateCopyCtor()



    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #31
0
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()

    # deprecated and removed
    c.find('SetVirtualSizeHints').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',
        '(ulong 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',
        '(ulong 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.addPyMethod(
        '__iter__',
        '(self)',
        doc=
        "A Python convenience method that allows Sizers to act as iterables that will yield their wx.SizerItems.",
        body="for item in self.GetChildren(): yield item")

    c.addPyCode('Sizer.__bool__ = Sizer.__nonzero__')  # For Python 3

    m = etgtools.MethodDef(
        type='void',
        name='RecalcSizes',
        argsString='()',
        isVirtual=True,
        briefDoc="This is a deprecated version of RepositionChildren()",
        detailedDoc=[
            dedent("""\
            This is a deprecated version of RepositionChildren() which doesn't take
            the minimal size parameter which is not needed for very simple sizers
            but typically is for anything more complicated, so prefer to override
            RepositionChildren() in new code.

            If RepositionChildren() is not overridden, this method must be
            overridden, calling the base class version results in an assertion
            failure.
            """)
        ],
    )
    c.insertItemAfter(c.find('RepositionChildren'), m)

    #---------------------------------------------
    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)
Exemple #32
0
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('wxPGCellData')
    assert isinstance(c, etgtools.ClassDef)
    c.find('~wxPGCellData').ignore(False)
    c.bases = ['wxRefCounter']

    c = module.find('wxPGCellRenderer')
    c.bases = ['wxRefCounter']


    c = module.find('wxPGProperty')
    tools.ignoreConstOverloads(c)
    c.find('StringToValue.variant').out = True
    c.find('IntToValue.variant').out = True

    c.addProperty('m_value GetValue SetValue')


    # SIP needs to be able to make a copy of the wxPGAttributeStorage value
    # but the C++ class doesn't have a copy ctor and the default will cause it
    # to lose references to the variants it contains, so let's just override
    # the use of the MappedType and convert it to a Python dictionary here
    # instead.
    m = c.find('GetAttributes')
    m.type = 'PyObject*'
    m.setCppCode("""\
        const wxPGAttributeStorage& attrs = self->GetAttributes();
        wxPGAttributeStorage::const_iterator it = attrs.StartIteration();
        wxVariant v;
        wxPyThreadBlocker blocker;

        PyObject* dict = PyDict_New();
        if ( !dict ) return NULL;

        while ( attrs.GetNext( it, v ) ) {
            const wxString& name = v.GetName();
            PyObject* pyStr = wx2PyString(name);
            PyObject* pyVal = wxPGVariant_out_helper(v);
            int res = PyDict_SetItem( dict, pyStr, pyVal );
        }
        return dict;
        """)

    # SetAttributes uses wxPGAttributeStorage too, but we'll just replace it
    # with a simple Python method.
    c.find('SetAttributes').ignore()
    c.addPyMethod('SetAttributes', '(self, attributes)',
        doc="Set the property's attributes from a Python dictionary.",
        body="""\
            for name,value in attributes.items():
                self.SetAttribute(name, value)
            """)

    c.find('AddPrivateChild.prop').transfer = True
    c.find('AddChild.prop').transfer = True

    # The [G|S]etClientData methods deal with untyped void* values, which we
    # don't support. The [G|S]etClientObject methods use wxClientData instances
    # which we have a MappedType for, so make the ClientData methods just be
    # aliases for ClientObjects. From the Python programmer's perspective they
    # would be virtually the same anyway.
    c.find('SetClientObject.clientObject').transfer = True
    c.find('SetClientObject.clientObject').name = 'data'
    c.find('GetClientData').ignore()
    c.find('SetClientData').ignore()
    c.find('GetClientObject').pyName = 'GetClientData'
    c.find('SetClientObject').pyName = 'SetClientData'
    c.addPyMethod('GetClientObject', '(self, n)',
        doc="Alias for :meth:`GetClientData`",
        body="return self.GetClientData(n)")
    c.addPyMethod('SetClientObject', '(self, n, data)',
        doc="Alias for :meth:`SetClientData`",
        body="self.SetClientData(n, data)")



    c = module.find('wxPGChoicesData')
    tools.ignoreConstOverloads(c)
    c.bases = ['wxRefCounter']
    c.find('~wxPGChoicesData').ignore(False)


    c = module.find('wxPGChoices')
    c.find('wxPGChoices').findOverload('wxChar **').ignore()
    tools.ignoreConstOverloads(c)
    c.find('operator[]').ignore()

    c.addPyMethod('__getitem__', '(self, index)',
        doc="Returns a reference to a :class:PGChoiceEntry using Python list syntax.",
        body="return self.Item(index)",
        )
    c.addPyMethod('__len__', '(self)',
        doc="",
        body="return self.GetCount()",
        )


    # Ignore some string constants (#defines) coming from dox, and add them
    # back in Python code. They are wchar_t* values and this seemed the
    # simplest way to deal with them.
    for name in [ 'wxPG_ATTR_DEFAULT_VALUE',
                  'wxPG_ATTR_MIN',
                  'wxPG_ATTR_MAX',
                  'wxPG_ATTR_UNITS',
                  'wxPG_ATTR_HINT',
                  'wxPG_ATTR_INLINE_HELP',
                  'wxPG_ATTR_AUTOCOMPLETE',
                  'wxPG_BOOL_USE_CHECKBOX',
                  'wxPG_BOOL_USE_DOUBLE_CLICK_CYCLING',
                  'wxPG_FLOAT_PRECISION',
                  'wxPG_STRING_PASSWORD',
                  'wxPG_UINT_BASE',
                  'wxPG_UINT_PREFIX',
                  'wxPG_FILE_WILDCARD',
                  'wxPG_FILE_SHOW_FULL_PATH',
                  'wxPG_FILE_SHOW_RELATIVE_PATH',
                  'wxPG_FILE_INITIAL_PATH',
                  'wxPG_FILE_DIALOG_TITLE',
                  'wxPG_FILE_DIALOG_STYLE',
                  'wxPG_DIR_DIALOG_MESSAGE',
                  'wxPG_ARRAY_DELIMITER',
                  'wxPG_DATE_FORMAT',
                  'wxPG_DATE_PICKER_STYLE',
                  'wxPG_ATTR_SPINCTRL_STEP',
                  'wxPG_ATTR_SPINCTRL_WRAP',
                  'wxPG_ATTR_SPINCTRL_MOTIONSPIN',
                  'wxPG_ATTR_MULTICHOICE_USERSTRINGMODE',
                  'wxPG_COLOUR_ALLOW_CUSTOM',
                  'wxPG_COLOUR_HAS_ALPHA',

                  # and some other #defines with similar issues
                  'wxNullProperty',
                  'wxPGChoicesEmptyData',
                  ]:
        module.find(name).ignore()

        module.addPyCode("""\
            PG_ATTR_DEFAULT_VALUE             = u"DefaultValue"
            PG_ATTR_MIN                       = u"Min"
            PG_ATTR_MAX                       = u"Max"
            PG_ATTR_UNITS                     = u"Units"
            PG_ATTR_HINT                      = u"Hint"
            PG_ATTR_INLINE_HELP               = u"InlineHelp"
            PG_ATTR_AUTOCOMPLETE              = u"AutoComplete"
            PG_BOOL_USE_CHECKBOX              = u"UseCheckbox"
            PG_BOOL_USE_DOUBLE_CLICK_CYCLING  = u"UseDClickCycling"
            PG_FLOAT_PRECISION                = u"Precision"
            PG_STRING_PASSWORD                = u"Password"
            PG_UINT_BASE                      = u"Base"
            PG_UINT_PREFIX                    = u"Prefix"
            PG_FILE_WILDCARD                  = u"Wildcard"
            PG_FILE_SHOW_FULL_PATH            = u"ShowFullPath"
            PG_FILE_SHOW_RELATIVE_PATH        = u"ShowRelativePath"
            PG_FILE_INITIAL_PATH              = u"InitialPath"
            PG_FILE_DIALOG_TITLE              = u"DialogTitle"
            PG_FILE_DIALOG_STYLE              = u"DialogStyle"
            PG_DIR_DIALOG_MESSAGE             = u"DialogMessage"
            PG_ARRAY_DELIMITER                = u"Delimiter"
            PG_DATE_FORMAT                    = u"DateFormat"
            PG_DATE_PICKER_STYLE              = u"PickerStyle"
            PG_ATTR_SPINCTRL_STEP             = u"Step"
            PG_ATTR_SPINCTRL_WRAP             = u"Wrap"
            PG_ATTR_SPINCTRL_MOTIONSPIN       = u"MotionSpin"
            PG_ATTR_MULTICHOICE_USERSTRINGMODE= u"UserStringMode"
            PG_COLOUR_ALLOW_CUSTOM            = u"AllowCustom"
            PG_COLOUR_HAS_ALPHA               = u"HasAlpha"

            NullProperty                      = None
            PGChoicesEmptyData                = None
            """)


    # Switch all wxVariant types to wxPGVariant, so the propgrid-specific
    # version of the MappedType will be used for converting to/from Python
    # objects.
    for item in module.allItems():
        if hasattr(item, 'type') and 'wxVariant' in item.type:
            item.type = item.type.replace('wxVariant', 'wxPGVariant')

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #33
0
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)
Exemple #34
0
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('wxAcceleratorEntry')
    assert isinstance(c, etgtools.ClassDef)
    tools.removeVirtuals(c)

    c = module.find('wxAcceleratorTable')
    assert isinstance(c, etgtools.ClassDef)
    tools.removeVirtuals(c)

    # Replace the implementation of the AcceleratorTable ctor so it can
    # accept a Python sequence of tuples or AcceleratorEntry objects like
    # Classic does. Using the arraySize and array annotations does let us
    # pass a list of entries, but they have to already be AccelertorEntry
    # obejcts. We want to allow Items in the list to be either
    # wx.AcceleratorEntry items or a 3-tuple containing the values to pass to
    # the wx.AcceleratorEntry ctor.

    # Ignore the current constructor
    c.find('wxAcceleratorTable').findOverload('entries').ignore()

    # and add the code for the new constructor
    c.addCppCtor(briefDoc="""\
            Constructs an AcceleratorTable from a sequence of items
            where each item is either a wx.AcceleratorEntry or a 
            corresponding 3-element tuple like (modifiers, keyCode, cmd).
            """,
                 argsString='(PyObject* entries)',
                 body="""\
    const char* errmsg = "Expected a sequence of 3-tuples or wx.AcceleratorEntry objects.";
    if (!PySequence_Check(entries)) {
        PyErr_SetString(PyExc_TypeError, errmsg);
        return NULL;
    }
    int count = PySequence_Size(entries);
    wxAcceleratorEntry* tmpEntries = new wxAcceleratorEntry[count];
    if (! tmpEntries) {
        PyErr_SetString(PyExc_MemoryError, "Unable to allocate temporary array");
        return NULL;
    }
    int idx;
    for (idx=0; idx<count; idx++) {
        PyObject* obj = PySequence_ITEM(entries, idx);
        if (sipCanConvertToType(obj, sipType_wxAcceleratorEntry, SIP_NO_CONVERTORS)) {
            int err = 0;
            wxAcceleratorEntry* entryPtr = reinterpret_cast<wxAcceleratorEntry*>(
                sipConvertToType(obj, sipType_wxAcceleratorEntry, NULL, 0, 0, &err));
            tmpEntries[idx] = *entryPtr;
        }
        else if (PySequence_Check(obj) && PySequence_Size(obj) == 3) {
            PyObject* o1 = PySequence_ITEM(obj, 0);
            PyObject* o2 = PySequence_ITEM(obj, 1);
            PyObject* o3 = PySequence_ITEM(obj, 2);
            tmpEntries[idx].Set(wxPyInt_AsLong(o1), wxPyInt_AsLong(o2), wxPyInt_AsLong(o3));
            Py_DECREF(o1);
            Py_DECREF(o2);
            Py_DECREF(o3);
        }
        else {
            PyErr_SetString(PyExc_TypeError, errmsg);
            return NULL;
        }
        Py_DECREF(obj);
    }

    wxAcceleratorTable* table = new wxAcceleratorTable(count, tmpEntries);
    delete [] tmpEntries;
    return table;
    """)

    # Mac doesn't have this, and we don't real with resource files from
    # wxPython anyway.
    c.find('wxAcceleratorTable').findOverload('resource').ignore()

    module.addPyFunction('GetAccelFromString',
                         '(label)',
                         deprecated=True,
                         body="""\
            accel = wx.AcceleratorEntry()
            accel.FromString(label)
            return accel
            """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #35
0
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('wxFont')
    assert isinstance(c, etgtools.ClassDef)
    tools.removeVirtuals(c)
    
    # FFont factory function for backwards compatibility
    module.addCppFunction('wxFont*', 'FFont', 
                          """(int pointSize,
                              wxFontFamily family,
                              int flags = wxFONTFLAG_DEFAULT,
                              const wxString& faceName = wxEmptyString,
                              wxFontEncoding encoding = wxFONTENCODING_DEFAULT)""",
        pyArgsString="(pointSize, family, flags=FONTFLAG_DEFAULT, faceName=EmptyString, encoding=FONTENCODING_DEFAULT)",
        body="""\
        wxFont* font = wxFont::New(pointSize, family, flags, *faceName, encoding);
        return font;
        """, factory=True)
    
    for item in c.findAll('New'):
        item.factory = True
    
    c.addProperty('Encoding GetEncoding SetEncoding')
    c.addProperty('FaceName GetFaceName SetFaceName')
    c.addProperty('Family GetFamily SetFamily')
    c.addProperty('NativeFontInfoDesc GetNativeFontInfoDesc SetNativeFontInfo')
    c.addProperty('NativeFontInfoUserDesc GetNativeFontInfoUserDesc SetNativeFontInfoUserDesc')
    c.addProperty('PointSize GetPointSize SetPointSize')
    c.addProperty('PixelSize GetPixelSize SetPixelSize')
    c.addProperty('Style GetStyle SetStyle')
    c.addProperty('Weight GetWeight SetWeight')

    # TODO, there is now a Underlined method so we can't have a
    # property of the same name.
    #c.addProperty('Underlined GetUnderlined SetUnderlined')
    #c.addProperty('Strikethrough GetStrikethrough SetStrikethrough')

    c.addCppMethod('int', '__nonzero__', '()', """\
        return self->IsOk();
        """)

    c.addCppMethod('void*', 'GetHFONT', '()', 
        doc="Returns the font's native handle.",
        body="""\
        #ifdef __WXMSW__
            return self->GetHFONT();
        #else
            return 0;
        #endif
        """)
    
    c.addCppMethod('void*', 'OSXGetCGFont', '()', 
        doc="Returns the font's native handle.",
        body="""\
        #ifdef __WXMAC__
            return self->OSXGetCGFont();
        #else
            return 0;
        #endif
        """)

    c.addCppMethod('void*', 'GetPangoFontDescription', '()', 
        doc="Returns the font's native handle.",
        body="""\
        #ifdef __WXGTK__
            return self->GetNativeFontInfo()->description;
        #else
            return 0;
        #endif
        """)
    
    
       
    # The stock Font items are documented as simple pointers, but in reality
    # they are macros that evaluate to a function call that returns a font
    # pointer, and that is only valid *after* the wx.App object has been
    # created. That messes up the code that SIP generates for them, so we need
    # to come up with another solution. So instead we will just create
    # uninitialized fonts in a block of Python code, that will then be
    # initialized later when the wx.App is created.
    c.addCppMethod('void', '_copyFrom', '(const wxFont* other)', 
                   "*self = *other;",
                   briefDoc="For internal use only.")  # ??
    pycode = '# These stock fonts will be initialized when the wx.App object is created.\n'
    for item in module:
        if '_FONT' in item.name:
            item.ignore()
            pycode += '%s = Font()\n' % tools.removeWxPrefix(item.name)
    module.addPyCode(pycode)

    # it is delay-initialized, see stockgdi.sip
    module.find('wxTheFontList').ignore()

    module.find('wxFromString').ignore()
    module.find('wxToString').ignore()

    c.addPyMethod('SetNoAntiAliasing', '(self, no=True)', 'pass', deprecated=True)
    c.addPyMethod('GetNoAntiAliasing', '(self)', 'pass', deprecated=True)

    # Some aliases that should be phased out eventually, (sooner rather than
    # later.) They are already gone (or wrapped by an #if) in the C++ code,
    # and so are not found in the documentation...
    module.addPyCode("""\
        wx.DEFAULT    = int(wx.FONTFAMILY_DEFAULT)
        wx.DECORATIVE = int(wx.FONTFAMILY_DECORATIVE)
        wx.ROMAN      = int(wx.FONTFAMILY_ROMAN)
        wx.SCRIPT     = int(wx.FONTFAMILY_SCRIPT)
        wx.SWISS      = int(wx.FONTFAMILY_SWISS)
        wx.MODERN     = int(wx.FONTFAMILY_MODERN)
        wx.TELETYPE   = int(wx.FONTFAMILY_TELETYPE)

        wx.NORMAL = int(wx.FONTWEIGHT_NORMAL)
        wx.LIGHT  = int(wx.FONTWEIGHT_LIGHT)
        wx.BOLD   = int(wx.FONTWEIGHT_BOLD)
        
        wx.NORMAL = int(wx.FONTSTYLE_NORMAL)
        wx.ITALIC = int(wx.FONTSTYLE_ITALIC)
        wx.SLANT  = int(wx.FONTSTYLE_SLANT)
        """)        


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #36
0
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('wxIcon')
    assert isinstance(c, etgtools.ClassDef)
    tools.removeVirtuals(c)
    c.mustHaveApp()

    c.find('wxIcon').findOverload('*bits').ignore()
    c.find('wxIcon').findOverload('bits[]').ignore()

    c.find('wxIcon.type').default = 'wxBITMAP_TYPE_ANY'
    c.find('LoadFile.type').default = 'wxBITMAP_TYPE_ANY'

    c.find('ConvertToDisabled').ignore()

    c.addCppCtor('(const wxBitmap& bmp)',
                 doc="Construct an Icon from a Bitmap.",
                 body="""\
            wxIcon* icon = new wxIcon();
            icon->CopyFromBitmap(*bmp);
            return icon;
            """)

    c.addCppMethod('int', '__nonzero__', '()', """\
        return self->IsOk();""")

    c.addCppMethod(
        'long', 'GetHandle', '()', """\
        #ifdef __WXMSW__
            return (long)self->GetHandle();
        #else
            return 0;
        #endif
        """)

    c.addCppMethod(
        'void', 'SetHandle', '(long handle)', """\
        #ifdef __WXMSW__
            self->SetHandle((WXHANDLE)handle);
        #endif
        """)

    c.find('CreateFromHICON').ignore()
    c.addCppMethod(
        'bool',
        'CreateFromHICON',
        '(long hicon)',
        doc='MSW-only method to create a wx.Icon from a native icon handle.',
        body="""\
            #ifdef __WXMSW__
                return self->CreateFromHICON((WXHICON)hicon);
            #else
                return false;
            #endif
            """)

    # For compatibility:
    module.addPyFunction(
        'EmptyIcon',
        '()',
        deprecated="Use :class:`Icon` instead",
        doc='A compatibility wrapper for the :class:`Icon` constructor',
        body='return Icon()')

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #37
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)
    module.check4unittest = False

    #-----------------------------------------------------------------
    # Tweak the parsed meta objects in the module object as needed for
    # customizing the generated code and docstrings.

    module.addHeaderCode('#include <wxpy_api.h>')
    module.addImport('_core')
    module.addPyCode('''\
    import wx
    ID_ANY = wx.ID_ANY  # Needed for some parameter defaults in this module
    ''',
                     order=10)
    module.addInclude(INCLUDES)

    #-----------------------------------------------------------------

    module.addHeaderCode('#include <wx/stc/stc.h>')

    c = module.find('wxStyledTextCtrl')
    assert isinstance(c, etgtools.ClassDef)
    c.bases = ['wxControl']  # wxTextCtrlIface is also a base...
    c.piBases = ['wx.Control', 'wx.TextEntry']
    tools.fixWindowClass(c, False)
    module.addGlobalStr('wxSTCNameStr', c)

    c.find('GetCurLine.linePos').out = True
    c.find('GetCurLineRaw.linePos').out = True
    for name in ['Remove', 'Replace', 'SetSelection', 'GetSelection']:
        m = c.find(name)
        m.find('from').name = 'from_'
        m.find('to').name = 'to_'

    c.find('GetSelection.from_').out = True
    c.find('GetSelection.to_').out = True
    c.find('PositionToXY.x').out = True
    c.find('PositionToXY.y').out = True

    # Split the HitTest overloads into separately named methods since once
    # the output parameters are applied they will have the same function
    # signature.
    ht1 = c.find('HitTest')
    ht2 = ht1.overloads[0]
    ht1.overloads = []
    c.insertItemAfter(ht1, ht2)
    ht1.pyName = 'HitTestPos'
    ht1.find('pos').out = True
    ht2.find('row').out = True
    ht2.find('col').out = True

    # Replace the *Pointer methods with ones that return a memoryview object instead.
    c.find('GetCharacterPointer').ignore()
    c.addCppMethod('PyObject*',
                   'GetCharacterPointer',
                   '()',
                   doc="""\
            Compact the document buffer and return a read-only memoryview
            object of the characters in the document.""",
                   body="""
            const char* ptr = self->GetCharacterPointer();
            Py_ssize_t len = self->GetLength();
            PyObject* rv;
            wxPyBLOCK_THREADS( rv = wxPyMakeBuffer((void*)ptr, len, true) );
            return rv;
            """)

    c.find('GetRangePointer').ignore()
    c.addCppMethod('PyObject*',
                   'GetRangePointer',
                   '(int position, int rangeLength)',
                   doc="""\
            Return a read-only pointer to a range of characters in the
            document. May move the gap so that the range is contiguous,
            but will only move up to rangeLength bytes.""",
                   body="""
            const char* ptr = self->GetRangePointer(position, rangeLength);
            Py_ssize_t len = rangeLength;
            PyObject* rv;
            wxPyBLOCK_THREADS( rv = wxPyMakeBuffer((void*)ptr, len, true) );
            return rv;
            """)

    # Generate the code for this differently because it needs to be
    # forcibly mashed into an int in the C code
    module.find('wxSTC_MASK_FOLDERS').forcedInt = True

    # Make sure that all the methods from wxTextEntry and wxTextCtrl are
    # included. This is needed because we are pretending that this class only
    # derives from wxControl but the real C++ class also derives from
    # wxTextCtrlIface which derives from wxTextEntryBase.
    import textentry
    mod = textentry.parseAndTweakModule()
    klass = mod.find('wxTextEntry')
    items = [
        item for item in klass.items if isinstance(item, etgtools.MethodDef)
        and not item.isCtor and not item.isDtor and not c.findItem(item.name)
    ]
    c.items.extend(items)

    import textctrl
    mod = textctrl.parseAndTweakModule()
    klass = mod.find('wxTextCtrl')
    items = [
        item for item in klass.items if isinstance(item, etgtools.MethodDef)
        and not item.isCtor and not item.isDtor and not c.findItem(item.name)
    ]
    c.items.extend(items)

    c.find('EmulateKeyPress').ignore()
    c.find('IsMultiLine').ignore()
    c.find('IsSingleLine').ignore()
    c.find('MacCheckSpelling').ignore()
    c.find('ShowNativeCaret').ignore()
    c.find('HideNativeCaret').ignore()

    # TODO:  Add the UTF8 PyMethods from classic (see _stc_utf8_methods.py)

    #-----------------------------------------------------------------
    c = module.find('wxStyledTextEvent')
    tools.fixEventClass(c)

    c.addPyCode("""\
        EVT_STC_CHANGE = wx.PyEventBinder( wxEVT_STC_CHANGE, 1 )
        EVT_STC_STYLENEEDED = wx.PyEventBinder( wxEVT_STC_STYLENEEDED, 1 )
        EVT_STC_CHARADDED = wx.PyEventBinder( wxEVT_STC_CHARADDED, 1 )
        EVT_STC_SAVEPOINTREACHED = wx.PyEventBinder( wxEVT_STC_SAVEPOINTREACHED, 1 )
        EVT_STC_SAVEPOINTLEFT = wx.PyEventBinder( wxEVT_STC_SAVEPOINTLEFT, 1 )
        EVT_STC_ROMODIFYATTEMPT = wx.PyEventBinder( wxEVT_STC_ROMODIFYATTEMPT, 1 )
        EVT_STC_KEY = wx.PyEventBinder( wxEVT_STC_KEY, 1 )
        EVT_STC_DOUBLECLICK = wx.PyEventBinder( wxEVT_STC_DOUBLECLICK, 1 )
        EVT_STC_UPDATEUI = wx.PyEventBinder( wxEVT_STC_UPDATEUI, 1 )
        EVT_STC_MODIFIED = wx.PyEventBinder( wxEVT_STC_MODIFIED, 1 )
        EVT_STC_MACRORECORD = wx.PyEventBinder( wxEVT_STC_MACRORECORD, 1 )
        EVT_STC_MARGINCLICK = wx.PyEventBinder( wxEVT_STC_MARGINCLICK, 1 )
        EVT_STC_NEEDSHOWN = wx.PyEventBinder( wxEVT_STC_NEEDSHOWN, 1 )
        EVT_STC_PAINTED = wx.PyEventBinder( wxEVT_STC_PAINTED, 1 )
        EVT_STC_USERLISTSELECTION = wx.PyEventBinder( wxEVT_STC_USERLISTSELECTION, 1 )
        EVT_STC_URIDROPPED = wx.PyEventBinder( wxEVT_STC_URIDROPPED, 1 )
        EVT_STC_DWELLSTART = wx.PyEventBinder( wxEVT_STC_DWELLSTART, 1 )
        EVT_STC_DWELLEND = wx.PyEventBinder( wxEVT_STC_DWELLEND, 1 )
        EVT_STC_START_DRAG = wx.PyEventBinder( wxEVT_STC_START_DRAG, 1 )
        EVT_STC_DRAG_OVER = wx.PyEventBinder( wxEVT_STC_DRAG_OVER, 1 )
        EVT_STC_DO_DROP = wx.PyEventBinder( wxEVT_STC_DO_DROP, 1 )
        EVT_STC_ZOOM = wx.PyEventBinder( wxEVT_STC_ZOOM, 1 )
        EVT_STC_HOTSPOT_CLICK = wx.PyEventBinder( wxEVT_STC_HOTSPOT_CLICK, 1 )
        EVT_STC_HOTSPOT_DCLICK = wx.PyEventBinder( wxEVT_STC_HOTSPOT_DCLICK, 1 )
        EVT_STC_HOTSPOT_RELEASE_CLICK = wx.PyEventBinder( wxEVT_STC_HOTSPOT_RELEASE_CLICK, 1 )
        EVT_STC_CALLTIP_CLICK = wx.PyEventBinder( wxEVT_STC_CALLTIP_CLICK, 1 )
        EVT_STC_AUTOCOMP_SELECTION = wx.PyEventBinder( wxEVT_STC_AUTOCOMP_SELECTION, 1 )
        EVT_STC_INDICATOR_CLICK = wx.PyEventBinder( wxEVT_STC_INDICATOR_CLICK, 1 )
        EVT_STC_INDICATOR_RELEASE = wx.PyEventBinder( wxEVT_STC_INDICATOR_RELEASE, 1 )
        EVT_STC_AUTOCOMP_CANCELLED = wx.PyEventBinder( wxEVT_STC_AUTOCOMP_CANCELLED, 1 )
        EVT_STC_AUTOCOMP_CHAR_DELETED = wx.PyEventBinder( wxEVT_STC_AUTOCOMP_CHAR_DELETED, 1 )
        """)

    #-----------------------------------------------------------------

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #38
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)
    module.check4unittest = False

    #-----------------------------------------------------------------
    # Tweak the parsed meta objects in the module object as needed for
    # customizing the generated code and docstrings.

    module.addHeaderCode('#include <wxPython/wxpy_api.h>')
    module.addImport('_core')
    module.addImport('_xml')
    module.addPyCode('''\
    import wx
    ID_NONE = wx.ID_NONE  # Needed for some parameter defaults in this module
    ''',
                     order=10)
    module.addInclude(INCLUDES)

    module.addInitializerCode("""\
        wxXmlInitResourceModule();
        wxXmlResource::Get()->InitAllHandlers();
        """)

    module.addHeaderCode('#include <wx/xrc/xmlres.h>')
    module.addHeaderCode('#include <wx/fs_mem.h>')
    module.addHeaderCode('#include "wxpybuffer.h"')

    module.insertItem(
        0,
        etgtools.WigCode("""\
        // forward declarations
        class wxAnimation;
        """))

    #-----------------------------------------------------------------

    c = module.find('wxXmlResource')
    assert isinstance(c, etgtools.ClassDef)
    c.addPrivateCopyCtor()

    # Add a bit of code to the ctors to call InitAllHandlers(), for
    # compatibility with Classic
    for ctor in c.find('wxXmlResource').all():
        template = """\
        Py_BEGIN_ALLOW_THREADS
        sipCpp = new sipwxXmlResource({args});
        sipCpp->InitAllHandlers();
        Py_END_ALLOW_THREADS
        """
        if 'filemask' in ctor.argsString:
            args = '*filemask,flags,*domain'
        else:
            args = 'flags,*domain'
        ctor.setCppCode_sip(template.format(args=args))

    c.addPublic()
    c.addCppMethod(
        'bool',
        'LoadFromBuffer',
        '(wxPyBuffer* data)',
        doc=
        "Load the resource from a bytes string or other data buffer compatible object.",
        #protection='public',
        body="""\
            static int s_memFileIdx = 0;

            // Check for memory FS. If not present, load the handler:
            wxMemoryFSHandler::AddFile(wxT("XRC_resource/dummy_file"),
                                       wxT("dummy data"));
            wxFileSystem fsys;
            wxFSFile *f = fsys.OpenFile(wxT("memory:XRC_resource/dummy_file"));
            wxMemoryFSHandler::RemoveFile(wxT("XRC_resource/dummy_file"));
            if (f)
                delete f;
            else
                wxFileSystem::AddHandler(new wxMemoryFSHandler);

            // Now put the resource data into the memory FS
            wxString filename(wxT("XRC_resource/data_string_"));
            filename << s_memFileIdx;
            s_memFileIdx += 1;
            wxMemoryFSHandler::AddFile(filename, data->m_ptr, data->m_len);

            // Load the "file" into the resource object
            bool retval = self->Load(wxT("memory:") + filename );
            return retval;
            """)
    c.addPyCode(
        "XmlResource.LoadFromString = wx.deprecated(XmlResource.LoadFromBuffer, 'Use LoadFromBuffer instead')"
    )

    c.find('AddHandler.handler').transfer = True
    c.find('InsertHandler.handler').transfer = True
    c.find('Set.res').transfer = True
    c.find('Set').transferBack = True
    c.find('AddSubclassFactory.factory').transfer = True

    #-----------------------------------------------------------------
    c = module.find('wxXmlResourceHandler')

    # un-ignore all the protected methods
    for item in c.allItems():
        if isinstance(item, etgtools.MethodDef):
            item.ignore(False)

    c.find('DoCreateResource').factory = True

    # TODO: It looks like there may be a bug in wx here.
    # Just ignore it for now.
    c.find('GetFilePath').ignore()

    #-----------------------------------------------------------------
    module.addPyFunction(
        'EmptyXmlResource',
        '(flags=XRC_USE_LOCALE, domain="")',
        deprecated="Use :class:`xrc.XmlResource` instead",
        doc=
        'A compatibility wrapper for the XmlResource(flags, domain) constructor',
        body='return XmlResource(flags, domain)')

    module.addPyFunction(
        'XRCID',
        '(str_id, value_if_not_found=wx.ID_NONE)',
        doc=
        'Returns a numeric ID that is equivalent to the string ID used in an XML resource.',
        body='return XmlResource.GetXRCID(str_id, value_if_not_found)')

    module.addPyFunction(
        'XRCCTRL',
        '(window, str_id, *ignoreargs)',
        doc=
        'Returns the child window associated with the string ID in an XML resource.',
        body='return window.FindWindow(XRCID(str_id))')

    cls = ClassDef(name='wxXmlSubclassFactory',
                   briefDoc="",
                   items=[
                       MethodDef(name='wxXmlSubclassFactory', isCtor=True),
                       MethodDef(name='~wxXmlSubclassFactory', isDtor=True),
                       MethodDef(name='Create',
                                 type='wxObject*',
                                 isVirtual=True,
                                 isPureVirtual=True,
                                 factory=True,
                                 items=[
                                     ParamDef(type='const wxString&',
                                              name='className')
                                 ])
                   ])
    module.addItem(cls)

    module.addPyCode("""\
        # Create a factory for handling the subclass property of XRC's
        # object tag.  This factory will search for the specified
        # package.module.class and will try to instantiate it for XRC's
        # use.  The class must support instantiation with no parameters and
        # delayed creation of the UI widget (aka 2-phase create).

        def _my_import(name):
            try:
                mod = __import__(name)
            except ImportError:
                import traceback
                print(traceback.format_exc())
                raise
            components = name.split('.')
            for comp in components[1:]:
                mod = getattr(mod, comp)
            return mod

        class XmlSubclassFactory_Python(XmlSubclassFactory):
            def __init__(self):
                XmlSubclassFactory.__init__(self)

            def Create(self, className):
                assert className.find('.') != -1, "Module name must be specified!"
                mname = className[:className.rfind('.')]
                cname = className[className.rfind('.')+1:]
                module = _my_import(mname)
                klass = getattr(module, cname)
                inst = klass()
                return inst

        XmlResource.AddSubclassFactory(XmlSubclassFactory_Python())
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #39
0
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/gdicmn.h>')

    def markFactories(klass):
        for func in klass.allItems():
            if isinstance(func, etgtools.FunctionDef) \
               and func.name.startswith('Create') \
               and '*' in func.type:
                func.factory = True

    #---------------------------------------------
    c = module.find('wxGraphicsObject')
    assert isinstance(c, etgtools.ClassDef)
    c.mustHaveApp()
    c.addCppMethod('bool', 'IsOk', '()', 'return !self->IsNull();')
    c.addCppMethod('int', '__nonzero__', '()', "return !self->IsNull();")

    #---------------------------------------------
    c = module.find('wxGraphicsContext')
    assert isinstance(c, etgtools.ClassDef)
    markFactories(c)
    tools.removeVirtuals(c)
    c.abstract = True
    c.mustHaveApp()

    # Ensure that the target DC or image lives as long as the GC does. NOTE:
    # Since the Creates are static methods there is no self to associate the
    # extra reference with, but since they are factories then that extra
    # reference will be held by the return value of the factory instead.
    for m in c.find('Create').all():
        for p in m.items:
            if 'DC' in p.name or p.name == 'image':
                p.keepReference = True

    # FIXME: Handle wxEnhMetaFileDC?
    c.find('Create').findOverload('wxEnhMetaFileDC').ignore()

    c.find('GetSize.width').out = True
    c.find('GetSize.height').out = True
    c.find('GetDPI.dpiX').out = True
    c.find('GetDPI.dpiY').out = True

    m = c.find('GetPartialTextExtents')
    m.find('widths').ignore()
    m.type = 'wxArrayDouble*'
    m.factory = True  # a new instance is being created
    m.setCppCode("""\
        wxArrayDouble rval;
        self->GetPartialTextExtents(*text, rval);
        return new wxArrayDouble(rval);
        """)

    m = c.find('GetTextExtent')
    m.pyName = 'GetFullTextExtent'
    m.find('width').out = True
    m.find('height').out = True
    m.find('descent').out = True
    m.find('externalLeading').out = True

    c.addCppMethod(
        'PyObject*',
        'GetTextExtent',
        '(const wxString& text)',
        pyArgsString="(text) -> (width, height)",
        doc=
        "Gets the dimensions of the string using the currently selected font.",
        body="""\
        wxDouble width = 0.0, height = 0.0;
        self->GetTextExtent(*text, &width, &height, NULL, NULL);
        wxPyThreadBlocker blocker;
        return sipBuildResult(0, "(dd)", width, height);
        """)

    c.addPyCode(
        "GraphicsContext.DrawRotatedText = wx.deprecated(GraphicsContext.DrawText, 'Use DrawText instead.')"
    )

    c.addCppCode(
        tools.ObjArrayHelperTemplate(
            'wxPoint2D', 'sipType_wxPoint2DDouble',
            "Expected a sequence of length-2 sequences or wx.Point2D objects.")
    )

    # we'll reimplement this overload as StrokeLineSegments
    c.find('StrokeLines').findOverload('beginPoints').ignore()
    c.addCppMethod('void',
                   'StrokeLineSegments',
                   '(PyObject* beginPoints, PyObject* endPoints)',
                   pyArgsString="(beginPoint2Ds, endPoint2Ds)",
                   doc="Stroke disconnected lines from begin to end points.",
                   body="""\
        size_t c1, c2, count;
        wxPoint2D* beginP = wxPoint2D_array_helper(beginPoints, &c1);
        wxPoint2D* endP =   wxPoint2D_array_helper(endPoints, &c2);

        if ( beginP != NULL && endP != NULL ) {
            count = wxMin(c1, c2);
            self->StrokeLines(count, beginP, endP);
        }
        delete [] beginP;
        delete [] endP;
        """)

    # Also reimplement the main StrokeLines method to reuse the same helper
    # function as StrokeLineSegments
    m = c.find('StrokeLines').findOverload('points').ignore()
    c.addCppMethod('void',
                   'StrokeLines',
                   '(PyObject* points)',
                   pyArgsString="(point2Ds)",
                   doc="Stroke lines conencting all the points.",
                   body="""\
        size_t count;
        wxPoint2D* ptsArray = wxPoint2D_array_helper(points, &count);

        if ( ptsArray != NULL ) {
            self->StrokeLines(count, ptsArray);
            delete [] ptsArray;
        }
        """)

    # and once more for DrawLines
    m = c.find('DrawLines').ignore()
    c.addCppMethod(
        'void',
        'DrawLines',
        '(PyObject* points, wxPolygonFillMode fillStyle = wxODDEVEN_RULE)',
        pyArgsString="(point2Ds, fillStyle=ODDEVEN_RULE)",
        doc="Draws a polygon.",
        body="""\
        size_t count;
        wxPoint2D* ptsArray = wxPoint2D_array_helper(points, &count);

        if ( ptsArray != NULL ) {
            self->DrawLines(count, ptsArray, fillStyle);
            delete [] ptsArray;
        }
        """)

    #---------------------------------------------
    c = module.find('wxGraphicsPath')
    tools.removeVirtuals(c)
    c.find('GetBox').findOverload('wxDouble *x, wxDouble *y').ignore()
    c.find('GetCurrentPoint').findOverload('wxDouble *x, wxDouble *y').ignore()
    c.mustHaveApp()

    #---------------------------------------------
    c = module.find('wxGraphicsRenderer')
    tools.removeVirtuals(c)
    markFactories(c)
    c.abstract = True

    for m in c.find('CreateContext').all():
        for p in m.items:
            if 'DC' in p.name or p.name == 'image':
                p.keepReference = True
    c.find('CreateContextFromImage.image').keepReference = True

    # FIXME: Handle wxEnhMetaFileDC?
    c.find('CreateContext').findOverload('wxEnhMetaFileDC').ignore()

    #---------------------------------------------
    c = module.find('wxGraphicsMatrix')
    tools.removeVirtuals(c)
    c.mustHaveApp()

    c.find('Concat').overloads = []
    c.find('IsEqual').overloads = []

    c.find('Get.a').out = True
    c.find('Get.b').out = True
    c.find('Get.c').out = True
    c.find('Get.d').out = True
    c.find('Get.tx').out = True
    c.find('Get.ty').out = True

    c.find('TransformDistance.dx').inOut = True
    c.find('TransformDistance.dy').inOut = True

    c.find('TransformPoint.x').inOut = True
    c.find('TransformPoint.y').inOut = True

    #---------------------------------------------
    c = module.find('wxGraphicsGradientStops')
    c.addCppMethod('SIP_SSIZE_T',
                   '__len__',
                   '()',
                   body="return (SIP_SSIZE_T)self->GetCount();")
    c.addCppMethod('wxGraphicsGradientStop*',
                   '__getitem__',
                   '(ulong n)',
                   pyArgsString='(n)',
                   body="return new wxGraphicsGradientStop(self->Item(n));",
                   factory=True)

    #---------------------------------------------
    # Use the pyNames we set for these classes in geometry.py so the old
    # names do not show up in the docstrings, etc.
    tools.changeTypeNames(module, 'wxPoint2DDouble', 'wxPoint2D')
    tools.changeTypeNames(module, 'wxRect2DDouble', 'wxRect2D')

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #40
0
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('wxConfigBase')
    assert isinstance(c, etgtools.ClassDef)
    c.mustHaveApp()

    c.abstract = True
    ctor = c.find('wxConfigBase')
    ctor.items.remove(ctor.find('conv'))
    c.find('ReadObject').ignore()

    c.find('Set'
           ).transferBack = True  # Python takes ownership of the return value
    c.find('Set.pConfig').transfer = True  # C++ takes ownership of the arg

    for func in c.findAll('Read'):
        if not 'wxString' in func.type:
            func.ignore()
        else:
            func.find('defaultVal').default = 'wxEmptyString'

    c.addCppMethod(
        'long', 'ReadInt', '(const wxString& key, long defaultVal=0)', """\
        long rv;
        self->Read(*key, &rv, defaultVal);
        return rv;
        """)
    c.addCppMethod(
        'double', 'ReadFloat', '(const wxString& key, double defaultVal=0.0)',
        """\
        double rv;
        self->Read(*key, &rv, defaultVal);
        return rv;
        """)
    c.find('ReadBool').ignore()
    c.addCppMethod(
        'bool', 'ReadBool', '(const wxString& key, bool defaultVal=false)',
        """\
        bool rv;
        self->Read(*key, &rv, defaultVal);
        return rv;
        """)

    c.find('Write').overloads = []
    c.addCppMethod('bool', 'WriteInt', '(const wxString& key, long value)',
                   """\
        return self->Write(*key, value);
        """)
    c.addCppMethod('bool', 'WriteFloat', '(const wxString& key, double value)',
                   """\
        return self->Write(*key, value);
        """)
    c.addCppMethod('bool', 'WriteBool', '(const wxString& key, bool value)',
                   """\
        return self->Write(*key, value);
        """)

    c.find('GetFirstGroup').ignore()
    c.find('GetNextGroup').ignore()
    c.find('GetFirstEntry').ignore()
    c.find('GetNextEntry').ignore()

    c.addCppCode("""\
        static PyObject* _Config_EnumerationHelper(bool flag, wxString& str, long index) {
        wxPyThreadBlocker blocker;
            PyObject* ret = PyTuple_New(3);
            if (ret) {
                PyTuple_SET_ITEM(ret, 0, PyBool_FromLong(flag));
                PyTuple_SET_ITEM(ret, 1, wx2PyString(str));
                PyTuple_SET_ITEM(ret, 2, wxPyInt_FromLong(index));
            }
            return ret;
        }
        """)

    c.addCppMethod('PyObject*',
                   'GetFirstGroup',
                   '()',
                   doc="""\
            GetFirstGroup() -> (more, value, index)\n
            Allows enumerating the subgroups in a config object.  Returns a tuple
            containing a flag indicating if there are more items, the name of the
            current item, and an index to pass to GetNextGroup to fetch the next
            item.""",
                   body="""\
            bool     more;
            long     index = 0;
            wxString value;
            more = self->GetFirstGroup(value, index);
            return _Config_EnumerationHelper(more, value, index);
            """)

    c.addCppMethod('PyObject*',
                   'GetNextGroup',
                   '(long index)',
                   doc="""\
            GetNextGroup(long index) -> (more, value, index)\n
            Allows enumerating the subgroups in a config object.  Returns a tuple
            containing a flag indicating if there are more items, the name of the
            current item, and an index to pass to GetNextGroup to fetch the next
            item.""",
                   body="""\
            bool more;
            wxString value;
            more = self->GetNextGroup(value, index);
            return _Config_EnumerationHelper(more, value, index);
            """)

    c.addCppMethod('PyObject*',
                   'GetFirstEntry',
                   '()',
                   doc="""\
            GetFirstEntry() -> (more, value, index)\n
            Allows enumerating the entries in the current group in a config
            object.  Returns a tuple containing a flag indicating if there are more
            items, the name of the current item, and an index to pass to
            GetNextEntry to fetch the next item.""",
                   body="""\
            bool     more;
            long     index = 0;
            wxString value;
            more = self->GetFirstEntry(value, index);
            return _Config_EnumerationHelper(more, value, index);
            """)

    c.addCppMethod('PyObject*',
                   'GetNextEntry',
                   '(long index)',
                   doc="""\
            GetNextEntry() -> (more, value, index)\n
            Allows enumerating the entries in the current group in a config
            object.  Returns a tuple containing a flag indicating if there are more
            items, the name of the current item, and an index to pass to
            GetNextEntry to fetch the next item.""",
                   body="""\
            bool     more;
            wxString value;
            more = self->GetNextEntry(value, index);
            return _Config_EnumerationHelper(more, value, index);
            """)

    #-----------------------------------------------------------------
    c = module.find('wxFileConfig')
    c.mustHaveApp()
    c.addPrivateCopyCtor()
    c.find('wxFileConfig').findOverload('wxInputStream').find('conv').ignore()
    ctor = c.find('wxFileConfig').findOverload('wxString').find(
        'conv').ignore()
    #ctor.items.remove(ctor.find('conv'))
    ctor = c.find('Save').find('conv').ignore()
    c.find('GetGlobalFile').ignore()
    c.find('GetLocalFile').ignore()

    c.find('GetFirstGroup').ignore()
    c.find('GetNextGroup').ignore()
    c.find('GetFirstEntry').ignore()
    c.find('GetNextEntry').ignore()

    #-----------------------------------------------------------------
    # In C++ wxConfig is a #define to some other config class. We'll let our
    # backend generator believe that it's a real class with that name. It will
    # end up using the wxConfig #defined in the C++ code, and will actually be
    # whatever is the default config class for the platform.
    wc = etgtools.WigCode("""\
    class wxConfig : wxConfigBase
    {
    public:
        wxConfig(const wxString& appName = wxEmptyString,
                 const wxString& vendorName = wxEmptyString,
                 const wxString& localFilename = wxEmptyString,
                 const wxString& globalFilename = wxEmptyString,
                 long style = wxCONFIG_USE_LOCAL_FILE | wxCONFIG_USE_GLOBAL_FILE);
        ~wxConfig();

        // pure virtuals with implementations here
        const wxString & GetPath() const;
        void SetPath(const wxString & strPath);
        size_t GetNumberOfEntries(bool bRecursive = false) const;
        size_t GetNumberOfGroups(bool bRecursive = false) const;
        bool HasEntry(const wxString & strName) const;
        bool HasGroup(const wxString & strName) const;
        bool Flush(bool bCurrentOnly = false);
        bool RenameEntry(const wxString & oldName, const wxString & newName);
        bool RenameGroup(const wxString & oldName, const wxString & newName);
        bool DeleteAll();
        bool DeleteEntry(const wxString & key, bool bDeleteGroupIfEmpty = true);
        bool DeleteGroup(const wxString & key);

    private:
        wxConfig(const wxConfig&);
    };
    """)
    module.addItem(wc)

    #-----------------------------------------------------------------
    c = module.find('wxConfigPathChanger')
    assert isinstance(c, etgtools.ClassDef)
    c.addPrivateCopyCtor()
    # context manager methods
    c.addPyMethod('__enter__', '(self)', 'return self')
    c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)',
                  'return False')

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #41
0
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('wxListItem')
    assert isinstance(c, etgtools.ClassDef)
    c.find('SetData').findOverload('void *').ignore()
    c.find('GetData').type = 'long'

    #-------------------------------------------------------
    c = module.find('wxListCtrl')
    tools.fixWindowClass(c)

    module.addGlobalStr('wxListCtrlNameStr', before=c)

    # Unignore some protected virtual methods that we want to allow to be
    # overridden in derived classes
    for name in [
            'OnGetItemAttr',
            #'OnGetItemColumnAttr',  # MSW only?
            'OnGetItemColumnImage',
            'OnGetItemImage',
            'OnGetItemText'
    ]:
        c.find(name).ignore(False)
        c.find(name).isVirtual = True

    # Tweaks to allow passing and using a Python callable object for the sort
    # compare function. First provide a sort callback function that can call the
    # Python function.
    c.addCppCode("""\
        static int wxCALLBACK wxPyListCtrl_SortItems(wxIntPtr item1, wxIntPtr item2, wxIntPtr funcPtr)
        {
            int retval = 0;
            PyObject* func = (PyObject*)funcPtr;
            wxPyThreadBlocker blocker;

        #if SIZEOF_LONG >= SIZEOF_VOID_P
            PyObject* args = Py_BuildValue("(ll)", item1, item2);
        #else
            PyObject* args = Py_BuildValue("(LL)", item1, item2);
        #endif

            PyObject* result = PyEval_CallObject(func, args);
            Py_DECREF(args);
            if (result) {
                retval = wxPyInt_AsLong(result);
                Py_DECREF(result);
            }
            return retval;
        }
        """)

    # Next, provide an alternate implementation of SortItems that will use that callback.
    sim = c.find('SortItems')
    assert isinstance(sim, etgtools.MethodDef)
    sim.find('fnSortCallBack').type = 'PyObject*'
    sim.find('data').ignore(
    )  # we will be using it to pass the python callback function
    sim.argsString = sim.argsString.replace('wxListCtrlCompare', 'PyObject*')
    sim.setCppCode("""\
        if (!PyCallable_Check(fnSortCallBack))
            return false;
        return self->SortItems((wxListCtrlCompare)wxPyListCtrl_SortItems,
                               (wxIntPtr)fnSortCallBack);
    """)

    # Change the semantics of GetColumn to return the item as the return
    # value instead of through a prameter.
    # bool GetColumn(int col, wxListItem& item) const;
    c.find('GetColumn').ignore()
    c.addCppMethod(
        'wxListItem*',
        'GetColumn',
        '(int col)',
        doc=
        'Gets information about this column. See SetItem() for more information.',
        factory=True,
        body="""\
        wxListItem item;
        item.SetMask( wxLIST_MASK_STATE |
                      wxLIST_MASK_TEXT  |
                      wxLIST_MASK_IMAGE |
                      wxLIST_MASK_DATA  |
                      wxLIST_SET_ITEM   |
                      wxLIST_MASK_WIDTH |
                      wxLIST_MASK_FORMAT
                      );
        if (self->GetColumn(col, item))
            return new wxListItem(item);
        else
            return NULL;
        """)

    # Do the same for GetItem
    # bool GetItem(wxListItem& info) const;
    c.find('GetItem').ignore()
    c.addCppMethod(
        'wxListItem*',
        'GetItem',
        '(int itemIdx, int col=0)',
        doc=
        'Gets information about the item. See SetItem() for more information.',
        factory=True,
        body="""\
        wxListItem* info = new wxListItem;
        info->m_itemId = itemIdx;
        info->m_col = col;
        info->m_mask = 0xFFFF;
        info->m_stateMask = 0xFFFF;
        self->GetItem(*info);
        return info;
        """)

    # bool GetItemPosition(long item, wxPoint& pos) const;
    c.find('GetItemPosition').ignore()
    c.addCppMethod(
        'wxPoint*',
        'GetItemPosition',
        '(long item)',
        doc='Returns the position of the item, in icon or small icon view.',
        factory=True,
        body="""\
        wxPoint* pos = new wxPoint;
        self->GetItemPosition(item, *pos);
        return pos;
        """)

    # bool GetItemRect(long item, wxRect& rect, int code = wxLIST_RECT_BOUNDS) const;
    c.find('GetItemRect').ignore()
    c.addCppMethod('wxRect*',
                   'GetItemRect',
                   '(long item, int code = wxLIST_RECT_BOUNDS)',
                   doc="""\
        Returns the rectangle representing the item's size and position, in physical coordinates.
        code is one of wx.LIST_RECT_BOUNDS, wx.LIST_RECT_ICON, wx.LIST_RECT_LABEL.""",
                   factory=True,
                   body="""\
        wxRect* rect = new wxRect;
        self->GetItemRect(item, *rect, code);
        return rect;
        """)

    c.find('EditLabel.textControlClass').ignore()
    c.find('EndEditLabel').ignore()
    c.find('AssignImageList.imageList').transfer = True
    c.find('HitTest.flags').out = True
    c.find('HitTest.ptrSubItem').ignore()

    c.addCppMethod(
        'PyObject*',
        'HitTestSubItem',
        '(const wxPoint& point)',
        pyArgsString="HitTestSubItem(point) -> (item, flags, subitem)",
        doc=
        "Determines which item (if any) is at the specified point, giving details in flags.",
        body="""\
            long item, subitem;
            int flags;
            item = self->HitTest(*point, flags, &subitem);
            wxPyThreadBlocker blocker;
            PyObject* rv = PyTuple_New(3);
            PyTuple_SetItem(rv, 0, wxPyInt_FromLong(item));
            PyTuple_SetItem(rv, 1, wxPyInt_FromLong(flags));
            PyTuple_SetItem(rv, 2, wxPyInt_FromLong(subitem));
            return rv;
            """)

    # Some deprecated aliases for Classic renames
    c.addPyCode(
        'ListCtrl.FindItemData = wx.deprecated(ListCtrl.FindItem, "Use FindItem instead.")'
    )
    c.addPyCode(
        'ListCtrl.FindItemAtPos = wx.deprecated(ListCtrl.FindItem, "Use FindItem instead.")'
    )
    c.addPyCode(
        'ListCtrl.InsertStringItem = wx.deprecated(ListCtrl.InsertItem, "Use InsertItem instead.")'
    )
    c.addPyCode(
        'ListCtrl.InsertImageItem = wx.deprecated(ListCtrl.InsertItem, "Use InsertItem instead.")'
    )
    c.addPyCode(
        'ListCtrl.InsertImageStringItem = wx.deprecated(ListCtrl.InsertItem, "Use InsertItem instead.")'
    )
    c.addPyCode(
        'ListCtrl.SetStringItem = wx.deprecated(ListCtrl.SetItem, "Use SetItem instead.")'
    )

    # Provide a way to determine if column ordering is possble
    c.addCppMethod(
        'bool', 'HasColumnOrderSupport', '()', """\
        #ifdef wxHAS_LISTCTRL_COLUMN_ORDER
            return true;
        #else
            return false;
        #endif
        """)

    # And provide implementation of those methods that will work whether or
    # not wx has column ordering support
    c.find('GetColumnOrder').setCppCode("""\
        #ifdef wxHAS_LISTCTRL_COLUMN_ORDER
            return self->GetColumnOrder(col);
        #else
            wxPyRaiseNotImplemented();
            return 0;
        #endif
        """)

    c.find('GetColumnIndexFromOrder').setCppCode("""\
        #ifdef wxHAS_LISTCTRL_COLUMN_ORDER
            return self->GetColumnIndexFromOrder(pos);
        #else
            wxPyRaiseNotImplemented();
            return 0;
        #endif
        """)

    c.find('GetColumnsOrder').type = 'wxArrayInt*'
    c.find('GetColumnsOrder').factory = True
    c.find('GetColumnsOrder').setCppCode("""\
        #ifdef wxHAS_LISTCTRL_COLUMN_ORDER
            return new wxArrayInt(self->GetColumnsOrder());
        #else
            wxPyRaiseNotImplemented();
            return new wxArrayInt();
        #endif
        """)

    c.find('SetColumnsOrder').setCppCode("""\
        #ifdef wxHAS_LISTCTRL_COLUMN_ORDER
            return self->SetColumnsOrder(*orders);
        #else
            wxPyRaiseNotImplemented();
            return false;
        #endif
        """)

    # Add some Python helper methods
    c.addPyMethod('Select',
                  '(self, idx, on=1)',
                  doc='Selects/deselects an item.',
                  body="""\
        if on: state = wx.LIST_STATE_SELECTED
        else: state = 0
        self.SetItemState(idx, state, wx.LIST_STATE_SELECTED)
        """)

    c.addPyMethod('Focus',
                  '(self, idx)',
                  doc='Focus and show the given item.',
                  body="""\
        self.SetItemState(idx, wx.LIST_STATE_FOCUSED, wx.LIST_STATE_FOCUSED)
        self.EnsureVisible(idx)
        """)

    c.addPyMethod(
        'GetFocusedItem',
        '(self)',
        doc='Gets the currently focused item or -1 if none is focused.',
        body=
        'return self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_FOCUSED)')

    c.addPyMethod(
        'GetFirstSelected',
        '(self, *args)',
        doc='Returns the first selected item, or -1 when none is selected.',
        body="return self.GetNextSelected(-1)")

    c.addPyMethod(
        'GetNextSelected',
        '(self, item)',
        doc=
        'Returns subsequent selected items, or -1 when no more are selected.',
        body=
        "return self.GetNextItem(item, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)"
    )

    c.addPyMethod(
        'IsSelected',
        '(self, idx)',
        doc='Returns ``True`` if the item is selected.',
        body=
        "return (self.GetItemState(idx, wx.LIST_STATE_SELECTED) & wx.LIST_STATE_SELECTED) != 0"
    )

    c.addPyMethod('SetColumnImage',
                  '(self, col, image)',
                  body="""\
        item = self.GetColumn(col)
        # preserve all other attributes too
        item.SetMask( wx.LIST_MASK_STATE |
                      wx.LIST_MASK_TEXT  |
                      wx.LIST_MASK_IMAGE |
                      wx.LIST_MASK_DATA  |
                      wx.LIST_SET_ITEM   |
                      wx.LIST_MASK_WIDTH |
                      wx.LIST_MASK_FORMAT )
        item.SetImage(image)
        self.SetColumn(col, item)
        """)

    c.addPyMethod('ClearColumnImage',
                  '(self, col)',
                  body="self.SetColumnImage(col, -1)")

    c.addPyMethod('Append',
                  '(self, entry)',
                  doc='''\
        Append an item to the list control.  The `entry` parameter should be a
        sequence with an item for each column''',
                  body="""\
        if len(entry):
            from six import text_type
            pos = self.GetItemCount()
            self.InsertItem(pos, text_type(entry[0]))
            for i in range(1, len(entry)):
                self.SetItem(pos, i, text_type(entry[i]))
            return pos
        """)

    c.addCppMethod('wxWindow*',
                   'GetMainWindow',
                   '()',
                   body="""\
        #if defined(__WXMSW__) || defined(__WXMAC__)
            return self;
        #else
            return (wxWindow*)self->m_mainWin;
        #endif
        """)

    #-------------------------------------------------------
    c = module.find('wxListView')
    tools.fixWindowClass(c)

    #-------------------------------------------------------
    c = module.find('wxListEvent')
    tools.fixEventClass(c)

    c.addPyCode("""\
        EVT_LIST_BEGIN_DRAG        = PyEventBinder(wxEVT_LIST_BEGIN_DRAG       , 1)
        EVT_LIST_BEGIN_RDRAG       = PyEventBinder(wxEVT_LIST_BEGIN_RDRAG      , 1)
        EVT_LIST_BEGIN_LABEL_EDIT  = PyEventBinder(wxEVT_LIST_BEGIN_LABEL_EDIT , 1)
        EVT_LIST_END_LABEL_EDIT    = PyEventBinder(wxEVT_LIST_END_LABEL_EDIT   , 1)
        EVT_LIST_DELETE_ITEM       = PyEventBinder(wxEVT_LIST_DELETE_ITEM      , 1)
        EVT_LIST_DELETE_ALL_ITEMS  = PyEventBinder(wxEVT_LIST_DELETE_ALL_ITEMS , 1)
        EVT_LIST_ITEM_SELECTED     = PyEventBinder(wxEVT_LIST_ITEM_SELECTED    , 1)
        EVT_LIST_ITEM_DESELECTED   = PyEventBinder(wxEVT_LIST_ITEM_DESELECTED  , 1)
        EVT_LIST_KEY_DOWN          = PyEventBinder(wxEVT_LIST_KEY_DOWN         , 1)
        EVT_LIST_INSERT_ITEM       = PyEventBinder(wxEVT_LIST_INSERT_ITEM      , 1)
        EVT_LIST_COL_CLICK         = PyEventBinder(wxEVT_LIST_COL_CLICK        , 1)
        EVT_LIST_ITEM_RIGHT_CLICK  = PyEventBinder(wxEVT_LIST_ITEM_RIGHT_CLICK , 1)
        EVT_LIST_ITEM_MIDDLE_CLICK = PyEventBinder(wxEVT_LIST_ITEM_MIDDLE_CLICK, 1)
        EVT_LIST_ITEM_ACTIVATED    = PyEventBinder(wxEVT_LIST_ITEM_ACTIVATED   , 1)
        EVT_LIST_CACHE_HINT        = PyEventBinder(wxEVT_LIST_CACHE_HINT       , 1)
        EVT_LIST_COL_RIGHT_CLICK   = PyEventBinder(wxEVT_LIST_COL_RIGHT_CLICK  , 1)
        EVT_LIST_COL_BEGIN_DRAG    = PyEventBinder(wxEVT_LIST_COL_BEGIN_DRAG   , 1)
        EVT_LIST_COL_DRAGGING      = PyEventBinder(wxEVT_LIST_COL_DRAGGING     , 1)
        EVT_LIST_COL_END_DRAG      = PyEventBinder(wxEVT_LIST_COL_END_DRAG     , 1)
        EVT_LIST_ITEM_FOCUSED      = PyEventBinder(wxEVT_LIST_ITEM_FOCUSED     , 1)

        # deprecated wxEVT aliases
        wxEVT_COMMAND_LIST_BEGIN_DRAG         = wxEVT_LIST_BEGIN_DRAG
        wxEVT_COMMAND_LIST_BEGIN_RDRAG        = wxEVT_LIST_BEGIN_RDRAG
        wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT   = wxEVT_LIST_BEGIN_LABEL_EDIT
        wxEVT_COMMAND_LIST_END_LABEL_EDIT     = wxEVT_LIST_END_LABEL_EDIT
        wxEVT_COMMAND_LIST_DELETE_ITEM        = wxEVT_LIST_DELETE_ITEM
        wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS   = wxEVT_LIST_DELETE_ALL_ITEMS
        wxEVT_COMMAND_LIST_ITEM_SELECTED      = wxEVT_LIST_ITEM_SELECTED
        wxEVT_COMMAND_LIST_ITEM_DESELECTED    = wxEVT_LIST_ITEM_DESELECTED
        wxEVT_COMMAND_LIST_KEY_DOWN           = wxEVT_LIST_KEY_DOWN
        wxEVT_COMMAND_LIST_INSERT_ITEM        = wxEVT_LIST_INSERT_ITEM
        wxEVT_COMMAND_LIST_COL_CLICK          = wxEVT_LIST_COL_CLICK
        wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK   = wxEVT_LIST_ITEM_RIGHT_CLICK
        wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK  = wxEVT_LIST_ITEM_MIDDLE_CLICK
        wxEVT_COMMAND_LIST_ITEM_ACTIVATED     = wxEVT_LIST_ITEM_ACTIVATED
        wxEVT_COMMAND_LIST_CACHE_HINT         = wxEVT_LIST_CACHE_HINT
        wxEVT_COMMAND_LIST_COL_RIGHT_CLICK    = wxEVT_LIST_COL_RIGHT_CLICK
        wxEVT_COMMAND_LIST_COL_BEGIN_DRAG     = wxEVT_LIST_COL_BEGIN_DRAG
        wxEVT_COMMAND_LIST_COL_DRAGGING       = wxEVT_LIST_COL_DRAGGING
        wxEVT_COMMAND_LIST_COL_END_DRAG       = wxEVT_LIST_COL_END_DRAG
        wxEVT_COMMAND_LIST_ITEM_FOCUSED       = wxEVT_LIST_ITEM_FOCUSED
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #42
0
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.

    # These are duplicates, ignore the ones in this module
    module.find('wxPG_PROPERTYVALUES_FLAGS').ignore()
    module.find('wxPG_LABEL').ignore()
    module.find('wxPG_LABEL_STRING').ignore()
    module.find('wxPG_COLOUR_BLACK').ignore()
    module.find('wxPG_COLOUR').ignore()
    module.find('wxPG_DEFAULT_IMAGE_SIZE').ignore()


    #----------------------------------------------------------
    c = module.find('wxPGPropArgCls')
    assert isinstance(c, etgtools.ClassDef)
    c.find('wxPGPropArgCls').findOverload('wxString &').ignore()
    c.find('wxPGPropArgCls').findOverload('char *').ignore()
    c.find('wxPGPropArgCls').findOverload('wchar_t *').ignore()
    c.find('wxPGPropArgCls').findOverload('int').ignore()
    c.find('wxPGPropArgCls').findOverload('deallocPtr').ignore()

    # Make a string ctor that uses the wxPython-specific version of
    # the C++ class' ctor
    newCtor = c.addCppCtor('(const wxString& str)',
        doc="Creates a PGPropArgCls from a string.",
        body="""\
            wxString* name = new wxString(*str);
            return new wxPGPropArgCls(name, true);
        """
        )

    # Make it be the first overload instead of the last
    ctor = c.find('wxPGPropArgCls')
    overloads = list(ctor.overloads)
    del overloads[overloads.index(newCtor)]
    overloads.insert(0, newCtor)
    ctor.overloads = overloads


    c.find('GetPtr').overloads[0].ignore()

    c.convertFromPyObject = """\
        // Code to test a PyObject for compatibility with wxPGPropArgCls
        if (!sipIsErr) {
            if (sipCanConvertToType(sipPy, sipType_wxPGPropArgCls, SIP_NO_CONVERTORS))
                return TRUE;
            if (PyBytes_Check(sipPy) || PyUnicode_Check(sipPy))
                return TRUE;
            if (sipPy == Py_None)
                return TRUE;
            if (sipCanConvertToType(sipPy, sipType_wxPGProperty, SIP_NO_CONVERTORS))
                return TRUE;
            return FALSE;
        }

        // Code to convert a compatible PyObject to a wxPGPropArgCls
        if (PyBytes_Check(sipPy) || PyUnicode_Check(sipPy)) {
            wxString* name = new wxString(Py2wxString(sipPy));
            *sipCppPtr = new wxPGPropArgCls(name, true);
            return sipGetState(sipTransferObj);
        }
        else if (sipCanConvertToType(sipPy, sipType_wxPGProperty, SIP_NO_CONVERTORS)) {
            int state = 0;
            wxPGProperty* prop = reinterpret_cast<wxPGProperty*>(
                sipConvertToType(sipPy, sipType_wxPGProperty, sipTransferObj, SIP_NO_CONVERTORS, &state, sipIsErr));
            *sipCppPtr = new wxPGPropArgCls(prop);
            sipReleaseType(prop, sipType_wxPGProperty, state);
            return sipGetState(sipTransferObj);
        }
        else if (sipPy == Py_None) {
            *sipCppPtr = new wxPGPropArgCls(static_cast< wxPGProperty * >(NULL));
            return sipGetState(sipTransferObj);
        }
        else {
            // It's already a wxPGPropArgCls, just fetch the pointer and return
            *sipCppPtr = reinterpret_cast<wxPGPropArgCls*>(sipConvertToType(
                sipPy, sipType_wxPGPropArgCls, sipTransferObj,
                SIP_NO_CONVERTORS, 0, sipIsErr));
            return 0; // not a new instance
        }
        """


    #----------------------------------------------------------
    c = module.find('wxPropertyGridInterface')
    c.abstract = True
    for m in c.findAll('GetIterator'):
        if m.type == 'wxPropertyGridConstIterator':
            m.ignore()

    tools.ignoreConstOverloads(c)

    spv = c.find('SetPropertyValue')
    spv.findOverload('int value').ignore()
    spv.findOverload('wxLongLong value').ignore()
    spv.findOverload('wxLongLong_t value').ignore()
    spv.findOverload('wxULongLong value').ignore()
    spv.findOverload('wxULongLong_t value').ignore()
    spv.findOverload('wxObject *value').ignore()
    spv.findOverload('wchar_t *value').ignore()
    spv.findOverload('char *value').ignore()

    # Reorder SetPropertyValue overloads so the one taking a long int is not
    # first. Mark others that could be auto-converted from int as
    # "constrained" so they will only be used for that specific type. This
    # should result in SetPropertyValue(id, double) only used for floats and
    # not ints, or other things that can convert to int.
    spv.findOverload('bool value').find('value').constrained = True
    spv.findOverload('double value').find('value').constrained = True
    spv_long = spv.findOverload('long value')
    spv_long.ignore()
    spv.reorderOverloads() # Ensures an ignored item is not first,
    spv_long.ignore(False) # and then we can unignore it.


    c.find('Append.property').transfer = True
    c.find('AppendIn.newProperty').transfer = True
    for m in c.find('Insert').all():
        m.find('newProperty').transfer = True

    # Fix some syntax that sip doesn't like
    p = c.find('GetPropertiesWithFlag.iterFlags')
    if p.default.startswith('('):
        p.default = p.default[1:-1]


    # Tons of Python method implementations ported from Classic...

    module.addPyCode("""\
        _type2property = None
        _vt2getter = None
        """)

    c.addPyMethod('MapType', '(self, class_, factory)',
        doc="""\
            Registers Python type/class to property mapping.

            :param `factory`: Property builder function/class.
            """,
        body="""\
            global _type2property
            if _type2property is None:
                raise AssertionError("call only after a propertygrid or "
                                     "manager instance constructed")
            _type2property[class_] = factory
            """)


    c.addPyMethod('DoDefaultTypeMappings', '(self)',
        doc="Add built-in properties to the map.",
        body="""\
            import sys
            global _type2property
            if _type2property is not None:
                return
            _type2property = dict()

            _type2property[str] = StringProperty
            if sys.version_info.major < 2:
                _type2property[unicode] = StringProperty
            _type2property[int] = IntProperty
            _type2property[float] = FloatProperty
            _type2property[bool] = BoolProperty
            _type2property[list] = ArrayStringProperty
            _type2property[tuple] = ArrayStringProperty
            _type2property[wx.Font] = FontProperty
            _type2property[wx.Colour] = ColourProperty
            #_type2property[wx.Size] = SizeProperty
            #_type2property[wx.Point] = PointProperty
            #_type2property[wx.FontData] = FontDataProperty
            """)


    # TODO: is this still needed?
    c.addPyMethod('DoDefaultValueTypeMappings', '(self)',
        doc="Map pg value type ids to getter methods.",
        body="""\
            global _vt2getter
            if _vt2getter is not None:
                return
            _vt2getter = dict()
        """)


    c.find('GetPropertyValues').ignore()
    c.addPyMethod('GetPropertyValues',
        '(self, dict_=None, as_strings=False, inc_attributes=False, flags=PG_ITERATE_PROPERTIES)',
        doc="""\
            Returns all property values in the grid.

            :param `dict_`: A diftionary to fill with the property values.
                If not given, then a new one is created. The dict_ can be an
                object as well, in which case it's __dict__ is used.
            :param `as_strings`: if True, then string representations of values
                are fetched instead of native types. Useful for config and such.
            :param `inc_attributes`: if True, then property attributes are added
                in the form of ``"@<propname>@<attr>"``.
            :param `flags`: Flags to pass to the iterator. See :ref:`wx.propgrid.PG_ITERATOR_FLAGS`.
            :returns: A dictionary with values. It is always a dictionary,
                so if dict_ was an object with __dict__ attribute, then that
                attribute is returned.
            """,
        body="""\
            if dict_ is None:
                dict_ = {}
            elif hasattr(dict_,'__dict__'):
                dict_ = dict_.__dict__

            getter = self.GetPropertyValue if not as_strings else self.GetPropertyValueAsString

            it = self.GetVIterator(flags)
            while not it.AtEnd():
                p = it.GetProperty()
                name = p.GetName()
                dict_[name] = getter(p)

                if inc_attributes:
                    attrs = p.GetAttributes()
                    if attrs and len(attrs):
                        dict_['@%s@attr'%name] = attrs

                it.Next()

            return dict_
            """)


    for m in c.find('SetPropertyValues').all():
        m.ignore()
    c.addPyMethod('SetPropertyValues', '(self, dict_, autofill=False)',
        doc="""\
            Sets property values from a dictionary.\n
            :param `dict_`: the source of the property values to set, which can be
                either a dictionary or an object with a __dict__ attribute.
            :param `autofill`: If true, keys with not relevant properties are
                auto-created. For more info, see :method:`AutoFill`.

            :note:
              * Keys starting with underscore are ignored.
              * Attributes can be set with entries named like "@<propname>@<attr>".
            """,
        body="""\
            if dict_ is None:
                dict_ = {}
            elif hasattr(dict_,'__dict__'):
                dict_ = dict_.__dict__
            attr_dicts = []

            def set_sub_obj(k0, dict_):
                for k,v in dict_.items():
                    if k[0] != '_':
                        if k.endswith('@attr'):
                            attr_dicts.append((k[1:-5],v))
                        else:
                            try:
                                self.SetPropertyValue(k,v)
                            except:
                                try:
                                    if autofill:
                                        self._AutoFillOne(k0,k,v)
                                        continue
                                except:
                                    if isinstance(v,dict):
                                        set_sub_obj(k,v)
                                    elif hasattr(v,'__dict__'):
                                        set_sub_obj(k,v.__dict__)

                for k,v in attr_dicts:
                    p = self.GetPropertyByName(k)
                    if not p:
                        raise AssertionError("No such property: '%s'"%k)
                    for an,av in v.items():
                        p.SetAttribute(an, av)


            cur_page = False
            is_manager = isinstance(self, PropertyGridManager)

            try:
                set_sub_obj(self.GetGrid().GetRoot(), dict_)
            except:
                import traceback
                traceback.print_exc()

            self.Refresh()
            """)

    # TODO: should these be marked as deprecated? Probably...
    module.addPyCode("""\
        PropertyGridInterface.GetValues = PropertyGridInterface.GetPropertyValues
        PropertyGridInterface.SetValues = PropertyGridInterface.SetPropertyValues
        """)


    c.addPyMethod('_AutoFillMany', '(self,cat,dict_)',
        body="""\
            for k,v in dict_.items():
                self._AutoFillOne(cat,k,v)
            """)

    c.addPyMethod('_AutoFillOne', '(self,cat,k,v)',
        body="""\
            global _type2property
            factory = _type2property.get(v.__class__,None)
            if factory:
                self.AppendIn(cat, factory(k,k,v))
            elif hasattr(v,'__dict__'):
                cat2 = self.AppendIn(cat, PropertyCategory(k))
                self._AutoFillMany(cat2, v.__dict__)
            elif isinstance(v, dict):
                cat2 = self.AppendIn(cat, PropertyCategory(k))
                self._AutoFillMany(cat2, v)
            elif not k.startswith('_'):
                raise AssertionError("member '%s' is of unregistered type/"
                                     "class '%s'"%(k,v.__class__))
            """)

    c.addPyMethod('AutoFill', '(self, obj, parent=None)',
        doc="""\
            "Clears properties and re-fills to match members and values of
            the given object or dictionary obj.
            """,
        body="""\
            self.edited_objects[parent] = obj

            cur_page = False
            is_manager = isinstance(self, PropertyGridManager)

            if not parent:
                if is_manager:
                    page = self.GetCurrentPage()
                    page.Clear()
                    parent = page.GetRoot()
                else:
                    self.Clear()
                    parent = self.GetGrid().GetRoot()
            else:
                it = self.GetIterator(PG_ITERATE_PROPERTIES, parent)
                it.Next()  # Skip the parent
                while not it.AtEnd():
                    p = it.GetProperty()
                    if not p.IsSomeParent(parent):
                        break

                    self.DeleteProperty(p)

                    name = p.GetName()
                    it.Next()

            if not is_manager or page == self.GetCurrentPage():
                self.Freeze()
                cur_page = True

            try:
                self._AutoFillMany(parent,obj.__dict__)
            except:
                import traceback
                traceback.print_exc()

            if cur_page:
                self.Thaw()
            """)


    c.addPyMethod('RegisterEditor', '(self, editor, editorName=None)',
        doc="Register a new editor, either an instance or a class.",
        body="""\
            if not isinstance(editor, PGEditor):
                editor = editor()
            if not editorName:
                editorName = editor.__class__.__name__
            try:
                self._editor_instances.append(editor)
            except:
                self._editor_instances = [editor]
            return PropertyGrid.DoRegisterEditorClass(editor, editorName)
            """
        )


    c.find('GetPropertyClientData').ignore()
    c.addPyMethod('GetPropertyClientData', '(self, p)',
        body="""\
            if isinstance(p, str):
                p = self.GetPropertyByName(p)
            return p.GetClientData()
            """)

    c.find('SetPropertyClientData').ignore()
    c.addPyMethod('SetPropertyClientData', '(self, p, data)',
        body="""\
            if isinstance(p, str):
                p = self.GetPropertyByName(p)
            return p.SetClientData(data)
            """)



    c.addPyMethod('GetPyIterator', '(self, flags=PG_ITERATE_DEFAULT, firstProperty=None)',
        doc="""\
            Returns a pythonic property iterator for a single :ref:`PropertyGrid`
            or page in :ref:`PropertyGridManager`. Arguments are same as for
            :ref:`GetIterator`.

            The following example demonstrates iterating absolutely all items in
            a single grid::

                iterator = propGrid.GetPyIterator(wx.propgrid.PG_ITERATE_ALL)
                for prop in iterator:
                    print(prop)

            :see: `wx.propgrid.PropertyGridInterface.Properties`
                  `wx.propgrid.PropertyGridInterface.Items`
            """,
        body="""\
            it = self.GetIterator(flags, firstProperty)
            while not it.AtEnd():
                yield it.GetProperty()
                it.Next()
            """)


    c.addPyMethod('GetPyVIterator', '(self, flags=PG_ITERATE_DEFAULT)',
        doc="""\
            Similar to :ref:`GetVIterator` but returns a pythonic iterator.
            """,
        body="""\
            it = self.GetVIterator(flags)
            while not it.AtEnd():
                yield it.GetProperty()
                it.Next()
            """)


    c.addPyMethod('_Properties', '(self)',
        doc="""\
            This attribute is a pythonic iterator over all properties in
            this `PropertyGrid` property container. It will only skip
            categories and private child properties. Usage is simple::

                for prop in propGrid.Properties:
                    print(prop)

            :see: `wx.propgrid.PropertyGridInterface.Items`
                  `wx.propgrid.PropertyGridInterface.GetPyIterator`
            """,
        body="""\
            it = self.GetIterator(PG_ITERATE_NORMAL)
            while not it.AtEnd():
                yield it.GetProperty()
                it.Next()
            """)
    c.addPyProperty('Properties', '_Properties')


    c.addPyMethod('_Items', '(self)',
        doc="""\
            This attribute is a pythonic iterator over all items in this
            `PropertyGrid` property container, excluding only private child
            properties. Usage is simple::

                for prop in propGrid.Items:
                    print(prop)

            :see: `wx.propgrid.PropertyGridInterface.Properties`
                  `wx.propgrid.PropertyGridInterface.GetPyVIterator`
            """,
        body="""\
            it = self.GetVIterator(PG_ITERATE_NORMAL | PG_ITERATE_CATEGORIES)
            while not it.AtEnd():
                yield it.GetProperty()
                it.Next()
            """)
    c.addPyProperty('Items', '_Items')


    def postProcessReST(text):
        # fix some autodoc glitches
        text = text.replace(':ref:`PropertyGridIterator Flags <propertygriditerator flags>`',
                            ':ref:`wx.propgrid.PG_ITERATOR_FLAGS`')
        return text

    c.setReSTPostProcessor(postProcessReST)

    #----------------------------------------------------------

    module.addItem(
        tools.wxArrayPtrWrapperTemplate('wxArrayPGProperty', 'wxPGProperty', module))



    # wxPGPropArg is a typedef for "const wxPGPropArgCls&" so having the
    # wrappers treat it as a normal type can be problematic. ("new cannot be
    # applied to a reference type", etc.) Let's just ignore it and replace it
    # everywhere for the real type.
    module.find('wxPGPropArg').ignore()
    for item in module.allItems():
        if hasattr(item, 'type') and item.type == 'wxPGPropArg':
            item.type = 'const wxPGPropArgCls &'


    # Switch all wxVariant types to wxPGVariant, so the propgrid-specific
    # version of the MappedType will be used for converting to/from Python
    # objects.
    for item in module.allItems():
        if hasattr(item, 'type') and 'wxVariant' in item.type:
            item.type = item.type.replace('wxVariant', 'wxPGVariant')


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #43
0
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('wxPageSetupDialogData')
    assert isinstance(c, etgtools.ClassDef)
    tools.removeVirtuals(c)

    c.find('GetPrintData').overloads = []

    c.addCppMethod('int', '__nonzero__', '()', "return self->IsOk();")
    c.addCppMethod('int', '__bool__', '()', "return self->IsOk();")

    c.addProperty('MarginBottomRight', 'GetMarginBottomRight',
                  'SetMarginBottomRight')
    c.addProperty('MarginTopLeft', 'GetMarginTopLeft', 'SetMarginTopLeft')
    c.addProperty('MinMarginBottomRight', 'GetMinMarginBottomRight',
                  'SetMinMarginBottomRight')
    c.addProperty('MinMarginTopLeft', 'GetMinMarginTopLeft',
                  'SetMinMarginTopLeft')
    c.addProperty('PaperId', 'GetPaperId', 'SetPaperId')
    c.addProperty('PaperSize', 'GetPaperSize', 'SetPaperSize')
    c.addProperty('PrintData', 'GetPrintData', 'SetPrintData')

    c = module.find('wxPrintData')
    assert isinstance(c, etgtools.ClassDef)
    tools.removeVirtuals(c)

    c.addCppMethod('wxSize*', 'GetPaperSize', '()',
                   'return new wxSize(self->GetPaperSize());')
    c.addCppMethod('void', 'SetPaperSize', '(const wxSize* sz)',
                   'self->SetPaperSize(*sz);')

    c.addCppMethod('int', '__nonzero__', '()', "return self->IsOk();")
    c.addCppMethod('int', '__bool__', '()', "return self->IsOk();")

    # TODO: These two methods should use something other than a PyString for
    # holding the data...
    c.addCppMethod(
        'PyObject*', 'GetPrivData', '()', """\
        PyObject* data;
        wxPyThreadBlocker blocker;
        data = PyBytes_FromStringAndSize(self->GetPrivData(),
                                         self->GetPrivDataLen());
        return data;
        """)

    c.addCppMethod(
        'void', 'SetPrivData', '(PyObject* data)', """\
        wxPyThreadBlocker blocker;
        if (! PyBytes_Check(data)) {
            wxPyErr_SetString(PyExc_TypeError, "Expected string object");
            return;
        }

        self->SetPrivData(PyBytes_AS_STRING(data), PyBytes_GET_SIZE(data));
        """)

    c.addAutoProperties()

    c = module.find('wxPrintDialogData')
    assert isinstance(c, etgtools.ClassDef)
    tools.removeVirtuals(c)
    c.find('SetSetupDialog').ignore()

    c.addCppMethod('int', '__nonzero__', '()', "return self->IsOk();")
    c.addCppMethod('int', '__bool__', '()', "return self->IsOk();")

    c.addAutoProperties()

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #44
0
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('wxNumericPropertyValidator')
    assert isinstance(c, etgtools.ClassDef)
    c.bases = ['wxValidator']

    c = module.find('wxNumericProperty')
    c.find('wxNumericProperty').ignore(False)
    c.addPrivateDefaultCtor()

    c = module.find('wxEditorDialogProperty')
    c.find('wxEditorDialogProperty').ignore(False)
    c.find('DisplayEditorDialog').ignore(False)
    c.addPrivateDefaultCtor()

    for name in ['wxEnumProperty', 'wxEditEnumProperty']:
        c = module.find(name)
        # Ignore problematic ctors, that we don't need anyway.
        # Yes, there are two of them
        c.find(name).findOverload('wxChar').ignore()
        c.find(name).findOverload('wxChar').ignore()

        m = c.find(name).findOverload('wxArrayString')
        m.find('label').default = 'wxPG_LABEL'
        m.find('name').default = 'wxPG_LABEL'
        m.find('labels').default = 'wxArrayString()'

    c = module.find('wxFlagsProperty')
    # Ignore problematic ctors, that we don't need anyway.
    c.find('wxFlagsProperty').findOverload('wxChar').ignore()

    c = module.find('wxIntProperty')
    # clear the parts of the docstrings that are not really applicable to Python
    c.briefDoc = "Basic property with integer value."
    c.detailedDoc = []

    c = module.find('wxLongStringProperty')
    tools.fixDialogProperty(c)

    c = module.find('wxDirProperty')
    tools.fixDialogProperty(c)

    c = module.find('wxFileProperty')
    tools.fixDialogProperty(c)

    c = module.find('wxArrayStringProperty')
    tools.fixDialogProperty(c)
    c.find('GenerateValueAsString').ignore(False)

    c = module.find('wxPGArrayEditorDialog')
    tools.fixWindowClass(c, hideVirtuals=False, ignoreProtected=False)

    c = module.find('wxPGArrayStringEditorDialog')
    tools.fixWindowClass(c, hideVirtuals=False, ignoreProtected=False)

    # Switch all wxVariant types to wxPGVariant, so the propgrid-specific
    # version of the MappedType will be used for converting to/from Python
    # objects.
    for item in module.allItems():
        if hasattr(item, 'type') and 'wxVariant' in item.type:
            item.type = item.type.replace('wxVariant', 'wxPGVariant')

    # Switch all StringToValue and IntToValue methods to return the variant
    # value instead of using it as a parameter.
    for item in module.allItems():
        if (item.name in ['StringToValue', 'IntToValue']
                and item.findItem('variant')):
            item.find('variant').out = True

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #45
0
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)
Exemple #46
0
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.

    # do not use the va_list forms of the functions
    for func in module.allItems():
        if 'wxVLog' in func.name:
            func.ignore()

    for f in module.find('wxLogTrace').all():  # deprecated in 2.8
        f.ignore()

    # Switch the parameters to wxStrings to capitalize on the conversion code
    # we already have for them. String formatting can be done in Python if
    # needed. Drop the '...' too.
    for name in [
            'wxLogMessage', 'wxLogVerbose', 'wxLogWarning', 'wxLogFatalError',
            'wxLogError', 'wxLogDebug', 'wxLogStatus', 'wxLogSysError',
            'wxLogGeneric'
    ]:
        for f in module.find(name).all():
            p = f.find('formatString')
            p.type = 'const wxString&'
            p.name = 'message'
            f.items = f.items[:-1]

    module.find('wxSysErrorMsg').type = 'wxString'

    c = module.find('wxLogRecordInfo')
    c.find('threadId').ignore()

    c = module.find('wxLog')
    assert isinstance(c, etgtools.ClassDef)
    c.addPrivateCopyCtor()
    c.addDefaultCtor('public')
    c.addDtor('public', isVirtual=True)

    c.find('SetActiveTarget').transferBack = True
    c.find('SetActiveTarget.logtarget').transfer = True
    c.find('SetThreadActiveTarget').transferBack = True
    c.find('SetThreadActiveTarget.logger').transfer = True

    # we need to un-ignore these protected methods as they need to be overridable
    c.find('DoLogRecord').ignore(False)
    c.find('DoLogTextAtLevel').ignore(False)
    c.find('DoLogText').ignore(False)

    c = module.find('wxLogStderr')
    c.find('wxLogStderr.fp').ignore()
    c.find('wxLogStderr.conv').ignore()
    c.addPrivateCopyCtor()
    c.addPrivateAssignOp()

    c = module.find('wxLogBuffer')
    c.addPrivateCopyCtor()
    c.addPrivateAssignOp()

    c = module.find('wxLogChain')
    c.addPrivateCopyCtor()
    c.addPrivateAssignOp()

    c = module.find('wxLogGui')
    c.addPrivateCopyCtor()
    c.addPrivateAssignOp()

    c = module.find('wxLogTextCtrl')
    c.addPrivateCopyCtor()
    c.addPrivateAssignOp()

    c = module.find('wxLogFormatter')
    c.find('FormatTime').ignore(False)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #47
0
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*(double d);
        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*(double d);
        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* truncates to int before assigning to the new point
    # object, which seems dumb. So let's make our own implementation which
    # preserves the floating point result.
    c.addCppMethod('wxRealPoint*',
                   '__mul__',
                   '(double d)',
                   isSlot=True,
                   body="""\
            return new wxRealPoint(self->x * d, self->y * d);
            """)

    # 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)
Exemple #48
0
def run():
    module = parseAndTweakModule()
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #49
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(
        PACKAGE, MODULE, NAME, DOCSTRING,
        check4unittest=False)  # all classes abstract, no unitests needed
    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('wxItemContainerImmutable')
    c.abstract = True

    c = module.find('wxItemContainer')
    assert isinstance(c, etgtools.ClassDef)
    c.abstract = True

    # Ignore the Append and Insert method overloads that we don't want to
    # support. This will keep the ones that take a wxString or an
    # wxArrayString, and wxClientData.
    def pickOverloads(m):
        assert isinstance(m, etgtools.MethodDef)
        if 'void *' in m.argsString or \
           'wxClientData **' in m.argsString or \
           'wxString *' in m.argsString:
            m.ignore()

    for m in c.findAll('Append'):
        pickOverloads(m)
    for m in c.findAll('Insert'):
        pickOverloads(m)
    for m in c.findAll('Set'):
        pickOverloads(m)

    # The [G|S]etClientData methods deal with untyped void* values, which we
    # don't support. The [G|S]etClientObject methods use wxClientData instaces
    # which we have a MappedType for, so make the ClientData methods just be
    # aliases for ClientObjects. From the Python programmer's perspective they
    # would be virtually the same anyway.
    c.find('SetClientObject.data').transfer = True
    c.find('GetClientData').ignore()
    c.find('SetClientData').ignore()
    c.find('GetClientObject').pyName = 'GetClientData'
    c.find('SetClientObject').pyName = 'SetClientData'
    c.addPyMethod('GetClientObject',
                  '(self, n)',
                  doc="Alias for :meth:`GetClientData`",
                  body="return self.GetClientData(n)")
    c.addPyMethod('SetClientObject',
                  '(self, n, data)',
                  doc="Alias for :meth:`SetClientData`",
                  body="self.SetClientData(n, data)")

    # Deal with transfering ownership of wxClientData objects
    c.find('DetachClientObject').transfer = True
    c.find('SetClientObject.data').transfer = True
    c.find('Append').findOverload('clientData').find(
        'clientData').transfer = True
    c.find('Insert').findOverload('clientData').find(
        'clientData').transfer = True

    # for compatibility, should they be deprecated?
    c.addPyMethod('AppendItems', '(self, items)', 'self.Append(items)')
    c.addPyMethod('GetItems', '(self)', 'return self.GetStrings()')
    c.addPyMethod('SetItems', '(self, items)', 'self.Set(items)')

    c = module.find('wxControlWithItems')
    c.abstract = True

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #50
0
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/treelist.h>')
    module.find('wxTreeListEventHandler').ignore()
    module.find('wxTreeListItems').ignore()

    #-----------------------------------------------------------------
    c = module.find('wxTreeListItem')
    assert isinstance(c, etgtools.ClassDef)

    c.addCppMethod('int', '__nonzero__', '()', """\
        return self->IsOk();
        """)

    c.addCppMethod('long', '__hash__', '()', """\
        return (long)self->GetID();
        """)

    c.addCppMethod('bool', '__eq__', '(wxTreeListItem* other)',
                   "return (self->GetID() == other->GetID());")
    c.addCppMethod('bool', '__ne__', '(wxTreeListItem* other)',
                   "return (self->GetID() != other->GetID());")

    #-----------------------------------------------------------------
    c = module.find('wxTreeListItemComparator')
    c.addPrivateCopyCtor()

    #-----------------------------------------------------------------
    c = module.find('wxTreeListCtrl')
    tools.fixWindowClass(c)

    module.addGlobalStr('wxTreeListCtrlNameStr', c)

    # Change NO_IMAGE default arg values to just -1, as the pi code has
    # problems when using the class name before the class is fully defined.
    for item in c.allItems():
        if isinstance(item, etgtools.ParamDef) and item.default == 'NO_IMAGE':
            item.default = '-1'

    # transfer ownership of some parameters
    c.find('AssignImageList.imageList').transfer = True
    c.find('SetItemData.data').transfer = True
    c.find('AppendItem.data').transfer = True
    c.find('InsertItem.data').transfer = True
    c.find('PrependItem.data').transfer = True

    # Replace GetSelections with an implementation that returns a Python list
    c.find('GetSelections').ignore()
    c.addCppMethod('PyObject*',
                   'GetSelections',
                   '()',
                   doc="""\
            Returns a list of all selected items. This method can be used in
            both single and multi-selection case.""",
                   body="""\
            unsigned count;
            wxTreeListItems items;
            count = self->GetSelections(items);

            wxPyThreadBlocker blocker;
            PyObject* list = PyList_New(count);
            for (size_t i=0; i<count; i++) {
                wxTreeListItem* item = new wxTreeListItem(items[i]);
                PyObject* obj = wxPyConstructObject((void*)item, wxT("wxTreeListItem"), true);
                PyList_SET_ITEM(list, i, obj); // PyList_SET_ITEM steals a reference
            }
            return list;
        """)

    # Set output parameter flags
    c.find('GetSortColumn.col').out = True
    c.find('GetSortColumn.ascendingOrder').out = True

    # Replace NO_IMAGE with wxTreeListCtrl::NO_IMAGE in parameter default values
    for item in c.allItems():
        if isinstance(item, etgtools.ParamDef) and item.default == 'NO_IMAGE':
            item.default = 'wxTreeListCtrl::NO_IMAGE'

    #-----------------------------------------------------------------
    c = module.find('wxTreeListEvent')
    tools.fixEventClass(c)

    c.addPyCode("""\
        EVT_TREELIST_SELECTION_CHANGED = wx.PyEventBinder( wxEVT_TREELIST_SELECTION_CHANGED )
        EVT_TREELIST_ITEM_EXPANDING =    wx.PyEventBinder( wxEVT_TREELIST_ITEM_EXPANDING )
        EVT_TREELIST_ITEM_EXPANDED =     wx.PyEventBinder( wxEVT_TREELIST_ITEM_EXPANDED )
        EVT_TREELIST_ITEM_CHECKED =      wx.PyEventBinder( wxEVT_TREELIST_ITEM_CHECKED )
        EVT_TREELIST_ITEM_ACTIVATED =    wx.PyEventBinder( wxEVT_TREELIST_ITEM_ACTIVATED )
        EVT_TREELIST_ITEM_CONTEXT_MENU = wx.PyEventBinder( wxEVT_TREELIST_ITEM_CONTEXT_MENU )
        EVT_TREELIST_COLUMN_SORTED =     wx.PyEventBinder( wxEVT_TREELIST_COLUMN_SORTED )

        # deprecated wxEVT aliases
        wxEVT_COMMAND_TREELIST_SELECTION_CHANGED  = wxEVT_TREELIST_SELECTION_CHANGED
        wxEVT_COMMAND_TREELIST_ITEM_EXPANDING     = wxEVT_TREELIST_ITEM_EXPANDING
        wxEVT_COMMAND_TREELIST_ITEM_EXPANDED      = wxEVT_TREELIST_ITEM_EXPANDED
        wxEVT_COMMAND_TREELIST_ITEM_CHECKED       = wxEVT_TREELIST_ITEM_CHECKED
        wxEVT_COMMAND_TREELIST_ITEM_ACTIVATED     = wxEVT_TREELIST_ITEM_ACTIVATED
        wxEVT_COMMAND_TREELIST_ITEM_CONTEXT_MENU  = wxEVT_TREELIST_ITEM_CONTEXT_MENU
        wxEVT_COMMAND_TREELIST_COLUMN_SORTED      = wxEVT_TREELIST_COLUMN_SORTED
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #51
0
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/bmpcbox.h>")

    c = module.find('wxBitmapComboBox')
    assert isinstance(c, etgtools.ClassDef)
    module.addGlobalStr('wxBitmapComboBoxNameStr', c)
    tools.fixWindowClass(c)

    # The MSW and GTK version of this class derive from wxComboBox, but the
    # OSX version derives from wxOwnerDrawnCombo. To make all platforms happy
    # with the generated wrapper code switch the declared base with the bases
    # that both of those classes have in common.
    c.bases = ['wxControl', 'wxTextEntry', 'wxItemContainer']

    # Copy any method definitions from wx.ComboBox that are not declared here
    import combobox
    mod = combobox.parseAndTweakModule()
    klass = mod.find('wxComboBox')
    items = [
        item for item in klass.items
        if isinstance(item, etgtools.MethodDef) and not item.isCtor
        and not item.isDtor and not item.ignored and not c.findItem(item.name)
    ]
    c.items.extend(items)
    #print([i.name for i in items])
    c.find('GetCurrentSelection').ignore()

    # Ignore the old C array verison of the ctor and Create methods, and
    # fixup the remaining ctor and Create with the typical default values for
    # the args
    c.find('wxBitmapComboBox').findOverload('wxString choices').ignore()
    m = c.find('wxBitmapComboBox').findOverload('wxArrayString')
    m.find('value').default = 'wxEmptyString'
    m.find('choices').default = 'wxArrayString()'
    m.find('style').default = '0'

    c.find('Create').findOverload('wxString choices').ignore()
    m = c.find('Create').findOverload('wxArrayString')
    m.find('value').default = 'wxEmptyString'
    m.find('choices').default = 'wxArrayString()'

    # Ignore the Append and Insert taking a void* for clientData
    c.find('Append').findOverload('void *').ignore()
    c.find('Insert').findOverload('void *').ignore()

    # And set the ownership transfer for the other one
    c.find('Append').findOverload('wxClientData *').find(
        'clientData').transfer = True
    c.find('Insert').findOverload('wxClientData *').find(
        'clientData').transfer = True

    # We need to disambiguate GetStringSelection since it is implemented in
    # multiple base classes
    c.find('GetStringSelection').ignore()
    c.addItem(
        etgtools.WigCode("""\
        virtual wxString GetStringSelection() const;
        %MethodCode
            sipRes = new wxString(sipCpp->wxItemContainerImmutable::GetStringSelection());
        %End
        %VirtualCallCode
            sipRes = wxItemContainerImmutable::GetStringSelection();
        %End
        """))

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #52
0
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/webview.h>')

    module.addGlobalStr('wxWebViewBackendDefault')
    module.addGlobalStr('wxWebViewBackendIE')
    module.addGlobalStr('wxWebViewBackendWebKit')

    c = module.find('wxWebView')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixWindowClass(c)
    c.abstract = True

    module.addGlobalStr('wxWebViewNameStr', c)
    module.addGlobalStr('wxWebViewDefaultURLStr', c)

    for m in c.find('New').all():
        m.factory = True
    c.find('New.id').default = 'wxID_ANY'
    c.find('New.parent').transferThis = True


    c.find('RegisterHandler.handler').type = 'wxWebViewHandler*'
    c.find('RegisterHandler.handler').transfer = True
    c.find('RegisterHandler').setCppCode_sip(
        "sipCpp->RegisterHandler(wxSharedPtr<wxWebViewHandler>(handler));")


    c.find('RegisterFactory.factory').type = 'wxWebViewFactory*'
    c.find('RegisterFactory.factory').transfer = True
    c.find('RegisterFactory').setCppCode_sip(
        "wxWebView::RegisterFactory(*backend, wxSharedPtr<wxWebViewFactory>(factory));")


    # Custom code to deal with the
    # wxVector<wxSharedPtr<wxWebViewHistoryItem>> return type of these two
    # methods. We'll just convert them to a Python list of history items.
    code = """\
        wxPyThreadBlocker blocker;
        PyObject* result = PyList_New(0);
        wxVector<wxSharedPtr<wxWebViewHistoryItem> >  vector = self->{method}();
        for (size_t idx=0; idx < vector.size(); idx++) {{
            PyObject* obj;
            wxWebViewHistoryItem* item = new wxWebViewHistoryItem(*vector[idx].get());
            obj = wxPyConstructObject((void*)item, "wxWebViewHistoryItem", true);
            PyList_Append(result, obj);
            Py_DECREF(obj);
        }}
        return result;
        """
    c.find('GetBackwardHistory').type = 'PyObject*'
    c.find('GetBackwardHistory').setCppCode(code.format(method='GetBackwardHistory'))
    c.find('GetForwardHistory').type = 'PyObject*'
    c.find('GetForwardHistory').setCppCode(code.format(method='GetForwardHistory'))


    # Since LoadHistoryItem expects to get an actual item in the history
    # list, and since we make copies of the items in the cppCode above, then
    # this won't be possible to do from the Python wrappers. However, it's
    # just as easy to use LoadURL to reload a history item so it's not a
    # great loss.
    c.find('LoadHistoryItem').ignore()
    ##c.find('LoadHistoryItem.item').type = 'wxWebViewHistoryItem*'
    ##c.find('LoadHistoryItem.item').transfer = True
    ##c.find('LoadHistoryItem').setCppCode_sip(
    ##    "sipCpp->LoadHistoryItem(wxSharedPtr<wxWebViewHistoryItem>(item));")





    c = module.find('wxWebViewEvent')
    tools.fixEventClass(c)

    module.addPyCode("""\
        EVT_WEBVIEW_NAVIGATING = wx.PyEventBinder( wxEVT_WEBVIEW_NAVIGATING, 1 )
        EVT_WEBVIEW_NAVIGATED = wx.PyEventBinder( wxEVT_WEBVIEW_NAVIGATED, 1 )
        EVT_WEBVIEW_LOADED = wx.PyEventBinder( wxEVT_WEBVIEW_LOADED, 1 )
        EVT_WEBVIEW_ERROR = wx.PyEventBinder( wxEVT_WEBVIEW_ERROR, 1 )
        EVT_WEBVIEW_NEWWINDOW = wx.PyEventBinder( wxEVT_WEBVIEW_NEWWINDOW, 1 )
        EVT_WEBVIEW_TITLE_CHANGED = wx.PyEventBinder( wxEVT_WEBVIEW_TITLE_CHANGED, 1 )

        # deprecated wxEVT aliases
        wxEVT_COMMAND_WEBVIEW_NAVIGATING     = wxEVT_WEBVIEW_NAVIGATING
        wxEVT_COMMAND_WEBVIEW_NAVIGATED      = wxEVT_WEBVIEW_NAVIGATED
        wxEVT_COMMAND_WEBVIEW_LOADED         = wxEVT_WEBVIEW_LOADED
        wxEVT_COMMAND_WEBVIEW_ERROR          = wxEVT_WEBVIEW_ERROR
        wxEVT_COMMAND_WEBVIEW_NEWWINDOW      = wxEVT_WEBVIEW_NEWWINDOW
        wxEVT_COMMAND_WEBVIEW_TITLE_CHANGED  = wxEVT_WEBVIEW_TITLE_CHANGED
        """)


    c = module.find('wxWebViewHistoryItem')
    tools.addAutoProperties(c)


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #53
0
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/dnd.h>')

    c = module.find('wxDropSource')
    assert isinstance(c, etgtools.ClassDef)
    c.addPrivateCopyCtor()

    for m in c.find('wxDropSource').all():
        if 'wxIcon' in m.argsString:
            # Ignore the ctors taking wxIcon parameters. They are GTK only
            # and we don't have an easy way yet to support platform specific
            # APIs in the ctors.
            m.ignore()
        else:
            # Ignore the cursor parameters. We'll need to use SetCursor or
            # SetIcon instead.
            m.find('iconCopy').ignore()
            m.find('iconMove').ignore()
            m.find('iconNone').ignore()

    # void SetCursor(wxDragResult res, const wxCursor& cursor);
    c.find('SetCursor').setCppCode("""\
        #ifdef __WXGTK__
            wxPyRaiseNotImplementedMsg("Cursors not supported, use SetIcon on wxGTK instead.");
        #else
            self->SetCursor(res, *cursor);
        #endif
        """)

    # void SetIcon(wxDragResult res, const wxIcon& icon)
    c.find('SetIcon').setCppCode("""\
        #ifdef __WXGTK__
            self->SetIcon(res, *icon);
        #else
            wxPyRaiseNotImplementedMsg("Icons not supported, use SetCursor on non-wxGTK ports.");
        #endif
        """)

    c = module.find('wxDropTarget')
    c.addPrivateCopyCtor()
    c.find('wxDropTarget.data').transfer = True
    c.find('SetDataObject.data').transfer = True

    module.addPyCode(
        "PyDropTarget = wx.deprecated(DropTarget, 'Use DropTarget instead.')")

    c = module.find('wxTextDropTarget')
    c.addItem(
        etgtools.WigCode(
            "virtual wxDragResult OnData(wxCoord x, wxCoord y, wxDragResult def);"
        ))

    c = module.find('wxFileDropTarget')
    c.addItem(
        etgtools.WigCode(
            "virtual wxDragResult OnData(wxCoord x, wxCoord y, wxDragResult def);"
        ))

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #54
0
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('wxPickerBase')
    assert isinstance(c, etgtools.ClassDef)
    c.find('CreateBase.id').default = 'wxID_ANY'
    c.find('GetTextCtrlStyle').ignore(False)
    c.find('GetPickerStyle').ignore(False)
    c.find('PostCreation').ignore(False)

    #-----------------------------------------------------------------

    module.addHeaderCode('#include <wx/clrpicker.h>')

    c = module.find('wxColourPickerCtrl')
    tools.fixWindowClass(c)
    module.addGlobalStr('wxColourPickerWidgetNameStr', c)
    module.addGlobalStr('wxColourPickerCtrlNameStr', c)

    c.addItem(
        etgtools.WigCode("""\
        virtual void UpdatePickerFromTextCtrl();
        virtual void UpdateTextCtrlFromPicker();
        """))

    c = module.find('wxColourPickerEvent')
    tools.fixEventClass(c)

    module.addPyCode("""\
        EVT_COLOURPICKER_CHANGED = wx.PyEventBinder( wxEVT_COLOURPICKER_CHANGED, 1 )

        # deprecated wxEVT alias
        wxEVT_COMMAND_COLOURPICKER_CHANGED  = wxEVT_COLOURPICKER_CHANGED
        """)

    #-----------------------------------------------------------------

    module.addHeaderCode('#include <wx/filepicker.h>')

    c = module.find('wxFilePickerCtrl')
    tools.fixWindowClass(c)
    module.addGlobalStr('wxFilePickerWidgetLabel', c)
    module.addGlobalStr('wxFilePickerWidgetNameStr', c)
    module.addGlobalStr('wxFilePickerCtrlNameStr', c)
    module.addGlobalStr('wxFileSelectorPromptStr', c)
    module.addGlobalStr('wxFileSelectorDefaultWildcardStr', c)

    c.addItem(
        etgtools.WigCode("""\
        virtual void UpdatePickerFromTextCtrl();
        virtual void UpdateTextCtrlFromPicker();
        """))

    # we'll use the [G|S]etPath methods instead so we don't have to mess with wxFileName
    c.find('GetFileName').ignore()
    c.find('SetFileName').ignore()

    c = module.find('wxDirPickerCtrl')
    tools.fixWindowClass(c)
    module.addGlobalStr('wxDirPickerWidgetLabel', c)
    module.addGlobalStr('wxDirPickerWidgetNameStr', c)
    module.addGlobalStr('wxDirPickerCtrlNameStr', c)
    module.addGlobalStr('wxDirSelectorPromptStr', c)

    c.addItem(
        etgtools.WigCode("""\
        virtual void UpdatePickerFromTextCtrl();
        virtual void UpdateTextCtrlFromPicker();
        """))

    # we'll use the [G|S]etPath methods instead so we don't have to mess with wxFileName
    c.find('GetDirName').ignore()
    c.find('SetDirName').ignore()

    c = module.find('wxFileDirPickerEvent')
    tools.fixEventClass(c)

    module.addPyCode("""\
        EVT_FILEPICKER_CHANGED = wx.PyEventBinder( wxEVT_FILEPICKER_CHANGED, 1 )
        EVT_DIRPICKER_CHANGED = wx.PyEventBinder( wxEVT_DIRPICKER_CHANGED, 1 )

        # deprecated wxEVT aliases
        wxEVT_COMMAND_FILEPICKER_CHANGED   = wxEVT_FILEPICKER_CHANGED
        wxEVT_COMMAND_DIRPICKER_CHANGED    = wxEVT_DIRPICKER_CHANGED
        """)

    #-----------------------------------------------------------------

    module.addHeaderCode('#include <wx/fontpicker.h>')

    c = module.find('wxFontPickerCtrl')
    tools.fixWindowClass(c)
    module.addGlobalStr('wxFontPickerWidgetNameStr', c)
    module.addGlobalStr('wxFontPickerCtrlNameStr', c)

    c.addItem(
        etgtools.WigCode("""\
        virtual void UpdatePickerFromTextCtrl();
        virtual void UpdateTextCtrlFromPicker();
        """))

    c = module.find('wxFontPickerEvent')
    tools.fixEventClass(c)

    module.addPyCode("""\
        EVT_FONTPICKER_CHANGED = wx.PyEventBinder( wxEVT_FONTPICKER_CHANGED, 1 )

        # deprecated wxEVT alias
        wxEVT_COMMAND_FONTPICKER_CHANGED  = wxEVT_FONTPICKER_CHANGED
        """)

    #-----------------------------------------------------------------
    # The C++ wxColourPickerCtrl uses a wx.Button for the implementation,
    # but that looks and works very badly on Mac because the native
    # button can't change color.  So for the Mac we'll implement our own
    # picker using a wx.BitmapButton instead.
    module.addPyCode("""\
    if 'wxMac' in wx.PlatformInfo:
        class ColourPickerCtrl(PickerBase):
            '''
            This control allows the user to select a colour. The
            implementation varies by platform but is usually a button which
            brings up a `wx.ColourDialog` when clicked.


            Window Styles
            -------------

                ======================  ============================================
                wx.CLRP_DEFAULT         Default style.
                wx.CLRP_USE_TEXTCTRL    Creates a text control to the left of the
                                        picker button which is completely managed
                                        by the `wx.ColourPickerCtrl` and which can
                                        be used by the user to specify a colour.
                                        The text control is automatically synchronized
                                        with the button's value. Use functions defined in
                                        `wx.PickerBase` to modify the text control.
                wx.CLRP_SHOW_LABEL      Shows the colour in HTML form (AABBCC) as the
                                        colour button label (instead of no label at all).
                ======================  ============================================

            Events
            ------

                ========================  ==========================================
                EVT_COLOURPICKER_CHANGED  The user changed the colour selected in the
                                          control either using the button or using the
                                          text control (see wx.CLRP_USE_TEXTCTRL; note
                                          that in this case the event is fired only if
                                          the user's input is valid, i.e. recognizable).
                ========================  ==========================================
            '''

            # ColourData object to be shared by all colour pickers, so they can
            # share the custom colours
            _colourData = None

            #--------------------------------------------------
            class ColourPickerButton(BitmapButton):
                def __init__(self, parent, id=-1, colour=wx.BLACK,
                             pos=wx.DefaultPosition, size=wx.DefaultSize,
                             style = CLRP_DEFAULT_STYLE,
                             validator = wx.DefaultValidator,
                             name = "colourpickerwidget"):

                    wx.BitmapButton.__init__(self, parent, id, wx.Bitmap(1,1),
                                             pos, size, style, validator, name)
                    self.SetColour(colour)
                    self.InvalidateBestSize()
                    self.SetInitialSize(size)
                    self.Bind(wx.EVT_BUTTON, self.OnButtonClick)

                    if ColourPickerCtrl._colourData is None:
                        ColourPickerCtrl._colourData = wx.ColourData()
                        ColourPickerCtrl._colourData.SetChooseFull(True)
                        grey = 0
                        for i in range(16):
                            c = wx.Colour(grey, grey, grey)
                            ColourPickerCtrl._colourData.SetCustomColour(i, c)
                            grey += 16

                def SetColour(self, colour):
                    # force a copy, in case the _colorData is shared
                    self.colour = wx.Colour(colour)
                    bmp = self._makeBitmap()
                    self.SetBitmapLabel(bmp)

                def GetColour(self):
                    return self.colour

                def OnButtonClick(self, evt):
                    ColourPickerCtrl._colourData.SetColour(self.colour)
                    dlg = wx.ColourDialog(self, ColourPickerCtrl._colourData)
                    if dlg.ShowModal() == wx.ID_OK:
                        ColourPickerCtrl._colourData = dlg.GetColourData()
                        self.SetColour(ColourPickerCtrl._colourData.GetColour())
                        evt = wx.ColourPickerEvent(self, self.GetId(), self.GetColour())
                        self.GetEventHandler().ProcessEvent(evt)

                def _makeBitmap(self):
                    width = height = 24
                    bg = self.GetColour()
                    if self.HasFlag(CLRP_SHOW_LABEL):
                        w, h = self.GetTextExtent(bg.GetAsString(wx.C2S_HTML_SYNTAX))
                        width += w
                    bmp = wx.Bitmap(width, height)
                    dc = wx.MemoryDC(bmp)
                    dc.SetBackground(wx.Brush(self.colour))
                    dc.Clear()
                    if self.HasFlag(CLRP_SHOW_LABEL):
                        from wx.lib.colourutils import BestLabelColour
                        fg = BestLabelColour(bg)
                        dc.SetTextForeground(fg)
                        dc.DrawText(bg.GetAsString(wx.C2S_HTML_SYNTAX),
                                    (width - w)/2, (height - h)/2)
                    return bmp

            #--------------------------------------------------

            def __init__(self, parent, id=-1, colour=wx.BLACK,
                         pos=wx.DefaultPosition, size=wx.DefaultSize,
                         style = CLRP_DEFAULT_STYLE,
                         validator = wx.DefaultValidator,
                         name = "colourpicker"):
                if type(colour) != wx.Colour:
                    colour = wx.Colour(colour)
                wx.PickerBase.__init__(self)
                self.CreateBase(parent, id, colour.GetAsString(),
                                pos, size, style, validator, name)
                widget = ColourPickerCtrl.ColourPickerButton(
                    self, -1, colour, style=self.GetPickerStyle(style))
                self.SetPickerCtrl(widget)
                widget.Bind(wx.EVT_COLOURPICKER_CHANGED, self.OnColourChange)
                self.PostCreation()


            def GetColour(self):
                '''Set the displayed colour.'''
                return self.GetPickerCtrl().GetColour()

            def SetColour(self, colour):
                '''Returns the currently selected colour.'''
                self.GetPickerCtrl().SetColour(colour)
                self.UpdateTextCtrlFromPicker()
            Colour = property(GetColour, SetColour)


            def UpdatePickerFromTextCtrl(self):
                col = wx.Colour(self.GetTextCtrl().GetValue())
                if not col.IsOk():
                    return
                if self.GetColour() != col:
                    self.GetPickerCtrl().SetColour(col)
                    evt = wx.ColourPickerEvent(self, self.GetId(), self.GetColour())
                    self.GetEventHandler().ProcessEvent(evt)

            def UpdateTextCtrlFromPicker(self):
                if not self.GetTextCtrl():
                    return
                self.GetTextCtrl().SetValue(self.GetColour().GetAsString())

            def GetPickerStyle(self, style):
                return style & CLRP_SHOW_LABEL

            def OnColourChange(self, evt):
                self.UpdateTextCtrlFromPicker()
                evt = wx.ColourPickerEvent(self, self.GetId(), self.GetColour())
                self.GetEventHandler().ProcessEvent(evt)
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #55
0
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('wxTreeItemId')
    assert isinstance(c, etgtools.ClassDef)
    c.addCppMethod('int', '__nonzero__', '()', """\
        return self->IsOk();
        """)

    td = etgtools.TypedefDef(name='wxTreeItemIdValue', type='void*')
    module.insertItemBefore(c, td)

    #-------------------------------------------------------
    module.addPyCode("""\
        def TreeItemData(data):
            return data
        TreeItemData = deprecated(TreeItemData, "The TreeItemData class no longer exists, just pass your object directly to the tree instead.")
        """)

    #-------------------------------------------------------
    c = module.find('wxTreeCtrl')
    tools.fixWindowClass(c)
    module.addGlobalStr('wxTreeCtrlNameStr', before=c)

    # Set all wxTreeItemData parameters to transfer ownership.  Is this still needed with MappedTypes?
    for item in c.allItems():
        if hasattr(item, 'type') and item.type == 'wxTreeItemData *' and \
           isinstance(item, etgtools.ParamDef):
            item.transfer = True

    c.addPyCode("""\
        TreeCtrl.GetItemPyData = wx.deprecated(TreeCtrl.GetItemData, 'Use GetItemData instead.')
        TreeCtrl.SetItemPyData = wx.deprecated(TreeCtrl.SetItemData, 'Use SetItemData instead.')
        TreeCtrl.GetPyData = wx.deprecated(TreeCtrl.GetItemData, 'Use GetItemData instead.')
        TreeCtrl.SetPyData = wx.deprecated(TreeCtrl.SetItemData, 'Use SetItemData instead.')
        """)

    # We can't use wxClassInfo
    c.find('EditLabel.textCtrlClass').ignore()

    # Replace GetSelections with a method that returns a Python list
    # size_t GetSelections(wxArrayTreeItemIds& selection) const;
    c.find('GetSelections').ignore()
    c.addCppMethod(
        'PyObject*',
        'GetSelections',
        '()',
        doc=
        'Returns a list of currently selected items in the tree.  This function '
        'can be called only if the control has the wx.TR_MULTIPLE style.',
        body="""\
        wxPyThreadBlocker blocker;
        PyObject*           rval = PyList_New(0);
        wxArrayTreeItemIds  array;
        size_t              num, x;
        num = self->GetSelections(array);
        for (x=0; x < num; x++) {
            wxTreeItemId *tii = new wxTreeItemId(array.Item(x));
            PyObject* item = wxPyConstructObject((void*)tii, wxT("wxTreeItemId"), true);
            PyList_Append(rval, item);
            Py_DECREF(item);
        }
        return rval;
        """)

    # Change GetBoundingRect to return the rectangle instead of modifying the parameter.
    #bool GetBoundingRect(const wxTreeItemId& item, wxRect& rect, bool textOnly = false) const;
    c.find('GetBoundingRect').ignore()
    c.addCppMethod('PyObject*',
                   'GetBoundingRect',
                   '(const wxTreeItemId& item, bool textOnly=false)',
                   doc="""\
        Returns the rectangle bounding the item. If textOnly is true,
        only the rectangle around the item's label will be returned, otherwise
        the item's image is also taken into account. The return value may be None
        if the rectangle was not successfully retrieved, such as if the item is
        currently not visible.
        """,
                   isFactory=True,
                   body="""\
        wxRect rect;
        if (self->GetBoundingRect(*item, rect, textOnly)) {
            wxPyThreadBlocker blocker;
            wxRect* r = new wxRect(rect);
            PyObject* val = wxPyConstructObject((void*)r, wxT("wxRect"), true);
            return val;
        }
        else
            RETURN_NONE();
        """)

    # switch the virtualness back on for those methods that need to have it.
    c.find('OnCompareItems').isVirtual = True

    # transfer imagelist ownership
    c.find('AssignImageList.imageList').transfer = True
    c.find('AssignStateImageList.imageList').transfer = True
    c.find('AssignButtonsImageList.imageList').transfer = True

    # Make the cookie values be returned, instead of setting it through the parameter
    c.find('GetFirstChild.cookie').out = True
    c.find('GetNextChild.cookie').inOut = True

    # TODO: These don't exist on MSW, Are they important enough that we
    # should provide them for the other platforms anyway?
    c.find('AssignButtonsImageList').ignore()
    c.find('GetButtonsImageList').ignore()
    c.find('SetButtonsImageList').ignore()

    #-------------------------------------------------------
    c = module.find('wxTreeEvent')
    tools.fixEventClass(c)

    c.addPyCode("""\
        EVT_TREE_BEGIN_DRAG        = PyEventBinder(wxEVT_TREE_BEGIN_DRAG       , 1)
        EVT_TREE_BEGIN_RDRAG       = PyEventBinder(wxEVT_TREE_BEGIN_RDRAG      , 1)
        EVT_TREE_BEGIN_LABEL_EDIT  = PyEventBinder(wxEVT_TREE_BEGIN_LABEL_EDIT , 1)
        EVT_TREE_END_LABEL_EDIT    = PyEventBinder(wxEVT_TREE_END_LABEL_EDIT   , 1)
        EVT_TREE_DELETE_ITEM       = PyEventBinder(wxEVT_TREE_DELETE_ITEM      , 1)
        EVT_TREE_GET_INFO          = PyEventBinder(wxEVT_TREE_GET_INFO         , 1)
        EVT_TREE_SET_INFO          = PyEventBinder(wxEVT_TREE_SET_INFO         , 1)
        EVT_TREE_ITEM_EXPANDED     = PyEventBinder(wxEVT_TREE_ITEM_EXPANDED    , 1)
        EVT_TREE_ITEM_EXPANDING    = PyEventBinder(wxEVT_TREE_ITEM_EXPANDING   , 1)
        EVT_TREE_ITEM_COLLAPSED    = PyEventBinder(wxEVT_TREE_ITEM_COLLAPSED   , 1)
        EVT_TREE_ITEM_COLLAPSING   = PyEventBinder(wxEVT_TREE_ITEM_COLLAPSING  , 1)
        EVT_TREE_SEL_CHANGED       = PyEventBinder(wxEVT_TREE_SEL_CHANGED      , 1)
        EVT_TREE_SEL_CHANGING      = PyEventBinder(wxEVT_TREE_SEL_CHANGING     , 1)
        EVT_TREE_KEY_DOWN          = PyEventBinder(wxEVT_TREE_KEY_DOWN         , 1)
        EVT_TREE_ITEM_ACTIVATED    = PyEventBinder(wxEVT_TREE_ITEM_ACTIVATED   , 1)
        EVT_TREE_ITEM_RIGHT_CLICK  = PyEventBinder(wxEVT_TREE_ITEM_RIGHT_CLICK , 1)
        EVT_TREE_ITEM_MIDDLE_CLICK = PyEventBinder(wxEVT_TREE_ITEM_MIDDLE_CLICK, 1)
        EVT_TREE_END_DRAG          = PyEventBinder(wxEVT_TREE_END_DRAG         , 1)
        EVT_TREE_STATE_IMAGE_CLICK = PyEventBinder(wxEVT_TREE_STATE_IMAGE_CLICK, 1)
        EVT_TREE_ITEM_GETTOOLTIP   = PyEventBinder(wxEVT_TREE_ITEM_GETTOOLTIP,   1)
        EVT_TREE_ITEM_MENU         = PyEventBinder(wxEVT_TREE_ITEM_MENU,         1)

        # deprecated wxEVT aliases
        wxEVT_COMMAND_TREE_BEGIN_DRAG         = wxEVT_TREE_BEGIN_DRAG
        wxEVT_COMMAND_TREE_BEGIN_RDRAG        = wxEVT_TREE_BEGIN_RDRAG
        wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT   = wxEVT_TREE_BEGIN_LABEL_EDIT
        wxEVT_COMMAND_TREE_END_LABEL_EDIT     = wxEVT_TREE_END_LABEL_EDIT
        wxEVT_COMMAND_TREE_DELETE_ITEM        = wxEVT_TREE_DELETE_ITEM
        wxEVT_COMMAND_TREE_GET_INFO           = wxEVT_TREE_GET_INFO
        wxEVT_COMMAND_TREE_SET_INFO           = wxEVT_TREE_SET_INFO
        wxEVT_COMMAND_TREE_ITEM_EXPANDED      = wxEVT_TREE_ITEM_EXPANDED
        wxEVT_COMMAND_TREE_ITEM_EXPANDING     = wxEVT_TREE_ITEM_EXPANDING
        wxEVT_COMMAND_TREE_ITEM_COLLAPSED     = wxEVT_TREE_ITEM_COLLAPSED
        wxEVT_COMMAND_TREE_ITEM_COLLAPSING    = wxEVT_TREE_ITEM_COLLAPSING
        wxEVT_COMMAND_TREE_SEL_CHANGED        = wxEVT_TREE_SEL_CHANGED
        wxEVT_COMMAND_TREE_SEL_CHANGING       = wxEVT_TREE_SEL_CHANGING
        wxEVT_COMMAND_TREE_KEY_DOWN           = wxEVT_TREE_KEY_DOWN
        wxEVT_COMMAND_TREE_ITEM_ACTIVATED     = wxEVT_TREE_ITEM_ACTIVATED
        wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK   = wxEVT_TREE_ITEM_RIGHT_CLICK
        wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK  = wxEVT_TREE_ITEM_MIDDLE_CLICK
        wxEVT_COMMAND_TREE_END_DRAG           = wxEVT_TREE_END_DRAG
        wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK  = wxEVT_TREE_STATE_IMAGE_CLICK
        wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP    = wxEVT_TREE_ITEM_GETTOOLTIP
        wxEVT_COMMAND_TREE_ITEM_MENU          = wxEVT_TREE_ITEM_MENU
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #56
0
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('wxCursor')
    assert isinstance(c, etgtools.ClassDef)
    
    c.find('wxCursor').findOverload('bits').ignore()
    c.find('wxCursor').findOverload('cursorName').find('type').default='wxBITMAP_TYPE_ANY'    
    # TODO: This ctor ^^ in Classic has a custom implementation for wxGTK that
    # sets the hotspot. Is that still needed?

    c.addCppMethod('int', '__nonzero__', '()', """\
        return self->IsOk();
    """)

    c.addCppMethod('long', 'GetHandle', '()', """\
    #ifdef __WXMSW__
        return (long)self->GetHandle();
    #else
        return 0;
    #endif""",
    briefDoc="Get the handle for the Cursor.  Windows only.")
    
    c.addCppMethod('void', 'SetHandle', '(long handle)', """\
    #ifdef __WXMSW__
        self->SetHandle((WXHANDLE)handle);
    #endif""",
    briefDoc="Set the handle to use for this Cursor.  Windows only.")
    
    # TODO:  Classic has MSW-only getters and setters for width, height, depth, and size.
    
    # The stock Cursor items are documented as simple pointers, but in reality
    # they are macros that evaluate to a function call that returns a cursor
    # pointer, and that is only valid *after* the wx.App object has been
    # created. That messes up the code that SIP generates for them, so we need
    # to come up with another solution. So instead we will just create
    # uninitialized cursor in a block of Python code, that will then be
    # intialized later when the wx.App is created.
    c.addCppMethod('void', '_copyFrom', '(const wxCursor* other)', 
                   "*self = *other;",
                   briefDoc="For internal use only.")  # ??
    pycode = '# These stock cursors will be initialized when the wx.App object is created.\n'
    for item in module:
        if '_CURSOR' in item.name:
            item.ignore()
            pycode += '%s = Cursor()\n' % tools.removeWxPrefix(item.name)
    module.addPyCode(pycode)
    
    # former renamed constructors
    module.addPyCode('StockCursor = wx.deprecated(Cursor, "Use Cursor instead.")')
    module.addPyCode('CursorFromImage = wx.deprecated(Cursor, "Use Cursor instead.")')
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #57
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING,
                                check4unittest=False)
    etgtools.parseDoxyXML(module, ITEMS)
    module.check4unittest = False

    #-----------------------------------------------------------------
    # Tweak the parsed meta objects in the module object as needed for
    # customizing the generated code and docstrings.

    c = module.find('wxTopLevelWindow')
    assert isinstance(c, etgtools.ClassDef)
    module.addGlobalStr('wxFrameNameStr', c)

    c.find('wxTopLevelWindow.title').default = 'wxEmptyString'
    c.find('Create.title').default = 'wxEmptyString'

    c.find('IsUsingNativeDecorations').ignore()
    c.find('UseNativeDecorations').ignore()
    c.find('UseNativeDecorationsByDefault').ignore()
    c.find('MSWGetSystemMenu').ignore() # what is this?

    c.addCppMethod('void', 'MacSetMetalAppearance', '(bool on)', """\
        int style = self->GetExtraStyle();
        if ( on )
            style |= wxFRAME_EX_METAL;
        else
            style &= ~wxFRAME_EX_METAL;
        self->SetExtraStyle(style);
        """)

    c.addCppMethod('bool', 'MacGetMetalAppearance', '()', """\
        return self->GetExtraStyle() & wxFRAME_EX_METAL;
        """)

    c.addCppMethod('bool', 'MacGetUnifiedAppearance', '()', 'return true;')

    c.addCppMethod('void*', 'MacGetTopLevelWindowRef', '()', """\
        #ifdef __WXMAC__
            return (void*)(self->MacGetTopLevelWindowRef());
        #else
            return 0;
        #endif
        """)

    c.find('GeometrySerializer').abstract = True

    c.addProperty('DefaultItem GetDefaultItem SetDefaultItem')
    c.addProperty('Icon GetIcon SetIcon')
    c.addProperty('Title GetTitle SetTitle')
    c.addProperty('TmpDefaultItem GetTmpDefaultItem SetTmpDefaultItem')
    c.addProperty('OSXModified OSXIsModified OSXSetModified')
    c.addProperty('MacMetalAppearance MacGetMetalAppearance MacSetMetalAppearance')

    tools.fixTopLevelWindowClass(c)
    c.find('ShouldPreventAppExit').isVirtual = True

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #58
0
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('wxHeaderCtrl')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixWindowClass(c)

    module.addGlobalStr('wxHeaderCtrlNameStr', c)
    module.addHeaderCode('#include <wx/headerctrl.h>')

    # Uningnore the protected virtuals that are intended to be overridden in
    # derived classes.
    for name in [
            'GetColumn', 'UpdateColumnVisibility', 'UpdateColumnsOrder',
            'UpdateColumnWidthToFit', 'OnColumnCountChanging'
    ]:
        c.find(name).ignore(False)
        c.find(name).isVirtual = True
    c.find('GetColumn').isPureVirtual = True
    c.find('GetColumn')._virtualCatcherCode = """\
        PyObject *resObj = sipCallMethod(0,sipMethod,"u",idx);
        sipIsErr = (!resObj || sipParseResult(0,sipMethod,resObj,"H1",sipType_wxHeaderColumn,&sipRes) < 0);
        if (sipIsErr)
            PyErr_Print();
        Py_XDECREF(resObj);
        if (sipIsErr)
            return *(new wxHeaderColumnSimple(""));
        """

    #-------------------------------------------------------
    c = module.find('wxHeaderCtrlSimple')
    tools.fixWindowClass(c)

    # Uningnore the protected virtuals that are indended to be overridden in
    # derived classes.
    c.find('GetBestFittingWidth').ignore(False)
    c.find('GetBestFittingWidth').isVirtual = True

    # indicate the the base class virtuals have implementations here
    c.addItem(
        etgtools.WigCode("""\
        virtual const wxHeaderColumn& GetColumn(unsigned int idx) const;
        virtual void UpdateColumnVisibility(unsigned int idx, bool show);
        virtual void UpdateColumnsOrder(const wxArrayInt& order);
        virtual bool UpdateColumnWidthToFit(unsigned int idx, int widthTitle);
        virtual void OnColumnCountChanging(unsigned int count);
        """,
                         protection='protected'))

    #-------------------------------------------------------
    c = module.find('wxHeaderCtrlEvent')
    tools.fixEventClass(c)

    module.addPyCode("""\
        EVT_HEADER_CLICK =              wx.PyEventBinder( wxEVT_HEADER_CLICK )
        EVT_HEADER_RIGHT_CLICK =        wx.PyEventBinder( wxEVT_HEADER_RIGHT_CLICK )
        EVT_HEADER_MIDDLE_CLICK =       wx.PyEventBinder( wxEVT_HEADER_MIDDLE_CLICK )
        EVT_HEADER_DCLICK =             wx.PyEventBinder( wxEVT_HEADER_DCLICK )
        EVT_HEADER_RIGHT_DCLICK =       wx.PyEventBinder( wxEVT_HEADER_RIGHT_DCLICK )
        EVT_HEADER_MIDDLE_DCLICK =      wx.PyEventBinder( wxEVT_HEADER_MIDDLE_DCLICK )
        EVT_HEADER_SEPARATOR_DCLICK =   wx.PyEventBinder( wxEVT_HEADER_SEPARATOR_DCLICK )
        EVT_HEADER_BEGIN_RESIZE =       wx.PyEventBinder( wxEVT_HEADER_BEGIN_RESIZE )
        EVT_HEADER_RESIZING =           wx.PyEventBinder( wxEVT_HEADER_RESIZING )
        EVT_HEADER_END_RESIZE =         wx.PyEventBinder( wxEVT_HEADER_END_RESIZE )
        EVT_HEADER_BEGIN_REORDER =      wx.PyEventBinder( wxEVT_HEADER_BEGIN_REORDER )
        EVT_HEADER_END_REORDER =        wx.PyEventBinder( wxEVT_HEADER_END_REORDER )
        EVT_HEADER_DRAGGING_CANCELLED = wx.PyEventBinder( wxEVT_HEADER_DRAGGING_CANCELLED )

        # deprecated wxEVT aliases
        wxEVT_COMMAND_HEADER_CLICK               = wxEVT_HEADER_CLICK
        wxEVT_COMMAND_HEADER_RIGHT_CLICK         = wxEVT_HEADER_RIGHT_CLICK
        wxEVT_COMMAND_HEADER_MIDDLE_CLICK        = wxEVT_HEADER_MIDDLE_CLICK
        wxEVT_COMMAND_HEADER_DCLICK              = wxEVT_HEADER_DCLICK
        wxEVT_COMMAND_HEADER_RIGHT_DCLICK        = wxEVT_HEADER_RIGHT_DCLICK
        wxEVT_COMMAND_HEADER_MIDDLE_DCLICK       = wxEVT_HEADER_MIDDLE_DCLICK
        wxEVT_COMMAND_HEADER_SEPARATOR_DCLICK    = wxEVT_HEADER_SEPARATOR_DCLICK
        wxEVT_COMMAND_HEADER_BEGIN_RESIZE        = wxEVT_HEADER_BEGIN_RESIZE
        wxEVT_COMMAND_HEADER_RESIZING            = wxEVT_HEADER_RESIZING
        wxEVT_COMMAND_HEADER_END_RESIZE          = wxEVT_HEADER_END_RESIZE
        wxEVT_COMMAND_HEADER_BEGIN_REORDER       = wxEVT_HEADER_BEGIN_REORDER
        wxEVT_COMMAND_HEADER_END_REORDER         = wxEVT_HEADER_END_REORDER
        wxEVT_COMMAND_HEADER_DRAGGING_CANCELLED  = wxEVT_HEADER_DRAGGING_CANCELLED
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #59
0
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/srchctrl.h>')

    c = module.find('wxSearchCtrl')
    assert isinstance(c, etgtools.ClassDef)
    module.addGlobalStr('wxSearchCtrlNameStr', c)

    c.find('SetMenu.menu').transfer = True

    c.addCppMethod(
        'void', 'SetSearchBitmap', '(const wxBitmap* bmp)', """\
            #ifdef __WXMAC__
            #else
                self->SetSearchBitmap(*bmp);
            #endif
            """)
    c.addCppMethod(
        'void', 'SetSearchMenuBitmap', '(const wxBitmap* bmp)', """\
            #ifdef __WXMAC__
            #else
                self->SetSearchMenuBitmap(*bmp);
            #endif
            """)
    c.addCppMethod(
        'void', 'SetCancelBitmap', '(const wxBitmap* bmp)', """\
            #ifdef __WXMAC__
            #else
                self->SetSearchMenuBitmap(*bmp);
            #endif
            """)

    searchCtrl = c

    # The safest way to reconcile the differences in the class hierachy
    # between the native wxSearchCtrl on Mac and the generic one on the other
    # platforms is to just say that this class derives directly from
    # wxControl (the first common ancestor) instead of wxTextCtrl, and then
    # redeclare all the wxTextEntry and/or wxTextCtrlIface methods that we
    # are interested in having here. That way the C++ compiler can sort out
    # the proper way to call those methods and avoid calling the wrong
    # implementations like would happen if try to force it another way...
    searchCtrl.bases = ['wxControl']

    # Instead of duplicating those declarations here, let's use the parser
    # and tweakers we already have and then just transplant those MethodDefs
    # into this ClassDef. That will then preserve things like the
    # documentation and custom tweaks that would be real tedious to duplicate
    # and maintain.
    import textentry
    mod = textentry.parseAndTweakModule()
    klass = mod.find('wxTextEntry')
    searchCtrl.items.extend(klass.items)

    # Do the same with wxTextCtrl, but also remove things like the
    # Constructors and Create methods first.
    import textctrl
    mod = textctrl.parseAndTweakModule()
    klass = mod.find('wxTextCtrl')
    # get just the methods that are not ctors, dtor or Create
    items = [
        item for item in klass.items if isinstance(item, etgtools.MethodDef)
        and not item.isCtor and not item.isDtor and item.name != 'Create'
    ]
    searchCtrl.items.extend(items)

    searchCtrl.find('LoadFile').ignore()
    searchCtrl.find('SaveFile').ignore()
    searchCtrl.find('MacCheckSpelling').ignore()

    # Add some properties that autoProperties would not see because they are
    # not using 'Get' and 'Set'
    searchCtrl.addProperty(
        'SearchButtonVisible IsSearchButtonVisible ShowSearchButton')
    searchCtrl.addProperty(
        'CancelButtonVisible IsCancelButtonVisible ShowCancelButton')
    searchCtrl.addAutoProperties()
    tools.fixWindowClass(searchCtrl)

    module.addPyCode("""\
        EVT_SEARCHCTRL_CANCEL_BTN = wx.PyEventBinder( wxEVT_SEARCHCTRL_CANCEL_BTN, 1)
        EVT_SEARCHCTRL_SEARCH_BTN = wx.PyEventBinder( wxEVT_SEARCHCTRL_SEARCH_BTN, 1)
        
        # deprecated wxEVT aliases
        wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN  = wxEVT_SEARCHCTRL_CANCEL_BTN
        wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN  = wxEVT_SEARCHCTRL_SEARCH_BTN
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #60
0
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('wxMask')
    c.mustHaveApp()

    c = module.find('wxBitmap')
    assert isinstance(c, etgtools.ClassDef)
    c.mustHaveApp()
    tools.removeVirtuals(c)

    # TODO: The wxCursor version of the ctor is not implemented on OSX...
    c.find('wxBitmap').findOverload('wxCursor').ignore()

    c.find('wxBitmap.bits').type = 'const char*'
    c.find('wxBitmap.type').default = 'wxBITMAP_TYPE_ANY'
    c.find('LoadFile.type').default = 'wxBITMAP_TYPE_ANY'

    c.find('wxBitmap').findOverload('(const char *const *bits)').ignore()

    c.addCppCtor(
        '(PyObject* listOfBytes)',
        doc="Construct a Bitmap from a list of strings formatted as XPM data.",
        body="""\
            wxPyThreadBlocker blocker;
            char**    cArray = NULL;
            int       count;
            char      errMsg[] = "Expected a list of bytes objects.";

            if (!PyList_Check(listOfBytes)) {
                PyErr_SetString(PyExc_TypeError, errMsg);
                return NULL;
            }
            count = PyList_Size(listOfBytes);
            cArray = new char*[count];

            for(int x=0; x<count; x++) {
                PyObject* item = PyList_GET_ITEM(listOfBytes, x);
                if (!PyBytes_Check(item)) {
                    PyErr_SetString(PyExc_TypeError, errMsg);
                    delete [] cArray;
                    return NULL;
                }
                cArray[x] = PyBytes_AsString(item);
            }
            wxBitmap* bmp = new wxBitmap(cArray);
            delete [] cArray;
            return bmp;
            """)

    c.find('SetMask.mask').transfer = True

    c.addCppMethod(
        'void', 'SetMaskColour', '(const wxColour& colour)', """\
        wxMask* mask = new wxMask(*self, *colour);
        self->SetMask(mask);
        """)

    c.addCppMethod('int', '__nonzero__', '()', """\
        return self->IsOk();
        """)

    c.addCppMethod(
        'long',
        'GetHandle',
        '()',
        doc='MSW-only method to fetch the windows handle for the bitmap.',
        body="""\
            #ifdef __WXMSW__
                return (long)self->GetHandle();
            #else
                return 0;
            #endif
            """)

    c.addCppMethod(
        'void',
        'SetHandle',
        '(long handle)',
        doc='MSW-only method to set the windows handle for the bitmap.',
        body="""\
            #ifdef __WXMSW__
                self->SetHandle((WXHANDLE)handle);
            #endif
            """)

    c.addCppMethod(
        'void',
        'SetSize',
        '(const wxSize& size)',
        doc=
        'Set the bitmap size (does not alter the existing native bitmap data or image size).',
        body="""\
            self->SetWidth(size->x);
            self->SetHeight(size->y);
            """)

    # On MSW the bitmap handler classes are different than what is
    # documented, and this causes compile errors. Nobody has needed them from
    # Python thus far, so just ignore them all for now.
    for m in c.find('FindHandler').all():
        m.ignore()
    c.find('AddHandler').ignore()
    c.find('CleanUpHandlers').ignore()
    c.find('GetHandlers').ignore()
    c.find('InsertHandler').ignore()
    c.find('RemoveHandler').ignore()

    # This one is called from the wx startup code, it's not needed in Python
    # so nuke it too since we're nuking all the others.
    c.find('InitStandardHandlers').ignore()

    module.find('wxBitmapHandler').ignore()
    #module.addItem(tools.wxListWrapperTemplate('wxList', 'wxBitmapHandler', module))

    #-----------------------------------------------------------------------
    # Declarations, helpers and methods for converting to/from buffer objects
    # with raw bitmap access.

    from etgtools import EnumDef, EnumValueDef
    e = EnumDef(name='wxBitmapBufferFormat')
    e.items.extend([
        EnumValueDef(name='wxBitmapBufferFormat_RGB'),
        EnumValueDef(name='wxBitmapBufferFormat_RGBA'),
        EnumValueDef(name='wxBitmapBufferFormat_RGB32'),
        EnumValueDef(name='wxBitmapBufferFormat_ARGB32'),
    ])
    module.insertItem(0, e)

    c.includeCppCode('src/bitmap_ex.cpp')
    module.addHeaderCode('#include "bitmap_ex.h"')

    c.addCppMethod(
        'void',
        'CopyFromBuffer',
        '(wxPyBuffer* data, wxBitmapBufferFormat format=wxBitmapBufferFormat_RGB, int stride=-1)',
        doc="""\
            Copy data from a buffer object to replace the bitmap pixel data.
            Default format is plain RGB, but other formats are now supported as
            well.  The following symbols are used to specify the format of the
            bytes in the buffer:

                =============================  ================================
                wx.BitmapBufferFormat_RGB      A simple sequence of RGB bytes
                wx.BitmapBufferFormat_RGBA     A simple sequence of RGBA bytes
                wx.BitmapBufferFormat_ARGB32   A sequence of 32-bit values in native endian order, with alpha in the upper 8 bits, followed by red, green, and blue.
                wx.BitmapBufferFormat_RGB32    Same as above but the alpha byte is ignored.
                =============================  ================================""",
        body="""\
            wxPyCopyBitmapFromBuffer(self, (byte*)data->m_ptr, data->m_len, format, stride);
        """)

    c.addCppMethod(
        'void',
        'CopyToBuffer',
        '(wxPyBuffer* data, wxBitmapBufferFormat format=wxBitmapBufferFormat_RGB, int stride=-1)',
        doc="""\
            Copy pixel data to a buffer object.  See :meth:`CopyFromBuffer` for buffer
            format details.""",
        body="""\
            wxPyCopyBitmapToBuffer(self, (byte*)data->m_ptr, data->m_len, format, stride);
            """)

    # Some bitmap factories added as static methods

    c.addCppMethod(
        'wxBitmap*',
        'FromBufferAndAlpha',
        '(int width, int height, wxPyBuffer* data, wxPyBuffer* alpha)',
        isStatic=True,
        factory=True,
        doc="""\
            Creates a :class:`wx.Bitmap` from in-memory data.  The data and alpha
            parameters must be a Python object that implements the buffer
            interface, such as a string, bytearray, etc.  The data object
            is expected to contain a series of RGB bytes and be at least
            width*height*3 bytes long, while the alpha object is expected
            to be width*height bytes long and represents the image's alpha
            channel.  On Windows and Mac the RGB values will be
            'premultiplied' by the alpha values.  (The other platforms do
            the multiplication themselves.)

            Unlike :func:`wx.ImageFromBuffer` the bitmap created with this function
            does not share the memory block with the buffer object.  This is
            because the native pixel buffer format varies on different
            platforms, and so instead an efficient as possible copy of the
            data is made from the buffer object to the bitmap's native pixel
            buffer.
            """,
        body="""\
            if (!data->checkSize(width*height*3) || !alpha->checkSize(width*height))
                return NULL;

            byte* ddata = (byte*)data->m_ptr;
            byte* adata = (byte*)alpha->m_ptr;
            wxBitmap* bmp = new wxBitmap(width, height, 32);

            wxAlphaPixelData pixData(*bmp, wxPoint(0,0), wxSize(width,height));
            if (! pixData) {
                wxPyErr_SetString(PyExc_RuntimeError, "Failed to gain raw access to bitmap data.");
                return NULL;
            }

            wxAlphaPixelData::Iterator p(pixData);
            for (int y=0; y<height; y++) {
                wxAlphaPixelData::Iterator rowStart = p;
                for (int x=0; x<width; x++) {
                    byte a = *(adata++);
                    p.Red()   = wxPy_premultiply(*(ddata++), a);
                    p.Green() = wxPy_premultiply(*(ddata++), a);
                    p.Blue()  = wxPy_premultiply(*(ddata++), a);
                    p.Alpha() = a;
                    ++p;
                }
                p = rowStart;
                p.OffsetY(pixData, 1);
            }
            return bmp;
            """)

    c.addCppMethod('wxBitmap*',
                   'FromBuffer',
                   '(int width, int height, wxPyBuffer* data)',
                   isStatic=True,
                   factory=True,
                   doc="""\
            Creates a :class:`wx.Bitmap` from in-memory data.  The data parameter
            must be a Python object that implements the buffer interface, such
            as a string, bytearray, etc.  The data object is expected to contain
            a series of RGB bytes and be at least width*height*3 bytes long.

            Unlike :func:`wx.ImageFromBuffer` the bitmap created with this function
            does not share the memory block with the buffer object.  This is
            because the native pixel buffer format varies on different
            platforms, and so instead an efficient as possible copy of the
            data is made from the buffer object to the bitmap's native pixel
            buffer.
            """,
                   body="""\
            wxBitmap* bmp = new wxBitmap(width, height, 24);
            wxPyCopyBitmapFromBuffer(bmp, (byte*)data->m_ptr, data->m_len, wxBitmapBufferFormat_RGB);
            wxPyThreadBlocker blocker;
            if (PyErr_Occurred()) {
                delete bmp;
                bmp = NULL;
            }
            return bmp;
            """)

    module.addPyFunction(
        'BitmapFromBuffer',
        '(width, height, dataBuffer, alphaBuffer=None)',
        deprecated=
        "Use :meth:`wx.Bitmap.FromBuffer` or :meth:`wx.Bitmap.FromBufferAndAlpha` instead.",
        doc=
        'A compatibility wrapper for :meth:`wx.Bitmap.FromBuffer` and :meth:`wx.Bitmap.FromBufferAndAlpha`',
        body="""\
            if alphaBuffer is not None:
                return Bitmap.FromBufferAndAlpha(width, height, dataBuffer, alphaBuffer)
            else:
                return Bitmap.FromBuffer(width, height, dataBuffer)
            """)

    c.addCppMethod('wxBitmap*',
                   'FromBufferRGBA',
                   '(int width, int height, wxPyBuffer* data)',
                   isStatic=True,
                   factory=True,
                   doc="""\
            Creates a :class:`wx.Bitmap` from in-memory data.  The data parameter
            must be a Python object that implements the buffer interface, such
            as a string, bytearray, etc.  The data object is expected to contain
            a series of RGBA bytes and be at least width*height*4 bytes long.
            On Windows and Mac the RGB values will be 'premultiplied' by the
            alpha values.  (The other platforms do the multiplication themselves.)

            Unlike :func:`wx.ImageFromBuffer` the bitmap created with this function
            does not share the memory block with the buffer object.  This is
            because the native pixel buffer format varies on different
            platforms, and so instead an efficient as possible copy of the
            data is made from the buffer object to the bitmap's native pixel
            buffer.
            """,
                   body="""\
            wxBitmap* bmp = new wxBitmap(width, height, 32);
            wxPyCopyBitmapFromBuffer(bmp, (byte*)data->m_ptr, data->m_len, wxBitmapBufferFormat_RGBA);
            wxPyThreadBlocker blocker;
            if (PyErr_Occurred()) {
                delete bmp;
                bmp = NULL;
            }
            return bmp;
            """)

    module.addPyFunction(
        'BitmapFromBufferRGBA',
        '(width, height, dataBuffer)',
        deprecated="Use :meth:`wx.Bitmap.FromBufferRGBA` instead.",
        doc='A compatibility wrapper for :meth:`wx.Bitmap.FromBufferRGBA`',
        body='return Bitmap.FromBufferRGBA(width, height, dataBuffer)')

    c.addCppMethod(
        'wxBitmap*',
        'FromRGBA',
        '(int width, int height, byte red=0, byte green=0, byte blue=0, byte alpha=0)',
        isStatic=True,
        factory=True,
        doc="""\
            Creates a new empty 32-bit :class:`wx.Bitmap` where every pixel has been
            initialized with the given RGBA values.
            """,
        body="""\
            if ( !(width > 0 && height > 0) ) {
                wxPyErr_SetString(PyExc_ValueError, "Width and height must be greater than zero");
                return NULL;
            }

            wxBitmap* bmp = new wxBitmap(width, height, 32);
            wxAlphaPixelData pixData(*bmp, wxPoint(0,0), wxSize(width,height));
            if (! pixData) {
                wxPyErr_SetString(PyExc_RuntimeError, "Failed to gain raw access to bitmap data.");
                return NULL;
            }

            wxAlphaPixelData::Iterator p(pixData);
            for (int y=0; y<height; y++) {
                wxAlphaPixelData::Iterator rowStart = p;
                for (int x=0; x<width; x++) {
                    p.Red()   = wxPy_premultiply(red, alpha);
                    p.Green() = wxPy_premultiply(green, alpha);
                    p.Blue()  = wxPy_premultiply(blue, alpha);
                    p.Alpha() = alpha;
                    ++p;
                }
                p = rowStart;
                p.OffsetY(pixData, 1);
            }
            return bmp;
            """)

    module.addPyFunction(
        'EmptyBitmapRGBA',
        '(width, height, red=0, green=0, blue=0, alpha=0)',
        deprecated="Use :meth:`wx.Bitmap.FromRGBA` instead.",
        doc='A compatibility wrapper for :meth:`wx.Bitmap.FromRGBA`',
        body='return Bitmap.FromRGBA(width, height, red, green, blue, alpha)')

    #-----------------------------------------------------------------------

    # For compatibility:
    module.addPyFunction(
        'EmptyBitmap',
        '(width, height, depth=BITMAP_SCREEN_DEPTH)',
        deprecated="Use :class:`wx.Bitmap` instead",
        doc=
        'A compatibility wrapper for the wx.Bitmap(width, height, depth) constructor',
        body='return Bitmap(width, height, depth)')

    module.addPyFunction(
        'BitmapFromImage',
        '(image)',
        deprecated="Use :class:`wx.Bitmap` instead",
        doc='A compatibility wrapper for the wx.Bitmap(wx.Image) constructor',
        body='return Bitmap(image)')

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)