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