]> git.saurik.com Git - wxWidgets.git/blob - build/tools/build-wxwidgets.py
Convert wxFSW_EVENT_{WARNING,ERROR} to string correctly.
[wxWidgets.git] / build / tools / build-wxwidgets.py
1 #!/usr/bin/env python
2
3 ###################################
4 # Author: Kevin Ollivier
5 # Licence: wxWindows licence
6 ###################################
7
8 import os
9 import re
10 import sys
11 import builder
12 import glob
13 import optparse
14 import platform
15 import shutil
16 import types
17 import subprocess
18
19 # builder object
20 wxBuilder = None
21
22 # other globals
23 scriptDir = None
24 wxRootDir = None
25 contribDir = None
26 options = None
27 configure_opts = None
28 exitWithException = True
29
30 verbose = False
31
32
33 def numCPUs():
34 """
35 Detects the number of CPUs on a system.
36 This approach is from detectCPUs here: http://www.artima.com/weblogs/viewpost.jsp?thread=230001
37 """
38 # Linux, Unix and MacOS:
39 if hasattr(os, "sysconf"):
40 if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
41 # Linux & Unix:
42 ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
43 if isinstance(ncpus, int) and ncpus > 0:
44 return ncpus
45 else: # OSX:
46 p = subprocess.Popen("sysctl -n hw.ncpu", shell=True, stdout=subprocess.PIPE)
47 return p.stdout.read()
48
49 # Windows:
50 if "NUMBER_OF_PROCESSORS" in os.environ:
51 ncpus = int(os.environ["NUMBER_OF_PROCESSORS"]);
52 if ncpus > 0:
53 return ncpus
54 return 1 # Default
55
56
57 def getXcodePath():
58 return getoutput("xcode-select -print-path")
59
60
61 def getVisCVersion():
62 text = getoutput("cl.exe")
63 if 'Version 15' in text:
64 return '90'
65 # TODO: Add more tests to get the other versions...
66 else:
67 return 'FIXME'
68
69
70 def exitIfError(code, msg):
71 if code != 0:
72 print(msg)
73 if exitWithException:
74 raise builder.BuildError(msg)
75 else:
76 sys.exit(1)
77
78
79 def getWxRelease(wxRoot=None):
80 if not wxRoot:
81 global wxRootDir
82 wxRoot = wxRootDir
83
84 configureText = open(os.path.join(wxRoot, "configure.in"), "r").read()
85 majorVersion = re.search("wx_major_version_number=(\d+)", configureText).group(1)
86 minorVersion = re.search("wx_minor_version_number=(\d+)", configureText).group(1)
87
88 versionText = "%s.%s" % (majorVersion, minorVersion)
89
90 if int(minorVersion) % 2:
91 releaseVersion = re.search("wx_release_number=(\d+)", configureText).group(1)
92 versionText += ".%s" % (releaseVersion)
93
94 return versionText
95
96
97 def getFrameworkName(options):
98 # the name of the framework is based on the wx port being built
99 name = "wxOSX"
100 if options.osx_cocoa:
101 name += "Cocoa"
102 else:
103 name += "Carbon"
104 return name
105
106
107 def getPrefixInFramework(options, wxRoot=None):
108 # the path inside the framework that is the wx --prefix
109 fwPrefix = os.path.join(
110 os.path.abspath(options.mac_framework_prefix),
111 "%s.framework/Versions/%s" % (getFrameworkName(options), getWxRelease(wxRoot)))
112 return fwPrefix
113
114
115 def macFixupInstallNames(destdir, prefix, buildDir=None):
116 # When an installdir is used then the install_names embedded in
117 # the dylibs are not correct. Reset the IDs and the dependencies
118 # to use just the prefix.
119 print("**** macFixupInstallNames(%s, %s, %s)" % (destdir, prefix, buildDir))
120 pwd = os.getcwd()
121 os.chdir(destdir+prefix+'/lib')
122 dylibs = glob.glob('*.dylib') # ('*[0-9].[0-9].[0-9].[0-9]*.dylib')
123 for lib in dylibs:
124 cmd = 'install_name_tool -id %s/lib/%s %s/lib/%s' % \
125 (prefix,lib, destdir+prefix,lib)
126 print(cmd)
127 run(cmd)
128 for dep in dylibs:
129 if buildDir is not None:
130 cmd = 'install_name_tool -change %s/lib/%s %s/lib/%s %s/lib/%s' % \
131 (buildDir,dep, prefix,dep, destdir+prefix,lib)
132 else:
133 cmd = 'install_name_tool -change %s/lib/%s %s/lib/%s %s/lib/%s' % \
134 (destdir+prefix,dep, prefix,dep, destdir+prefix,lib)
135 print(cmd)
136 run(cmd)
137 os.chdir(pwd)
138
139
140 def run(cmd):
141 global verbose
142 if verbose:
143 print("Running %s" % cmd)
144 return exitIfError(os.system(cmd), "Error running %s" % cmd)
145
146
147 def getoutput(cmd):
148 sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
149 output = None
150 output = sp.stdout.read()
151 if sys.version_info > (3,):
152 output = output.decode('utf-8') # TODO: is utf-8 okay here?
153 output = output.rstrip()
154 rval = sp.wait()
155 if rval:
156 # Failed!
157 print("Command '%s' failed with exit code %d." % (cmd, rval))
158 sys.exit(rval)
159 return output
160
161
162 def main(scriptName, args):
163 global scriptDir
164 global wxRootDir
165 global contribDir
166 global options
167 global configure_opts
168 global wxBuilder
169
170 scriptDir = os.path.dirname(os.path.abspath(scriptName))
171 wxRootDir = os.path.abspath(os.path.join(scriptDir, "..", ".."))
172
173 contribDir = os.path.join("contrib", "src")
174 installDir = None
175
176 VERSION = tuple([int(i) for i in getWxRelease().split('.')[:2]])
177
178 if sys.platform.startswith("win"):
179 contribDir = os.path.join(wxRootDir, "contrib", "build")
180
181 if sys.platform.startswith("win"):
182 toolkit = "msvc"
183 else:
184 toolkit = "autoconf"
185
186 defJobs = str(numCPUs())
187 defFwPrefix = '/Library/Frameworks'
188
189 option_dict = {
190 "clean" : (False, "Clean all files from the build directory"),
191 "debug" : (False, "Build the library in debug symbols"),
192 "builddir" : ("", "Directory where the build will be performed for autoconf builds."),
193 "prefix" : ("", "Configured prefix to use for autoconf builds. Defaults to installdir if set. Ignored for framework builds."),
194 "jobs" : (defJobs, "Number of jobs to run at one time in make. Default: %s" % defJobs),
195 "install" : (False, "Install the toolkit to the installdir directory, or the default dir."),
196 "installdir" : ("", "Directory where built wxWidgets will be installed"),
197 "mac_distdir" : (None, "If set on Mac, will create an installer package in the specified dir."),
198 "mac_universal_binary"
199 : ("", "Comma separated list of architectures to include in the Mac universal binary"),
200 "mac_framework" : (False, "Install the Mac build as a framework"),
201 "mac_framework_prefix"
202 : (defFwPrefix, "Prefix where the framework should be installed. Default: %s" % defFwPrefix),
203 "cairo" : (False, "Enable dynamicly loading the Cairo lib for wxGraphicsContext on MSW"),
204 "no_config" : (False, "Turn off configure step on autoconf builds"),
205 "config_only" : (False, "Only run the configure step and then exit"),
206 "rebake" : (False, "Regenerate Bakefile and autoconf files"),
207 "unicode" : (False, "Build the library with unicode support"),
208 "wxpython" : (False, "Build the wxWidgets library with all options needed by wxPython"),
209 "cocoa" : (False, "Build the old Mac Cooca port."),
210 "osx_cocoa" : (False, "Build the new Cocoa port"),
211 "shared" : (False, "Build wx as a dynamic library"),
212 "extra_make" : ("", "Extra args to pass on [n]make's command line."),
213 "features" : ("", "A comma-separated list of wxUSE_XYZ defines on Win, or a list of configure flags on unix."),
214 "verbose" : (False, "Print commands as they are run, (to aid with debugging this script)"),
215 }
216
217 parser = optparse.OptionParser(usage="usage: %prog [options]", version="%prog 1.0")
218
219 keys = option_dict.keys()
220 for opt in sorted(keys):
221 default = option_dict[opt][0]
222 action = "store"
223 if type(default) == bool:
224 action = "store_true"
225 parser.add_option("--" + opt, default=default, action=action, dest=opt,
226 help=option_dict[opt][1])
227
228 options, arguments = parser.parse_args(args=args)
229
230 global verbose
231 if options.verbose:
232 verbose = True
233
234 # compiler / build system specific args
235 buildDir = options.builddir
236 args = []
237 installDir = options.installdir
238 prefixDir = options.prefix
239
240 if toolkit == "autoconf":
241 if not buildDir:
242 buildDir = os.getcwd()
243 configure_opts = []
244 if options.features != "":
245 configure_opts.extend(options.features.split(" "))
246
247 if options.unicode:
248 configure_opts.append("--enable-unicode")
249
250 if options.debug:
251 configure_opts.append("--enable-debug")
252
253 if options.cocoa:
254 configure_opts.append("--with-old_cocoa")
255
256 if options.osx_cocoa:
257 configure_opts.append("--with-osx_cocoa")
258
259 wxpy_configure_opts = [
260 "--with-opengl",
261 "--enable-sound",
262 "--enable-graphics_ctx",
263 "--enable-mediactrl",
264 "--enable-display",
265 "--enable-geometry",
266 "--enable-debug_flag",
267 "--enable-optimise",
268 "--disable-debugreport",
269 "--enable-uiactionsim",
270 ]
271
272 if sys.platform.startswith("darwin"):
273 wxpy_configure_opts.append("--enable-monolithic")
274 else:
275 wxpy_configure_opts.append("--with-sdl")
276 wxpy_configure_opts.append("--with-gnomeprint")
277
278 # Try to use use lowest available SDK back to 10.5. Both Carbon and
279 # Cocoa builds require at least the 10.5 SDK now. We only add it to
280 # the wxpy options because this is a hard-requirement for wxPython,
281 # but other cases it is optional and is left up to the developer.
282 # TODO: there should be a command line option to set the SDK...
283 if sys.platform.startswith("darwin"):
284 xcodePath = getXcodePath()
285 sdks = [
286 xcodePath+"/SDKs/MacOSX10.5.sdk",
287 xcodePath+"/SDKs/MacOSX10.6.sdk",
288 xcodePath+"/SDKs/MacOSX10.7.sdk",
289 ]
290
291 # use the lowest available sdk
292 for sdk in sdks:
293 if os.path.exists(sdk):
294 wxpy_configure_opts.append(
295 "--with-macosx-sdk=%s" % sdk)
296 break
297
298 if not options.mac_framework:
299 if installDir and not prefixDir:
300 prefixDir = installDir
301 if prefixDir:
302 prefixDir = os.path.abspath(prefixDir)
303 configure_opts.append("--prefix=" + prefixDir)
304
305
306 if options.wxpython:
307 configure_opts.extend(wxpy_configure_opts)
308 if options.debug:
309 # wxPython likes adding these debug options too
310 configure_opts.append("--enable-debug_gdb")
311 configure_opts.append("--disable-optimise")
312 configure_opts.remove("--enable-optimise")
313
314
315 if options.rebake:
316 retval = run("make -f autogen.mk")
317 exitIfError(retval, "Error running autogen.mk")
318
319 if options.mac_framework:
320 # TODO: Should options.install be automatically turned on if the
321 # mac_framework flag is given?
322
323 # framework builds always need to be monolithic
324 if not "--enable-monolithic" in configure_opts:
325 configure_opts.append("--enable-monolithic")
326
327 # The --prefix given to configure will be the framework prefix
328 # plus the framework specific dir structure.
329 prefixDir = getPrefixInFramework(options)
330 configure_opts.append("--prefix=" + prefixDir)
331
332 # the framework build adds symlinks above the installDir + prefixDir folder
333 # so we need to wipe from the framework root instead of inside the prefixDir.
334 frameworkRootDir = os.path.abspath(os.path.join(installDir + prefixDir, "..", ".."))
335 if os.path.exists(frameworkRootDir):
336 if os.path.exists(frameworkRootDir):
337 shutil.rmtree(frameworkRootDir)
338
339 if options.mac_universal_binary:
340 if options.mac_universal_binary == 'default':
341 if options.osx_cocoa:
342 configure_opts.append("--enable-universal_binary=i386,x86_64")
343 else:
344 configure_opts.append("--enable-universal_binary")
345 else:
346 configure_opts.append("--enable-universal_binary=%s" % options.mac_universal_binary)
347
348
349 print("Configure options: " + repr(configure_opts))
350 wxBuilder = builder.AutoconfBuilder()
351 if not options.no_config and not options.clean:
352 olddir = os.getcwd()
353 if buildDir:
354 os.chdir(buildDir)
355 exitIfError(wxBuilder.configure(dir=wxRootDir, options=configure_opts),
356 "Error running configure")
357 os.chdir(olddir)
358
359 if options.config_only:
360 print("Exiting after configure")
361 return
362
363 elif toolkit in ["msvc", "msvcProject"]:
364 flags = {}
365 buildDir = os.path.abspath(os.path.join(scriptDir, "..", "msw"))
366
367 print("creating wx/msw/setup.h from setup0.h")
368 if options.unicode:
369 flags["wxUSE_UNICODE"] = "1"
370 if VERSION < (2,9):
371 flags["wxUSE_UNICODE_MSLU"] = "1"
372
373 if options.cairo:
374 if not os.environ.get("CAIRO_ROOT"):
375 print("WARNING: Expected CAIRO_ROOT set in the environment!")
376 flags["wxUSE_CAIRO"] = "1"
377
378 if options.wxpython:
379 flags["wxDIALOG_UNIT_COMPATIBILITY "] = "0"
380 flags["wxUSE_DEBUGREPORT"] = "0"
381 flags["wxUSE_DIALUP_MANAGER"] = "0"
382 flags["wxUSE_GRAPHICS_CONTEXT"] = "1"
383 flags["wxUSE_DISPLAY"] = "1"
384 flags["wxUSE_GLCANVAS"] = "1"
385 flags["wxUSE_POSTSCRIPT"] = "1"
386 flags["wxUSE_AFM_FOR_POSTSCRIPT"] = "0"
387 flags["wxUSE_DATEPICKCTRL_GENERIC"] = "1"
388
389 if VERSION < (2,9):
390 flags["wxUSE_DIB_FOR_BITMAP"] = "1"
391
392 if VERSION >= (2,9):
393 flags["wxUSE_UIACTIONSIMULATOR"] = "1"
394
395
396 mswIncludeDir = os.path.join(wxRootDir, "include", "wx", "msw")
397 setup0File = os.path.join(mswIncludeDir, "setup0.h")
398 setupText = open(setup0File, "rb").read()
399
400 for flag in flags:
401 setupText, subsMade = re.subn(flag + "\s+?\d", "%s %s" % (flag, flags[flag]), setupText)
402 if subsMade == 0:
403 print("Flag %s wasn't found in setup0.h!" % flag)
404 sys.exit(1)
405
406 setupFile = open(os.path.join(mswIncludeDir, "setup.h"), "wb")
407 setupFile.write(setupText)
408 setupFile.close()
409 args = []
410 if toolkit == "msvc":
411 print("setting build options...")
412 args.append("-f makefile.vc")
413 if options.unicode:
414 args.append("UNICODE=1")
415 if VERSION < (2,9):
416 args.append("MSLU=1")
417
418 if options.wxpython:
419 args.append("OFFICIAL_BUILD=1")
420 args.append("COMPILER_VERSION=%s" % getVisCVersion())
421 args.append("SHARED=1")
422 args.append("MONOLITHIC=0")
423 args.append("USE_OPENGL=1")
424 args.append("USE_GDIPLUS=1")
425
426 if not options.debug:
427 args.append("BUILD=release")
428 else:
429 args.append("BUILD=debug")
430
431 if options.shared:
432 args.append("SHARED=1")
433
434 if options.cairo:
435 args.append(
436 "CPPFLAGS=/I%s" %
437 os.path.join(os.environ.get("CAIRO_ROOT", ""), 'include\\cairo'))
438
439 wxBuilder = builder.MSVCBuilder()
440
441 if toolkit == "msvcProject":
442 args = []
443 if options.shared or options.wxpython:
444 args.append("wx_dll.dsw")
445 else:
446 args.append("wx.dsw")
447
448 # TODO:
449 wxBuilder = builder.MSVCProjectBuilder()
450
451
452 if not wxBuilder:
453 print("Builder not available for your specified platform/compiler.")
454 sys.exit(1)
455
456 if options.clean:
457 print("Performing cleanup.")
458 wxBuilder.clean(dir=buildDir, options=args)
459
460 sys.exit(0)
461
462 if options.extra_make:
463 args.append(options.extra_make)
464
465 if not sys.platform.startswith("win"):
466 args.append("--jobs=" + options.jobs)
467 exitIfError(wxBuilder.build(dir=buildDir, options=args), "Error building")
468
469 if options.install:
470 extra=None
471 if installDir:
472 extra = ['DESTDIR='+installDir]
473 wxBuilder.install(dir=buildDir, options=extra)
474
475 if options.install and options.mac_framework:
476
477 def renameLibrary(libname, frameworkname):
478 reallib = libname
479 links = []
480 while os.path.islink(reallib):
481 links.append(reallib)
482 reallib = "lib/" + os.readlink(reallib)
483
484 #print("reallib is %s" % reallib)
485 run("mv -f %s lib/%s.dylib" % (reallib, frameworkname))
486
487 for link in links:
488 run("ln -s -f %s.dylib %s" % (frameworkname, link))
489
490 frameworkRootDir = prefixDir
491 if installDir:
492 print("installDir = %s" % installDir)
493 frameworkRootDir = installDir + prefixDir
494 os.chdir(frameworkRootDir)
495 build_string = ""
496 if options.debug:
497 build_string = "d"
498
499 fwname = getFrameworkName(options)
500 version = getoutput("bin/wx-config --release")
501 version_full = getoutput("bin/wx-config --version")
502 basename = getoutput("bin/wx-config --basename")
503 configname = getoutput("bin/wx-config --selected-config")
504
505 os.makedirs("Resources")
506 wxplist = dict(
507 CFBundleDevelopmentRegion="English",
508 CFBundleIdentifier='org.wxwidgets.wxosxcocoa',
509 CFBundleName=fwname,
510 CFBundleVersion=version_full,
511 CFBundleExecutable=fwname,
512 CFBundleGetInfoString="%s %s" % (fwname, version_full),
513 CFBundlePackageType="FMWK",
514 CFBundleSignature="WXCO",
515 CFBundleShortVersionString=version_full,
516 CFBundleInfoDictionaryVersion="6.0",
517 )
518
519 import plistlib
520 plistlib.writePlist(wxplist, os.path.join(frameworkRootDir, "Resources", "Info.plist"))
521
522 # we make wx the "actual" library file and link to it from libwhatever.dylib
523 # so that things can link to wx and survive minor version changes
524 renameLibrary("lib/lib%s-%s.dylib" % (basename, version), fwname)
525 run("ln -s -f lib/%s.dylib %s" % (fwname, fwname))
526
527 run("ln -s -f include Headers")
528
529 for lib in ["GL", "STC", "Gizmos", "Gizmos_xrc"]:
530 libfile = "lib/lib%s_%s-%s.dylib" % (basename, lib.lower(), version)
531 if os.path.exists(libfile):
532 frameworkDir = "framework/wx%s/%s" % (lib, version)
533 if not os.path.exists(frameworkDir):
534 os.makedirs(frameworkDir)
535 renameLibrary(libfile, "wx" + lib)
536 run("ln -s -f ../../../%s %s/wx%s" % (libfile, frameworkDir, lib))
537
538 for lib in glob.glob("lib/*.dylib"):
539 if not os.path.islink(lib):
540 corelibname = "lib/lib%s-%s.0.dylib" % (basename, version)
541 run("install_name_tool -id %s %s" % (os.path.join(prefixDir, lib), lib))
542 run("install_name_tool -change %s %s %s" % (os.path.join(frameworkRootDir, corelibname), os.path.join(prefixDir, corelibname), lib))
543
544 os.chdir("include")
545
546 header_template = """
547 #ifndef __WX_FRAMEWORK_HEADER__
548 #define __WX_FRAMEWORK_HEADER__
549
550 %s
551
552 #endif // __WX_FRAMEWORK_HEADER__
553 """
554 headers = ""
555 header_dir = "wx-%s/wx" % version
556 for include in glob.glob(header_dir + "/*.h"):
557 headers += "#include <wx/" + os.path.basename(include) + ">\n"
558
559 framework_header = open("%s.h" % fwname, "w")
560 framework_header.write(header_template % headers)
561 framework_header.close()
562
563 run("ln -s -f %s wx" % header_dir)
564 os.chdir("wx-%s/wx" % version)
565 run("ln -s -f ../../../lib/wx/include/%s/wx/setup.h setup.h" % configname)
566
567 os.chdir(os.path.join(frameworkRootDir, ".."))
568 run("ln -s -f %s Current" % getWxRelease())
569 os.chdir("..")
570 run("ln -s -f Versions/Current/Headers Headers")
571 run("ln -s -f Versions/Current/Resources Resources")
572 run("ln -s -f Versions/Current/%s %s" % (fwname, fwname))
573
574 # sanity check to ensure the symlink works
575 os.chdir("Versions/Current")
576
577 # put info about the framework into wx-config
578 os.chdir(frameworkRootDir)
579 text = file('lib/wx/config/%s' % configname).read()
580 text = text.replace("MAC_FRAMEWORK=", "MAC_FRAMEWORK=%s" % getFrameworkName(options))
581 if options.mac_framework_prefix not in ['/Library/Frameworks',
582 '/System/Library/Frameworks']:
583 text = text.replace("MAC_FRAMEWORK_PREFIX=",
584 "MAC_FRAMEWORK_PREFIX=%s" % options.mac_framework_prefix)
585 file('lib/wx/config/%s' % configname, 'w').write(text)
586
587 # The framework is finished!
588 print("wxWidgets framework created at: " +
589 os.path.join( installDir,
590 options.mac_framework_prefix,
591 '%s.framework' % fwname))
592
593
594 # adjust the install_name if needed
595 if sys.platform.startswith("darwin") and \
596 options.install and \
597 options.installdir and \
598 not options.mac_framework and \
599 not options.wxpython: # wxPython's build will do this later if needed
600 if not prefixDir:
601 prefixDir = '/usr/local'
602 macFixupInstallNames(options.installdir, prefixDir)#, buildDir)
603
604 # make a package if a destdir was set.
605 if options.mac_framework and \
606 options.install and \
607 options.installdir and \
608 options.mac_distdir:
609
610 if os.path.exists(options.mac_distdir):
611 shutil.rmtree(options.mac_distdir)
612
613 packagedir = os.path.join(options.mac_distdir, "packages")
614 os.makedirs(packagedir)
615 basename = os.path.basename(prefixDir.split(".")[0])
616 packageName = basename + "-" + getWxRelease()
617 packageMakerPath = getXcodePath()+"/usr/bin/packagemaker "
618 args = []
619 args.append("--root %s" % options.installdir)
620 args.append("--id org.wxwidgets.%s" % basename.lower())
621 args.append("--title %s" % packageName)
622 args.append("--version %s" % getWxRelease())
623 args.append("--out %s" % os.path.join(packagedir, packageName + ".pkg"))
624 cmd = packageMakerPath + ' '.join(args)
625 print("cmd = %s" % cmd)
626 run(cmd)
627
628 os.chdir(options.mac_distdir)
629
630 run('hdiutil create -srcfolder %s -volname "%s" -imagekey zlib-level=9 %s.dmg' % (packagedir, packageName, packageName))
631
632 shutil.rmtree(packagedir)
633
634 if __name__ == '__main__':
635 exitWithException = False # use sys.exit instead
636 main(sys.argv[0], sys.argv[1:])
637