3 ###################################
4 # Author: Kevin Ollivier
5 # Licence: wxWindows licence
6 ###################################
28 exitWithException
= True
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
38 # Linux, Unix and MacOS:
39 if hasattr(os
, "sysconf"):
40 if "SC_NPROCESSORS_ONLN" in os
.sysconf_names
:
42 ncpus
= os
.sysconf("SC_NPROCESSORS_ONLN")
43 if isinstance(ncpus
, int) and ncpus
> 0:
46 p
= subprocess
.Popen("sysctl -n hw.ncpu", shell
=True, stdout
=subprocess
.PIPE
)
47 return p
.stdout
.read()
50 if "NUMBER_OF_PROCESSORS" in os
.environ
:
51 ncpus
= int(os
.environ
["NUMBER_OF_PROCESSORS"]);
58 return getoutput("xcode-select -print-path")
62 text
= getoutput("cl.exe")
63 if 'Version 15' in text
:
65 # TODO: Add more tests to get the other versions...
70 def exitIfError(code
, msg
):
74 raise builder
.BuildError(msg
)
79 def getWxRelease(wxRoot
=None):
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)
88 versionText
= "%s.%s" % (majorVersion
, minorVersion
)
90 if int(minorVersion
) % 2:
91 releaseVersion
= re
.search("wx_release_number=(\d+)", configureText
).group(1)
92 versionText
+= ".%s" % (releaseVersion
)
97 def getFrameworkName(options
):
98 # the name of the framework is based on the wx port being built
100 if options
.osx_cocoa
:
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
)))
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
))
121 os
.chdir(destdir
+prefix
+'/lib')
122 dylibs
= glob
.glob('*.dylib') # ('*[0-9].[0-9].[0-9].[0-9]*.dylib')
124 cmd
= 'install_name_tool -id %s/lib/%s %s/lib/%s' % \
125 (prefix
,lib
, destdir
+prefix
,lib
)
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
)
133 cmd
= 'install_name_tool -change %s/lib/%s %s/lib/%s %s/lib/%s' % \
134 (destdir
+prefix
,dep
, prefix
,dep
, destdir
+prefix
,lib
)
143 print("Running %s" % cmd
)
144 return exitIfError(os
.system(cmd
), "Error running %s" % cmd
)
148 sp
= subprocess
.Popen(cmd
, shell
=True, stdout
=subprocess
.PIPE
, stderr
=subprocess
.STDOUT
)
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()
157 print("Command '%s' failed with exit code %d." % (cmd
, rval
))
162 def main(scriptName
, args
):
167 global configure_opts
170 scriptDir
= os
.path
.dirname(os
.path
.abspath(scriptName
))
171 wxRootDir
= os
.path
.abspath(os
.path
.join(scriptDir
, "..", ".."))
173 contribDir
= os
.path
.join("contrib", "src")
176 VERSION
= tuple([int(i
) for i
in getWxRelease().split('.')[:2]])
178 if sys
.platform
.startswith("win"):
179 contribDir
= os
.path
.join(wxRootDir
, "contrib", "build")
181 if sys
.platform
.startswith("win"):
186 defJobs
= str(numCPUs())
187 defFwPrefix
= '/Library/Frameworks'
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)"),
217 parser
= optparse
.OptionParser(usage
="usage: %prog [options]", version
="%prog 1.0")
219 keys
= option_dict
.keys()
220 for opt
in sorted(keys
):
221 default
= option_dict
[opt
][0]
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])
228 options
, arguments
= parser
.parse_args(args
=args
)
234 # compiler / build system specific args
235 buildDir
= options
.builddir
237 installDir
= options
.installdir
238 prefixDir
= options
.prefix
240 if toolkit
== "autoconf":
242 buildDir
= os
.getcwd()
244 if options
.features
!= "":
245 configure_opts
.extend(options
.features
.split(" "))
248 configure_opts
.append("--enable-unicode")
251 configure_opts
.append("--enable-debug")
254 configure_opts
.append("--with-old_cocoa")
256 if options
.osx_cocoa
:
257 configure_opts
.append("--with-osx_cocoa")
259 wxpy_configure_opts
= [
262 "--enable-graphics_ctx",
263 "--enable-mediactrl",
266 "--enable-debug_flag",
268 "--disable-debugreport",
269 "--enable-uiactionsim",
272 if sys
.platform
.startswith("darwin"):
273 wxpy_configure_opts
.append("--enable-monolithic")
275 wxpy_configure_opts
.append("--with-sdl")
276 wxpy_configure_opts
.append("--with-gnomeprint")
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()
286 xcodePath
+"/SDKs/MacOSX10.5.sdk",
287 xcodePath
+"/SDKs/MacOSX10.6.sdk",
288 xcodePath
+"/SDKs/MacOSX10.7.sdk",
291 # use the lowest available sdk
293 if os
.path
.exists(sdk
):
294 wxpy_configure_opts
.append(
295 "--with-macosx-sdk=%s" % sdk
)
298 if not options
.mac_framework
:
299 if installDir
and not prefixDir
:
300 prefixDir
= installDir
302 prefixDir
= os
.path
.abspath(prefixDir
)
303 configure_opts
.append("--prefix=" + prefixDir
)
307 configure_opts
.extend(wxpy_configure_opts
)
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")
316 retval
= run("make -f autogen.mk")
317 exitIfError(retval
, "Error running autogen.mk")
319 if options
.mac_framework
:
320 # TODO: Should options.install be automatically turned on if the
321 # mac_framework flag is given?
323 # framework builds always need to be monolithic
324 if not "--enable-monolithic" in configure_opts
:
325 configure_opts
.append("--enable-monolithic")
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
)
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
)
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")
344 configure_opts
.append("--enable-universal_binary")
346 configure_opts
.append("--enable-universal_binary=%s" % options
.mac_universal_binary
)
349 print("Configure options: " + repr(configure_opts
))
350 wxBuilder
= builder
.AutoconfBuilder()
351 if not options
.no_config
and not options
.clean
:
355 exitIfError(wxBuilder
.configure(dir=wxRootDir
, options
=configure_opts
),
356 "Error running configure")
359 if options
.config_only
:
360 print("Exiting after configure")
363 elif toolkit
in ["msvc", "msvcProject"]:
365 buildDir
= os
.path
.abspath(os
.path
.join(scriptDir
, "..", "msw"))
367 print("creating wx/msw/setup.h from setup0.h")
369 flags
["wxUSE_UNICODE"] = "1"
371 flags
["wxUSE_UNICODE_MSLU"] = "1"
374 if not os
.environ
.get("CAIRO_ROOT"):
375 print("WARNING: Expected CAIRO_ROOT set in the environment!")
376 flags
["wxUSE_CAIRO"] = "1"
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"
390 flags
["wxUSE_DIB_FOR_BITMAP"] = "1"
393 flags
["wxUSE_UIACTIONSIMULATOR"] = "1"
396 mswIncludeDir
= os
.path
.join(wxRootDir
, "include", "wx", "msw")
397 setup0File
= os
.path
.join(mswIncludeDir
, "setup0.h")
398 setupText
= open(setup0File
, "rb").read()
401 setupText
, subsMade
= re
.subn(flag
+ "\s+?\d", "%s %s" % (flag
, flags
[flag
]), setupText
)
403 print("Flag %s wasn't found in setup0.h!" % flag
)
406 setupFile
= open(os
.path
.join(mswIncludeDir
, "setup.h"), "wb")
407 setupFile
.write(setupText
)
410 if toolkit
== "msvc":
411 print("setting build options...")
412 args
.append("-f makefile.vc")
414 args
.append("UNICODE=1")
416 args
.append("MSLU=1")
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")
426 if not options
.debug
:
427 args
.append("BUILD=release")
429 args
.append("BUILD=debug")
432 args
.append("SHARED=1")
437 os
.path
.join(os
.environ
.get("CAIRO_ROOT", ""), 'include\\cairo'))
439 wxBuilder
= builder
.MSVCBuilder()
441 if toolkit
== "msvcProject":
443 if options
.shared
or options
.wxpython
:
444 args
.append("wx_dll.dsw")
446 args
.append("wx.dsw")
449 wxBuilder
= builder
.MSVCProjectBuilder()
453 print("Builder not available for your specified platform/compiler.")
457 print("Performing cleanup.")
458 wxBuilder
.clean(dir=buildDir
, options
=args
)
462 if options
.extra_make
:
463 args
.append(options
.extra_make
)
465 if not sys
.platform
.startswith("win"):
466 args
.append("--jobs=" + options
.jobs
)
467 exitIfError(wxBuilder
.build(dir=buildDir
, options
=args
), "Error building")
472 extra
= ['DESTDIR='+installDir
]
473 wxBuilder
.install(dir=buildDir
, options
=extra
)
475 if options
.install
and options
.mac_framework
:
477 def renameLibrary(libname
, frameworkname
):
480 while os
.path
.islink(reallib
):
481 links
.append(reallib
)
482 reallib
= "lib/" + os
.readlink(reallib
)
484 #print("reallib is %s" % reallib)
485 run("mv -f %s lib/%s.dylib" % (reallib
, frameworkname
))
488 run("ln -s -f %s.dylib %s" % (frameworkname
, link
))
490 frameworkRootDir
= prefixDir
492 print("installDir = %s" % installDir
)
493 frameworkRootDir
= installDir
+ prefixDir
494 os
.chdir(frameworkRootDir
)
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")
505 os
.makedirs("Resources")
507 CFBundleDevelopmentRegion
="English",
508 CFBundleIdentifier
='org.wxwidgets.wxosxcocoa',
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",
520 plistlib
.writePlist(wxplist
, os
.path
.join(frameworkRootDir
, "Resources", "Info.plist"))
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
))
527 run("ln -s -f include Headers")
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
))
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
))
546 header_template
= """
547 #ifndef __WX_FRAMEWORK_HEADER__
548 #define __WX_FRAMEWORK_HEADER__
552 #endif // __WX_FRAMEWORK_HEADER__
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"
559 framework_header
= open("%s.h" % fwname
, "w")
560 framework_header
.write(header_template
% headers
)
561 framework_header
.close()
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
)
567 os
.chdir(os
.path
.join(frameworkRootDir
, ".."))
568 run("ln -s -f %s Current" % getWxRelease())
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
))
574 # sanity check to ensure the symlink works
575 os
.chdir("Versions/Current")
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
)
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
))
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
601 prefixDir
= '/usr/local'
602 macFixupInstallNames(options
.installdir
, prefixDir
)#, buildDir)
604 # make a package if a destdir was set.
605 if options
.mac_framework
and \
606 options
.install
and \
607 options
.installdir
and \
610 if os
.path
.exists(options
.mac_distdir
):
611 shutil
.rmtree(options
.mac_distdir
)
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 "
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
)
628 os
.chdir(options
.mac_distdir
)
630 run('hdiutil create -srcfolder %s -volname "%s" -imagekey zlib-level=9 %s.dmg' % (packagedir
, packageName
, packageName
))
632 shutil
.rmtree(packagedir
)
634 if __name__
== '__main__':
635 exitWithException
= False # use sys.exit instead
636 main(sys
.argv
[0], sys
.argv
[1:])