File: _xrc.py

package info (click to toggle)
wxpython4.0 4.2.3%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 221,752 kB
  • sloc: cpp: 962,555; python: 230,573; ansic: 170,731; makefile: 51,756; sh: 9,342; perl: 1,564; javascript: 584; php: 326; xml: 200
file content (227 lines) | stat: -rw-r--r-- 8,313 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#---------------------------------------------------------------------------
# Name:        etg/_xrc.py
# Author:      Robin Dunn
#
# Created:     28-Nov-2012
# Copyright:   (c) 2012-2020 by Total Control Software
# License:     wxWindows License
#---------------------------------------------------------------------------

import etgtools
import etgtools.tweaker_tools as tools
from etgtools import ClassDef, MethodDef, ParamDef

PACKAGE   = "wx"
MODULE    = "_xrc"
NAME      = "_xrc"   # Base name of the file to generate to for this script
DOCSTRING = """\
The classes in this module enable loading widgets and layout from XML.
"""

# The classes and/or the basename of the Doxygen XML files to be processed by
# this script.
ITEMS  = [ 'wxXmlResource',
           'wxXmlResourceHandler',
           ]


# The list of other ETG scripts and back-end generator modules that are
# included as part of this module. These should all be items that are put in
# the wxWidgets "xrc" library in a multi-lib build.
INCLUDES = [ ]


# Separate the list into those that are generated from ETG scripts and the
# rest. These lists can be used from the build scripts to get a list of
# sources and/or additional dependencies when building this extension module.
ETGFILES = ['etg/%s.py' % NAME] + tools.getEtgFiles(INCLUDES)
DEPENDS = tools.getNonEtgFiles(INCLUDES)
OTHERDEPS = [  ]


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

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

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

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

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

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

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

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

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

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


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

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

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

            // Load the "file" into the resource object
            bool retval = self->Load(wxT("memory:") + filename );
            return retval;
            """)
    c.addPyCode("XmlResource.LoadFromString = wx.deprecated(XmlResource.LoadFromBuffer, 'Use LoadFromBuffer instead')")

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


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

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

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

    # TODO: It looks like there may be a bug in wx here.
    # Just ignore it for now.
    c.find('GetFilePath').ignore()

    c.find('GetAnimation.ctrl').type = 'wxAnimationCtrl *'

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

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

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



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



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

        def _my_import(name):
            try:
                mod = __import__(name)
            except ImportError:
                import traceback
                print(traceback.format_exc())
                raise
            components = name.split('.')
            for comp in components[1:]:
                mod = getattr(mod, comp)
            return mod

        class XmlSubclassFactory_Python(XmlSubclassFactory):
            def __init__(self):
                XmlSubclassFactory.__init__(self)

            def Create(self, className):
                assert className.find('.') != -1, "Module name must be specified!"
                mname = className[:className.rfind('.')]
                cname = className[className.rfind('.')+1:]
                module = _my_import(mname)
                klass = getattr(module, cname)
                inst = klass()
                return inst

        XmlResource.AddSubclassFactory(XmlSubclassFactory_Python())
        """)

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



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

if __name__ == '__main__':
    run()