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 configure_opts
.append("--enable-universal_binary=%s" % options
.mac_universal_binary
)
343 print("Configure options: " + repr(configure_opts
))
344 wxBuilder
= builder
.AutoconfBuilder()
345 if not options
.no_config
and not options
.clean
:
349 exitIfError(wxBuilder
.configure(dir=wxRootDir
, options
=configure_opts
),
350 "Error running configure")
353 if options
.config_only
:
354 print("Exiting after configure")
357 elif toolkit
in ["msvc", "msvcProject"]:
359 buildDir
= os
.path
.abspath(os
.path
.join(scriptDir
, "..", "msw"))
361 print("creating wx/msw/setup.h from setup0.h")
363 flags
["wxUSE_UNICODE"] = "1"
365 flags
["wxUSE_UNICODE_MSLU"] = "1"
368 if not os
.environ
.get("CAIRO_ROOT"):
369 print("WARNING: Expected CAIRO_ROOT set in the environment!")
370 flags
["wxUSE_CAIRO"] = "1"
373 flags
["wxDIALOG_UNIT_COMPATIBILITY "] = "0"
374 flags
["wxUSE_DEBUGREPORT"] = "0"
375 flags
["wxUSE_DIALUP_MANAGER"] = "0"
376 flags
["wxUSE_GRAPHICS_CONTEXT"] = "1"
377 flags
["wxUSE_DISPLAY"] = "1"
378 flags
["wxUSE_GLCANVAS"] = "1"
379 flags
["wxUSE_POSTSCRIPT"] = "1"
380 flags
["wxUSE_AFM_FOR_POSTSCRIPT"] = "0"
381 flags
["wxUSE_DATEPICKCTRL_GENERIC"] = "1"
384 flags
["wxUSE_DIB_FOR_BITMAP"] = "1"
387 flags
["wxUSE_UIACTIONSIMULATOR"] = "1"
390 mswIncludeDir
= os
.path
.join(wxRootDir
, "include", "wx", "msw")
391 setup0File
= os
.path
.join(mswIncludeDir
, "setup0.h")
392 setupText
= open(setup0File
, "rb").read()
395 setupText
, subsMade
= re
.subn(flag
+ "\s+?\d", "%s %s" % (flag
, flags
[flag
]), setupText
)
397 print("Flag %s wasn't found in setup0.h!" % flag
)
400 setupFile
= open(os
.path
.join(mswIncludeDir
, "setup.h"), "wb")
401 setupFile
.write(setupText
)
404 if toolkit
== "msvc":
405 print("setting build options...")
406 args
.append("-f makefile.vc")
408 args
.append("UNICODE=1")
410 args
.append("MSLU=1")
413 args
.append("OFFICIAL_BUILD=1")
414 args
.append("COMPILER_VERSION=%s" % getVisCVersion())
415 args
.append("SHARED=1")
416 args
.append("MONOLITHIC=0")
417 args
.append("USE_OPENGL=1")
418 args
.append("USE_GDIPLUS=1")
420 if not options
.debug
:
421 args
.append("BUILD=release")
423 args
.append("BUILD=debug")
426 args
.append("SHARED=1")
431 os
.path
.join(os
.environ
.get("CAIRO_ROOT", ""), 'include\\cairo'))
433 wxBuilder
= builder
.MSVCBuilder()
435 if toolkit
== "msvcProject":
437 if options
.shared
or options
.wxpython
:
438 args
.append("wx_dll.dsw")
440 args
.append("wx.dsw")
443 wxBuilder
= builder
.MSVCProjectBuilder()
447 print("Builder not available for your specified platform/compiler.")
451 print("Performing cleanup.")
452 wxBuilder
.clean(dir=buildDir
, options
=args
)
456 if options
.extra_make
:
457 args
.append(options
.extra_make
)
459 if not sys
.platform
.startswith("win"):
460 args
.append("--jobs=" + options
.jobs
)
461 exitIfError(wxBuilder
.build(dir=buildDir
, options
=args
), "Error building")
466 extra
= ['DESTDIR='+installDir
]
467 wxBuilder
.install(dir=buildDir
, options
=extra
)
469 if options
.install
and options
.mac_framework
:
471 def renameLibrary(libname
, frameworkname
):
474 while os
.path
.islink(reallib
):
475 links
.append(reallib
)
476 reallib
= "lib/" + os
.readlink(reallib
)
478 #print("reallib is %s" % reallib)
479 run("mv -f %s lib/%s.dylib" % (reallib
, frameworkname
))
482 run("ln -s -f %s.dylib %s" % (frameworkname
, link
))
484 frameworkRootDir
= prefixDir
486 print("installDir = %s" % installDir
)
487 frameworkRootDir
= installDir
+ prefixDir
488 os
.chdir(frameworkRootDir
)
493 fwname
= getFrameworkName(options
)
494 version
= getoutput("bin/wx-config --release")
495 version_full
= getoutput("bin/wx-config --version")
496 basename
= getoutput("bin/wx-config --basename")
497 configname
= getoutput("bin/wx-config --selected-config")
499 os
.makedirs("Resources")
501 CFBundleDevelopmentRegion
="English",
502 CFBundleIdentifier
='org.wxwidgets.wxosxcocoa',
504 CFBundleVersion
=version_full
,
505 CFBundleExecutable
=fwname
,
506 CFBundleGetInfoString
="%s %s" % (fwname
, version_full
),
507 CFBundlePackageType
="FMWK",
508 CFBundleSignature
="WXCO",
509 CFBundleShortVersionString
=version_full
,
510 CFBundleInfoDictionaryVersion
="6.0",
514 plistlib
.writePlist(wxplist
, os
.path
.join(frameworkRootDir
, "Resources", "Info.plist"))
516 # we make wx the "actual" library file and link to it from libwhatever.dylib
517 # so that things can link to wx and survive minor version changes
518 renameLibrary("lib/lib%s-%s.dylib" % (basename
, version
), fwname
)
519 run("ln -s -f lib/%s.dylib %s" % (fwname
, fwname
))
521 run("ln -s -f include Headers")
523 for lib
in ["GL", "STC", "Gizmos", "Gizmos_xrc"]:
524 libfile
= "lib/lib%s_%s-%s.dylib" % (basename
, lib
.lower(), version
)
525 if os
.path
.exists(libfile
):
526 frameworkDir
= "framework/wx%s/%s" % (lib
, version
)
527 if not os
.path
.exists(frameworkDir
):
528 os
.makedirs(frameworkDir
)
529 renameLibrary(libfile
, "wx" + lib
)
530 run("ln -s -f ../../../%s %s/wx%s" % (libfile
, frameworkDir
, lib
))
532 for lib
in glob
.glob("lib/*.dylib"):
533 if not os
.path
.islink(lib
):
534 corelibname
= "lib/lib%s-%s.0.dylib" % (basename
, version
)
535 run("install_name_tool -id %s %s" % (os
.path
.join(prefixDir
, lib
), lib
))
536 run("install_name_tool -change %s %s %s" % (os
.path
.join(frameworkRootDir
, corelibname
), os
.path
.join(prefixDir
, corelibname
), lib
))
540 header_template
= """
541 #ifndef __WX_FRAMEWORK_HEADER__
542 #define __WX_FRAMEWORK_HEADER__
546 #endif // __WX_FRAMEWORK_HEADER__
549 header_dir
= "wx-%s/wx" % version
550 for include
in glob
.glob(header_dir
+ "/*.h"):
551 headers
+= "#include <wx/" + os
.path
.basename(include
) + ">\n"
553 framework_header
= open("%s.h" % fwname
, "w")
554 framework_header
.write(header_template
% headers
)
555 framework_header
.close()
557 run("ln -s -f %s wx" % header_dir
)
558 os
.chdir("wx-%s/wx" % version
)
559 run("ln -s -f ../../../lib/wx/include/%s/wx/setup.h setup.h" % configname
)
561 os
.chdir(os
.path
.join(frameworkRootDir
, ".."))
562 run("ln -s -f %s Current" % getWxRelease())
564 run("ln -s -f Versions/Current/Headers Headers")
565 run("ln -s -f Versions/Current/Resources Resources")
566 run("ln -s -f Versions/Current/%s %s" % (fwname
, fwname
))
568 # sanity check to ensure the symlink works
569 os
.chdir("Versions/Current")
571 # put info about the framework into wx-config
572 os
.chdir(frameworkRootDir
)
573 text
= file('lib/wx/config/%s' % configname
).read()
574 text
= text
.replace("MAC_FRAMEWORK=", "MAC_FRAMEWORK=%s" % getFrameworkName(options
))
575 if options
.mac_framework_prefix
not in ['/Library/Frameworks',
576 '/System/Library/Frameworks']:
577 text
= text
.replace("MAC_FRAMEWORK_PREFIX=",
578 "MAC_FRAMEWORK_PREFIX=%s" % options
.mac_framework_prefix
)
579 file('lib/wx/config/%s' % configname
, 'w').write(text
)
581 # The framework is finished!
582 print("wxWidgets framework created at: " +
583 os
.path
.join( installDir
,
584 options
.mac_framework_prefix
,
585 '%s.framework' % fwname
))
588 # adjust the install_name if needed
589 if sys
.platform
.startswith("darwin") and \
590 options
.install
and \
591 options
.installdir
and \
592 not options
.mac_framework
and \
593 not options
.wxpython
: # wxPython's build will do this later if needed
595 prefixDir
= '/usr/local'
596 macFixupInstallNames(options
.installdir
, prefixDir
)#, buildDir)
598 # make a package if a destdir was set.
599 if options
.mac_framework
and \
600 options
.install
and \
601 options
.installdir
and \
604 if os
.path
.exists(options
.mac_distdir
):
605 shutil
.rmtree(options
.mac_distdir
)
607 packagedir
= os
.path
.join(options
.mac_distdir
, "packages")
608 os
.makedirs(packagedir
)
609 basename
= os
.path
.basename(prefixDir
.split(".")[0])
610 packageName
= basename
+ "-" + getWxRelease()
611 packageMakerPath
= getXcodePath()+"/usr/bin/packagemaker "
613 args
.append("--root %s" % options
.installdir
)
614 args
.append("--id org.wxwidgets.%s" % basename
.lower())
615 args
.append("--title %s" % packageName
)
616 args
.append("--version %s" % getWxRelease())
617 args
.append("--out %s" % os
.path
.join(packagedir
, packageName
+ ".pkg"))
618 cmd
= packageMakerPath
+ ' '.join(args
)
619 print("cmd = %s" % cmd
)
622 os
.chdir(options
.mac_distdir
)
624 run('hdiutil create -srcfolder %s -volname "%s" -imagekey zlib-level=9 %s.dmg' % (packagedir
, packageName
, packageName
))
626 shutil
.rmtree(packagedir
)
628 if __name__
== '__main__':
629 exitWithException
= False # use sys.exit instead
630 main(sys
.argv
[0], sys
.argv
[1:])