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