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 13' in text
:
65 if 'Version 15' in text
:
67 # TODO: Add more tests to get the other versions...
72 def exitIfError(code
, msg
):
76 raise builder
.BuildError(msg
)
81 def getWxRelease(wxRoot
=None):
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)
90 versionText
= "%s.%s" % (majorVersion
, minorVersion
)
92 if int(minorVersion
) % 2:
93 releaseVersion
= re
.search("wx_release_number=(\d+)", configureText
).group(1)
94 versionText
+= ".%s" % (releaseVersion
)
99 def getFrameworkName(options
):
100 # the name of the framework is based on the wx port being built
102 if options
.osx_cocoa
:
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
)))
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
))
123 os
.chdir(destdir
+prefix
+'/lib')
124 dylibs
= glob
.glob('*.dylib') # ('*[0-9].[0-9].[0-9].[0-9]*.dylib')
126 cmd
= 'install_name_tool -id %s/lib/%s %s/lib/%s' % \
127 (prefix
,lib
, destdir
+prefix
,lib
)
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
)
135 cmd
= 'install_name_tool -change %s/lib/%s %s/lib/%s %s/lib/%s' % \
136 (destdir
+prefix
,dep
, prefix
,dep
, destdir
+prefix
,lib
)
145 print("Running %s" % cmd
)
146 return exitIfError(os
.system(cmd
), "Error running %s" % cmd
)
150 sp
= subprocess
.Popen(cmd
, shell
=True, stdout
=subprocess
.PIPE
, stderr
=subprocess
.STDOUT
)
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()
159 print("Command '%s' failed with exit code %d." % (cmd
, rval
))
164 def main(scriptName
, args
):
169 global configure_opts
172 scriptDir
= os
.path
.dirname(os
.path
.abspath(scriptName
))
173 wxRootDir
= os
.path
.abspath(os
.path
.join(scriptDir
, "..", ".."))
175 contribDir
= os
.path
.join("contrib", "src")
178 VERSION
= tuple([int(i
) for i
in getWxRelease().split('.')[:2]])
180 if sys
.platform
.startswith("win"):
181 contribDir
= os
.path
.join(wxRootDir
, "contrib", "build")
183 if sys
.platform
.startswith("win"):
188 defJobs
= str(numCPUs())
189 defFwPrefix
= '/Library/Frameworks'
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)"),
219 parser
= optparse
.OptionParser(usage
="usage: %prog [options]", version
="%prog 1.0")
221 keys
= option_dict
.keys()
222 for opt
in sorted(keys
):
223 default
= option_dict
[opt
][0]
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])
230 options
, arguments
= parser
.parse_args(args
=args
)
236 # compiler / build system specific args
237 buildDir
= options
.builddir
239 installDir
= options
.installdir
240 prefixDir
= options
.prefix
242 if toolkit
== "autoconf":
244 buildDir
= os
.getcwd()
246 if options
.features
!= "":
247 configure_opts
.extend(options
.features
.split(" "))
250 configure_opts
.append("--enable-unicode")
253 configure_opts
.append("--enable-debug")
256 configure_opts
.append("--with-old_cocoa")
258 if options
.osx_cocoa
:
259 configure_opts
.append("--with-osx_cocoa")
261 wxpy_configure_opts
= [
264 "--enable-graphics_ctx",
265 "--enable-mediactrl",
268 "--enable-debug_flag",
270 "--disable-debugreport",
271 "--enable-uiactionsim",
274 if sys
.platform
.startswith("darwin"):
275 wxpy_configure_opts
.append("--enable-monolithic")
277 wxpy_configure_opts
.append("--with-sdl")
278 wxpy_configure_opts
.append("--with-gnomeprint")
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()
288 xcodePath
+"/SDKs/MacOSX10.5.sdk",
289 xcodePath
+"/SDKs/MacOSX10.6.sdk",
290 xcodePath
+"/SDKs/MacOSX10.7.sdk",
293 # use the lowest available sdk
295 if os
.path
.exists(sdk
):
296 wxpy_configure_opts
.append(
297 "--with-macosx-sdk=%s" % sdk
)
300 if not options
.mac_framework
:
301 if installDir
and not prefixDir
:
302 prefixDir
= installDir
304 prefixDir
= os
.path
.abspath(prefixDir
)
305 configure_opts
.append("--prefix=" + prefixDir
)
309 configure_opts
.extend(wxpy_configure_opts
)
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")
318 retval
= run("make -f autogen.mk")
319 exitIfError(retval
, "Error running autogen.mk")
321 if options
.mac_framework
:
322 # TODO: Should options.install be automatically turned on if the
323 # mac_framework flag is given?
325 # framework builds always need to be monolithic
326 if not "--enable-monolithic" in configure_opts
:
327 configure_opts
.append("--enable-monolithic")
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
)
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
)
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")
346 configure_opts
.append("--enable-universal_binary")
348 configure_opts
.append("--enable-universal_binary=%s" % options
.mac_universal_binary
)
351 print("Configure options: " + repr(configure_opts
))
352 wxBuilder
= builder
.AutoconfBuilder()
353 if not options
.no_config
and not options
.clean
:
357 exitIfError(wxBuilder
.configure(dir=wxRootDir
, options
=configure_opts
),
358 "Error running configure")
361 if options
.config_only
:
362 print("Exiting after configure")
365 elif toolkit
in ["msvc", "msvcProject"]:
367 buildDir
= os
.path
.abspath(os
.path
.join(scriptDir
, "..", "msw"))
369 print("creating wx/msw/setup.h from setup0.h")
371 flags
["wxUSE_UNICODE"] = "1"
373 flags
["wxUSE_UNICODE_MSLU"] = "1"
376 if not os
.environ
.get("CAIRO_ROOT"):
377 print("WARNING: Expected CAIRO_ROOT set in the environment!")
378 flags
["wxUSE_CAIRO"] = "1"
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"
392 flags
["wxUSE_DIB_FOR_BITMAP"] = "1"
395 flags
["wxUSE_UIACTIONSIMULATOR"] = "1"
398 mswIncludeDir
= os
.path
.join(wxRootDir
, "include", "wx", "msw")
399 setup0File
= os
.path
.join(mswIncludeDir
, "setup0.h")
400 setupText
= open(setup0File
, "rb").read()
403 setupText
, subsMade
= re
.subn(flag
+ "\s+?\d", "%s %s" % (flag
, flags
[flag
]), setupText
)
405 print("Flag %s wasn't found in setup0.h!" % flag
)
408 setupFile
= open(os
.path
.join(mswIncludeDir
, "setup.h"), "wb")
409 setupFile
.write(setupText
)
412 if toolkit
== "msvc":
413 print("setting build options...")
414 args
.append("-f makefile.vc")
416 args
.append("UNICODE=1")
418 args
.append("MSLU=1")
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")
428 if not options
.debug
:
429 args
.append("BUILD=release")
431 args
.append("BUILD=debug")
434 args
.append("SHARED=1")
439 os
.path
.join(os
.environ
.get("CAIRO_ROOT", ""), 'include\\cairo'))
441 wxBuilder
= builder
.MSVCBuilder()
443 if toolkit
== "msvcProject":
445 if options
.shared
or options
.wxpython
:
446 args
.append("wx_dll.dsw")
448 args
.append("wx.dsw")
451 wxBuilder
= builder
.MSVCProjectBuilder()
455 print("Builder not available for your specified platform/compiler.")
459 print("Performing cleanup.")
460 wxBuilder
.clean(dir=buildDir
, options
=args
)
464 if options
.extra_make
:
465 args
.append(options
.extra_make
)
467 if not sys
.platform
.startswith("win"):
468 args
.append("--jobs=" + options
.jobs
)
469 exitIfError(wxBuilder
.build(dir=buildDir
, options
=args
), "Error building")
474 extra
= ['DESTDIR='+installDir
]
475 wxBuilder
.install(dir=buildDir
, options
=extra
)
477 if options
.install
and options
.mac_framework
:
479 def renameLibrary(libname
, frameworkname
):
482 while os
.path
.islink(reallib
):
483 links
.append(reallib
)
484 reallib
= "lib/" + os
.readlink(reallib
)
486 #print("reallib is %s" % reallib)
487 run("mv -f %s lib/%s.dylib" % (reallib
, frameworkname
))
490 run("ln -s -f %s.dylib %s" % (frameworkname
, link
))
492 frameworkRootDir
= prefixDir
494 print("installDir = %s" % installDir
)
495 frameworkRootDir
= installDir
+ prefixDir
496 os
.chdir(frameworkRootDir
)
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")
507 os
.makedirs("Resources")
509 CFBundleDevelopmentRegion
="English",
510 CFBundleIdentifier
='org.wxwidgets.wxosxcocoa',
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",
522 plistlib
.writePlist(wxplist
, os
.path
.join(frameworkRootDir
, "Resources", "Info.plist"))
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
))
529 run("ln -s -f include Headers")
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
))
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
))
548 header_template
= """
549 #ifndef __WX_FRAMEWORK_HEADER__
550 #define __WX_FRAMEWORK_HEADER__
554 #endif // __WX_FRAMEWORK_HEADER__
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"
561 framework_header
= open("%s.h" % fwname
, "w")
562 framework_header
.write(header_template
% headers
)
563 framework_header
.close()
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
)
569 os
.chdir(os
.path
.join(frameworkRootDir
, ".."))
570 run("ln -s -f %s Current" % getWxRelease())
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
))
576 # sanity check to ensure the symlink works
577 os
.chdir("Versions/Current")
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
)
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
))
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
603 prefixDir
= '/usr/local'
604 macFixupInstallNames(options
.installdir
, prefixDir
)#, buildDir)
606 # make a package if a destdir was set.
607 if options
.mac_framework
and \
608 options
.install
and \
609 options
.installdir
and \
612 if os
.path
.exists(options
.mac_distdir
):
613 shutil
.rmtree(options
.mac_distdir
)
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 "
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
)
630 os
.chdir(options
.mac_distdir
)
632 run('hdiutil create -srcfolder %s -volname "%s" -imagekey zlib-level=9 %s.dmg' % (packagedir
, packageName
, packageName
))
634 shutil
.rmtree(packagedir
)
636 if __name__
== '__main__':
637 exitWithException
= False # use sys.exit instead
638 main(sys
.argv
[0], sys
.argv
[1:])