3 ###################################
4 # Author: Kevin Ollivier
5 # Licence: wxWindows licence
6 ###################################
28 exitWithException
= True
29 nmakeCommand
= 'nmake.exe'
36 Detects the number of CPUs on a system.
37 This approach is from detectCPUs here: http://www.artima.com/weblogs/viewpost.jsp?thread=230001
39 # Linux, Unix and MacOS:
40 if hasattr(os
, "sysconf"):
41 if "SC_NPROCESSORS_ONLN" in os
.sysconf_names
:
43 ncpus
= os
.sysconf("SC_NPROCESSORS_ONLN")
44 if isinstance(ncpus
, int) and ncpus
> 0:
47 p
= subprocess
.Popen("sysctl -n hw.ncpu", shell
=True, stdout
=subprocess
.PIPE
)
48 return p
.stdout
.read()
51 if "NUMBER_OF_PROCESSORS" in os
.environ
:
52 ncpus
= int(os
.environ
["NUMBER_OF_PROCESSORS"]);
59 base
= getoutput("xcode-select -print-path")
60 return [base
, base
+"/Platforms/MacOSX.platform/Developer"]
64 text
= getoutput("cl.exe")
65 if 'Version 13' in text
:
67 if 'Version 15' in text
:
69 if 'Version 16' in text
:
71 # TODO: Add more tests to get the other versions...
76 def exitIfError(code
, msg
):
80 raise builder
.BuildError(msg
)
85 def getWxRelease(wxRoot
=None):
90 configureText
= open(os
.path
.join(wxRoot
, "configure.in"), "r").read()
91 majorVersion
= re
.search("wx_major_version_number=(\d+)", configureText
).group(1)
92 minorVersion
= re
.search("wx_minor_version_number=(\d+)", configureText
).group(1)
94 versionText
= "%s.%s" % (majorVersion
, minorVersion
)
96 if int(minorVersion
) % 2:
97 releaseVersion
= re
.search("wx_release_number=(\d+)", configureText
).group(1)
98 versionText
+= ".%s" % (releaseVersion
)
103 def getFrameworkName(options
):
104 # the name of the framework is based on the wx port being built
106 if options
.osx_cocoa
:
113 def getPrefixInFramework(options
, wxRoot
=None):
114 # the path inside the framework that is the wx --prefix
115 fwPrefix
= os
.path
.join(
116 os
.path
.abspath(options
.mac_framework_prefix
),
117 "%s.framework/Versions/%s" % (getFrameworkName(options
), getWxRelease(wxRoot
)))
121 def macFixupInstallNames(destdir
, prefix
, buildDir
=None):
122 # When an installdir is used then the install_names embedded in
123 # the dylibs are not correct. Reset the IDs and the dependencies
124 # to use just the prefix.
125 print("**** macFixupInstallNames(%s, %s, %s)" % (destdir
, prefix
, buildDir
))
127 os
.chdir(destdir
+prefix
+'/lib')
128 dylibs
= glob
.glob('*.dylib') # ('*[0-9].[0-9].[0-9].[0-9]*.dylib')
130 cmd
= 'install_name_tool -id %s/lib/%s %s/lib/%s' % \
131 (prefix
,lib
, destdir
+prefix
,lib
)
135 if buildDir
is not None:
136 cmd
= 'install_name_tool -change %s/lib/%s %s/lib/%s %s/lib/%s' % \
137 (buildDir
,dep
, prefix
,dep
, destdir
+prefix
,lib
)
139 cmd
= 'install_name_tool -change %s/lib/%s %s/lib/%s %s/lib/%s' % \
140 (destdir
+prefix
,dep
, prefix
,dep
, destdir
+prefix
,lib
)
149 print("Running %s" % cmd
)
150 return exitIfError(os
.system(cmd
), "Error running %s" % cmd
)
154 sp
= subprocess
.Popen(cmd
, shell
=True, stdout
=subprocess
.PIPE
, stderr
=subprocess
.STDOUT
)
156 output
= sp
.stdout
.read()
157 if sys
.version_info
> (3,):
158 output
= output
.decode('utf-8') # TODO: is utf-8 okay here?
159 output
= output
.rstrip()
163 print("Command '%s' failed with exit code %d." % (cmd
, rval
))
168 def main(scriptName
, args
):
173 global configure_opts
177 scriptDir
= os
.path
.dirname(os
.path
.abspath(scriptName
))
178 wxRootDir
= os
.path
.abspath(os
.path
.join(scriptDir
, "..", ".."))
180 contribDir
= os
.path
.join("contrib", "src")
183 VERSION
= tuple([int(i
) for i
in getWxRelease().split('.')[:2]])
185 if sys
.platform
.startswith("win"):
186 contribDir
= os
.path
.join(wxRootDir
, "contrib", "build")
188 if sys
.platform
.startswith("win"):
193 defJobs
= str(numCPUs())
194 defFwPrefix
= '/Library/Frameworks'
197 "clean" : (False, "Clean all files from the build directory"),
198 "debug" : (False, "Build the library in debug symbols"),
199 "builddir" : ("", "Directory where the build will be performed for autoconf builds."),
200 "prefix" : ("", "Configured prefix to use for autoconf builds. Defaults to installdir if set. Ignored for framework builds."),
201 "jobs" : (defJobs
, "Number of jobs to run at one time in make. Default: %s" % defJobs
),
202 "install" : (False, "Install the toolkit to the installdir directory, or the default dir."),
203 "installdir" : ("", "Directory where built wxWidgets will be installed"),
204 "mac_distdir" : (None, "If set on Mac, will create an installer package in the specified dir."),
205 "mac_universal_binary"
206 : ("", "Comma separated list of architectures to include in the Mac universal binary"),
207 "mac_framework" : (False, "Install the Mac build as a framework"),
208 "mac_framework_prefix"
209 : (defFwPrefix
, "Prefix where the framework should be installed. Default: %s" % defFwPrefix
),
210 "cairo" : (False, "Enable dynamicly loading the Cairo lib for wxGraphicsContext on MSW"),
211 "no_config" : (False, "Turn off configure step on autoconf builds"),
212 "config_only" : (False, "Only run the configure step and then exit"),
213 "rebake" : (False, "Regenerate Bakefile and autoconf files"),
214 "unicode" : (False, "Build the library with unicode support"),
215 "wxpython" : (False, "Build the wxWidgets library with all options needed by wxPython"),
216 "cocoa" : (False, "Build the old Mac Cooca port."),
217 "osx_cocoa" : (False, "Build the new Cocoa port"),
218 "shared" : (False, "Build wx as a dynamic library"),
219 "extra_make" : ("", "Extra args to pass on [n]make's command line."),
220 "features" : ("", "A comma-separated list of wxUSE_XYZ defines on Win, or a list of configure flags on unix."),
221 "verbose" : (False, "Print commands as they are run, (to aid with debugging this script)"),
222 "jom" : (False, "Use jom.exe instead of nmake for MSW builds."),
225 parser
= optparse
.OptionParser(usage
="usage: %prog [options]", version
="%prog 1.0")
227 keys
= option_dict
.keys()
228 for opt
in sorted(keys
):
229 default
= option_dict
[opt
][0]
231 if type(default
) == bool:
232 action
= "store_true"
233 parser
.add_option("--" + opt
, default
=default
, action
=action
, dest
=opt
,
234 help=option_dict
[opt
][1])
236 options
, arguments
= parser
.parse_args(args
=args
)
242 # compiler / build system specific args
243 buildDir
= options
.builddir
245 installDir
= options
.installdir
246 prefixDir
= options
.prefix
248 if toolkit
== "autoconf":
250 buildDir
= os
.getcwd()
252 if options
.features
!= "":
253 configure_opts
.extend(options
.features
.split(" "))
256 configure_opts
.append("--enable-unicode")
259 configure_opts
.append("--enable-debug")
262 configure_opts
.append("--with-old_cocoa")
264 if options
.osx_cocoa
:
265 configure_opts
.append("--with-osx_cocoa")
267 wxpy_configure_opts
= [
270 "--enable-graphics_ctx",
271 "--enable-mediactrl",
274 "--enable-debug_flag",
276 "--disable-debugreport",
277 "--enable-uiactionsim",
280 if sys
.platform
.startswith("darwin"):
281 wxpy_configure_opts
.append("--enable-monolithic")
283 wxpy_configure_opts
.append("--with-sdl")
284 wxpy_configure_opts
.append("--with-gnomeprint")
286 # Try to use use lowest available SDK back to 10.5. Both Carbon and
287 # Cocoa builds require at least the 10.5 SDK now. We only add it to
288 # the wxpy options because this is a hard-requirement for wxPython,
289 # but other cases it is optional and is left up to the developer.
290 # TODO: there should be a command line option to set the SDK...
291 if sys
.platform
.startswith("darwin"):
292 for xcodePath
in getXcodePaths():
294 xcodePath
+"/SDKs/MacOSX10.5.sdk",
295 xcodePath
+"/SDKs/MacOSX10.6.sdk",
296 xcodePath
+"/SDKs/MacOSX10.7.sdk",
297 xcodePath
+"/SDKs/MacOSX10.8.sdk",
300 # use the lowest available sdk
302 if os
.path
.exists(sdk
):
303 wxpy_configure_opts
.append(
304 "--with-macosx-sdk=%s" % sdk
)
307 if not options
.mac_framework
:
308 if installDir
and not prefixDir
:
309 prefixDir
= installDir
311 prefixDir
= os
.path
.abspath(prefixDir
)
312 configure_opts
.append("--prefix=" + prefixDir
)
316 configure_opts
.extend(wxpy_configure_opts
)
318 # wxPython likes adding these debug options too
319 configure_opts
.append("--enable-debug_gdb")
320 configure_opts
.append("--disable-optimise")
321 configure_opts
.remove("--enable-optimise")
325 retval
= run("make -f autogen.mk")
326 exitIfError(retval
, "Error running autogen.mk")
328 if options
.mac_framework
:
329 # TODO: Should options.install be automatically turned on if the
330 # mac_framework flag is given?
332 # framework builds always need to be monolithic
333 if not "--enable-monolithic" in configure_opts
:
334 configure_opts
.append("--enable-monolithic")
336 # The --prefix given to configure will be the framework prefix
337 # plus the framework specific dir structure.
338 prefixDir
= getPrefixInFramework(options
)
339 configure_opts
.append("--prefix=" + prefixDir
)
341 # the framework build adds symlinks above the installDir + prefixDir folder
342 # so we need to wipe from the framework root instead of inside the prefixDir.
343 frameworkRootDir
= os
.path
.abspath(os
.path
.join(installDir
+ prefixDir
, "..", ".."))
344 if os
.path
.exists(frameworkRootDir
):
345 if os
.path
.exists(frameworkRootDir
):
346 shutil
.rmtree(frameworkRootDir
)
348 if options
.mac_universal_binary
:
349 if options
.mac_universal_binary
== 'default':
350 if options
.osx_cocoa
:
351 configure_opts
.append("--enable-universal_binary=i386,x86_64")
353 configure_opts
.append("--enable-universal_binary")
355 configure_opts
.append("--enable-universal_binary=%s" % options
.mac_universal_binary
)
358 print("Configure options: " + repr(configure_opts
))
359 wxBuilder
= builder
.AutoconfBuilder()
360 if not options
.no_config
and not options
.clean
:
364 exitIfError(wxBuilder
.configure(dir=wxRootDir
, options
=configure_opts
),
365 "Error running configure")
368 if options
.config_only
:
369 print("Exiting after configure")
372 elif toolkit
in ["msvc", "msvcProject"]:
374 buildDir
= os
.path
.abspath(os
.path
.join(scriptDir
, "..", "msw"))
376 print("creating wx/msw/setup.h from setup0.h")
378 flags
["wxUSE_UNICODE"] = "1"
380 flags
["wxUSE_UNICODE_MSLU"] = "1"
383 if not os
.environ
.get("CAIRO_ROOT"):
384 print("WARNING: Expected CAIRO_ROOT set in the environment!")
385 flags
["wxUSE_CAIRO"] = "1"
388 flags
["wxDIALOG_UNIT_COMPATIBILITY "] = "0"
389 flags
["wxUSE_DEBUGREPORT"] = "0"
390 flags
["wxUSE_DIALUP_MANAGER"] = "0"
391 flags
["wxUSE_GRAPHICS_CONTEXT"] = "1"
392 flags
["wxUSE_DISPLAY"] = "1"
393 flags
["wxUSE_GLCANVAS"] = "1"
394 flags
["wxUSE_POSTSCRIPT"] = "1"
395 flags
["wxUSE_AFM_FOR_POSTSCRIPT"] = "0"
396 flags
["wxUSE_DATEPICKCTRL_GENERIC"] = "1"
399 flags
["wxUSE_DIB_FOR_BITMAP"] = "1"
402 flags
["wxUSE_UIACTIONSIMULATOR"] = "1"
405 mswIncludeDir
= os
.path
.join(wxRootDir
, "include", "wx", "msw")
406 setup0File
= os
.path
.join(mswIncludeDir
, "setup0.h")
407 setupText
= open(setup0File
, "rb").read()
410 setupText
, subsMade
= re
.subn(flag
+ "\s+?\d", "%s %s" % (flag
, flags
[flag
]), setupText
)
412 print("Flag %s wasn't found in setup0.h!" % flag
)
415 setupFile
= open(os
.path
.join(mswIncludeDir
, "setup.h"), "wb")
416 setupFile
.write(setupText
)
419 if toolkit
== "msvc":
420 print("setting build options...")
421 args
.append("-f makefile.vc")
423 args
.append("UNICODE=1")
425 args
.append("MSLU=1")
428 args
.append("OFFICIAL_BUILD=1")
429 args
.append("COMPILER_VERSION=%s" % getVisCVersion())
430 args
.append("SHARED=1")
431 args
.append("MONOLITHIC=0")
432 args
.append("USE_OPENGL=1")
433 args
.append("USE_GDIPLUS=1")
435 if not options
.debug
:
436 args
.append("BUILD=release")
438 args
.append("BUILD=debug")
441 args
.append("SHARED=1")
446 os
.path
.join(os
.environ
.get("CAIRO_ROOT", ""), 'include\\cairo'))
449 nmakeCommand
= 'jom.exe'
451 wxBuilder
= builder
.MSVCBuilder(commandName
=nmakeCommand
)
453 if toolkit
== "msvcProject":
455 if options
.shared
or options
.wxpython
:
456 args
.append("wx_dll.dsw")
458 args
.append("wx.dsw")
461 wxBuilder
= builder
.MSVCProjectBuilder()
465 print("Builder not available for your specified platform/compiler.")
469 print("Performing cleanup.")
470 wxBuilder
.clean(dir=buildDir
, options
=args
)
474 if options
.extra_make
:
475 args
.append(options
.extra_make
)
477 if not sys
.platform
.startswith("win"):
478 args
.append("--jobs=" + options
.jobs
)
479 exitIfError(wxBuilder
.build(dir=buildDir
, options
=args
), "Error building")
484 extra
= ['DESTDIR='+installDir
]
485 wxBuilder
.install(dir=buildDir
, options
=extra
)
487 if options
.install
and options
.mac_framework
:
489 def renameLibrary(libname
, frameworkname
):
492 while os
.path
.islink(reallib
):
493 links
.append(reallib
)
494 reallib
= "lib/" + os
.readlink(reallib
)
496 #print("reallib is %s" % reallib)
497 run("mv -f %s lib/%s.dylib" % (reallib
, frameworkname
))
500 run("ln -s -f %s.dylib %s" % (frameworkname
, link
))
502 frameworkRootDir
= prefixDir
504 print("installDir = %s" % installDir
)
505 frameworkRootDir
= installDir
+ prefixDir
506 os
.chdir(frameworkRootDir
)
511 fwname
= getFrameworkName(options
)
512 version
= getoutput("bin/wx-config --release")
513 version_full
= getoutput("bin/wx-config --version")
514 basename
= getoutput("bin/wx-config --basename")
515 configname
= getoutput("bin/wx-config --selected-config")
517 os
.makedirs("Resources")
519 CFBundleDevelopmentRegion
="English",
520 CFBundleIdentifier
='org.wxwidgets.wxosxcocoa',
522 CFBundleVersion
=version_full
,
523 CFBundleExecutable
=fwname
,
524 CFBundleGetInfoString
="%s %s" % (fwname
, version_full
),
525 CFBundlePackageType
="FMWK",
526 CFBundleSignature
="WXCO",
527 CFBundleShortVersionString
=version_full
,
528 CFBundleInfoDictionaryVersion
="6.0",
532 plistlib
.writePlist(wxplist
, os
.path
.join(frameworkRootDir
, "Resources", "Info.plist"))
534 # we make wx the "actual" library file and link to it from libwhatever.dylib
535 # so that things can link to wx and survive minor version changes
536 renameLibrary("lib/lib%s-%s.dylib" % (basename
, version
), fwname
)
537 run("ln -s -f lib/%s.dylib %s" % (fwname
, fwname
))
539 run("ln -s -f include Headers")
541 for lib
in ["GL", "STC", "Gizmos", "Gizmos_xrc"]:
542 libfile
= "lib/lib%s_%s-%s.dylib" % (basename
, lib
.lower(), version
)
543 if os
.path
.exists(libfile
):
544 frameworkDir
= "framework/wx%s/%s" % (lib
, version
)
545 if not os
.path
.exists(frameworkDir
):
546 os
.makedirs(frameworkDir
)
547 renameLibrary(libfile
, "wx" + lib
)
548 run("ln -s -f ../../../%s %s/wx%s" % (libfile
, frameworkDir
, lib
))
550 for lib
in glob
.glob("lib/*.dylib"):
551 if not os
.path
.islink(lib
):
552 corelibname
= "lib/lib%s-%s.0.dylib" % (basename
, version
)
553 run("install_name_tool -id %s %s" % (os
.path
.join(prefixDir
, lib
), lib
))
554 run("install_name_tool -change %s %s %s" % (os
.path
.join(frameworkRootDir
, corelibname
), os
.path
.join(prefixDir
, corelibname
), lib
))
558 header_template
= """
559 #ifndef __WX_FRAMEWORK_HEADER__
560 #define __WX_FRAMEWORK_HEADER__
564 #endif // __WX_FRAMEWORK_HEADER__
567 header_dir
= "wx-%s/wx" % version
568 for include
in glob
.glob(header_dir
+ "/*.h"):
569 headers
+= "#include <wx/" + os
.path
.basename(include
) + ">\n"
571 framework_header
= open("%s.h" % fwname
, "w")
572 framework_header
.write(header_template
% headers
)
573 framework_header
.close()
575 run("ln -s -f %s wx" % header_dir
)
576 os
.chdir("wx-%s/wx" % version
)
577 run("ln -s -f ../../../lib/wx/include/%s/wx/setup.h setup.h" % configname
)
579 os
.chdir(os
.path
.join(frameworkRootDir
, ".."))
580 run("ln -s -f %s Current" % getWxRelease())
582 run("ln -s -f Versions/Current/Headers Headers")
583 run("ln -s -f Versions/Current/Resources Resources")
584 run("ln -s -f Versions/Current/%s %s" % (fwname
, fwname
))
586 # sanity check to ensure the symlink works
587 os
.chdir("Versions/Current")
589 # put info about the framework into wx-config
590 os
.chdir(frameworkRootDir
)
591 text
= file('lib/wx/config/%s' % configname
).read()
592 text
= text
.replace("MAC_FRAMEWORK=", "MAC_FRAMEWORK=%s" % getFrameworkName(options
))
593 if options
.mac_framework_prefix
not in ['/Library/Frameworks',
594 '/System/Library/Frameworks']:
595 text
= text
.replace("MAC_FRAMEWORK_PREFIX=",
596 "MAC_FRAMEWORK_PREFIX=%s" % options
.mac_framework_prefix
)
597 file('lib/wx/config/%s' % configname
, 'w').write(text
)
599 # The framework is finished!
600 print("wxWidgets framework created at: " +
601 os
.path
.join( installDir
,
602 options
.mac_framework_prefix
,
603 '%s.framework' % fwname
))
606 # adjust the install_name if needed
607 if sys
.platform
.startswith("darwin") and \
608 options
.install
and \
609 options
.installdir
and \
610 not options
.mac_framework
and \
611 not options
.wxpython
: # wxPython's build will do this later if needed
613 prefixDir
= '/usr/local'
614 macFixupInstallNames(options
.installdir
, prefixDir
)#, buildDir)
616 # make a package if a destdir was set.
617 if options
.mac_framework
and \
618 options
.install
and \
619 options
.installdir
and \
622 if os
.path
.exists(options
.mac_distdir
):
623 shutil
.rmtree(options
.mac_distdir
)
625 packagedir
= os
.path
.join(options
.mac_distdir
, "packages")
626 os
.makedirs(packagedir
)
627 basename
= os
.path
.basename(prefixDir
.split(".")[0])
628 packageName
= basename
+ "-" + getWxRelease()
629 packageMakerPath
= getXcodePaths()[0]+"/usr/bin/packagemaker "
631 args
.append("--root %s" % options
.installdir
)
632 args
.append("--id org.wxwidgets.%s" % basename
.lower())
633 args
.append("--title %s" % packageName
)
634 args
.append("--version %s" % getWxRelease())
635 args
.append("--out %s" % os
.path
.join(packagedir
, packageName
+ ".pkg"))
636 cmd
= packageMakerPath
+ ' '.join(args
)
637 print("cmd = %s" % cmd
)
640 os
.chdir(options
.mac_distdir
)
642 run('hdiutil create -srcfolder %s -volname "%s" -imagekey zlib-level=9 %s.dmg' % (packagedir
, packageName
, packageName
))
644 shutil
.rmtree(packagedir
)
646 if __name__
== '__main__':
647 exitWithException
= False # use sys.exit instead
648 main(sys
.argv
[0], sys
.argv
[1:])