]> git.saurik.com Git - wxWidgets.git/blob - wxPython/config.py
fixes to wint_t and wchar_t handling in unichar.h (fixes FreeBSD compilation and...
[wxWidgets.git] / 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.)
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
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
29
30 import distutils.command.install
31 import distutils.command.install_data
32 import distutils.command.install_headers
33 import distutils.command.clean
34
35 #----------------------------------------------------------------------
36 # flags and values that affect this script
37 #----------------------------------------------------------------------
38
39 VER_MAJOR = 2 # The first three must match wxWidgets
40 VER_MINOR = 9
41 VER_RELEASE = 0
42 VER_SUBREL = 0 # wxPython release num for x.y.z release of wxWidgets
43 VER_FLAGS = "" # release flags, such as prerelease or RC num, etc.
44
45 DESCRIPTION = "Cross platform GUI toolkit for Python"
46 AUTHOR = "Robin Dunn"
47 AUTHOR_EMAIL = "Robin Dunn <robin@alldunn.com>"
48 URL = "http://wxPython.org/"
49 DOWNLOAD_URL = "http://wxPython.org/download.php"
50 LICENSE = "wxWidgets Library License (LGPL derivative)"
51 PLATFORMS = "WIN32,OSX,POSIX"
52 KEYWORDS = "GUI,wx,wxWindows,wxWidgets,cross-platform"
53
54 LONG_DESCRIPTION = """\
55 wxPython is a GUI toolkit for Python that is a wrapper around the
56 wxWidgets C++ GUI library. wxPython provides a large variety of
57 window types and controls, all implemented with a native look and
58 feel (by using the native widgets) on the platforms upon which it is
59 supported.
60 """
61
62 CLASSIFIERS = """\
63 Development Status :: 6 - Mature
64 Environment :: MacOS X :: Carbon
65 Environment :: Win32 (MS Windows)
66 Environment :: X11 Applications :: GTK
67 Intended Audience :: Developers
68 License :: OSI Approved
69 Operating System :: MacOS :: MacOS X
70 Operating System :: Microsoft :: Windows :: Windows 95/98/2000
71 Operating System :: POSIX
72 Programming Language :: Python
73 Topic :: Software Development :: User Interfaces
74 """
75
76 ## License :: OSI Approved :: wxWidgets Library Licence
77
78
79 # Config values below this point can be reset on the setup.py command line.
80
81 BUILD_GLCANVAS = 1 # If true, build the contrib/glcanvas extension module
82 BUILD_OGL = 0 # If true, build the contrib/ogl extension module
83 BUILD_STC = 1 # If true, build the contrib/stc extension module
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.
87
88 # Internet Explorer wrapper (experimental)
89 BUILD_ACTIVEX = (os.name == 'nt') # new version of IEWIN and more
90
91
92 CORE_ONLY = 0 # if true, don't build any of the above
93
94 PREP_ONLY = 0 # Only run the prepatory steps, not the actual build.
95
96 USE_SWIG = 0 # Should we actually execute SWIG, or just use the
97 # files already in the distribution?
98
99 SWIG = "swig" # The swig executable to use.
100
101 BUILD_RENAMERS = 0 # Should we build the renamer modules too?
102
103 FULL_DOCS = 0 # Some docstrings are split into a basic docstring and a
104 # details string. Setting this flag to 1 will
105 # cause the two strings to be combined and output
106 # as the full docstring.
107
108 UNICODE = 1 # This will pass the 'wxUSE_UNICODE' flag to SWIG and
109 # will ensure that the right headers are found and the
110 # right libs are linked.
111
112 UNDEF_NDEBUG = 1 # Python 2.2 on Unix/Linux by default defines NDEBUG,
113 # and distutils will pick this up and use it on the
114 # compile command-line for the extensions. This could
115 # conflict with how wxWidgets was built. If NDEBUG is
116 # set then wxWidgets' __WXDEBUG__ setting will be turned
117 # off. If wxWidgets was actually built with it turned
118 # on then you end up with mismatched class structures,
119 # and wxPython will crash.
120
121 NO_SCRIPTS = 0 # Don't install the tool scripts
122 NO_HEADERS = 0 # Don't install the wxPython *.h and *.i files
123
124 INSTALL_MULTIVERSION = 1 # Install the packages such that multiple versions
125 # can co-exist. When turned on the wx and wxPython
126 # pacakges will be installed in a versioned subdir
127 # of site-packages, and a *.pth file will be
128 # created that adds that dir to the sys.path. In
129 # addition, a wxselect.py module will be installed
130 # to site-pacakges that will allow applications to
131 # choose a specific version if more than one is
132 # installed.
133
134 FLAVOUR = "" # Optional flavour string to be appended to VERSION
135 # in MULTIVERSION installs
136
137 EP_ADD_OPTS = 1 # When doing MULTIVERSION installs the wx port and
138 # ansi/unicode settings can optionally be added to the
139 # subdir path used in site-packages
140
141 EP_FULL_VER = 0 # When doing MULTIVERSION installs the default is to
142 # put only 2 or 3 (depending on stable/unstable) of
143 # the version compnonents into the "extra path"
144 # subdir of site-packages. Setting this option to
145 # 1 will cause the full 4 components of the version
146 # number to be used instead.
147
148 WX_CONFIG = None # Usually you shouldn't need to touch this, but you can set
149 # it to pass an alternate version of wx-config or alternate
150 # flags, eg. as required by the .deb in-tree build. By
151 # default a wx-config command will be assembled based on
152 # version, port, etc. and it will be looked for on the
153 # default $PATH.
154
155 SYS_WX_CONFIG = None # When installing an in tree build, setup.py uses wx-config
156 # for two different purposes. First, to determine the prefix
157 # where files will be installed, and secondly, to initialise
158 # build_options.py with the correct options for it.
159 # WX_CONFIG is used for the first task. SYS_WX_CONFIG may
160 # be set independently, to the value that should appear in
161 # build_options.py, if it is different to that. The default
162 # is to use the value of WX_CONFIG.
163
164 WXPORT = 'gtk2' # On Linux/Unix there are several ports of wxWidgets available.
165 # Setting this value lets you select which will be used for
166 # the wxPython build. Possibilites are 'gtk', 'gtk2' and
167 # 'x11'. Curently only gtk and gtk2 works.
168
169 BUILD_BASE = "build" # Directory to use for temporary build files.
170 # This name will be appended to if the WXPORT or
171 # the UNICODE flags are set to non-standard
172 # values. See below.
173
174
175 CONTRIBS_INC = "" # A dir to add as an -I flag when compiling the contribs
176
177
178 # Some MSW build settings
179
180 MONOLITHIC = 0 # The core wxWidgets lib can be built as either a
181 # single monolithic DLL or as a collection of DLLs.
182 # This flag controls which set of libs will be used
183 # on Windows. (For other platforms it is automatic
184 # via using wx-config.)
185
186 FINAL = 0 # Will use the release version of the wxWidgets libs on MSW.
187
188 HYBRID = 1 # Will use the "hybrid" version of the wxWidgets
189 # libs on MSW. A "hybrid" build is one that is
190 # basically a release build, but that also defines
191 # __WXDEBUG__ to activate the runtime checks and
192 # assertions in the library. When any of these is
193 # triggered it is turned into a Python exception so
194 # this is a very useful feature to have turned on.
195
196
197 # Version part of wxWidgets LIB/DLL names
198 WXDLLVER = '%d%d' % (VER_MAJOR, VER_MINOR)
199
200 WXPY_SRC = '.' # Assume we're in the source tree already, but allow the
201 # user to change it, particularly for extension building.
202
203 ARCH = '' # If this is set, add an -arch XXX flag to cflags
204 # Only tested (and presumably, needed) for OS X universal
205 # binary builds created using lipo.
206
207
208 #----------------------------------------------------------------------
209
210 def msg(text):
211 if hasattr(sys, 'setup_is_main') and sys.setup_is_main:
212 print text
213
214
215 def opj(*args):
216 path = os.path.join(*args)
217 return os.path.normpath(path)
218
219
220 def libFlag():
221 if FINAL:
222 rv = ''
223 elif HYBRID:
224 rv = 'h'
225 else:
226 rv = 'd'
227 if UNICODE:
228 rv = 'u' + rv
229 return rv
230
231
232 #----------------------------------------------------------------------
233 # Some other globals
234 #----------------------------------------------------------------------
235
236 PKGDIR = 'wx'
237 wxpExtensions = []
238 DATA_FILES = []
239 CLEANUP = []
240
241 force = '--force' in sys.argv or '-f' in sys.argv
242 debug = '--debug' in sys.argv or '-g' in sys.argv
243 cleaning = 'clean' in sys.argv
244
245
246 # change the PORT default for wxMac
247 if sys.platform[:6] == "darwin":
248 WXPORT = 'mac'
249
250 # and do the same for wxMSW, just for consistency
251 if os.name == 'nt':
252 WXPORT = 'msw'
253
254 WXPYTHON_TYPE_TABLE = '_wxPython_table'
255
256 #----------------------------------------------------------------------
257 # Check for build flags on the command line
258 #----------------------------------------------------------------------
259
260 # Boolean (int) flags
261 for flag in [ 'BUILD_ACTIVEX', 'BUILD_DLLWIDGET',
262 'BUILD_GIZMOS', 'BUILD_GLCANVAS',
263 'BUILD_OGL', 'BUILD_STC',
264 'CORE_ONLY', 'PREP_ONLY', 'USE_SWIG', 'UNICODE',
265 'UNDEF_NDEBUG', 'NO_SCRIPTS', 'NO_HEADERS', 'BUILD_RENAMERS',
266 'FULL_DOCS', 'INSTALL_MULTIVERSION', 'EP_ADD_OPTS', 'EP_FULL_VER',
267 'MONOLITHIC', 'FINAL', 'HYBRID', ]:
268 for x in range(len(sys.argv)):
269 if sys.argv[x].find(flag) == 0:
270 pos = sys.argv[x].find('=') + 1
271 if pos > 0:
272 vars()[flag] = eval(sys.argv[x][pos:])
273 sys.argv[x] = ''
274
275 # String options
276 for option in ['WX_CONFIG', 'SYS_WX_CONFIG', 'WXDLLVER', 'BUILD_BASE',
277 'WXPORT', 'SWIG', 'CONTRIBS_INC', 'WXPY_SRC', 'FLAVOUR',
278 'VER_FLAGS', 'ARCH',
279 ]:
280 for x in range(len(sys.argv)):
281 if sys.argv[x].find(option) == 0:
282 pos = sys.argv[x].find('=') + 1
283 if pos > 0:
284 vars()[option] = sys.argv[x][pos:]
285 sys.argv[x] = ''
286
287 sys.argv = filter(None, sys.argv)
288
289
290 #----------------------------------------------------------------------
291 # some helper functions
292 #----------------------------------------------------------------------
293
294 def Verify_WX_CONFIG():
295 """ Called below for the builds that need wx-config, if WX_CONFIG
296 is not set then determines the flags needed based on build
297 options and searches for wx-config on the PATH.
298 """
299 # if WX_CONFIG hasn't been set to an explicit value then construct one.
300 global WX_CONFIG
301 if WX_CONFIG is None:
302 WX_CONFIG='wx-config'
303 port = WXPORT
304 if port == "x11":
305 port = "x11univ"
306 flags = ' --toolkit=%s' % port
307 flags += ' --unicode=%s' % (UNICODE and 'yes' or 'no')
308 flags += ' --version=%s.%s' % (VER_MAJOR, VER_MINOR)
309
310 searchpath = os.environ["PATH"]
311 for p in searchpath.split(':'):
312 fp = os.path.join(p, 'wx-config')
313 if os.path.exists(fp) and os.access(fp, os.X_OK):
314 # success
315 msg("Found wx-config: " + fp)
316 msg(" Using flags: " + flags)
317 WX_CONFIG = fp + flags
318 if hasattr(sys, 'setup_is_main') and not sys.setup_is_main:
319 WX_CONFIG += " 2>/dev/null "
320 break
321 else:
322 msg("ERROR: WX_CONFIG not specified and wx-config not found on the $PATH")
323 # should we exit?
324
325 # TODO: execute WX_CONFIG --list and verify a matching config is found
326
327
328 def run_swig(files, dir, gendir, package, USE_SWIG, force, swig_args,
329 swig_deps=[], add_under=False):
330 """Run SWIG the way I want it done"""
331
332 if USE_SWIG and not os.path.exists(os.path.join(dir, gendir)):
333 os.mkdir(os.path.join(dir, gendir))
334
335 sources = []
336
337 if add_under: pre = '_'
338 else: pre = ''
339
340 for file in files:
341 basefile = os.path.splitext(file)[0]
342 i_file = os.path.join(dir, file)
343 py_file = os.path.join(dir, gendir, pre+basefile+'.py')
344 cpp_file = os.path.join(dir, gendir, pre+basefile+'_wrap.cpp')
345
346 if add_under:
347 interface = ['-interface', '_'+basefile+'_']
348 else:
349 interface = []
350
351 sources.append(cpp_file)
352
353 if not cleaning and USE_SWIG:
354 for dep in swig_deps:
355 # this may fail for external builds, but it's not
356 # a fatal error, so keep going.
357 try:
358 if newer(dep, py_file) or newer(dep, cpp_file):
359 force = 1
360 break
361 except:
362 pass
363
364 if force or newer(i_file, py_file) or newer(i_file, cpp_file):
365 ## we need forward slashes here, even on win32
366 #cpp_file = opj(cpp_file) #'/'.join(cpp_file.split('\\'))
367 #i_file = opj(i_file) #'/'.join(i_file.split('\\'))
368
369 if BUILD_RENAMERS:
370 xmltemp = tempfile.mktemp('.xml')
371
372 # First run swig to produce the XML file, adding
373 # an extra -D that prevents the old rename
374 # directives from being used
375 cmd = [ swig_cmd ] + swig_args + \
376 [ '-DBUILDING_RENAMERS', '-xmlout', xmltemp ] + \
377 ['-I'+dir, '-o', cpp_file, i_file]
378 msg(' '.join(cmd))
379 spawn(cmd)
380
381 # Next run build_renamers to process the XML
382 myRenamer = BuildRenamers()
383 myRenamer.run(dir, pre+basefile, xmltemp)
384 os.remove(xmltemp)
385
386 # Then run swig for real
387 cmd = [ swig_cmd ] + swig_args + interface + \
388 ['-I'+dir, '-o', cpp_file, i_file]
389 msg(' '.join(cmd))
390 spawn(cmd)
391
392
393 # copy the generated python file to the package directory
394 copy_file(py_file, package, update=not force, verbose=0)
395 CLEANUP.append(opj(package, os.path.basename(py_file)))
396
397 return sources
398
399
400 def swig_version():
401 # It may come on either stdout or stderr, depending on the
402 # version, so read both.
403 i, o, e = os.popen3(SWIG + ' -version', 't')
404 stext = o.read() + e.read()
405 import re
406 match = re.search(r'[0-9]+\.[0-9]+\.[0-9]+$', stext, re.MULTILINE)
407 if not match:
408 raise 'NotFound'
409 SVER = match.group(0)
410 return SVER
411
412
413 # Specializations of some distutils command classes
414 class wx_smart_install_data(distutils.command.install_data.install_data):
415 """need to change self.install_dir to the actual library dir"""
416 def run(self):
417 install_cmd = self.get_finalized_command('install')
418 self.install_dir = getattr(install_cmd, 'install_lib')
419 return distutils.command.install_data.install_data.run(self)
420
421
422 class wx_extra_clean(distutils.command.clean.clean):
423 """
424 Also cleans stuff that this setup.py copies itself. If the
425 --all flag was used also searches for .pyc, .pyd, .so files
426 """
427 def run(self):
428 from distutils import log
429 from distutils.filelist import FileList
430 global CLEANUP
431
432 distutils.command.clean.clean.run(self)
433
434 if self.all:
435 fl = FileList()
436 fl.include_pattern("*.pyc", 0)
437 fl.include_pattern("*.pyd", 0)
438 fl.include_pattern("*.so", 0)
439 CLEANUP += fl.files
440
441 for f in CLEANUP:
442 if os.path.isdir(f):
443 try:
444 if not self.dry_run and os.path.exists(f):
445 os.rmdir(f)
446 log.info("removing '%s'", f)
447 except IOError:
448 log.warning("unable to remove '%s'", f)
449
450 else:
451 try:
452 if not self.dry_run and os.path.exists(f):
453 os.remove(f)
454 log.info("removing '%s'", f)
455 except IOError:
456 log.warning("unable to remove '%s'", f)
457
458
459
460 class wx_install(distutils.command.install.install):
461 """
462 Turns off install_path_file
463 """
464 def initialize_options(self):
465 distutils.command.install.install.initialize_options(self)
466 self.install_path_file = 0
467
468
469 class wx_install_headers(distutils.command.install_headers.install_headers):
470 """
471 Install the header files to the WXPREFIX, with an extra dir per
472 filename too
473 """
474 def initialize_options(self):
475 self.root = None
476 distutils.command.install_headers.install_headers.initialize_options(self)
477
478 def finalize_options(self):
479 self.set_undefined_options('install', ('root', 'root'))
480 distutils.command.install_headers.install_headers.finalize_options(self)
481
482 def run(self):
483 if os.name == 'nt':
484 return
485 headers = self.distribution.headers
486 if not headers:
487 return
488
489 root = self.root
490 #print "WXPREFIX is %s, root is %s" % (WXPREFIX, root)
491 # hack for universal builds, which append i386/ppc
492 # to the root
493 if root is None or WXPREFIX.startswith(os.path.dirname(root)):
494 root = ''
495 for header, location in headers:
496 install_dir = os.path.normpath(root +
497 WXPREFIX +
498 '/include/wx-%d.%d/wx' % (VER_MAJOR, VER_MINOR) +
499 location)
500 self.mkpath(install_dir)
501 (out, _) = self.copy_file(header, install_dir)
502 self.outfiles.append(out)
503
504
505
506
507 def build_locale_dir(destdir, verbose=1):
508 """Build a locale dir under the wxPython package for MSW"""
509 moFiles = glob.glob(opj(WXDIR, 'locale', '*.mo'))
510 for src in moFiles:
511 lang = os.path.splitext(os.path.basename(src))[0]
512 #dest = opj(destdir, lang)
513 dest = opj(destdir, lang, 'LC_MESSAGES')
514 mkpath(dest, verbose=verbose)
515 copy_file(src, opj(dest, 'wxstd.mo'), update=1, verbose=verbose)
516 CLEANUP.append(opj(dest, 'wxstd.mo'))
517 CLEANUP.append(dest)
518
519
520 def build_locale_list(srcdir):
521 # get a list of all files under the srcdir, to be used for install_data
522 def walk_helper(lst, dirname, files):
523 for f in files:
524 filename = opj(dirname, f)
525 if not os.path.isdir(filename):
526 lst.append( (dirname, [filename]) )
527 file_list = []
528 os.path.walk(srcdir, walk_helper, file_list)
529 return file_list
530
531
532 def find_data_files(srcdir, *wildcards):
533 # get a list of all files under the srcdir matching wildcards,
534 # returned in a format to be used for install_data
535
536 def walk_helper(arg, dirname, files):
537 names = []
538 lst, wildcards = arg
539 for wc in wildcards:
540 for f in files:
541 filename = opj(dirname, f)
542 if fnmatch.fnmatch(filename, wc) and not os.path.isdir(filename):
543 names.append(filename)
544 if names:
545 lst.append( (dirname, names ) )
546
547 file_list = []
548 os.path.walk(srcdir, walk_helper, (file_list, wildcards))
549 return file_list
550
551
552 def makeLibName(name):
553 if os.name == 'posix':
554 libname = '%s_%s-%s' % (WXBASENAME, name, WXRELEASE)
555 elif name:
556 libname = 'wxmsw%s%s_%s' % (WXDLLVER, libFlag(), name)
557 else:
558 libname = 'wxmsw%s%s' % (WXDLLVER, libFlag())
559 return [libname]
560
561
562 def findLib(name, libdirs):
563 name = makeLibName(name)[0]
564 if os.name == 'posix':
565 dirs = libdirs + ['/usr/lib', '/usr/local/lib']
566 name = 'lib'+name
567 else:
568 dirs = libdirs[:]
569 for d in dirs:
570 p = os.path.join(d, name)
571 if glob.glob(p+'*') != []:
572 return True
573 return False
574
575
576 def adjustCFLAGS(cflags, defines, includes):
577 '''Extract the raw -I, -D, and -U flags and put them into
578 defines and includes as needed.'''
579 newCFLAGS = []
580 for flag in cflags:
581 if flag[:2] == '-I':
582 includes.append(flag[2:])
583 elif flag[:2] == '-D':
584 flag = flag[2:]
585 if flag.find('=') == -1:
586 defines.append( (flag, None) )
587 else:
588 defines.append( tuple(flag.split('=')) )
589 elif flag[:2] == '-U':
590 defines.append( (flag[2:], ) )
591 else:
592 newCFLAGS.append(flag)
593 return newCFLAGS
594
595
596
597 def adjustLFLAGS(lflags, libdirs, libs):
598 '''Extract the -L and -l flags and put them in libdirs and libs as needed'''
599 newLFLAGS = []
600 for flag in lflags:
601 if flag[:2] == '-L':
602 libdirs.append(flag[2:])
603 elif flag[:2] == '-l':
604 libs.append(flag[2:])
605 else:
606 newLFLAGS.append(flag)
607
608 # remove any flags for universal binaries, we'll get those from
609 # distutils instead
610 return newLFLAGS #[flag for flag in newLFLAGS
611 # if flag not in ['-isysroot', '-arch', 'ppc', 'i386'] and
612 # not flag.startswith('/Developer') ]
613
614
615
616 def getExtraPath(shortVer=True, addOpts=False):
617 """Get the dirname that wxPython will be installed under."""
618
619 if shortVer:
620 # short version, just Major.Minor
621 ep = "wx-%d.%d" % (VER_MAJOR, VER_MINOR)
622
623 # plus release if minor is odd
624 if VER_MINOR % 2 == 1:
625 ep += ".%d" % VER_RELEASE
626
627 ##ep = "wx-%d.%d.%d" % (VER_MAJOR, VER_MINOR, VER_RELEASE)
628
629 else:
630 # long version, full version
631 ep = "wx-%d.%d.%d.%d" % (VER_MAJOR, VER_MINOR, VER_RELEASE, VER_SUBREL)
632
633 if addOpts:
634 port = WXPORT
635 if port == "msw": port = "win32"
636 ep += "-%s-%s" % (WXPORT, (UNICODE and 'unicode' or 'ansi'))
637
638 if FLAVOUR:
639 ep += "-" + FLAVOUR
640
641 return ep
642
643 #----------------------------------------------------------------------
644 # sanity checks
645
646 if CORE_ONLY:
647 BUILD_GLCANVAS = 0
648 BUILD_OGL = 0
649 BUILD_STC = 0
650 BUILD_GIZMOS = 0
651 BUILD_DLLWIDGET = 0
652 BUILD_ACTIVEX = 0
653
654 if debug:
655 FINAL = 0
656 HYBRID = 0
657
658 if FINAL:
659 HYBRID = 0
660
661 if UNICODE and WXPORT not in ['msw', 'gtk2', 'mac']:
662 raise SystemExit, "UNICODE mode not currently supported on this WXPORT: "+WXPORT
663
664
665 if CONTRIBS_INC:
666 CONTRIBS_INC = [ CONTRIBS_INC ]
667 else:
668 CONTRIBS_INC = []
669
670
671 #----------------------------------------------------------------------
672 # Setup some platform specific stuff
673 #----------------------------------------------------------------------
674
675 if os.name == 'nt':
676 # Set compile flags and such for MSVC. These values are derived
677 # from the wxWidgets makefiles for MSVC, other compilers settings
678 # will probably vary...
679 if os.environ.has_key('WXWIN'):
680 WXDIR = os.environ['WXWIN']
681 else:
682 msg("WARNING: WXWIN not set in environment.")
683 WXDIR = '..' # assumes in CVS tree
684 WXPLAT = '__WXMSW__'
685 GENDIR = 'msw'
686
687 includes = ['include', 'src',
688 opj(WXDIR, 'lib', 'vc_dll', 'msw' + libFlag()),
689 opj(WXDIR, 'include'),
690 opj(WXDIR, 'contrib', 'include'),
691 ]
692
693 defines = [ ('WIN32', None),
694 ('_WINDOWS', None),
695
696 (WXPLAT, None),
697 ('WXUSINGDLL', '1'),
698
699 ('SWIG_TYPE_TABLE', WXPYTHON_TYPE_TABLE),
700 ('SWIG_PYTHON_OUTPUT_TUPLE', None),
701 ('WXP_USE_THREAD', '1'),
702 ]
703
704 if UNDEF_NDEBUG:
705 defines.append( ('NDEBUG',) ) # using a 1-tuple makes it do an undef
706
707 if HYBRID:
708 defines.append( ('__NO_VC_CRTDBG__', None) )
709
710 if not FINAL or HYBRID:
711 defines.append( ('__WXDEBUG__', None) )
712
713 if UNICODE:
714 defines.append( ('wxUSE_UNICODE', 1) )
715
716 libdirs = [ opj(WXDIR, 'lib', 'vc_dll') ]
717 if MONOLITHIC:
718 libs = makeLibName('')
719 else:
720 libs = [ 'wxbase' + WXDLLVER + libFlag(),
721 'wxbase' + WXDLLVER + libFlag() + '_net',
722 'wxbase' + WXDLLVER + libFlag() + '_xml',
723 makeLibName('core')[0],
724 makeLibName('adv')[0],
725 makeLibName('html')[0],
726 ]
727
728 libs = libs + ['kernel32', 'user32', 'gdi32', 'comdlg32',
729 'winspool', 'winmm', 'shell32', 'oldnames', 'comctl32',
730 'odbc32', 'ole32', 'oleaut32', 'uuid', 'rpcrt4',
731 'advapi32', 'wsock32']
732
733
734 cflags = [ '/Gy',
735 # '/GX-' # workaround for internal compiler error in MSVC on some machines
736 ]
737 lflags = None
738
739 # Other MSVC flags...
740 # Too bad I don't remember why I was playing with these, can they be removed?
741 if FINAL:
742 pass #cflags = cflags + ['/O1']
743 elif HYBRID :
744 pass #cflags = cflags + ['/Ox']
745 else:
746 pass # cflags = cflags + ['/Od', '/Z7']
747 # lflags = ['/DEBUG', ]
748
749
750
751 #----------------------------------------------------------------------
752
753 elif os.name == 'posix':
754 WXDIR = '..'
755 includes = ['include', 'src']
756 defines = [('SWIG_TYPE_TABLE', WXPYTHON_TYPE_TABLE),
757 ('SWIG_PYTHON_OUTPUT_TUPLE', None),
758 ('WXP_USE_THREAD', '1'),
759 ]
760 if UNDEF_NDEBUG:
761 defines.append( ('NDEBUG',) ) # using a 1-tuple makes it do an undef
762
763 Verify_WX_CONFIG()
764
765 libdirs = []
766 libs = []
767
768 # If you get unresolved symbol errors on Solaris and are using gcc, then
769 # uncomment this block to add the right flags to the link step and build
770 # again.
771 ## if os.uname()[0] == 'SunOS':
772 ## import commands
773 ## libs.append('gcc')
774 ## libdirs.append(commands.getoutput("gcc -print-search-dirs | grep '^install' | awk '{print $2}'")[:-1])
775
776 cflags = os.popen(WX_CONFIG + ' --cxxflags', 'r').read()[:-1]
777 cflags = cflags.split()
778 if debug:
779 cflags.append('-g')
780 cflags.append('-O0')
781 else:
782 cflags.append('-O3')
783
784 lflags = os.popen(WX_CONFIG + ' --libs', 'r').read()[:-1]
785 MONOLITHIC = (lflags.find("_xrc") == -1)
786 lflags = lflags.split()
787
788 WXBASENAME = os.popen(WX_CONFIG + ' --basename').read()[:-1]
789 WXRELEASE = os.popen(WX_CONFIG + ' --release').read()[:-1]
790 WXPREFIX = os.popen(WX_CONFIG + ' --prefix').read()[:-1]
791
792
793 if sys.platform[:6] == "darwin" and WXPORT == 'mac':
794 # Flags and such for a Darwin (Max OS X) build of Python
795 WXPLAT = '__WXMAC__'
796 GENDIR = 'mac'
797 libs = ['stdc++']
798 NO_SCRIPTS = 1
799 if not ARCH == "":
800 cflags.append("-arch")
801 cflags.append(ARCH)
802 lflags.append("-arch")
803 lflags.append(ARCH)
804 #if ARCH == "ppc":
805 # cflags.append("-isysroot")
806 # cflags.append("/Developer/SDKs/MacOSX10.3.9.sdk")
807
808
809 else:
810 # Set flags for other Unix type platforms
811 GENDIR = WXPORT
812
813 if WXPORT == 'gtk':
814 WXPLAT = '__WXGTK__'
815 portcfg = os.popen('gtk-config --cflags', 'r').read()[:-1]
816 elif WXPORT == 'gtk2':
817 WXPLAT = '__WXGTK__'
818 GENDIR = 'gtk' # no code differences so use the same generated sources
819 portcfg = os.popen('pkg-config gtk+-2.0 --cflags', 'r').read()[:-1]
820 BUILD_BASE = BUILD_BASE + '-' + WXPORT
821 elif WXPORT == 'x11':
822 WXPLAT = '__WXX11__'
823 portcfg = ''
824 BUILD_BASE = BUILD_BASE + '-' + WXPORT
825 else:
826 raise SystemExit, "Unknown WXPORT value: " + WXPORT
827
828 cflags += portcfg.split()
829
830 # Some distros (e.g. Mandrake) put libGLU in /usr/X11R6/lib, but
831 # wx-config doesn't output that for some reason. For now, just
832 # add it unconditionally but we should really check if the lib is
833 # really found there or wx-config should be fixed.
834 libdirs.append("/usr/X11R6/lib")
835
836
837 # Move the various -I, -D, etc. flags we got from the *config scripts
838 # into the distutils lists.
839 cflags = adjustCFLAGS(cflags, defines, includes)
840 lflags = adjustLFLAGS(lflags, libdirs, libs)
841
842
843 #----------------------------------------------------------------------
844 else:
845 raise 'Sorry, platform not supported...'
846
847
848 #----------------------------------------------------------------------
849 # build options file
850 #----------------------------------------------------------------------
851
852 if SYS_WX_CONFIG is None:
853 SYS_WX_CONFIG = WX_CONFIG
854
855 build_options_template = """
856 UNICODE=%d
857 UNDEF_NDEBUG=%d
858 INSTALL_MULTIVERSION=%d
859 FLAVOUR="%s"
860 EP_ADD_OPTS=%d
861 EP_FULL_VER=%d
862 WX_CONFIG="%s"
863 WXPORT="%s"
864 MONOLITHIC=%d
865 FINAL=%d
866 HYBRID=%d
867 """ % (UNICODE, UNDEF_NDEBUG, INSTALL_MULTIVERSION, FLAVOUR, EP_ADD_OPTS,
868 EP_FULL_VER, SYS_WX_CONFIG, WXPORT, MONOLITHIC, FINAL, HYBRID)
869
870 try:
871 from build_options import *
872 except:
873 build_options_file = os.path.join(os.path.dirname(__file__), "build_options.py")
874 if not os.path.exists(build_options_file):
875 try:
876 myfile = open(build_options_file, "w")
877 myfile.write(build_options_template)
878 myfile.close()
879 except:
880 print "WARNING: Unable to create build_options.py."
881
882
883 #----------------------------------------------------------------------
884 # post platform setup checks and tweaks, create the full version string
885 #----------------------------------------------------------------------
886
887 if UNICODE:
888 BUILD_BASE = BUILD_BASE + '.unicode'
889
890 if os.path.exists('DAILY_BUILD'):
891 VER_FLAGS += '.' + open('DAILY_BUILD').read().strip()
892
893 VERSION = "%s.%s.%s.%s%s" % (VER_MAJOR, VER_MINOR, VER_RELEASE,
894 VER_SUBREL, VER_FLAGS)
895
896
897 #----------------------------------------------------------------------
898 # SWIG defaults
899 #----------------------------------------------------------------------
900
901 # *.i files could live in the wxWidgets/wxPython/src dir, or in
902 # a subdirectory of the devel package. Let's specify both
903 # dirs as includes so we don't have to guess which is correct.
904
905 wxfilesdir = ""
906 i_subdir = opj("include", getExtraPath(), "wx", "wxPython", "i_files")
907 if os.name != "nt":
908 wxfilesdir = opj(WXPREFIX, i_subdir)
909 else:
910 wxfilesdir = opj(WXPY_SRC, i_subdir)
911
912 i_files_includes = [ '-I' + opj(WXPY_SRC, 'src'),
913 '-I' + wxfilesdir ]
914
915 swig_cmd = SWIG
916 swig_force = force
917 swig_args = ['-c++',
918 #'-Wall',
919 '-python',
920 '-new_repr',
921 '-modern',
922 '-D'+WXPLAT,
923 ] + i_files_includes
924
925 if USE_SWIG:
926 SVER = swig_version()
927 if int(SVER[-2:]) >= 29:
928 swig_args += [ '-fastdispatch',
929 '-fvirtual',
930 '-fastinit',
931 '-fastunpack',
932 #'-outputtuple', Currently setting this with a -D define above
933 ]
934
935 if UNICODE:
936 swig_args.append('-DwxUSE_UNICODE')
937
938 if FULL_DOCS:
939 swig_args.append('-D_DO_FULL_DOCS')
940
941
942 swig_deps = [ opj(WXPY_SRC, 'src/my_typemaps.i'),
943 opj(WXPY_SRC, 'src/pyfragments.swg'),
944 ]
945
946 depends = [ #'include/wx/wxPython/wxPython.h',
947 #'include/wx/wxPython/wxPython_int.h',
948 #'src/pyclasses.h',
949 ]
950
951 #----------------------------------------------------------------------
952
953 ####################################
954 # BuildRenamers
955 ####################################
956
957 import pprint, shutil
958 try:
959 import libxml2
960 FOUND_LIBXML2 = True
961 except ImportError:
962 FOUND_LIBXML2 = False
963
964 #---------------------------------------------------------------------------
965
966 renamerTemplateStart = """\
967 // A bunch of %rename directives generated by BuildRenamers in config.py
968 // in order to remove the wx prefix from all global scope names.
969
970 #ifndef BUILDING_RENAMERS
971
972 """
973
974 renamerTemplateEnd = """
975 #endif
976 """
977
978 wxPythonTemplateStart = """\
979 ## This file reverse renames symbols in the wx package to give
980 ## them their wx prefix again, for backwards compatibility.
981 ##
982 ## Generated by BuildRenamers in config.py
983
984 # This silly stuff here is so the wxPython.wx module doesn't conflict
985 # with the wx package. We need to import modules from the wx package
986 # here, then we'll put the wxPython.wx entry back in sys.modules.
987 import sys
988 _wx = None
989 if sys.modules.has_key('wxPython.wx'):
990 _wx = sys.modules['wxPython.wx']
991 del sys.modules['wxPython.wx']
992
993 import wx.%s
994
995 sys.modules['wxPython.wx'] = _wx
996 del sys, _wx
997
998
999 # Now assign all the reverse-renamed names:
1000 """
1001
1002 wxPythonTemplateEnd = """
1003
1004 """
1005
1006
1007
1008 #---------------------------------------------------------------------------
1009 class BuildRenamers:
1010 def run(self, destdir, modname, xmlfile, wxPythonDir="wxPython"):
1011
1012 assert FOUND_LIBXML2, "The libxml2 module is required to use the BuildRenamers functionality."
1013
1014 if not os.path.exists(wxPythonDir):
1015 os.mkdir(wxPythonDir)
1016
1017 swigDest = os.path.join(destdir, "_"+modname+"_rename.i")
1018 pyDest = os.path.join(wxPythonDir, modname + '.py')
1019
1020 swigDestTemp = tempfile.mktemp('.tmp')
1021 swigFile = open(swigDestTemp, "w")
1022 swigFile.write(renamerTemplateStart)
1023
1024 pyDestTemp = tempfile.mktemp('.tmp')
1025 pyFile = open(pyDestTemp, "w")
1026 pyFile.write(wxPythonTemplateStart % modname)
1027
1028 print "Parsing XML and building renamers..."
1029 self.processXML(xmlfile, modname, swigFile, pyFile)
1030
1031 self.checkOtherNames(pyFile, modname,
1032 os.path.join(destdir, '_'+modname+'_reverse.txt'))
1033 pyFile.write(wxPythonTemplateEnd)
1034 pyFile.close()
1035
1036 swigFile.write(renamerTemplateEnd)
1037 swigFile.close()
1038
1039 # Compare the files just created with the existing one and
1040 # blow away the old one if they are different.
1041 for dest, temp in [(swigDest, swigDestTemp),
1042 (pyDest, pyDestTemp)]:
1043 # NOTE: we don't use shutil.move() because it was introduced
1044 # in Python 2.3. Eventually we can switch to it when people
1045 # stop building using 2.2.
1046 if not os.path.exists(dest):
1047 shutil.copyfile(temp, dest)
1048 elif open(dest).read() != open(temp).read():
1049 os.unlink(dest)
1050 shutil.copyfile(temp, dest)
1051 else:
1052 print dest + " not changed."
1053 os.unlink(temp)
1054
1055 #---------------------------------------------------------------------------
1056
1057
1058 def GetAttr(self, node, name):
1059 path = "./attributelist/attribute[@name='%s']/@value" % name
1060 n = node.xpathEval2(path)
1061 if len(n):
1062 return n[0].content
1063 else:
1064 return None
1065
1066
1067 def processXML(self, xmlfile, modname, swigFile, pyFile):
1068
1069 topnode = libxml2.parseFile(xmlfile).children
1070
1071 # remove any import nodes as we don't need to do renamers for symbols found therein
1072 imports = topnode.xpathEval2("*/import")
1073 for n in imports:
1074 n.unlinkNode()
1075 n.freeNode()
1076
1077 # do a depth first iteration over what's left
1078 for node in topnode:
1079 doRename = False
1080 addWX = False
1081 revOnly = False
1082
1083
1084 if node.name == "class":
1085 lastClassName = name = self.GetAttr(node, "name")
1086 lastClassSymName = sym_name = self.GetAttr(node, "sym_name")
1087 doRename = True
1088 if sym_name != name:
1089 name = sym_name
1090 addWX = True
1091
1092 # renamed constructors
1093 elif node.name == "constructor":
1094 name = self.GetAttr(node, "name")
1095 sym_name = self.GetAttr(node, "sym_name")
1096 if sym_name != name:
1097 name = sym_name
1098 addWX = True
1099 doRename = True
1100
1101 # only enumitems at the top level
1102 elif node.name == "enumitem" and node.parent.parent.name == "include":
1103 name = self.GetAttr(node, "name")
1104 sym_name = self.GetAttr(node, "sym_name")
1105 doRename = True
1106
1107
1108 elif node.name in ["cdecl", "constant"]:
1109 name = self.GetAttr(node, "name")
1110 sym_name = self.GetAttr(node, "sym_name")
1111 toplevel = node.parent.name == "include"
1112
1113 # top-level functions
1114 if toplevel and self.GetAttr(node, "view") == "globalfunctionHandler":
1115 doRename = True
1116
1117 # top-level global vars
1118 elif toplevel and self.GetAttr(node, "feature_immutable") == "1":
1119 doRename = True
1120
1121 # static methods
1122 elif self.GetAttr(node, "view") == "staticmemberfunctionHandler":
1123 name = lastClassName + '_' + name
1124 sym_name = lastClassSymName + '_' + sym_name
1125 # only output the reverse renamer in this case
1126 doRename = revOnly = True
1127
1128 if doRename and name != sym_name:
1129 name = sym_name
1130 addWX = True
1131
1132
1133 if doRename and name:
1134 old = new = name
1135 if old.startswith('wx') and not old.startswith('wxEVT_'):
1136 # remove all wx prefixes except wxEVT_ and write a %rename directive for it
1137 new = old[2:]
1138 if not revOnly:
1139 swigFile.write("%%rename(%s) %35s;\n" % (new, old))
1140
1141 # Write assignments to import into the old wxPython namespace
1142 if addWX and not old.startswith('wx'):
1143 old = 'wx'+old
1144 pyFile.write("%s = wx.%s.%s\n" % (old, modname, new))
1145
1146
1147 #---------------------------------------------------------------------------
1148
1149 def checkOtherNames(self, pyFile, moduleName, filename):
1150 if os.path.exists(filename):
1151 prefixes = []
1152 for line in file(filename):
1153 if line.endswith('\n'):
1154 line = line[:-1]
1155 if line and not line.startswith('#'):
1156 if line.endswith('*'):
1157 prefixes.append(line[:-1])
1158 elif line.find('=') != -1:
1159 pyFile.write("%s\n" % line)
1160 else:
1161 wxname = 'wx' + line
1162 if line.startswith('wx') or line.startswith('WX') or line.startswith('EVT'):
1163 wxname = line
1164 pyFile.write("%s = wx.%s.%s\n" % (wxname, moduleName, line))
1165
1166 if prefixes:
1167 pyFile.write(
1168 "\n\nd = globals()\nfor k, v in wx.%s.__dict__.iteritems():"
1169 % moduleName)
1170 first = True
1171 for p in prefixes:
1172 if first:
1173 pyFile.write("\n if ")
1174 first = False
1175 else:
1176 pyFile.write("\n elif ")
1177 pyFile.write("k.startswith('%s'):\n d[k] = v" % p)
1178 pyFile.write("\ndel d, k, v\n\n")
1179
1180
1181 #---------------------------------------------------------------------------