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 dynamically 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 Cocoa 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")
285 # Try to use use lowest available SDK back to 10.5. Both Carbon and
286 # Cocoa builds require at least the 10.5 SDK now. We only add it to
287 # the wxpy options because this is a hard-requirement for wxPython,
288 # but other cases it is optional and is left up to the developer.
289 # TODO: there should be a command line option to set the SDK...
290 if sys
.platform
.startswith("darwin"):
291 for xcodePath
in getXcodePaths():
293 xcodePath
+"/SDKs/MacOSX10.5.sdk",
294 xcodePath
+"/SDKs/MacOSX10.6.sdk",
295 xcodePath
+"/SDKs/MacOSX10.7.sdk",
296 xcodePath
+"/SDKs/MacOSX10.8.sdk",
299 # use the lowest available sdk
301 if os
.path
.exists(sdk
):
302 wxpy_configure_opts
.append(
303 "--with-macosx-sdk=%s" % sdk
)
306 if not options
.mac_framework
:
307 if installDir
and not prefixDir
:
308 prefixDir
= installDir
310 prefixDir
= os
.path
.abspath(prefixDir
)
311 configure_opts
.append("--prefix=" + prefixDir
)
315 configure_opts
.extend(wxpy_configure_opts
)
317 # wxPython likes adding these debug options too
318 configure_opts
.append("--enable-debug_gdb")
319 configure_opts
.append("--disable-optimise")
320 configure_opts
.remove("--enable-optimise")
324 retval
= run("make -f autogen.mk")
325 exitIfError(retval
, "Error running autogen.mk")
327 if options
.mac_framework
:
328 # TODO: Should options.install be automatically turned on if the
329 # mac_framework flag is given?
331 # framework builds always need to be monolithic
332 if not "--enable-monolithic" in configure_opts
:
333 configure_opts
.append("--enable-monolithic")
335 # The --prefix given to configure will be the framework prefix
336 # plus the framework specific dir structure.
337 prefixDir
= getPrefixInFramework(options
)
338 configure_opts
.append("--prefix=" + prefixDir
)
340 # the framework build adds symlinks above the installDir + prefixDir folder
341 # so we need to wipe from the framework root instead of inside the prefixDir.
342 frameworkRootDir
= os
.path
.abspath(os
.path
.join(installDir
+ prefixDir
, "..", ".."))
343 if os
.path
.exists(frameworkRootDir
):
344 if os
.path
.exists(frameworkRootDir
):
345 shutil
.rmtree(frameworkRootDir
)
347 if options
.mac_universal_binary
:
348 if options
.mac_universal_binary
== 'default':
349 if options
.osx_cocoa
:
350 configure_opts
.append("--enable-universal_binary=i386,x86_64")
352 configure_opts
.append("--enable-universal_binary")
354 configure_opts
.append("--enable-universal_binary=%s" % options
.mac_universal_binary
)
357 print("Configure options: " + repr(configure_opts
))
358 wxBuilder
= builder
.AutoconfBuilder()
359 if not options
.no_config
and not options
.clean
:
363 exitIfError(wxBuilder
.configure(dir=wxRootDir
, options
=configure_opts
),
364 "Error running configure")
367 if options
.config_only
:
368 print("Exiting after configure")
371 elif toolkit
in ["msvc", "msvcProject"]:
373 buildDir
= os
.path
.abspath(os
.path
.join(scriptDir
, "..", "msw"))
375 print("creating wx/msw/setup.h from setup0.h")
377 flags
["wxUSE_UNICODE"] = "1"
379 flags
["wxUSE_UNICODE_MSLU"] = "1"
382 if not os
.environ
.get("CAIRO_ROOT"):
383 print("WARNING: Expected CAIRO_ROOT set in the environment!")
384 flags
["wxUSE_CAIRO"] = "1"
387 flags
["wxDIALOG_UNIT_COMPATIBILITY "] = "0"
388 flags
["wxUSE_DEBUGREPORT"] = "0"
389 flags
["wxUSE_DIALUP_MANAGER"] = "0"
390 flags
["wxUSE_GRAPHICS_CONTEXT"] = "1"
391 flags
["wxUSE_DISPLAY"] = "1"
392 flags
["wxUSE_GLCANVAS"] = "1"
393 flags
["wxUSE_POSTSCRIPT"] = "1"
394 flags
["wxUSE_AFM_FOR_POSTSCRIPT"] = "0"
395 flags
["wxUSE_DATEPICKCTRL_GENERIC"] = "1"
398 flags
["wxUSE_DIB_FOR_BITMAP"] = "1"
401 flags
["wxUSE_UIACTIONSIMULATOR"] = "1"
404 mswIncludeDir
= os
.path
.join(wxRootDir
, "include", "wx", "msw")
405 setup0File
= os
.path
.join(mswIncludeDir
, "setup0.h")
406 setupText
= open(setup0File
, "rb").read()
409 setupText
, subsMade
= re
.subn(flag
+ "\s+?\d", "%s %s" % (flag
, flags
[flag
]), setupText
)
411 print("Flag %s wasn't found in setup0.h!" % flag
)
414 setupFile
= open(os
.path
.join(mswIncludeDir
, "setup.h"), "wb")
415 setupFile
.write(setupText
)
418 if toolkit
== "msvc":
419 print("setting build options...")
420 args
.append("-f makefile.vc")
422 args
.append("UNICODE=1")
424 args
.append("MSLU=1")
427 args
.append("OFFICIAL_BUILD=1")
428 args
.append("COMPILER_VERSION=%s" % getVisCVersion())
429 args
.append("SHARED=1")
430 args
.append("MONOLITHIC=0")
431 args
.append("USE_OPENGL=1")
432 args
.append("USE_GDIPLUS=1")
434 if not options
.debug
:
435 args
.append("BUILD=release")
437 args
.append("BUILD=debug")
440 args
.append("SHARED=1")
445 os
.path
.join(os
.environ
.get("CAIRO_ROOT", ""), 'include\\cairo'))
448 nmakeCommand
= 'jom.exe'
450 wxBuilder
= builder
.MSVCBuilder(commandName
=nmakeCommand
)
452 if toolkit
== "msvcProject":
454 if options
.shared
or options
.wxpython
:
455 args
.append("wx_dll.dsw")
457 args
.append("wx.dsw")
460 wxBuilder
= builder
.MSVCProjectBuilder()
464 print("Builder not available for your specified platform/compiler.")
468 print("Performing cleanup.")
469 wxBuilder
.clean(dir=buildDir
, options
=args
)
473 if options
.extra_make
:
474 args
.append(options
.extra_make
)
476 if not sys
.platform
.startswith("win"):
477 args
.append("--jobs=" + options
.jobs
)
478 exitIfError(wxBuilder
.build(dir=buildDir
, options
=args
), "Error building")
483 extra
= ['DESTDIR='+installDir
]
484 wxBuilder
.install(dir=buildDir
, options
=extra
)
486 if options
.install
and options
.mac_framework
:
488 def renameLibrary(libname
, frameworkname
):
491 while os
.path
.islink(reallib
):
492 links
.append(reallib
)
493 reallib
= "lib/" + os
.readlink(reallib
)
495 #print("reallib is %s" % reallib)
496 run("mv -f %s lib/%s.dylib" % (reallib
, frameworkname
))
499 run("ln -s -f %s.dylib %s" % (frameworkname
, link
))
501 frameworkRootDir
= prefixDir
503 print("installDir = %s" % installDir
)
504 frameworkRootDir
= installDir
+ prefixDir
505 os
.chdir(frameworkRootDir
)
510 fwname
= getFrameworkName(options
)
511 version
= getoutput("bin/wx-config --release")
512 version_full
= getoutput("bin/wx-config --version")
513 basename
= getoutput("bin/wx-config --basename")
514 configname
= getoutput("bin/wx-config --selected-config")
516 os
.makedirs("Resources")
518 CFBundleDevelopmentRegion
="English",
519 CFBundleIdentifier
='org.wxwidgets.wxosxcocoa',
521 CFBundleVersion
=version_full
,
522 CFBundleExecutable
=fwname
,
523 CFBundleGetInfoString
="%s %s" % (fwname
, version_full
),
524 CFBundlePackageType
="FMWK",
525 CFBundleSignature
="WXCO",
526 CFBundleShortVersionString
=version_full
,
527 CFBundleInfoDictionaryVersion
="6.0",
531 plistlib
.writePlist(wxplist
, os
.path
.join(frameworkRootDir
, "Resources", "Info.plist"))
533 # we make wx the "actual" library file and link to it from libwhatever.dylib
534 # so that things can link to wx and survive minor version changes
535 renameLibrary("lib/lib%s-%s.dylib" % (basename
, version
), fwname
)
536 run("ln -s -f lib/%s.dylib %s" % (fwname
, fwname
))
538 run("ln -s -f include Headers")
540 for lib
in ["GL", "STC", "Gizmos", "Gizmos_xrc"]:
541 libfile
= "lib/lib%s_%s-%s.dylib" % (basename
, lib
.lower(), version
)
542 if os
.path
.exists(libfile
):
543 frameworkDir
= "framework/wx%s/%s" % (lib
, version
)
544 if not os
.path
.exists(frameworkDir
):
545 os
.makedirs(frameworkDir
)
546 renameLibrary(libfile
, "wx" + lib
)
547 run("ln -s -f ../../../%s %s/wx%s" % (libfile
, frameworkDir
, lib
))
549 for lib
in glob
.glob("lib/*.dylib"):
550 if not os
.path
.islink(lib
):
551 corelibname
= "lib/lib%s-%s.0.dylib" % (basename
, version
)
552 run("install_name_tool -id %s %s" % (os
.path
.join(prefixDir
, lib
), lib
))
553 run("install_name_tool -change %s %s %s" % (os
.path
.join(frameworkRootDir
, corelibname
), os
.path
.join(prefixDir
, corelibname
), lib
))
557 header_template
= """
558 #ifndef __WX_FRAMEWORK_HEADER__
559 #define __WX_FRAMEWORK_HEADER__
563 #endif // __WX_FRAMEWORK_HEADER__
566 header_dir
= "wx-%s/wx" % version
567 for include
in glob
.glob(header_dir
+ "/*.h"):
568 headers
+= "#include <wx/" + os
.path
.basename(include
) + ">\n"
570 framework_header
= open("%s.h" % fwname
, "w")
571 framework_header
.write(header_template
% headers
)
572 framework_header
.close()
574 run("ln -s -f %s wx" % header_dir
)
575 os
.chdir("wx-%s/wx" % version
)
576 run("ln -s -f ../../../lib/wx/include/%s/wx/setup.h setup.h" % configname
)
578 os
.chdir(os
.path
.join(frameworkRootDir
, ".."))
579 run("ln -s -f %s Current" % getWxRelease())
581 run("ln -s -f Versions/Current/Headers Headers")
582 run("ln -s -f Versions/Current/Resources Resources")
583 run("ln -s -f Versions/Current/%s %s" % (fwname
, fwname
))
585 # sanity check to ensure the symlink works
586 os
.chdir("Versions/Current")
588 # put info about the framework into wx-config
589 os
.chdir(frameworkRootDir
)
590 text
= file('lib/wx/config/%s' % configname
).read()
591 text
= text
.replace("MAC_FRAMEWORK=", "MAC_FRAMEWORK=%s" % getFrameworkName(options
))
592 if options
.mac_framework_prefix
not in ['/Library/Frameworks',
593 '/System/Library/Frameworks']:
594 text
= text
.replace("MAC_FRAMEWORK_PREFIX=",
595 "MAC_FRAMEWORK_PREFIX=%s" % options
.mac_framework_prefix
)
596 file('lib/wx/config/%s' % configname
, 'w').write(text
)
598 # The framework is finished!
599 print("wxWidgets framework created at: " +
600 os
.path
.join( installDir
,
601 options
.mac_framework_prefix
,
602 '%s.framework' % fwname
))
605 # adjust the install_name if needed
606 if sys
.platform
.startswith("darwin") and \
607 options
.install
and \
608 options
.installdir
and \
609 not options
.mac_framework
and \
610 not options
.wxpython
: # wxPython's build will do this later if needed
612 prefixDir
= '/usr/local'
613 macFixupInstallNames(options
.installdir
, prefixDir
)#, buildDir)
615 # make a package if a destdir was set.
616 if options
.mac_framework
and \
617 options
.install
and \
618 options
.installdir
and \
621 if os
.path
.exists(options
.mac_distdir
):
622 shutil
.rmtree(options
.mac_distdir
)
624 packagedir
= os
.path
.join(options
.mac_distdir
, "packages")
625 os
.makedirs(packagedir
)
626 basename
= os
.path
.basename(prefixDir
.split(".")[0])
627 packageName
= basename
+ "-" + getWxRelease()
628 packageMakerPath
= getXcodePaths()[0]+"/usr/bin/packagemaker "
630 args
.append("--root %s" % options
.installdir
)
631 args
.append("--id org.wxwidgets.%s" % basename
.lower())
632 args
.append("--title %s" % packageName
)
633 args
.append("--version %s" % getWxRelease())
634 args
.append("--out %s" % os
.path
.join(packagedir
, packageName
+ ".pkg"))
635 cmd
= packageMakerPath
+ ' '.join(args
)
636 print("cmd = %s" % cmd
)
639 os
.chdir(options
.mac_distdir
)
641 run('hdiutil create -srcfolder %s -volname "%s" -imagekey zlib-level=9 %s.dmg' % (packagedir
, packageName
, packageName
))
643 shutil
.rmtree(packagedir
)
645 if __name__
== '__main__':
646 exitWithException
= False # use sys.exit instead
647 main(sys
.argv
[0], sys
.argv
[1:])