예제 #1
0
파일: app.py 프로젝트: wqqforever/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.find('wxDISABLE_DEBUG_SUPPORT').ignore()

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

    etgtools.prependText(
        c.detailedDoc,
        "Note that it is not intended for this class to be used directly from "
        "Python. It is wrapped just for inheriting its methods in :class:`App`."
    )

    # There's no need for the command line stuff as Python has its own ways to
    # deal with that
    c.find('argc').ignore()
    c.find('argv').ignore()
    c.find('OnCmdLineError').ignore()
    c.find('OnCmdLineHelp').ignore()
    c.find('OnCmdLineParsed').ignore()
    c.find('OnInitCmdLine').ignore()

    c.find('HandleEvent').ignore()

    # We will use OnAssertFailure, but I don't think we should let it be
    # overridden in Python.
    c.find('OnAssertFailure').ignore()

    # TODO: Decide if these should be visible from Python. They are for
    # dealing with C/C++ exceptions, but perhaps we could also add the ability
    # to deal with unhandled Python exceptions using these (overridable)
    # methods too.
    c.find('OnExceptionInMainLoop').ignore()
    c.find('OnFatalException').ignore()
    c.find('OnUnhandledException').ignore()
    c.find('StoreCurrentException').ignore()
    c.find('RethrowStoredException').ignore()

    # Release the GIL for potentially blocking or long-running functions
    c.find('MainLoop').releaseGIL()
    c.find('ProcessPendingEvents').releaseGIL()
    c.find('Yield').releaseGIL()

    c.addProperty('AppDisplayName GetAppDisplayName SetAppDisplayName')
    c.addProperty('AppName GetAppName SetAppName')
    c.addProperty('ClassName GetClassName SetClassName')
    c.addProperty(
        'VendorDisplayName GetVendorDisplayName SetVendorDisplayName')
    c.addProperty('VendorName GetVendorName SetVendorName')
    c.addProperty('Traits GetTraits')

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

    # Add a new C++ wxPyApp class that adds empty Mac* methods for other
    # platforms, and other goodies, then change the name so SIP will
    # generate code wrapping this class as if it was the wxApp class seen in
    # the DoxyXML.
    c.includeCppCode('src/app_ex.cpp')

    # Now change the class name, ctors and dtor names from wxApp to wxPyApp
    for item in c.allItems():
        if item.name == 'wxApp':
            item.name = 'wxPyApp'
        if item.name == '~wxApp':
            item.name = '~wxPyApp'

    c.find('ProcessMessage').ignore()

    c.addCppMethod('void',
                   'MacHideApp',
                   '()',
                   doc="""\
            Hide all application windows just as the user can do with the
            system Hide command.  Mac only.""",
                   body="""\
            #ifdef __WXMAC__
                self->MacHideApp();
            #endif
            """)

    c.addCppMethod('int',
                   'GetComCtl32Version',
                   '()',
                   isStatic=True,
                   doc="""\
        Returns 400, 470, 471, etc. for comctl32.dll 4.00, 4.70, 4.71 or 0 if
        it wasn't found at all.  Raises an exception on non-Windows platforms.""",
                   body="""\
            #ifdef __WXMSW__
                return wxApp::GetComCtl32Version();
            #else
                wxPyRaiseNotImplemented();
                return 0;
            #endif
            """)

    # Remove the virtualness from these methods
    for m in [
            'GetDisplayMode',
            'GetLayoutDirection',
            'GetTopWindow',
            'IsActive',
            'SafeYield',
            'SafeYieldFor',
            'SetDisplayMode',
            'SetNativeTheme',
    ]:
        c.find(m).isVirtual = False

    # Methods we implement in wxPyApp beyond what are in wxApp, plus some
    # overridden virtuals (or at least some that we want the wrapper
    # generator to treat as if they are overridden.)
    #
    # TODO: Add them as etg method objects instead of a WigCode block so the
    # documentation generators will see them too
    c.addItem(
        etgtools.WigCode("""\
        protected:
        virtual bool TryBefore(wxEvent& event);
        virtual bool TryAfter(wxEvent& event);

        public:
        virtual int  MainLoop() /ReleaseGIL/;
        virtual void OnPreInit();
        virtual bool OnInit();
        virtual bool OnInitGui();
        virtual int  OnRun();
        virtual int  OnExit();

        void         _BootstrapApp();

        static long GetMacAboutMenuItemId();
        static long GetMacPreferencesMenuItemId();
        static long GetMacExitMenuItemId();
        static wxString GetMacHelpMenuTitleName();
        static void SetMacAboutMenuItemId(long val);
        static void SetMacPreferencesMenuItemId(long val);
        static void SetMacExitMenuItemId(long val);
        static void SetMacHelpMenuTitleName(const wxString& val);
        """))

    # Add these methods by creating extractor objects so they can be tweaked
    # like normal, their docs will be able to be generated, etc.
    c.addItem(
        etgtools.MethodDef(
            protection='public',
            type='wxAppAssertMode',
            name='GetAssertMode',
            argsString='()',
            briefDoc=
            "Returns the current mode for how the application responds to wx asserts.",
            className=c.name))

    m = etgtools.MethodDef(protection='public',
                           type='void',
                           name='SetAssertMode',
                           argsString='(wxAppAssertMode mode)',
                           briefDoc="""\
        Set the mode indicating how the application responds to wx assertion
        statements. Valid settings are a combination of these flags:

            - wx.APP_ASSERT_SUPPRESS
            - wx.APP_ASSERT_EXCEPTION
            - wx.APP_ASSERT_DIALOG
            - wx.APP_ASSERT_LOG

        The default behavior is to raise a wx.wxAssertionError exception.
        """,
                           className=c.name)

    m.addItem(etgtools.ParamDef(type='wxAppAssertMode',
                                name='wxAppAssertMode'))
    c.addItem(m)

    c.addItem(
        etgtools.MethodDef(protection='public',
                           isStatic=True,
                           type='bool',
                           name='IsDisplayAvailable',
                           argsString='()',
                           briefDoc="""\
        Returns True if the application is able to connect to the system's
        display, or whatever the equivallent is for the platform.""",
                           className=c.name))

    # Release the GIL for potentially blocking or long-running functions
    c.find('SafeYield').releaseGIL()
    c.find('SafeYieldFor').releaseGIL()

    c.addProperty('AssertMode GetAssertMode SetAssertMode')
    c.addProperty('DisplayMode GetDisplayMode SetDisplayMode')
    c.addProperty(
        'ExitOnFrameDelete GetExitOnFrameDelete SetExitOnFrameDelete')
    c.addProperty('LayoutDirection GetLayoutDirection')
    c.addProperty('UseBestVisual GetUseBestVisual SetUseBestVisual')
    c.addProperty('TopWindow GetTopWindow SetTopWindow')

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

    module.addHeaderCode("""\
        enum wxAppAssertMode {
            wxAPP_ASSERT_SUPPRESS  = 1,
            wxAPP_ASSERT_EXCEPTION = 2,
            wxAPP_ASSERT_DIALOG    = 4,
            wxAPP_ASSERT_LOG       = 8
        };""")
    # add extractor objects for the enum too
    enum = etgtools.EnumDef(name='wxAppAssertMode')
    for eitem in "wxAPP_ASSERT_SUPPRESS wxAPP_ASSERT_EXCEPTION wxAPP_ASSERT_DIALOG wxAPP_ASSERT_LOG".split(
    ):
        enum.addItem(etgtools.EnumValueDef(name=eitem))
    module.insertItemBefore(c, enum)

    module.addHeaderCode("""\
        wxAppConsole* wxGetApp();
        """)
    module.find('wxTheApp').ignore()
    f = module.find('wxGetApp')
    f.type = 'wxAppConsole*'
    f.briefDoc = "Returns the current application object."
    f.detailedDoc = []

    module.find('wxYield').releaseGIL()
    module.find('wxSafeYield').releaseGIL()

    module.addPyFunction(
        'YieldIfNeeded',
        '()',
        doc="Convenience function for wx.GetApp().Yield(True)",
        body="return wx.GetApp().Yield(True)")

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

    # Now add extractor objects for the main App class as a Python class,
    # deriving from the wx.PyApp class that we created above. Also define the
    # stdio helper class too.

    module.addPyClass(
        'PyOnDemandOutputWindow',
        ['object'],
        doc="""\
            A class that can be used for redirecting Python's stdout and
            stderr streams.  It will do nothing until something is wrriten to
            the stream at which point it will create a Frame with a text area
            and write the text there.
            """,
        items=[
            PyFunctionDef('__init__',
                          '(self, title="wxPython: stdout/stderr")',
                          body="""\
                    self.frame  = None
                    self.title  = title
                    self.pos    = wx.DefaultPosition
                    self.size   = (450, 300)
                    self.parent = None
                    """),
            PyFunctionDef(
                'SetParent',
                '(self, parent)',
                doc=
                """Set the window to be used as the popup Frame's parent.""",
                body="""self.parent = parent"""),
            PyFunctionDef('CreateOutputWindow',
                          '(self, txt)',
                          doc="",
                          body="""\
                    self.frame = wx.Frame(self.parent, -1, self.title, self.pos, self.size,
                                          style=wx.DEFAULT_FRAME_STYLE)
                    self.text  = wx.TextCtrl(self.frame, -1, "",
                                             style=wx.TE_MULTILINE|wx.TE_READONLY)
                    self.text.AppendText(txt)
                    self.frame.Show(True)
                    self.frame.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
                    """),
            PyFunctionDef('OnCloseWindow',
                          '(self, event)',
                          doc="",
                          body="""\
                    if self.frame is not None:
                        self.frame.Destroy()
                    self.frame = None
                    self.text  = None
                    self.parent = None
                    """),

            # These methods provide the file-like output behaviour.
            PyFunctionDef('write',
                          '(self, text)',
                          doc="""\
                    Create the output window if needed and write the string to it.
                    If not called in the context of the gui thread then CallAfter is
                    used to do the work there.
                    """,
                          body="""\
                    if self.frame is None:
                        if not wx.IsMainThread():
                            wx.CallAfter(self.CreateOutputWindow, text)
                        else:
                            self.CreateOutputWindow(text)
                    else:
                        if not wx.IsMainThread():
                            wx.CallAfter(self.text.AppendText, text)
                        else:
                            self.text.AppendText(text)
                     """),
            PyFunctionDef('close',
                          '(self)',
                          doc="",
                          body="""\
                    if self.frame is not None:
                        wx.CallAfter(self.frame.Close)
                    """),
            PyFunctionDef('flush', '(self)', 'pass'),
        ])

    module.addPyClass(
        'App', ['PyApp'],
        doc="""\
            The ``wx.App`` class represents the application and is used to:

              * bootstrap the wxPython system and initialize the underlying
                gui toolkit
              * set and get application-wide properties
              * implement the native windowing system main message or event loop,
                and to dispatch events to window instances
              * etc.

            Every wx application must have a single ``wx.App`` instance, and all
            creation of UI objects should be delayed until after the ``wx.App`` object
            has been created in order to ensure that the gui platform and wxWidgets
            have been fully initialized.

            Normally you would derive from this class and implement an ``OnInit``
            method that creates a frame and then calls ``self.SetTopWindow(frame)``,
            however ``wx.App`` is also usable on its own without derivation.
            """,
        items=[
            PyCodeDef('outputWindowClass = PyOnDemandOutputWindow'),
            PyFunctionDef(
                '__init__',
                '(self, redirect=False, filename=None, useBestVisual=False, clearSigInt=True)',
                doc="""\
                    Construct a ``wx.App`` object.

                    :param redirect: Should ``sys.stdout`` and ``sys.stderr`` be
                        redirected?  Defaults to False. If ``filename`` is None
                        then output will be redirected to a window that pops up
                        as needed.  (You can control what kind of window is created
                        for the output by resetting the class variable
                        ``outputWindowClass`` to a class of your choosing.)

                    :param filename: The name of a file to redirect output to, if
                        redirect is True.

                    :param useBestVisual: Should the app try to use the best
                        available visual provided by the system (only relevant on
                        systems that have more than one visual.)  This parameter
                        must be used instead of calling `SetUseBestVisual` later
                        on because it must be set before the underlying GUI
                        toolkit is initialized.

                    :param clearSigInt: Should SIGINT be cleared?  This allows the
                        app to terminate upon a Ctrl-C in the console like other
                        GUI apps will.

                    :note: You should override OnInit to do application
                        initialization to ensure that the system, toolkit and
                        wxWidgets are fully initialized.
                    """,
                body="""\
                    PyApp.__init__(self)

                    # make sure we can create a GUI
                    if not self.IsDisplayAvailable():

                        if wx.Port == "__WXMAC__":
                            msg = "This program needs access to the screen. Please run with a\\n" \\
                                  "Framework build of python, and only when you are logged in\\n" \\
                                  "on the main display of your Mac."

                        elif wx.Port == "__WXGTK__":
                            msg ="Unable to access the X Display, is $DISPLAY set properly?"

                        else:
                            msg = "Unable to create GUI"
                            # TODO: more description is needed for wxMSW...

                        raise SystemExit(msg)

                    # This has to be done before OnInit
                    self.SetUseBestVisual(useBestVisual)

                    # Set the default handler for SIGINT.  This fixes a problem
                    # where if Ctrl-C is pressed in the console that started this
                    # app then it will not appear to do anything, (not even send
                    # KeyboardInterrupt???)  but will later segfault on exit.  By
                    # setting the default handler then the app will exit, as
                    # expected (depending on platform.)
                    if clearSigInt:
                        try:
                            import signal
                            signal.signal(signal.SIGINT, signal.SIG_DFL)
                        except:
                            pass

                    # Save and redirect the stdio to a window?
                    self.stdioWin = None
                    self.saveStdio = (_sys.stdout, _sys.stderr)
                    if redirect:
                        self.RedirectStdio(filename)

                    # Use Python's install prefix as the default
                    prefix = _sys.prefix
                    if isinstance(prefix, (bytes, bytearray)):
                        prefix = prefix.decode(_sys.getfilesystemencoding())
                    wx.StandardPaths.Get().SetInstallPrefix(prefix)

                    # Until the new native control for wxMac is up to par, still use the generic one.
                    wx.SystemOptions.SetOption("mac.listctrl.always_use_generic", 1)

                    # This finishes the initialization of wxWindows and then calls
                    # the OnInit that should be present in the derived class
                    self._BootstrapApp()
                    """),
            PyFunctionDef('OnPreInit',
                          '(self)',
                          doc="""\
                    Things that must be done after _BootstrapApp has done its thing, but
                    would be nice if they were already done by the time that OnInit is
                    called.  This can be overridden in derived classes, but be sure to call
                    this method from there.
                    """,
                          body="""\
                    wx.StockGDI._initStockObjects()
                    self.InitLocale()
                    """),
            PyFunctionDef('__del__',
                          '(self)',
                          doc="",
                          body="""\
                    # Just in case the MainLoop was overridden without calling RestoreStio
                    self.RestoreStdio()
                    """),
            PyFunctionDef('SetTopWindow',
                          '(self, frame)',
                          doc="""\
                    Set the \"main\" top level window, which will be used for the parent of
                    the on-demand output window as well as for dialogs that do not have
                    an explicit parent set.
                    """,
                          body="""\
                    if self.stdioWin:
                        self.stdioWin.SetParent(frame)
                    wx.PyApp.SetTopWindow(self, frame)
                    """),
            PyFunctionDef('MainLoop',
                          '(self)',
                          doc="""Execute the main GUI event loop""",
                          body="""\
                    rv = wx.PyApp.MainLoop(self)
                    self.RestoreStdio()
                    return rv
                    """),
            PyFunctionDef(
                'RedirectStdio',
                '(self, filename=None)',
                doc=
                """Redirect sys.stdout and sys.stderr to a file or a popup window.""",
                body="""\
                    if filename:
                        _sys.stdout = _sys.stderr = open(filename, 'a')
                    else:
                        self.stdioWin = self.outputWindowClass()
                        _sys.stdout = _sys.stderr = self.stdioWin
                    """),
            PyFunctionDef('RestoreStdio',
                          '(self)',
                          doc="",
                          body="""\
                    try:
                        _sys.stdout, _sys.stderr = self.saveStdio
                    except:
                        pass
                    """),
            PyFunctionDef('SetOutputWindowAttributes',
                          '(self, title=None, pos=None, size=None)',
                          doc="""\
                    Set the title, position and/or size of the output window if the stdio
                    has been redirected. This should be called before any output would
                    cause the output window to be created.
                    """,
                          body="""\
                    if self.stdioWin:
                        if title is not None:
                            self.stdioWin.title = title
                        if pos is not None:
                            self.stdioWin.pos = pos
                        if size is not None:
                            self.stdioWin.size = size
                    """),
            PyFunctionDef('InitLocale',
                          '(self)',
                          doc="""\
                    Try to ensure that the C and Python locale is in sync with wxWidgets locale.
                    """,
                          body="""\
                    self.ResetLocale()
                    import locale
                    try:
                        loc, enc = locale.getlocale()
                    except ValueError:
                        loc = enc = None
                    # Try to set it to the same language as what is already set in the C locale
                    info = wx.Locale.FindLanguageInfo(loc) if loc else None
                    if info:
                        self._initial_locale = wx.Locale(info.Language)
                    else:
                        # otherwise fall back to the system default
                        self._initial_locale = wx.Locale(wx.LANGUAGE_DEFAULT)
                    """),
            PyFunctionDef('ResetLocale',
                          '(self)',
                          doc="""\
                    Release the wx.Locale object created in :meth:`InitLocale`.
                    This will reset the application's locale to the previous settings.
                    """,
                          body="""\
                    self._initial_locale = None
                    """),
            PyFunctionDef('Get',
                          '()',
                          isStatic=True,
                          doc="""\
                    A staticmethod returning the currently active application object.
                    Essentially just a more pythonic version of :meth:`GetApp`.""",
                          body="return GetApp()")
        ])

    module.addPyClass(
        'PySimpleApp', ['App'],
        deprecated="Use :class:`App` instead.",
        doc="""This class is deprecated.  Please use :class:`App` instead.""",
        items=[
            PyFunctionDef('__init__',
                          '(self, *args, **kw)',
                          body="App.__init__(self, *args, **kw)")
        ])

    module.find('wxInitialize').ignore()
    module.find('wxUninitialize').ignore()

    for item in module.allItems():
        if item.name == 'wxEntry':
            item.ignore()

    module.find('wxWakeUpIdle').mustHaveApp()

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
예제 #2
0
파일: event.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.addCppCode("""
    #if !wxUSE_HOTKEY
    #define wxEVT_HOTKEY 0
    #endif
    """)

    # C macros that need to be ignored
    module.find('wx__DECLARE_EVT0').ignore()
    module.find('wx__DECLARE_EVT1').ignore()
    module.find('wx__DECLARE_EVT2').ignore()
    module.find('wxEVENT_HANDLER_CAST').ignore()
    module.find('wxDECLARE_EXPORTED_EVENT').ignore()
    module.find('wxDECLARE_EVENT').ignore()
    module.find('wxDEFINE_EVENT').ignore()

    module.addPyClass(
        'PyEventBinder', ['object'],
        doc="""\
            Instances of this class are used to bind specific events to event handlers.
            """,
        items=[
            PyFunctionDef('__init__',
                          '(self, evtType, expectedIDs=0)',
                          body="""\
                    if expectedIDs not in [0, 1, 2]:
                        raise ValueError("Invalid number of expectedIDs")
                    self.expectedIDs = expectedIDs

                    if isinstance(evtType, (list, tuple)):
                        self.evtType = list(evtType)
                    else:
                        self.evtType = [evtType]
                    """),
            PyFunctionDef(
                'Bind',
                '(self, target, id1, id2, function)',
                doc=
                """Bind this set of event types to target using its Connect() method.""",
                body="""\
                    for et in self.evtType:
                        target.Connect(id1, id2, et, function)
                    """),
            PyFunctionDef('Unbind',
                          '(self, target, id1, id2, handler=None)',
                          doc="""Remove an event binding.""",
                          body="""\
                    success = 0
                    for et in self.evtType:
                        success += int(target.Disconnect(id1, id2, et, handler))
                    return success != 0
                    """),
            PyFunctionDef('_getEvtType',
                          '(self)',
                          doc="""\
                    Make it easy to get to the default wxEventType typeID for this
                    event binder.
                    """,
                          body="""return self.evtType[0]"""),
            PyPropertyDef('typeId', '_getEvtType'),
            PyFunctionDef('__call__',
                          '(self, *args)',
                          deprecated="Use :meth:`EvtHandler.Bind` instead.",
                          doc="""\
                    For backwards compatibility with the old ``EVT_*`` functions.
                    Should be called with either (window, func), (window, ID,
                    func) or (window, ID1, ID2, func) parameters depending on the
                    type of the event.
                    """,
                          body="""\
                    assert len(args) == 2 + self.expectedIDs
                    id1 = ID_ANY
                    id2 = ID_ANY
                    target = args[0]
                    if self.expectedIDs == 0:
                        func = args[1]
                    elif self.expectedIDs == 1:
                        id1 = args[1]
                        func = args[2]
                    elif self.expectedIDs == 2:
                        id1 = args[1]
                        id2 = args[2]
                        func = args[3]
                    else:
                        raise ValueError("Unexpected number of IDs")

                    self.Bind(target, id1, id2, func)
                    """)
        ])

    module.includePyCode('src/event_ex.py')

    #---------------------------------------
    # wxEvtHandler
    c = module.find('wxEvtHandler')
    c.addPrivateCopyCtor()
    c.addPublic()

    c.includeCppCode('src/event_ex.cpp')

    # Ignore the Connect/Disconnect and Bind/Unbind methods (and all overloads) for now.
    for item in c.allItems():
        if item.name in ['Connect', 'Disconnect', 'Bind', 'Unbind']:
            item.ignore()

    # Connect and Disconnect methods for wxPython. Hold a reference to the
    # event handler function in the event table, so we can fetch it later when
    # it is time to handle the event.
    c.addCppMethod(
        'void',
        'Connect',
        '(int id, int lastId, wxEventType eventType, PyObject* func)',
        doc="Make an entry in the dynamic event table for an event binding.",
        body="""\
            if (PyCallable_Check(func)) {
                self->Connect(id, lastId, eventType,
                              (wxObjectEventFunction)&wxPyCallback::EventThunker,
                              new wxPyCallback(func));
            }
            else if (func == Py_None) {
                self->Disconnect(id, lastId, eventType,
                                 (wxObjectEventFunction)(wxEventFunction)
                                 &wxPyCallback::EventThunker);
            }
            else {
                PyErr_SetString(PyExc_TypeError, "Expected callable object or None.");
            }
        """)

    c.addCppMethod(
        'bool',
        'Disconnect', '(int id, int lastId=-1, '
        'wxEventType eventType=wxEVT_NULL, '
        'PyObject* func=NULL)',
        doc=
        "Remove an event binding by removing its entry in the dynamic event table.",
        body="""\
            if (func && func != Py_None) {
                // Find the current matching binder that has this function
                // pointer and disconnect that one.  Unfortunately since we
                // wrapped the PyObject function pointer in another object we
                // have to do the searching ourselves...
                size_t cookie;
                wxDynamicEventTableEntry *entry = self->GetFirstDynamicEntry(cookie);
                while (entry)
                {
                    if ((entry->m_id == id) &&
                        ((entry->m_lastId == lastId) || (lastId == wxID_ANY)) &&
                        ((entry->m_eventType == eventType) || (eventType == wxEVT_NULL)) &&
                        entry->m_fn->IsMatching(wxObjectEventFunctor((wxObjectEventFunction)&wxPyCallback::EventThunker, NULL)) &&
                        (entry->m_callbackUserData != NULL))
                    {
                        wxPyThreadBlocker block;
                        wxPyCallback *cb = (wxPyCallback*)entry->m_callbackUserData;
                        // NOTE: Just comparing PyObject pointers is not enough, as bound
                        // methods can result in different PyObjects each time obj.Method
                        // is evaluated. (!!!)
                        if (PyObject_RichCompareBool(cb->m_func, func, Py_EQ) == 1) {
                            delete cb;
                            entry->m_callbackUserData = NULL;
                            // Now Disconnect should work
                            return self->Disconnect(id, lastId, eventType,
                                                    (wxObjectEventFunction)&wxPyCallback::EventThunker);
                        }
                    }
                    entry = self->GetNextDynamicEntry(cookie);
                }
                return false;
            }
            else {
                return self->Disconnect(id, lastId, eventType,
                                        (wxObjectEventFunction)&wxPyCallback::EventThunker);
            }
        """)

    # Ignore the C++ version of CallAfter. We have our own.
    # TODO: If we want to support this we'll need concrete implementations of
    # the template, probably using PyObject* args.
    for m in c.find('CallAfter').all():
        m.ignore()

    c.find('QueueEvent.event').transfer = True
    module.find('wxQueueEvent.event').transfer = True

    # TODO: If we don't need to use the wxEvtHandler's client data for our own
    # tracking then enable these....
    c.find('GetClientObject').ignore()
    c.find('SetClientObject').ignore()
    c.find('GetClientData').ignore()
    c.find('SetClientData').ignore()

    # We only care about overriding a few virtuals, ignore the rest.
    tools.removeVirtuals(c)
    c.find('ProcessEvent').isVirtual = True
    c.find('TryBefore').isVirtual = True
    c.find('TryAfter').isVirtual = True
    c.find('TryBefore').ignore(False)
    c.find('TryAfter').ignore(False)

    # Release the GIL for potentially blocking or long-running functions
    c.find('ProcessEvent').releaseGIL()
    c.find('ProcessEventLocally').releaseGIL()
    c.find('SafelyProcessEvent').releaseGIL()
    c.find('ProcessPendingEvents').releaseGIL()

    c.addPyMethod(
        'Bind',
        '(self, event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY)',
        doc="""\
            Bind an event to an event handler.

            :param event: One of the ``EVT_*`` event binder objects that
                          specifies the type of event to bind.

            :param handler: A callable object to be invoked when the
                            event is delivered to self.  Pass ``None`` to
                            disconnect an event handler.

            :param source: Sometimes the event originates from a
                           different window than self, but you still
                           want to catch it in self.  (For example, a
                           button event delivered to a frame.)  By
                           passing the source of the event, the event
                           handling system is able to differentiate
                           between the same event type from different
                           controls.

            :param id: Used to spcify the event source by ID instead
                       of instance.

            :param id2: Used when it is desirable to bind a handler
                        to a range of IDs, such as with EVT_MENU_RANGE.
            """,
        body="""\
            assert isinstance(event, wx.PyEventBinder)
            assert callable(handler) or handler is None
            assert source is None or hasattr(source, 'GetId')
            if source is not None:
                id  = source.GetId()
            event.Bind(self, id, id2, handler)
            """)

    c.addPyMethod(
        'Unbind',
        '(self, event, source=None, id=wx.ID_ANY, id2=wx.ID_ANY, handler=None)',
        doc="""\
            Disconnects the event handler binding for event from `self`.
            Returns ``True`` if successful.
            """,
        body="""\
            if source is not None:
                id  = source.GetId()
            return event.Unbind(self, id, id2, handler)
            """)

    module.addPyCode(
        'PyEvtHandler = wx.deprecated(EvtHandler, "Use :class:`EvtHandler` instead.")'
    )

    #---------------------------------------
    # wxEvent
    c = module.find('wxEvent')
    assert isinstance(c, etgtools.ClassDef)
    c.abstract = True
    c.find('Clone').factory = True

    c.addProperty('EventObject GetEventObject SetEventObject')
    c.addProperty('EventType GetEventType SetEventType')
    c.addProperty('Id GetId SetId')
    c.addProperty('Skipped GetSkipped')
    c.addProperty('Timestamp GetTimestamp SetTimestamp')

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

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

    c.addProperty('ExtraLong GetExtraLong SetExtraLong')
    c.addProperty('Int GetInt SetInt')
    c.addProperty('Selection GetSelection')
    c.addProperty('String GetString SetString')

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

    c.find('GetPosition').findOverload('wxCoord').ignore()
    c.find('GetUnicodeKey').type = 'int'

    c.addProperty('X GetX')
    c.addProperty('Y GetY')
    c.addProperty('KeyCode GetKeyCode')
    c.addProperty('Position GetPosition')
    c.addProperty('RawKeyCode GetRawKeyCode')
    c.addProperty('RawKeyFlags GetRawKeyFlags')
    c.addProperty('UnicodeKey GetUnicodeKey')

    #---------------------------------------
    # wxScrollEvent
    c = module.find('wxScrollEvent')
    c.addProperty('Orientation GetOrientation SetOrientation')
    c.addProperty('Position GetPosition SetPosition')

    #---------------------------------------
    # wxScrollWinEvent
    c = module.find('wxScrollWinEvent')
    c.addProperty('Orientation GetOrientation SetOrientation')
    c.addProperty('Position GetPosition SetPosition')

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

    c.addCppMethod('void',
                   'SetWheelAxis',
                   '(wxMouseWheelAxis wheelAxis)',
                   body="self->m_wheelAxis = wheelAxis;")

    c.addCppMethod('void',
                   'SetWheelRotation',
                   '(int wheelRotation)',
                   body="self->m_wheelRotation = wheelRotation;")

    c.addCppMethod('void',
                   'SetWheelDelta',
                   '(int wheelDelta)',
                   body="self->m_wheelDelta = wheelDelta;")

    c.addCppMethod('void',
                   'SetLinesPerAction',
                   '(int linesPerAction)',
                   body="self->m_linesPerAction = linesPerAction;")

    c.addCppMethod('void',
                   'SetColumnsPerAction',
                   '(int columnsPerAction)',
                   body="self->m_columnsPerAction = columnsPerAction;")

    c.addProperty('WheelAxis GetWheelAxis SetWheelAxis')
    c.addProperty('WheelRotation GetWheelRotation SetWheelRotation')
    c.addProperty('WheelDelta GetWheelDelta SetWheelDelta')
    c.addProperty('LinesPerAction GetLinesPerAction SetLinesPerAction')
    c.addProperty('ColumnsPerAction GetColumnsPerAction SetColumnsPerAction')

    #---------------------------------------
    # wxSetCursorEvent
    c = module.find('wxSetCursorEvent')
    c.addProperty('Cursor GetCursor SetCursor')
    c.addProperty('X GetX')
    c.addProperty('Y GetY')

    #---------------------------------------
    # wxSizeEvent
    c = module.find('wxSizeEvent')
    c.addProperty('Rect GetRect SetRect')
    c.addProperty('Size GetSize SetSize')

    #---------------------------------------
    # wxMoveEvent
    c = module.find('wxMoveEvent')
    c.addProperty('Rect GetRect SetRect')
    c.addProperty('Position GetPosition SetPosition')

    #---------------------------------------
    # wxEraseEvent
    c = module.find('wxEraseEvent')
    c.addProperty('DC GetDC')

    #---------------------------------------
    # wxFocusEvent
    c = module.find('wxFocusEvent')
    c.addProperty('Window GetWindow SetWindow')

    #---------------------------------------
    # wxChildFocusEvent
    c = module.find('wxChildFocusEvent')
    c.addProperty('Window GetWindow')

    #---------------------------------------
    # wxActivateEvent
    c = module.find('wxActivateEvent')
    c.addProperty('Active GetActive')

    #---------------------------------------
    # wxMenuEvent
    c = module.find('wxMenuEvent')
    c.addProperty('Menu GetMenu')
    c.addProperty('MenuId GetMenuId')

    #---------------------------------------
    # wxShowEvent
    c = module.find('wxShowEvent')
    c.find('GetShow').ignore()  # deprecated
    c.addProperty('Show IsShown SetShow')

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

    # wxDropFilesEvent assumes that the C array of wxString objects will
    # continue to live as long as the event object does, and does not take
    # ownership of the array. Unfortunately the mechanism used to turn the
    # Python list into a C array will also delete it after the API call, and
    # so when wxDropFilesEvent tries to access it later the memory pointer is
    # bad. So we'll copy that array into a special holder class and give that
    # one to the API, and also assign a Python reference to it to the event
    # object, so it will get garbage collected later.
    c.find('wxDropFilesEvent.files').array = True
    c.find('wxDropFilesEvent.files').transfer = True
    c.find('wxDropFilesEvent.noFiles').arraySize = True
    c.addHeaderCode('#include "arrayholder.h"')
    c.find('wxDropFilesEvent').setCppCode_sip("""\
        if (files) {
            wxStringCArrayHolder* holder = new wxStringCArrayHolder;
            holder->m_array = files;
            // Make a PyObject for the holder, and transfer its ownership to self.
            PyObject* pyHolder = sipConvertFromNewType(
                    (void*)holder, sipType_wxStringCArrayHolder, (PyObject*)sipSelf);
            Py_DECREF(pyHolder);
            sipCpp = new sipwxDropFilesEvent(id,(int)noFiles, holder->m_array);
        }
        else
            sipCpp = new sipwxDropFilesEvent(id);
        """)

    c.find('GetFiles').type = 'PyObject*'
    c.find('GetFiles').setCppCode("""\
        int         count   = self->GetNumberOfFiles();
        wxString*   files   = self->GetFiles();
        wxPyThreadBlocker   blocker;
        PyObject*   list    = PyList_New(count);
        if (!list) {
            PyErr_SetString(PyExc_MemoryError, "Can't allocate list of files!");
            return NULL;
        }
        for (int i=0; i<count; i++) {
            PyObject* s = wx2PyString(files[i]);
            PyList_SET_ITEM(list, i, s);
        }
        return list;
        """)

    c.addProperty('Files GetFiles')
    c.addProperty('NumberOfFiles GetNumberOfFiles')
    c.addProperty('Position GetPosition')

    #---------------------------------------
    # wxUpdateUIEvent
    c = module.find('wxUpdateUIEvent')
    c.addProperty('Checked GetChecked Check')
    c.addProperty('Enabled GetEnabled Enable')
    c.addProperty('Shown GetShown Show')
    c.addProperty('Text GetText SetText')

    #---------------------------------------
    # wxMouseCaptureChangedEvent
    c = module.find('wxMouseCaptureChangedEvent')
    c.addProperty('CapturedWindow GetCapturedWindow')

    #---------------------------------------
    # wxPaletteChangedEvent
    c = module.find('wxPaletteChangedEvent')
    c.addProperty('ChangedWindow GetChangedWindow SetChangedWindow')

    #---------------------------------------
    # wxQueryNewPaletteEvent
    c = module.find('wxQueryNewPaletteEvent')
    c.addProperty('PaletteRealized GetPaletteRealized SetPaletteRealized')

    #---------------------------------------
    # wxNavigationKeyEvent
    c = module.find('wxNavigationKeyEvent')
    c.addProperty('CurrentFocus GetCurrentFocus SetCurrentFocus')
    c.addProperty('Direction GetDirection SetDirection')

    #---------------------------------------
    # wxWindowCreateEvent
    c = module.find('wxWindowCreateEvent')
    c.addProperty('Window GetWindow')

    #---------------------------------------
    # wxWindowDestroyEvent
    c = module.find('wxWindowDestroyEvent')
    c.addProperty('Window GetWindow')

    #---------------------------------------
    # wxContextMenuEvent
    c = module.find('wxContextMenuEvent')
    c.addProperty('Position GetPosition SetPosition')

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

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

    # Apply common fixups for all the event classes
    for name in [n for n in ITEMS if n.endswith('Event')]:
        c = module.find(name)
        tools.fixEventClass(c)

    #---------------------------------------
    # wxEventBlocker
    c = module.find('wxEventBlocker')
    c.addPyMethod('__enter__', '(self)', 'return self')
    c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)',
                  'return False')

    #---------------------------------------
    # wxPropagationDisabler
    c = module.find('wxPropagationDisabler')
    c.addPyMethod('__enter__', '(self)', 'return self')
    c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)',
                  'return False')
    c.addPrivateCopyCtor()

    #---------------------------------------
    # wxPropagateOnce
    c = module.find('wxPropagateOnce')
    c.addPyMethod('__enter__', '(self)', 'return self')
    c.addPyMethod('__exit__', '(self, exc_type, exc_val, exc_tb)',
                  'return False')
    c.addPrivateCopyCtor()

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

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

    module.addHeaderCode("#include <wx/dataview.h>")

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

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

    c.addCppMethod('int', '__nonzero__', '()', """\
        return self->IsOk();
        """)
    c.addCppMethod('long', '__hash__', '()', """\
        return (long)self->GetID();
        """)
    c.addCppMethod('bool', '__lt__', '(wxDataViewItem* other)',
                   "return (self->GetID() <  other->GetID());")
    c.addCppMethod('bool', '__le__', '(wxDataViewItem* other)',
                   "return (self->GetID() <= other->GetID());")
    c.addCppMethod('bool', '__eq__', '(wxDataViewItem* other)',
                   "return (self->GetID() == other->GetID());")
    c.addCppMethod('bool', '__ne__', '(wxDataViewItem* other)',
                   "return (self->GetID() != other->GetID());")
    c.addCppMethod('bool', '__ge__', '(wxDataViewItem* other)',
                   "return (self->GetID() >= other->GetID());")
    c.addCppMethod('bool', '__gt__', '(wxDataViewItem* other)',
                   "return (self->GetID() >  other->GetID());")
    c.addAutoProperties()

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

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

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

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

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

    # The DataViewItemObjectMapper class helps map from data items to Python
    # objects, and is used as a base class of PyDataViewModel as a
    # convenience.
    module.addPyClass(
        'DataViewItemObjectMapper', ['object'],
        doc="""\
            This class provides a mechanism for mapping between Python objects and the
            :class:`DataViewItem` objects used by the :class:`DataViewModel` for tracking the items in
            the view. The ID used for the item is the id() of the Python object. Use
            :meth:`ObjectToItem` to create a :class:`DataViewItem` using a Python object as its ID,
            and use :meth:`ItemToObject` to fetch that Python object again later for a given
            :class:`DataViewItem`.
    
            By default a regular dictionary is used to implement the ID to object
            mapping. Optionally a WeakValueDictionary can be useful when there will be
            a high turnover of objects and mantaining an extra reference to the
            objects would be unwise.  If weak references are used then the objects
            associated with data items must be weak-referenceable.  (Things like
            stock lists and dictionaries are not.)  See :meth:`UseWeakRefs`.
            
            This class is used in :class:`PyDataViewModel` as a mixin for convenience.
            """,
        items=[
            PyFunctionDef('__init__',
                          '(self)',
                          body="""\
                    self.mapper = dict()
                    self.usingWeakRefs = False
                    """),
            PyFunctionDef(
                'ObjectToItem',
                '(self, obj)',
                doc=
                "Create a :class:`DataViewItem` for the object, and remember the ID-->obj mapping.",
                body="""\
                    import sys
                    oid = id(obj)
                    while oid > sys.maxsize:
                        # risk of conflict here... May need some more thought.
                        oid -= sys.maxsize
                    self.mapper[oid] = obj 
                    return DataViewItem(oid)
                    """),
            PyFunctionDef(
                'ItemToObject',
                '(self, item)',
                doc="Retrieve the object that was used to create an item.",
                body="""\
                    oid = int(item.GetID())
                    return self.mapper[oid]
                    """),
            PyFunctionDef('UseWeakRefs',
                          '(self, flag)',
                          doc="""\
                    Switch to or from using a weak value dictionary for keeping the ID to
                    object map.""",
                          body="""\
                    if flag == self.usingWeakRefs:
                        return
                    if flag:
                        import weakref
                        newmap = weakref.WeakValueDictionary()
                    else:
                        newmap = dict()
                    newmap.update(self.mapper)
                    self.mapper = newmap
                    self.usingWeakRefs = flag
                    """),
        ])

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

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

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

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

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

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

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

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

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

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

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

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

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

    c = module.find('wxDataViewCustomRenderer')
    _fixupBoolGetters(c.find('GetValueFromEditorCtrl'),
                      'bool (wxWindow * editor, wxDVCVariant& value)')
    c.find('GetTextExtent').ignore(False)

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

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

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

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

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

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

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

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

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

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

    # Pythonize HitTest
    c.find('HitTest').ignore()
    c.addCppMethod('PyObject*',
                   'HitTest',
                   '(const wxPoint& point)',
                   isConst=True,
                   doc="""\
            HitTest(point) -> (item, col)\n
            Returns the item and column located at point, as a 2 element tuple.
            """,
                   body="""\
            wxDataViewItem*   item = new wxDataViewItem();;
            wxDataViewColumn* col = NULL;
            
            self->HitTest(*point, *item, col);
            
            wxPyThreadBlocker blocker;
            PyObject* value = PyTuple_New(2);
            PyObject* item_obj =
                wxPyConstructObject((void*)item, wxT("wxDataViewItem"), 1);   // owned
            PyObject* col_obj;
            if (col) {
                col_obj = wxPyConstructObject((void*)col, wxT("wxDataViewColumn"), 0);  // not owned
            } else {
                col_obj = Py_None;
                Py_INCREF(Py_None);
            }
            PyTuple_SET_ITEM(value, 0, item_obj);
            PyTuple_SET_ITEM(value, 1, col_obj);
            // PyTuple steals a reference, so we don't need to decref the items here
            return value;
            """)

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

    c.addProperty('EditCancelled', 'IsEditCancelled', 'SetEditCanceled')

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

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

    # TODO: SetDataBuffer

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

    module.addPyCode("""\
        EVT_DATAVIEW_SELECTION_CHANGED         = wx.PyEventBinder( wxEVT_DATAVIEW_SELECTION_CHANGED, 1)
        EVT_DATAVIEW_ITEM_ACTIVATED            = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_ACTIVATED, 1)
        EVT_DATAVIEW_ITEM_COLLAPSED            = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_COLLAPSED, 1)
        EVT_DATAVIEW_ITEM_EXPANDED             = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EXPANDED, 1)
        EVT_DATAVIEW_ITEM_COLLAPSING           = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_COLLAPSING, 1)
        EVT_DATAVIEW_ITEM_EXPANDING            = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EXPANDING, 1)
        EVT_DATAVIEW_ITEM_START_EDITING        = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_START_EDITING, 1)    
        EVT_DATAVIEW_ITEM_EDITING_STARTED      = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EDITING_STARTED, 1)
        EVT_DATAVIEW_ITEM_EDITING_DONE         = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_EDITING_DONE, 1)
        EVT_DATAVIEW_ITEM_VALUE_CHANGED        = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, 1)
        EVT_DATAVIEW_ITEM_CONTEXT_MENU         = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, 1)
        EVT_DATAVIEW_COLUMN_HEADER_CLICK       = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_HEADER_CLICK, 1)
        EVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK, 1)
        EVT_DATAVIEW_COLUMN_SORTED             = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_SORTED, 1)
        EVT_DATAVIEW_COLUMN_REORDERED          = wx.PyEventBinder( wxEVT_DATAVIEW_COLUMN_REORDERED, 1)
        EVT_DATAVIEW_ITEM_BEGIN_DRAG           = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_BEGIN_DRAG, 1)
        EVT_DATAVIEW_ITEM_DROP_POSSIBLE        = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_DROP_POSSIBLE, 1)      
        EVT_DATAVIEW_ITEM_DROP                 = wx.PyEventBinder( wxEVT_DATAVIEW_ITEM_DROP, 1)
        EVT_DATAVIEW_CACHE_HINT                = wx.PyEventBinder( wxEVT_DATAVIEW_CACHE_HINT, 1 )
        
        # deprecated wxEVT aliases
        wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED          = wxEVT_DATAVIEW_SELECTION_CHANGED
        wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED             = wxEVT_DATAVIEW_ITEM_ACTIVATED
        wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED             = wxEVT_DATAVIEW_ITEM_COLLAPSED
        wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED              = wxEVT_DATAVIEW_ITEM_EXPANDED
        wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING            = wxEVT_DATAVIEW_ITEM_COLLAPSING
        wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING             = wxEVT_DATAVIEW_ITEM_EXPANDING
        wxEVT_COMMAND_DATAVIEW_ITEM_START_EDITING         = wxEVT_DATAVIEW_ITEM_START_EDITING
        wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED       = wxEVT_DATAVIEW_ITEM_EDITING_STARTED
        wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE          = wxEVT_DATAVIEW_ITEM_EDITING_DONE
        wxEVT_COMMAND_DATAVIEW_ITEM_VALUE_CHANGED         = wxEVT_DATAVIEW_ITEM_VALUE_CHANGED
        wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU          = wxEVT_DATAVIEW_ITEM_CONTEXT_MENU
        wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK        = wxEVT_DATAVIEW_COLUMN_HEADER_CLICK
        wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK  = wxEVT_DATAVIEW_COLUMN_HEADER_RIGHT_CLICK
        wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED              = wxEVT_DATAVIEW_COLUMN_SORTED
        wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED           = wxEVT_DATAVIEW_COLUMN_REORDERED
        wxEVT_COMMAND_DATAVIEW_CACHE_HINT                 = wxEVT_DATAVIEW_CACHE_HINT
        wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG            = wxEVT_DATAVIEW_ITEM_BEGIN_DRAG
        wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE         = wxEVT_DATAVIEW_ITEM_DROP_POSSIBLE
        wxEVT_COMMAND_DATAVIEW_ITEM_DROP                  = wxEVT_DATAVIEW_ITEM_DROP
        """)

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

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

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

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

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

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

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

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

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
예제 #4
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)
    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.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: keywords 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)