]>
git.saurik.com Git - wxWidgets.git/blob - wxPython/config.py
1 #----------------------------------------------------------------------
2 # Name: wx.build.config
3 # Purpose: Most of the contents of this module used to be located
4 # in wxPython's setup.py script. It was moved here so
5 # it would be installed with the rest of wxPython and
6 # could therefore be used by the setup.py for other
7 # projects that needed this same info and functionality
8 # (most likely in order to be compatible with wxPython.)
10 # This split from setup.py is still fairly rough, and
11 # some things may still get shuffled back and forth,
12 # refactored, etc. Please send me any comments and
13 # suggestions about this.
17 # Created: 23-March-2004
19 # Copyright: (c) 2004 by Total Control Software
20 # Licence: wxWindows license
21 #----------------------------------------------------------------------
23 import sys
, os
, glob
, fnmatch
, tempfile
24 from distutils
.core
import setup
, Extension
25 from distutils
.file_util
import copy_file
26 from distutils
.dir_util
import mkpath
27 from distutils
.dep_util
import newer
28 from distutils
.spawn
import spawn
30 import distutils
.command
.install_data
31 import distutils
.command
.install_headers
32 import distutils
.command
.clean
34 #----------------------------------------------------------------------
35 # flags and values that affect this script
36 #----------------------------------------------------------------------
38 VER_MAJOR
= 2 # The first three must match wxWidgets
41 VER_SUBREL
= 3 # wxPython release num for x.y.z release of wxWidgets
42 VER_FLAGS
= "p" # release flags, such as prerelease num, unicode, etc.
44 DESCRIPTION
= "Cross platform GUI toolkit for Python"
46 AUTHOR_EMAIL
= "Robin Dunn <robin@alldunn.com>"
47 URL
= "http://wxPython.org/"
48 DOWNLOAD_URL
= "http://wxPython.org/download.php"
49 LICENSE
= "wxWidgets Library License (LGPL derivative)"
50 PLATFORMS
= "WIN32,OSX,POSIX"
51 KEYWORDS
= "GUI,wx,wxWindows,wxWidgets,cross-platform"
53 LONG_DESCRIPTION
= """\
54 wxPython is a GUI toolkit for Python that is a wrapper around the
55 wxWidgets C++ GUI library. wxPython provides a large variety of
56 window types and controls, all implemented with a native look and
57 feel (by using the native widgets) on the platforms it is supported
62 Development Status :: 6 - Mature
63 Environment :: MacOS X :: Carbon
64 Environment :: Win32 (MS Windows)
65 Environment :: X11 Applications :: GTK
66 Intended Audience :: Developers
67 License :: OSI Approved
68 Operating System :: MacOS :: MacOS X
69 Operating System :: Microsoft :: Windows :: Windows 95/98/2000
70 Operating System :: POSIX
71 Programming Language :: Python
72 Topic :: Software Development :: User Interfaces
75 ## License :: OSI Approved :: wxWidgets Library Licence
78 # Config values below this point can be reset on the setup.py command line.
80 BUILD_GLCANVAS
= 1 # If true, build the contrib/glcanvas extension module
81 BUILD_OGL
= 1 # If true, build the contrib/ogl extension module
82 BUILD_STC
= 1 # If true, build the contrib/stc extension module
83 BUILD_XRC
= 1 # XML based resource system
84 BUILD_GIZMOS
= 1 # Build a module for the gizmos contrib library
85 BUILD_DLLWIDGET
= 0# Build a module that enables unknown wx widgets
86 # to be loaded from a DLL and to be used from Python.
88 # Internet Explorer wrapper (experimental)
89 BUILD_IEWIN
= (os
.name
== 'nt')
90 BUILD_ACTIVEX
= (os
.name
== 'nt') # new version of IEWIN and more
93 CORE_ONLY
= 0 # if true, don't build any of the above
95 PREP_ONLY
= 0 # Only run the prepatory steps, not the actual build.
97 USE_SWIG
= 0 # Should we actually execute SWIG, or just use the
98 # files already in the distribution?
100 SWIG
= "swig" # The swig executable to use.
102 BUILD_RENAMERS
= 1 # Should we build the renamer modules too?
104 FULL_DOCS
= 0 # Some docstrings are split into a basic docstring and a
105 # details string. Setting this flag to 1 will
106 # cause the two strings to be combined and output
107 # as the full docstring.
109 UNICODE
= 0 # This will pass the 'wxUSE_UNICODE' flag to SWIG and
110 # will ensure that the right headers are found and the
111 # right libs are linked.
113 UNDEF_NDEBUG
= 1 # Python 2.2 on Unix/Linux by default defines NDEBUG,
114 # and distutils will pick this up and use it on the
115 # compile command-line for the extensions. This could
116 # conflict with how wxWidgets was built. If NDEBUG is
117 # set then wxWidgets' __WXDEBUG__ setting will be turned
118 # off. If wxWidgets was actually built with it turned
119 # on then you end up with mismatched class structures,
120 # and wxPython will crash.
122 NO_SCRIPTS
= 0 # Don't install the tool scripts
123 NO_HEADERS
= 0 # Don't install the wxPython *.h and *.i files
125 WX_CONFIG
= None # Usually you shouldn't need to touch this, but you can set
126 # it to pass an alternate version of wx-config or alternate
127 # flags, eg. as required by the .deb in-tree build. By
128 # default a wx-config command will be assembled based on
129 # version, port, etc. and it will be looked for on the
132 WXPORT
= 'gtk' # On Linux/Unix there are several ports of wxWidgets available.
133 # Setting this value lets you select which will be used for
134 # the wxPython build. Possibilites are 'gtk', 'gtk2' and
135 # 'x11'. Curently only gtk and gtk2 works.
137 BUILD_BASE
= "build" # Directory to use for temporary build files.
138 # This name will be appended to if the WXPORT or
139 # the UNICODE flags are set to non-standard
143 CONTRIBS_INC
= "" # A dir to add as an -I flag when compiling the contribs
146 # Some MSW build settings
148 FINAL
= 0 # Mirrors use of same flag in wx makefiles,
149 # (0 or 1 only) should probably find a way to
152 HYBRID
= 1 # If set and not debug or FINAL, then build a
153 # hybrid extension that can be used by the
154 # non-debug version of python, but contains
155 # debugging symbols for wxWidgets and wxPython.
156 # wxWidgets must have been built with /MD, not /MDd
157 # (using FINAL=hybrid will do it.)
159 # Version part of wxWidgets LIB/DLL names
160 WXDLLVER
= '%d%d' % (VER_MAJOR
, VER_MINOR
)
162 WXPY_SRC
= '.' # Assume we're in the source tree already, but allow the
163 # user to change it, particularly for extension building.
166 #----------------------------------------------------------------------
169 if hasattr(sys
, 'setup_is_main') and sys
.setup_is_main
:
174 path
= os
.path
.join(*args
)
175 return os
.path
.normpath(path
)
190 #----------------------------------------------------------------------
192 #----------------------------------------------------------------------
199 force
= '--force' in sys
.argv
or '-f' in sys
.argv
200 debug
= '--debug' in sys
.argv
or '-g' in sys
.argv
201 cleaning
= 'clean' in sys
.argv
204 # change the PORT default for wxMac
205 if sys
.platform
[:6] == "darwin":
208 # and do the same for wxMSW, just for consistency
213 #----------------------------------------------------------------------
214 # Check for build flags on the command line
215 #----------------------------------------------------------------------
217 # Boolean (int) flags
218 for flag
in ['BUILD_GLCANVAS', 'BUILD_OGL', 'BUILD_STC', 'BUILD_XRC',
219 'BUILD_GIZMOS', 'BUILD_DLLWIDGET', 'BUILD_IEWIN', 'BUILD_ACTIVEX',
220 'CORE_ONLY', 'PREP_ONLY', 'USE_SWIG', 'UNICODE',
221 'UNDEF_NDEBUG', 'NO_SCRIPTS', 'NO_HEADERS', 'BUILD_RENAMERS',
223 'FINAL', 'HYBRID', ]:
224 for x
in range(len(sys
.argv
)):
225 if sys
.argv
[x
].find(flag
) == 0:
226 pos
= sys
.argv
[x
].find('=') + 1
228 vars()[flag
] = eval(sys
.argv
[x
][pos
:])
232 for option
in ['WX_CONFIG', 'WXDLLVER', 'BUILD_BASE', 'WXPORT', 'SWIG',
233 'CONTRIBS_INC', 'WXPY_SRC']:
234 for x
in range(len(sys
.argv
)):
235 if sys
.argv
[x
].find(option
) == 0:
236 pos
= sys
.argv
[x
].find('=') + 1
238 vars()[option
] = sys
.argv
[x
][pos
:]
241 sys
.argv
= filter(None, sys
.argv
)
244 #----------------------------------------------------------------------
245 # some helper functions
246 #----------------------------------------------------------------------
248 def Verify_WX_CONFIG():
249 """ Called below for the builds that need wx-config, if WX_CONFIG
250 is not set then determins the flags needed based on build
251 options and searches for wx-config on the PATH.
253 # if WX_CONFIG hasn't been set to an explicit value then construct one.
255 if WX_CONFIG
is None:
259 flags
= ' --toolkit=%s' % port
260 flags
+= ' --unicode=%s' % (UNICODE
and 'yes' or 'no')
261 flags
+= ' --version=%s.%s' % (VER_MAJOR
, VER_MINOR
)
263 searchpath
= os
.environ
["PATH"]
264 for p
in searchpath
.split(':'):
265 fp
= os
.path
.join(p
, 'wx-config')
266 if os
.path
.exists(fp
) and os
.access(fp
, os
.X_OK
):
268 msg("Found wx-config: " + fp
)
269 msg(" Using flags: " + flags
)
270 WX_CONFIG
= fp
+ flags
273 msg("ERROR: WX_CONFIG not specified and wx-config not found on the $PATH")
276 # TODO: exeucte WX_CONFIG --list and verify a matching config is found
279 def run_swig(files
, dir, gendir
, package
, USE_SWIG
, force
, swig_args
,
280 swig_deps
=[], add_under
=False):
281 """Run SWIG the way I want it done"""
283 if USE_SWIG
and not os
.path
.exists(os
.path
.join(dir, gendir
)):
284 os
.mkdir(os
.path
.join(dir, gendir
))
286 if USE_SWIG
and not os
.path
.exists(os
.path
.join("docs", "xml-raw")):
287 if not os
.path
.exists("docs"):
289 os
.mkdir(os
.path
.join("docs", "xml-raw"))
293 if add_under
: pre
= '_'
297 basefile
= os
.path
.splitext(file)[0]
298 i_file
= os
.path
.join(dir, file)
299 py_file
= os
.path
.join(dir, gendir
, pre
+basefile
+'.py')
300 cpp_file
= os
.path
.join(dir, gendir
, pre
+basefile
+'_wrap.cpp')
301 xml_file
= os
.path
.join("docs", "xml-raw", basefile
+pre
+'_swig.xml')
304 interface
= ['-interface', '_'+basefile
+'_']
308 sources
.append(cpp_file
)
310 if not cleaning
and USE_SWIG
:
311 for dep
in swig_deps
:
312 if newer(dep
, py_file
) or newer(dep
, cpp_file
):
316 if force
or newer(i_file
, py_file
) or newer(i_file
, cpp_file
):
317 ## we need forward slashes here even on win32
318 #cpp_file = opj(cpp_file) #'/'.join(cpp_file.split('\\'))
319 #i_file = opj(i_file) #'/'.join(i_file.split('\\'))
322 xmltemp
= tempfile
.mktemp('.xml')
324 # First run swig to produce the XML file, adding
325 # an extra -D that prevents the old rename
326 # directives from being used
327 cmd
= [ swig_cmd
] + swig_args
+ \
328 [ '-DBUILDING_RENAMERS', '-xmlout', xmltemp
] + \
329 ['-I'+dir, '-o', cpp_file
, i_file
]
333 # Next run build_renamers to process the XML
334 myRenamer
= BuildRenamers()
335 myRenamer
.run(dir, pre
+basefile
, xmltemp
)
338 # Then run swig for real
339 cmd
= [ swig_cmd
] + swig_args
+ interface
+ \
340 ['-I'+dir, '-o', cpp_file
, '-xmlout', xml_file
, i_file
]
345 # copy the generated python file to the package directory
346 copy_file(py_file
, package
, update
=not force
, verbose
=0)
347 CLEANUP
.append(opj(package
, os
.path
.basename(py_file
)))
353 # Specializations of some distutils command classes
354 class wx_smart_install_data(distutils
.command
.install_data
.install_data
):
355 """need to change self.install_dir to the actual library dir"""
357 install_cmd
= self
.get_finalized_command('install')
358 self
.install_dir
= getattr(install_cmd
, 'install_lib')
359 return distutils
.command
.install_data
.install_data
.run(self
)
362 class wx_extra_clean(distutils
.command
.clean
.clean
):
364 Also cleans stuff that this setup.py copies itself. If the
365 --all flag was used also searches for .pyc, .pyd, .so files
368 from distutils
import log
369 from distutils
.filelist
import FileList
372 distutils
.command
.clean
.clean
.run(self
)
376 fl
.include_pattern("*.pyc", 0)
377 fl
.include_pattern("*.pyd", 0)
378 fl
.include_pattern("*.so", 0)
384 if not self
.dry_run
and os
.path
.exists(f
):
386 log
.info("removing '%s'", f
)
388 log
.warning("unable to remove '%s'", f
)
392 if not self
.dry_run
and os
.path
.exists(f
):
394 log
.info("removing '%s'", f
)
396 log
.warning("unable to remove '%s'", f
)
400 class wx_install_headers(distutils
.command
.install_headers
.install_headers
):
402 Install the header files to the WXPREFIX, with an extra dir per
405 def initialize_options (self
):
407 distutils
.command
.install_headers
.install_headers
.initialize_options(self
)
409 def finalize_options (self
):
410 self
.set_undefined_options('install', ('root', 'root'))
411 distutils
.command
.install_headers
.install_headers
.finalize_options(self
)
416 headers
= self
.distribution
.headers
421 if root
is None or WXPREFIX
.startswith(root
):
423 for header
, location
in headers
:
424 install_dir
= os
.path
.normpath(root
+
426 '/include/wx-%d.%d/wx' % (VER_MAJOR
, VER_MINOR
) +
428 self
.mkpath(install_dir
)
429 (out
, _
) = self
.copy_file(header
, install_dir
)
430 self
.outfiles
.append(out
)
435 def build_locale_dir(destdir
, verbose
=1):
436 """Build a locale dir under the wxPython package for MSW"""
437 moFiles
= glob
.glob(opj(WXDIR
, 'locale', '*.mo'))
439 lang
= os
.path
.splitext(os
.path
.basename(src
))[0]
440 dest
= opj(destdir
, lang
, 'LC_MESSAGES')
441 mkpath(dest
, verbose
=verbose
)
442 copy_file(src
, opj(dest
, 'wxstd.mo'), update
=1, verbose
=verbose
)
443 CLEANUP
.append(opj(dest
, 'wxstd.mo'))
447 def build_locale_list(srcdir
):
448 # get a list of all files under the srcdir, to be used for install_data
449 def walk_helper(lst
, dirname
, files
):
451 filename
= opj(dirname
, f
)
452 if not os
.path
.isdir(filename
):
453 lst
.append( (dirname
, [filename
]) )
455 os
.path
.walk(srcdir
, walk_helper
, file_list
)
459 def find_data_files(srcdir
, *wildcards
):
460 # get a list of all files under the srcdir matching wildcards,
461 # returned in a format to be used for install_data
463 def walk_helper(arg
, dirname
, files
):
468 filename
= opj(dirname
, f
)
469 if fnmatch
.fnmatch(filename
, wc
) and not os
.path
.isdir(filename
):
470 names
.append(filename
)
472 lst
.append( (dirname
, names
) )
475 os
.path
.walk(srcdir
, walk_helper
, (file_list
, wildcards
))
479 def makeLibName(name
):
480 if os
.name
== 'posix':
481 libname
= '%s_%s-%s' % (WXBASENAME
, name
, WXRELEASE
)
483 libname
= 'wxmsw%s%s_%s' % (WXDLLVER
, libFlag(), name
)
489 def adjustCFLAGS(cflags
, defines
, includes
):
490 '''Extrace the raw -I, -D, and -U flags and put them into
491 defines and includes as needed.'''
495 includes
.append(flag
[2:])
496 elif flag
[:2] == '-D':
498 if flag
.find('=') == -1:
499 defines
.append( (flag
, None) )
501 defines
.append( tuple(flag
.split('=')) )
502 elif flag
[:2] == '-U':
503 defines
.append( (flag
[2:], ) )
505 newCFLAGS
.append(flag
)
510 def adjustLFLAGS(lfags
, libdirs
, libs
):
511 '''Extrace the -L and -l flags and put them in libdirs and libs as needed'''
515 libdirs
.append(flag
[2:])
516 elif flag
[:2] == '-l':
517 libs
.append(flag
[2:])
519 newLFLAGS
.append(flag
)
523 #----------------------------------------------------------------------
543 if UNICODE
and WXPORT
not in ['msw', 'gtk2']:
544 raise SystemExit, "UNICODE mode not currently supported on this WXPORT: "+WXPORT
548 CONTRIBS_INC
= [ CONTRIBS_INC
]
553 #----------------------------------------------------------------------
554 # Setup some platform specific stuff
555 #----------------------------------------------------------------------
558 # Set compile flags and such for MSVC. These values are derived
559 # from the wxWidgets makefiles for MSVC, other compilers settings
560 # will probably vary...
561 if os
.environ
.has_key('WXWIN'):
562 WXDIR
= os
.environ
['WXWIN']
564 msg("WARNING: WXWIN not set in environment.")
565 WXDIR
= '..' # assumes in CVS tree
569 includes
= ['include', 'src',
570 opj(WXDIR
, 'lib', 'vc_dll', 'msw' + libFlag()),
571 opj(WXDIR
, 'include'),
572 opj(WXDIR
, 'contrib', 'include'),
575 defines
= [ ('WIN32', None),
581 ('SWIG_GLOBAL', None),
582 ('WXP_USE_THREAD', '1'),
586 defines
.append( ('NDEBUG',) ) # using a 1-tuple makes it do an undef
589 defines
.append( ('__NO_VC_CRTDBG__', None) )
591 if not FINAL
or HYBRID
:
592 defines
.append( ('__WXDEBUG__', None) )
594 libdirs
= [ opj(WXDIR
, 'lib', 'vc_dll') ]
595 libs
= [ 'wxbase' + WXDLLVER
+ libFlag(), # TODO: trim this down to what is really needed for the core
596 'wxbase' + WXDLLVER
+ libFlag() + '_net',
597 'wxbase' + WXDLLVER
+ libFlag() + '_xml',
598 makeLibName('core')[0],
599 makeLibName('adv')[0],
600 makeLibName('html')[0],
603 libs
= libs
+ ['kernel32', 'user32', 'gdi32', 'comdlg32',
604 'winspool', 'winmm', 'shell32', 'oldnames', 'comctl32',
605 'odbc32', 'ole32', 'oleaut32', 'uuid', 'rpcrt4',
606 'advapi32', 'wsock32']
610 # '/GX-' # workaround for internal compiler error in MSVC on some machines
614 # Other MSVC flags...
615 # Too bad I don't remember why I was playing with these, can they be removed?
617 pass #cflags = cflags + ['/O1']
619 pass #cflags = cflags + ['/Ox']
621 pass # cflags = cflags + ['/Od', '/Z7']
622 # lflags = ['/DEBUG', ]
626 #----------------------------------------------------------------------
628 elif os
.name
== 'posix':
630 includes
= ['include', 'src']
631 defines
= [('SWIG_GLOBAL', None),
632 ('HAVE_CONFIG_H', None),
633 ('WXP_USE_THREAD', '1'),
636 defines
.append( ('NDEBUG',) ) # using a 1-tuple makes it do an undef
643 # If you get unresolved symbol errors on Solaris and are using gcc, then
644 # uncomment this block to add the right flags to the link step and build
646 ## if os.uname()[0] == 'SunOS':
647 ## libs.append('gcc')
648 ## libdirs.append(commands.getoutput("gcc -print-search-dirs | grep '^install' | awk '{print $2}'")[:-1])
650 cflags
= os
.popen(WX_CONFIG
+ ' --cxxflags', 'r').read()[:-1]
651 cflags
= cflags
.split()
658 lflags
= os
.popen(WX_CONFIG
+ ' --libs', 'r').read()[:-1]
659 lflags
= lflags
.split()
661 WXBASENAME
= os
.popen(WX_CONFIG
+ ' --basename').read()[:-1]
662 WXRELEASE
= os
.popen(WX_CONFIG
+ ' --release').read()[:-1]
663 WXPREFIX
= os
.popen(WX_CONFIG
+ ' --prefix').read()[:-1]
666 if sys
.platform
[:6] == "darwin":
667 # Flags and such for a Darwin (Max OS X) build of Python
675 # Set flags for other Unix type platforms
680 portcfg
= os
.popen('gtk-config --cflags', 'r').read()[:-1]
681 elif WXPORT
== 'gtk2':
683 GENDIR
= 'gtk' # no code differences so use the same generated sources
684 portcfg
= os
.popen('pkg-config gtk+-2.0 --cflags', 'r').read()[:-1]
685 BUILD_BASE
= BUILD_BASE
+ '-' + WXPORT
686 elif WXPORT
== 'x11':
689 BUILD_BASE
= BUILD_BASE
+ '-' + WXPORT
691 raise SystemExit, "Unknown WXPORT value: " + WXPORT
693 cflags
+= portcfg
.split()
695 # Some distros (e.g. Mandrake) put libGLU in /usr/X11R6/lib, but
696 # wx-config doesn't output that for some reason. For now, just
697 # add it unconditionally but we should really check if the lib is
698 # really found there or wx-config should be fixed.
699 libdirs
.append("/usr/X11R6/lib")
702 # Move the various -I, -D, etc. flags we got from the *config scripts
703 # into the distutils lists.
704 cflags
= adjustCFLAGS(cflags
, defines
, includes
)
705 lflags
= adjustLFLAGS(lflags
, libdirs
, libs
)
708 #----------------------------------------------------------------------
710 raise 'Sorry, platform not supported...'
713 #----------------------------------------------------------------------
714 # post platform setup checks and tweaks, create the full version string
715 #----------------------------------------------------------------------
718 BUILD_BASE
= BUILD_BASE
+ '.unicode'
721 if os
.path
.exists('DAILY_BUILD'):
723 VER_FLAGS
+= '.' + open('DAILY_BUILD').read().strip()
725 VERSION
= "%s.%s.%s.%s%s" % (VER_MAJOR
, VER_MINOR
, VER_RELEASE
,
726 VER_SUBREL
, VER_FLAGS
)
729 #----------------------------------------------------------------------
731 #----------------------------------------------------------------------
744 '-I' + opj(WXPY_SRC
, 'src'),
749 swig_args
.append('-DwxUSE_UNICODE')
752 swig_args
.append('-D_DO_FULL_DOCS')
755 swig_deps
= [ opj(WXPY_SRC
, 'src/my_typemaps.i'),
756 opj(WXPY_SRC
, 'src/common.swg'),
757 opj(WXPY_SRC
, 'src/pyrun.swg'),
760 depends
= [ #'include/wx/wxPython/wxPython.h',
761 #'include/wx/wxPython/wxPython_int.h',
765 #----------------------------------------------------------------------
767 ####################################
769 ####################################
778 FOUND_LIBXML2
= False
780 #---------------------------------------------------------------------------
783 renamerTemplateStart
= """\
784 // A bunch of %rename directives generated by BuildRenamers in config.py
785 // in order to remove the wx prefix from all global scope names.
787 #ifndef BUILDING_RENAMERS
791 renamerTemplateEnd
= """
795 wxPythonTemplateStart
= """\
796 ## This file reverse renames symbols in the wx package to give
797 ## them their wx prefix again, for backwards compatibility.
799 ## Generated by BuildRenamers in config.py
801 # This silly stuff here is so the wxPython.wx module doesn't conflict
802 # with the wx package. We need to import modules from the wx package
803 # here, then we'll put the wxPython.wx entry back in sys.modules.
806 if sys.modules.has_key('wxPython.wx'):
807 _wx = sys.modules['wxPython.wx']
808 del sys.modules['wxPython.wx']
812 sys.modules['wxPython.wx'] = _wx
816 # Now assign all the reverse-renamed names:
819 wxPythonTemplateEnd
= """
825 #---------------------------------------------------------------------------
827 def run(self
, destdir
, modname
, xmlfile
, wxPythonDir
="wxPython"):
829 assert FOUND_LIBXML2
, "The libxml2 module is required to use the BuildRenamers functionality."
831 if not os
.path
.exists(wxPythonDir
):
832 os
.mkdir(wxPythonDir
)
834 swigDest
= os
.path
.join(destdir
, "_"+modname
+"_rename.i")
835 pyDest
= os
.path
.join(wxPythonDir
, modname
+ '.py')
837 swigDestTemp
= tempfile
.mktemp('.tmp')
838 swigFile
= open(swigDestTemp
, "w")
839 swigFile
.write(renamerTemplateStart
)
841 pyDestTemp
= tempfile
.mktemp('.tmp')
842 pyFile
= open(pyDestTemp
, "w")
843 pyFile
.write(wxPythonTemplateStart
% modname
)
845 print "Parsing XML and building renamers..."
846 self
.processXML(xmlfile
, modname
, swigFile
, pyFile
)
848 self
.checkOtherNames(pyFile
, modname
,
849 os
.path
.join(destdir
, '_'+modname
+'_reverse.txt'))
850 pyFile
.write(wxPythonTemplateEnd
)
853 swigFile
.write(renamerTemplateEnd
)
856 # Compare the files just created with the existing one and
857 # blow away the old one if they are different.
858 for dest
, temp
in [(swigDest
, swigDestTemp
),
859 (pyDest
, pyDestTemp
)]:
860 if not os
.path
.exists(dest
):
861 os
.rename(temp
, dest
)
862 elif open(dest
).read() != open(temp
).read():
864 os
.rename(temp
, dest
)
866 print dest
+ " not changed."
869 #---------------------------------------------------------------------------
872 def GetAttr(self
, node
, name
):
873 path
= "./attributelist/attribute[@name='%s']/@value" % name
874 n
= node
.xpathEval2(path
)
881 def processXML(self
, xmlfile
, modname
, swigFile
, pyFile
):
883 topnode
= libxml2
.parseFile(xmlfile
).children
885 # remove any import nodes as we don't need to do renamers for symbols found therein
886 imports
= topnode
.xpathEval2("*/import")
891 # do a depth first iteration over what's left
899 if node
.name
== "class":
900 lastClassName
= name
= self
.GetAttr(node
, "name")
901 lastClassSymName
= sym_name
= self
.GetAttr(node
, "sym_name")
908 # renamed constructors
909 elif node
.name
== "constructor":
910 name
= self
.GetAttr(node
, "name")
911 sym_name
= self
.GetAttr(node
, "sym_name")
917 # only enumitems at the top level
918 elif node
.name
== "enumitem" and node
.parent
.parent
.name
== "include":
919 name
= self
.GetAttr(node
, "name")
920 sym_name
= self
.GetAttr(node
, "sym_name")
924 elif node
.name
in ["cdecl", "constant"]:
925 name
= self
.GetAttr(node
, "name")
926 sym_name
= self
.GetAttr(node
, "sym_name")
927 toplevel
= node
.parent
.name
== "include"
929 # top-level functions
930 if toplevel
and self
.GetAttr(node
, "view") == "globalfunctionHandler":
933 # top-level global vars
934 elif toplevel
and self
.GetAttr(node
, "feature_immutable") == "1":
938 elif self
.GetAttr(node
, "view") == "staticmemberfunctionHandler":
939 name
= lastClassName
+ '_' + name
940 sym_name
= lastClassSymName
+ '_' + sym_name
941 # only output the reverse renamer in this case
942 doRename
= revOnly
= True
944 if doRename
and name
!= sym_name
:
949 if doRename
and name
:
951 if old
.startswith('wx') and not old
.startswith('wxEVT_'):
952 # remove all wx prefixes except wxEVT_ and write a %rename directive for it
955 swigFile
.write("%%rename(%s) %35s;\n" % (new
, old
))
957 # Write assignments to import into the old wxPython namespace
958 if addWX
and not old
.startswith('wx'):
960 pyFile
.write("%s = wx.%s.%s\n" % (old
, modname
, new
))
962 pyFile
.write("%sPtr = wx.%s.%sPtr\n" % (old
, modname
, new
))
965 #---------------------------------------------------------------------------
967 def checkOtherNames(self
, pyFile
, moduleName
, filename
):
968 if os
.path
.exists(filename
):
970 for line
in file(filename
):
971 if line
.endswith('\n'):
973 if line
and not line
.startswith('#'):
974 if line
.endswith('*'):
975 prefixes
.append(line
[:-1])
976 elif line
.find('=') != -1:
977 pyFile
.write("%s\n" % line
)
980 if line
.startswith('wx') or line
.startswith('WX') or line
.startswith('EVT'):
982 pyFile
.write("%s = wx.%s.%s\n" % (wxname
, moduleName
, line
))
986 "\n\nd = globals()\nfor k, v in wx.%s.__dict__.iteritems():"
991 pyFile
.write("\n if ")
994 pyFile
.write("\n elif ")
995 pyFile
.write("k.startswith('%s'):\n d[k] = v" % p
)
996 pyFile
.write("\ndel d, k, v\n\n")
999 #---------------------------------------------------------------------------