Esempio n. 1
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)

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

    c = module.find('wxRichTextHeaderFooterData')
    assert isinstance(c, etgtools.ClassDef)
    tools.ignoreAllOperators(c)


    c = module.find('wxRichTextPrintout')
    assert isinstance(c, etgtools.ClassDef)
    c.find('GetPageInfo.minPage').out = True
    c.find('GetPageInfo.maxPage').out = True
    c.find('GetPageInfo.selPageFrom').out = True
    c.find('GetPageInfo.selPageTo').out = True


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


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Esempio n. 2
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)
    
    #-----------------------------------------------------------------
    # Tweak the parsed meta objects in the module object as needed for
    # customizing the generated code and docstrings.
    
    c = module.find('wxRichTextHeaderFooterData')
    assert isinstance(c, etgtools.ClassDef)
    tools.ignoreAllOperators(c)
    
    
    c = module.find('wxRichTextPrintout')
    assert isinstance(c, etgtools.ClassDef)
    c.find('GetPageInfo.minPage').out = True
    c.find('GetPageInfo.maxPage').out = True
    c.find('GetPageInfo.selPageFrom').out = True
    c.find('GetPageInfo.selPageTo').out = True
    
    
    c = module.find('wxRichTextPrinting')
    assert isinstance(c, etgtools.ClassDef)
    c.addPrivateCopyCtor()
    
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Esempio n. 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/unichar.h>')

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

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

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

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


    tools.ignoreAllOperators(c)


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

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

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

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

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

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

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

    tools.ignoreAllOperators(c)

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

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

    # ignore some of these enum values
    e = module.find('wxBitmapType')
    for i in e:
        if i.name.endswith('_RESOURCE'):
            i.ignore()

    module.addCppCode("""\
    #if !defined(__WXMAC__)
    #define wxCURSOR_COPY_ARROW wxCURSOR_ARROW
    #endif
    """)

    # these are X11 only
    e = module.find('wxStockCursor')
    e.find('wxCURSOR_BASED_ARROW_DOWN').ignore()
    e.find('wxCURSOR_BASED_ARROW_UP').ignore()
    e.find('wxCURSOR_CROSS_REVERSE').ignore()
    e.find('wxCURSOR_DOUBLE_ARROW').ignore()

    module.find('wxClientDisplayRect.x').out = True
    module.find('wxClientDisplayRect.y').out = True
    module.find('wxClientDisplayRect.width').out = True
    module.find('wxClientDisplayRect.height').out = True

    module.find('wxDisplaySize.width').out = True
    module.find('wxDisplaySize.height').out = True
    module.find('wxDisplaySizeMM.width').out = True
    module.find('wxDisplaySizeMM.height').out = True

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

    # Some operators are documented within the class that shouldn't be, so just
    # ignore them all.
    tools.ignoreAllOperators(c)

    # Undo a few of those ignores for legitimate items that were
    # documented correctly
    for f in c.find('operator+=').all() + c.find('operator-=').all():
        f.ignore(False)

    # Add some method declarations for operators that really do exist. Note
    # that these actually use C++ global operator functions, but we treat
    # them as methods to help disambiguate implementations due to how
    # multiple classes can be converted automatically to/from 2-element
    # sequences.
    c.addCppMethod('bool',
                   '__eq__',
                   '(const wxPoint& other)',
                   body="return *self == *other;")
    c.addCppMethod('bool',
                   '__ne__',
                   '(const wxPoint& other)',
                   body="return *self != *other;")

    c.addItem(
        etgtools.WigCode("""\
        wxPoint operator+(const wxPoint& other);
        wxPoint operator+(const wxSize& other);
        wxPoint operator-();
        wxPoint operator-(const wxPoint& other);
        wxPoint operator-(const wxSize& other);
        wxPoint operator*(int i);
        wxPoint operator/(int i);
        """))

    # wxPoint typemap
    c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxPoint')

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

    tools.addGetIMMethodTemplate(module, c, ['x', 'y'])

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

    module.addItem(
        tools.wxListWrapperTemplate('wxPointList',
                                    'wxPoint',
                                    module,
                                    includeConvertToType=True))

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

    # Used for testing releasing or holding the GIL in giltest.py
    #c.find('wxSize').findOverload('int width, int height').releaseGIL()
    #c.find('DecBy').findOverload('int dx, int dy').releaseGIL()
    #c.find('IncBy').findOverload('int dx, int dy').releaseGIL()

    c.addProperty("width GetWidth SetWidth")
    c.addProperty("height GetHeight SetHeight")

    # TODO:  How prevalent is the use of x,y properties on a size object?  Can we deprecate them?
    c.addProperty("x GetWidth SetWidth")
    c.addProperty("y GetHeight SetHeight")

    # Take care of the same issues as wxPoint
    tools.ignoreAllOperators(c)
    for f in c.find('operator+=').all() + \
             c.find('operator-=').all() + \
             c.find('operator*=').all() + \
             c.find('operator/=').all():
        f.ignore(False)

    c.addCppMethod('bool',
                   '__eq__',
                   '(const wxSize& other)',
                   body="return *self == *other;")
    c.addCppMethod('bool',
                   '__ne__',
                   '(const wxSize& other)',
                   body="return *self != *other;")

    c.addItem(
        etgtools.WigCode("""\
        wxSize operator+(const wxSize& other);
        wxSize operator-(const wxSize& other);
        wxSize operator*(int i);
        wxSize operator/(int i);

        wxPoint operator+(const wxPoint& other);
        wxPoint operator-(const wxPoint& other);
        wxRealPoint operator+(const wxRealPoint& other);
        wxRealPoint operator-(const wxRealPoint& other);
        """))

    # wxSize typemap
    c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxSize')

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

    tools.addGetIMMethodTemplate(module, c, ['width', 'height'])

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

    #---------------------------------------
    # wxRect tweaks
    c = module.find('wxRect')
    assert isinstance(c, etgtools.ClassDef)
    tools.addAutoProperties(c)

    c.addProperty("left GetLeft SetLeft")
    c.addProperty("top GetTop SetTop")
    c.addProperty("right GetRight SetRight")
    c.addProperty("bottom GetBottom SetBottom")

    c.addProperty("bottomLeft GetBottomLeft SetBottomLeft")
    c.addProperty("bottomRight GetBottomRight SetBottomRight")
    c.addProperty("topLeft GetTopLeft SetTopLeft")
    c.addProperty("topRight GetTopRight SetTopRight")

    # take care of the same issues as wxPoint
    tools.ignoreAllOperators(c)
    for f in c.find('operator+=').all() + \
             c.find('operator*=').all():
        f.ignore(False)

    c.addCppMethod('bool',
                   '__eq__',
                   '(const wxRect& other)',
                   body="return *self == *other;")
    c.addCppMethod('bool',
                   '__ne__',
                   '(const wxRect& other)',
                   body="return *self != *other;")

    c.addItem(
        etgtools.WigCode("""\
        wxRect operator+(const wxRect& other);
        wxRect operator*(const wxRect& other);
        """))

    # Because of our add-ons that make wx.Point and wx.Size act like 2-element
    # sequences, and also the typecheck code that allows 2-element sequences, then
    # we end up with a bit of confusion about the (Point,Point) and the
    # (Point,Size) overloads of the wx.Rect constructor. The confusion can be
    # dealt with by using keyword args, but I think that the (Point,Size) version
    # will be used more, so reorder the overloads so it is found first.
    m = module.find('wxRect.wxRect')
    mo = m.findOverload('topLeft')
    del m.overloads[m.overloads.index(mo)]
    m.overloads.append(mo)

    # These methods have some overloads that will end up with the same signature
    # in Python, so we have to remove one.
    module.find('wxRect.Deflate').findOverload(') const').ignore()
    module.find('wxRect.Inflate').findOverload(') const').ignore()
    module.find('wxRect.Union').findOverload(') const').ignore()
    module.find('wxRect.Intersect').findOverload(') const').ignore()

    # wxRect typemap
    c.convertFromPyObject = tools.convertFourIntegersTemplate('wxRect')

    c.addCppMethod('PyObject*',
                   'Get',
                   '()',
                   """\
        wxPyThreadBlocker blocker;
        return sipBuildResult(0, "(iiii)",
                              self->x, self->y, self->width, self->height);
        """,
                   pyArgsString="() -> (x, y, width, height)",
                   briefDoc="Return the rectangle's properties as a tuple.")

    tools.addGetIMMethodTemplate(module, c, ['x', 'y', 'width', 'height'])

    # Add sequence protocol methods and other goodies
    c.addPyMethod('__str__', '(self)', 'return str(self.Get())')
    c.addPyMethod('__repr__', '(self)', 'return "wx.Rect"+str(self.Get())')
    c.addPyMethod('__len__', '(self)', 'return len(self.Get())')
    c.addPyMethod('__nonzero__', '(self)', 'return self.Get() != (0,0,0,0)')
    c.addPyMethod('__reduce__', '(self)', 'return (Rect, self.Get())')
    c.addPyMethod('__getitem__', '(self, idx)', 'return self.Get()[idx]')
    c.addPyMethod(
        '__setitem__', '(self, idx, val)', """\
                  if idx == 0: self.x = val
                  elif idx == 1: self.y = val
                  elif idx == 2: self.width = val
                  elif idx == 3: self.height = val
                  else: raise IndexError
                  """)
    c.addPyCode('Rect.__safe_for_unpickling__ = True')

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

    # take care of the same issues as wxPoint
    tools.ignoreAllOperators(c)
    for f in c.find('operator+=').all() + \
             c.find('operator-=').all():
        f.ignore(False)

    c.addCppMethod('bool',
                   '__eq__',
                   '(const wxRealPoint& other)',
                   body="return *self == *other;")
    c.addCppMethod('bool',
                   '__ne__',
                   '(const wxRealPoint& other)',
                   body="return *self != *other;")

    c.addItem(
        etgtools.WigCode("""\
        wxRealPoint operator+(const wxRealPoint& other);
        wxRealPoint operator-(const wxRealPoint& other);
        wxRealPoint operator*(int i);
        wxRealPoint operator/(int i);
        """))

    # wxRealPoint typemap
    c.convertFromPyObject = tools.convertTwoDoublesTemplate('wxRealPoint')

    c.addCppMethod('PyObject*',
                   'Get',
                   '()',
                   """\
        wxPyThreadBlocker blocker;
        return sipBuildResult(0, "(dd)", self->x, self->y);
        """,
                   pyArgsString="() -> (x, y)",
                   briefDoc="Return the point's properties as a tuple.")

    tools.addGetIMMethodTemplate(module, c, ['x', 'y'])

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

    c = module.find('wxColourDatabase')
    c.mustHaveApp()
    c.addPyMethod('FindColour', '(self, colour)', 'return self.Find(colour)')

    module.find('wxTheColourDatabase').ignore()

    #-----------------------------------------------------------------
    module.addCppFunction('PyObject*',
                          'IntersectRect',
                          '(wxRect* r1, wxRect* r2)',
                          doc="""\
            Calculate and return the intersection of r1 and r2.  Returns None if there
            is no intersection.""",
                          body="""\
            wxRegion  reg1(*r1);
            wxRegion  reg2(*r2);
            wxRect    dest(0,0,0,0);
            PyObject* obj;

            reg1.Intersect(reg2);
            dest = reg1.GetBox();

            wxPyThreadBlocker blocker;
            if (dest != wxRect(0,0,0,0)) {
                wxRect* newRect = new wxRect(dest);
                obj = wxPyConstructObject((void*)newRect, wxT("wxRect"), true);
                return obj;
            }
            Py_INCREF(Py_None);
            return Py_None;
            """)

    for funcname in [
            'wxColourDisplay',
            'wxDisplayDepth',
            'wxDisplaySize',
            'wxGetDisplaySize',
            'wxDisplaySizeMM',
            'wxGetDisplaySizeMM',
            'wxGetDisplayPPI',
            'wxClientDisplayRect',
            'wxGetClientDisplayRect',
            'wxSetCursor',
            #'wxGetXDisplay',
    ]:
        c = module.find(funcname)
        c.mustHaveApp()

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Esempio n. 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.
    
    
    # Lots of the uses of wxDateTime_t have been changed to "unsigned short"
    # in the interface file, so lets go ahead and translate the rest of them
    # too so there will not be any "wxDateTime_t" in Phoenix confusingly
    # mixed with "unsigned short"s.
    #
    # Also add the class scope specifier to nested enum types for parameters
    # and return values.
    for item in module.allItems():
        if isinstance(item, (etgtools.FunctionDef, etgtools.ParamDef, etgtools.VariableDef)):
            typesMap = { 'wxDateTime_t': 'unsigned short', 
                         'Month'       : 'wxDateTime::Month',
                         'WeekDay'     : 'wxDateTime::WeekDay',
                         'TZ'          : 'wxDateTime::TZ',
                         'TimeZone'    : 'wxDateTime::TimeZone',
                         'Tm'          : 'wxDateTime::Tm',
                        } 
            if item.type in typesMap: 
                item.type = typesMap[item.type]
                
                    
    # ignore the #define and add it as a Python alias instead
    module.find('wxInvalidDateTime').ignore()
    module.addPyCode('InvalidDateTime = DefaultDateTime')
    gs = module.addGlobalStr('wxDefaultDateTimeFormat', module.find('wxInvalidDateTime'))
    module.addGlobalStr('wxDefaultTimeSpanFormat', gs)
    
    #---------------------------------------------
    # Tweaks for the wxDateTime class
    c = module.find('wxDateTime')
    assert isinstance(c, etgtools.ClassDef)
    c.allowAutoProperties = False
    tools.ignoreAllOperators(c)
    
    # Ignore ctors with unknown types or that have overload conflicts that
    # can't be distingished in Python
    ctor = c.find('wxDateTime')
    ctor.findOverload('time_t').ignore()
    ctor.findOverload('struct tm').ignore()
    ctor.findOverload('double jdn').ignore()
    ctor.findOverload('_SYSTEMTIME').ignore()
    ctor.findOverload('hour').ignore() # careful, the one we want to keep has an 'hour' param too
    
    # Add static factories for some of the ctors we ignored
    c.addCppMethod('wxDateTime*', 'FromTimeT', '(time_t timet)', 
        factory=True, isStatic=True,
        doc="Construct a :class:`DateTime` from a C ``time_t`` value, the number of seconds since the epoch.",
        body="return new wxDateTime(timet);")
                   
    c.addCppMethod('wxDateTime*', 'FromJDN', '(double jdn)', 
        factory=True, isStatic=True,
        doc="Construct a :class:`DateTime` from a Julian Day Number.\n\n"
            "By definition, the Julian Day Number, usually abbreviated as JDN, of a particular instant is the fractional number of days since 12 hours Universal Coordinated Time (Greenwich mean noon) on January 1 of the year -4712 in the Julian proleptic calendar.",
        body="return new wxDateTime(jdn);")
    
    c.addCppMethod('wxDateTime*', 'FromHMS', 
        """(unsigned short hour, 
            unsigned short minute=0, 
            unsigned short second=0, 
            unsigned short millisecond=0)""", 
        factory=True, isStatic=True,
        doc="Construct a :class:`DateTime` equal to :meth:`Today` () with the time set to the supplied parameters.",
        body="return new wxDateTime(hour, minute, second, millisecond);")

    c.addCppMethod('wxDateTime*', 'FromDMY', 
        """(unsigned short day,
            wxDateTime::Month month,
            int year = Inv_Year,
            unsigned short hour=0, 
            unsigned short minute=0, 
            unsigned short second=0, 
            unsigned short millisecond=0)""", 
        factory=True, isStatic=True,
        doc="Construct a :class:`DateTime` using the supplied parameters.",
        body="return new wxDateTime(day, month, year, hour, minute, second, millisecond);")
    
    # and give them some simple wrappers for Classic compatibility
    module.addPyFunction('DateTimeFromTimeT', '(timet)',
        doc="Compatibility wrapper for :meth:`DateTime.FromTimeT`",
        body="return DateTime.FromTimeT(timet)",
        deprecated='Use :meth:`DateTime.FromTimeT` instead.')
    module.addPyFunction('DateTimeFromJDN', '(jdn)',
        doc="Compatibility wrapper for :meth:`DateTime.FromJDN`",
        body="return DateTime.FromJDN(jdn)",
        deprecated='Use :meth:`DateTime.FromJDN` instead.')
    module.addPyFunction('DateTimeFromHMS', '(hour, minute=0, second=0, millisecond=0)',
        doc="Compatibility wrapper for :meth:`DateTime.FromHMS`",
        body="return DateTime.FromHMS(hour, minute, second, millisecond)",
        deprecated='Use :meth:`DateTime.FromHMS` instead.')
    module.addPyFunction('DateTimeFromDMY', '(day, month, year=DateTime.Inv_Year, hour=0, minute=0, second=0, millisecond=0)',
        doc="Compatibility wrapper for :meth:`DateTime.FromDMY`",
        body="return DateTime.FromDMY(day, month, year, hour, minute, second, millisecond)",
        deprecated='Use :meth:`DateTime.FromDMY` instead.')
    
    
    # Fixup similar conflicts in the Set method overloads
    c.find('Set').findOverload('struct tm').ignore()
    c.find('Set').renameOverload('Tm',         'SetTm')
    c.find('Set').renameOverload('time_t',     'SetTimeT')
    c.find('Set').renameOverload('double jdn', 'SetJDN')
    c.find('Set').renameOverload('hour',       'SetHMS')
    
    # Unknown parameter and return types
    c.find('SetFromMSWSysTime').ignore()
    c.find('GetAsMSWSysTime').ignore()
    
    # this overload is static, the other isn't.  Rename it?
    c.find('GetCentury').findOverload('year').ignore()
    
    c.find('GetNumberOfDays').ignore()
    c.find('GetTmNow').ignore()
    c.find('GetTmNow').ignore()
    
    # Link error??
    c.find('IsGregorianDate').ignore()

    # output the am/pm parameter values
    c.find('GetAmPmStrings.am').out = True
    c.find('GetAmPmStrings.pm').out = True


    # remove the const version of the overloaded Add's and Subtract's
    c.find('Add').findOverload('wxDateSpan', isConst=True).ignore()
    c.find('Add').findOverload('wxTimeSpan', isConst=True).ignore()
    c.find('Subtract').findOverload('wxDateSpan', isConst=True).ignore()
    c.find('Subtract').findOverload('wxTimeSpan', isConst=True).ignore()

    # Ignore the end parameter for the parse methods, and provide replacement
    # implementations that don't need them.
    c.find('ParseDate.end').ignore()
    c.find('ParseTime.end').ignore()
    c.find('ParseDateTime.end').ignore()
    c.find('ParseRfc822Date.end').ignore()
    for m in c.find('ParseFormat').all():
        m.find('end').ignore()
    
    c.find('ParseDate').setCppCode("""\
        wxString::const_iterator end;
        return self->ParseDate(*date, &end);
        """)
    c.find('ParseTime').setCppCode("""\
        wxString::const_iterator end;
        return self->ParseTime(*time, &end);
        """)
    c.find('ParseDateTime').setCppCode("""\
        wxString::const_iterator end;
        return self->ParseDateTime(*datetime, &end);
        """)        
    c.find('ParseRfc822Date').setCppCode("""\
        wxString::const_iterator end;
        return self->ParseRfc822Date(*date, &end);
        """)
    
    pf = c.find('ParseFormat')
    pf.findOverload('const wxString &date, const wxString &format, const wxDateTime &dateDef, wxString::').setCppCode(
        """\
        wxString::const_iterator end;
        return self->ParseFormat(*date, *format, *dateDef, &end);
        """)
    pf.findOverload('const wxString &date, const wxString &format, wxString::').setCppCode(
        """\
        wxString::const_iterator end;
        return self->ParseFormat(*date, *format, &end);
        """)
    pf.findOverload('const wxString &date, wxString::').setCppCode(
        """\
        wxString::const_iterator end;
        return self->ParseFormat(*date, &end);
        """)
    
    
    c.addPyMethod('__repr__', '(self)', """\
        if self.IsValid():
            f = self.Format().encode('utf-8')
            return '<wx.DateTime: \"%s\">' % f
        else:
            return '<wx.DateTime: \"INVALID\">'
        """)
    
    c.addPyMethod('__str__', '(self)', """\
        if self.IsValid():
            return self.Format().encode('utf-8')
        else:
            return "INVALID DateTime"
        """)


    # use lowercase to avoid conflicts
    c.addProperty("day GetDay SetDay")
    c.addProperty("month GetMonth SetMonth")
    c.addProperty("year GetYear SetYear")
    c.addProperty("hour GetHour SetHour")
    c.addProperty("minute GetMinute SetMinute")
    c.addProperty("second GetSecond SetSecond")
    c.addProperty("millisecond GetMillisecond SetMillisecond")
    c.addProperty("JDN GetJDN SetJDN")

    c.addProperty("DayOfYear GetDayOfYear")
    c.addProperty("JulianDayNumber GetJulianDayNumber")
    c.addProperty("LastMonthDay GetLastMonthDay")
    c.addProperty("MJD GetMJD")
    c.addProperty("ModifiedJulianDayNumber GetModifiedJulianDayNumber")
    c.addProperty("RataDie GetRataDie")
    c.addProperty("Ticks GetTicks")
    c.addProperty("WeekOfMonth GetWeekOfMonth")
    c.addProperty("WeekOfYear GetWeekOfYear")
    

    c.addItem(etgtools.WigCode("""\
        bool operator<(const wxDateTime& dt) const;
        bool operator<=(const wxDateTime& dt) const;
        bool operator>(const wxDateTime& dt) const;
        bool operator>=(const wxDateTime& dt) const;
        bool operator==(const wxDateTime& dt) const;
        bool operator!=(const wxDateTime& dt) const;
        wxDateTime& operator+=(const wxTimeSpan& diff);
        wxDateTime operator+(const wxTimeSpan& ts) const;
        wxDateTime& operator-=(const wxTimeSpan& diff);
        wxDateTime operator-(const wxTimeSpan& ts) const;
        wxDateTime& operator+=(const wxDateSpan& diff);
        wxDateTime operator+(const wxDateSpan& ds) const;
        wxDateTime& operator-=(const wxDateSpan& diff);
        wxDateTime operator-(const wxDateSpan& ds) const;
        wxTimeSpan operator-(const wxDateTime& dt2) const;
        """))
    
    # Add some code to automatically convert from a Python datetime.date or a
    # datetime.datetime object
    c.addHeaderCode("#include <datetime.h>")
    c.convertFromPyObject = """\
        PyDateTime_IMPORT;
    
        // Code to test a PyObject for compatibility with wxDateTime
        if (!sipIsErr) {
            if (sipCanConvertToType(sipPy, sipType_wxDateTime, SIP_NO_CONVERTORS))
                    return TRUE;        
            if (PyDateTime_Check(sipPy) || PyDate_Check(sipPy))
                return TRUE;
            return FALSE;
        }
    
        // Code to convert a compatible PyObject to a wxDateTime
        if (PyDateTime_Check(sipPy)) {
            *sipCppPtr = new wxDateTime(PyDateTime_GET_DAY(sipPy),
                                        (wxDateTime::Month)(PyDateTime_GET_MONTH(sipPy)-1),
                                        PyDateTime_GET_YEAR(sipPy),
                                        PyDateTime_DATE_GET_HOUR(sipPy),
                                        PyDateTime_DATE_GET_MINUTE(sipPy),
                                        PyDateTime_DATE_GET_SECOND(sipPy),
                                        PyDateTime_DATE_GET_MICROSECOND(sipPy)/1000); // micro to milli
            return sipGetState(sipTransferObj);
        }            
        if (PyDate_Check(sipPy)) {
            *sipCppPtr = new wxDateTime(PyDateTime_GET_DAY(sipPy),
                                        (wxDateTime::Month)(PyDateTime_GET_MONTH(sipPy)-1),
                                        PyDateTime_GET_YEAR(sipPy));
            return sipGetState(sipTransferObj);
        }            
        // if we get this far then it must already be a wxDateTime instance
        *sipCppPtr = reinterpret_cast<wxDateTime*>(sipConvertToType(
                sipPy, sipType_wxDateTime, sipTransferObj, SIP_NO_CONVERTORS, 0, sipIsErr));
        
        return 0;  // Not a new isntance
        """


    #---------------------------------------------
    # Tweaks for the wxDateSpan class
    c = module.find('wxDateSpan')
    c.allowAutoProperties = False
    tools.ignoreAllOperators(c)

    c.find('Add').findOverload('', isConst=True).ignore()
    c.find('Multiply').findOverload('', isConst=True).ignore()
    c.find('Subtract').findOverload('', isConst=True).ignore()
    
    c.addItem(etgtools.WigCode("""\
        wxDateSpan& operator+=(const wxDateSpan& other);
        wxDateSpan operator+(const wxDateSpan& ds) const;
        wxDateSpan& operator-=(const wxDateSpan& other);
        wxDateSpan operator-(const wxDateSpan& ds) const;
        wxDateSpan& operator-();
        wxDateSpan& operator*=(int factor);
        wxDateSpan operator*(int n) const;
        bool operator==(const wxDateSpan& ds) const;
        bool operator!=(const wxDateSpan& ds) const;
        """))



    #---------------------------------------------
    # Tweaks for the wxTimeSpan class
    c = module.find('wxTimeSpan')
    c.allowAutoProperties = False
    tools.ignoreAllOperators(c)

    c.find('Add').findOverload('', isConst=True).ignore()
    c.find('Multiply').findOverload('', isConst=True).ignore()
    c.find('Subtract').findOverload('', isConst=True).ignore()

    c.addItem(etgtools.WigCode("""\
        wxTimeSpan& operator+=(const wxTimeSpan& diff);
        wxTimeSpan operator+(const wxTimeSpan& ts) const;
        wxTimeSpan& operator-=(const wxTimeSpan& diff);
        wxTimeSpan operator-(const wxTimeSpan& ts);
        wxTimeSpan& operator*=(int n);
        wxTimeSpan operator*(int n) const;
        wxTimeSpan& operator-();
        bool operator<(const wxTimeSpan &ts) const;
        bool operator<=(const wxTimeSpan &ts) const;
        bool operator>(const wxTimeSpan &ts) const;
        bool operator>=(const wxTimeSpan &ts) const;
        bool operator==(const wxTimeSpan &ts) const;
        bool operator!=(const wxTimeSpan &ts) const;
        """))
    

    #---------------------------------------------
    # Convert to/from Python date objects
    module.addPyFunction('pydate2wxdate', '(date)', 
        doc='Convert a Python date or datetime to a :class:`DateTime` object',
        body="""\
            import datetime
            assert isinstance(date, (datetime.datetime, datetime.date))
            return DateTime(date)  # the built-in typemap will convert it for us
        """)
    
    module.addPyFunction('wxdate2pydate', '(date)', 
        doc='Convert a :class:`DateTime` object to a Python datetime.',
        body="""\
            import datetime
            assert isinstance(date, DateTime)
            if date.IsValid():
                return datetime.datetime(date.year, date.month+1, date.day,
                                         date.hour, date.minute, date.second, date.millisecond*1000)
            else:
                return None
            """)
    
    
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Esempio n. 7
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)

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

    # Lots of the uses of wxDateTime_t have been changed to "unsigned short"
    # in the interface file, so lets go ahead and translate the rest of them
    # too so there will not be any "wxDateTime_t" in Phoenix confusingly
    # mixed with "unsigned short"s.
    #
    # Also add the class scope specifier to nested enum types for parameters
    # and return values.
    for item in module.allItems():
        if isinstance(
                item,
            (etgtools.FunctionDef, etgtools.ParamDef, etgtools.VariableDef)):
            typesMap = {
                'wxDateTime_t': 'unsigned short',
                'Month': 'wxDateTime::Month',
                'WeekDay': 'wxDateTime::WeekDay',
                'TZ': 'wxDateTime::TZ',
                'TimeZone': 'wxDateTime::TimeZone',
                'Tm': 'wxDateTime::Tm',
            }
            if item.type in typesMap:
                item.type = typesMap[item.type]

    # ignore the #define and add it as a Python alias instead
    module.find('wxInvalidDateTime').ignore()
    module.addPyCode('InvalidDateTime = DefaultDateTime')
    gs = module.addGlobalStr('wxDefaultDateTimeFormat',
                             module.find('wxInvalidDateTime'))
    module.addGlobalStr('wxDefaultTimeSpanFormat', gs)

    #---------------------------------------------
    # Tweaks for the wxDateTime class
    c = module.find('wxDateTime')
    assert isinstance(c, etgtools.ClassDef)
    c.allowAutoProperties = False
    tools.ignoreAllOperators(c)

    # Ignore ctors with unknown types or that have overload conflicts that
    # can't be distingished in Python
    ctor = c.find('wxDateTime')
    ctor.findOverload('time_t').ignore()
    ctor.findOverload('struct tm').ignore()
    ctor.findOverload('double jdn').ignore()
    ctor.findOverload('_SYSTEMTIME').ignore()
    ctor.findOverload('hour').ignore(
    )  # careful, the one we want to keep has an 'hour' param too

    # Add static factories for some of the ctors we ignored
    c.addCppMethod(
        'wxDateTime*',
        'FromTimeT',
        '(time_t timet)',
        factory=True,
        isStatic=True,
        doc=
        "Construct a :class:`DateTime` from a C ``time_t`` value, the number of seconds since the epoch.",
        body="return new wxDateTime(timet);")

    c.addCppMethod(
        'wxDateTime*',
        'FromJDN',
        '(double jdn)',
        factory=True,
        isStatic=True,
        doc="Construct a :class:`DateTime` from a Julian Day Number.\n\n"
        "By definition, the Julian Day Number, usually abbreviated as JDN, of a particular instant is the fractional number of days since 12 hours Universal Coordinated Time (Greenwich mean noon) on January 1 of the year -4712 in the Julian proleptic calendar.",
        body="return new wxDateTime(jdn);")

    c.addCppMethod(
        'wxDateTime*',
        'FromHMS',
        """(unsigned short hour, 
            unsigned short minute=0, 
            unsigned short second=0, 
            unsigned short millisecond=0)""",
        factory=True,
        isStatic=True,
        doc=
        "Construct a :class:`DateTime` equal to :meth:`Today` () with the time set to the supplied parameters.",
        body="return new wxDateTime(hour, minute, second, millisecond);")

    c.addCppMethod(
        'wxDateTime*',
        'FromDMY',
        """(unsigned short day,
            wxDateTime::Month month,
            int year = Inv_Year,
            unsigned short hour=0, 
            unsigned short minute=0, 
            unsigned short second=0, 
            unsigned short millisecond=0)""",
        factory=True,
        isStatic=True,
        doc="Construct a :class:`DateTime` using the supplied parameters.",
        body=
        "return new wxDateTime(day, month, year, hour, minute, second, millisecond);"
    )

    # and give them some simple wrappers for Classic compatibility
    module.addPyFunction(
        'DateTimeFromTimeT',
        '(timet)',
        doc="Compatibility wrapper for :meth:`DateTime.FromTimeT`",
        body="return DateTime.FromTimeT(timet)",
        deprecated='Use :meth:`DateTime.FromTimeT` instead.')
    module.addPyFunction(
        'DateTimeFromJDN',
        '(jdn)',
        doc="Compatibility wrapper for :meth:`DateTime.FromJDN`",
        body="return DateTime.FromJDN(jdn)",
        deprecated='Use :meth:`DateTime.FromJDN` instead.')
    module.addPyFunction(
        'DateTimeFromHMS',
        '(hour, minute=0, second=0, millisecond=0)',
        doc="Compatibility wrapper for :meth:`DateTime.FromHMS`",
        body="return DateTime.FromHMS(hour, minute, second, millisecond)",
        deprecated='Use :meth:`DateTime.FromHMS` instead.')
    module.addPyFunction(
        'DateTimeFromDMY',
        '(day, month, year=DateTime.Inv_Year, hour=0, minute=0, second=0, millisecond=0)',
        doc="Compatibility wrapper for :meth:`DateTime.FromDMY`",
        body=
        "return DateTime.FromDMY(day, month, year, hour, minute, second, millisecond)",
        deprecated='Use :meth:`DateTime.FromDMY` instead.')

    # Fixup similar conflicts in the Set method overloads
    c.find('Set').findOverload('struct tm').ignore()
    c.find('Set').renameOverload('Tm', 'SetTm')
    c.find('Set').renameOverload('time_t', 'SetTimeT')
    c.find('Set').renameOverload('double jdn', 'SetJDN')
    c.find('Set').renameOverload('hour', 'SetHMS')

    # Unknown parameter and return types
    c.find('SetFromMSWSysTime').ignore()
    c.find('GetAsMSWSysTime').ignore()

    # this overload is static, the other isn't.  Rename it?
    c.find('GetCentury').findOverload('year').ignore()

    c.find('GetNumberOfDays').ignore()
    c.find('GetTmNow').ignore()
    c.find('GetTmNow').ignore()

    # output the am/pm parameter values
    c.find('GetAmPmStrings.am').out = True
    c.find('GetAmPmStrings.pm').out = True

    # remove the const version of the overloaded Add's and Subtract's
    c.find('Add').findOverload('wxDateSpan', isConst=True).ignore()
    c.find('Add').findOverload('wxTimeSpan', isConst=True).ignore()
    c.find('Subtract').findOverload('wxDateSpan', isConst=True).ignore()
    c.find('Subtract').findOverload('wxTimeSpan', isConst=True).ignore()

    # Ignore the end parameter for the Parse*() methods, and provide
    # replacement implementations that don't need them. Change them to be
    # like they were in Classic, returning a -1 on failure, or the number of
    # characters parsed otherwise.
    def fixParseMethod(m, code):
        assert isinstance(m, etgtools.MethodDef)
        m.find('end').ignore()
        m.type = 'int'
        m.setCppCode(code)
        return m

    fixParseMethod(
        c.find('ParseDate'), """\
        wxString::const_iterator begin = date->begin();
        wxString::const_iterator end;
        if (! self->ParseDate(*date, &end))
            return -1;
        return end - begin;
        """)

    fixParseMethod(
        c.find('ParseDateTime'), """\
        wxString::const_iterator begin = datetime->begin();
        wxString::const_iterator end;
        if (! self->ParseDateTime(*datetime, &end))
            return -1;
        return end - begin;
        """)

    fixParseMethod(
        c.find('ParseTime'), """\
        wxString::const_iterator begin = time->begin();
        wxString::const_iterator end;
        if (! self->ParseTime(*time, &end))
            return -1;
        return end - begin;
        """)

    fixParseMethod(
        c.find('ParseRfc822Date'), """\
        wxString::const_iterator begin = date->begin();
        wxString::const_iterator end;
        if (! self->ParseRfc822Date(*date, &end))
            return -1;
        return end - begin;
        """)

    pf = c.find('ParseFormat')
    pf1 = fixParseMethod(
        pf.findOverload(
            'const wxString &date, const wxString &format, const wxDateTime &dateDef, wxString::'
        ), """\
        wxString::const_iterator begin = date->begin();
        wxString::const_iterator end;
        if (! self->ParseFormat(*date, *format, *dateDef, &end))
            return -1;
        return end - begin;
        """)

    pf2 = fixParseMethod(
        pf.findOverload(
            'const wxString &date, const wxString &format, wxString::'), """\
        wxString::const_iterator begin = date->begin();
        wxString::const_iterator end;
        if (! self->ParseFormat(*date, *format, &end))
            return -1;
        return end - begin;
        """)

    pf3 = fixParseMethod(
        pf.findOverload('const wxString &date, wxString::'), """\
        wxString::const_iterator begin = date->begin();
        wxString::const_iterator end;
        if (! self->ParseFormat(*date, &end))
            return -1;
        return end - begin;
        """)

    # Fiddle with the docstrings for ParseFormat to make them refect the new
    # reality. The other Parse*() docs refer the reader to this one, so we
    # don't have to change all of them.

    # find the <simplesect kind="return"> node in the last paragraph
    para = pf1.detailedDoc[-1]
    elem = para.find("simplesect[@kind='return']")
    # it has a child paragraph containing the text we need to replace
    elem[
        0].text = '-1 if the parse failed, the number of characters parsed otherwise.'

    pf2.briefDoc = "This version of the :meth:`ParseFormat` method works the same, but with missing values filled in from :meth:`Today`."
    pf3.briefDoc = "This version uses \"%c\" as the format code, which is the same default used by :meth:`Format`."

    c.addPyMethod(
        '__repr__', '(self)', """\
        from wx.lib.six import PY2
        if self.IsValid():
            f = self.Format()
            if PY2: f = f.encode('utf-8')
            return '<wx.DateTime: "%s">' % f
        else:
            return '<wx.DateTime: \"INVALID\">'
        """)

    c.addPyMethod(
        '__str__', '(self)', """\
        from wx.lib.six import PY2
        if self.IsValid():
            f = self.Format()
            if PY2: f = f.encode('utf-8')
            return f
        else:
            return "INVALID DateTime"
        """)

    # use lowercase to avoid conflicts
    c.addProperty("day GetDay SetDay")
    c.addProperty("month GetMonth SetMonth")
    c.addProperty("year GetYear SetYear")
    c.addProperty("hour GetHour SetHour")
    c.addProperty("minute GetMinute SetMinute")
    c.addProperty("second GetSecond SetSecond")
    c.addProperty("millisecond GetMillisecond SetMillisecond")
    c.addProperty("JDN GetJDN SetJDN")

    c.addProperty("DayOfYear GetDayOfYear")
    c.addProperty("JulianDayNumber GetJulianDayNumber")
    c.addProperty("LastMonthDay GetLastMonthDay")
    c.addProperty("MJD GetMJD")
    c.addProperty("ModifiedJulianDayNumber GetModifiedJulianDayNumber")
    c.addProperty("RataDie GetRataDie")
    c.addProperty("Ticks GetTicks")
    c.addProperty("WeekOfMonth GetWeekOfMonth")
    c.addProperty("WeekOfYear GetWeekOfYear")

    c.addItem(
        etgtools.WigCode("""\
        bool operator<(const wxDateTime& dt) const;
        bool operator<=(const wxDateTime& dt) const;
        bool operator>(const wxDateTime& dt) const;
        bool operator>=(const wxDateTime& dt) const;
        bool operator==(const wxDateTime& dt) const;
        bool operator!=(const wxDateTime& dt) const;
        wxDateTime& operator+=(const wxTimeSpan& diff);
        wxDateTime operator+(const wxTimeSpan& ts) const;
        wxDateTime& operator-=(const wxTimeSpan& diff);
        wxDateTime operator-(const wxTimeSpan& ts) const;
        wxDateTime& operator+=(const wxDateSpan& diff);
        wxDateTime operator+(const wxDateSpan& ds) const;
        wxDateTime& operator-=(const wxDateSpan& diff);
        wxDateTime operator-(const wxDateSpan& ds) const;
        wxTimeSpan operator-(const wxDateTime& dt2) const;
        """))

    # Add some code to automatically convert from a Python datetime.date or a
    # datetime.datetime object
    c.addHeaderCode("#include <datetime.h>")
    c.convertFromPyObject = """\
        PyDateTime_IMPORT;
    
        // Code to test a PyObject for compatibility with wxDateTime
        if (!sipIsErr) {
            if (sipCanConvertToType(sipPy, sipType_wxDateTime, SIP_NO_CONVERTORS))
                    return TRUE;        
            if (PyDateTime_Check(sipPy) || PyDate_Check(sipPy))
                return TRUE;
            return FALSE;
        }
    
        // Code to convert a compatible PyObject to a wxDateTime
        if (PyDateTime_Check(sipPy)) {
            *sipCppPtr = new wxDateTime(PyDateTime_GET_DAY(sipPy),
                                        (wxDateTime::Month)(PyDateTime_GET_MONTH(sipPy)-1),
                                        PyDateTime_GET_YEAR(sipPy),
                                        PyDateTime_DATE_GET_HOUR(sipPy),
                                        PyDateTime_DATE_GET_MINUTE(sipPy),
                                        PyDateTime_DATE_GET_SECOND(sipPy),
                                        PyDateTime_DATE_GET_MICROSECOND(sipPy)/1000); // micro to milli
            return sipGetState(sipTransferObj);
        }            
        if (PyDate_Check(sipPy)) {
            *sipCppPtr = new wxDateTime(PyDateTime_GET_DAY(sipPy),
                                        (wxDateTime::Month)(PyDateTime_GET_MONTH(sipPy)-1),
                                        PyDateTime_GET_YEAR(sipPy));
            return sipGetState(sipTransferObj);
        }            
        // if we get this far then it must already be a wxDateTime instance
        *sipCppPtr = reinterpret_cast<wxDateTime*>(sipConvertToType(
                sipPy, sipType_wxDateTime, sipTransferObj, SIP_NO_CONVERTORS, 0, sipIsErr));
        
        return 0;  // Not a new isntance
        """

    #---------------------------------------------
    # Tweaks for the wxDateSpan class
    c = module.find('wxDateSpan')
    c.allowAutoProperties = False
    tools.ignoreAllOperators(c)

    c.find('Add').findOverload('', isConst=True).ignore()
    c.find('Multiply').findOverload('', isConst=True).ignore()
    c.find('Subtract').findOverload('', isConst=True).ignore()

    c.addItem(
        etgtools.WigCode("""\
        wxDateSpan& operator+=(const wxDateSpan& other);
        wxDateSpan operator+(const wxDateSpan& ds) const;
        wxDateSpan& operator-=(const wxDateSpan& other);
        wxDateSpan operator-(const wxDateSpan& ds) const;
        wxDateSpan& operator-();
        wxDateSpan& operator*=(int factor);
        wxDateSpan operator*(int n) const;
        bool operator==(const wxDateSpan& ds) const;
        bool operator!=(const wxDateSpan& ds) const;
        """))

    #---------------------------------------------
    # Tweaks for the wxTimeSpan class
    c = module.find('wxTimeSpan')
    c.allowAutoProperties = False
    tools.ignoreAllOperators(c)

    c.find('Add').findOverload('', isConst=True).ignore()
    c.find('Multiply').findOverload('', isConst=True).ignore()
    c.find('Subtract').findOverload('', isConst=True).ignore()

    c.addItem(
        etgtools.WigCode("""\
        wxTimeSpan& operator+=(const wxTimeSpan& diff);
        wxTimeSpan operator+(const wxTimeSpan& ts) const;
        wxTimeSpan& operator-=(const wxTimeSpan& diff);
        wxTimeSpan operator-(const wxTimeSpan& ts);
        wxTimeSpan& operator*=(int n);
        wxTimeSpan operator*(int n) const;
        wxTimeSpan& operator-();
        bool operator<(const wxTimeSpan &ts) const;
        bool operator<=(const wxTimeSpan &ts) const;
        bool operator>(const wxTimeSpan &ts) const;
        bool operator>=(const wxTimeSpan &ts) const;
        bool operator==(const wxTimeSpan &ts) const;
        bool operator!=(const wxTimeSpan &ts) const;
        """))

    #---------------------------------------------
    # Convert to/from Python date objects
    module.addPyFunction(
        'pydate2wxdate',
        '(date)',
        doc='Convert a Python date or datetime to a :class:`DateTime` object',
        body="""\
            import datetime
            assert isinstance(date, (datetime.datetime, datetime.date))
            return DateTime(date)  # the built-in typemap will convert it for us
        """)

    module.addPyFunction(
        'wxdate2pydate',
        '(date)',
        doc='Convert a :class:`DateTime` object to a Python datetime.',
        body="""\
            import datetime
            assert isinstance(date, DateTime)
            if date.IsValid():
                return datetime.datetime(date.year, date.month+1, date.day,
                                         date.hour, date.minute, date.second, date.millisecond*1000)
            else:
                return None
            """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Esempio n. 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.
    
    
    # ignore some of these enum values
    e = module.find('wxBitmapType')
    for i in e:
        if i.name.endswith('_RESOURCE'):
            i.ignore()
    
    module.addCppCode("""\
    #if !defined(__WXMAC__)
    #define wxCURSOR_COPY_ARROW wxCURSOR_ARROW
    #endif
    """)
    
    # these are X11 only
    e = module.find('wxStockCursor')
    e.find('wxCURSOR_BASED_ARROW_DOWN').ignore()
    e.find('wxCURSOR_BASED_ARROW_UP').ignore()
    e.find('wxCURSOR_CROSS_REVERSE').ignore()
    e.find('wxCURSOR_DOUBLE_ARROW').ignore()
    
    module.find('wxClientDisplayRect.x').out = True
    module.find('wxClientDisplayRect.y').out = True
    module.find('wxClientDisplayRect.width').out = True
    module.find('wxClientDisplayRect.height').out = True
    
    module.find('wxDisplaySize.width').out = True
    module.find('wxDisplaySize.height').out = True
    module.find('wxDisplaySizeMM.width').out = True
    module.find('wxDisplaySizeMM.height').out = True
    
    #---------------------------------------
    # wxPoint tweaks
    c = module.find('wxPoint')
    tools.addAutoProperties(c)
    
    # Some operators are documented within the class that shouldn't be, so just
    # ignore them all.
    tools.ignoreAllOperators(c)
    
    # Undo a few of those ignores for legitimate items that were 
    # documented correctly
    for f in c.find('operator+=').all() + c.find('operator-=').all():
        f.ignore(False)
        
    # Add some method declarations for operators that really do exist. Note
    # that these actually use C++ global operator functions, but we treat
    # them as methods to help disambiguate implementations due to how
    # multiple classes can be converted automatically to/from 2-element
    # sequences.    
    c.addCppMethod('bool', '__eq__', '(const wxPoint& other)',
        body="return *self == *other;")
    c.addCppMethod('bool', '__neq__', '(const wxPoint& other)',
        body="return *self != *other;")
    
    c.addItem(etgtools.WigCode("""\
        wxPoint operator+(const wxPoint& other);
        wxPoint operator-();
        wxPoint operator-(const wxPoint& other);
        wxPoint operator*(int i);
        wxPoint operator/(int i);
        """))
    
    
    # wxPoint typemap
    c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxPoint')
    
    c.addCppMethod('PyObject*', 'Get', '()', """\
        return sipBuildResult(0, "(ii)", self->x, self->y);
        """, 
        pyArgsString="() -> (x,y)",
        briefDoc="Return the x and y properties as a tuple.")
    
    # Add sequence protocol methods and other goodies
    c.addPyMethod('__str__', '(self)',             'return str(self.Get())')
    c.addPyMethod('__repr__', '(self)',            'return "wx.Point"+str(self.Get())')
    c.addPyMethod('__len__', '(self)',             'return len(self.Get())')
    c.addPyMethod('__nonzero__', '(self)',         'return self.Get() != (0,0)')
    c.addPyMethod('__reduce__', '(self)',          'return (Point, self.Get())')
    c.addPyMethod('__getitem__', '(self, idx)',    'return self.Get()[idx]')
    c.addPyMethod('__setitem__', '(self, idx, val)',
                  """\
                  if idx == 0: self.x = val
                  elif idx == 1: self.y = val
                  else: raise IndexError
                  """) 
    c.addPyCode('Point.__safe_for_unpickling__ = True')
                                    
    module.addItem(
        tools.wxListWrapperTemplate('wxPointList', 'wxPoint', module, includeConvertToType=True))
    
    
    #---------------------------------------
    # wxSize tweaks
    c = module.find('wxSize')
    tools.addAutoProperties(c)

    # Used for testing releasing or holding the GIL in giltest.py
    #c.find('wxSize').findOverload('int width, int height').releaseGIL()
    #c.find('DecBy').findOverload('int dx, int dy').releaseGIL()
    #c.find('IncBy').findOverload('int dx, int dy').releaseGIL()
        
    c.addProperty("width GetWidth SetWidth")
    c.addProperty("height GetHeight SetHeight")

    # TODO:  How prevalent is the use of x,y properties on a size object?  Can we deprecate them?
    c.addProperty("x GetWidth SetWidth")
    c.addProperty("y GetHeight SetHeight")
    
    # Take care of the same issues as wxPoint
    tools.ignoreAllOperators(c)
    for f in c.find('operator+=').all() + \
             c.find('operator-=').all() + \
             c.find('operator*=').all() + \
             c.find('operator/=').all():
        f.ignore(False)
        
    c.addCppMethod('bool', '__eq__', '(const wxSize& other)',
        body="return *self == *other;")
    c.addCppMethod('bool', '__neq__', '(const wxSize& other)',
        body="return *self != *other;")
    
    c.addItem(etgtools.WigCode("""\
        wxSize operator+(const wxSize& other);
        wxSize operator-(const wxSize& other);
        wxSize operator*(int i);
        wxSize operator/(int i);

        wxPoint operator+(const wxPoint& other);
        wxPoint operator-(const wxPoint& other);
        wxRealPoint operator+(const wxRealPoint& other);
        wxRealPoint operator-(const wxRealPoint& other);
        """))
    
    
    # wxSize typemap
    c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxSize')
    
    c.addCppMethod('PyObject*', 'Get', '()', """\
        return sipBuildResult(0, "(ii)", self->GetWidth(), self->GetHeight());
        """,
        pyArgsString="() -> (width, height)",
        briefDoc="Return the width and height properties as a tuple.")
    
    # Add sequence protocol methods and other goodies
    c.addPyMethod('__str__', '(self)',             'return str(self.Get())')
    c.addPyMethod('__repr__', '(self)',            'return "wx.Size"+str(self.Get())')
    c.addPyMethod('__len__', '(self)',             'return len(self.Get())')
    c.addPyMethod('__nonzero__', '(self)',         'return self.Get() != (0,0)')
    c.addPyMethod('__reduce__', '(self)',          'return (Size, self.Get())')
    c.addPyMethod('__getitem__', '(self, idx)',    'return self.Get()[idx]')
    c.addPyMethod('__setitem__', '(self, idx, val)',
                  """\
                  if idx == 0: self.width = val
                  elif idx == 1: self.height = val
                  else: raise IndexError
                  """) 
    c.addPyCode('Size.__safe_for_unpickling__ = True')
    
    
    
    #---------------------------------------
    # wxRect tweaks
    c = module.find('wxRect')
    assert isinstance(c, etgtools.ClassDef)
    tools.addAutoProperties(c)
    
    c.addProperty("left GetLeft SetLeft")
    c.addProperty("top GetTop SetTop")
    c.addProperty("right GetRight SetRight")
    c.addProperty("bottom GetBottom SetBottom")
    
    c.addProperty("bottomLeft GetBottomLeft SetBottomLeft")
    c.addProperty("bottomRight GetBottomRight SetBottomRight")
    c.addProperty("topLeft GetTopLeft SetTopLeft")
    c.addProperty("topRight GetTopRight SetTopRight")
    
    # take care of the same issues as wxPoint
    tools.ignoreAllOperators(c)
    for f in c.find('operator+=').all() + \
             c.find('operator*=').all():
        f.ignore(False)
                
    c.addCppMethod('bool', '__eq__', '(const wxRect& other)',
        body="return *self == *other;")
    c.addCppMethod('bool', '__neq__', '(const wxRect& other)',
        body="return *self != *other;")
    
    c.addItem(etgtools.WigCode("""\
        wxRect operator+(const wxRect& other);
        wxRect operator*(const wxRect& other);
        """))

    
    # Because of our add-ons that make wx.Point and wx.Size act like 2-element
    # sequences, and also the typecheck code that allows 2-element sequences, then
    # we end up with a bit of confusion about the (Point,Point) and the
    # (Point,Size) overloads of the wx.Rect constructor. The confusion can be
    # dealt with by using keyword args, but I think that the (Point,Size) version
    # will be used more, so reorder the overloads so it is found first.
    m = module.find('wxRect.wxRect')
    mo = m.findOverload('topLeft')
    del m.overloads[m.overloads.index(mo)]
    m.overloads.append(mo)
    
    # These methods have some overloads that will end up with the same signature
    # in Python, so we have to remove one.
    module.find('wxRect.Deflate').findOverload(') const').ignore()
    module.find('wxRect.Inflate').findOverload(') const').ignore()
    module.find('wxRect.Union').findOverload(') const').ignore()
    module.find('wxRect.Intersect').findOverload(') const').ignore()
    
    # wxRect typemap
    c.convertFromPyObject = tools.convertFourIntegersTemplate('wxRect')
    
    c.addCppMethod('PyObject*', 'Get', '()', """\
        return sipBuildResult(0, "(iiii)", 
                              self->x, self->y, self->width, self->height);
        """, 
        pyArgsString="() -> (x, y, width, height)",
        briefDoc="Return the rectangle's properties as a tuple.")
    
    # Add sequence protocol methods and other goodies
    c.addPyMethod('__str__', '(self)',             'return str(self.Get())')
    c.addPyMethod('__repr__', '(self)',            'return "wx.Rect"+str(self.Get())')
    c.addPyMethod('__len__', '(self)',             'return len(self.Get())')
    c.addPyMethod('__nonzero__', '(self)',         'return self.Get() != (0,0,0,0)')
    c.addPyMethod('__reduce__', '(self)',          'return (Rect, self.Get())')
    c.addPyMethod('__getitem__', '(self, idx)',    'return self.Get()[idx]')
    c.addPyMethod('__setitem__', '(self, idx, val)',
                  """\
                  if idx == 0: self.x = val
                  elif idx == 1: self.y = val
                  elif idx == 2: self.width = val
                  elif idx == 3: self.height = val
                  else: raise IndexError
                  """) 
    c.addPyCode('Rect.__safe_for_unpickling__ = True')
    
    
    
    #---------------------------------------
    # wxRealPoint tweaks
    c = module.find('wxRealPoint')
    tools.addAutoProperties(c)
        
    # take care of the same issues as wxPoint
    tools.ignoreAllOperators(c)
    for f in c.find('operator+=').all() + \
             c.find('operator-=').all():
        f.ignore(False)
                
    c.addCppMethod('bool', '__eq__', '(const wxRealPoint& other)',
        body="return *self == *other;")
    c.addCppMethod('bool', '__neq__', '(const wxRealPoint& other)',
        body="return *self != *other;")
    
    c.addItem(etgtools.WigCode("""\
        wxRealPoint operator+(const wxRealPoint& other);
        wxRealPoint operator-(const wxRealPoint& other);
        wxRealPoint operator*(int i);
        wxRealPoint operator/(int i);
        """))

        
    # wxRealPoint typemap
    c.convertFromPyObject = tools.convertTwoDoublesTemplate('wxRealPoint')

    c.addCppMethod('PyObject*', 'Get', '()', """\
        return sipBuildResult(0, "(dd)", self->x, self->y);
        """, 
        pyArgsString="() -> (x, y)",
        briefDoc="Return the point's properties as a tuple.")
    
    # Add sequence protocol methods and other goodies
    c.addPyMethod('__str__', '(self)',             'return str(self.Get())')
    c.addPyMethod('__repr__', '(self)',            'return "wx.RealPoint"+str(self.Get())')
    c.addPyMethod('__len__', '(self)',             'return len(self.Get())')
    c.addPyMethod('__nonzero__', '(self)',         'return self.Get() != (0,0)')
    c.addPyMethod('__reduce__', '(self)',          'return (Rect, self.Get())')
    c.addPyMethod('__getitem__', '(self, idx)',    'return self.Get()[idx]')
    c.addPyMethod('__setitem__', '(self, idx, val)',
                  """\
                  if idx == 0: self.x = val
                  elif idx == 1: self.y = val
                  else: raise IndexError
                  """) 
    c.addPyCode('RealPoint.__safe_for_unpickling__ = True')

    
    
    
    c = module.find('wxColourDatabase')
    c.addPyMethod('FindColour', '(self, colour)',    'return self.Find(colour)')   

    module.find('wxTheColourDatabase').ignore()
        
                               
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)