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

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

    module.addHeaderCode('#include <wxPython/wxpy_api.h>')
    module.addImport('_core')
    module.addPyCode('import wx', order=10)
    module.addInclude(INCLUDES)

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

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

    tools.generateStubs(
        'wxUSE_GLCANVAS',
        module,
        extraHdrCode='#define wxGLCanvasName wxT("GLCanvas")\n',
        typeValMap={
            'wxGLAttributes &': '*this',
            'wxGLContextAttrs &': '*this',
        })

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

    c = module.find('wxGLAttribsBase')
    assert isinstance(c, etgtools.ClassDef)
    c.find('GetGLAttrs').ignore()

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

    # We already have a MappedType for wxArrayInt, so just tweak the
    # interfaces to use that instead of a const int pointer.
    c.find('wxGLCanvas').findOverload('const int *attribList').ignore()
    m = c.addCppCtor_sip(
        argsString="""(
             wxWindow* parent /TransferThis/,
             wxWindowID id=wxID_ANY,
             wxArrayInt* attribList=NULL,
             const wxPoint& pos=wxDefaultPosition,
             const wxSize& size=wxDefaultSize,
             long style=0,
             const wxString& name="GLCanvas",
             const wxPalette& palette=wxNullPalette)
             """,
        cppSignature="""(
             wxWindow* parent, wxWindowID id=wxID_ANY, const int* attribList=NULL,
             const wxPoint& pos=wxDefaultPosition, const wxSize& size=wxDefaultSize,
             long style=0, const wxString& name="GLCanvas",
             const wxPalette& palette=wxNullPalette)""",
        pyArgsString=
        "(parent, id=wx.ID_ANY, attribList=None, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name='GLCanvas', palette=wx.NullPalette)",
        body="""\
            const int* attribPtr = NULL;
            if (attribList) {
                attribList->push_back(0); // ensure it is zero-terminated
                attribPtr = &attribList->front();
            }
            sipCpp = new sipwxGLCanvas(parent, id, attribPtr, *pos, *size, style, *name, *palette);
            """,
        noDerivedCtor=False,
    )

    m = c.find('IsDisplaySupported').findOverload('attribList')
    m.find('attribList').type = 'wxArrayInt*'
    m.setCppCode_sip("""\
        const int* attribPtr = NULL;
        if (attribList) {
            attribList->push_back(0); // ensure it is zero-terminated
            attribPtr = &attribList->front();
        }
        sipRes = wxGLCanvas::IsDisplaySupported(attribPtr);
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #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('wxImage')
    assert isinstance(c, etgtools.ClassDef)
    c.find('wxImage').findOverload('(const char *const *xpmData)').ignore()

    c.find('GetHandlers').ignore()  # TODO

    # Ignore the ctors taking raw data buffers, so we can add in our own
    # versions that are a little smarter (accept any buffer object, check
    # the data length, etc.)
    c.find('wxImage').findOverload(
        'int width, int height, unsigned char *data, bool static_data').ignore(
        )
    c.find('wxImage').findOverload(
        'const wxSize &sz, unsigned char *data, bool static_data').ignore()
    c.find('wxImage').findOverload(
        'int width, int height, unsigned char *data, unsigned char *alpha, bool static_data'
    ).ignore()
    c.find('wxImage').findOverload(
        'const wxSize &sz, unsigned char *data, unsigned char *alpha, bool static_data'
    ).ignore()

    c.addCppCtor_sip('(int width, int height, wxPyBuffer* data)',
                     doc="Creates an image from RGB data in memory.",
                     body="""\
            if (! data->checkSize(width*height*3)) 
                return NULL;
            void* copy = data->copy();
            if (! copy) 
                return NULL;
            sipCpp = new sipwxImage;
            sipCpp->Create(width, height, (byte*)copy);            
            """)

    c.addCppCtor_sip(
        '(int width, int height, wxPyBuffer* data, wxPyBuffer* alpha)',
        doc="Creates an image from RGB data in memory, plus an alpha channel",
        body="""\
            void* dcopy; void* acopy;
            if (!data->checkSize(width*height*3) || !alpha->checkSize(width*height))
                return NULL;
            if ((dcopy = data->copy()) == NULL || (acopy = alpha->copy()) == NULL)
                return NULL;
            sipCpp = new sipwxImage;
            sipCpp->Create(width, height, (byte*)dcopy, (byte*)acopy, false);
            """)

    c.addCppCtor_sip('(const wxSize& size, wxPyBuffer* data)',
                     doc="Creates an image from RGB data in memory.",
                     body="""\
            if (! data->checkSize(size->x*size->y*3)) 
                return NULL;
            void* copy = data->copy();
            if (! copy) 
                return NULL;
            sipCpp = new sipwxImage;
            sipCpp->Create(size->x, size->y, (byte*)copy, false);
            """)

    c.addCppCtor_sip(
        '(const wxSize& size, wxPyBuffer* data, wxPyBuffer* alpha)',
        doc="Creates an image from RGB data in memory, plus an alpha channel",
        body="""\
            void* dcopy; void* acopy;
            if (!data->checkSize(size->x*size->y*3) || !alpha->checkSize(size->x*size->y))
                return NULL;
            if ((dcopy = data->copy()) == NULL || (acopy = alpha->copy()) == NULL)
                return NULL;
            sipCpp = new sipwxImage;
            sipCpp->Create(size->x, size->y, (byte*)dcopy, (byte*)acopy, false);
            """)

    # Do the same for the Create method overloads that need to deal with data buffers
    c.find('Create').findOverload(
        'int width, int height, unsigned char *data, bool static_data').ignore(
        )
    c.find('Create').findOverload(
        'const wxSize &sz, unsigned char *data, bool static_data').ignore()
    c.find('Create').findOverload(
        'int width, int height, unsigned char *data, unsigned char *alpha, bool static_data'
    ).ignore()
    c.find('Create').findOverload(
        'const wxSize &sz, unsigned char *data, unsigned char *alpha, bool static_data'
    ).ignore()

    c.addCppMethod(
        'bool',
        'Create',
        '(int width, int height, wxPyBuffer* data)',
        doc="Create a new image initialized with the given RGB data.",
        body="""\
            if (! data->checkSize(width*height*3)) 
                return false;
            void* copy = data->copy();
            if (! copy) 
                return false;
            return self->Create(width, height, (byte*)copy);
            """)

    c.addCppMethod(
        'bool',
        'Create',
        '(int width, int height, wxPyBuffer* data, wxPyBuffer* alpha)',
        doc=
        "Create a new image initialized with the given RGB data and Alpha data.",
        body="""\
            void* dcopy; void* acopy;
            if (!data->checkSize(width*height*3) || !alpha->checkSize(width*height))
                return false;
            if ((dcopy = data->copy()) == NULL || (acopy = alpha->copy()) == NULL)
                return false;
            return self->Create(width, height, (byte*)dcopy, (byte*)acopy);
            """)

    c.addCppMethod(
        'bool',
        'Create',
        '(const wxSize& size, wxPyBuffer* data)',
        doc="Create a new image initialized with the given RGB data.",
        body="""\
            if (! data->checkSize(size->x*size->y*3)) 
                return false;
            void* copy = data->copy();
            if (! copy) 
                return false;
            return self->Create(size->x, size->y, (byte*)copy);
            """)

    c.addCppMethod(
        'bool',
        'Create',
        '(const wxSize& size, wxPyBuffer* data, wxPyBuffer* alpha)',
        doc=
        "Create a new image initialized with the given RGB data and Alpha data.",
        body="""\
            void* dcopy; void* acopy;
            if (!data->checkSize(size->x*size->y*3) || !alpha->checkSize(size->x*size->y))
                return false;
            if ((dcopy = data->copy()) == NULL || (acopy = alpha->copy()) == NULL)
                return false;
            return self->Create(size->x, size->y, (byte*)dcopy, (byte*)acopy);
            """)

    # And also do similar for SetData and SetAlpha
    m = c.find('SetData').findOverload('unsigned char *data')
    bd, dd = m.briefDoc, m.detailedDoc
    m.ignore()
    c.addCppMethod('void',
                   'SetData',
                   '(wxPyBuffer* data)',
                   briefDoc=bd,
                   detailedDoc=dd,
                   body="""\
        if (!data->checkSize(self->GetWidth()*self->GetHeight()*3))
            return;
        void* copy = data->copy();
        if (!copy)
            return;
        self->SetData((byte*)copy, false);
        """)

    c.find('SetData').findOverload('int new_width').ignore()
    c.addCppMethod('void',
                   'SetData',
                   '(wxPyBuffer* data, int new_width, int new_height)',
                   body="""\
        if (!data->checkSize(new_width*new_height*3))
            return;
        void* copy = data->copy();
        if (!copy)
            return;
        self->SetData((byte*)copy, new_width, new_height, false);
        """)

    m = c.find('SetAlpha').findOverload('unsigned char *alpha')
    bd, dd = m.briefDoc, m.detailedDoc
    m.ignore()
    c.addCppMethod('void',
                   'SetAlpha',
                   '(wxPyBuffer* alpha)',
                   briefDoc=bd,
                   detailedDoc=dd,
                   body="""\
        if (!alpha->checkSize(self->GetWidth()*self->GetHeight()))
            return;
        void* copy = alpha->copy();
        if (!copy)
            return;
        self->SetAlpha((byte*)copy, false);
        """)

    # GetData() and GetAlpha() return a copy of the image data/alpha bytes as
    # a bytearray object.
    c.find('GetData').ignore()
    c.addCppMethod('PyObject*',
                   'GetData',
                   '()',
                   doc="Returns a copy of the RGB bytes of the image.",
                   body="""\
            byte* data = self->GetData();
            Py_ssize_t len = self->GetWidth() * self->GetHeight() * 3;
            PyObject* rv = NULL;
            wxPyBLOCK_THREADS( rv = PyByteArray_FromStringAndSize((const char*)data, len));
            return rv;           
            """)

    c.find('GetAlpha').findOverload('()').ignore()
    c.addCppMethod('PyObject*',
                   'GetAlpha',
                   '()',
                   doc="Returns a copy of the Alpha bytes of the image.",
                   body="""\
            byte* data = self->GetAlpha();
            Py_ssize_t len = self->GetWidth() * self->GetHeight();
            PyObject* rv = NULL;
            wxPyBLOCK_THREADS( rv = PyByteArray_FromStringAndSize((const char*)data, len));
            return rv;           
            """)

    # GetDataBuffer, GetAlphaBuffer provide direct access to the image's
    # internal buffers as a writable buffer object.  We'll use memoryview
    # objects.
    c.addCppMethod('PyObject*',
                   'GetDataBuffer',
                   '()',
                   doc="""\
        Returns a writable Python buffer object that is pointing at the RGB
        image data buffer inside the :class:`Image`. You need to ensure that you do
        not use this buffer object after the image has been destroyed.""",
                   body="""\
            byte* data = self->GetData();
            Py_ssize_t len = self->GetWidth() * self->GetHeight() * 3;
            PyObject* rv;
            wxPyThreadBlocker blocker;
            rv = wxPyMakeBuffer(data, len);
            return rv;
            """)

    c.addCppMethod('PyObject*',
                   'GetAlphaBuffer',
                   '()',
                   doc="""\
        Returns a writable Python buffer object that is pointing at the Alpha
        data buffer inside the :class:`Image`. You need to ensure that you do
        not use this buffer object after the image has been destroyed.""",
                   body="""\
            byte* data = self->GetAlpha();
            Py_ssize_t len = self->GetWidth() * self->GetHeight();
            PyObject* rv;
            wxPyThreadBlocker blocker;
            rv = wxPyMakeBuffer(data, len);
            return rv;
            """)

    # SetDataBuffer, SetAlphaBuffer tell the image to use some other memory
    # buffer pointed to by a Python buffer object.
    c.addCppMethod('void',
                   'SetDataBuffer',
                   '(wxPyBuffer* data)',
                   doc="""\
        Sets the internal image data pointer to point at a Python buffer
        object.  This can save making an extra copy of the data but you must
        ensure that the buffer object lives lives at least as long as the 
        :class:`Image` does.""",
                   body="""\
            if (!data->checkSize(self->GetWidth() * self->GetHeight() * 3))
                return;
            // True means don't free() the pointer
            self->SetData((byte*)data->m_ptr, true);  
            """)
    c.addCppMethod('void',
                   'SetDataBuffer',
                   '(wxPyBuffer* data, int new_width, int new_height)',
                   doc="""\
        Sets the internal image data pointer to point at a Python buffer
        object.  This can save making an extra copy of the data but you must
        ensure that the buffer object lives lives at least as long as the 
        :class:`Image` does.""",
                   body="""\
            if (!data->checkSize(new_width * new_height * 3))
                return;
            // True means don't free() the pointer
            self->SetData((byte*)data->m_ptr, new_width, new_height, true);  
            """)

    c.addCppMethod('void',
                   'SetAlphaBuffer',
                   '(wxPyBuffer* alpha)',
                   doc="""\
        Sets the internal image alpha pointer to point at a Python buffer
        object.  This can save making an extra copy of the data but you must
        ensure that the buffer object lives lives at least as long as the 
        :class:`Image` does.""",
                   body="""\
            if (!alpha->checkSize(self->GetWidth() * self->GetHeight()))
                return;
            // True means don't free() the pointer
            self->SetAlpha((byte*)alpha->m_ptr, true);
            """)

    def setParamsPyInt(name):
        """Set the pyInt flag on 'unsigned char' params"""
        method = c.find(name)
        for m in [method] + method.overloads:
            for p in m.items:
                if p.type == 'unsigned char':
                    p.pyInt = True

    setParamsPyInt('Replace')
    setParamsPyInt('ConvertAlphaToMask')
    setParamsPyInt('ConvertToMono')
    setParamsPyInt('ConvertToDisabled')
    setParamsPyInt('IsTransparent')
    setParamsPyInt('SetAlpha')
    setParamsPyInt('SetMaskColour')
    setParamsPyInt('SetMaskFromImage')
    setParamsPyInt('SetRGB')

    c.find('FindFirstUnusedColour').type = 'void'
    c.find('FindFirstUnusedColour.r').pyInt = True
    c.find('FindFirstUnusedColour.g').pyInt = True
    c.find('FindFirstUnusedColour.b').pyInt = True
    c.find('FindFirstUnusedColour.startR').pyInt = True
    c.find('FindFirstUnusedColour.startG').pyInt = True
    c.find('FindFirstUnusedColour.startB').pyInt = True
    c.find('FindFirstUnusedColour.r').out = True
    c.find('FindFirstUnusedColour.g').out = True
    c.find('FindFirstUnusedColour.b').out = True

    c.find('GetAlpha').findOverload('int x, int y').pyInt = True
    c.find('GetRed').pyInt = True
    c.find('GetGreen').pyInt = True
    c.find('GetBlue').pyInt = True
    c.find('GetMaskRed').pyInt = True
    c.find('GetMaskGreen').pyInt = True
    c.find('GetMaskBlue').pyInt = True

    c.find('GetOrFindMaskColour').type = 'void'
    c.find('GetOrFindMaskColour.r').pyInt = True
    c.find('GetOrFindMaskColour.g').pyInt = True
    c.find('GetOrFindMaskColour.b').pyInt = True
    c.find('GetOrFindMaskColour.r').out = True
    c.find('GetOrFindMaskColour.g').out = True
    c.find('GetOrFindMaskColour.b').out = True

    c.find('RGBValue.red').pyInt = True
    c.find('RGBValue.green').pyInt = True
    c.find('RGBValue.blue').pyInt = True
    c.find('RGBValue.RGBValue.r').pyInt = True
    c.find('RGBValue.RGBValue.g').pyInt = True
    c.find('RGBValue.RGBValue.b').pyInt = True

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

    c.addPyMethod('ConvertToBitmap',
                  '(self, depth=-1)',
                  doc="""\
        ConvertToBitmap(depth=-1) -> Bitmap\n
        Convert the image to a :class:`Bitmap`.""",
                  body="""\
        bmp = wx.Bitmap(self, depth)
        return bmp
        """)

    c.addPyMethod('ConvertToMonoBitmap',
                  '(self, red, green, blue)',
                  doc="""\
        ConvertToMonoBitmap(red, green, blue) -> Bitmap\n
        Creates a monochrome version of the image and returns it as a :class:`Bitmap`.""",
                  body="""\
        mono = self.ConvertToMono( red, green, blue )
        bmp = wx.Bitmap( mono, 1 )
        return bmp    
        """)

    c.addCppMethod(
        'wxImage*',
        'AdjustChannels',
        '(double factor_red, double factor_green, double factor_blue, double factor_alpha=1.0)',
        doc="""\
        This function muliplies all 4 channels (red, green, blue, alpha) with
        a factor (around 1.0). Useful for gamma correction, colour correction
        and to add a certain amount of transparency to a image (fade in fade
        out effects). If factor_alpha is given but the original image has no
        alpha channel then a alpha channel will be added.
        """,
        body="""\
        wxCHECK_MSG( self->Ok(), NULL, wxT("invalid image") );

        wxImage* dest = new wxImage( self->GetWidth(), self->GetHeight(), false );
        wxCHECK_MSG( dest && dest->IsOk(), NULL, wxT("unable to create image") );

        unsigned rgblen =   3 * self->GetWidth() * self->GetHeight();
        unsigned alphalen = self->GetWidth() * self->GetHeight();
        byte* src_data =  self->GetData();
        byte* src_alpha = self->GetAlpha();
        byte* dst_data =  dest->GetData();
        byte* dst_alpha = NULL;

        // adjust rgb
        if ( factor_red == 1.0 && factor_green == 1.0 && factor_blue == 1.0)
        {
            // nothing to do for RGB
            memcpy(dst_data, src_data, rgblen);
        }
        else
        {
            // rgb pixel for pixel
            for ( unsigned i = 0; i < rgblen; i= i + 3 )
            {
                dst_data[i] =     (byte) wxMin( 255, (int) (factor_red * src_data[i]) );
                dst_data[i + 1] = (byte) wxMin( 255, (int) (factor_green * src_data[i + 1]) );
                dst_data[i + 2] = (byte) wxMin( 255, (int) (factor_blue * src_data[i + 2]) );
            }
        }

        // adjust the mask colour
        if ( self->HasMask() )
        {
            dest->SetMaskColour((byte) wxMin( 255, (int) (factor_red * self->GetMaskRed() ) ),
                                (byte) wxMin( 255, (int) (factor_green * self->GetMaskGreen() ) ),
                                (byte) wxMin( 255, (int) (factor_blue * self->GetMaskBlue() ) ) );
        }

        // adjust the alpha channel
        if ( src_alpha )
        {
            // source image already has alpha information
            dest->SetAlpha(); // create an empty alpha channel (not initialized)
            dst_alpha = dest->GetAlpha();

            wxCHECK_MSG( dst_alpha, NULL, wxT("unable to create alpha data") );

            if ( factor_alpha == 1.0)
            {
                // no need to adjust
                memcpy(dst_alpha, src_alpha, alphalen);
            }
            else
            {
                // alpha value for alpha value
                for ( unsigned i = 0; i < alphalen; ++i )
                {
                    dst_alpha[i] = (byte) wxMin( 255, (int) (factor_alpha * src_alpha[i]) );
                }
            }
        }
        else if ( factor_alpha != 1.0 )
        {
            // no alpha yet but we want to adjust -> create
            dest->SetAlpha(); // create an empty alpha channel (not initialized)
            dst_alpha = dest->GetAlpha();
    
            wxCHECK_MSG( dst_alpha, NULL, wxT("unable to create alpha data") );
    
            for ( unsigned i = 0; i < alphalen; ++i )
            {
                dst_alpha[i] = (byte) wxMin( 255, (int) (factor_alpha * 255) );
            }
        }

        // do we have an alpha channel and a mask in the new image?
        if ( dst_alpha && dest->HasMask() )
        {
            // make the mask transparent honoring the alpha channel
            const byte mr = dest->GetMaskRed();
            const byte mg = dest->GetMaskGreen();
            const byte mb = dest->GetMaskBlue();

            for ( unsigned i = 0; i < alphalen; ++i )
            {
                int n = i * 3;
                dst_alpha[i] = ( dst_data[n] == mr && dst_data[n + 1] == mg && dst_data[n + 2] == mb )
                    ? wxIMAGE_ALPHA_TRANSPARENT
                    : dst_alpha[i];
            }

            // remove the mask now
            dest->SetMask(false);
        }

        return dest;""",
        factory=True)

    c.addProperty('Width GetWidth')
    c.addProperty('Height GetHeight')
    c.addProperty('MaskBlue GetMaskBlue')
    c.addProperty('MaskGreen GetMaskGreen')
    c.addProperty('MaskRed GetMaskRed')
    c.addProperty('Type GetType SetType')

    # For compatibility:
    module.addPyFunction(
        'EmptyImage',
        '(width=0, height=0, clear=True)',
        deprecated="Use :class:`Image` instead.",
        doc=
        'A compatibility wrapper for the wx.Image(width, height) constructor',
        body='return Image(width, height, clear)')

    module.addPyFunction('ImageFromBitmap',
                         '(bitmap)',
                         deprecated="Use bitmap.ConvertToImage instead.",
                         doc='Create a :class:`Image` from a :class:`Bitmap`',
                         body='return bitmap.ConvertToImage()')

    module.addPyFunction('ImageFromStream',
                         '(stream, type=BITMAP_TYPE_ANY, index=-1)',
                         deprecated="Use :class:`Image` instead.",
                         doc='Load an image from a stream (file-like object)',
                         body='return wx.Image(stream, type, index)')

    module.addPyFunction(
        'ImageFromData',
        '(width, height, data)',
        deprecated="Use :class:`Image` instead.",
        doc='Compatibility wrapper for creating an image from RGB data',
        body='return Image(width, height, data)')

    module.addPyFunction(
        'ImageFromDataWithAlpha',
        '(width, height, data, alpha)',
        deprecated="Use :class:`Image` instead.",
        doc=
        'Compatibility wrapper for creating an image from RGB and Alpha data',
        body='return Image(width, height, data, alpha)')

    module.addPyFunction('ImageFromBuffer',
                         '(width, height, dataBuffer, alphaBuffer=None)',
                         doc="""\
            Creates a :class:`Image` from the data in `dataBuffer`.  The `dataBuffer`
            parameter must be a Python object that implements the buffer interface,
            such as a string, array, etc.  The `dataBuffer` object is expected to
            contain a series of RGB bytes and be width*height*3 bytes long.  A buffer
            object can optionally be supplied for the image's alpha channel data, and
            it is expected to be width*height bytes long.
        
            The :class:`Image` will be created with its data and alpha pointers initialized
            to the memory address pointed to by the buffer objects, thus saving the
            time needed to copy the image data from the buffer object to the :class:`Image`.
            While this has advantages, it also has the shoot-yourself-in-the-foot
            risks associated with sharing a C pointer between two objects.
        
            To help alleviate the risk a reference to the data and alpha buffer
            objects are kept with the :class:`Image`, so that they won't get deleted until
            after the wx.Image is deleted.  However please be aware that it is not
            guaranteed that an object won't move its memory buffer to a new location
            when it needs to resize its contents.  If that happens then the :class:`Image`
            will end up referring to an invalid memory location and could cause the
            application to crash.  Therefore care should be taken to not manipulate
            the objects used for the data and alpha buffers in a way that would cause
            them to change size.
            """,
                         body="""\
            img = Image(width, height)
            img.SetDataBuffer(dataBuffer)
            if alphaBuffer:
                img.SetAlphaBuffer(alphaBuffer)
            img._buffer = dataBuffer
            img._alpha = alphaBuffer
            return img
            """)

    #-------------------------------------------------------
    c = module.find('wxImageHistogram')
    c.bases = ['wxObject']
    setParamsPyInt('MakeKey')
    c.find('FindFirstUnusedColour').type = 'void'
    c.find('FindFirstUnusedColour.r').pyInt = True
    c.find('FindFirstUnusedColour.g').pyInt = True
    c.find('FindFirstUnusedColour.b').pyInt = True
    c.find('FindFirstUnusedColour.startR').pyInt = True
    c.find('FindFirstUnusedColour.startG').pyInt = True
    c.find('FindFirstUnusedColour.startB').pyInt = True
    c.find('FindFirstUnusedColour.r').out = True
    c.find('FindFirstUnusedColour.g').out = True
    c.find('FindFirstUnusedColour.b').out = True

    #-------------------------------------------------------
    c = module.find('wxImageHandler')
    c.abstract = True
    c.addPrivateCopyCtor()
    c.find('GetLibraryVersionInfo').ignore()

    c.find('DoGetImageCount').ignore(False)
    c.find('DoCanRead').ignore(False)

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

    module.find('wxIMAGE_ALPHA_TRANSPARENT').pyInt = True
    module.find('wxIMAGE_ALPHA_OPAQUE').pyInt = True
    module.find('wxIMAGE_ALPHA_THRESHOLD').pyInt = True

    # These are defines for string objects, not integers, so we can't
    # generate code for them the same way as integer values. Since they are
    # #defines we can't just tell SIP that they are global wxString objects
    # because it will then end up taking the address of temporary values when
    # it makes the getters for them. So instead we'll just make some python
    # code to insert into the .py module and hope that the interface file
    # always has the correct values of these options.
    pycode = ""
    for item in module:
        if 'IMAGE_OPTION' in item.name and isinstance(item,
                                                      etgtools.DefineDef):
            item.ignore()
            name = tools.removeWxPrefix(item.name)
            value = item.value
            for txt in ['wxString(', 'wxT(', ')']:
                value = value.replace(txt, '')

            pycode += '%s = %s\n' % (name, value)
    module.addPyCode(pycode)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #3
0
ファイル: choicdlg.py プロジェクト: wangdyna/wxPython
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('wxMultiChoiceDialog')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixTopLevelWindowClass(c)
    
    
    
    c = module.find('wxSingleChoiceDialog')
    tools.fixTopLevelWindowClass(c)
    
    # Make a new class so we can ignore the clientData parameter in the 
    c.addHeaderCode("""\
    class wxPySingleChoiceDialog : public wxSingleChoiceDialog {
    public:
        wxPySingleChoiceDialog(wxWindow* parent,
                               const wxString& message,
                               const wxString& caption,
                               const wxArrayString& choices,
                               long style = wxCHOICEDLG_STYLE,
                               const wxPoint& pos = wxDefaultPosition)
            : wxSingleChoiceDialog(parent, message, caption, choices, (void**)NULL, style, pos)
            {}
    };
    """)
    
    for item in c.allItems():  
        if item.name == 'wxSingleChoiceDialog':
            item.name = 'wxPySingleChoiceDialog' 
    c.pyName = 'SingleChoiceDialog'

    # ignore this ctor
    c.find('wxPySingleChoiceDialog').findOverload('int n').ignore()

    # and ignore the clientData param in this one
    ctor = c.find('wxPySingleChoiceDialog').findOverload('wxArrayString')
    ctor.find('clientData').ignore()

    c.find('GetSelectionData').ignore()
    

    # ignore a bunch of the standalone functions
    for f in module.find('wxGetSingleChoiceIndex').all():
        f.ignore()
    for f in module.find('wxGetSingleChoiceData').all():
        f.ignore()
    for f in module.find('wxGetSelectedChoices').all():  # TODO, it might be nice to keep this one
        f.ignore()
        
    # keep just the overloads of this function that use wxArrayString, and
    # ignore the ones that have "int n"
    for func in module.find('wxGetSingleChoice').all():
        for p in func:
            if p.type == 'int' and p.name == 'n':
                func.ignore()
                
            
    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #4
0
ファイル: toolbar.py プロジェクト: oneApple/Phoenix
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.insertItem(0, etgtools.WigCode("""\
        // forward declarations
        class wxToolBarBase;
        """))

    # Use wxPyUserData for the clientData values instead of a plain wxObject
    def _fixClientData(c):
        for item in c.allItems():
            if isinstance(item, etgtools.ParamDef) and item.name == 'clientData':
                item.type = 'wxPyUserData*'
                item.transfer = True
                      
                                           
    #---------------------------------------------                
    c = module.find('wxToolBarToolBase')
    assert isinstance(c, etgtools.ClassDef)
    c.abstract = True
    _fixClientData(c)

    gcd = c.find('GetClientData')
    gcd.type = 'wxPyUserData*'
    gcd.setCppCode('return dynamic_cast<wxPyUserData*>(self->GetClientData());')

    
   
    #---------------------------------------------                
    c = module.find('wxToolBar')
    tools.fixWindowClass(c)
    _fixClientData(c)
    c.find('SetBitmapResource').ignore()
    module.addGlobalStr('wxToolBarNameStr', c)

    gcd = c.find('GetToolClientData')
    gcd.type = 'wxPyUserData*'
    gcd.setCppCode('return dynamic_cast<wxPyUserData*>(self->GetToolClientData(toolId));')

    c.find('AddTool.tool').transfer = True
    c.find('InsertTool.tool').transfer = True

    c.find('OnLeftClick').ignore()
    c.find('OnMouseEnter').ignore()
    c.find('OnRightClick').ignore()
    c.find('OnLeftClick').ignore()


    # Add some deprecated methods to aid with Classic compatibility.
    # TODO: Which others are commonly enough used that they should be here too?
    c.addPyMethod('AddSimpleTool', '(self, toolId, bitmap, shortHelpString="", longHelpString="", isToggle=0)',
        doc='Old style method to add a tool to the toolbar.',
        deprecated='Use :meth:`AddTool` instead.',
        body="""\
            kind = wx.ITEM_NORMAL
            if isToggle: kind = wx.ITEM_CHECK
            return self.AddTool(toolId, '', bitmap, wx.NullBitmap, kind,
                                shortHelpString, longHelpString)
            """)
    c.addPyMethod('AddLabelTool', 
                  '(self, id, label, bitmap, bmpDisabled=wx.NullBitmap, kind=wx.ITEM_NORMAL,'
                  ' shortHelp="", longHelp="", clientData=None)',
        doc='Old style method to add a tool in the toolbar.',
        deprecated='Use :meth:`AddTool` instead.',
        body="""\
            return self.AddTool(id, label, bitmap, bmpDisabled, kind,
                                shortHelp, longHelp, clientData)
            """)

    c.addPyMethod('InsertSimpleTool', '(self, pos, toolId, bitmap, shortHelpString="", longHelpString="", isToggle=0)',
        doc='Old style method to insert a tool in the toolbar.',
        deprecated='Use :meth:`InsertTool` instead.',
        body="""\
            kind = wx.ITEM_NORMAL
            if isToggle: kind = wx.ITEM_CHECK
            return self.InsertTool(pos, toolId, '', bitmap, wx.NullBitmap, kind,
                                   shortHelpString, longHelpString)
            """)
    c.addPyMethod('InsertLabelTool', 
                  '(self, pos, id, label, bitmap, bmpDisabled=wx.NullBitmap, kind=wx.ITEM_NORMAL,'
                  ' shortHelp="", longHelp="", clientData=None)',
        doc='Old style method to insert a tool in the toolbar.',
        deprecated='Use :meth:`InsertTool` instead.',
        body="""\
            return self.InsertTool(pos, id, label, bitmap, bmpDisabled, kind,
                                   shortHelp, longHelp, clientData)
            """)




    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #5
0
ファイル: webview.py プロジェクト: ztq2016/Phoenix
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)

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

    module.addHeaderCode("""\
        #include <wx/webview.h>
        #if wxUSE_WEBVIEW_IE && defined(__WXMSW__)
            #include <wx/msw/webview_ie.h>
        #endif
        """)
    module.addHeaderCode('#include <wx/filesys.h>')

    module.addGlobalStr('wxWebViewBackendDefault', 0)
    module.addGlobalStr('wxWebViewBackendIE', 0)
    module.addGlobalStr('wxWebViewBackendWebKit', 0)
    module.addGlobalStr('wxWebViewNameStr', 0)
    module.addGlobalStr('wxWebViewDefaultURLStr', 0)

    # This tweak is needed only for the stub code
    module.find('wxWebViewHandler.wxWebViewHandler'
                ).argsString = '(const wxString& scheme="")'

    tools.generateStubs('wxUSE_WEBVIEW',
                        module,
                        typeValMap={
                            'wxWebViewNavigationActionFlags':
                            'wxWEBVIEW_NAV_ACTION_NONE'
                        })

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

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

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

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

    c.find('RunScript.output').out = True

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

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

    c.find('MSWSetModernEmulationLevel').setCppCode("""\
        #if wxUSE_WEBVIEW_IE && defined(__WXMSW__)
            return wxWebViewIE::MSWSetModernEmulationLevel(modernLevel);
        #else
            return false;
        #endif
        """)

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

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

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

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

    for name in [
            'wxWebViewHandler', 'wxWebViewArchiveHandler', 'wxWebViewFSHandler'
    ]:
        c = module.find(name)
        c.find('GetFile').factory = True

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #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.addHeaderCode('#include <wx/taskbar.h>')

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

    module.addPyCode("""\
        EVT_TASKBAR_MOVE = wx.PyEventBinder (         wxEVT_TASKBAR_MOVE )
        EVT_TASKBAR_LEFT_DOWN = wx.PyEventBinder (    wxEVT_TASKBAR_LEFT_DOWN )
        EVT_TASKBAR_LEFT_UP = wx.PyEventBinder (      wxEVT_TASKBAR_LEFT_UP )
        EVT_TASKBAR_RIGHT_DOWN = wx.PyEventBinder (   wxEVT_TASKBAR_RIGHT_DOWN )
        EVT_TASKBAR_RIGHT_UP = wx.PyEventBinder (     wxEVT_TASKBAR_RIGHT_UP )
        EVT_TASKBAR_LEFT_DCLICK = wx.PyEventBinder (  wxEVT_TASKBAR_LEFT_DCLICK )
        EVT_TASKBAR_RIGHT_DCLICK = wx.PyEventBinder ( wxEVT_TASKBAR_RIGHT_DCLICK )
        EVT_TASKBAR_CLICK =  wx.PyEventBinder (       wxEVT_TASKBAR_CLICK )
        EVT_TASKBAR_BALLOON_TIMEOUT = wx.PyEventBinder ( wxEVT_TASKBAR_BALLOON_TIMEOUT )
        EVT_TASKBAR_BALLOON_CLICK = wx.PyEventBinder ( wxEVT_TASKBAR_BALLOON_CLICK )
        """)

    c = module.find('wxTaskBarIcon')
    c.mustHaveApp()
    method = c.find('CreatePopupMenu')
    method.ignore(False)
    method.transfer = True
    method.virtualCatcherCode = """\
        // VirtualCatcherCode for wxTaskBarIcon.CreatePopupMenu
        PyObject *sipResObj = sipCallMethod(0, sipMethod, "");
        sipParseResult(0, sipMethod, sipResObj, "H0", sipType_wxMenu, &sipRes);
        if (sipRes) {
            sipTransferTo(sipResObj, Py_None);
        }
        """

    c.find('Destroy').transferThis = True

    c.addCppMethod('bool',
                   'ShowBalloon',
                   '(const wxString& title, const wxString& text,'
                   'unsigned msec = 0, int flags = 0)',
                   doc="""\
            Show a balloon notification (the icon must have been already
            initialized using SetIcon).  Only implemented for Windows.

            The ``title`` and ``text`` parameters are limited to 63 and 255
            characters respectively, ``msec`` is the timeout, in milliseconds,
            before the balloon disappears (will be clamped down to the allowed
            10-30s range by Windows if it's outside it) and ``flags`` can
            include wxICON_ERROR/INFO/WARNING to show a corresponding icon.

            Returns ``True`` if balloon was shown, ``False`` on error (incorrect
            parameters or function unsupported by OS).
            """,
                   body="""\
            #ifdef __WXMSW__
                return self->ShowBalloon(*title, *text, msec, flags);
            #else
                return false;
            #endif
            """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #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.

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

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

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

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

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


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

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

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


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


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

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

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

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



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


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #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)
    module.check4unittest = False

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

    module.addHeaderCode('#include <wxPython/wxpy_api.h>')

    module.addInclude(INCLUDES)
    module.includePyCode('src/core_ex.py', order=10)

    module.addPyFunction('version', '()',
        doc="""Returns a string containing version and port info""",
        body="""\
            if wx.Port == '__WXMSW__':
                port = 'msw'
            elif wx.Port == '__WXMAC__':
                if 'wxOSX-carbon' in wx.PlatformInfo:
                    port = 'osx-carbon'
                else:
                    port = 'osx-cocoa'
            elif wx.Port == '__WXGTK__':
                port = 'gtk'
                if 'gtk2' in wx.PlatformInfo:
                    port = 'gtk2'
                elif 'gtk3' in wx.PlatformInfo:
                    port = 'gtk3'
            else:
                port = '???'
            return "%s %s (phoenix) %s" % (wx.VERSION_STRING, port, wx.wxWidgets_version)
            """)


    module.addPyFunction('CallAfter', '(callableObj, *args, **kw)', doc="""\
            Call the specified function after the current and pending event
            handlers have been completed.  This is also good for making GUI
            method calls from non-GUI threads.  Any extra positional or
            keyword args are passed on to the callable when it is called.

            :param PyObject callableObj: the callable object
            :param args: arguments to be passed to the callable object
            :param kw: keywords to be passed to the callable object

            .. seealso::
                :ref:`wx.CallLater`

            """,
        body="""\
            assert callable(callableObj), "callableObj is not callable"
            app = wx.GetApp()
            assert app is not None, 'No wx.App created yet'

            if not hasattr(app, "_CallAfterId"):
                app._CallAfterId = wx.NewEventType()
                app.Connect(-1, -1, app._CallAfterId,
                            lambda event: event.callable(*event.args, **event.kw) )
            evt = wx.PyEvent()
            evt.SetEventType(app._CallAfterId)
            evt.callable = callableObj
            evt.args = args
            evt.kw = kw
            wx.PostEvent(app, evt)""")


    module.addPyClass('CallLater', ['object'],
        doc="""\
            A convenience class for :class:`wx.Timer`, that calls the given callable
            object once after the given amount of milliseconds, passing any
            positional or keyword args.  The return value of the callable is
            available after it has been run with the :meth:`~wx.CallLater.GetResult`
            method.

            If you don't need to get the return value or restart the timer
            then there is no need to hold a reference to this object. CallLater
            maintains references to its instances while they are running. When they
            finish, the internal reference is deleted and the GC is free to collect
            naturally.

            .. seealso::
                :func:`wx.CallAfter`

            """,
        items = [
            PyCodeDef('__instances = {}'),
            PyFunctionDef('__init__', '(self, millis, callableObj, *args, **kwargs)',
                doc="""\
                    Constructs a new :class:`wx.CallLater` object.

                    :param int millis: number of milliseconds to delay until calling the callable object
                    :param PyObject callableObj: the callable object
                    :param args: arguments to be passed to the callable object
                    :param kw: keyword arguments to be passed to the callable object
                """,

                body="""\
                    assert callable(callableObj), "callableObj is not callable"
                    self.millis = millis
                    self.callable = callableObj
                    self.SetArgs(*args, **kwargs)
                    self.runCount = 0
                    self.running = False
                    self.hasRun = False
                    self.result = None
                    self.timer = None
                    self.Start()"""),

            PyFunctionDef('__del__', '(self)', 'self.Stop()'),

            PyFunctionDef('Start', '(self, millis=None, *args, **kwargs)',
                doc="""\
                    (Re)start the timer

                    :param int millis: number of milli seconds
                    :param args: arguments to be passed to the callable object
                    :param kw: keywords to be passed to the callable object

                    """,
                body="""\
                    self.hasRun = False
                    if millis is not None:
                        self.millis = millis
                    if args or kwargs:
                        self.SetArgs(*args, **kwargs)
                    self.Stop()
                    CallLater.__instances[self] = "value irrelevant"  # Maintain a reference to avoid GC
                    self.timer = wx.PyTimer(self.Notify)
                    self.timer.Start(self.millis, wx.TIMER_ONE_SHOT)
                    self.running = True"""),
            PyCodeDef('Restart = Start'),

            PyFunctionDef('Stop', '(self)',
                doc="Stop and destroy the timer.",
                body="""\
                    if self in CallLater.__instances:
                        del CallLater.__instances[self]
                    if self.timer is not None:
                        self.timer.Stop()
                        self.timer = None"""),

            PyFunctionDef('GetInterval', '(self)', """\
                if self.timer is not None:
                    return self.timer.GetInterval()
                else:
                    return 0"""),

            PyFunctionDef('IsRunning', '(self)',
                """return self.timer is not None and self.timer.IsRunning()"""),

            PyFunctionDef('SetArgs', '(self, *args, **kwargs)',
                doc="""\
                    (Re)set the args passed to the callable object.  This is
                    useful in conjunction with :meth:`Start` if
                    you want to schedule a new call to the same callable
                    object but with different parameters.

                    :param args: arguments to be passed to the callable object
                    :param kw: keywords to be passed to the callable object

                    """,
                body="""\
                    self.args = args
                    self.kwargs = kwargs"""),

            PyFunctionDef('HasRun', '(self)', 'return self.hasRun',
                doc="""\
                    Returns whether or not the callable has run.

                    :rtype: bool

                    """),

            PyFunctionDef('GetResult', '(self)', 'return self.result',
                doc="""\
                    Returns the value of the callable.

                    :rtype: a Python object
                    :return: result from callable
                    """),

            PyFunctionDef('Notify', '(self)',
                doc="The timer has expired so call the callable.",
                body="""\
                    if self.callable and getattr(self.callable, 'im_self', True):
                        self.runCount += 1
                        self.running = False
                        self.result = self.callable(*self.args, **self.kwargs)
                    self.hasRun = True
                    if not self.running:
                        # if it wasn't restarted, then cleanup
                        wx.CallAfter(self.Stop)"""),

            PyPropertyDef('Interval', 'GetInterval'),
            PyPropertyDef('Result', 'GetResult'),
            ])

    module.addPyCode("FutureCall = deprecated(CallLater, 'Use CallLater instead.')")

    module.addPyCode("""\
        def GetDefaultPyEncoding():
            return "utf-8"
        GetDefaultPyEncoding = deprecated(GetDefaultPyEncoding, msg="wxPython now always uses utf-8")
        """)

    module.addCppFunction('bool', 'IsMainThread', '()',
        doc="Returns ``True`` if the current thread is what wx considers the GUI thread.",
        body="return wxThread::IsMain();")


    module.addInitializerCode("""\
        wxPyPreInit(sipModuleDict);
        """)

    # This code is inserted into the module initialization function
    module.addPostInitializerCode("""\
        wxPyCoreModuleInject(sipModuleDict);
        """)
    # Here is the function it calls
    module.includeCppCode('src/core_ex.cpp')
    module.addItem(etgtools.WigCode("void _wxPyCleanup();"))


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

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

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

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

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

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

    searchCtrl = c

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

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

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

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

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

    module.addPyCode("""\
        EVT_SEARCHCTRL_CANCEL_BTN = wx.PyEventBinder( wxEVT_SEARCHCTRL_CANCEL_BTN, 1)
        EVT_SEARCHCTRL_SEARCH_BTN = wx.PyEventBinder( wxEVT_SEARCHCTRL_SEARCH_BTN, 1)

        # deprecated wxEVT aliases
        wxEVT_COMMAND_SEARCHCTRL_CANCEL_BTN  = wxEVT_SEARCHCTRL_CANCEL_BTN
        wxEVT_COMMAND_SEARCHCTRL_SEARCH_BTN  = wxEVT_SEARCHCTRL_SEARCH_BTN
        """)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    c.find('wxCheckListBox').findOverload('wxString choices').ignore()
    c.find('wxCheckListBox').findOverload('wxArrayString').find(
        'choices').default = 'wxArrayString()'

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

    tools.fixWindowClass(c)

    # We already have the Python methods below, so just ignore this new method for now.
    c.find('GetCheckedItems').ignore()

    c.addPyMethod(
        'GetCheckedItems',
        '(self)',
        doc="""\
        GetCheckedItems()

        Return a sequence of integers corresponding to the checked items in
        the control, based on :meth:`IsChecked`.""",
        body="return tuple([i for i in range(self.Count) if self.IsChecked(i)])"
    )

    c.addPyMethod(
        'GetCheckedStrings',
        '(self)',
        doc="""\
            GetCheckedStrings()

            Return a tuple of strings corresponding to the checked
            items of the control, based on :meth:`GetChecked`.""",
        body="return tuple([self.GetString(i) for i in self.GetCheckedItems()])"
    )

    c.addPyMethod('SetCheckedItems',
                  '(self, indexes)',
                  doc="""\
            SetCheckedItems(indexes)

            Sets the checked state of items if the index of the item is
            found in the indexes sequence.""",
                  body="""\
            for i in indexes:
                assert 0 <= i < self.Count, "Index (%s) out of range" % i
            for i in range(self.Count):
                self.Check(i, i in indexes)""")

    c.addPyMethod('SetCheckedStrings',
                  '(self, strings)',
                  doc="""\
            SetCheckedStrings(strings)

            Sets the checked state of items if the item's string is found
            in the strings sequence.""",
                  body="""\
            for s in strings:
                assert s in self.GetStrings(), "String ('%s') not found" % s
            for i in range(self.Count):
                self.Check(i, self.GetString(i) in strings)""")

    c.addPyMethod('GetChecked',
                  '(self)',
                  'return self.GetCheckedItems()',
                  deprecated='Use GetCheckedItems instead.')
    c.addPyMethod('SetChecked',
                  '(self, indexes)',
                  'return self.SetCheckedItems(indexes)',
                  deprecated='Use SetCheckedItems instead.')

    c.addPyProperty('Checked GetChecked SetChecked')
    c.addPyProperty('CheckedItems GetCheckedItems SetCheckedItems')
    c.addPyProperty('CheckedStrings GetCheckedStrings SetCheckedStrings')

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #12
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('wxFontInfo')
    assert isinstance(c, etgtools.ClassDef)
    ctor = c.find('wxFontInfo').findOverload('T pointSize')
    ctor.find('pointSize').type = 'float'

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

    # Set mustHaveApp on all ctors except the default ctor
    for ctor in c.find('wxFont').all():
        if ctor.isCtor and ctor.argsString != '()':
            ctor.mustHaveApp()

    for func in c.find('New').all():
        func.mustHaveApp()

    c.find('GetDefaultEncoding').mustHaveApp()
    c.find('SetDefaultEncoding').mustHaveApp()

    # Tweak the documentation in this constructor a little, replacing the
    # link to another constructor with a simpler version of the text.
    ctor = c.find('wxFont').findOverload('int pointSize')
    # TODO: should implement an easier way to findDocNode() the node containing what we're looking for...
    ref = list(ctor.detailedDoc[0])[0]
    assert ref.text.startswith('wxFont(')
    ref.tag = 'para'
    ref.text = 'the constructor accepting a :ref:`wx.FontInfo`'

    # FFont factory function for backwards compatibility
    module.addCppFunction(
        'wxFont*',
        'FFont',
        """(int pointSize,
                              wxFontFamily family,
                              int flags = wxFONTFLAG_DEFAULT,
                              const wxString& faceName = wxEmptyString,
                              wxFontEncoding encoding = wxFONTENCODING_DEFAULT)""",
        pyArgsString=
        "(pointSize, family, flags=FONTFLAG_DEFAULT, faceName=EmptyString, encoding=FONTENCODING_DEFAULT)",
        body="""\
        wxFont* font = wxFont::New(pointSize, family, flags, *faceName, encoding);
        return font;
        """,
        factory=True)

    for item in c.findAll('New'):
        item.factory = True

    c.addProperty('Encoding GetEncoding SetEncoding')
    c.addProperty('FaceName GetFaceName SetFaceName')
    c.addProperty('Family GetFamily SetFamily')
    c.addProperty('NativeFontInfoDesc GetNativeFontInfoDesc SetNativeFontInfo')
    c.addProperty(
        'NativeFontInfoUserDesc GetNativeFontInfoUserDesc SetNativeFontInfoUserDesc'
    )
    c.addProperty('PointSize GetPointSize SetPointSize')
    c.addProperty('PixelSize GetPixelSize SetPixelSize')
    c.addProperty('Style GetStyle SetStyle')
    c.addProperty('Weight GetWeight SetWeight')

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

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

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

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

    c.addCppMethod('void*',
                   'GetPangoFontDescription',
                   '()',
                   doc="Returns the font's native handle.",
                   body="""\
        #ifdef __WXGTK__
            return self->GetNativeFontInfo()->description;
        #else
            return 0;
        #endif
        """)

    c.find('AddPrivateFont').setCppCode("""\
        #if wxUSE_PRIVATE_FONTS
            return wxFont::AddPrivateFont(*filename);
        #else
            wxPyRaiseNotImplemented();
            return false;
        #endif
        """)

    c.addCppMethod(
        'bool',
        'CanUsePrivateFont',
        '()',
        isStatic=True,
        doc=
        "Returns ``True`` if this build of wxPython supports using :meth:`AddPrivateFont`.",
        body="return wxUSE_PRIVATE_FONTS;")

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

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

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

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

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

        wx.NORMAL = int(wx.FONTWEIGHT_NORMAL)
        wx.LIGHT  = int(wx.FONTWEIGHT_LIGHT)
        wx.BOLD   = int(wx.FONTWEIGHT_BOLD)

        wx.NORMAL = int(wx.FONTSTYLE_NORMAL)
        wx.ITALIC = int(wx.FONTSTYLE_ITALIC)
        wx.SLANT  = int(wx.FONTSTYLE_SLANT)
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #13
0
ファイル: msgdlg.py プロジェクト: swt2c/Phoenix
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)

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

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

    module.addGlobalStr('wxMessageBoxCaptionStr', c)

    # These argument types are actually ButtonLabel, but the class is a private
    # helper. We will always be passing in strings, and ButtonLabel will implicitly
    # convert.
    c.find('SetHelpLabel.help').type = 'const wxString&'
    c.find('SetOKCancelLabels.ok').type = 'const wxString&'
    c.find('SetOKCancelLabels.cancel').type = 'const wxString&'

    c.find('SetOKLabel.ok').type = 'const wxString&'

    c.find('SetYesNoCancelLabels.yes').type = 'const wxString&'
    c.find('SetYesNoCancelLabels.no').type = 'const wxString&'
    c.find('SetYesNoCancelLabels.cancel').type = 'const wxString&'

    c.find('SetYesNoLabels.yes').type = 'const wxString&'
    c.find('SetYesNoLabels.no').type = 'const wxString&'

    tools.fixTopLevelWindowClass(c)



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

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

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

    module.addItem(gmd)


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

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


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #14
0
ファイル: _xrc.py プロジェクト: alexbelevantsev/Phoenix
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)
    module.check4unittest = False

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

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

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

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

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

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

    c = module.find('wxXmlResource')
    assert isinstance(c, etgtools.ClassDef)
    c.piBases = ['wx.Object']
    c.addPrivateCopyCtor()

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

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

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

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

            // Load the "file" into the resource object
            bool retval = self->Load(wxT("memory:") + filename );
            return retval;
            """)

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

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

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

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

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

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

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

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

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

        def _my_import(name):
            try:
                mod = __import__(name)
            except ImportError:
                import traceback
                print(traceback.format_exc())
                raise
            components = name.split('.')
            for comp in components[1:]:
                mod = getattr(mod, comp)
            return mod
        
        class XmlSubclassFactory_Python(XmlSubclassFactory):
            def __init__(self):
                XmlSubclassFactory.__init__(self)
        
            def Create(self, className):
                assert className.find('.') != -1, "Module name must be specified!"
                mname = className[:className.rfind('.')]
                cname = className[className.rfind('.')+1:]
                module = _my_import(mname)
                klass = getattr(module, cname)
                inst = klass()
                return inst        
        
        XmlResource.AddSubclassFactory(XmlSubclassFactory_Python())
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #15
0
ファイル: pen.py プロジェクト: velascopja/Phoenix
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('wxPen')
    assert isinstance(c, etgtools.ClassDef)
    tools.removeVirtuals(c)

    # The stipple bitmap ctor is not implemented on wxGTK
    c.find('wxPen').findOverload('wxBitmap').ignore()

    m = c.find('GetDashes')
    assert isinstance(m, etgtools.MethodDef)
    m.find('dashes').ignore()
    m.type = 'wxArrayInt*'
    m.factory = True
    m.setCppCode("""\
        wxArrayInt* arr = new wxArrayInt;
        wxDash* dashes;
        int num = self->GetDashes(&dashes);
        for (int i=0; i<num; i++)
            arr->Add(dashes[i]);
        return arr;
        """)

    # SetDashes does not take ownership of the array passed to it, yet that
    # array must be kept alive as long as the pen lives, so we'll create an
    # array holder object that will be associated with the pen, and that will
    # delete the dashes array when it is deleted.
    #c.find('SetDashes').ignore()
    c.addHeaderCode('#include "arrayholder.h"')
    m = c.find('SetDashes')
    # ignore the existing parameters
    m.find('n').ignore()
    m.find('dash').ignore()
    # add a new one
    m.items.append(etgtools.ParamDef(type='const wxArrayInt&', name='dashes'))
    m.setCppCode_sip("""\
        size_t len = dashes->GetCount();
        wxDashCArrayHolder* holder = new wxDashCArrayHolder;
        holder->m_array = new wxDash[len];
        for (int idx=0; idx<len; idx+=1) {
            holder->m_array[idx] = (*dashes)[idx];
        }
        // Make a PyObject for the holder, and transfer its ownership to self.
        PyObject* pyHolder = sipConvertFromNewType(
                (void*)holder, sipType_wxDashCArrayHolder, (PyObject*)sipSelf);
        Py_DECREF(pyHolder);
        sipCpp->SetDashes(len, holder->m_array);
        """)

    c.addAutoProperties()

    # The stock Pen items are documented as simple pointers, but in reality
    # they are macros that evaluate to a function call that returns a pen
    # pointer, and that is only valid *after* the wx.App object has been
    # created. That messes up the code that SIP generates for them, so we need
    # to come up with another solution. So instead we will just create
    # uninitialized pens in a block of Python code, that will then be
    # intialized later when the wx.App is created.
    c.addCppMethod('void',
                   '_copyFrom',
                   '(const wxPen* other)',
                   "*self = *other;",
                   briefDoc="For internal use only.")  # ??
    pycode = '# These stock pens will be initialized when the wx.App object is created.\n'
    for item in module:
        if '_PEN' in item.name:
            item.ignore()
            pycode += '%s = Pen()\n' % tools.removeWxPrefix(item.name)
    module.addPyCode(pycode)

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

    # Some aliases that should be phased out eventually, (sooner rather than
    # later.) They are already gone (or wrapped by an #if) in the C++ code,
    # and so are not found in the documentation...
    module.addPyCode("""\
        wx.SOLID       = int(wx.PENSTYLE_SOLID)
        wx.DOT         = int(wx.PENSTYLE_DOT) 
        wx.LONG_DASH   = int(wx.PENSTYLE_LONG_DASH)
        wx.SHORT_DASH  = int(wx.PENSTYLE_SHORT_DASH) 
        wx.DOT_DASH    = int(wx.PENSTYLE_DOT_DASH) 
        wx.USER_DASH   = int(wx.PENSTYLE_USER_DASH) 
        wx.TRANSPARENT = int(wx.PENSTYLE_TRANSPARENT) 
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #16
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)
    
    #-----------------------------------------------------------------
    # Tweak the parsed meta objects in the module object as needed for
    # customizing the generated code and docstrings.
    
    module.addHeaderCode('#include <wx/richtext/richtextbuffer.h>')
    
    module.addItem(
        tools.wxArrayWrapperTemplate('wxRichTextRangeArray', 'wxRichTextRange', module))
    module.addItem(
        tools.wxArrayWrapperTemplate('wxRichTextAttrArray', 'wxRichTextAttr', module))
    module.addItem(
        tools.wxArrayWrapperTemplate('wxRichTextVariantArray', 'wxVariant', module))     
    module.addItem(
        tools.wxListWrapperTemplate('wxRichTextObjectList', 'wxRichTextObject', module))
    module.addItem(
        tools.wxListWrapperTemplate('wxRichTextLineList', 'wxRichTextLine', module))
    
    # Can this even work?  Apparently it does.
    module.addItem(
        tools.wxArrayPtrWrapperTemplate('wxRichTextObjectPtrArray', 'wxRichTextObject', module))     
    module.addItem(
        tools.wxArrayWrapperTemplate('wxRichTextObjectPtrArrayArray', 'wxRichTextObjectPtrArray', module))

    
    module.find('wxRICHTEXT_ALL').ignore()
    module.find('wxRICHTEXT_NONE').ignore()
    module.find('wxRICHTEXT_NO_SELECTION').ignore()
    code = etgtools.PyCodeDef("""\
        RICHTEXT_ALL = RichTextRange(-2, -2)
        RICHTEXT_NONE = RichTextRange(-1, -1)
        RICHTEXT_NO_SELECTION = RichTextRange(-2, -2)
        """)
    module.insertItemAfter(module.find('wxRichTextRange'), code)
    
    module.insertItem(0, etgtools.WigCode("""\
        // forward declarations
        class wxRichTextFloatCollector;
        """))
    
    
    #-------------------------------------------------------
    c = module.find('wxTextAttrDimension')
    assert isinstance(c, etgtools.ClassDef)
    c.find('SetValue').findOverload('units').ignore()
    c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();")
    
    #-------------------------------------------------------
    c = module.find('wxTextAttrDimensions')
    tools.ignoreConstOverloads(c)
    c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();")
    
    #-------------------------------------------------------
    c = module.find('wxTextAttrSize')
    tools.ignoreConstOverloads(c)
    c.find('SetWidth').findOverload('units').ignore()
    c.find('SetHeight').findOverload('units').ignore()
    c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();")
    
    #-------------------------------------------------------
    c = module.find('wxTextAttrBorder')
    tools.ignoreConstOverloads(c)
    c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();")


    #-------------------------------------------------------
    c = module.find('wxTextAttrBorders')
    tools.ignoreConstOverloads(c)
    c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();")


    #-------------------------------------------------------
    c = module.find('wxTextBoxAttr')
    tools.ignoreConstOverloads(c)


    #-------------------------------------------------------
    c = module.find('wxRichTextAttr')
    tools.ignoreConstOverloads(c)
    

    #-------------------------------------------------------
    c = module.find('wxRichTextProperties')
    tools.ignoreConstOverloads(c)

    c.find('SetProperty').findOverload('bool').ignore()
    c.find('operator[]').ignore()
    
    #-------------------------------------------------------
    c = module.find('wxRichTextSelection')
    tools.ignoreConstOverloads(c)
    c.addCppMethod('int', '__nonzero__', '()', "return self->IsValid();")
    c.find('operator[]').ignore()


    #-------------------------------------------------------
    c = module.find('wxRichTextRange')
    tools.addAutoProperties(c)
        
    # wxRichTextRange typemap
    c.convertFromPyObject = tools.convertTwoIntegersTemplate('wxRichTextRange')
    
    c.addCppMethod('PyObject*', 'Get', '()', """\
        return sipBuildResult(0, "(ii)", self->GetStart(), self->GetEnd());
        """,
        pyArgsString="() -> (start, end)",
        briefDoc="Return the start and end properties as a tuple.")
    
    # Add sequence protocol methods and other goodies
    c.addPyMethod('__str__', '(self)',             'return str(self.Get())')
    c.addPyMethod('__repr__', '(self)',            'return "RichTextRange"+str(self.Get())')
    c.addPyMethod('__len__', '(self)',             'return len(self.Get())')
    c.addPyMethod('__nonzero__', '(self)',         'return self.Get() != (0,0)')
    c.addPyMethod('__reduce__', '(self)',          'return (RichTextRange, self.Get())')
    c.addPyMethod('__getitem__', '(self, idx)',    'return self.Get()[idx]')
    c.addPyMethod('__setitem__', '(self, idx, val)',
                  """\
                  if idx == 0: self.Start = val
                  elif idx == 1: self.End = val
                  else: raise IndexError
                  """) 
    c.addPyCode('RichTextRange.__safe_for_unpickling__ = True')


    #-------------------------------------------------------
    def _fixDrawObject(c, addMissingVirtuals=True):
        assert isinstance(c, etgtools.ClassDef)
        if c.findItem('HitTest'):
            c.find('HitTest.textPosition').out = True
            c.find('HitTest.obj').out = True
            c.find('HitTest.contextObj').out = True
    
        if c.findItem('FindPosition'):
            c.find('FindPosition.pt').out = True
            c.find('FindPosition.height').out = True
    
        if c.findItem('GetBoxRects'):
            c.find('GetBoxRects.marginRect').out = True
            c.find('GetBoxRects.borderRect').out = True
            c.find('GetBoxRects.contentRect').out = True
            c.find('GetBoxRects.paddingRect').out = True
            c.find('GetBoxRects.outlineRect').out = True
    
        if c.findItem('GetTotalMargin'):
            c.find('GetTotalMargin.leftMargin').out = True
            c.find('GetTotalMargin.rightMargin').out = True
            c.find('GetTotalMargin.topMargin').out = True
            c.find('GetTotalMargin.bottomMargin').out = True
    
        if c.findItem('CalculateRange'):
            c.find('CalculateRange.end').out = True  # TODO: should it be an inOut?
    
    
        # These are the pure virtuals in the base class. SIP needs to see that
        # all the derived classes have an implementation, otherwise it will
        # consider them to be ABCs.
        if not c.findItem('Draw') and addMissingVirtuals:
            c.addItem(etgtools.WigCode("""\
                virtual bool Draw(wxDC& dc, wxRichTextDrawingContext& context, 
                                  const wxRichTextRange& range,
                                  const wxRichTextSelection& selection, 
                                  const wxRect& rect, int descent, int style);"""))
        if not c.findItem('Layout') and addMissingVirtuals:
            c.addItem(etgtools.WigCode("""\
                virtual bool Layout(wxDC& dc, wxRichTextDrawingContext& context, 
                                    const wxRect& rect, const wxRect& parentRect, 
                                    int style);"""))
            
        # TODO: Some of these args are output parameters.  How should they be dealt with?
        if not c.findItem('GetRangeSize') and addMissingVirtuals:
            c.addItem(etgtools.WigCode("""\
                virtual bool GetRangeSize(const wxRichTextRange& range, wxSize& size, 
                              int& descent,
                              wxDC& dc, wxRichTextDrawingContext& context, int flags,
                              const wxPoint& position = wxPoint(0,0),
                              const wxSize& parentSize = wxDefaultSize,
                              wxArrayInt* partialExtents = NULL) const;"""))


    #-------------------------------------------------------
    c = module.find('wxRichTextObject')
    #c.find('ImportFromXML').ignore()
    tools.ignoreConstOverloads(c)
    _fixDrawObject(c)
    
    
    #-------------------------------------------------------
    c = module.find('wxRichTextCompositeObject')
    tools.ignoreConstOverloads(c)
    _fixDrawObject(c, addMissingVirtuals=False)
    

    #-------------------------------------------------------
    c = module.find('wxRichTextParagraphLayoutBox')
    tools.ignoreConstOverloads(c)
    _fixDrawObject(c)

    c.find('MoveAnchoredObjectToParagraph.from').name = 'from_'
    c.find('MoveAnchoredObjectToParagraph.to').name = 'to_'
    c.find('DoNumberList.def').name = 'styleDef'
    c.find('SetListStyle.def').name = 'styleDef'

    #-------------------------------------------------------
    c = module.find('wxRichTextBox')
    _fixDrawObject(c)

    #-------------------------------------------------------
    c = module.find('wxRichTextField')
    _fixDrawObject(c)


    #-------------------------------------------------------
    c = module.find('wxRichTextLine')
    tools.ignoreConstOverloads(c)
    c.find('SetRange.from').name = 'from_'
    c.find('SetRange.to').name = 'to_'


    #-------------------------------------------------------
    c = module.find('wxRichTextParagraph')
    _fixDrawObject(c)
    
    # These methods use an untyped wxList, but since we know what is in it
    # we'll make a fake typed list for wxPython so we can know what kinds of
    # values to get from it.
    module.addItem(
        tools.wxListWrapperTemplate('wxList', 'wxRichTextObject', module, 
                                    fakeListClassName='wxRichTextObjectList_'))
    c.find('MoveToList.list').type = 'wxRichTextObjectList_&'
    c.find('MoveFromList.list').type = 'wxRichTextObjectList_&'
    
    
    #-------------------------------------------------------
    c = module.find('wxRichTextPlainText')
    _fixDrawObject(c)
    
    #-------------------------------------------------------
    c = module.find('wxRichTextImage')
    _fixDrawObject(c)
    
    #-------------------------------------------------------
    c = module.find('wxRichTextBuffer')
    tools.ignoreConstOverloads(c)
    _fixDrawObject(c)

    # More untyped wxLists
    module.addItem(
        tools.wxListWrapperTemplate('wxList', 'wxRichTextFileHandler', module, 
                                    fakeListClassName='wxRichTextFileHandlerList'))
    c.find('GetHandlers').type = 'wxRichTextFileHandlerList&'
    c.find('GetHandlers').noCopy = True
    
    module.addItem(
        tools.wxListWrapperTemplate('wxList', 'wxRichTextDrawingHandler', module, 
                                    fakeListClassName='wxRichTextDrawingHandlerList'))
    c.find('GetDrawingHandlers').type = 'wxRichTextDrawingHandlerList&'
    c.find('GetDrawingHandlers').noCopy = True

    # TODO: Need a template to wrap STRING_HASH_MAP
    c.find('GetFieldTypes').ignore()
    
    c.find('AddHandler.handler').transfer = True
    c.find('InsertHandler.handler').transfer = True

    c.find('AddDrawingHandler.handler').transfer = True
    c.find('InsertDrawingHandler.handler').transfer = True

    c.find('AddFieldType.fieldType').transfer = True
   
    # TODO:  Transfer ownership with AddEventHandler?  TransferBack with Remove?


    c.find('FindHandler').renameOverload('name', 'FindHandlerByName')
    c.find('FindHandler').renameOverload('extension', 'FindHandlerByExtension')
    c.find('FindHandler').pyName = 'FindHandlerByType'
    
    c.find('FindHandlerFilenameOrType').pyName = 'FindHandlerByFilename'
    
    
    #-------------------------------------------------------
    c = module.find('wxRichTextTable')
    tools.ignoreConstOverloads(c)
    _fixDrawObject(c)
    
    
    #-------------------------------------------------------
    c = module.find('wxRichTextObjectAddress')
    tools.ignoreConstOverloads(c)


    #-------------------------------------------------------
    c = module.find('wxRichTextCommand')
    
    module.addItem(
        tools.wxListWrapperTemplate('wxList', 'wxRichTextAction', module, 
                                    fakeListClassName='wxRichTextActionList'))
    c.find('GetActions').type = 'wxRichTextActionList&'
    c.find('GetActions').noCopy = True
     
    c.find('AddAction.action').transfer = True
    
    
    #-------------------------------------------------------
    c = module.find('wxRichTextAction')
    tools.ignoreConstOverloads(c)

    
    #-------------------------------------------------------
    c = module.find('wxRichTextFileHandler')
    c.find('DoLoadFile').ignore(False)
    c.find('DoSaveFile').ignore(False)
    
    c = module.find('wxRichTextPlainTextHandler')
    c.find('DoLoadFile').ignore(False)
    c.find('DoSaveFile').ignore(False)

    
    
    
    #-------------------------------------------------------
    # Ignore all Dump() methods since we don't wrap wxTextOutputStream.
    
    # TODO: try swithcing the parameter type to wxOutputStream and then in
    # the wrapper code create a wxTextOutputStream from that to pass on to
    # Dump.
    
    for m in module.findAll('Dump'):
        if m.findItem('stream'):
            m.ignore()
    

    
    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #17
0
ファイル: utils.py プロジェクト: lcl1995225/Phoenix
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/utils.h>')
    module.addHeaderCode('#include <wx/power.h>')


    c = module.find('wxWindowDisabler')
    assert isinstance(c, etgtools.ClassDef)
    c.mustHaveApp()
    c.addPrivateCopyCtor()
    # add context manager methods
    c.addPyMethod('__enter__', '(self)', 'return self')
    c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)', 'pass')


    module.find('wxQsort').ignore()
    module.find('wxGetEmailAddress').findOverload('buf').ignore()
    module.find('wxGetHostName').findOverload('buf').ignore()
    module.find('wxGetUserId').findOverload('buf').ignore()
    module.find('wxGetUserName').findOverload('buf').ignore()
    module.find('wxSortCallback').ignore()

    module.find('wxLoadUserResource').findOverload('pLen').ignore()
    module.find('wxLoadUserResource').findOverload('outData').ignore()

    module.find('wxGetFreeMemory').ignore()
    module.find('wxGetLinuxDistributionInfo').ignore()
    module.find('wxGetDisplayName').ignore()
    module.find('wxSetDisplayName').ignore()
    module.find('wxPostDelete').ignore()

    # deprecated and removed
    module.find('wxUsleep').ignore()


    # ignore all the environment related functions
    for item in module.allItems():
        if 'Env' in item.name:
            item.ignore()
    module.find('wxGetenv').ignore()

    # Keep just the first wxExecute overload
    f = module.find('wxExecute')
    f.overloads = []
    f.mustHaveApp()

    module.find('wxGetOsVersion.major').out = True
    module.find('wxGetOsVersion.minor').out = True

    c = module.find('wxBusyCursor')
    c.mustHaveApp()
    # add context manager methods
    c.addPyMethod('__enter__', '(self)', 'return self')
    c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)', 'pass')


    for funcname in ['wxBell',
                     'wxBeginBusyCursor',
                     'wxEndBusyCursor',
                     'wxShutdown',
                     'wxInfoMessageBox',
                     'wxIsBusy',
                     'wxGetMousePosition',
                     'wxGetKeyState',
                     'wxGetMouseState',
                     ]:
        c = module.find(funcname)
        c.mustHaveApp()


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #18
0
ファイル: object.py プロジェクト: zinayon/Phoenix
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)
コード例 #19
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)
    module.check4unittest = False

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

    module.addHeaderCode('#include <wxpy_api.h>')
    module.addImport('_core')
    module.addPyCode('import wx', order=10)
    module.addInclude(INCLUDES)

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

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

    c = module.find('wxStyledTextCtrl')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixWindowClass(c, False)
    module.addGlobalStr('wxSTCNameStr', c)

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

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

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

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

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

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

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

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

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

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

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

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

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

    # These are MSW only. Make them be empty stubs for the other ports
    c.find('GetBackgroundColour').type = 'wxColour*'
    c.find('GetBackgroundColour').setCppCode("""\
        #ifdef __WXMSW__
            return &self->GetBackgroundColour();
        #else
            return &wxNullColour;
        #endif
        """)

    c.find('SetBackgroundColour').setCppCode("""\
        #ifdef __WXMSW__
            self->SetBackgroundColour(*colour);
        #endif
        """)

    c.find('GetFont').type = 'wxFont*'
    c.find('GetFont').setCppCode("""\
        #ifdef __WXMSW__
            return &self->GetFont();
        #else
            return &wxNullFont;
        #endif
        """)

    c.find('SetFont').setCppCode("""\
        #ifdef __WXMSW__
            self->SetFont(*font);
        #endif
        """)

    c.find('GetMarginWidth').setCppCode("""\
        #ifdef __WXMSW__
            return self->GetMarginWidth();
        #else
            return -1;
        #endif
        """)

    c.find('SetMarginWidth').setCppCode("""\
        #ifdef __WXMSW__
            self->SetMarginWidth(width);
        #endif
        """)

    c.find('GetTextColour').type = 'wxColour*'
    c.find('GetTextColour').setCppCode("""\
        #ifdef __WXMSW__
            return &self->GetTextColour();
        #else
            return &wxNullColour;
        #endif
        """)

    c.find('SetTextColour').setCppCode("""\
        #ifdef __WXMSW__
            self->SetTextColour(*colour);
        #endif
        """)

    c.find('SetBitmap').setCppCode("""\
        #ifdef __WXMSW__
            self->SetBitmap(*bmp, checked);
        #else
            self->SetBitmap(*bmp); // no checked arg in this case
        #endif
        """)

    c.find('SetBitmaps').setCppCode("""\
        #ifdef __WXMSW__
            self->SetBitmaps(*checked, *unchecked);
        #else
            self->SetBitmap(*checked);
        #endif
        """)

    module.addItem(
        tools.wxListWrapperTemplate('wxMenuItemList', 'wxMenuItem', module))

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

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

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

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

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

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

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

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


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

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

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

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

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

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

    def markCreateFactories(klass):
        """Mark all Create methods as factories"""
        for func in klass.allItems():
            if isinstance(func, etgtools.FunctionDef) \
               and func.name.startswith('Create') \
               and '*' in func.type:
                func.factory = True

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

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

    c.addCppMethod('wxGraphicsContext*',
                   'Create',
                   '(wxAutoBufferedPaintDC* autoPaintDC /KeepReference/)',
                   pyArgsString='(autoPaintDC) -> GraphicsContext',
                   isStatic=True,
                   body="""\
            return wxGraphicsContext::Create(*autoPaintDC);
            """)

    m = c.find('Create').findOverload('wxEnhMetaFileDC')
    m.find('metaFileDC').type = 'const wxMetafileDC&'
    m.argsString = '(const wxMetafileDC& metaFileDC)'
    m.setCppCode("""\
        #ifdef __WXMSW__
        #if wxUSE_ENH_METAFILE
            return wxGraphicsContext::Create(*metaFileDC);
        #endif
        #endif
            wxPyRaiseNotImplemented();
            return NULL;
        """)

    markCreateFactories(c)

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

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

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

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

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

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

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

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

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

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

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

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

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

    # TODO: support this?
    c.find('CreateFromNativeHDC').ignore()

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

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

    # The KeepReference annotation doesn't work for us in this case, as it will
    # hold the reference in the renderer object, but it is better to hold the
    # reference in the returned context object instead. Otherwise there is still
    # some possibility that the held DC will be destroyed before the context.
    c.addPyCode("""\
        def _ctx_hold_ref(f):
            from functools import wraps
            @wraps(f)
            def wrapper(self, obj):
                ctx = f(self, obj)
                if ctx is not None:
                    ctx._obj = obj
                return ctx
            return wrapper
        GraphicsRenderer.CreateContext = _ctx_hold_ref(GraphicsRenderer.CreateContext)
        GraphicsRenderer.CreateContextFromImage = _ctx_hold_ref(GraphicsRenderer.CreateContextFromImage)
        GraphicsRenderer.CreateContextFromUnknownDC = _ctx_hold_ref(GraphicsRenderer.CreateContextFromUnknownDC)
        """)

    # TODO: support this?
    c.find('CreateContext').findOverload('wxEnhMetaFileDC').ignore()

    # TODO: support this?
    c.find('CreateContextFromNativeHDC').ignore()

    c.addPyMethod('GetType',
                  '(self)',
                  doc="Returns the name of the GraphicsRenderer class.",
                  body="return self.GetClassInfo().GetClassName()")

    c.find('GetGDIPlusRenderer').ignore()
    c.addCppMethod('wxGraphicsRenderer*',
                   'GetGDIPlusRenderer',
                   '()',
                   isStatic=True,
                   doc="Returns GDI+ renderer (MSW only).",
                   body="""\
            #ifdef __WXMSW__
                return wxGraphicsRenderer::GetGDIPlusRenderer();
            #else
                return NULL;
            #endif
            """)

    c.find('GetDirect2DRenderer').ignore()
    c.addCppMethod('wxGraphicsRenderer*',
                   'GetDirect2DRenderer',
                   '()',
                   isStatic=True,
                   doc="Returns Direct2D renderer (MSW and Python3 only).",
                   body="""\
            #if wxUSE_GRAPHICS_DIRECT2D
                return wxGraphicsRenderer::GetDirect2DRenderer();
            #else
                return NULL;
            #endif
            """)

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

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

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

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

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

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

    #---------------------------------------------
    c = module.find('wxGraphicsPenInfo')
    # Ignore Dashes for now
    # TODO: we need to do something like wx.Pen.SetDashes, but since
    # GraphicsPenInfo is transitory we can't save the reference in it to the
    # holder, and the pen will not have been created yet...
    c.find('Dashes').ignore()
    c.find('GetDashes').ignore()
    c.find('GetDashCount').ignore()
    c.find('GetDash').ignore()

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

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #23
0
ファイル: defs.py プロジェクト: mprosperi/Phoenix
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING,
                                check4unittest=False)
    etgtools.parseDoxyXML(module, ITEMS)
    module.check4unittest = False
    
    #-----------------------------------------------------------------
    # Tweak the parsed meta objects in the module object as needed for
    # customizing the generated code and docstrings.
        
    # tweaks for defs.h to help SIP understand the types better
    module.find('wxInt16').type = 'short'
    module.find('wxInt64').type = 'long long'
    module.find('wxUint64').type = 'unsigned long long'
    
    # See src/wacky_ints.sip
    module.find('wxIntPtr').ignore()
    module.find('wxUIntPtr').ignore()
        
    # Correct the types for these as their values are outside the range of int
    module.find('wxUINT32_MAX').type = 'unsigned long'
    module.find('wxINT64_MIN').type = 'long long'
    module.find('wxINT64_MAX').type = 'long long'
    module.find('wxUINT64_MAX').type = 'unsigned long long'

    # Generate the code for these differently because they need to be
    # forcibly mashed into an int in the C code
    module.find('wxCANCEL_DEFAULT').forcedInt = True
    module.find('wxVSCROLL').forcedInt = True
    module.find('wxWINDOW_STYLE_MASK').forcedInt = True

    module.find('wxInt8').pyInt = True
    module.find('wxUint8').pyInt = True
    module.find('wxByte').pyInt = True
    
    module.find('wxDELETE').ignore()
    module.find('wxDELETEA').ignore()
    module.find('wxSwap').ignore()
    module.find('wxVaCopy').ignore()
    
    # Add some typedefs for basic wx types and others so the backend
    # generator knows what they are
    td = module.find('wxUIntPtr')
    module.insertItemAfter(td, etgtools.TypedefDef(type='wchar_t', name='wxUChar'))
    module.insertItemAfter(td, etgtools.TypedefDef(type='wchar_t', name='wxChar'))
    module.insertItemAfter(td, etgtools.TypedefDef(type='long', name='time_t'))
    module.insertItemAfter(td, etgtools.TypedefDef(type='long long', name='wxFileOffset'))
    module.insertItemAfter(td, etgtools.TypedefDef(type='SIP_SSIZE_T', name='ssize_t'))
    module.insertItemAfter(td, etgtools.TypedefDef(type='unsigned char', name='byte', pyInt=True))
    module.insertItemAfter(td, etgtools.TypedefDef(type='unsigned long', name='ulong'))
    

    
    # Forward declarations for classes that are referenced but not defined
    # yet. 
    # 
    # TODO: Remove these when the classes are added for real.
    # TODO: Add these classes for real :-)
    module.insertItem(0, etgtools.WigCode("""\
        // forward declarations
        class wxPalette;
        class wxExecuteEnv;
        """))
    
   
    # Add some code for getting the version numbers
    module.addCppCode("""
        #include <wx/version.h>
        const int MAJOR_VERSION = wxMAJOR_VERSION;
        const int MINOR_VERSION = wxMINOR_VERSION;           
        const int RELEASE_NUMBER = wxRELEASE_NUMBER;     
        """)
    module.addItem(etgtools.WigCode("""
        const int MAJOR_VERSION;
        const int MINOR_VERSION;
        const int RELEASE_NUMBER;
        """))

    module.addPyCode("BG_STYLE_CUSTOM = BG_STYLE_PAINT")
    module.addItem(etgtools.DefineDef(name='wxADJUST_MINSIZE', value='0'))
    

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #24
0
ファイル: sizer.py プロジェクト: maroianenasrellah/wxWidgets
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)

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

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

    # ctors taking a sizer transfer ownership
    for m in c.find('wxSizerItem').all():
        if m.findItem('sizer'):
            m.find('sizer').transfer = True

    c.find('AssignSizer.sizer').transfer = True

    # userData args transfer ownership too, and we'll use wxPyUserData
    # instead of any wxObject
    for m in c.allItems():
        if isinstance(m, etgtools.MethodDef) and m.findItem('userData'):
            m.find('userData').transfer = True
            m.find('userData').type = 'wxPyUserData*'

    gud = c.find('GetUserData')
    gud.type = 'wxPyUserData*'
    gud.setCppCode('return dynamic_cast<wxPyUserData*>(self->GetUserData());')

    # these have been deprecated for a while so go ahead and get rid of them
    c.find('SetWindow').ignore()
    c.find('SetSizer').ignore()
    c.find('SetSpacer').ignore()

    c.addPrivateCopyCtor()

    #---------------------------------------------
    c = module.find('wxSizer')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixSizerClass(c)
    c.addPrivateCopyCtor()
    c.addPrivateAssignOp()

    for func in c.findAll('Add') + c.findAll('Insert') + c.findAll('Prepend'):
        if func.findItem('sizer'):
            func.find('sizer').transfer = True
        if func.findItem('userData'):
            func.find('userData').transfer = True
            func.find('userData').type = 'wxPyUserData*'
        if func.findItem('item'):
            func.find('item').transfer = True

    c.find('GetChildren').overloads = []
    c.find('GetChildren').noCopy = True

    # Needs wxWin 2.6 compatibility
    c.find('Remove').findOverload('(wxWindow *window)').ignore()

    # deprecated and removed
    c.find('SetVirtualSizeHints').ignore()

    c.addPyMethod('AddMany',
                  '(self, items)',
                  doc="""\
        :meth:`AddMany` is a convenience method for adding several items to a sizer
        at one time. Simply pass it a list of tuples, where each tuple
        consists of the parameters that you would normally pass to the :meth:`Add`
        method.
        """,
                  body="""\
        for item in items:
            if not isinstance(item, (tuple, list)):
                item = (item, )
            self.Add(*item)
        """)

    c.addCppMethod(
        'wxSizerItem*',
        'Add', '(const wxSize& size, int proportion=0, int flag=0, '
        'int border=0, wxPyUserData* userData /Transfer/ = NULL)',
        doc="Add a spacer using a :class:`Size` object.",
        body=
        "return self->Add(size->x, size->y, proportion, flag, border, userData);"
    )

    c.addCppMethod(
        'wxSizerItem*',
        'Prepend', '(const wxSize& size, int proportion=0, int flag=0, '
        'int border=0, wxPyUserData* userData /Transfer/ = NULL)',
        doc="Prepend a spacer using a :class:`Size` object.",
        body=
        "return self->Prepend(size->x, size->y, proportion, flag, border, userData);"
    )

    c.addCppMethod(
        'wxSizerItem*',
        'Insert',
        '(ulong index, const wxSize& size, int proportion=0, int flag=0, '
        'int border=0, wxPyUserData* userData /Transfer/ = NULL)',
        doc="Insert a spacer using a :class:`Size` object.",
        body=
        "return self->Insert(index, size->x, size->y, proportion, flag, border, userData);"
    )

    c.addCppMethod('wxSizerItem*',
                   'Add',
                   '(const wxSize& size, const wxSizerFlags& flags)',
                   doc="Add a spacer using a :class:`Size` object.",
                   body="return self->Add(size->x, size->y, *flags);")

    c.addCppMethod('wxSizerItem*',
                   'Prepend',
                   '(const wxSize& size, const wxSizerFlags& flags)',
                   doc="Prepend a spacer using a :class:`Size` object.",
                   body="return self->Prepend(size->x, size->y, *flags);")

    c.addCppMethod(
        'wxSizerItem*',
        'Insert',
        '(ulong index, const wxSize& size, const wxSizerFlags& flags)',
        doc="Insert a spacer using a :class:`Size` object.",
        body="return self->Insert(index, size->x, size->y, *flags);")

    c.addPyMethod(
        '__nonzero__',
        '(self)',
        doc=
        "Can be used to test if the C++ part of the sizer still exists, with \n"
        "code like this::\n\n"
        "    if theSizer:\n"
        "        doSomething()",
        body="""\
        import wx.siplib
        return not wx.siplib.isdeleted(self)
        """)

    c.addPyMethod(
        '__iter__',
        '(self)',
        doc=
        "A Py convenience method that allows Sizers to act as iterables that will yield their wx.SizerItems.",
        body="for item in self.GetChildren(): yield item")

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

    #---------------------------------------------
    c = module.find('wxBoxSizer')
    tools.fixSizerClass(c)
    c.find('wxBoxSizer.orient').default = 'wxHORIZONTAL'

    #---------------------------------------------
    c = module.find('wxStaticBoxSizer')
    tools.fixSizerClass(c)
    c.find('wxStaticBoxSizer.orient').default = 'wxHORIZONTAL'

    #---------------------------------------------
    c = module.find('wxGridSizer')
    tools.fixSizerClass(c)

    c.addPyMethod('CalcRowsCols',
                  '(self)',
                  doc="""\
        CalcRowsCols() -> (rows, cols)

        Calculates how many rows and columns will be in the sizer based
        on the current number of items and also the rows, cols specified
        in the constructor.
        """,
                  body="""\
        nitems = len(self.GetChildren())
        rows = self.GetRows()
        cols = self.GetCols()
        assert rows != 0 or cols != 0, "Grid sizer must have either rows or columns fixed"
        if cols != 0:
            rows = (nitems + cols - 1) / cols
        elif rows != 0:
            cols = (nitems + rows - 1) / rows
        return (rows, cols)
        """)

    #---------------------------------------------
    c = module.find('wxFlexGridSizer')
    tools.fixSizerClass(c)

    #---------------------------------------------
    c = module.find('wxStdDialogButtonSizer')
    tools.fixSizerClass(c)

    module.addPyCode("PySizer = wx.deprecated(Sizer, 'Use Sizer instead.')")

    module.addItem(
        tools.wxListWrapperTemplate('wxSizerItemList', 'wxSizerItem', module))

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

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

    #-------------------------------------------------------
    c = module.find('wxListItem')
    assert isinstance(c, etgtools.ClassDef)
    c.find('SetData').findOverload('void *').ignore()
    c.find('GetData').type = 'long'

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

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

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

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

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

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

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

    # SetItemData takes a long, so lets return that type from GetItemData too,
    # instead of a wxUIntPtr.
    c.find('GetItemData').type = 'long'
    c.find('SetItemPtrData').ignore()

    # Monkey-patch SetItemData to ensure the data value isn't too big. It's
    # limited to a C long...
    orig = c.find('SetItemData')
    orig.pyName = '_SetItemData'
    orig.docsignored = True

    c.addPyMethod(
        'SetItemData',
        '(self, item, data)',
        doc="Associates an application-defined data value with this item.",
        body="""\
            from wx._core import _LONG_MIN, _LONG_MAX
            if data < _LONG_MIN or data > _LONG_MAX:
                raise OverflowError("Values limited to what can be held in a C long.")
            return self._SetItemData(item, data)
            """)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    c.addPrivateCopyCtor()
    c.addPublic()
    tools.removeVirtuals(c)

    c.addDtor('public', True)

    # Keep only the wxSize overloads of these
    c.find('GetSize').findOverload('wxCoord').ignore()
    c.find('GetSizeMM').findOverload('wxCoord').ignore()

    # TODO: needs wxAffineMatrix2D support.
    #c.find('GetTransformMatrix').ignore()
    #c.find('SetTransformMatrix').ignore()

    # remove wxPoint* overloads, we use the wxPointList ones
    c.find('DrawLines').findOverload('wxPoint points').ignore()
    c.find('DrawPolygon').findOverload('wxPoint points').ignore()
    c.find('DrawSpline').findOverload('wxPoint points').ignore()

    # TODO: we'll need a custom method implementation for this since there
    # are multiple array parameters involved...
    c.find('DrawPolyPolygon').ignore()


    # Add output param annotations so the generated docstrings will be correct
    c.find('GetUserScale.x').out = True
    c.find('GetUserScale.y').out = True

    c.find('GetLogicalScale.x').out = True
    c.find('GetLogicalScale.y').out = True

    c.find('GetLogicalOrigin').overloads = []
    c.find('GetLogicalOrigin.x').out = True
    c.find('GetLogicalOrigin.y').out = True

    c.find('GetClippingBox').findOverload('wxRect').ignore()
    c.find('GetClippingBox.x').out = True
    c.find('GetClippingBox.y').out = True
    c.find('GetClippingBox.width').out = True
    c.find('GetClippingBox.height').out = True
    c.addPyMethod('GetClippingRect', '(self)',
        doc="Returns the rectangle surrounding the current clipping region as a wx.Rect.",
        body="""\
            rv, x, y, w, h = self.GetClippingBox()
            return wx.Rect(x,y,w,h)
            """)


    # Deal with the text-extent methods. In Classic we renamed one overloaded
    # method with a "Full" name, and the simpler one was left with the
    # original name.  I think a simpler approach here will be to remove the
    # simple version, rename the Full version as before, and then add a
    # CppMethod to reimplement the simple version.

    for name in ['GetTextExtent', 'GetMultiLineTextExtent']:
        m = c.find(name)
        # if these fail then double-check order of parsed methods, etc.
        assert len(m.overloads) == 1
        assert 'wxCoord' not in m.overloads[0].argsString
        m.overloads = []

    c.find('GetTextExtent').pyName = 'GetFullTextExtent'
    c.find('GetMultiLineTextExtent').pyName = 'GetFullMultiLineTextExtent'

    # Set output parameters
    c.find('GetTextExtent.w').out = True
    c.find('GetTextExtent.h').out = True
    c.find('GetTextExtent.descent').out = True
    c.find('GetTextExtent.externalLeading').out = True

    c.find('GetMultiLineTextExtent.w').out = True
    c.find('GetMultiLineTextExtent.h').out = True
    c.find('GetMultiLineTextExtent.heightLine').out = True


    # Update the docs to remove references to overloading, pointer values, etc.
    m = c.find('GetTextExtent')
    m.briefDoc = "Gets the dimensions of the string as it would be drawn."
    m.detailedDoc = [dedent("""\
        The ``string`` parameter is the string to measure.  The return value
        is a tuple of integer values consisting of ``widget``, ``height``,
        ``decent`` and ``externalLeading``. The ``descent`` is the dimension
        from the baseline of the font to the bottom of the descender, and
        ``externalLeading`` is any extra vertical space added to the font by the
        font designer (usually is zero).

        If the optional parameter ``font`` is specified and valid, then it is
        used for the text extent calculation. Otherwise the currently selected
        font is.

        .. seealso:: :class:`wx.Font`, :meth:`~wx.DC.SetFont`,
           :meth:`~wx.DC.GetPartialTextExtents, :meth:`~wx.DC.GetMultiLineTextExtent`
        """)]

    m = c.find('GetMultiLineTextExtent')
    m.briefDoc = "Gets the dimensions of the string as it would be drawn."
    m.detailedDoc = [dedent("""\
        The ``string`` parameter is the string to measure.  The return value
        is a tuple of integer values consisting of ``widget``, ``height`` and
        ``heightLine``.  The ``heightLine`` is the the height of a single line.

        If the optional parameter ``font`` is specified and valid, then it is
        used for the text extent calculation. Otherwise the currently selected
        font is.

        .. note:: This function works with both single-line and multi-line strings.

        .. seealso:: :class:`wx.Font`, :meth:`~wx.DC.SetFont`,
           :meth:`~wx.DC.GetPartialTextExtents, :meth:`~wx.DC.GetTextExtent`
        """)]

    # Now add the simpler versions of the extent methods
    c.addCppMethod('wxSize*', 'GetTextExtent', '(const wxString& st)', isConst=True,
        doc=dedent("""\
            Return the dimensions of the given string's text extent using the
            currently selected font.

            :param st: The string to be measured

            .. seealso:: :meth:`~wx.DC.GetFullTextExtent`
            """),
        body="""\
            return new wxSize(self->GetTextExtent(*st));
            """,
        overloadOkay=False, factory=True)

    c.addCppMethod('wxSize*', 'GetMultiLineTextExtent', '(const wxString& st)', isConst=True,
        doc=dedent("""\
            Return the dimensions of the given string's text extent using the
            currently selected font, taking into account multiple lines if
            present in the string.

            :param st: The string to be measured

            .. seealso:: :meth:`~wx.DC.GetFullMultiLineTextExtent`
            """),
        body="""\
            return new wxSize(self->GetMultiLineTextExtent(*st));
            """,
        overloadOkay=False, factory=True)




    # Add some alternate implementations for other DC methods, in order to
    # avoid using parameters as return values, etc. as well as Classic
    # compatibility.
    c.find('GetPixel').ignore()
    c.addCppMethod('wxColour*', 'GetPixel', '(wxCoord x, wxCoord y)',
        doc="""\
            Gets the colour at the specified location on the DC.

            This method isn't available for ``wx.PostScriptDC`` or ``wx.MetafileDC`` nor
            for any DC in wxOSX port, and simply returns ``wx.NullColour`` there.

            .. note:: Setting a pixel can be done using DrawPoint().

            .. note:: This method shouldn't be used with ``wx.PaintDC`` as accessing the
                      DC while drawing can result in unexpected results, notably in wxGTK.
            """,
        body="""\
            wxColour* col = new wxColour;
            self->GetPixel(x, y, col);
            return col;
            """,
        factory=True)

    # Return the rect instead of using an output parameter
    m = c.find('DrawLabel').findOverload('rectBounding')
    m.type = 'wxRect*'
    m.find('rectBounding').ignore()
    m.factory = True  # a new instance of wxRect is being created
    m.setCppCode("""\
        wxRect rv;
        self->DrawLabel(*text, *bitmap, *rect, alignment, indexAccel, &rv);
        return new wxRect(rv);
        """)
    c.addPyCode('DC.DrawImageLabel = wx.deprecated(DC.DrawLabel, "Use DrawLabel instead.")')


    # Return the array instead of using an output parameter
    m = c.find('GetPartialTextExtents')
    m.type = 'wxArrayInt*'
    m.find('widths').ignore()
    m.factory = True  # a new instance is being created
    m.setCppCode("""\
        wxArrayInt rval;
        self->GetPartialTextExtents(*text, rval);
        return new wxArrayInt(rval);
        """)


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

    c.addPyMethod('GetBoundingBox', '(self)', doc="""\
        GetBoundingBox() -> (x1,y1, x2,y2)\n
        Returns the min and max points used in drawing commands so far.""",
        body="return (self.MinX(), self.MinY(), self.MaxX(), self.MaxY())")


    m = c.find('GetHandle')
    m.type = 'wxUIntPtr*'
    m.setCppCode("return new wxUIntPtr((wxUIntPtr)self->GetHandle());")


    c.addCppMethod('long', 'GetHDC', '()', """\
        #ifdef __WXMSW__
            return (long)self->GetHandle();
        #else
            wxPyRaiseNotImplemented();
            return 0;
        #endif""")
    c.addCppMethod('wxUIntPtr*', 'GetCGContext', '()', """\
        #ifdef __WXMAC__
            return new wxUIntPtr((wxUIntPtr)self->GetHandle());
        #else
            wxPyRaiseNotImplemented();
            return NULL;
        #endif""")
    c.addCppMethod('wxUIntPtr*', 'GetGdkDrawable', '()', """\
        #ifdef __WXGTK__
            return new wxUIntPtr((wxUIntPtr)self->GetHandle());
        #else
            wxPyRaiseNotImplemented();
            return NULL;
        #endif""")

    c.addPyCode('DC.GetHDC = wx.deprecated(DC.GetHDC, "Use GetHandle instead.")')
    c.addPyCode('DC.GetCGContext = wx.deprecated(DC.GetCGContext, "Use GetHandle instead.")')
    c.addPyCode('DC.GetGdkDrawable = wx.deprecated(DC.GetGdkDrawable, "Use GetHandle instead.")')

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


    # This file contains implementations of functions for quickly drawing
    # lists of items on the DC. They are called from the CppMethods defined
    # below, which in turn are called from the PyMethods below that.
    c.includeCppCode('src/dc_ex.cpp')

    c.addCppMethod('PyObject*', '_DrawPointList', '(PyObject* pyCoords, PyObject* pyPens, PyObject* pyBrushes)',
        body="return wxPyDrawXXXList(*self, wxPyDrawXXXPoint, pyCoords, pyPens, pyBrushes);")

    c.addCppMethod('PyObject*', '_DrawLineList', '(PyObject* pyCoords, PyObject* pyPens, PyObject* pyBrushes)',
        body="return wxPyDrawXXXList(*self, wxPyDrawXXXLine, pyCoords, pyPens, pyBrushes);")

    c.addCppMethod('PyObject*', '_DrawRectangleList', '(PyObject* pyCoords, PyObject* pyPens, PyObject* pyBrushes)',
        body="return wxPyDrawXXXList(*self, wxPyDrawXXXRectangle, pyCoords, pyPens, pyBrushes);")

    c.addCppMethod('PyObject*', '_DrawEllipseList', '(PyObject* pyCoords, PyObject* pyPens, PyObject* pyBrushes)',
        body="return wxPyDrawXXXList(*self, wxPyDrawXXXEllipse, pyCoords, pyPens, pyBrushes);")

    c.addCppMethod('PyObject*', '_DrawPolygonList', '(PyObject* pyCoords, PyObject* pyPens, PyObject* pyBrushes)',
        body="return wxPyDrawXXXList(*self, wxPyDrawXXXPolygon, pyCoords, pyPens, pyBrushes);")

    c.addCppMethod('PyObject*', '_DrawTextList',
        '(PyObject* textList, PyObject* pyPoints, PyObject* foregroundList, PyObject* backgroundList)',
        body="return wxPyDrawTextList(*self, textList, pyPoints, foregroundList, backgroundList);")


    c.addPyMethod('DrawPointList', '(self, points, pens=None)',
        doc="""\
            Draw a list of points as quickly as possible.

            :param points: A sequence of 2-element sequences representing
                           each point to draw, (x,y).
            :param pens:   If None, then the current pen is used.  If a single
                           pen then it will be used for all points.  If a list of
                           pens then there should be one for each point in points.
            """,
        body="""\
            if pens is None:
                pens = []
            elif isinstance(pens, wx.Pen):
                pens = [pens]
            elif len(pens) != len(points):
                raise ValueError('points and pens must have same length')
            return self._DrawPointList(points, pens, [])
            """)

    c.addPyMethod('DrawLineList', '(self, lines, pens=None)',
        doc="""\
            Draw a list of lines as quickly as possible.

            :param lines: A sequence of 4-element sequences representing
                          each line to draw, (x1,y1, x2,y2).
            :param pens:  If None, then the current pen is used.  If a
                          single pen then it will be used for all lines.  If
                          a list of pens then there should be one for each line
                          in lines.
            """,
        body="""\
            if pens is None:
                pens = []
            elif isinstance(pens, wx.Pen):
                pens = [pens]
            elif len(pens) != len(lines):
                raise ValueError('lines and pens must have same length')
            return self._DrawLineList(lines, pens, [])
            """)

    c.addPyMethod('DrawRectangleList', '(self, rectangles, pens=None, brushes=None)',
        doc="""\
            Draw a list of rectangles as quickly as possible.

            :param rectangles: A sequence of 4-element sequences representing
                               each rectangle to draw, (x,y, w,h).
            :param pens:       If None, then the current pen is used.  If a
                               single pen then it will be used for all rectangles.
                               If a list of pens then there should be one for each
                               rectangle in rectangles.
            :param brushes:    A brush or brushes to be used to fill the rectagles,
                               with similar semantics as the pens parameter.
            """,
        body="""\
            if pens is None:
                pens = []
            elif isinstance(pens, wx.Pen):
                pens = [pens]
            elif len(pens) != len(rectangles):
                raise ValueError('rectangles and pens must have same length')
            if brushes is None:
                brushes = []
            elif isinstance(brushes, wx.Brush):
                brushes = [brushes]
            elif len(brushes) != len(rectangles):
                raise ValueError('rectangles and brushes must have same length')
            return self._DrawRectangleList(rectangles, pens, brushes)
            """)

    c.addPyMethod('DrawEllipseList', '(self, ellipses, pens=None, brushes=None)',
        doc="""\
            Draw a list of ellipses as quickly as possible.

            :param ellipses: A sequence of 4-element sequences representing
                             each ellipse to draw, (x,y, w,h).
            :param pens:     If None, then the current pen is used.  If a
                             single pen then it will be used for all ellipses.
                             If a list of pens then there should be one for each
                             ellipse in ellipses.
            :param brushes:  A brush or brushes to be used to fill the ellipses,
                             with similar semantics as the pens parameter.
            """,
        body="""\
            if pens is None:
                pens = []
            elif isinstance(pens, wx.Pen):
                pens = [pens]
            elif len(pens) != len(ellipses):
                raise ValueError('ellipses and pens must have same length')
            if brushes is None:
                brushes = []
            elif isinstance(brushes, wx.Brush):
                brushes = [brushes]
            elif len(brushes) != len(ellipses):
                raise ValueError('ellipses and brushes must have same length')
            return self._DrawEllipseList(ellipses, pens, brushes)
            """)

    c.addPyMethod('DrawPolygonList', '(self, polygons, pens=None, brushes=None)',
        doc="""\
            Draw a list of polygons, each of which is a list of points.

            :param polygons: A sequence of sequences of sequences.
                             [[(x1,y1),(x2,y2),(x3,y3)...], [(x1,y1),(x2,y2),(x3,y3)...]]

            :param pens:     If None, then the current pen is used.  If a
                             single pen then it will be used for all polygons.
                             If a list of pens then there should be one for each
                             polygon.
            :param brushes:  A brush or brushes to be used to fill the polygons,
                             with similar semantics as the pens parameter.
            """,
        body="""\
            if pens is None:
                pens = []
            elif isinstance(pens, wx.Pen):
                pens = [pens]
            elif len(pens) != len(polygons):
                raise ValueError('polygons and pens must have same length')
            if brushes is None:
                brushes = []
            elif isinstance(brushes, wx.Brush):
                brushes = [brushes]
            elif len(brushes) != len(polygons):
                raise ValueError('polygons and brushes must have same length')
            return self._DrawPolygonList(polygons, pens, brushes)
            """)

    c.addPyMethod('DrawTextList', '(self, textList, coords, foregrounds=None, backgrounds=None)',
        doc="""\
            Draw a list of strings using a list of coordinants for positioning each string.

            :param textList:    A list of strings
            :param coords:      A list of (x,y) positions
            :param foregrounds: A list of `wx.Colour` objects to use for the
                                foregrounds of the strings.
            :param backgrounds: A list of `wx.Colour` objects to use for the
                                backgrounds of the strings.

            NOTE: Make sure you set background mode to wx.Solid (DC.SetBackgroundMode)
                  If you want backgrounds to do anything.
            """,
        body="""\
            if type(textList) == type(''):
                textList = [textList]
            elif len(textList) != len(coords):
                raise ValueError('textlist and coords must have same length')
            if foregrounds is None:
                foregrounds = []
            elif isinstance(foregrounds, wx.Colour):
                foregrounds = [foregrounds]
            elif len(foregrounds) != len(coords):
                raise ValueError('foregrounds and coords must have same length')
            if backgrounds is None:
                backgrounds = []
            elif isinstance(backgrounds, wx.Colour):
                backgrounds = [backgrounds]
            elif len(backgrounds) != len(coords):
                raise ValueError('backgrounds and coords must have same length')
            return  self._DrawTextList(textList, coords, foregrounds, backgrounds)
            """)




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


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


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


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


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


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


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


    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #27
0
ファイル: window.py プロジェクト: ghisvail/Phoenix
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)

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

    c = module.find('wxWindow')
    assert isinstance(c, etgtools.ClassDef)
    module.addGlobalStr('wxPanelNameStr', c)

    c.find('FindFocus').mustHaveApp()
    c.find('GetCapture').mustHaveApp()

    # First we need to let the wrapper generator know about wxWindowBase since
    # AddChild and RemoveChild need to use that type in order to be virtualized.
    winbase = ClassDef(
        name='wxWindowBase',
        bases=['wxEvtHandler'],
        abstract=True,
        items=[
            MethodDef(name='AddChild',
                      isVirtual=True,
                      type='void',
                      protection='public',
                      items=[ParamDef(name='child', type='wxWindowBase*')]),
            MethodDef(name='RemoveChild',
                      isVirtual=True,
                      type='void',
                      protection='public',
                      items=[ParamDef(name='child', type='wxWindowBase*')])
        ])
    module.insertItemBefore(c, winbase)

    # Now change the base class of wxWindow
    c.bases = ['wxWindowBase']

    # And fix the arg types we get from Doxy
    c.find('AddChild.child').type = 'wxWindowBase*'
    c.find('RemoveChild.child').type = 'wxWindowBase*'

    # We now return you to our regularly scheduled programming...
    c.includeCppCode('src/window_ex.cpp')

    # ignore some overloads that will be ambiguous afer wrapping
    c.find('GetChildren').overloads = []
    c.find('GetChildren').noCopy = True
    for name in ['GetVirtualSize', 'GetPosition', 'GetScreenPosition']:
        c.find(name).findOverload('int *').ignore()

    # Fix ClientToScreen/ScreenToClient int * overloads
    for name in ['ClientToScreen', 'ScreenToClient']:
        c.find(name).findOverload('int *').find('x').inOut = True
        c.find(name).findOverload('int *').find('y').inOut = True

    # Like the above, but these also need to transplant the docs from the
    # ignored item to the non-ignored overload.
    for name in ['GetClientSize', 'GetSize']:
        c.find(name).findOverload('int *').ignore()
        item = c.find(name)
        ov = item.overloads[0]
        item.briefDoc = ov.briefDoc
        item.detailedDoc = ov.detailedDoc

    # Release the GIL for potentially blocking or long-running functions
    c.find('PopupMenu').releaseGIL()
    c.find('ProcessEvent').releaseGIL()
    c.find('ProcessWindowEvent').releaseGIL()
    c.find('ProcessWindowEventLocally').releaseGIL()

    # Add a couple wrapper functions for symmetry with the getters of the same name
    c.addPyMethod('SetRect', '(self, rect)', 'return self.SetSize(rect)')
    c.addPyProperty('Rect GetRect SetRect')
    c.addPyMethod('SetClientRect', '(self, rect)',
                  'return self.SetClientSize(rect)')
    c.addPyProperty('ClientRect GetClientRect SetClientRect')

    m = c.find('GetTextExtent').findOverload('int *')
    m.pyName = 'GetFullTextExtent'
    m.find('w').out = True
    m.find('h').out = True
    m.find('descent').out = True
    m.find('externalLeading').out = True

    c.find('GetHandle').type = 'wxUIntPtr*'
    c.find('GetHandle').setCppCode(
        "return new wxUIntPtr(wxPyGetWinHandle(self));")

    c.addCppMethod(
        'void*', 'GetGtkWidget', '()', """\
    #ifdef __WXGTK__
        return (void*)self->GetHandle();
    #else
        return NULL;
    #endif
    """)

    c.addCppMethod('void',
                   'AssociateHandle',
                   '(long handle)',
                   doc="Associate the window with a new native handle",
                   body="self->AssociateHandle((WXWidget)handle);")
    c.addCppMethod('void',
                   'DissociateHandle',
                   '()',
                   doc="Dissociate the current native handle from the window",
                   body="self->DissociateHandle();")

    # Add some new methods
    c.addCppMethod(
        'wxWindow*',
        'GetTopLevelParent',
        '()',
        'return wxGetTopLevelParent(self);',
        briefDoc=
        "Returns the first ancestor of this window which is a top-level window."
    )

    c.addCppMethod(
        'bool',
        'MacIsWindowScrollbar',
        '(const wxWindow* sb)',
        """\
    #ifdef __WXMAC__
        return self->MacIsWindowScrollbar(sb);
    #else
        return false;
    #endif
    """,
        pyArgsString="(sb)",
        briefDoc=
        "Is the given widget one of this window's built-in scrollbars?  Only applicable on Mac."
    )

    c.addCppMethod(
        'void',
        'SetDimensions',
        '(int x, int y, int width, int height, int sizeFlags=wxSIZE_AUTO)',
        pyArgsString="(x, y, width, height, sizeFlags=SIZE_AUTO)",
        body="""\
        self->SetSize(x, y, width, height, sizeFlags);
        """)
    c.addPyCode(
        "Window.SetDimensions = wx.deprecated(Window.SetDimensions, 'Use SetSize instead.')"
    )

    # Make the Register/UnregisterHotKey functions be available on Windows,
    # and empty stubs otherwise
    c.find('RegisterHotKey').setCppCode("""\
    #if wxUSE_HOTKEY
        return self->RegisterHotKey(hotkeyId, modifiers, virtualKeyCode);
    #else
        return false;
    #endif
    """)
    c.find('UnregisterHotKey').setCppCode("""\
    #if wxUSE_HOTKEY
        return self->UnregisterHotKey(hotkeyId);
    #else
        return false;
    #endif
    """)
    c.find('RegisterHotKey').isVirtual = False
    c.find('UnregisterHotKey').isVirtual = False

    c.find('SetDoubleBuffered').setCppCode("""\
    #if defined(__WXGTK20__) || defined(__WXGTK3__) || defined(__WXMSW__)
        self->SetDoubleBuffered(on);
    #endif
    """)

    c.addPyMethod(
        '__nonzero__',
        '(self)',
        doc=
        "Can be used to test if the C++ part of the window still exists, with \n"
        "code like this::\n\n"
        "    if theWindow:\n"
        "        doSomething()",
        body="""\
        import wx.siplib
        return not wx.siplib.isdeleted(self)
        """)
    c.addPyCode('Window.__bool__ = Window.__nonzero__')  # For Python 3

    c.addPyMethod('DestroyLater',
                  '(self)',
                  doc="""\
           Schedules the window to be destroyed in the near future.

           This should be used whenever Destroy could happen too soon, such
           as when there may still be events for this window or its children
           waiting in the event queue.
           """,
                  body="""\
            self.Hide()
            wx.GetApp().ScheduleForDestruction(self)
            """)

    c.addPyMethod('DLG_UNIT',
                  '(self, dlg_unit)',
                  doc="""\
            A convenience wrapper for :meth:`ConvertDialogToPixels`.
            """,
                  body="""\
            is_wxType = isinstance(dlg_unit, (wx.Size, wx.Point))
            pix = self.ConvertDialogToPixels(dlg_unit)
            if not is_wxType:
                pix = tuple(pix)
            return pix
            """)

    # MSW only.  Do we want them wrapped?
    c.find('GetAccessible').ignore()
    c.find('SetAccessible').ignore()

    # Make some of the protected methods visible and overridable from Python
    c.find('SendDestroyEvent').ignore(False)

    c.find('Destroy').transferThis = True
    c.addPyMethod('PostCreate',
                  '(self, pre)',
                  'pass',
                  deprecated='PostCreate is no longer necessary.')

    # transfer ownership of these parameters to the C++ object
    c.find('SetCaret.caret').transfer = True
    c.find('SetToolTip.tip').transfer = True
    c.find('SetDropTarget.target').transfer = True
    c.find('SetConstraints.constraints').transfer = True
    c.find('SetSizer.sizer').transfer = True
    c.find('SetSizerAndFit.sizer').transfer = True

    # Change some =0 default values to =NULL so the docs will make more sense
    c.find('FindWindowById.parent').default = 'NULL'
    c.find('FindWindowByLabel.parent').default = 'NULL'
    c.find('FindWindowByName.parent').default = 'NULL'

    # Define some properties using the getter and setter methods
    c.addProperty('AcceleratorTable GetAcceleratorTable SetAcceleratorTable')
    c.addProperty('AutoLayout GetAutoLayout SetAutoLayout')
    c.addProperty('BackgroundColour GetBackgroundColour SetBackgroundColour')
    c.addProperty('BackgroundStyle GetBackgroundStyle SetBackgroundStyle')
    c.addProperty('EffectiveMinSize GetEffectiveMinSize')
    c.addProperty('BestSize GetBestSize')
    c.addProperty('BestVirtualSize GetBestVirtualSize')
    c.addProperty('Border GetBorder')
    c.addProperty('Caret GetCaret SetCaret')
    c.addProperty('CharHeight GetCharHeight')
    c.addProperty('CharWidth GetCharWidth')
    c.addProperty('Children GetChildren')
    c.addProperty('ClientAreaOrigin GetClientAreaOrigin')
    c.addProperty('ClientSize GetClientSize SetClientSize')
    c.addProperty('Constraints GetConstraints SetConstraints')
    c.addProperty('ContainingSizer GetContainingSizer SetContainingSizer')
    c.addProperty('Cursor GetCursor SetCursor')
    c.addProperty('DefaultAttributes GetDefaultAttributes')
    c.addProperty('DropTarget GetDropTarget SetDropTarget')
    c.addProperty('EventHandler GetEventHandler SetEventHandler')
    c.addProperty('ExtraStyle GetExtraStyle SetExtraStyle')
    c.addProperty('Font GetFont SetFont')
    c.addProperty('ForegroundColour GetForegroundColour SetForegroundColour')
    c.addProperty('GrandParent GetGrandParent')
    c.addProperty('TopLevelParent GetTopLevelParent')
    c.addProperty('Handle GetHandle')
    c.addProperty('HelpText GetHelpText SetHelpText')
    c.addProperty('Id GetId SetId')
    c.addProperty('Label GetLabel SetLabel')
    c.addProperty('LayoutDirection GetLayoutDirection SetLayoutDirection')
    c.addProperty('MaxHeight GetMaxHeight')
    c.addProperty('MaxSize GetMaxSize SetMaxSize')
    c.addProperty('MaxWidth GetMaxWidth')
    c.addProperty('MinHeight GetMinHeight')
    c.addProperty('MinSize GetMinSize SetMinSize')
    c.addProperty('MinWidth GetMinWidth')
    c.addProperty('Name GetName SetName')
    c.addProperty('Parent GetParent')
    c.addProperty('Position GetPosition SetPosition')
    c.addProperty('ScreenPosition GetScreenPosition')
    c.addProperty('ScreenRect GetScreenRect')
    c.addProperty('Size GetSize SetSize')
    c.addProperty('Sizer GetSizer SetSizer')
    c.addProperty('ThemeEnabled GetThemeEnabled SetThemeEnabled')
    c.addProperty('ToolTip GetToolTip SetToolTip')
    c.addProperty('UpdateClientRect GetUpdateClientRect')
    c.addProperty('UpdateRegion GetUpdateRegion')
    c.addProperty('Validator GetValidator SetValidator')
    c.addProperty('VirtualSize GetVirtualSize SetVirtualSize')
    c.addProperty('WindowStyle GetWindowStyle SetWindowStyle')
    c.addProperty('WindowStyleFlag GetWindowStyleFlag SetWindowStyleFlag')
    c.addProperty('WindowVariant GetWindowVariant SetWindowVariant')
    c.addProperty('Shown IsShown Show')
    c.addProperty('Enabled IsEnabled Enable')
    c.addProperty('TopLevel IsTopLevel')
    c.addProperty('MinClientSize GetMinClientSize SetMinClientSize')
    c.addProperty('MaxClientSize GetMaxClientSize SetMaxClientSize')
    ##c.addProperty('GtkWidget GetGtkWidget')

    tools.fixWindowClass(c)
    tools.addSipConvertToSubClassCode(c)

    # for compatibility with Classic
    c.addPyMethod('GetPositionTuple',
                  '(self)',
                  'return self.GetPosition()',
                  deprecated='Use GetPosition instead')
    c.addPyMethod('GetSizeTuple',
                  '(self)',
                  'return self.GetSize()',
                  deprecated='Use GetSize instead')
    c.addPyMethod('MoveXY',
                  '(self, x, y)',
                  'return self.Move(x, y)',
                  deprecated='Use Move instead.')
    c.addPyMethod('SetSizeWH',
                  '(self, w, h)',
                  'return self.SetSize(w,h)',
                  deprecated='Use SetSize instead.')
    c.addPyMethod('SetVirtualSizeWH',
                  '(self, w, h)',
                  'return self.SetVirtualSize(w,h)',
                  deprecated='Use SetVirtualSize instead.')
    c.addPyMethod('GetVirtualSizeTuple',
                  '(self)',
                  'return self.GetVirtualSize()',
                  deprecated='Use GetVirtualSize instead.')
    c.addPyMethod('SetToolTipString',
                  '(self, string)',
                  'return self.SetToolTip(string)',
                  deprecated='Use SetToolTip instead.')
    c.addPyMethod('ConvertDialogPointToPixels',
                  '(self, point)',
                  'return self.ConvertDialogToPixels(point)',
                  deprecated='Use ConvertDialogToPixels instead.')
    c.addPyMethod('ConvertDialogSizeToPixels',
                  '(self, size)',
                  'return self.ConvertDialogToPixels(point)',
                  deprecated='Use ConvertDialogToPixels instead.')

    c.addPyMethod(
        'SetSizeHintsSz',
        '(self, minSize, maxSize=wx.DefaultSize, incSize=wx.DefaultSize)',
        'return self.SetSizeHints(minSize, maxSize, incSize)',
        deprecated='Use SetSizeHints instead.')

    # TODO: the C++ DoEraseBackground is protected in wxMSW. We need a way to
    # unprotect it, like adding a shim in the sip class...
    #c.addHeaderCode("""\
    #    #ifdef __WXMSW__
    #    #include <wx/msw/dc.h>
    #    #endif
    #    """)
    #c.addCppMethod('bool', 'DoEraseBackground', '(wxDC* dc)',
    #    doc="Default erase background implementation.",
    #    body="""\
    #    #ifdef __WXMSW__
    #        return self->DoEraseBackground(((wxMSWDCImpl*)dc->GetImpl())->GetHDC());
    #    #else
    #        dc->SetBackground(wxBrush(self->GetBackgroundColour()));
    #        dc->Clear();
    #        return true;
    #    #endif
    #    """)

    # this is a nested class
    c.find('ChildrenRepositioningGuard').addPrivateCopyCtor()
    module.insertItem(
        0,
        etgtools.TypedefDef(type='wxWindow::ChildrenRepositioningGuard',
                            name='ChildrenRepositioningGuard'))

    #-----------------------------------------------------------------------
    # Other stuff

    module.addPyCode('''\
    class FrozenWindow(object):
        """
        A context manager to be used with Python 'with' statements
        that will freeze the given window for the duration of the
        with block.
        """
        def __init__(self, window):
            self._win = window
        def __enter__(self):
            self._win.Freeze()
            return self
        def __exit__(self, exc_type, exc_val, exc_tb):
            self._win.Thaw()
    ''')

    module.addPyCode('''\
        def DLG_UNIT(win, dlg_unit, val2=None):
            """
            Convenience function for converting a wx.Point, wx.Size or
            (x,y) in dialog units to pixels, using the given window as a 
            reference.
            """
            if val2 is not None:
                dlg_unit = (dlg_unit, val2)
            is_wxType = isinstance(dlg_unit, (wx.Size, wx.Point))
            pix = win.ConvertDialogToPixels(dlg_unit)
            if not is_wxType:
                pix = tuple(pix)
            return pix

        DLG_PNT = wx.deprecated(DLG_UNIT, "Use DLG_UNIT instead.")
        DLG_SZE = wx.deprecated(DLG_UNIT, "Use DLG_UNIT instead.")
        ''')

    # Add a wrapper for wxWindowList and a new iterator class for it that
    # makes wxWindowList quack like a read-only Python sequence.
    module.addItem(
        tools.wxListWrapperTemplate('wxWindowList', 'wxWindow', module))

    module.addCppFunction(
        'wxWindowList*',
        'GetTopLevelWindows',
        '()',
        noCopy=True,
        briefDoc=
        "Returns a list-like object of the the application's top-level windows, (frames,dialogs, etc.)",
        body="return &wxTopLevelWindows;")

    module.addPyCode("PyWindow = wx.deprecated(Window, 'Use Window instead.')")

    module.find('wxFindWindowAtPointer.pt').out = True

    module.find('wxFindWindowAtPointer').mustHaveApp()
    module.find('wxGetActiveWindow').mustHaveApp()
    module.find('wxGetTopLevelParent').mustHaveApp()

    module.addCppFunction('wxWindow*',
                          'FindWindowById',
                          '(long id, const wxWindow* parent=NULL)',
                          doc="""\
            FindWindowById(id, parent=None) -> Window

            Find the first window in the application with the given id. If parent
            is None, the search will start from all top-level frames and dialog
            boxes; if non-None, the search will be limited to the given window
            hierarchy. The search is recursive in both cases.
            """,
                          body="return wxWindow::FindWindowById(id, parent);",
                          mustHaveAppFlag=True)

    module.addCppFunction(
        'wxWindow*',
        'FindWindowByName',
        '(const wxString& name, const wxWindow* parent=NULL)',
        doc="""\
            FindWindowByName(name, parent=None) -> Window

            Find a window by its name (as given in a window constructor or Create
            function call). If parent is None, the search will start from all
            top-level frames and dialog boxes; if non-None, the search will be
            limited to the given window hierarchy. The search is recursive in both
            cases.

            If no window with the name is found, wx.FindWindowByLabel is called.""",
        body="return wxWindow::FindWindowByName(*name, parent);",
        mustHaveAppFlag=True)

    module.addCppFunction(
        'wxWindow*',
        'FindWindowByLabel',
        '(const wxString& label, const wxWindow* parent=NULL)',
        doc="""\
            FindWindowByLabel(label, parent=None) -> Window

            Find a window by its label. Depending on the type of window, the label
            may be a window title or panel item label. If parent is None, the
            search will start from all top-level frames and dialog boxes; if
            non-None, the search will be limited to the given window
            hierarchy. The search is recursive in both cases.""",
        body="return wxWindow::FindWindowByLabel(*label, parent);",
        mustHaveAppFlag=True)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #28
0
ファイル: calctrl.py プロジェクト: www3838438/Phoenix
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('wxCalendarEvent')
    assert isinstance(c, etgtools.ClassDef)
    tools.fixEventClass(c)

    module.addPyCode("""\
        EVT_CALENDAR =                 wx.PyEventBinder( wxEVT_CALENDAR_DOUBLECLICKED, 1)
        EVT_CALENDAR_SEL_CHANGED =     wx.PyEventBinder( wxEVT_CALENDAR_SEL_CHANGED, 1)
        EVT_CALENDAR_WEEKDAY_CLICKED = wx.PyEventBinder( wxEVT_CALENDAR_WEEKDAY_CLICKED, 1)
        EVT_CALENDAR_PAGE_CHANGED =    wx.PyEventBinder( wxEVT_CALENDAR_PAGE_CHANGED, 1)
        """)

    # These are deprecated, get rid of them later...
    module.addPyCode("""\
        EVT_CALENDAR_DAY =             wx.PyEventBinder( wxEVT_CALENDAR_DAY_CHANGED, 1)
        EVT_CALENDAR_MONTH =           wx.PyEventBinder( wxEVT_CALENDAR_MONTH_CHANGED, 1)
        EVT_CALENDAR_YEAR =            wx.PyEventBinder( wxEVT_CALENDAR_YEAR_CHANGED, 1)
        """)
    for name in [
            'wxEVT_CALENDAR_DAY_CHANGED', 'wxEVT_CALENDAR_MONTH_CHANGED',
            'wxEVT_CALENDAR_YEAR_CHANGED'
    ]:
        item = etgtools.GlobalVarDef(name=name,
                                     pyName=name,
                                     type='wxEventType')
        module.insertItemAfter(module.find('wxEVT_CALENDAR_WEEK_CLICKED'),
                               item)

    cc = module.find('wxCalendarCtrl')
    gcc = tools.copyClassDef(cc, 'wxGenericCalendarCtrl')
    module.insertItemAfter(cc, gcc)

    for c in [cc, gcc]:
        tools.fixWindowClass(c)
        c.find('GetDateRange.lowerdate').out = True
        c.find('GetDateRange.upperdate').out = True
        c.find('HitTest.date').out = True
        c.find('HitTest.wd').out = True
        c.find('SetAttr.attr').transfer = True

        c.addPyCode("""\
            {name}.PyGetDate = wx.deprecated({name}.GetDate, 'Use GetDate instead.')
            {name}.PySetDate = wx.deprecated({name}.SetDate, 'Use SetDate instead.')
            {name}.PySetDateRange = wx.deprecated({name}.SetDateRange, 'Use SetDateRange instead.')
            """.format(name=c.name[2:]))

    cc.find('EnableYearChange').ignore()
    gcc.addHeaderCode("#include <wx/generic/calctrlg.h>")

    module.addGlobalStr('wxCalendarNameStr', cc)

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

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

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

    # Set mustHaveApp on all ctors except the default ctor
    for ctor in c.find('wxBrush').all():
        if ctor.isCtor and ctor.argsString != '()':
            ctor.mustHaveApp()

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

    c.addCppCode("""\
        #ifdef __WXMAC__
        #include <wx/osx/private.h>
        #endif
        """)
    c.addCppMethod(
        'void', 'MacSetTheme', '(int macThemeBrushID)', """\
        #ifdef __WXMAC__
            self->SetColour(wxColour(wxMacCreateCGColorFromHITheme(macThemeBrushID)));
        #else
            wxPyRaiseNotImplemented();
        #endif
        """)

    c.addAutoProperties()

    # The stock Brush items are documented as simple pointers, but in reality
    # they are macros that evaluate to a function call that returns a brush
    # pointer, and that is only valid *after* the wx.App object has been
    # created. That messes up the code that SIP generates for them, so we need
    # to come up with another solution. So instead we will just create
    # uninitialized brush in a block of Python code, that will then be
    # intialized later when the wx.App is created.
    c.addCppMethod('void',
                   '_copyFrom',
                   '(const wxBrush* other)',
                   "*self = *other;",
                   briefDoc="For internal use only.")  # ??
    pycode = '# These stock brushes will be initialized when the wx.App object is created.\n'
    for item in module:
        if '_BRUSH' in item.name:
            item.ignore()
            pycode += '%s = Brush()\n' % tools.removeWxPrefix(item.name)
    module.addPyCode(pycode)

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

    # Some aliases that should be phased out eventually, (sooner rather than
    # later.) They are already gone (or wrapped by an #if) in the C++ code,
    # and so are not found in the documentation...
    module.addPyCode("""\
        wx.STIPPLE_MASK_OPAQUE = int(wx.BRUSHSTYLE_STIPPLE_MASK_OPAQUE)
        wx.STIPPLE_MASK        = int(wx.BRUSHSTYLE_STIPPLE_MASK)
        wx.STIPPLE             = int(wx.BRUSHSTYLE_STIPPLE)
        wx.BDIAGONAL_HATCH     = int(wx.BRUSHSTYLE_BDIAGONAL_HATCH)
        wx.CROSSDIAG_HATCH     = int(wx.BRUSHSTYLE_CROSSDIAG_HATCH)
        wx.FDIAGONAL_HATCH     = int(wx.BRUSHSTYLE_FDIAGONAL_HATCH)
        wx.CROSS_HATCH         = int(wx.BRUSHSTYLE_CROSS_HATCH)
        wx.HORIZONTAL_HATCH    = int(wx.BRUSHSTYLE_HORIZONTAL_HATCH)
        wx.VERTICAL_HATCH      = int(wx.BRUSHSTYLE_VERTICAL_HATCH)
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
コード例 #30
0
ファイル: axbase.py プロジェクト: jessjames541/Jessem
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)

    #-----------------------------------------------------------------
    # The wxPyAxBaseWindow class does not come from the parsed Doxygen xml,
    # instead it is manufactured entirely in this ETG script.  We're doing it
    # here instead of in a raw .sip file so we can run the generators on it
    # and get things like documentation and .pyi files generated like any
    # normal class.

    # First, output some C++ code
    module.addHeaderCode("""\
        class wxPyAxBaseWindow : public wxWindow
        {
            DECLARE_DYNAMIC_CLASS(wxPyAxBaseWindow)
        public:
            wxPyAxBaseWindow(wxWindow* parent, const wxWindowID id=-1,
                            const wxPoint& pos = wxDefaultPosition,
                            const wxSize& size = wxDefaultSize,
                            long style = 0,
                            const wxString& name = wxPanelNameStr)
            : wxWindow(parent, id, pos, size, style, name) {}
            wxPyAxBaseWindow() : wxWindow() {}
            virtual bool MSWTranslateMessage(WXMSG* msg)
            {
                return wxWindow::MSWTranslateMessage(msg);
            }
        };
        """)
    module.addCppCode("""\
        IMPLEMENT_DYNAMIC_CLASS(wxPyAxBaseWindow, wxWindow);
        """)

    # Now create the extractor objects that will be run through the generators
    module.addItem(TypedefDef(type='void', name='WXMSG'))

    cls = ClassDef(name='wxPyAxBaseWindow',
                   bases=['wxWindow'],
                   briefDoc="""\
            A Window class for use with ActiveX controls.

            This Window class exposes some low-level Microsoft Windows
            specific methods which can be overridden in Python.  Intended for
            use as an ActiveX container, but could also be useful
            elsewhere.""",
                   items=[
                       MethodDef(name='wxPyAxBaseWindow',
                                 isCtor=True,
                                 items=[
                                     ParamDef(type='wxWindow*', name='parent'),
                                     ParamDef(type='const wxWindowID',
                                              name='id',
                                              default='-1'),
                                     ParamDef(type='const wxPoint&',
                                              name='pos',
                                              default='wxDefaultPosition'),
                                     ParamDef(type='const wxSize&',
                                              name='size',
                                              default='wxDefaultSize'),
                                     ParamDef(type='long',
                                              name='style',
                                              default='0'),
                                     ParamDef(type='const wxString&',
                                              name='name',
                                              default='wxPanelNameStr'),
                                 ],
                                 overloads=[
                                     MethodDef(name='wxPyAxBaseWindow',
                                               isCtor=True),
                                 ]),
                       MethodDef(type='bool',
                                 name='MSWTranslateMessage',
                                 isVirtual=True,
                                 items=[ParamDef(type='WXMSG*', name='msg')])
                   ])

    module.addItem(cls)

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