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