sconstruct 14.9 KB
###
#This file is a part of the NVDA project.
#URL: http://www.nvda-project.org/
#Copyright 2010-2014 NV Access Limited.
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License version 2.0, as published by
#the Free Software Foundation.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#This license can be found at:
#http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
###

import sys
import os
import time
import _winreg
from glob import glob

def recursiveCopy(env,targetDir,sourceDir):
	targets=[]
	for topDir,subDirs,files in os.walk(sourceDir.abspath):
		relTopDir=os.path.relpath(topDir,sourceDir.abspath)
		for f in files:
			fNode=targetDir.Dir(relTopDir).File(f)
			env.Command(fNode,Dir(topDir).File(f),Copy('$TARGET','$SOURCE'))
			targets.append(fNode)
		if len(files)==0:
			dNode=targetDir.Dir(relTopDir)
			env.Command(dNode,Dir(topDir),Mkdir('$TARGET'))
			targets.append(dNode)
	return targets

# Import NVDA's versionInfo module.
import gettext
gettext.install("nvda", unicode=True)
sys.path.append("source")
import versionInfo
del sys.path[-1]

makensis = "miscDeps\\tools\\NSIS\\makensis"

# Get the path to xgettext.
XGETTEXT = os.path.abspath(os.path.join("miscDeps", "tools", "xgettext.exe"))

def keyCommandsDocTool(env):
	import keyCommandsDoc
	kcdAction=env.Action(
		lambda target,source,env: not keyCommandsDoc.KeyCommandsMaker(source[0].path,target[0].path).make(),
		lambda target,source,env: 'Generating %s'%target[0],
	)
	kcdBuilder=env.Builder(
		action=kcdAction,
		suffix='.t2t',
		src_suffix='.t2t',
	)
	env['BUILDERS']['keyCommandsDoc']=kcdBuilder

keyCommandsLangBlacklist=set([])

vars = Variables()
vars.Add("version", "The version of this build", versionInfo.version)
vars.Add("version_build", "A unique number for this build.", "0")
vars.Add(BoolVariable("release", "Whether this is a release version", False))
vars.Add("publisher", "The publisher of this build", versionInfo.publisher)
vars.Add("updateVersionType", "The version type for which to check for updates", versionInfo.updateVersionType or "")
vars.Add(PathVariable("certFile", "The certificate file with which to sign executables", "",
	lambda key, val, env: not val or PathVariable.PathIsFile(key, val, env)))
vars.Add("certPassword", "The password for the private key in the signing certificate", "")
vars.Add("certTimestampServer", "The URL of the timestamping server to use to timestamp authenticode signatures", "")
vars.Add(PathVariable("outputDir", "The directory where the final built archives and such will be placed", "output",PathVariable.PathIsDirCreate))
vars.Add(ListVariable("nvdaHelperDebugFlags", "a list of debugging features you require", 'none', ["debugCRT","RTC"]))
vars.Add(EnumVariable('nvdaHelperLogLevel','The level of logging you wish to see, lower is more verbose','15',allowed_values=[str(x) for x in xrange(60)]))

#Base environment for this and sub sconscripts
env = Environment(variables=vars,HOST_ARCH='x86',tools=["textfile","gettext","t2t",keyCommandsDocTool,'doxygen','recursiveInstall'])

# speed up subsiquent runs by checking timestamps of targets and dependencies, and only using md5 if timestamps differ.
env.Decider('MD5-timestamp')

#Make our recursiveCopy function available to any script using this environment
env.AddMethod(recursiveCopy)

#Check for any unknown variables
unknown=vars.UnknownVariables().keys()
if len(unknown)>0:
	print "Unknown commandline variables: %s"%unknown
	Exit(1)

#Ensure that any Python subprocesses (such as for py2exe) can find our Python directory in miscDeps
env['ENV']['PYTHONPATH']=Dir('#miscDeps/python').abspath

env["copyright"]=versionInfo.copyright
env['version_year']=versionInfo.version_year
env['version_major']=versionInfo.version_major
env['version_minor']=versionInfo.version_minor
version = env["version"]
version_build = env["version_build"]
release = env["release"]
publisher = env["publisher"]
certFile = env["certFile"]
certPassword = env["certPassword"]
certTimestampServer = env["certTimestampServer"]
userDocsDir=Dir('user_docs')
sourceDir = Dir("source")
Export('sourceDir')
clientDir=Dir('extras/controllerClient')
Export('clientDir')
sourceLibDir=sourceDir.Dir('lib')
Export('sourceLibDir')
sourceTypelibDir=sourceDir.Dir('typelibs')
Export('sourceTypelibDir')
sourceLibDir64=sourceDir.Dir('lib64')
Export('sourceLibDir64')
buildDir = Dir("build")
outFilePrefix = "nvda{type}_{version}".format(type="" if release else "_snapshot", version=version)
outputDir=Dir(env['outputDir'])
devDocsOutputDir=outputDir.Dir('devDocs')

# An action to sign an executable with certFile.
signExecCmd = ["signtool", "sign", "/f", certFile]
if certPassword:
	signExecCmd.extend(("/p", certPassword))
if certTimestampServer:
	signExecCmd.extend(("/t", certTimestampServer))
def signExec(target,source,env):
	print [str(x) for x in target]
	#sys.exit(1)
	# #3795: signtool can quite commonly fail with timestamping, so allow it to try up to 3 times with a 1 second delay between each try. 
	res=0
	for count in xrange(3):
		res=env.Execute([signExecCmd+[target[0].abspath]])
		if not res:
			return 0 # success
		time.sleep(1)
	return res # failed
#Export via scons environment so other libraries can be signed
env['signExec']=signExec

#architecture-specific environments
archTools=['default','windowsSdk','midl','msrpc']
env32=env.Clone(TARGET_ARCH='x86',tools=archTools)
env64=env.Clone(TARGET_ARCH='x86_64',tools=archTools)
# Hack around odd bug where some tool [after] msvc states that static and shared objects are different
env32['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
env64['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1

env=env32

#Fill sourceDir with anything provided for it by miscDeps
env.recursiveCopy(sourceDir,Dir('miscdeps/source'))

env.SConscript('source/comInterfaces_sconscript',exports=['env'])

#Process nvdaHelper scons files
env32.SConscript('nvdaHelper/archBuild_sconscript',exports={'env':env32,'clientInstallDir':clientDir.Dir('x86'),'libInstallDir':sourceLibDir},variant_dir='build/x86')
env64.SConscript('nvdaHelper/archBuild_sconscript',exports={'env':env64,'clientInstallDir':clientDir.Dir('x64'),'libInstallDir':sourceLibDir64},variant_dir='build/x86_64')

#Allow all NVDA's gettext po files to be compiled in source/locale
for po in env.Glob(sourceDir.path+'/locale/*/lc_messages/*.po'):
	env.gettextMoFile(po)

#Allow all key command t2t files to be generated from their userGuide t2t sources
for lang in os.listdir(userDocsDir.path):
	if lang in keyCommandsLangBlacklist: continue
	for ug in glob(os.path.join(userDocsDir.path,lang,'userGuide.t2t')):
		env.keyCommandsDoc(File(ug).File('keyCommands.t2t'),ug)

t2tBuildConf = env.Textfile(userDocsDir.File("build.t2tConf"), [
	# We need to do this one as PostProc so it gets converted for the title.
	r"%!PostProc: NVDA_VERSION {}".format(version),
	r"%!PreProc: NVDA_URL {}".format(versionInfo.url),
	r"%!PreProc: NVDA_COPYRIGHT_YEARS {}".format(versionInfo.copyrightYears),
])

#Allow all t2t files to be converted to html in user_docs
#As we use scons Glob this will also include the keyCommands.t2t files
for t2tFile in env.Glob(os.path.join(userDocsDir.path,'*','*.t2t')):
	htmlFile=env.txt2tags(t2tFile)
	#txt2tags can not be run in parallel so make sure scons knows this
	env.SideEffect('_txt2tags',htmlFile)
	# All of our t2t files require build.t2tConf.
	env.Depends(htmlFile,t2tBuildConf)
#And also build the developer guide -- which must be moved at some point
htmlFile=env.txt2tags('developerGuide.t2t')
env.Depends(htmlFile,t2tBuildConf)
env.SideEffect('_txt2tags',htmlFile)
devGuide=env.Command(devDocsOutputDir.File('developerGuide.html'),htmlFile,Move('$TARGET','$SOURCE'))
env.Alias("developerGuide",devGuide)

# A builder to generate an NVDA distribution.
def NVDADistGenerator(target, source, env, for_signature):
	buildVersionFn = os.path.join(str(source[0]), "_buildVersion.py")
	# Make the NVDA build use the specified version.
	# We don't do this using normal scons mechanisms because we want it to be cleaned up immediately after this builder
	# and py2exe will cause bytecode files to be created for it which scons doesn't know about.
	updateVersionType = env["updateVersionType"] or None
	action = [lambda target, source, env: file(buildVersionFn, "w").write(
		'version = {version!r}\r\n'
		'publisher = {publisher!r}\r\n'
		'updateVersionType = {updateVersionType!r}\r\n'
		'version_build = {version_build!r}\r\n'
		.format(version=version, publisher=publisher, updateVersionType=updateVersionType,version_build=version_build))]

	buildCmd = ["cd", source[0].path, "&&",
		sys.executable]
	if release:
		buildCmd.append("-O")
	buildCmd.extend(("setup.py", "build", "--build-base", buildDir.abspath,
		"py2exe", "--dist-dir", target[0].abspath))
	if release:
		buildCmd.append("-O1")
	action.append(buildCmd)

	if env.get("uiAccess"):
		buildCmd.append("--enable-uiAccess")
	if certFile:
		for prog in "nvda_noUIAccess.exe", "nvda_uiAccess.exe", "nvda_slave.exe", "nvda_service.exe", "nvda_eoaProxy.exe":
			action.append(lambda target,source,env, progByVal=prog: signExec([target[0].File(progByVal)],source,env))

	for ext in "", "c", "o":
		action.append(Delete(buildVersionFn + ext))

	return action
env["BUILDERS"]["NVDADist"] = Builder(generator=NVDADistGenerator, target_factory=Dir)

# A builder to generate a zip archive.
# We roll our own instead of using env.Zip because we want to create some archives
# relative to a specified directory.
def ZipArchiveAction(target, source, env):
	relativeTo = env.get("relativeTo", None)
	if relativeTo:
		relativeTo = relativeTo.path
		def getArcName(origName):
			arcName = os.path.relpath(origName, relativeTo)
			if arcName.startswith(".."):
				arcName = arcName.replace(".." + os.path.sep, "")
			return "" if arcName == "." else arcName
	else:
		getArcName = lambda origName: "" if origName == "." else origName

	# Nasty hack to make zipfile use best compression, since it isn't configurable.
	# Tried setting memlevel to 9 as well, but it made compression slightly worse.
	import zlib
	origZDefComp = zlib.Z_DEFAULT_COMPRESSION
	zlib.Z_DEFAULT_COMPRESSION = zlib.Z_BEST_COMPRESSION

	import zipfile
	zf = None
	try:
		zf = zipfile.ZipFile(target[0].path, "w", zipfile.ZIP_DEFLATED)
		for s in source:
			if os.path.isdir(s.path):
				for path, dirs, files in os.walk(s.path):
					arcPath = getArcName(path)
					if arcPath:
						zf.write(path, arcPath)
					for f in files:
						zf.write(os.path.join(path, f), os.path.join(arcPath, f))
			else:
				zf.write(s.path, getArcName(s.path))

	finally:
		if zf:
			zf.close()
		zlib.Z_DEFAULT_COMPRESSION = origZDefComp

env["BUILDERS"]["ZipArchive"] = Builder(action=ZipArchiveAction)

uninstFile=File("dist/uninstall.exe")
uninstGen = env.Command(File("uninstaller/uninstGen.exe"), "uninstaller/uninst.nsi",
	[[makensis, "/V2",
	"/DVERSION=$version", '/DPUBLISHER="$publisher"','/DCOPYRIGHT="$copyright"','/DVERSION_YEAR="$version_year"','/DVERSION_MAJOR="$version_major"','/DVERSION_MINOR="$version_minor"','/DVERSION_BUILD="$version_build"',
	"/DUNINSTEXE=%s"%uninstFile.abspath,
	"/DINSTEXE=${TARGET.abspath}",
	"$SOURCE"]])
uninstaller=env.Command(uninstFile,uninstGen,[uninstGen])
if certFile:
	env.AddPostAction(uninstaller, [signExec])

dist = env.NVDADist("dist", [sourceDir,userDocsDir], uiAccess=bool(certFile))
env.Depends(dist,uninstaller)
# Dir node targets don't get cleaned, so cleaning of the dist nodes has to be explicitly specified.
env.Clean(dist, dist)
# Clean the intermediate build directory.
env.Clean([dist], buildDir)

launcher = env.Command(outputDir.File("%s.exe" % outFilePrefix), ["launcher/nvdaLauncher.nsi", dist],
	[[makensis, "/V2",
	"/DVERSION=$version", '/DPUBLISHER="$publisher"','/DCOPYRIGHT="$copyright"','/DVERSION_YEAR="$version_year"','/DVERSION_MAJOR="$version_major"','/DVERSION_MINOR="$version_minor"','/DVERSION_BUILD="$version_build"',
	"/DNVDADistDir=${SOURCES[1].abspath}", "/DLAUNCHEREXE=${TARGET.abspath}",
	"$SOURCE"]])
if certFile:
	env.AddPostAction(launcher, [signExec])
env.Alias("launcher", launcher)

clientArchive = env.ZipArchive(outputDir.File("%s_controllerClient.zip" % outFilePrefix), clientDir, relativeTo=clientDir)
env.Alias("client", clientArchive)

changesFile=env.Command(outputDir.File("%s_changes.html" % outFilePrefix),userDocsDir.File('en/changes.html'),Copy('$TARGET','$SOURCE'))
env.Alias('changes',changesFile)
userGuideFile=env.Command(outputDir.File("userGuide.html"),userDocsDir.File('en/userGuide.html'),Copy('$TARGET','$SOURCE'))
env.Alias('userGuide',userGuideFile)

def makePot(target, source, env):
	# Generate the pot.
	if env.Execute([["cd", sourceDir, "&&",
			XGETTEXT,
			"-o", target[0].abspath,
			"--package-name", versionInfo.name, "--package-version", version,
			"--foreign-user",
			"--add-comments=Translators:",
			"--keyword=pgettext:1c,2",
			# Needed because xgettext doesn't recognise the .pyw extension.
			"--language=python",
		] + [os.path.relpath(str(f), str(sourceDir)) for f in source]
	]) != 0:
		raise RuntimeError("xgettext failed")

	# Tweak the headers.
	potFn = str(target[0])
	tmpFn = "%s.tmp" % potFn
	with file(potFn, "rt") as inp, file(tmpFn, "wt") as out:
		for lineNum, line in enumerate(inp):
			if lineNum == 1:
				line = "# %s\n" % versionInfo.copyright
			elif lineNum == 2:
				# Delete line.
				continue
			elif lineNum == 15:
				line = line.replace("CHARSET", "UTF-8")
			out.write(line)
	os.remove(potFn)
	os.rename(tmpFn, potFn)

devDocs_nvdaHelper_temp=env.Doxygen(source='nvdaHelper/doxyfile')
devDocs_nvdaHelper=env.Command(devDocsOutputDir.Dir('nvdaHelper'),devDocs_nvdaHelper_temp,Move('$TARGET','$SOURCE'))
env.Alias('devDocs_nvdaHelper', devDocs_nvdaHelper)
env.Clean('devDocs_nvdaHelper', devDocs_nvdaHelper)

devDocs_nvda = env.Command(devDocsOutputDir.Dir("nvda"), None, [[
	"cd", sourceDir.path, "&&",
	sys.executable, "-c", "import sourceEnv; from epydoc.cli import cli; cli()",
	"--output", "${TARGET.abspath}",
	"--quiet", "--html", "--include-log", "--no-frames",
	"--name", "NVDA", "--url", "http://www.nvda-project.org/",
	"*.py", "appModules", "brailleDisplayDrivers", r"comInterfaces\__init__.py",
	"config", "globalPlugins", "gui", "NVDAObjects",
	"synthDrivers", "textInfos", "virtualBuffers",
]])

env.Alias('devDocs', [devGuide, devDocs_nvda])
env.Clean('devDocs', [devGuide, devDocs_nvda])

pot = env.Command(outputDir.File("%s.pot" % outFilePrefix),
	# Don't use sourceDir as the source, as this depends on comInterfaces and nvdaHelper.
	# We only depend on the Python files.
	[f for pattern in ("*.py", "*.pyw", r"*\*.py", r"*\*\*.py") for f in env.Glob(os.path.join(sourceDir.path, pattern))],
	makePot)

env.Alias("pot", pot)

symbolsList=[]
symbolsList.extend(env.Glob(os.path.join(sourceLibDir.path,'*.pdb')))
symbolsList.extend(env.Glob(os.path.join(sourceLibDir64.path,'*.pdb')))
symbolsArchive = env.ZipArchive(outputDir.File("%s_debugSymbols.zip" % outFilePrefix), symbolsList)
env.Alias("symbolsArchive", symbolsArchive)

env.Default(dist)