]> git.saurik.com Git - wxWidgets.git/blame - wxPython/config.py
mention *TabOrder and Navigate methods
[wxWidgets.git] / wxPython / config.py
CommitLineData
1128a89b
RD
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.)
9#
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.
14#
15# Author: Robin Dunn
16#
17# Created: 23-March-2004
18# RCS-ID: $Id$
19# Copyright: (c) 2004 by Total Control Software
20# Licence: wxWindows license
21#----------------------------------------------------------------------
22
23import sys, os, glob, fnmatch, tempfile
24from distutils.core import setup, Extension
25from distutils.file_util import copy_file
26from distutils.dir_util import mkpath
27from distutils.dep_util import newer
28from distutils.spawn import spawn
29
30import distutils.command.install_data
31import distutils.command.install_headers
32import distutils.command.clean
33
34#----------------------------------------------------------------------
35# flags and values that affect this script
36#----------------------------------------------------------------------
37
38VER_MAJOR = 2 # The first three must match wxWidgets
39VER_MINOR = 5
1eac708b 40VER_RELEASE = 2
96acd0c1
RD
41VER_SUBREL = 2 # wxPython release num for x.y.z release of wxWidgets
42VER_FLAGS = "p" # release flags, such as prerelease num, unicode, etc.
1128a89b
RD
43
44DESCRIPTION = "Cross platform GUI toolkit for Python"
45AUTHOR = "Robin Dunn"
46AUTHOR_EMAIL = "Robin Dunn <robin@alldunn.com>"
47URL = "http://wxPython.org/"
48DOWNLOAD_URL = "http://wxPython.org/download.php"
49LICENSE = "wxWidgets Library License (LGPL derivative)"
50PLATFORMS = "WIN32,OSX,POSIX"
51KEYWORDS = "GUI,wx,wxWindows,wxWidgets,cross-platform"
52
53LONG_DESCRIPTION = """\
54wxPython is a GUI toolkit for Python that is a wrapper around the
55wxWidgets C++ GUI library. wxPython provides a large variety of
56window types and controls, all implemented with a native look and
57feel (by using the native widgets) on the platforms it is supported
58on.
59"""
60
61CLASSIFIERS = """\
62Development Status :: 6 - Mature
63Environment :: MacOS X :: Carbon
64Environment :: Win32 (MS Windows)
65Environment :: X11 Applications :: GTK
66Intended Audience :: Developers
67License :: OSI Approved
68Operating System :: MacOS :: MacOS X
69Operating System :: Microsoft :: Windows :: Windows 95/98/2000
70Operating System :: POSIX
71Programming Language :: Python
72Topic :: Software Development :: User Interfaces
73"""
74
75## License :: OSI Approved :: wxWidgets Library Licence
76
77
78# Config values below this point can be reset on the setup.py command line.
79
80BUILD_GLCANVAS = 1 # If true, build the contrib/glcanvas extension module
81BUILD_OGL = 1 # If true, build the contrib/ogl extension module
82BUILD_STC = 1 # If true, build the contrib/stc extension module
83BUILD_XRC = 1 # XML based resource system
84BUILD_GIZMOS = 1 # Build a module for the gizmos contrib library
85BUILD_DLLWIDGET = 0# Build a module that enables unknown wx widgets
86 # to be loaded from a DLL and to be used from Python.
87
88 # Internet Explorer wrapper (experimental)
89BUILD_IEWIN = (os.name == 'nt')
ef8b9c3e 90BUILD_ACTIVEX = (os.name == 'nt') # new version of IEWIN and more
1128a89b
RD
91
92
93CORE_ONLY = 0 # if true, don't build any of the above
94
95PREP_ONLY = 0 # Only run the prepatory steps, not the actual build.
96
97USE_SWIG = 0 # Should we actually execute SWIG, or just use the
98 # files already in the distribution?
99
100SWIG = "swig" # The swig executable to use.
101
102BUILD_RENAMERS = 1 # Should we build the renamer modules too?
103
d07d2bc9
RD
104FULL_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.
108
1128a89b
RD
109UNICODE = 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.
112
113UNDEF_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.
121
122NO_SCRIPTS = 0 # Don't install the tool scripts
123NO_HEADERS = 0 # Don't install the wxPython *.h and *.i files
124
125WX_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
130 # default $PATH.
131
132WXPORT = '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.
136
137BUILD_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
140 # values. See below.
141
142
143CONTRIBS_INC = "" # A dir to add as an -I flag when compiling the contribs
144
145
146# Some MSW build settings
147
148FINAL = 0 # Mirrors use of same flag in wx makefiles,
149 # (0 or 1 only) should probably find a way to
150 # autodetect this...
151
152HYBRID = 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.)
158
159 # Version part of wxWidgets LIB/DLL names
160WXDLLVER = '%d%d' % (VER_MAJOR, VER_MINOR)
161
73a22369
RD
162WXPY_SRC = '.' # Assume we're in the source tree already, but allow the
163 # user to change it, particularly for extension building.
164
1128a89b
RD
165
166#----------------------------------------------------------------------
167
168def msg(text):
fb3d05e9 169 if hasattr(sys, 'setup_is_main') and sys.setup_is_main:
1128a89b
RD
170 print text
171
172
173def opj(*args):
73a22369 174 path = os.path.join(*args)
1128a89b
RD
175 return os.path.normpath(path)
176
177
178def libFlag():
179 if FINAL:
180 rv = ''
181 elif HYBRID:
182 rv = 'h'
183 else:
184 rv = 'd'
185 if UNICODE:
186 rv = 'u' + rv
187 return rv
188
189
190#----------------------------------------------------------------------
191# Some other globals
192#----------------------------------------------------------------------
193
194PKGDIR = 'wx'
195wxpExtensions = []
196DATA_FILES = []
197CLEANUP = []
198
199force = '--force' in sys.argv or '-f' in sys.argv
200debug = '--debug' in sys.argv or '-g' in sys.argv
201cleaning = 'clean' in sys.argv
202
203
204# change the PORT default for wxMac
205if sys.platform[:6] == "darwin":
206 WXPORT = 'mac'
207
208# and do the same for wxMSW, just for consistency
209if os.name == 'nt':
210 WXPORT = 'msw'
211
212
213#----------------------------------------------------------------------
214# Check for build flags on the command line
215#----------------------------------------------------------------------
216
217# Boolean (int) flags
218for 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',
d07d2bc9 222 'FULL_DOCS',
1128a89b
RD
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
227 if pos > 0:
228 vars()[flag] = eval(sys.argv[x][pos:])
229 sys.argv[x] = ''
230
231# String options
232for option in ['WX_CONFIG', 'WXDLLVER', 'BUILD_BASE', 'WXPORT', 'SWIG',
73a22369 233 'CONTRIBS_INC', 'WXPY_SRC']:
1128a89b
RD
234 for x in range(len(sys.argv)):
235 if sys.argv[x].find(option) == 0:
236 pos = sys.argv[x].find('=') + 1
237 if pos > 0:
238 vars()[option] = sys.argv[x][pos:]
239 sys.argv[x] = ''
240
241sys.argv = filter(None, sys.argv)
242
243
244#----------------------------------------------------------------------
245# some helper functions
246#----------------------------------------------------------------------
247
248def Verify_WX_CONFIG():
249 """ Called below for the builds that need wx-config,
250 if WX_CONFIG is not set then tries to select the specific
251 wx*-config script based on build options. If not found
252 then it defaults to 'wx-config'.
253 """
254 # if WX_CONFIG hasn't been set to an explicit value then construct one.
255 global WX_CONFIG
256 if WX_CONFIG is None:
257 if debug: # TODO: Fix this. wxPython's --debug shouldn't be tied to wxWidgets...
258 df = 'd'
259 else:
260 df = ''
261 if UNICODE:
262 uf = 'u'
263 else:
264 uf = ''
265 ver2 = "%s.%s" % (VER_MAJOR, VER_MINOR)
266 port = WXPORT
267 if port == "x11":
268 port = "x11univ"
269 WX_CONFIG = 'wx%s%s%s-%s-config' % (port, uf, df, ver2)
270
271 searchpath = os.environ["PATH"]
272 for p in searchpath.split(':'):
273 fp = os.path.join(p, WX_CONFIG)
274 if os.path.exists(fp) and os.access(fp, os.X_OK):
275 # success
276 msg("Found wx-config: " + fp)
277 WX_CONFIG = fp
278 break
279 else:
280 msg("WX_CONFIG not specified and %s not found on $PATH "
281 "defaulting to \"wx-config\"" % WX_CONFIG)
282 WX_CONFIG = 'wx-config'
283
284
285
54f9ee45
RD
286def run_swig(files, dir, gendir, package, USE_SWIG, force, swig_args,
287 swig_deps=[], add_under=False):
1128a89b
RD
288 """Run SWIG the way I want it done"""
289
290 if USE_SWIG and not os.path.exists(os.path.join(dir, gendir)):
291 os.mkdir(os.path.join(dir, gendir))
292
293 if USE_SWIG and not os.path.exists(os.path.join("docs", "xml-raw")):
73a22369
RD
294 if not os.path.exists("docs"):
295 os.mkdir("docs")
1128a89b
RD
296 os.mkdir(os.path.join("docs", "xml-raw"))
297
298 sources = []
299
54f9ee45
RD
300 if add_under: pre = '_'
301 else: pre = ''
302
1128a89b
RD
303 for file in files:
304 basefile = os.path.splitext(file)[0]
305 i_file = os.path.join(dir, file)
54f9ee45
RD
306 py_file = os.path.join(dir, gendir, pre+basefile+'.py')
307 cpp_file = os.path.join(dir, gendir, pre+basefile+'_wrap.cpp')
fda33067 308 xml_file = os.path.join("docs", "xml-raw", basefile+pre+'_swig.xml')
1128a89b 309
54f9ee45
RD
310 if add_under:
311 interface = ['-interface', '_'+basefile+'_']
312 else:
313 interface = []
314
1128a89b
RD
315 sources.append(cpp_file)
316
317 if not cleaning and USE_SWIG:
318 for dep in swig_deps:
319 if newer(dep, py_file) or newer(dep, cpp_file):
320 force = 1
321 break
322
323 if force or newer(i_file, py_file) or newer(i_file, cpp_file):
324 ## we need forward slashes here even on win32
325 #cpp_file = opj(cpp_file) #'/'.join(cpp_file.split('\\'))
326 #i_file = opj(i_file) #'/'.join(i_file.split('\\'))
327
328 if BUILD_RENAMERS:
1128a89b
RD
329 xmltemp = tempfile.mktemp('.xml')
330
331 # First run swig to produce the XML file, adding
332 # an extra -D that prevents the old rename
333 # directives from being used
334 cmd = [ swig_cmd ] + swig_args + \
335 [ '-DBUILDING_RENAMERS', '-xmlout', xmltemp ] + \
336 ['-I'+dir, '-o', cpp_file, i_file]
337 msg(' '.join(cmd))
338 spawn(cmd)
339
340 # Next run build_renamers to process the XML
73a22369
RD
341 myRenamer = BuildRenamers()
342 myRenamer.run(dir, pre+basefile, xmltemp)
1128a89b
RD
343 os.remove(xmltemp)
344
345 # Then run swig for real
54f9ee45
RD
346 cmd = [ swig_cmd ] + swig_args + interface + \
347 ['-I'+dir, '-o', cpp_file, '-xmlout', xml_file, i_file]
1128a89b
RD
348 msg(' '.join(cmd))
349 spawn(cmd)
350
351
352 # copy the generated python file to the package directory
353 copy_file(py_file, package, update=not force, verbose=0)
354 CLEANUP.append(opj(package, os.path.basename(py_file)))
355
356 return sources
357
358
359
360# Specializations of some distutils command classes
361class wx_smart_install_data(distutils.command.install_data.install_data):
362 """need to change self.install_dir to the actual library dir"""
363 def run(self):
364 install_cmd = self.get_finalized_command('install')
365 self.install_dir = getattr(install_cmd, 'install_lib')
366 return distutils.command.install_data.install_data.run(self)
367
368
369class wx_extra_clean(distutils.command.clean.clean):
370 """
371 Also cleans stuff that this setup.py copies itself. If the
372 --all flag was used also searches for .pyc, .pyd, .so files
373 """
374 def run(self):
375 from distutils import log
376 from distutils.filelist import FileList
377 global CLEANUP
378
379 distutils.command.clean.clean.run(self)
380
381 if self.all:
382 fl = FileList()
383 fl.include_pattern("*.pyc", 0)
384 fl.include_pattern("*.pyd", 0)
385 fl.include_pattern("*.so", 0)
386 CLEANUP += fl.files
387
388 for f in CLEANUP:
389 if os.path.isdir(f):
390 try:
391 if not self.dry_run and os.path.exists(f):
392 os.rmdir(f)
393 log.info("removing '%s'", f)
394 except IOError:
395 log.warning("unable to remove '%s'", f)
396
397 else:
398 try:
399 if not self.dry_run and os.path.exists(f):
400 os.remove(f)
401 log.info("removing '%s'", f)
402 except IOError:
403 log.warning("unable to remove '%s'", f)
404
405
406
407class wx_install_headers(distutils.command.install_headers.install_headers):
408 """
409 Install the header files to the WXPREFIX, with an extra dir per
410 filename too
411 """
412 def initialize_options (self):
413 self.root = None
414 distutils.command.install_headers.install_headers.initialize_options(self)
415
416 def finalize_options (self):
417 self.set_undefined_options('install', ('root', 'root'))
418 distutils.command.install_headers.install_headers.finalize_options(self)
419
420 def run(self):
421 if os.name == 'nt':
422 return
423 headers = self.distribution.headers
424 if not headers:
425 return
426
427 root = self.root
862b5362 428 if root is None or WXPREFIX.startswith(root):
1128a89b
RD
429 root = ''
430 for header, location in headers:
431 install_dir = os.path.normpath(root + WXPREFIX + location)
432 self.mkpath(install_dir)
433 (out, _) = self.copy_file(header, install_dir)
434 self.outfiles.append(out)
435
436
437
438
439def build_locale_dir(destdir, verbose=1):
440 """Build a locale dir under the wxPython package for MSW"""
441 moFiles = glob.glob(opj(WXDIR, 'locale', '*.mo'))
442 for src in moFiles:
443 lang = os.path.splitext(os.path.basename(src))[0]
444 dest = opj(destdir, lang, 'LC_MESSAGES')
445 mkpath(dest, verbose=verbose)
446 copy_file(src, opj(dest, 'wxstd.mo'), update=1, verbose=verbose)
447 CLEANUP.append(opj(dest, 'wxstd.mo'))
448 CLEANUP.append(dest)
449
450
451def build_locale_list(srcdir):
452 # get a list of all files under the srcdir, to be used for install_data
453 def walk_helper(lst, dirname, files):
454 for f in files:
455 filename = opj(dirname, f)
456 if not os.path.isdir(filename):
457 lst.append( (dirname, [filename]) )
458 file_list = []
459 os.path.walk(srcdir, walk_helper, file_list)
460 return file_list
461
462
463def find_data_files(srcdir, *wildcards):
464 # get a list of all files under the srcdir matching wildcards,
465 # returned in a format to be used for install_data
466
467 def walk_helper(arg, dirname, files):
468 names = []
469 lst, wildcards = arg
470 for wc in wildcards:
471 for f in files:
472 filename = opj(dirname, f)
473 if fnmatch.fnmatch(filename, wc) and not os.path.isdir(filename):
474 names.append(filename)
475 if names:
476 lst.append( (dirname, names ) )
477
478 file_list = []
479 os.path.walk(srcdir, walk_helper, (file_list, wildcards))
480 return file_list
481
482
483def makeLibName(name):
484 if os.name == 'posix':
485 libname = '%s_%s-%s' % (WXBASENAME, name, WXRELEASE)
486 else:
487 libname = 'wxmsw%s%s_%s' % (WXDLLVER, libFlag(), name)
488
489 return [libname]
490
491
492
493def adjustCFLAGS(cflags, defines, includes):
494 '''Extrace the raw -I, -D, and -U flags and put them into
495 defines and includes as needed.'''
496 newCFLAGS = []
497 for flag in cflags:
498 if flag[:2] == '-I':
499 includes.append(flag[2:])
500 elif flag[:2] == '-D':
501 flag = flag[2:]
502 if flag.find('=') == -1:
503 defines.append( (flag, None) )
504 else:
505 defines.append( tuple(flag.split('=')) )
506 elif flag[:2] == '-U':
507 defines.append( (flag[2:], ) )
508 else:
509 newCFLAGS.append(flag)
510 return newCFLAGS
511
512
513
514def adjustLFLAGS(lfags, libdirs, libs):
515 '''Extrace the -L and -l flags and put them in libdirs and libs as needed'''
516 newLFLAGS = []
517 for flag in lflags:
518 if flag[:2] == '-L':
519 libdirs.append(flag[2:])
520 elif flag[:2] == '-l':
521 libs.append(flag[2:])
522 else:
523 newLFLAGS.append(flag)
524
525 return newLFLAGS
526
527#----------------------------------------------------------------------
528# sanity checks
529
530if CORE_ONLY:
531 BUILD_GLCANVAS = 0
532 BUILD_OGL = 0
533 BUILD_STC = 0
534 BUILD_XRC = 0
535 BUILD_GIZMOS = 0
536 BUILD_DLLWIDGET = 0
537 BUILD_IEWIN = 0
538 BUILD_ACTIVEX = 0
539
540if debug:
541 FINAL = 0
542 HYBRID = 0
543
544if FINAL:
545 HYBRID = 0
546
547if UNICODE and WXPORT not in ['msw', 'gtk2']:
548 raise SystemExit, "UNICODE mode not currently supported on this WXPORT: "+WXPORT
549
550
551if CONTRIBS_INC:
552 CONTRIBS_INC = [ CONTRIBS_INC ]
553else:
554 CONTRIBS_INC = []
555
556
557#----------------------------------------------------------------------
558# Setup some platform specific stuff
559#----------------------------------------------------------------------
560
561if os.name == 'nt':
562 # Set compile flags and such for MSVC. These values are derived
563 # from the wxWidgets makefiles for MSVC, other compilers settings
564 # will probably vary...
565 if os.environ.has_key('WXWIN'):
566 WXDIR = os.environ['WXWIN']
567 else:
568 msg("WARNING: WXWIN not set in environment.")
569 WXDIR = '..' # assumes in CVS tree
570 WXPLAT = '__WXMSW__'
571 GENDIR = 'msw'
572
573 includes = ['include', 'src',
574 opj(WXDIR, 'lib', 'vc_dll', 'msw' + libFlag()),
575 opj(WXDIR, 'include'),
576 opj(WXDIR, 'contrib', 'include'),
577 ]
578
579 defines = [ ('WIN32', None),
580 ('_WINDOWS', None),
581
582 (WXPLAT, None),
583 ('WXUSINGDLL', '1'),
584
585 ('SWIG_GLOBAL', None),
586 ('WXP_USE_THREAD', '1'),
587 ]
588
589 if UNDEF_NDEBUG:
590 defines.append( ('NDEBUG',) ) # using a 1-tuple makes it do an undef
591
592 if HYBRID:
593 defines.append( ('__NO_VC_CRTDBG__', None) )
594
595 if not FINAL or HYBRID:
596 defines.append( ('__WXDEBUG__', None) )
597
598 libdirs = [ opj(WXDIR, 'lib', 'vc_dll') ]
599 libs = [ 'wxbase' + WXDLLVER + libFlag(), # TODO: trim this down to what is really needed for the core
600 'wxbase' + WXDLLVER + libFlag() + '_net',
601 'wxbase' + WXDLLVER + libFlag() + '_xml',
602 makeLibName('core')[0],
603 makeLibName('adv')[0],
604 makeLibName('html')[0],
605 ]
606
607 libs = libs + ['kernel32', 'user32', 'gdi32', 'comdlg32',
608 'winspool', 'winmm', 'shell32', 'oldnames', 'comctl32',
609 'odbc32', 'ole32', 'oleaut32', 'uuid', 'rpcrt4',
610 'advapi32', 'wsock32']
611
612
613 cflags = [ '/Gy',
614 # '/GX-' # workaround for internal compiler error in MSVC on some machines
615 ]
616 lflags = None
617
618 # Other MSVC flags...
619 # Too bad I don't remember why I was playing with these, can they be removed?
620 if FINAL:
621 pass #cflags = cflags + ['/O1']
622 elif HYBRID :
623 pass #cflags = cflags + ['/Ox']
624 else:
625 pass # cflags = cflags + ['/Od', '/Z7']
626 # lflags = ['/DEBUG', ]
627
628
629
630#----------------------------------------------------------------------
631
632elif os.name == 'posix':
633 WXDIR = '..'
634 includes = ['include', 'src']
635 defines = [('SWIG_GLOBAL', None),
636 ('HAVE_CONFIG_H', None),
637 ('WXP_USE_THREAD', '1'),
638 ]
639 if UNDEF_NDEBUG:
640 defines.append( ('NDEBUG',) ) # using a 1-tuple makes it do an undef
641
642 Verify_WX_CONFIG()
643
644 libdirs = []
645 libs = []
646
647 # If you get unresolved symbol errors on Solaris and are using gcc, then
648 # uncomment this block to add the right flags to the link step and build
649 # again.
650 ## if os.uname()[0] == 'SunOS':
651 ## libs.append('gcc')
652 ## libdirs.append(commands.getoutput("gcc -print-search-dirs | grep '^install' | awk '{print $2}'")[:-1])
653
654 cflags = os.popen(WX_CONFIG + ' --cxxflags', 'r').read()[:-1]
655 cflags = cflags.split()
656 if debug:
657 cflags.append('-g')
658 cflags.append('-O0')
659 else:
660 cflags.append('-O3')
661
662 lflags = os.popen(WX_CONFIG + ' --libs', 'r').read()[:-1]
663 lflags = lflags.split()
664
665 WXBASENAME = os.popen(WX_CONFIG + ' --basename').read()[:-1]
666 WXRELEASE = os.popen(WX_CONFIG + ' --release').read()[:-1]
667 WXPREFIX = os.popen(WX_CONFIG + ' --prefix').read()[:-1]
668
669
670 if sys.platform[:6] == "darwin":
671 # Flags and such for a Darwin (Max OS X) build of Python
672 WXPLAT = '__WXMAC__'
673 GENDIR = 'mac'
674 libs = ['stdc++']
675 NO_SCRIPTS = 1
676
677
678 else:
679 # Set flags for other Unix type platforms
680 GENDIR = WXPORT
681
682 if WXPORT == 'gtk':
683 WXPLAT = '__WXGTK__'
684 portcfg = os.popen('gtk-config --cflags', 'r').read()[:-1]
685 elif WXPORT == 'gtk2':
686 WXPLAT = '__WXGTK__'
687 GENDIR = 'gtk' # no code differences so use the same generated sources
688 portcfg = os.popen('pkg-config gtk+-2.0 --cflags', 'r').read()[:-1]
689 BUILD_BASE = BUILD_BASE + '-' + WXPORT
690 elif WXPORT == 'x11':
691 WXPLAT = '__WXX11__'
692 portcfg = ''
693 BUILD_BASE = BUILD_BASE + '-' + WXPORT
694 else:
695 raise SystemExit, "Unknown WXPORT value: " + WXPORT
696
697 cflags += portcfg.split()
698
699 # Some distros (e.g. Mandrake) put libGLU in /usr/X11R6/lib, but
700 # wx-config doesn't output that for some reason. For now, just
701 # add it unconditionally but we should really check if the lib is
702 # really found there or wx-config should be fixed.
703 libdirs.append("/usr/X11R6/lib")
704
705
706 # Move the various -I, -D, etc. flags we got from the *config scripts
707 # into the distutils lists.
708 cflags = adjustCFLAGS(cflags, defines, includes)
709 lflags = adjustLFLAGS(lflags, libdirs, libs)
710
711
712#----------------------------------------------------------------------
713else:
714 raise 'Sorry, platform not supported...'
715
716
717#----------------------------------------------------------------------
718# post platform setup checks and tweaks, create the full version string
719#----------------------------------------------------------------------
720
721if UNICODE:
722 BUILD_BASE = BUILD_BASE + '.unicode'
723 VER_FLAGS += 'u'
724
96acd0c1 725if os.path.exists('DAILY_BUILD'):
4b2826e5
RD
726
727 VER_FLAGS += '.' + open('DAILY_BUILD').read().strip()
1128a89b
RD
728
729VERSION = "%s.%s.%s.%s%s" % (VER_MAJOR, VER_MINOR, VER_RELEASE,
730 VER_SUBREL, VER_FLAGS)
731
732
733#----------------------------------------------------------------------
734# SWIG defaults
735#----------------------------------------------------------------------
736
737swig_cmd = SWIG
738swig_force = force
739swig_args = ['-c++',
740 '-Wall',
741 '-nodefault',
742
743 '-python',
744 '-keyword',
745 '-new_repr',
746 '-modern',
747
73a22369 748 '-I' + opj(WXPY_SRC, 'src'),
1128a89b
RD
749 '-D'+WXPLAT,
750 '-noruntime'
751 ]
752if UNICODE:
753 swig_args.append('-DwxUSE_UNICODE')
754
d07d2bc9
RD
755if FULL_DOCS:
756 swig_args.append('-D_DO_FULL_DOCS')
757
758
73a22369
RD
759swig_deps = [ opj(WXPY_SRC, 'src/my_typemaps.i'),
760 opj(WXPY_SRC, 'src/common.swg'),
761 opj(WXPY_SRC, 'src/pyrun.swg'),
1128a89b
RD
762 ]
763
764depends = [ #'include/wx/wxPython/wxPython.h',
765 #'include/wx/wxPython/wxPython_int.h',
766 #'src/pyclasses.h',
767 ]
768
769#----------------------------------------------------------------------
c278542b
RD
770
771####################################
772# BuildRenamers
773####################################
774
775import pprint
776import xml.sax
777
778try:
779 import libxml2
780 FOUND_LIBXML2 = True
781except ImportError:
782 FOUND_LIBXML2 = False
783
784#---------------------------------------------------------------------------
785
786
787renamerTemplateStart = """\
788// A bunch of %rename directives generated by BuildRenamers in config.py
789// in order to remove the wx prefix from all global scope names.
790
791#ifndef BUILDING_RENAMERS
792
793"""
794
795renamerTemplateEnd = """
796#endif
797"""
798
799wxPythonTemplateStart = """\
800## This file reverse renames symbols in the wx package to give
801## them their wx prefix again, for backwards compatibility.
802##
803## Generated by BuildRenamers in config.py
804
805# This silly stuff here is so the wxPython.wx module doesn't conflict
806# with the wx package. We need to import modules from the wx package
807# here, then we'll put the wxPython.wx entry back in sys.modules.
808import sys
809_wx = None
810if sys.modules.has_key('wxPython.wx'):
811 _wx = sys.modules['wxPython.wx']
812 del sys.modules['wxPython.wx']
813
814import wx.%s
815
816sys.modules['wxPython.wx'] = _wx
817del sys, _wx
818
819
820# Now assign all the reverse-renamed names:
821"""
822
823wxPythonTemplateEnd = """
824
825"""
826
827
828
829#---------------------------------------------------------------------------
830class BuildRenamers:
831 def run(self, destdir, modname, xmlfile, wxPythonDir="wxPython"):
832
833 assert FOUND_LIBXML2, "The libxml2 module is required to use the BuildRenamers functionality."
834
835 if not os.path.exists(wxPythonDir):
836 os.mkdir(wxPythonDir)
837
838 swigDest = os.path.join(destdir, "_"+modname+"_rename.i")
839 pyDest = os.path.join(wxPythonDir, modname + '.py')
840
841 swigDestTemp = tempfile.mktemp('.tmp')
842 swigFile = open(swigDestTemp, "w")
843 swigFile.write(renamerTemplateStart)
844
845 pyDestTemp = tempfile.mktemp('.tmp')
846 pyFile = open(pyDestTemp, "w")
847 pyFile.write(wxPythonTemplateStart % modname)
848
849 print "Parsing XML and building renamers..."
850 self.processXML(xmlfile, modname, swigFile, pyFile)
851
852 self.checkOtherNames(pyFile, modname,
853 os.path.join(destdir, '_'+modname+'_reverse.txt'))
854 pyFile.write(wxPythonTemplateEnd)
855 pyFile.close()
856
857 swigFile.write(renamerTemplateEnd)
858 swigFile.close()
859
860 # Compare the files just created with the existing one and
861 # blow away the old one if they are different.
862 for dest, temp in [(swigDest, swigDestTemp),
863 (pyDest, pyDestTemp)]:
864 if not os.path.exists(dest):
865 os.rename(temp, dest)
866 elif open(dest).read() != open(temp).read():
867 os.unlink(dest)
868 os.rename(temp, dest)
869 else:
870 print dest + " not changed."
871 os.unlink(temp)
872
873 #---------------------------------------------------------------------------
874
875
876 def GetAttr(self, node, name):
877 path = "./attributelist/attribute[@name='%s']/@value" % name
878 n = node.xpathEval2(path)
879 if len(n):
880 return n[0].content
881 else:
882 return None
883
884
885 def processXML(self, xmlfile, modname, swigFile, pyFile):
886
887 topnode = libxml2.parseFile(xmlfile).children
888
889 # remove any import nodes as we don't need to do renamers for symbols found therein
890 imports = topnode.xpathEval2("*/import")
891 for n in imports:
892 n.unlinkNode()
893 n.freeNode()
894
895 # do a depth first iteration over what's left
896 for node in topnode:
897 doRename = False
898 doPtr = False
899 addWX = False
900 revOnly = False
901
902
903 if node.name == "class":
904 lastClassName = name = self.GetAttr(node, "name")
905 lastClassSymName = sym_name = self.GetAttr(node, "sym_name")
906 doRename = True
907 doPtr = True
908 if sym_name != name:
909 name = sym_name
910 addWX = True
911
912 # renamed constructors
913 elif node.name == "constructor":
914 name = self.GetAttr(node, "name")
915 sym_name = self.GetAttr(node, "sym_name")
916 if sym_name != name:
917 name = sym_name
918 addWX = True
919 doRename = True
920
921 # only enumitems at the top level
922 elif node.name == "enumitem" and node.parent.parent.name == "include":
923 name = self.GetAttr(node, "name")
924 sym_name = self.GetAttr(node, "sym_name")
925 doRename = True
926
927
928 elif node.name in ["cdecl", "constant"]:
929 name = self.GetAttr(node, "name")
930 sym_name = self.GetAttr(node, "sym_name")
931 toplevel = node.parent.name == "include"
932
933 # top-level functions
934 if toplevel and self.GetAttr(node, "view") == "globalfunctionHandler":
935 doRename = True
936
937 # top-level global vars
938 elif toplevel and self.GetAttr(node, "feature_immutable") == "1":
939 doRename = True
940
941 # static methods
942 elif self.GetAttr(node, "view") == "staticmemberfunctionHandler":
943 name = lastClassName + '_' + name
944 sym_name = lastClassSymName + '_' + sym_name
945 # only output the reverse renamer in this case
946 doRename = revOnly = True
947
948 if doRename and name != sym_name:
949 name = sym_name
950 addWX = True
951
952
953 if doRename and name:
954 old = new = name
955 if old.startswith('wx') and not old.startswith('wxEVT_'):
956 # remove all wx prefixes except wxEVT_ and write a %rename directive for it
957 new = old[2:]
958 if not revOnly:
959 swigFile.write("%%rename(%s) %35s;\n" % (new, old))
960
961 # Write assignments to import into the old wxPython namespace
962 if addWX and not old.startswith('wx'):
963 old = 'wx'+old
964 pyFile.write("%s = wx.%s.%s\n" % (old, modname, new))
965 if doPtr:
966 pyFile.write("%sPtr = wx.%s.%sPtr\n" % (old, modname, new))
967
968
969 #---------------------------------------------------------------------------
970
971 def checkOtherNames(self, pyFile, moduleName, filename):
972 if os.path.exists(filename):
973 prefixes = []
974 for line in file(filename):
975 if line.endswith('\n'):
976 line = line[:-1]
977 if line and not line.startswith('#'):
978 if line.endswith('*'):
979 prefixes.append(line[:-1])
980 elif line.find('=') != -1:
981 pyFile.write("%s\n" % line)
982 else:
983 wxname = 'wx' + line
984 if line.startswith('wx') or line.startswith('WX') or line.startswith('EVT'):
985 wxname = line
986 pyFile.write("%s = wx.%s.%s\n" % (wxname, moduleName, line))
987
988 if prefixes:
989 pyFile.write(
990 "\n\nd = globals()\nfor k, v in wx.%s.__dict__.iteritems():"
991 % moduleName)
992 first = True
993 for p in prefixes:
994 if first:
995 pyFile.write("\n if ")
996 first = False
997 else:
998 pyFile.write("\n elif ")
999 pyFile.write("k.startswith('%s'):\n d[k] = v" % p)
1000 pyFile.write("\ndel d, k, v\n\n")
1001
1002
1003#---------------------------------------------------------------------------