Exemple #1
0
    def fixRendererClass(name):
        klass = module.find(name)
        assert isinstance(klass, etgtools.ClassDef)
        tools.fixRefCountedClass(klass)
        tools.addAutoProperties(klass)

        methods = [
            ('Clone',       "virtual wxGridCellRenderer* Clone() const /Factory/;"),
            ('Draw',        "virtual void Draw(wxGrid& grid, wxGridCellAttr& attr, wxDC& dc, "
                            "    const wxRect& rect, int row, int col, bool isSelected);"),
            ('GetBestSize', "virtual wxSize GetBestSize(wxGrid& grid, wxGridCellAttr& attr, "
                            "    wxDC& dc, int row, int col);"),
            ]
        for method, code in methods:
            if not klass.findItem(method):
                klass.addItem(etgtools.WigCode(code))
Exemple #2
0
    def fixRendererClass(name):
        klass = module.find(name)
        assert isinstance(klass, etgtools.ClassDef)
        tools.fixRefCountedClass(klass)
        tools.addAutoProperties(klass)

        methods = [
            ('Clone',       "virtual wxGridCellRenderer* Clone() const /Factory/;"),
            ('Draw',        "virtual void Draw(wxGrid& grid, wxGridCellAttr& attr, wxDC& dc, "
                            "    const wxRect& rect, int row, int col, bool isSelected);"),
            ('GetBestSize', "virtual wxSize GetBestSize(wxGrid& grid, wxGridCellAttr& attr, "
                            "    wxDC& dc, int row, int col);"),
            ]
        for method, code in methods:
            if not klass.findItem(method):
                klass.addItem(etgtools.WigCode(code))
Exemple #3
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/dataview.h>")

    for item in module.allItems():
        if hasattr(item, 'type') and 'wxVariant' in item.type:
            item.type = item.type.replace('wxVariant', 'wxDVCVariant')

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

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

    c.addCppMethod(
        'bool', '__eq__', '(wxDataViewItem* other)',
        "return other ? (self->GetID() == other->GetID()) : false;")
    c.addCppMethod('bool', '__ne__', '(wxDataViewItem* other)',
                   "return other ? (self->GetID() != other->GetID()) : true;")
    c.addAutoProperties()

    module.addItem(
        tools.wxArrayWrapperTemplate('wxDataViewItemArray', 'wxDataViewItem',
                                     module))
    module.addPyCode("NullDataViewItem = DataViewItem()")

    #-----------------------------------------------------------------
    c = module.find('wxDataViewModel')
    c.addAutoProperties()
    tools.fixRefCountedClass(c)

    c.find('~wxDataViewModel').ignore(False)

    c.find('AddNotifier.notifier').transfer = True
    c.find('RemoveNotifier.notifier').transferBack = True

    # Change the GetValue method to return the value instead of passing it
    # through a parameter for modification.
    c.find('GetValue.variant').out = True
    c.find(
        'GetValue'
    ).cppSignature = 'void (wxVariant& variant, const wxDataViewItem& item, unsigned int col)'

    # The DataViewItemObjectMapper class helps map from data items to Python
    # objects, and is used as a base class of PyDataViewModel as a
    # convenience.
    module.addPyClass(
        'DataViewItemObjectMapper', ['object'],
        doc="""\
            This class provides a mechanism for mapping between Python objects and the
            :class:`DataViewItem` objects used by the :class:`DataViewModel` for tracking the items in
            the view. The ID used for the item is the id() of the Python object. Use
            :meth:`ObjectToItem` to create a :class:`DataViewItem` using a Python object as its ID,
            and use :meth:`ItemToObject` to fetch that Python object again later for a given
            :class:`DataViewItem`.

            By default a regular dictionary is used to implement the ID to object
            mapping. Optionally a WeakValueDictionary can be useful when there will be
            a high turnover of objects and maintaining an extra reference to the
            objects would be unwise.  If weak references are used then the objects
            associated with data items must be weak-referenceable.  (Things like
            stock lists and dictionaries are not.)  See :meth:`UseWeakRefs`.

            This class is used in :class:`PyDataViewModel` as a mixin for convenience.
            """,
        items=[
            PyFunctionDef('__init__',
                          '(self)',
                          body="""\
                    self.mapper = dict()
                    self.usingWeakRefs = False
                    """),
            PyFunctionDef(
                'ObjectToItem',
                '(self, obj)',
                doc=
                "Create a :class:`DataViewItem` for the object, and remember the ID-->obj mapping.",
                body="""\
                    import sys
                    oid = id(obj)
                    while oid > sys.maxsize:
                        # risk of conflict here... May need some more thought.
                        oid -= sys.maxsize
                    self.mapper[oid] = obj
                    return DataViewItem(oid)
                    """),
            PyFunctionDef(
                'ItemToObject',
                '(self, item)',
                doc="Retrieve the object that was used to create an item.",
                body="""\
                    oid = int(item.GetID())
                    return self.mapper[oid]
                    """),
            PyFunctionDef('UseWeakRefs',
                          '(self, flag)',
                          doc="""\
                    Switch to or from using a weak value dictionary for keeping the ID to
                    object map.""",
                          body="""\
                    if flag == self.usingWeakRefs:
                        return
                    if flag:
                        import weakref
                        newmap = weakref.WeakValueDictionary()
                    else:
                        newmap = dict()
                    newmap.update(self.mapper)
                    self.mapper = newmap
                    self.usingWeakRefs = flag
                    """),
        ])

    module.addPyClass(
        'PyDataViewModel', ['DataViewModel', 'DataViewItemObjectMapper'],
        doc=
        "A convenience class that is a :class:`DataViewModel` combined with an object mapper.",
        items=[
            PyFunctionDef('__init__',
                          '(self)',
                          body="""\
                    DataViewModel.__init__(self)
                    DataViewItemObjectMapper.__init__(self)
                    """)
        ])

    #-----------------------------------------------------------------
    c = module.find('wxDataViewListModel')
    c.addAutoProperties()
    tools.fixRefCountedClass(c)

    # Change the GetValueByRow method to return the value instead of passing
    # it through a parameter for modification.
    c.find('GetValueByRow.variant').out = True
    c.find(
        'GetValueByRow'
    ).cppSignature = 'void (wxVariant& variant, unsigned int row, unsigned int col)'

    # declare implementations for base class virtuals
    c.addItem(
        etgtools.WigCode("""\
        virtual wxDataViewItem GetParent( const wxDataViewItem &item ) const;
        virtual bool IsContainer( const wxDataViewItem &item ) const;
        virtual void GetValue( wxDVCVariant &variant /Out/, const wxDataViewItem &item, unsigned int col ) const [void ( wxDVCVariant &variant, const wxDataViewItem &item, unsigned int col )];
        virtual bool SetValue( const wxDVCVariant &variant, const wxDataViewItem &item, unsigned int col );
        virtual bool GetAttr(const wxDataViewItem &item, unsigned int col, wxDataViewItemAttr &attr) const;
        virtual bool IsEnabled(const wxDataViewItem &item, unsigned int col) const;
        virtual bool IsListModel() const;
        """))

    # Add some of the pure virtuals since there are undocumented
    # implementations of them in these classes. The others will need to be
    # implemented in Python classes derived from these.
    for name in ['wxDataViewIndexListModel', 'wxDataViewVirtualListModel']:
        c = module.find(name)

        c.addItem(
            etgtools.WigCode("""\
            virtual unsigned int GetRow(const wxDataViewItem& item) const;
            virtual unsigned int GetCount() const;
            virtual unsigned int GetChildren( const wxDataViewItem &item, wxDataViewItemArray &children ) const;
            """))

    # compatibility aliases
    module.addPyCode("""\
        PyDataViewIndexListModel = wx.deprecated(DataViewIndexListModel)
        PyDataViewVirtualListModel = wx.deprecated(DataViewVirtualListModel)
        """)

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

    def _fixupBoolGetters(method, sig):
        method.type = 'void'
        method.find('value').out = True
        method.find('value').type = 'wxDVCVariant&'
        method.cppSignature = sig

    def _fixupTypeParam(klass):
        param = klass.findItem('{}.varianttype'.format(klass.name))
        if param and param.default == 'GetDefaultType()':
            param.default = '{}::GetDefaultType()'.format(klass.name)

    c = module.find('wxDataViewRenderer')
    c.addPrivateCopyCtor()
    c.abstract = True
    c.find('GetView').ignore(False)

    # TODO: This is only available when wxUSE_ACCESSIBILITY is set to 1
    c.find('GetAccessibleDescription').ignore()

    c.addAutoProperties()

    # Change variant getters to return the value
    for name, sig in [
        ('GetValue', 'bool (wxVariant& value)'),
        ('GetValueFromEditorCtrl',
         'bool (wxWindow * editor, wxVariant& value)'),
    ]:
        _fixupBoolGetters(c.find(name), sig)

    m = c.find('SetValue')
    m.find('value').type = 'const wxDVCVariant&'
    m.cppSignature = 'bool (const wxVariant& value)'

    m = c.find('CreateEditorCtrl')
    m.cppSignature = 'wxWindow* (wxWindow * parent, wxRect labelRect, const wxVariant& value)'

    c.find('GetView').ignore(False)

    c = module.find('wxDataViewCustomRenderer')
    _fixupTypeParam(c)
    m = c.find('GetValueFromEditorCtrl')
    _fixupBoolGetters(m, 'bool (wxWindow * editor, wxVariant& value)')

    # Change the virtual method handler code to follow the same pattern as the
    # tweaked public API, namely that the value is the return value instead of
    # an out parameter.
    m.virtualCatcherCode = """\
        PyObject *sipResObj = sipCallMethod(&sipIsErr, sipMethod, "D", editor, sipType_wxWindow, NULL);
        if (sipResObj == NULL) {
            if (PyErr_Occurred())
                PyErr_Print();
            sipRes = false;
        }
        else if (sipResObj == Py_None) {
            sipRes = false;
        } else {
            sipRes = true;
            sipParseResult(&sipIsErr, sipMethod, sipResObj, "H5", sipType_wxDVCVariant, &value);
        }
        """

    c.find('GetTextExtent').ignore(False)

    m = c.find('CreateEditorCtrl')
    m.cppSignature = 'wxWindow* (wxWindow * parent, wxRect labelRect, const wxVariant& value)'

    module.addPyCode("""\
        PyDataViewCustomRenderer = wx.deprecated(DataViewCustomRenderer,
                                                 "Use DataViewCustomRenderer instead")"""
                     )

    # Add the pure virtuals since there are undocumented implementations of
    # them in all these classes
    for name in [
            'wxDataViewTextRenderer',
            'wxDataViewIconTextRenderer',
            'wxDataViewProgressRenderer',
            'wxDataViewSpinRenderer',
            'wxDataViewToggleRenderer',
            'wxDataViewChoiceRenderer',
            #'wxDataViewChoiceByIndexRenderer',
            'wxDataViewDateRenderer',
            'wxDataViewBitmapRenderer',
    ]:
        c = module.find(name)
        c.addAutoProperties()
        _fixupTypeParam(c)

        c.addItem(
            etgtools.WigCode("""\
            virtual bool SetValue( const wxDVCVariant &value ) [bool (const wxVariant& value)];
            virtual void GetValue( wxDVCVariant &value /Out/ ) const [bool (wxVariant& value)];
            %Property(name=Value, get=GetValue, set=SetValue)
            """,
                             protection='public'))

    # The SpinRenderer has a few additional pure virtuals that need to be declared
    # since it derives from DataViewCustomRenderer
    c = module.find('wxDataViewSpinRenderer')
    c.addItem(
        etgtools.WigCode("""\
        virtual wxSize GetSize() const;
        virtual bool Render(wxRect cell, wxDC* dc, int state);
        """,
                         protection='public'))

    #-----------------------------------------------------------------
    c = module.find('wxDataViewColumn')
    for m in c.find('wxDataViewColumn').all():
        m.find('renderer').transfer = True

    # declare the virtuals from wxSettableHeaderColumn
    c.addItem(
        etgtools.WigCode("""\
        virtual void SetTitle(const wxString& title);
        virtual wxString GetTitle() const;
        virtual void SetBitmap(const wxBitmap& bitmap);
        virtual wxBitmap GetBitmap() const;
        virtual void SetWidth(int width);
        virtual int GetWidth() const;
        virtual void SetMinWidth(int minWidth);
        virtual int GetMinWidth() const;
        virtual void SetAlignment(wxAlignment align);
        virtual wxAlignment GetAlignment() const;
        virtual void SetFlags(int flags);
        virtual int GetFlags() const;
        virtual bool IsSortKey() const;
        virtual void SetSortOrder(bool ascending);
        virtual bool IsSortOrderAscending() const;

        virtual void SetResizeable(bool resizable);
        virtual void SetSortable(bool sortable);
        virtual void SetReorderable(bool reorderable);
        virtual void SetHidden(bool hidden);
        """))

    c.addAutoProperties()
    c.addProperty('Title', 'GetTitle', 'SetTitle')
    c.addProperty('Bitmap', 'GetBitmap', 'SetBitmap')
    c.addProperty('Width', 'GetWidth', 'SetWidth')
    c.addProperty('MinWidth', 'GetMinWidth', 'SetMinWidth')
    c.addProperty('Alignment', 'GetAlignment', 'SetAlignment')
    c.addProperty('Flags', 'GetFlags', 'SetFlags')
    c.addProperty('SortOrder', 'IsSortOrderAscending', 'SetSortOrder')

    #-----------------------------------------------------------------
    c = module.find('wxDataViewCtrl')
    tools.fixWindowClass(c)
    module.addGlobalStr('wxDataViewCtrlNameStr', c)

    tools.addEnableSystemTheme(c, 'wx.dataview.DataViewCtrl')

    c.find('AssociateModel.model').transfer = True
    c.find('AssociateModel').pyName = '_AssociateModel'
    c.addPyMethod('AssociateModel',
                  '(self, model)',
                  doc="""\
            Associates a :class:`DataViewModel` with the control.
            Ownership of the model object is passed to C++, however it
            is reference counted so it can be shared with other views.
            """,
                  body="""\
            import wx.siplib
            wasPyOwned = wx.siplib.ispyowned(model)
            self._AssociateModel(model)
            # Ownership of the python object has just been transferred to
            # C++, so DecRef the C++ instance associated with this python
            # reference.
            if wasPyOwned:
                model.DecRef()
            """)

    c.find('PrependColumn.col').transfer = True
    c.find('InsertColumn.col').transfer = True
    c.find('AppendColumn.col').transfer = True

    c.addPyMethod(
        'GetColumns',
        '(self)',
        doc="Returns a list of column objects.",
        body="return [self.GetColumn(i) for i in range(self.GetColumnCount())]"
    )

    c.find('GetSelections').ignore()
    c.addCppMethod('wxDataViewItemArray*',
                   'GetSelections',
                   '()',
                   isConst=True,
                   factory=True,
                   doc="Returns a list of the currently selected items.",
                   body="""\
            wxDataViewItemArray* selections = new wxDataViewItemArray;
            self->GetSelections(*selections);
            return selections;
            """)

    # Pythonize HitTest
    c.find('HitTest').ignore()
    c.addCppMethod('PyObject*',
                   'HitTest',
                   '(const wxPoint& point)',
                   isConst=True,
                   doc="""\
            HitTest(point) -> (item, col)\n
            Returns the item and column located at point, as a 2 element tuple.
            """,
                   body="""\
            wxDataViewItem*   item = new wxDataViewItem();;
            wxDataViewColumn* col = NULL;

            self->HitTest(*point, *item, col);

            wxPyThreadBlocker blocker;
            PyObject* value = PyTuple_New(2);
            PyObject* item_obj =
                wxPyConstructObject((void*)item, wxT("wxDataViewItem"), 1);   // owned
            PyObject* col_obj;
            if (col) {
                col_obj = wxPyConstructObject((void*)col, wxT("wxDataViewColumn"), 0);  // not owned
            } else {
                col_obj = Py_None;
                Py_INCREF(Py_None);
            }
            PyTuple_SET_ITEM(value, 0, item_obj);
            PyTuple_SET_ITEM(value, 1, col_obj);
            // PyTuple steals a reference, so we don't need to decref the items here
            return value;
            """)

    # TODO: add support for wxVector templates
    c.find('GetSortingColumns').ignore()

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

    c.find('SetCache.from').name = 'from_'
    c.find('SetCache.to').name = 'to_'

    c.find('GetDataBuffer').ignore()
    c.addCppMethod('PyObject*',
                   'GetDataBuffer',
                   '()',
                   isConst=True,
                   doc="Gets the data buffer for a drop data transfer",
                   body="""\
            wxPyThreadBlocker blocker;
            return wxPyMakeBuffer(self->GetDataBuffer(), self->GetDataSize(), true);
            """)

    # TODO: SetDataBuffer

    c.find('SetDataObject.obj').transfer = True

    module.addPyCode("""\
        EVT_DATAVIEW_SELECTION_CHANGED         = wx.PyEventBinder( wxEVT_DATAVIEW_SELECTION_CHANGED, 1)
        EVT_DATAVIEW_ITEM_ACTIVATED            = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_ACTIVATED, 1)
        EVT_DATAVIEW_ITEM_COLLAPSED            = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_COLLAPSED, 1)
        EVT_DATAVIEW_ITEM_EXPANDED             = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EXPANDED, 1)
        EVT_DATAVIEW_ITEM_COLLAPSING           = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_COLLAPSING, 1)
        EVT_DATAVIEW_ITEM_EXPANDING            = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EXPANDING, 1)
        EVT_DATAVIEW_ITEM_START_EDITING        = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_START_EDITING, 1)
        EVT_DATAVIEW_ITEM_EDITING_STARTED      = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EDITING_STARTED, 1)
        EVT_DATAVIEW_ITEM_EDITING_DONE         = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EDITING_DONE, 1)
        EVT_DATAVIEW_ITEM_VALUE_CHANGED        = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, 1)
        EVT_DATAVIEW_ITEM_CONTEXT_MENU         = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, 1)
        EVT_DATAVIEW_COLUMN_HEADER_CLICK       = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_HEADER_CLICK, 1)
        EVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK, 1)
        EVT_DATAVIEW_COLUMN_SORTED             = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_SORTED, 1)
        EVT_DATAVIEW_COLUMN_REORDERED          = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_REORDERED, 1)
        EVT_DATAVIEW_ITEM_BEGIN_DRAG           = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_BEGIN_DRAG, 1)
        EVT_DATAVIEW_ITEM_DROP_POSSIBLE        = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_DROP_POSSIBLE, 1)
        EVT_DATAVIEW_ITEM_DROP                 = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_DROP, 1)
        EVT_DATAVIEW_CACHE_HINT                = wx.PyEventBinder( wxEVT_DATAVIEW_CACHE_HINT, 1 )

        # deprecated wxEVT aliases
        wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED          = wxEVT_DATAVIEW_SELECTION_CHANGED
        wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED             = wxEVT_DATAVIEW_ITEM_ACTIVATED
        wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED             = wxEVT_DATAVIEW_ITEM_COLLAPSED
        wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED              = wxEVT_DATAVIEW_ITEM_EXPANDED
        wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING            = wxEVT_DATAVIEW_ITEM_COLLAPSING
        wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING             = wxEVT_DATAVIEW_ITEM_EXPANDING
        wxEVT_COMMAND_DATAVIEW_ITEM_START_EDITING         = wxEVT_DATAVIEW_ITEM_START_EDITING
        wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED       = wxEVT_DATAVIEW_ITEM_EDITING_STARTED
        wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE          = wxEVT_DATAVIEW_ITEM_EDITING_DONE
        wxEVT_COMMAND_DATAVIEW_ITEM_VALUE_CHANGED         = wxEVT_DATAVIEW_ITEM_VALUE_CHANGED
        wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU          = wxEVT_DATAVIEW_ITEM_CONTEXT_MENU
        wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK        = wxEVT_DATAVIEW_COLUMN_HEADER_CLICK
        wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK  = wxEVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK
        wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED              = wxEVT_DATAVIEW_COLUMN_SORTED
        wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED           = wxEVT_DATAVIEW_COLUMN_REORDERED
        wxEVT_COMMAND_DATAVIEW_CACHE_HINT                 = wxEVT_DATAVIEW_CACHE_HINT
        wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG            = wxEVT_DATAVIEW_ITEM_BEGIN_DRAG
        wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE         = wxEVT_DATAVIEW_ITEM_DROP_POSSIBLE
        wxEVT_COMMAND_DATAVIEW_ITEM_DROP                  = wxEVT_DATAVIEW_ITEM_DROP
        """)

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

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

    c.find('AppendItem.values').type = 'const wxVariantVector&'
    c.find('PrependItem.values').type = 'const wxVariantVector&'
    c.find('InsertItem.values').type = 'const wxVariantVector&'

    c.find('GetValue.value').out = True

    for name in 'AppendColumn InsertColumn PrependColumn'.split():
        for m in c.find(name).all():
            m.find('column').transfer = True

    c = module.find('wxDataViewListStore')
    c.find('AppendItem.values').type = 'const wxVariantVector&'
    c.find('PrependItem.values').type = 'const wxVariantVector&'
    c.find('InsertItem.values').type = 'const wxVariantVector&'
    c.find('GetValueByRow.value').out = True
    c.find(
        'GetValueByRow'
    ).cppSignature = 'void (wxVariant& value, unsigned int row, unsigned int col)'

    c.addAutoProperties()

    #-----------------------------------------------------------------
    def _setClientDataTrasfer(klass):
        for item in klass.allItems():
            if isinstance(item, ParamDef) and item.type == 'wxClientData *':
                item.transfer = True

    c = module.find('wxDataViewTreeCtrl')
    tools.fixWindowClass(c)
    _setClientDataTrasfer(c)
    c.find('GetStore').overloads = []

    c = module.find('wxDataViewTreeStore')
    c.addAutoProperties()
    tools.fixRefCountedClass(c)
    _setClientDataTrasfer(c)

    #-----------------------------------------------------------------
    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.addGlobalStr('wxGridNameStr', module.items[0])
    module.addPyCode("""\
        GRID_VALUE_STRING =    "string"
        GRID_VALUE_BOOL =      "bool"
        GRID_VALUE_NUMBER =    "long"
        GRID_VALUE_FLOAT =     "double"
        GRID_VALUE_CHOICE =    "choice"
        GRID_VALUE_DATE =      "date"
        GRID_VALUE_TEXT =      "string"
        GRID_VALUE_LONG =      "long"
        GRID_VALUE_CHOICEINT = "choiceint"
        GRID_VALUE_DATETIME =  "datetime"
        """)

    # Add compatibility constants for these since they've been removed from wxWidgets
    # TODO: Remove these in a future release.
    module.addPyCode("""\
        GRIDTABLE_REQUEST_VIEW_GET_VALUES = 2000
        GRIDTABLE_REQUEST_VIEW_SEND_VALUES = 2001
        """)

    module.insertItem(
        0, etgtools.TypedefDef(type='wxWindow', name='wxGridWindow'))

    #-----------------------------------------------------------------
    c = module.find('wxGridCellCoords')
    assert isinstance(c, etgtools.ClassDef)
    tools.addAutoProperties(c)
    c.find('operator!').ignore()
    c.find('operator=').ignore()

    # Add a typemap for 2 element sequences
    c.convertFromPyObject = tools.convertTwoIntegersTemplate(
        'wxGridCellCoords')

    c.addCppMethod('PyObject*',
                   'Get',
                   '()',
                   """\
        wxPyThreadBlocker blocker;
        return sipBuildResult(0, "(ii)", self->GetRow(), self->GetCol());
        """,
                   pyArgsString="() -> (row,col)",
                   briefDoc="Return the row and col properties as a tuple.")

    tools.addGetIMMethodTemplate(module, c, ['Row', 'Col'])

    # Add sequence protocol methods and other goodies
    c.addPyMethod('__str__', '(self)', 'return str(self.Get())')
    c.addPyMethod('__repr__', '(self)',
                  'return "GridCellCoords"+str(self.Get())')
    c.addPyMethod('__len__', '(self)', 'return len(self.Get())')
    c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0)')
    c.addPyMethod('__bool__', '(self)', 'return self.Get() != (0,0)')
    c.addPyMethod('__reduce__', '(self)',
                  'return (GridCellCoords, self.Get())')
    c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]')
    c.addPyMethod(
        '__setitem__', '(self, idx, val)', """\
                  if idx == 0: self.Row = val
                  elif idx == 1: self.Col = val
                  else: raise IndexError
                  """)
    c.addPyCode('GridCellCoords.__safe_for_unpickling__ = True')

    module.addItem(
        tools.wxArrayWrapperTemplate('wxGridCellCoordsArray',
                                     'wxGridCellCoords',
                                     module,
                                     getItemCopy=True))

    #-----------------------------------------------------------------
    c = module.find('wxGridBlockCoords')
    tools.addAutoProperties(c)

    c.find('operator!').ignore()
    c.addCppMethod('int', '__bool__', '()', "return self->operator!();")

    c.addCppMethod('PyObject*',
                   'Get',
                   '()',
                   """\
        wxPyThreadBlocker blocker;
        return sipBuildResult(0, "(iiii)", self->GetTopRow(), self->GetLeftCol(), self->GetBottomRow(), self->GetRightCol());
        """,
                   pyArgsString="() -> (topRow, leftCol, bottomRow, rightCol)",
                   briefDoc="Return the block coordinants as a tuple.")

    c.addPyMethod('__str__', '(self)', 'return str(self.Get())')
    c.addPyMethod('__repr__', '(self)',
                  'return "GridBlockCoords"+str(self.Get())')

    #-----------------------------------------------------------------
    c = module.find('wxGridBlockDiffResult')
    c.find('m_parts').ignore()

    c.addCppMethod(
        'PyObject*', '_getParts', '()', """\
        wxPyThreadBlocker blocker;
        PyObject* ret = PyTuple_New(4);
        if (ret) {
            PyTuple_SET_ITEM(ret, 0, wxPyConstructObject(&self->m_parts[0], "wxGridBlockCoords", false));
            PyTuple_SET_ITEM(ret, 1, wxPyConstructObject(&self->m_parts[1], "wxGridBlockCoords", false));
            PyTuple_SET_ITEM(ret, 2, wxPyConstructObject(&self->m_parts[2], "wxGridBlockCoords", false));
            PyTuple_SET_ITEM(ret, 3, wxPyConstructObject(&self->m_parts[3], "wxGridBlockCoords", false));
        }
        return ret;
        """)
    c.addProperty('m_parts', '_getParts')

    #-----------------------------------------------------------------
    c = module.find('wxGridBlocks')
    c.addPrivateDefaultCtor()
    c.addPrivateAssignOp()

    c.addPyMethod(
        '__iter__', '(self)', 'return PyGridBlocksIterator(self)',
        "Returns a Python iterator for accessing the collection of grid blocks."
    )

    # This class is the Python iterator that knows how to fetch blocks from the
    # wxGridBlocks object
    c.addPyCode("""\
        class PyGridBlocksIterator(object):
            "A Python iterator for GridBlocks objects"
            def __init__(self, blocks):
                self._blocks = blocks
                self._iterator = self._blocks.begin()

            def __next__(self):
                if self._iterator == self._blocks.end():
                    raise StopIteration
                obj = self._iterator._get()
                self._iterator = self._iterator._next()
                return obj
        """)

    # c.find('iterator').addCppMethod('wxGridBlocks::iterator', '_next', '()',
    #                                 "return self->operator++();")
    # c.find('iterator').addCppMethod('const wxGridBlockCoords&', '_get', '()',
    #                                 "return self->operator*();")

    # TODO: Doing these the normal way (above) breaks because it tries to use just
    # "iterator" for the self param type, instead of wxGridBlocks::iterator.
    # That should be fixable, but until then just add these methods the manual
    # sip way.
    c.find('iterator').addItem(
        etgtools.WigCode("""\
        iterator& _next();
        %MethodCode
            PyErr_Clear();
            Py_BEGIN_ALLOW_THREADS
            sipRes = &sipCpp->operator++();
            Py_END_ALLOW_THREADS
            if (PyErr_Occurred()) return 0;
        %End

        const wxGridBlockCoords& _get() const;
        %MethodCode
            PyErr_Clear();
            Py_BEGIN_ALLOW_THREADS
            sipRes =  new ::wxGridBlockCoords(sipCpp->operator*());
            Py_END_ALLOW_THREADS
            if (PyErr_Occurred()) return 0;
        %End

        bool __eq__(const iterator& it) const;
        bool __ne__(const iterator& it) const;
        """))

    #-----------------------------------------------------------------
    c = module.find('wxGridSizesInfo')
    c.find('m_customSizes').ignore(
    )  # TODO: Add support for wxUnsignedToIntHashMap??

    #-----------------------------------------------------------------
    def fixRendererClass(name):
        klass = module.find(name)
        assert isinstance(klass, etgtools.ClassDef)
        tools.fixRefCountedClass(klass)
        tools.addAutoProperties(klass)

        methods = [
            ('Clone', "virtual wxGridCellRenderer* Clone() const /Factory/;"),
            ('Draw',
             "virtual void Draw(wxGrid& grid, wxGridCellAttr& attr, wxDC& dc, "
             "    const wxRect& rect, int row, int col, bool isSelected);"),
            ('GetBestSize',
             "virtual wxSize GetBestSize(wxGrid& grid, wxGridCellAttr& attr, "
             "    wxDC& dc, int row, int col);"),
        ]
        for method, code in methods:
            if not klass.findItem(method):
                klass.addItem(etgtools.WigCode(code))

    c = module.find('wxGridCellRenderer')
    c.addPrivateCopyCtor()
    c.find('~wxGridCellRenderer').ignore(False)
    c.find('Clone').factory = True
    tools.fixRefCountedClass(c)

    for name in ITEMS:
        if 'Cell' in name and 'Renderer' in name:
            fixRendererClass(name)

    module.addPyCode(
        "PyGridCellRenderer = wx.deprecated(GridCellRenderer, 'Use GridCellRenderer instead.')"
    )

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

    c = module.find('wxGridActivationResult')
    c.ignore()  # FIXME
    c.addPrivateAssignOp()
    c.instanceCode = 'sipCpp = new wxGridActivationResult::DoNothing();'

    c = module.find('wxGridActivationSource')
    c.ignore()  # FIXME
    c.noDefCtor = True
    c.addPrivateAssignOp()

    #-----------------------------------------------------------------
    def fixEditorClass(name):
        klass = module.find(name)
        assert isinstance(klass, etgtools.ClassDef)
        tools.fixRefCountedClass(klass)
        tools.addAutoProperties(klass)

        methods = [
            ('BeginEdit',
             "virtual void BeginEdit(int row, int col, wxGrid* grid);"),
            ('Clone', "virtual wxGridCellEditor* Clone() const /Factory/;"),
            ('Create',
             "virtual void Create(wxWindow* parent, wxWindowID id, wxEvtHandler* evtHandler);"
             ),
            #('EndEdit',    "virtual bool EndEdit(int row, int col, const wxGrid* grid, const wxString& oldval, wxString* newval);"),
            ('ApplyEdit',
             "virtual void ApplyEdit(int row, int col, wxGrid* grid);"),
            ('Reset', "virtual void Reset();"),
            ('GetValue', "virtual wxString GetValue() const;"),
        ]
        for method, code in methods:
            if not klass.findItem(method):
                klass.addItem(etgtools.WigCode(code))

        # Fix up EndEdit so it returns newval on success or None on failure
        pureVirtual = False
        if klass.findItem('EndEdit'):
            klass.find('EndEdit').ignore()
            pureVirtual = True

        # The Python version of EndEdit has a different signature than the
        # C++ version, so we need to take care of mapping between them so the
        # C++ compiler still recognizes this as a match for the virtual
        # method in the base class.
        klass.addCppMethod(
            'PyObject*',
            'EndEdit',
            '(int row, int col, const wxGrid* grid, const wxString& oldval)',
            cppSignature=
            'bool (int row, int col, const wxGrid* grid, const wxString& oldval, wxString* newval)',
            pyArgsString='(row, col, grid, oldval)',
            isVirtual=True,
            isPureVirtual=pureVirtual,
            doc="""\
                End editing the cell.

                This function must check if the current value of the editing cell
                is valid and different from the original value in its string
                form. If not then simply return None.  If it has changed then
                this method should save the new value so that ApplyEdit can
                apply it later and the string representation of the new value
                should be returned.

                Notice that this method shoiuld not modify the grid as the
                change could still be vetoed.
                """,

            # Code for Python --> C++ calls.  Make it return newval or None.
            body="""\
                bool rv;
                wxString newval;
                rv = self->EndEdit(row, col, grid, *oldval, &newval);
                if (rv) {
                    return wx2PyString(newval);
                }
                else {
                    Py_INCREF(Py_None);
                    return Py_None;
                }
                """,

            # Code for C++ --> Python calls. This is used when a C++ method
            # call needs to be reflected to a call to the overridden Python
            # method, so we need to translate between the real C++ signature
            # and the Python signature.
            virtualCatcherCode="""\
                // VirtualCatcherCode for wx.grid.GridCellEditor.EndEdit
                PyObject *result;
                result = sipCallMethod(0, sipMethod, "iiDN", row, col,
                                       const_cast<wxGrid *>(grid),sipType_wxGrid,NULL,
                                       new wxString(oldval),sipType_wxString,NULL);
                if (result == NULL) {
                    if (PyErr_Occurred())
                        PyErr_Print();
                    sipRes = false;
                }
                else if (result == Py_None) {
                    sipRes = false;
                }
                else {
                    sipRes = true;
                    *newval = Py2wxString(result);
                }
                Py_XDECREF(result);
                """ if pureVirtual else "",  # only used with the base class
        )

    c = module.find('wxGridCellEditor')
    c.addPrivateCopyCtor()
    c.find('~wxGridCellEditor').ignore(False)
    c.find('Clone').factory = True
    tools.fixRefCountedClass(c)
    c.find('TryActivate').ignore(
    )  # FIXME: remove this when the compilation issues with wxGridActivationResult is fixed

    c = module.find('wxGridCellActivatableEditor')
    c.ignore()  # FIXME: see above

    c = module.find('wxGridCellChoiceEditor')
    c.find('wxGridCellChoiceEditor').findOverload('count').ignore()

    for name in ITEMS:
        if 'Cell' in name and 'Editor' in name and name != 'wxGridCellActivatableEditor':
            fixEditorClass(name)

    module.addPyCode(
        "PyGridCellEditor = wx.deprecated(GridCellEditor, 'Use GridCellEditor instead.')"
    )

    #-----------------------------------------------------------------
    c = module.find('wxGridCellAttr')
    c.addPrivateCopyCtor()
    c.find('~wxGridCellAttr').ignore(False)
    c.find('Clone').factory = True
    tools.fixRefCountedClass(c)

    c.find('GetAlignment.hAlign').out = True
    c.find('GetAlignment.vAlign').out = True
    c.find('GetNonDefaultAlignment.hAlign').out = True
    c.find('GetNonDefaultAlignment.vAlign').out = True
    c.find('GetSize.num_rows').out = True
    c.find('GetSize.num_cols').out = True

    c.find('SetEditor.editor'
           ).transfer = True  # these are probably redundant now...
    c.find('SetRenderer.renderer').transfer = True

    #-----------------------------------------------------------------
    module.find('wxGridCellRendererPtr').piIgnored = True
    module.find('wxGridCellEditorPtr').piIgnored = True
    module.find('wxGridCellAttrPtr').piIgnored = True

    #-----------------------------------------------------------------
    # The instanceCode attribute is code that is used to make a default
    # instance of the class. We can't create them using the same class in
    # this case because they are abstract.

    c = module.find('wxGridCornerHeaderRenderer')
    c.instanceCode = 'sipCpp = new wxGridCornerHeaderRendererDefault;'

    c = module.find('wxGridRowHeaderRenderer')
    c.instanceCode = 'sipCpp = new wxGridRowHeaderRendererDefault;'

    c = module.find('wxGridColumnHeaderRenderer')
    c.instanceCode = 'sipCpp = new wxGridColumnHeaderRendererDefault;'

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

    c.find('SetAttr.attr').transfer = True
    c.find('SetRowAttr.attr').transfer = True
    c.find('SetColAttr.attr').transfer = True

    module.addPyCode(
        "PyGridCellAttrProvider = wx.deprecated(GridCellAttrProvider, 'Use GridCellAttrProvider instead.')"
    )

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

    c.find('SetAttr.attr').transfer = True
    c.find('SetRowAttr.attr').transfer = True
    c.find('SetColAttr.attr').transfer = True

    module.addPyCode(
        "PyGridTableBase = wx.deprecated(GridTableBase, 'Use GridTableBase instead.')"
    )

    # Make the GetValue methods easier to use from Python.  For example,
    # instead of needing to always return a string, the GetValue in the derived
    # class can return any type (as long as the renderer and editor knows how
    # to deal with it, and the value can be converted to a string for display).
    m = c.find('GetValue')
    m.type = 'PyObject*'
    m.cppSignature = 'wxString (int row, int col)'
    m.setCppCode("return wx2PyString(self->GetValue(row, col));")
    m.virtualCatcherCode = """\
        // virtualCatcherCode for GridTableBase.GetValue
        PyObject *result = sipCallMethod(&sipIsErr, sipMethod, "ii", row, col);
        if (result == NULL) {
            if (PyErr_Occurred())
                PyErr_Print();
            sipRes = "";
        }
        else if (result == Py_None) {
            sipRes = "";
        }
        else {
            if (!PyBytes_Check(result) && !PyUnicode_Check(result)) {
                PyObject* old = result;
                result = PyObject_Str(result);
                Py_DECREF(old);
            }
            sipRes = Py2wxString(result);
        }
        Py_XDECREF(result);
        """

    # SetValue is okay as-is...

    # Replace these virtuals in the base class with Python methods, they just
    # need to call GetValue or SetValue directly since they must already be
    # implemented in the derived Python class because they are pure virtual.
    c.addPyMethod('GetValueAsLong',
                  '(self, row, col)',
                  body="""\
            val = self.GetValue(row, col)
            try:
                return int(val)
            except ValueError:
                return 0
            """,
                  docsIgnored=True)

    c.addPyMethod('GetValueAsDouble',
                  '(self, row, col)',
                  body="""\
            val = self.GetValue(row, col)
            try:
                return float(val)
            except ValueError:
                return 0.0
            """,
                  docsIgnored=True)

    c.addPyMethod('GetValueAsBool',
                  '(self, row, col)',
                  body="""\
            val = self.GetValue(row, col)
            try:
                return bool(val)
            except ValueError:
                return False
            """,
                  docsIgnored=True)

    c.addPyMethod('SetValueAsLong',
                  '(self, row, col, value)',
                  body="self.SetValue(row, col, int(value))",
                  docsIgnored=True)

    c.addPyMethod('SetValueAsDouble',
                  '(self, row, col, value)',
                  body="self.SetValue(row, col, float(value))",
                  docsIgnored=True)

    c.addPyMethod('SetValueAsBool',
                  '(self, row, col, value)',
                  body="self.SetValue(row, col, bool(value))",
                  docsIgnored=True)

    # Should we add support for using generic PyObjects in the *AsCustom
    # methods? I don't think it is necessary due to the GetValue
    # modifications above, so for now, at least, let.s just ignore them.
    c.find('GetValueAsCustom').ignore()
    c.find('SetValueAsCustom').ignore()

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

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

    #-----------------------------------------------------------------
    c = module.find('wxGrid')
    tools.fixWindowClass(c, ignoreProtected=False)
    c.bases = ['wxScrolledCanvas']

    c.find('GetColLabelAlignment.horiz').out = True
    c.find('GetColLabelAlignment.vert').out = True
    c.find('GetRowLabelAlignment.horiz').out = True
    c.find('GetRowLabelAlignment.vert').out = True

    c.find('GetCellAlignment.horiz').out = True
    c.find('GetCellAlignment.vert').out = True
    c.find('GetDefaultCellAlignment.horiz').out = True
    c.find('GetDefaultCellAlignment.vert').out = True

    c.find('RegisterDataType.renderer').transfer = True
    c.find('RegisterDataType.editor').transfer = True

    c.find('SetRowAttr.attr').transfer = True
    c.find('SetColAttr.attr').transfer = True
    c.find('SetCellEditor.editor').transfer = True
    c.find('SetCellRenderer.renderer').transfer = True

    # This overload is deprecated, so don't generate code for it.
    c.find('SetCellValue').findOverload('wxString &val').ignore()

    c.find('SetDefaultEditor.editor').transfer = True
    c.find('SetDefaultRenderer.renderer').transfer = True

    for n in [
            'GetColGridLinePen', 'GetDefaultGridLinePen', 'GetRowGridLinePen'
    ]:
        c.find(n).isVirtual = True

    # The SetTable method can optionally pass ownership of the table
    # object to the grid, so we need to optionally update the
    # ownership of the Python proxy object to match.
    c.find('SetTable').pyName = '_SetTable'
    c.addPyMethod(
        'SetTable',
        '(self, table, takeOwnership=False, selmode=Grid.GridSelectCells)',
        piArgsString=
        '(self, table, takeOwnership=False, selmode=GridSelectCells)',
        doc="Set the Grid Table to be used by this grid.",
        body="""\
            val = self._SetTable(table, takeOwnership, selmode)
            if takeOwnership:
                import wx.siplib
                wx.siplib.transferto(table, self)
            return val
        """)

    # SIP will normally try to add support for overriding this method since
    # it is inherited from super classes, but in this case we want it to be
    # ignored (because IRL it is private in one of the intermediate classes)
    # so we'll tell SIP that it is private here instead.
    c.addItem(
        etgtools.WigCode("""\
        wxSize GetSizeAvailableForScrollTarget(const wxSize& size);
        """,
                         protection='private'))

    # Add a simpler set of names for the wxGridSelectionModes enum
    c.addPyCode("""\
        Grid.SelectCells = Grid.GridSelectCells
        Grid.SelectRows = Grid.GridSelectRows
        Grid.SelectColumns = Grid.GridSelectColumns
        Grid.SelectRowsOrColumns = Grid.GridSelectRowsOrColumns
        """)

    c.find('SetCellAlignment').findOverload('align').ignore()
    c.find('SetCellTextColour').overloads = []

    c.find('GetGridWindowOffset').findOverload('int &x').ignore()

    # Custom code to deal with the wxGridBlockCoordsVector return type of these
    # methods. It's a wxVector, which we'll just convert to a list.

    # TODO: There are a few of these now to we ought to either wrap wxVector, or add
    #       something in tweaker_tools to make adding code like this easier and more
    #       automated.
    code = """\
        wxPyThreadBlocker blocker;
        PyObject* result = PyList_New(0);
        wxGridBlockCoordsVector vector = self->{method}();
        for (size_t idx=0; idx < vector.size(); idx++) {{
            PyObject* obj;
            wxGridBlockCoords* item = new wxGridBlockCoords(vector[idx]);
            obj = wxPyConstructObject((void*)item, "wxGridBlockCoords", true);
            PyList_Append(result, obj);
            Py_DECREF(obj);
        }}
        return result;
        """
    c.find('GetSelectedRowBlocks').type = 'PyObject*'
    c.find('GetSelectedRowBlocks').setCppCode(
        code.format(method='GetSelectedRowBlocks'))
    c.find('GetSelectedColBlocks').type = 'PyObject*'
    c.find('GetSelectedColBlocks').setCppCode(
        code.format(method='GetSelectedColBlocks'))

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

    # context manager methods
    c.addPyMethod('__enter__', '(self)', 'return self')
    c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)',
                  'return False')

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

    for name in [
            'wxGridSizeEvent', 'wxGridRangeSelectEvent',
            'wxGridEditorCreatedEvent', 'wxGridEvent'
    ]:
        c = module.find(name)
        tools.fixEventClass(c)

    module.addPyCode("""\
        EVT_GRID_CELL_LEFT_CLICK = wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_CLICK )
        EVT_GRID_CELL_RIGHT_CLICK = wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_CLICK )
        EVT_GRID_CELL_LEFT_DCLICK = wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_DCLICK )
        EVT_GRID_CELL_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_DCLICK )
        EVT_GRID_LABEL_LEFT_CLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_CLICK )
        EVT_GRID_LABEL_RIGHT_CLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_CLICK )
        EVT_GRID_LABEL_LEFT_DCLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_DCLICK )
        EVT_GRID_LABEL_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_DCLICK )
        EVT_GRID_ROW_SIZE = wx.PyEventBinder( wxEVT_GRID_ROW_SIZE )
        EVT_GRID_COL_SIZE = wx.PyEventBinder( wxEVT_GRID_COL_SIZE )
        EVT_GRID_RANGE_SELECT = wx.PyEventBinder( wxEVT_GRID_RANGE_SELECT )
        EVT_GRID_CELL_CHANGING = wx.PyEventBinder( wxEVT_GRID_CELL_CHANGING )
        EVT_GRID_CELL_CHANGED = wx.PyEventBinder( wxEVT_GRID_CELL_CHANGED )
        EVT_GRID_SELECT_CELL = wx.PyEventBinder( wxEVT_GRID_SELECT_CELL )
        EVT_GRID_EDITOR_SHOWN = wx.PyEventBinder( wxEVT_GRID_EDITOR_SHOWN )
        EVT_GRID_EDITOR_HIDDEN = wx.PyEventBinder( wxEVT_GRID_EDITOR_HIDDEN )
        EVT_GRID_EDITOR_CREATED = wx.PyEventBinder( wxEVT_GRID_EDITOR_CREATED )
        EVT_GRID_CELL_BEGIN_DRAG = wx.PyEventBinder( wxEVT_GRID_CELL_BEGIN_DRAG )
        EVT_GRID_COL_MOVE = wx.PyEventBinder( wxEVT_GRID_COL_MOVE )
        EVT_GRID_COL_SORT = wx.PyEventBinder( wxEVT_GRID_COL_SORT )
        EVT_GRID_TABBING = wx.PyEventBinder( wxEVT_GRID_TABBING )

        # The same as above but with the ability to specify an identifier
        EVT_GRID_CMD_CELL_LEFT_CLICK =     wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_CLICK,    1 )
        EVT_GRID_CMD_CELL_RIGHT_CLICK =    wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_CLICK,   1 )
        EVT_GRID_CMD_CELL_LEFT_DCLICK =    wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_DCLICK,   1 )
        EVT_GRID_CMD_CELL_RIGHT_DCLICK =   wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_DCLICK,  1 )
        EVT_GRID_CMD_LABEL_LEFT_CLICK =    wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_CLICK,   1 )
        EVT_GRID_CMD_LABEL_RIGHT_CLICK =   wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_CLICK,  1 )
        EVT_GRID_CMD_LABEL_LEFT_DCLICK =   wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_DCLICK,  1 )
        EVT_GRID_CMD_LABEL_RIGHT_DCLICK =  wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_DCLICK, 1 )
        EVT_GRID_CMD_ROW_SIZE =            wx.PyEventBinder( wxEVT_GRID_ROW_SIZE,           1 )
        EVT_GRID_CMD_COL_SIZE =            wx.PyEventBinder( wxEVT_GRID_COL_SIZE,           1 )
        EVT_GRID_CMD_RANGE_SELECT =        wx.PyEventBinder( wxEVT_GRID_RANGE_SELECT,       1 )
        EVT_GRID_CMD_CELL_CHANGING =       wx.PyEventBinder( wxEVT_GRID_CELL_CHANGING,      1 )
        EVT_GRID_CMD_CELL_CHANGED =        wx.PyEventBinder( wxEVT_GRID_CELL_CHANGED,       1 )
        EVT_GRID_CMD_SELECT_CELL =         wx.PyEventBinder( wxEVT_GRID_SELECT_CELL,        1 )
        EVT_GRID_CMD_EDITOR_SHOWN =        wx.PyEventBinder( wxEVT_GRID_EDITOR_SHOWN,       1 )
        EVT_GRID_CMD_EDITOR_HIDDEN =       wx.PyEventBinder( wxEVT_GRID_EDITOR_HIDDEN,      1 )
        EVT_GRID_CMD_EDITOR_CREATED =      wx.PyEventBinder( wxEVT_GRID_EDITOR_CREATED,     1 )
        EVT_GRID_CMD_CELL_BEGIN_DRAG =     wx.PyEventBinder( wxEVT_GRID_CELL_BEGIN_DRAG,    1 )
        EVT_GRID_CMD_COL_MOVE =            wx.PyEventBinder( wxEVT_GRID_COL_MOVE,           1 )
        EVT_GRID_CMD_COL_SORT =            wx.PyEventBinder( wxEVT_GRID_COL_SORT,           1 )
        EVT_GRID_CMD_TABBING =             wx.PyEventBinder( wxEVT_GRID_TABBING,            1 )
        """)

    #-----------------------------------------------------------------
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #5
0
    def fixEditorClass(name):
        klass = module.find(name)
        assert isinstance(klass, etgtools.ClassDef)
        tools.fixRefCountedClass(klass)
        tools.addAutoProperties(klass)

        methods = [
            ('BeginEdit',
             "virtual void BeginEdit(int row, int col, wxGrid* grid);"),
            ('Clone', "virtual wxGridCellEditor* Clone() const /Factory/;"),
            ('Create',
             "virtual void Create(wxWindow* parent, wxWindowID id, wxEvtHandler* evtHandler);"
             ),
            #('EndEdit',    "virtual bool EndEdit(int row, int col, const wxGrid* grid, const wxString& oldval, wxString* newval);"),
            ('ApplyEdit',
             "virtual void ApplyEdit(int row, int col, wxGrid* grid);"),
            ('Reset', "virtual void Reset();"),
            ('GetValue', "virtual wxString GetValue() const;"),
        ]
        for method, code in methods:
            if not klass.findItem(method):
                klass.addItem(etgtools.WigCode(code))

        # Fix up EndEdit so it returns newval on success or None on failure
        pureVirtual = False
        if klass.findItem('EndEdit'):
            klass.find('EndEdit').ignore()
            pureVirtual = True

        # The Python version of EndEdit has a different signature than the
        # C++ version, so we need to take care of mapping between them so the
        # C++ compiler still recognizes this as a match for the virtual
        # method in the base class.
        klass.addCppMethod(
            'PyObject*',
            'EndEdit',
            '(int row, int col, const wxGrid* grid, const wxString& oldval)',
            cppSignature=
            'bool (int row, int col, const wxGrid* grid, const wxString& oldval, wxString* newval)',
            pyArgsString='(row, col, grid, oldval)',
            isVirtual=True,
            isPureVirtual=pureVirtual,
            doc="""\
                End editing the cell.

                This function must check if the current value of the editing cell
                is valid and different from the original value in its string
                form. If not then simply return None.  If it has changed then
                this method should save the new value so that ApplyEdit can
                apply it later and the string representation of the new value
                should be returned.

                Notice that this method shoiuld not modify the grid as the
                change could still be vetoed.
                """,

            # Code for Python --> C++ calls.  Make it return newval or None.
            body="""\
                bool rv;
                wxString newval;
                rv = self->EndEdit(row, col, grid, *oldval, &newval);
                if (rv) {
                    return wx2PyString(newval);
                }
                else {
                    Py_INCREF(Py_None);
                    return Py_None;
                }
                """,

            # Code for C++ --> Python calls. This is used when a C++ method
            # call needs to be reflected to a call to the overridden Python
            # method, so we need to translate between the real C++ signature
            # and the Python signature.
            virtualCatcherCode="""\
                // VirtualCatcherCode for wx.grid.GridCellEditor.EndEdit
                PyObject *result;
                result = sipCallMethod(0, sipMethod, "iiDN", row, col,
                                       const_cast<wxGrid *>(grid),sipType_wxGrid,NULL,
                                       new wxString(oldval),sipType_wxString,NULL);
                if (result == NULL) {
                    if (PyErr_Occurred())
                        PyErr_Print();
                    sipRes = false;
                }
                else if (result == Py_None) {
                    sipRes = false;
                }
                else {
                    sipRes = true;
                    *newval = Py2wxString(result);
                }
                Py_XDECREF(result);
                """ if pureVirtual else "",  # only used with the base class
        )
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.

    module.addGlobalStr('wxGridNameStr', module.items[0])
    module.addPyCode("""\
        GRID_VALUE_STRING =    "string"
        GRID_VALUE_BOOL =      "bool"
        GRID_VALUE_NUMBER =    "long"
        GRID_VALUE_FLOAT =     "double"
        GRID_VALUE_CHOICE =    "choice"
        GRID_VALUE_TEXT =      "string"
        GRID_VALUE_LONG =      "long"
        GRID_VALUE_CHOICEINT = "choiceint"
        GRID_VALUE_DATETIME =  "datetime"
        """)

    #-----------------------------------------------------------------
    c = module.find('wxGridCellCoords')
    assert isinstance(c, etgtools.ClassDef)
    tools.addAutoProperties(c)
    c.find('operator!').ignore()
    c.find('operator=').ignore()

    # Add a typemap for 2 element sequences
    c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxGridCellCoords')

    c.addCppMethod('PyObject*', 'Get', '()', """\
        wxPyThreadBlocker blocker;
        return sipBuildResult(0, "(ii)", self->GetRow(), self->GetCol());
        """,
        pyArgsString="() -> (row,col)",
        briefDoc="Return the row and col properties as a tuple.")

    tools.addGetIMMethodTemplate(module, c, ['Row', 'Col'])

    # Add sequence protocol methods and other goodies
    c.addPyMethod('__str__', '(self)',             'return str(self.Get())')
    c.addPyMethod('__repr__', '(self)',            'return "GridCellCoords"+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 (GridCellCoords, self.Get())')
    c.addPyMethod('__getitem__', '(self, idx)',    'return self.Get()[idx]')
    c.addPyMethod('__setitem__', '(self, idx, val)',
                  """\
                  if idx == 0: self.Row = val
                  elif idx == 1: self.Col = val
                  else: raise IndexError
                  """)
    c.addPyCode('GridCellCoords.__safe_for_unpickling__ = True')

    module.addItem(
        tools.wxArrayWrapperTemplate('wxGridCellCoordsArray', 'wxGridCellCoords', module,
                                     getItemCopy=True))


    #-----------------------------------------------------------------
    c = module.find('wxGridSizesInfo')
    c.find('m_customSizes').ignore()   # TODO: Add support for wxUnsignedToIntHashMap??


    #-----------------------------------------------------------------
    def fixRendererClass(name):
        klass = module.find(name)
        assert isinstance(klass, etgtools.ClassDef)
        tools.fixRefCountedClass(klass)
        tools.addAutoProperties(klass)

        methods = [
            ('Clone',       "virtual wxGridCellRenderer* Clone() const /Factory/;"),
            ('Draw',        "virtual void Draw(wxGrid& grid, wxGridCellAttr& attr, wxDC& dc, "
                            "    const wxRect& rect, int row, int col, bool isSelected);"),
            ('GetBestSize', "virtual wxSize GetBestSize(wxGrid& grid, wxGridCellAttr& attr, "
                            "    wxDC& dc, int row, int col);"),
            ]
        for method, code in methods:
            if not klass.findItem(method):
                klass.addItem(etgtools.WigCode(code))


    c = module.find('wxGridCellRenderer')
    c.addPrivateCopyCtor()
    c.find('~wxGridCellRenderer').ignore(False)
    c.find('Clone').factory = True
    tools.fixRefCountedClass(c)

    for name in ITEMS:
        if 'Cell' in name and 'Renderer' in name:
            fixRendererClass(name)

    module.addPyCode("PyGridCellRenderer = wx.deprecated(GridCellRenderer, 'Use GridCellRenderer instead.')")


    #-----------------------------------------------------------------
    def fixEditorClass(name):
        klass = module.find(name)
        assert isinstance(klass, etgtools.ClassDef)
        tools.fixRefCountedClass(klass)
        tools.addAutoProperties(klass)

        methods = [
            ('BeginEdit',  "virtual void BeginEdit(int row, int col, wxGrid* grid);"),
            ('Clone',      "virtual wxGridCellEditor* Clone() const /Factory/;"),
            ('Create',     "virtual void Create(wxWindow* parent, wxWindowID id, wxEvtHandler* evtHandler);"),
            #('EndEdit',    "virtual bool EndEdit(int row, int col, const wxGrid* grid, const wxString& oldval, wxString* newval);"),
            ('ApplyEdit',  "virtual void ApplyEdit(int row, int col, wxGrid* grid);"),
            ('Reset',      "virtual void Reset();"),
            ('GetValue',   "virtual wxString GetValue() const;"),
            ]
        for method, code in methods:
            if not klass.findItem(method):
                klass.addItem(etgtools.WigCode(code))


        # Fix up EndEdit so it returns newval on success or None on failure
        pureVirtual = False
        if klass.findItem('EndEdit'):
            klass.find('EndEdit').ignore()
            pureVirtual = True

        # The Python version of EndEdit has a different signature than the
        # C++ version, so we need to take care of mapping between them so the
        # C++ compiler still recognizes this as a match for the virtual
        # method in the base class.
        klass.addCppMethod('PyObject*', 'EndEdit', '(int row, int col, const wxGrid* grid, const wxString& oldval)',
            cppSignature='bool (int row, int col, const wxGrid* grid, const wxString& oldval, wxString* newval)',
            pyArgsString='(row, col, grid, oldval)',
            isVirtual=True,
            isPureVirtual=pureVirtual,
            doc="""\
                End editing the cell.

                This function must check if the current value of the editing cell
                is valid and different from the original value in its string
                form. If not then simply return None.  If it has changed then
                this method should save the new value so that ApplyEdit can
                apply it later and the string representation of the new value
                should be returned.

                Notice that this method shoiuld not modify the grid as the
                change could still be vetoed.
                """,

            # Code for Python --> C++ calls.  Make it return newval or None.
            body="""\
                bool rv;
                wxString newval;
                rv = self->EndEdit(row, col, grid, *oldval, &newval);
                if (rv) {
                    return wx2PyString(newval);
                }
                else {
                    Py_INCREF(Py_None);
                    return Py_None;
                }
                """,

            # Code for C++ --> Python calls. This is used when a C++ method
            # call needs to be reflected to a call to the overridden Python
            # method, so we need to translate between the real C++ signature
            # and the Python signature.
            virtualCatcherCode="""\
                // VirtualCatcherCode for wx.grid.GridCellEditor.EndEdit
                PyObject *result;
                result = sipCallMethod(0, sipMethod, "iiDN", row, col,
                                       const_cast<wxGrid *>(grid),sipType_wxGrid,NULL,
                                       new wxString(oldval),sipType_wxString,NULL);
                if (result == Py_None) {
                    sipRes = false;
                }
                else {
                    sipRes = true;
                    *newval = Py2wxString(result);
                }
                Py_DECREF(result);
                """  if pureVirtual else "",  # only used with the base class
            )


    c = module.find('wxGridCellEditor')
    c.addPrivateCopyCtor()
    c.find('~wxGridCellEditor').ignore(False)
    c.find('Clone').factory = True
    tools.fixRefCountedClass(c)

    c = module.find('wxGridCellChoiceEditor')
    c.find('wxGridCellChoiceEditor').findOverload('count').ignore()

    for name in ITEMS:
        if 'Cell' in name and 'Editor' in name:
            fixEditorClass(name)

    module.addPyCode("PyGridCellEditor = wx.deprecated(GridCellEditor, 'Use GridCellEditor instead.')")

    #-----------------------------------------------------------------
    c = module.find('wxGridCellAttr')
    c.addPrivateCopyCtor()
    c.find('~wxGridCellAttr').ignore(False)
    c.find('Clone').factory = True
    tools.fixRefCountedClass(c)

    c.find('GetAlignment.hAlign').out = True
    c.find('GetAlignment.vAlign').out = True
    c.find('GetNonDefaultAlignment.hAlign').out = True
    c.find('GetNonDefaultAlignment.vAlign').out = True
    c.find('GetSize.num_rows').out = True
    c.find('GetSize.num_cols').out = True

    c.find('SetEditor.editor').transfer = True  # these are probably redundant now...
    c.find('SetRenderer.renderer').transfer = True


    #-----------------------------------------------------------------
    # The instanceCode attribute is code that is used to make a default
    # instance of the class. We can't create them using the same class in
    # this case because they are abstract.

    c = module.find('wxGridCornerHeaderRenderer')
    c.instanceCode = 'sipCpp = new wxGridCornerHeaderRendererDefault;'

    c = module.find('wxGridRowHeaderRenderer')
    c.instanceCode = 'sipCpp = new wxGridRowHeaderRendererDefault;'

    c = module.find('wxGridColumnHeaderRenderer')
    c.instanceCode = 'sipCpp = new wxGridColumnHeaderRendererDefault;'



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

    c.find('SetAttr.attr').transfer = True
    c.find('SetRowAttr.attr').transfer = True
    c.find('SetColAttr.attr').transfer = True

    module.addPyCode("PyGridCellAttrProvider = wx.deprecated(GridCellAttrProvider, 'Use GridCellAttrProvider instead.')")


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

    c.find('SetAttr.attr').transfer = True
    c.find('SetRowAttr.attr').transfer = True
    c.find('SetColAttr.attr').transfer = True

    module.addPyCode("PyGridTableBase = wx.deprecated(GridTableBase, 'Use GridTableBase instead.')")


    # Make the GetValue methods easier to use from Python.  For example,
    # instead of needing to always return a string, the GetValue in the derived
    # class can return any type (as long as the renderer and editor knows how
    # to deal with it, and the value can be converted to a string for display).
    m = c.find('GetValue')
    m.type = 'PyObject*'
    m.cppSignature = 'wxString (int row, int col)'
    m.setCppCode("return wx2PyString(self->GetValue(row, col));")
    m.virtualCatcherCode = """\
        // virtualCatcherCode for GridTableBase.GetValue
        PyObject *result = sipCallMethod(&sipIsErr, sipMethod, "ii", row, col);
        if (result == Py_None) {
            sipRes = "";
        }
        else {
            if (!PyBytes_Check(result) && !PyUnicode_Check(result)) {
                PyObject* old = result;
                result = PyObject_Str(result);
                Py_DECREF(old);
            }
            sipRes = Py2wxString(result);
        }
        Py_XDECREF(result);
        """

    # SetValue is okay as-is...


    # Replace these virtuals in the base class with Python methods, they just
    # need to call GetValue or SetValue directly since they must already be
    # implemented in the derived Python class because they are pure virtual.
    c.addPyMethod('GetValueAsLong', '(self, row, col)',
        body="""\
            val = self.GetValue(row, col)
            try:
                return int(val)
            except ValueError:
                return 0
            """, docsIgnored=True)

    c.addPyMethod('GetValueAsDouble', '(self, row, col)',
        body="""\
            val = self.GetValue(row, col)
            try:
                return float(val)
            except ValueError:
                return 0.0
            """, docsIgnored=True)

    c.addPyMethod('GetValueAsBool', '(self, row, col)',
        body="""\
            val = self.GetValue(row, col)
            try:
                return bool(val)
            except ValueError:
                return False
            """, docsIgnored=True)

    c.addPyMethod('SetValueAsLong', '(self, row, col, value)',
        body="self.SetValue(row, col, int(value))", docsIgnored=True)

    c.addPyMethod('SetValueAsDouble', '(self, row, col, value)',
        body="self.SetValue(row, col, float(value))", docsIgnored=True)

    c.addPyMethod('SetValueAsBool', '(self, row, col, value)',
        body="self.SetValue(row, col, bool(value))", docsIgnored=True)


    # Should we add support for using generic PyObjects in the *AsCustom
    # methods? I don't think it is necessary due to the GetValue
    # modifications above, so for now, at least, let.s just ignore them.
    c.find('GetValueAsCustom').ignore()
    c.find('SetValueAsCustom').ignore()
    


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


    #-----------------------------------------------------------------
    c = module.find('wxGrid')
    tools.fixWindowClass(c, ignoreProtected=False)
    c.bases = ['wxScrolledWindow']

    c.find('GetColLabelAlignment.horiz').out = True
    c.find('GetColLabelAlignment.vert').out = True
    c.find('GetRowLabelAlignment.horiz').out = True
    c.find('GetRowLabelAlignment.vert').out = True

    c.find('GetCellAlignment.horiz').out = True
    c.find('GetCellAlignment.vert').out = True
    c.find('GetDefaultCellAlignment.horiz').out = True
    c.find('GetDefaultCellAlignment.vert').out = True


    c.find('RegisterDataType.renderer').transfer = True
    c.find('RegisterDataType.editor').transfer = True

    c.find('SetRowAttr.attr').transfer = True
    c.find('SetColAttr.attr').transfer = True
    c.find('SetCellEditor.editor').transfer = True
    c.find('SetCellRenderer.renderer').transfer = True

    # This overload is deprecated, so don't generate code for it.
    c.find('SetCellValue').findOverload('wxString &val').ignore()

    c.find('SetDefaultEditor.editor').transfer = True
    c.find('SetDefaultRenderer.renderer').transfer = True

    for n in ['GetColGridLinePen', 'GetDefaultGridLinePen', 'GetRowGridLinePen']:
        c.find(n).isVirtual = True


    # The SetTable method can optionally pass ownership of the table
    # object to the grid, so we need to optionally update the
    # ownership of the Python proxy object to match.
    c.find('SetTable').pyName = '_SetTable'
    c.addPyMethod('SetTable', '(self, table, takeOwnership=False, selmode=Grid.SelectCells)',
        piArgsString='(self, table, takeOwnership=False, selmode=SelectCells)',
        doc="Set the Grid Table to be used by this grid.",
        body="""\
            val = self._SetTable(table, takeOwnership, selmode)
            if takeOwnership:
                import wx.siplib
                wx.siplib.transferto(table, self)
            return val
        """)


    # SIP will normally try to add support for overriding this method since
    # it is inherited from super classes, but in this case we want it to be
    # ignored (because IRL it is private in one of the intermediate classes)
    # so we'll tell SIP that it is private here instead.
    c.addItem(etgtools.WigCode("""\
        wxSize GetSizeAvailableForScrollTarget(const wxSize& size);
        """, protection='private'))


    # Rename some nested enum values
    c.find('wxGridSelectionModes.wxGridSelectCells').pyName = 'SelectCells'
    c.find('wxGridSelectionModes.wxGridSelectRows').pyName = 'SelectRows'
    c.find('wxGridSelectionModes.wxGridSelectColumns').pyName = 'SelectColumns'
    c.find('wxGridSelectionModes.wxGridSelectRowsOrColumns').pyName = 'SelectRowsOrColumns'

    # But also keep aliases for the old names, just in case
    c.addPyCode("""\
        Grid.wxGridSelectCells = Grid.SelectCells
        Grid.wxGridSelectRows = Grid.SelectRows
        Grid.wxGridSelectColumns = Grid.SelectColumns
        Grid.wxGridSelectRowsOrColumns = Grid.SelectRowsOrColumns
        """)

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

    # context manager methods
    c.addPyMethod('__enter__', '(self)', 'return self')
    c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)', 'return False')


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

    for name in ['wxGridSizeEvent',
                 'wxGridRangeSelectEvent',
                 'wxGridEditorCreatedEvent',
                 'wxGridEvent'
                 ]:
        c = module.find(name)
        tools.fixEventClass(c)


    c.addPyCode("""\
        EVT_GRID_CELL_LEFT_CLICK = wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_CLICK )
        EVT_GRID_CELL_RIGHT_CLICK = wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_CLICK )
        EVT_GRID_CELL_LEFT_DCLICK = wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_DCLICK )
        EVT_GRID_CELL_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_DCLICK )
        EVT_GRID_LABEL_LEFT_CLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_CLICK )
        EVT_GRID_LABEL_RIGHT_CLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_CLICK )
        EVT_GRID_LABEL_LEFT_DCLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_DCLICK )
        EVT_GRID_LABEL_RIGHT_DCLICK = wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_DCLICK )
        EVT_GRID_ROW_SIZE = wx.PyEventBinder( wxEVT_GRID_ROW_SIZE )
        EVT_GRID_COL_SIZE = wx.PyEventBinder( wxEVT_GRID_COL_SIZE )
        EVT_GRID_RANGE_SELECT = wx.PyEventBinder( wxEVT_GRID_RANGE_SELECT )
        EVT_GRID_CELL_CHANGING = wx.PyEventBinder( wxEVT_GRID_CELL_CHANGING )
        EVT_GRID_CELL_CHANGED = wx.PyEventBinder( wxEVT_GRID_CELL_CHANGED )
        EVT_GRID_SELECT_CELL = wx.PyEventBinder( wxEVT_GRID_SELECT_CELL )
        EVT_GRID_EDITOR_SHOWN = wx.PyEventBinder( wxEVT_GRID_EDITOR_SHOWN )
        EVT_GRID_EDITOR_HIDDEN = wx.PyEventBinder( wxEVT_GRID_EDITOR_HIDDEN )
        EVT_GRID_EDITOR_CREATED = wx.PyEventBinder( wxEVT_GRID_EDITOR_CREATED )
        EVT_GRID_CELL_BEGIN_DRAG = wx.PyEventBinder( wxEVT_GRID_CELL_BEGIN_DRAG )
        EVT_GRID_COL_MOVE = wx.PyEventBinder( wxEVT_GRID_COL_MOVE )
        EVT_GRID_COL_SORT = wx.PyEventBinder( wxEVT_GRID_COL_SORT )
        EVT_GRID_TABBING = wx.PyEventBinder( wxEVT_GRID_TABBING )

        # The same as above but with the ability to specify an identifier
        EVT_GRID_CMD_CELL_LEFT_CLICK =     wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_CLICK,    1 )
        EVT_GRID_CMD_CELL_RIGHT_CLICK =    wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_CLICK,   1 )
        EVT_GRID_CMD_CELL_LEFT_DCLICK =    wx.PyEventBinder( wxEVT_GRID_CELL_LEFT_DCLICK,   1 )
        EVT_GRID_CMD_CELL_RIGHT_DCLICK =   wx.PyEventBinder( wxEVT_GRID_CELL_RIGHT_DCLICK,  1 )
        EVT_GRID_CMD_LABEL_LEFT_CLICK =    wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_CLICK,   1 )
        EVT_GRID_CMD_LABEL_RIGHT_CLICK =   wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_CLICK,  1 )
        EVT_GRID_CMD_LABEL_LEFT_DCLICK =   wx.PyEventBinder( wxEVT_GRID_LABEL_LEFT_DCLICK,  1 )
        EVT_GRID_CMD_LABEL_RIGHT_DCLICK =  wx.PyEventBinder( wxEVT_GRID_LABEL_RIGHT_DCLICK, 1 )
        EVT_GRID_CMD_ROW_SIZE =            wx.PyEventBinder( wxEVT_GRID_ROW_SIZE,           1 )
        EVT_GRID_CMD_COL_SIZE =            wx.PyEventBinder( wxEVT_GRID_COL_SIZE,           1 )
        EVT_GRID_CMD_RANGE_SELECT =        wx.PyEventBinder( wxEVT_GRID_RANGE_SELECT,       1 )
        EVT_GRID_CMD_CELL_CHANGING =       wx.PyEventBinder( wxEVT_GRID_CELL_CHANGING,      1 )
        EVT_GRID_CMD_CELL_CHANGED =        wx.PyEventBinder( wxEVT_GRID_CELL_CHANGED,       1 )
        EVT_GRID_CMD_SELECT_CELL =         wx.PyEventBinder( wxEVT_GRID_SELECT_CELL,        1 )
        EVT_GRID_CMD_EDITOR_SHOWN =        wx.PyEventBinder( wxEVT_GRID_EDITOR_SHOWN,       1 )
        EVT_GRID_CMD_EDITOR_HIDDEN =       wx.PyEventBinder( wxEVT_GRID_EDITOR_HIDDEN,      1 )
        EVT_GRID_CMD_EDITOR_CREATED =      wx.PyEventBinder( wxEVT_GRID_EDITOR_CREATED,     1 )
        EVT_GRID_CMD_CELL_BEGIN_DRAG =     wx.PyEventBinder( wxEVT_GRID_CELL_BEGIN_DRAG,    1 )
        EVT_GRID_CMD_COL_MOVE =            wx.PyEventBinder( wxEVT_GRID_COL_MOVE,           1 )
        EVT_GRID_CMD_COL_SORT =            wx.PyEventBinder( wxEVT_GRID_COL_SORT,           1 )
        EVT_GRID_CMD_TABBING =             wx.PyEventBinder( wxEVT_GRID_TABBING,            1 )
        """)

    #-----------------------------------------------------------------
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Exemple #7
0
    def fixEditorClass(name):
        klass = module.find(name)
        assert isinstance(klass, etgtools.ClassDef)
        tools.fixRefCountedClass(klass)
        tools.addAutoProperties(klass)

        methods = [
            ('BeginEdit',  "virtual void BeginEdit(int row, int col, wxGrid* grid);"),
            ('Clone',      "virtual wxGridCellEditor* Clone() const /Factory/;"),
            ('Create',     "virtual void Create(wxWindow* parent, wxWindowID id, wxEvtHandler* evtHandler);"),
            #('EndEdit',    "virtual bool EndEdit(int row, int col, const wxGrid* grid, const wxString& oldval, wxString* newval);"),
            ('ApplyEdit',  "virtual void ApplyEdit(int row, int col, wxGrid* grid);"),
            ('Reset',      "virtual void Reset();"),
            ('GetValue',   "virtual wxString GetValue() const;"),
            ]
        for method, code in methods:
            if not klass.findItem(method):
                klass.addItem(etgtools.WigCode(code))


        # Fix up EndEdit so it returns newval on success or None on failure
        pureVirtual = False
        if klass.findItem('EndEdit'):
            klass.find('EndEdit').ignore()
            pureVirtual = True

        # The Python version of EndEdit has a different signature than the
        # C++ version, so we need to take care of mapping between them so the
        # C++ compiler still recognizes this as a match for the virtual
        # method in the base class.
        klass.addCppMethod('PyObject*', 'EndEdit', '(int row, int col, const wxGrid* grid, const wxString& oldval)',
            cppSignature='bool (int row, int col, const wxGrid* grid, const wxString& oldval, wxString* newval)',
            pyArgsString='(row, col, grid, oldval)',
            isVirtual=True,
            isPureVirtual=pureVirtual,
            doc="""\
                End editing the cell.

                This function must check if the current value of the editing cell
                is valid and different from the original value in its string
                form. If not then simply return None.  If it has changed then
                this method should save the new value so that ApplyEdit can
                apply it later and the string representation of the new value
                should be returned.

                Notice that this method shoiuld not modify the grid as the
                change could still be vetoed.
                """,

            # Code for Python --> C++ calls.  Make it return newval or None.
            body="""\
                bool rv;
                wxString newval;
                rv = self->EndEdit(row, col, grid, *oldval, &newval);
                if (rv) {
                    return wx2PyString(newval);
                }
                else {
                    Py_INCREF(Py_None);
                    return Py_None;
                }
                """,

            # Code for C++ --> Python calls. This is used when a C++ method
            # call needs to be reflected to a call to the overridden Python
            # method, so we need to translate between the real C++ signature
            # and the Python signature.
            virtualCatcherCode="""\
                // VirtualCatcherCode for wx.grid.GridCellEditor.EndEdit
                PyObject *result;
                result = sipCallMethod(0, sipMethod, "iiDN", row, col,
                                       const_cast<wxGrid *>(grid),sipType_wxGrid,NULL,
                                       new wxString(oldval),sipType_wxString,NULL);
                if (result == Py_None) {
                    sipRes = false;
                }
                else {
                    sipRes = true;
                    *newval = Py2wxString(result);
                }
                Py_DECREF(result);
                """  if pureVirtual else "",  # only used with the base class
            )
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/dataview.h>")

    for item in module.allItems():
        if hasattr(item, 'type') and 'wxVariant' in item.type:
            item.type = item.type.replace('wxVariant', 'wxDVCVariant')


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

    c.addCppMethod('int', '__nonzero__', '()', """\
        return self->IsOk();
        """)
    c.addCppMethod('long', '__hash__', '()', """\
        return (long)self->GetID();
        """)
    c.addCppMethod('bool', '__eq__', '(wxDataViewItem* other)',
                   "return other ? (self->GetID() == other->GetID()) : false;")
    c.addCppMethod('bool', '__ne__', '(wxDataViewItem* other)',
                   "return other ? (self->GetID() != other->GetID()) : true;")
    c.addAutoProperties()


    module.addItem(
        tools.wxArrayWrapperTemplate('wxDataViewItemArray', 'wxDataViewItem', module))
    module.addPyCode("NullDataViewItem = DataViewItem()")


    #-----------------------------------------------------------------
    c = module.find('wxDataViewModel')
    c.addAutoProperties()
    tools.fixRefCountedClass(c)

    c.find('~wxDataViewModel').ignore(False)

    c.find('AddNotifier.notifier').transfer = True
    c.find('RemoveNotifier.notifier').transferBack = True

    # Change the GetValue method to return the value instead of passing it
    # through a parameter for modification.
    c.find('GetValue.variant').out = True


    # The DataViewItemObjectMapper class helps map from data items to Python
    # objects, and is used as a base class of PyDataViewModel as a
    # convenience.
    module.addPyClass('DataViewItemObjectMapper', ['object'],
        doc="""\
            This class provides a mechanism for mapping between Python objects and the
            :class:`DataViewItem` objects used by the :class:`DataViewModel` for tracking the items in
            the view. The ID used for the item is the id() of the Python object. Use
            :meth:`ObjectToItem` to create a :class:`DataViewItem` using a Python object as its ID,
            and use :meth:`ItemToObject` to fetch that Python object again later for a given
            :class:`DataViewItem`.

            By default a regular dictionary is used to implement the ID to object
            mapping. Optionally a WeakValueDictionary can be useful when there will be
            a high turnover of objects and mantaining an extra reference to the
            objects would be unwise.  If weak references are used then the objects
            associated with data items must be weak-referenceable.  (Things like
            stock lists and dictionaries are not.)  See :meth:`UseWeakRefs`.

            This class is used in :class:`PyDataViewModel` as a mixin for convenience.
            """,
        items=[
            PyFunctionDef('__init__', '(self)',
                body="""\
                    self.mapper = dict()
                    self.usingWeakRefs = False
                    """),

            PyFunctionDef('ObjectToItem', '(self, obj)',
                doc="Create a :class:`DataViewItem` for the object, and remember the ID-->obj mapping.",
                body="""\
                    import sys
                    oid = id(obj)
                    while oid > sys.maxsize:
                        # risk of conflict here... May need some more thought.
                        oid -= sys.maxsize
                    self.mapper[oid] = obj
                    return DataViewItem(oid)
                    """),

            PyFunctionDef('ItemToObject', '(self, item)',
                doc="Retrieve the object that was used to create an item.",
                body="""\
                    oid = int(item.GetID())
                    return self.mapper[oid]
                    """),

            PyFunctionDef('UseWeakRefs', '(self, flag)',
                doc="""\
                    Switch to or from using a weak value dictionary for keeping the ID to
                    object map.""",
                body="""\
                    if flag == self.usingWeakRefs:
                        return
                    if flag:
                        import weakref
                        newmap = weakref.WeakValueDictionary()
                    else:
                        newmap = dict()
                    newmap.update(self.mapper)
                    self.mapper = newmap
                    self.usingWeakRefs = flag
                    """),
            ])

    module.addPyClass('PyDataViewModel', ['DataViewModel', 'DataViewItemObjectMapper'],
        doc="A convenience class that is a :class:`DataViewModel` combined with an object mapper.",
        items=[
            PyFunctionDef('__init__', '(self)',
                body="""\
                    DataViewModel.__init__(self)
                    DataViewItemObjectMapper.__init__(self)
                    """)
            ])


    #-----------------------------------------------------------------
    c = module.find('wxDataViewListModel')
    c.addAutoProperties()
    tools.fixRefCountedClass(c)

    # Change the GetValueByRow method to return the value instead of passing
    # it through a parameter for modification.
    c.find('GetValueByRow.variant').out = True

    # declare implementations for base class virtuals
    c.addItem(etgtools.WigCode("""\
        virtual wxDataViewItem GetParent( const wxDataViewItem &item ) const;
        virtual bool IsContainer( const wxDataViewItem &item ) const;
        virtual void GetValue( wxDVCVariant &variant /Out/, const wxDataViewItem &item, unsigned int col ) const [void ( wxDVCVariant &variant, const wxDataViewItem &item, unsigned int col )];
        virtual bool SetValue( const wxDVCVariant &variant, const wxDataViewItem &item, unsigned int col );
        virtual bool GetAttr(const wxDataViewItem &item, unsigned int col, wxDataViewItemAttr &attr) const;
        virtual bool IsEnabled(const wxDataViewItem &item, unsigned int col) const;
        virtual bool IsListModel() const;
        """))


    # Add some of the pure virtuals since there are undocumented
    # implementations of them in these classes. The others will need to be
    # implemented in Python classes derived from these.
    for name in ['wxDataViewIndexListModel', 'wxDataViewVirtualListModel']:
        c = module.find(name)

        c.addItem(etgtools.WigCode("""\
            virtual unsigned int GetRow(const wxDataViewItem& item) const;
            virtual unsigned int GetCount() const;
            virtual unsigned int GetChildren( const wxDataViewItem &item, wxDataViewItemArray &children ) const;
            """))


    # compatibility aliases
    module.addPyCode("""\
        PyDataViewIndexListModel = wx.deprecated(DataViewIndexListModel)
        PyDataViewVirtualListModel = wx.deprecated(DataViewVirtualListModel)
        """)


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

    def _fixupBoolGetters(method, sig):
        method.type = 'void'
        method.find('value').out = True
        method.find('value').type = 'wxDVCVariant&'
        method.cppSignature = sig

    def _fixupTypeParam(klass):
        param = klass.findItem('{}.varianttype'.format(klass.name))
        if param and param.default == 'GetDefaultType()':
            param.default = '{}::GetDefaultType()'.format(klass.name)

    c = module.find('wxDataViewRenderer')
    c.addPrivateCopyCtor()
    c.abstract = True
    c.find('GetView').ignore(False)

    # TODO: This is only available when wxUSE_ACCESSIBILITY is set to 1
    c.find('GetAccessibleDescription').ignore()

    c.addAutoProperties()

    # Change variant getters to return the value
    for name, sig in [
        ('GetValue',               'bool (wxVariant& value)'),
        ('GetValueFromEditorCtrl', 'bool (wxWindow * editor, wxVariant& value)'),
        ]:
        _fixupBoolGetters(c.find(name), sig)

    m = c.find('SetValue')
    m.find('value').type = 'const wxDVCVariant&'
    m.cppSignature = 'bool (const wxVariant& value)'

    m = c.find('CreateEditorCtrl')
    m.cppSignature = 'wxWindow* (wxWindow * parent, wxRect labelRect, const wxVariant& value)'

    c.find('GetView').ignore(False)



    c = module.find('wxDataViewCustomRenderer')
    _fixupTypeParam(c)
    m = c.find('GetValueFromEditorCtrl')
    _fixupBoolGetters(m, 'bool (wxWindow * editor, wxVariant& value)')

    # Change the virtual method handler code to follow the same pattern as the
    # tweaked public API, namely that the value is the return value instead of
    # an out parameter.
    m.virtualCatcherCode = """\
        PyObject *sipResObj = sipCallMethod(&sipIsErr, sipMethod, "D", editor, sipType_wxWindow, NULL);
        if (sipResObj == Py_None) {
            sipRes = false;
        } else {
            sipRes = true;
            sipParseResult(&sipIsErr, sipMethod, sipResObj, "H5", sipType_wxDVCVariant, &value);
        }
        """

    c.find('GetTextExtent').ignore(False)

    m = c.find('CreateEditorCtrl')
    m.cppSignature = 'wxWindow* (wxWindow * parent, wxRect labelRect, const wxVariant& value)'


    module.addPyCode("""\
        PyDataViewCustomRenderer = wx.deprecated(DataViewCustomRenderer,
                                                 "Use DataViewCustomRenderer instead")""")


    # Add the pure virtuals since there are undocumented implementations of
    # them in all these classes
    for name in [ 'wxDataViewTextRenderer',
                  'wxDataViewIconTextRenderer',
                  'wxDataViewProgressRenderer',
                  'wxDataViewSpinRenderer',
                  'wxDataViewToggleRenderer',
                  'wxDataViewChoiceRenderer',
                  #'wxDataViewChoiceByIndexRenderer',
                  'wxDataViewDateRenderer',
                  'wxDataViewBitmapRenderer',
                  ]:
        c = module.find(name)
        c.addAutoProperties()
        _fixupTypeParam(c)

        c.addItem(etgtools.WigCode("""\
            virtual bool SetValue( const wxDVCVariant &value ) [bool (const wxVariant& value)];
            virtual void GetValue( wxDVCVariant &value /Out/ ) const [bool (wxVariant& value)];
            %Property(name=Value, get=GetValue, set=SetValue)
            """, protection='public'))

    # The SpinRenderer has a few additional pure virtuals that need to be declared
    # since it derives from DataViewCustomRenderer
    c = module.find('wxDataViewSpinRenderer')
    c.addItem(etgtools.WigCode("""\
        virtual wxSize GetSize() const;
        virtual bool Render(wxRect cell, wxDC* dc, int state);
        """, protection='public'))


    #-----------------------------------------------------------------
    c = module.find('wxDataViewColumn')
    for m in c.find('wxDataViewColumn').all():
        m.find('renderer').transfer = True

    # declare the virtuals from wxSettableHeaderColumn
    c.addItem(etgtools.WigCode("""\
        virtual void SetTitle(const wxString& title);
        virtual wxString GetTitle() const;
        virtual void SetBitmap(const wxBitmap& bitmap);
        virtual wxBitmap GetBitmap() const;
        virtual void SetWidth(int width);
        virtual int GetWidth() const;
        virtual void SetMinWidth(int minWidth);
        virtual int GetMinWidth() const;
        virtual void SetAlignment(wxAlignment align);
        virtual wxAlignment GetAlignment() const;
        virtual void SetFlags(int flags);
        virtual int GetFlags() const;
        virtual bool IsSortKey() const;
        virtual void SetSortOrder(bool ascending);
        virtual bool IsSortOrderAscending() const;

        virtual void SetResizeable(bool resizable);
        virtual void SetSortable(bool sortable);
        virtual void SetReorderable(bool reorderable);
        virtual void SetHidden(bool hidden);
        """))

    c.addAutoProperties()
    c.addProperty('Title', 'GetTitle', 'SetTitle')
    c.addProperty('Bitmap', 'GetBitmap', 'SetBitmap')
    c.addProperty('Width', 'GetWidth', 'SetWidth')
    c.addProperty('MinWidth', 'GetMinWidth', 'SetMinWidth')
    c.addProperty('Alignment', 'GetAlignment', 'SetAlignment')
    c.addProperty('Flags', 'GetFlags', 'SetFlags')
    c.addProperty('SortOrder', 'IsSortOrderAscending', 'SetSortOrder')



    #-----------------------------------------------------------------
    c = module.find('wxDataViewCtrl')
    tools.fixWindowClass(c)
    module.addGlobalStr('wxDataViewCtrlNameStr', c)

    c.find('AssociateModel.model').transfer = True
    c.find('AssociateModel').pyName = '_AssociateModel'
    c.addPyMethod('AssociateModel', '(self, model)',
        doc="""\
            Associates a :class:`DataViewModel` with the control.
            Ownership of the model object is passed to C++, however it
            is reference counted so it can be shared with other views.
            """,
        body="""\
            import wx.siplib
            wasPyOwned = wx.siplib.ispyowned(model)
            self._AssociateModel(model)
            # Ownership of the python object has just been transferred to
            # C++, so DecRef the C++ instance associated with this python
            # reference.
            if wasPyOwned:
                model.DecRef()
            """)

    c.find('PrependColumn.col').transfer = True
    c.find('InsertColumn.col').transfer = True
    c.find('AppendColumn.col').transfer = True

    c.addPyMethod('GetColumns', '(self)',
        doc="Returns a list of column objects.",
        body="return [self.GetColumn(i) for i in range(self.GetColumnCount())]")

    c.find('GetSelections').ignore()
    c.addCppMethod('wxDataViewItemArray*', 'GetSelections', '()',
        isConst=True, factory=True,
        doc="Returns a list of the currently selected items.",
        body="""\
            wxDataViewItemArray* selections = new wxDataViewItemArray;
            self->GetSelections(*selections);
            return selections;
            """)

    # Pythonize HitTest
    c.find('HitTest').ignore()
    c.addCppMethod('PyObject*', 'HitTest', '(const wxPoint& point)',
        isConst=True,
        doc="""\
            HitTest(point) -> (item, col)\n
            Returns the item and column located at point, as a 2 element tuple.
            """,
        body="""\
            wxDataViewItem*   item = new wxDataViewItem();;
            wxDataViewColumn* col = NULL;

            self->HitTest(*point, *item, col);

            wxPyThreadBlocker blocker;
            PyObject* value = PyTuple_New(2);
            PyObject* item_obj =
                wxPyConstructObject((void*)item, wxT("wxDataViewItem"), 1);   // owned
            PyObject* col_obj;
            if (col) {
                col_obj = wxPyConstructObject((void*)col, wxT("wxDataViewColumn"), 0);  // not owned
            } else {
                col_obj = Py_None;
                Py_INCREF(Py_None);
            }
            PyTuple_SET_ITEM(value, 0, item_obj);
            PyTuple_SET_ITEM(value, 1, col_obj);
            // PyTuple steals a reference, so we don't need to decref the items here
            return value;
            """)


    # TODO: add support for wxVector templates
    c.find('GetSortingColumns').ignore()


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

    c.find('SetCache.from').name = 'from_'
    c.find('SetCache.to').name = 'to_'

    c.find('GetDataBuffer').ignore()
    c.addCppMethod('PyObject*', 'GetDataBuffer', '()', isConst=True,
        doc="Gets the data buffer for a drop data transfer",
        body="""\
            wxPyThreadBlocker blocker;
            return wxPyMakeBuffer(self->GetDataBuffer(), self->GetDataSize(), true);
            """)

    # TODO: SetDataBuffer

    c.find('SetDataObject.obj').transfer = True


    module.addPyCode("""\
        EVT_DATAVIEW_SELECTION_CHANGED         = wx.PyEventBinder( wxEVT_DATAVIEW_SELECTION_CHANGED, 1)
        EVT_DATAVIEW_ITEM_ACTIVATED            = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_ACTIVATED, 1)
        EVT_DATAVIEW_ITEM_COLLAPSED            = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_COLLAPSED, 1)
        EVT_DATAVIEW_ITEM_EXPANDED             = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EXPANDED, 1)
        EVT_DATAVIEW_ITEM_COLLAPSING           = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_COLLAPSING, 1)
        EVT_DATAVIEW_ITEM_EXPANDING            = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EXPANDING, 1)
        EVT_DATAVIEW_ITEM_START_EDITING        = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_START_EDITING, 1)
        EVT_DATAVIEW_ITEM_EDITING_STARTED      = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EDITING_STARTED, 1)
        EVT_DATAVIEW_ITEM_EDITING_DONE         = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EDITING_DONE, 1)
        EVT_DATAVIEW_ITEM_VALUE_CHANGED        = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, 1)
        EVT_DATAVIEW_ITEM_CONTEXT_MENU         = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, 1)
        EVT_DATAVIEW_COLUMN_HEADER_CLICK       = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_HEADER_CLICK, 1)
        EVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK, 1)
        EVT_DATAVIEW_COLUMN_SORTED             = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_SORTED, 1)
        EVT_DATAVIEW_COLUMN_REORDERED          = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_REORDERED, 1)
        EVT_DATAVIEW_ITEM_BEGIN_DRAG           = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_BEGIN_DRAG, 1)
        EVT_DATAVIEW_ITEM_DROP_POSSIBLE        = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_DROP_POSSIBLE, 1)
        EVT_DATAVIEW_ITEM_DROP                 = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_DROP, 1)
        EVT_DATAVIEW_CACHE_HINT                = wx.PyEventBinder( wxEVT_DATAVIEW_CACHE_HINT, 1 )

        # deprecated wxEVT aliases
        wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED          = wxEVT_DATAVIEW_SELECTION_CHANGED
        wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED             = wxEVT_DATAVIEW_ITEM_ACTIVATED
        wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED             = wxEVT_DATAVIEW_ITEM_COLLAPSED
        wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED              = wxEVT_DATAVIEW_ITEM_EXPANDED
        wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING            = wxEVT_DATAVIEW_ITEM_COLLAPSING
        wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING             = wxEVT_DATAVIEW_ITEM_EXPANDING
        wxEVT_COMMAND_DATAVIEW_ITEM_START_EDITING         = wxEVT_DATAVIEW_ITEM_START_EDITING
        wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED       = wxEVT_DATAVIEW_ITEM_EDITING_STARTED
        wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE          = wxEVT_DATAVIEW_ITEM_EDITING_DONE
        wxEVT_COMMAND_DATAVIEW_ITEM_VALUE_CHANGED         = wxEVT_DATAVIEW_ITEM_VALUE_CHANGED
        wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU          = wxEVT_DATAVIEW_ITEM_CONTEXT_MENU
        wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK        = wxEVT_DATAVIEW_COLUMN_HEADER_CLICK
        wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK  = wxEVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK
        wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED              = wxEVT_DATAVIEW_COLUMN_SORTED
        wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED           = wxEVT_DATAVIEW_COLUMN_REORDERED
        wxEVT_COMMAND_DATAVIEW_CACHE_HINT                 = wxEVT_DATAVIEW_CACHE_HINT
        wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG            = wxEVT_DATAVIEW_ITEM_BEGIN_DRAG
        wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE         = wxEVT_DATAVIEW_ITEM_DROP_POSSIBLE
        wxEVT_COMMAND_DATAVIEW_ITEM_DROP                  = wxEVT_DATAVIEW_ITEM_DROP
        """)

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

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

    c.find('AppendItem.values').type = 'const wxVariantVector&'
    c.find('PrependItem.values').type = 'const wxVariantVector&'
    c.find('InsertItem.values').type = 'const wxVariantVector&'

    c.find('GetValue.value').out = True

    for name in 'AppendColumn InsertColumn PrependColumn'.split():
        for m in c.find(name).all():
            m.find('column').transfer = True


    c = module.find('wxDataViewListStore')
    c.find('AppendItem.values').type = 'const wxVariantVector&'
    c.find('PrependItem.values').type = 'const wxVariantVector&'
    c.find('InsertItem.values').type = 'const wxVariantVector&'
    c.find('GetValueByRow.value').out = True
    c.addAutoProperties()


    #-----------------------------------------------------------------
    c = module.find('wxDataViewTreeCtrl')
    tools.fixWindowClass(c)
    c.find('GetStore').overloads = []


    c = module.find('wxDataViewTreeStore')
    c.addAutoProperties()
    tools.fixRefCountedClass(c)


    #-----------------------------------------------------------------
    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,
                                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.find('wxCreateDynamicObject').ignore()

    #--------------------------------------------------
    c = module.find('wxClassInfo')
    assert isinstance(c, etgtools.ClassDef)
    module.insertItemBefore(
        c, etgtools.TypedefDef(type='void*', name='wxObjectConstructorFn'))
    module.find('wxClassInfo').abstract = True
    module.find('wxClassInfo.wxClassInfo').ignore()

    #--------------------------------------------------
    c = module.find('wxRefCounter')
    assert isinstance(c, etgtools.ClassDef)
    c.find('~wxRefCounter').ignore(False)
    c.addPrivateCopyCtor()
    tools.fixRefCountedClass(c)

    #--------------------------------------------------
    c = module.find('wxObject')
    c.find('operator delete').ignore()
    c.find('operator new').ignore()
    c.find('IsKindOf').ignore()

    # EXPERIMENTAL: By turning off the virtualness of the wxObject dtor, and
    # since there are no other virtuals that we are exposing here, then all
    # classes that derive from wxObject that do not have any virtuals of
    # their own (or have the virtual flags turned off by the tweaker code)
    # can have simpler wrappers generated for them with no extra derived
    # class whose only purpose is to reflect calls to the virtual methods to
    # Python implementations. (And since the only virtual is the dtor then
    # that is of no real benefit to Python code since we're not overriding
    # the dtor anyhow.) In addition it appears so far that none of these
    # classes would ever need to have Python derived classes anyway. This
    # also makes it easier and less SIP-specific to add or replace ctors in
    # those classes with custom C++ code. (See wxFont and wxAcceleratorTable
    # for examples.)
    c.find('~wxObject').isVirtual = False
    c.find('GetClassInfo').isVirtual = False

    c.addCppMethod('const wxChar*',
                   'GetClassName',
                   '()',
                   body='return self->GetClassInfo()->GetClassName();',
                   doc='Returns the class name of the C++ class using wxRTTI.')

    c.addCppMethod(
        'void',
        'Destroy',
        '()',
        body='delete self;',
        doc='Deletes the C++ object this Python object is a proxy for.',
        transferThis=True)  # TODO: Check this

    tools.addSipConvertToSubClassCode(c)

    #-----------------------------------------------------------------
    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,
                                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.find('wxCreateDynamicObject').ignore()

    #module.find('wxClassInfo').abstract = True
    #module.find('wxClassInfo.wxClassInfo').ignore()



    #--------------------------------------------------
    c = module.find('wxRefCounter')
    assert isinstance(c, etgtools.ClassDef)
    c.find('~wxRefCounter').ignore(False)
    c.addPrivateCopyCtor()
    tools.fixRefCountedClass(c)


    #--------------------------------------------------
    c = module.find('wxObject')
    c.find('operator delete').ignore()
    c.find('operator new').ignore()
    c.find('GetClassInfo').ignore()
    c.find('IsKindOf').ignore()

    # EXPERIMENTAL: By turning off the virtualness of the wxObject dtor, and
    # since there are no other virtuals that we are exposing here, then all
    # classes that derive from wxObject that do not have any virtuals of
    # their own (or have the virtual flags turned off by the tweaker code)
    # can have simpler wrappers generated for them with no extra derived
    # class whose only purpose is to reflect calls to the virtual methods to
    # Python implementations. (And since the only virtual is the dtor then
    # that is of no real benefit to Python code since we're not overriding
    # the dtor anyhow.) In addition it appears so far that none of these
    # classes would ever need to have Python derived classes anyway. This
    # also makes it easier and less SIP-specific to add or replace ctors in
    # those classes with custom C++ code. (See wxFont and wxAcceleratorTable
    # for examples.)
    c.find('~wxObject').isVirtual = False

    c.addCppMethod('const wxChar*', 'GetClassName', '()',
        body='return self->GetClassInfo()->GetClassName();',
        doc='Returns the class name of the C++ class using wxRTTI.')

    c.addCppMethod('void', 'Destroy', '()',
        body='delete self;',
        doc='Deletes the C++ object this Python object is a proxy for.',
        transferThis=True)  # TODO: Check this


    tools.addSipConvertToSubClassCode(c)

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