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

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

    c = module.find('wxFileSystemWatcherEvent')
    assert isinstance(c, etgtools.ClassDef)
    c.addItem(
        etgtools.MethodDef(name='Clone',
                           type='wxEvent*',
                           argsString='() const',
                           isConst=True,
                           isVirtual=True))

    tools.generateStubs('wxUSE_FSWATCHER',
                        module,
                        extraHdrCode='static wxFileName _NullFileName;\n',
                        typeValMap={
                            'const wxFileName &': '_NullFileName',
                            'wxFSWWarningType': 'wxFSW_WARNING_NONE'
                        })

    # In the C++ code the wxFSW_EVENT_UNMOUNT item is only part of the enum
    # for platforms that have INOTIFY so we need to fake it elsewhere.
    module.addHeaderCode("""
        #include <wx/fswatcher.h>
        #if wxUSE_FSWATCHER && !defined(wxHAS_INOTIFY) && !defined(wxHAVE_FSEVENTS_FILE_NOTIFICATIONS)
            const int wxFSW_EVENT_UNMOUNT = 0x2000;
        #endif
        """)

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

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

    module.addPyCode("""\
        EVT_FSWATCHER = wx.PyEventBinder(wxEVT_FSWATCHER)
        """)

    #-----------------------------------------------------------------
    tools.doCommonTweaks(module)
    tools.runGenerators(module)
Ejemplo n.º 2
0
def fixDefaultAttributesMethods(klass):
    if not klass.findItem('GetClassDefaultAttributes'):
        m = extractors.MethodDef(type='wxVisualAttributes',
                                 name='GetClassDefaultAttributes',
                                 isStatic=True,
                                 protection='public',
                                 items=[
                                     extractors.ParamDef(
                                         type='wxWindowVariant',
                                         name='variant',
                                         default='wxWINDOW_VARIANT_NORMAL')
                                 ])
        klass.addItem(m)

    if klass.findItem('GetDefaultAttributes'):
        klass.find('GetDefaultAttributes').mustHaveApp()
    klass.find('GetClassDefaultAttributes').mustHaveApp()
Ejemplo n.º 3
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)

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

    module.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 it's 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)
Ejemplo n.º 4
0
def run():
    # Parse the XML file(s) building a collection of Extractor objects
    module = etgtools.ModuleDef(PACKAGE, MODULE, NAME, DOCSTRING)
    etgtools.parseDoxyXML(module, ITEMS)

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

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

    module.addGlobalStr('wxMessageBoxCaptionStr', c)

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

    tools.fixTopLevelWindowClass(c)

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

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

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

    module.addItem(gmd)

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

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

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

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

    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()

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

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

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

    c = module.find('wxAuiTabContainer')
    tools.ignoreConstOverloads(c)

    module.addItem(
        tools.wxArrayWrapperTemplate('wxAuiNotebookPageArray',
                                     'wxAuiNotebookPage', module))

    module.addItem(
        tools.wxArrayWrapperTemplate('wxAuiTabContainerButtonArray',
                                     'wxAuiTabContainerButton', module))

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

    c = module.find('wxAuiNotebookEvent')
    tools.fixEventClass(c)
    module.addPyCode("""\
        EVT_AUINOTEBOOK_PAGE_CLOSE = wx.PyEventBinder( wxEVT_AUINOTEBOOK_PAGE_CLOSE, 1 )
        EVT_AUINOTEBOOK_PAGE_CLOSED = wx.PyEventBinder( wxEVT_AUINOTEBOOK_PAGE_CLOSED, 1 )
        EVT_AUINOTEBOOK_PAGE_CHANGED = wx.PyEventBinder( wxEVT_AUINOTEBOOK_PAGE_CHANGED, 1 )
        EVT_AUINOTEBOOK_PAGE_CHANGING = wx.PyEventBinder( wxEVT_AUINOTEBOOK_PAGE_CHANGING, 1 )
        EVT_AUINOTEBOOK_BUTTON = wx.PyEventBinder( wxEVT_AUINOTEBOOK_BUTTON, 1 )
        EVT_AUINOTEBOOK_BEGIN_DRAG = wx.PyEventBinder( wxEVT_AUINOTEBOOK_BEGIN_DRAG, 1 )
        EVT_AUINOTEBOOK_END_DRAG = wx.PyEventBinder( wxEVT_AUINOTEBOOK_END_DRAG, 1 )
        EVT_AUINOTEBOOK_DRAG_MOTION = wx.PyEventBinder( wxEVT_AUINOTEBOOK_DRAG_MOTION, 1 )
        EVT_AUINOTEBOOK_ALLOW_DND = wx.PyEventBinder( wxEVT_AUINOTEBOOK_ALLOW_DND, 1 )
        EVT_AUINOTEBOOK_DRAG_DONE = wx.PyEventBinder( wxEVT_AUINOTEBOOK_DRAG_DONE, 1 )
        EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN = wx.PyEventBinder( wxEVT_AUINOTEBOOK_TAB_MIDDLE_DOWN, 1 )
        EVT_AUINOTEBOOK_TAB_MIDDLE_UP = wx.PyEventBinder( wxEVT_AUINOTEBOOK_TAB_MIDDLE_UP, 1 )
        EVT_AUINOTEBOOK_TAB_RIGHT_DOWN = wx.PyEventBinder( wxEVT_AUINOTEBOOK_TAB_RIGHT_DOWN, 1 )
        EVT_AUINOTEBOOK_TAB_RIGHT_UP = wx.PyEventBinder( wxEVT_AUINOTEBOOK_TAB_RIGHT_UP, 1 )
        EVT_AUINOTEBOOK_BG_DCLICK = wx.PyEventBinder( wxEVT_AUINOTEBOOK_BG_DCLICK, 1 )
        """)

    #-----------------------------------------------------------------
    # Add AuiTabCtrl in.
    c = etgtools.ClassDef(
        name="wxAuiTabCtrl",
        bases=["wxControl", "wxAuiTabContainer"],
        mustHaveAppFlag=True,
        items=[
            etgtools.MethodDef(name="wxAuiTabCtrl",
                               classname="wxAuiTabCtrl",
                               isCtor=True,
                               items=[
                                   etgtools.ParamDef(type="wxWindow*",
                                                     name="parent"),
                                   etgtools.ParamDef(type="wxWindowID",
                                                     name="id",
                                                     default="wxID_ANY"),
                                   etgtools.ParamDef(
                                       type="const wxPoint&",
                                       name="pos",
                                       default="wxDefaultPosition"),
                                   etgtools.ParamDef(type="const wxSize&",
                                                     name="size",
                                                     default="wxDefaultSize"),
                                   etgtools.ParamDef(type="long",
                                                     name="style",
                                                     default="0")
                               ]),
            etgtools.MethodDef(type="bool",
                               name="IsDragging",
                               classname="wxAuiTabCtrl",
                               isConst=True)
        ])
    tools.fixWindowClass(c)
    module.addItem(c)

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

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

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

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

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

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

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

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

    c.addPrivateCopyCtor()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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