You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

macdeployqtplus 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2011 Patrick "p2k" Schneider <me@p2k-network.org>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #
  18. import subprocess, sys, re, os, shutil, stat, os.path, time
  19. from string import Template
  20. from argparse import ArgumentParser
  21. # This is ported from the original macdeployqt with modifications
  22. class FrameworkInfo(object):
  23. def __init__(self):
  24. self.frameworkDirectory = ""
  25. self.frameworkName = ""
  26. self.frameworkPath = ""
  27. self.binaryDirectory = ""
  28. self.binaryName = ""
  29. self.binaryPath = ""
  30. self.version = ""
  31. self.installName = ""
  32. self.deployedInstallName = ""
  33. self.sourceFilePath = ""
  34. self.destinationDirectory = ""
  35. self.sourceResourcesDirectory = ""
  36. self.sourceVersionContentsDirectory = ""
  37. self.sourceContentsDirectory = ""
  38. self.destinationResourcesDirectory = ""
  39. self.destinationVersionContentsDirectory = ""
  40. def __eq__(self, other):
  41. if self.__class__ == other.__class__:
  42. return self.__dict__ == other.__dict__
  43. else:
  44. return False
  45. def __str__(self):
  46. return """ Framework name: %s
  47. Framework directory: %s
  48. Framework path: %s
  49. Binary name: %s
  50. Binary directory: %s
  51. Binary path: %s
  52. Version: %s
  53. Install name: %s
  54. Deployed install name: %s
  55. Source file Path: %s
  56. Deployed Directory (relative to bundle): %s
  57. """ % (self.frameworkName,
  58. self.frameworkDirectory,
  59. self.frameworkPath,
  60. self.binaryName,
  61. self.binaryDirectory,
  62. self.binaryPath,
  63. self.version,
  64. self.installName,
  65. self.deployedInstallName,
  66. self.sourceFilePath,
  67. self.destinationDirectory)
  68. def isDylib(self):
  69. return self.frameworkName.endswith(".dylib")
  70. def isQtFramework(self):
  71. if self.isDylib():
  72. return self.frameworkName.startswith("libQt")
  73. else:
  74. return self.frameworkName.startswith("Qt")
  75. reOLine = re.compile(r'^(.+) \(compatibility version [0-9.]+, current version [0-9.]+\)$')
  76. bundleFrameworkDirectory = "Contents/Frameworks"
  77. bundleBinaryDirectory = "Contents/MacOS"
  78. @classmethod
  79. def fromOtoolLibraryLine(cls, line):
  80. # Note: line must be trimmed
  81. if line == "":
  82. return None
  83. # Don't deploy system libraries (exception for libQtuitools and libQtlucene).
  84. if line.startswith("/System/Library/") or line.startswith("@executable_path") or (line.startswith("/usr/lib/") and "libQt" not in line):
  85. return None
  86. m = cls.reOLine.match(line)
  87. if m is None:
  88. raise RuntimeError("otool line could not be parsed: " + line)
  89. path = m.group(1)
  90. info = cls()
  91. info.sourceFilePath = path
  92. info.installName = path
  93. if path.endswith(".dylib"):
  94. dirname, filename = os.path.split(path)
  95. info.frameworkName = filename
  96. info.frameworkDirectory = dirname
  97. info.frameworkPath = path
  98. info.binaryDirectory = dirname
  99. info.binaryName = filename
  100. info.binaryPath = path
  101. info.version = "-"
  102. info.installName = path
  103. info.deployedInstallName = "@executable_path/../Frameworks/" + info.binaryName
  104. info.sourceFilePath = path
  105. info.destinationDirectory = cls.bundleFrameworkDirectory
  106. else:
  107. parts = path.split("/")
  108. i = 0
  109. # Search for the .framework directory
  110. for part in parts:
  111. if part.endswith(".framework"):
  112. break
  113. i += 1
  114. if i == len(parts):
  115. raise RuntimeError("Could not find .framework or .dylib in otool line: " + line)
  116. info.frameworkName = parts[i]
  117. info.frameworkDirectory = "/".join(parts[:i])
  118. info.frameworkPath = os.path.join(info.frameworkDirectory, info.frameworkName)
  119. info.binaryName = parts[i+3]
  120. info.binaryDirectory = "/".join(parts[i+1:i+3])
  121. info.binaryPath = os.path.join(info.binaryDirectory, info.binaryName)
  122. info.version = parts[i+2]
  123. info.deployedInstallName = "@executable_path/../Frameworks/" + os.path.join(info.frameworkName, info.binaryPath)
  124. info.destinationDirectory = os.path.join(cls.bundleFrameworkDirectory, info.frameworkName, info.binaryDirectory)
  125. info.sourceResourcesDirectory = os.path.join(info.frameworkPath, "Resources")
  126. info.sourceContentsDirectory = os.path.join(info.frameworkPath, "Contents")
  127. info.sourceVersionContentsDirectory = os.path.join(info.frameworkPath, "Versions", info.version, "Contents")
  128. info.destinationResourcesDirectory = os.path.join(cls.bundleFrameworkDirectory, info.frameworkName, "Resources")
  129. info.destinationContentsDirectory = os.path.join(cls.bundleFrameworkDirectory, info.frameworkName, "Contents")
  130. info.destinationVersionContentsDirectory = os.path.join(cls.bundleFrameworkDirectory, info.frameworkName, "Versions", info.version, "Contents")
  131. return info
  132. class ApplicationBundleInfo(object):
  133. def __init__(self, path):
  134. self.path = path
  135. appName = os.path.splitext(os.path.basename(path))[0]
  136. self.binaryPath = os.path.join(path, "Contents", "MacOS", appName)
  137. if not os.path.exists(self.binaryPath):
  138. raise RuntimeError("Could not find bundle binary for " + path)
  139. self.resourcesPath = os.path.join(path, "Contents", "Resources")
  140. self.pluginPath = os.path.join(path, "Contents", "PlugIns")
  141. class DeploymentInfo(object):
  142. def __init__(self):
  143. self.qtPath = None
  144. self.pluginPath = None
  145. self.deployedFrameworks = []
  146. def detectQtPath(self, frameworkDirectory):
  147. parentDir = os.path.dirname(frameworkDirectory)
  148. if os.path.exists(os.path.join(parentDir, "translations")):
  149. # Classic layout, e.g. "/usr/local/Trolltech/Qt-4.x.x"
  150. self.qtPath = parentDir
  151. elif os.path.exists(os.path.join(parentDir, "share", "qt4", "translations")):
  152. # MacPorts layout, e.g. "/opt/local/share/qt4"
  153. self.qtPath = os.path.join(parentDir, "share", "qt4")
  154. elif os.path.exists(os.path.join(os.path.dirname(parentDir), "share", "qt4", "translations")):
  155. # Newer Macports layout
  156. self.qtPath = os.path.join(os.path.dirname(parentDir), "share", "qt4")
  157. else:
  158. self.qtPath = os.getenv("QTDIR", None)
  159. if self.qtPath is not None:
  160. pluginPath = os.path.join(self.qtPath, "plugins")
  161. if os.path.exists(pluginPath):
  162. self.pluginPath = pluginPath
  163. def usesFramework(self, name):
  164. nameDot = "%s." % name
  165. libNameDot = "lib%s." % name
  166. for framework in self.deployedFrameworks:
  167. if framework.endswith(".framework"):
  168. if framework.startswith(nameDot):
  169. return True
  170. elif framework.endswith(".dylib"):
  171. if framework.startswith(libNameDot):
  172. return True
  173. return False
  174. def getFrameworks(binaryPath, verbose):
  175. if verbose >= 3:
  176. print "Inspecting with otool: " + binaryPath
  177. otoolbin=os.getenv("OTOOL", "otool")
  178. otool = subprocess.Popen([otoolbin, "-L", binaryPath], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  179. o_stdout, o_stderr = otool.communicate()
  180. if otool.returncode != 0:
  181. if verbose >= 1:
  182. sys.stderr.write(o_stderr)
  183. sys.stderr.flush()
  184. raise RuntimeError("otool failed with return code %d" % otool.returncode)
  185. otoolLines = o_stdout.split("\n")
  186. otoolLines.pop(0) # First line is the inspected binary
  187. if ".framework" in binaryPath or binaryPath.endswith(".dylib"):
  188. otoolLines.pop(0) # Frameworks and dylibs list themselves as a dependency.
  189. libraries = []
  190. for line in otoolLines:
  191. line = line.replace("@loader_path", os.path.dirname(binaryPath))
  192. info = FrameworkInfo.fromOtoolLibraryLine(line.strip())
  193. if info is not None:
  194. if verbose >= 3:
  195. print "Found framework:"
  196. print info
  197. libraries.append(info)
  198. return libraries
  199. def runInstallNameTool(action, *args):
  200. installnametoolbin=os.getenv("INSTALLNAMETOOL", "install_name_tool")
  201. subprocess.check_call([installnametoolbin, "-"+action] + list(args))
  202. def changeInstallName(oldName, newName, binaryPath, verbose):
  203. if verbose >= 3:
  204. print "Using install_name_tool:"
  205. print " in", binaryPath
  206. print " change reference", oldName
  207. print " to", newName
  208. runInstallNameTool("change", oldName, newName, binaryPath)
  209. def changeIdentification(id, binaryPath, verbose):
  210. if verbose >= 3:
  211. print "Using install_name_tool:"
  212. print " change identification in", binaryPath
  213. print " to", id
  214. runInstallNameTool("id", id, binaryPath)
  215. def runStrip(binaryPath, verbose):
  216. stripbin=os.getenv("STRIP", "strip")
  217. if verbose >= 3:
  218. print "Using strip:"
  219. print " stripped", binaryPath
  220. subprocess.check_call([stripbin, "-x", binaryPath])
  221. def copyFramework(framework, path, verbose):
  222. if framework.sourceFilePath.startswith("Qt"):
  223. #standard place for Nokia Qt installer's frameworks
  224. fromPath = "/Library/Frameworks/" + framework.sourceFilePath
  225. else:
  226. fromPath = framework.sourceFilePath
  227. toDir = os.path.join(path, framework.destinationDirectory)
  228. toPath = os.path.join(toDir, framework.binaryName)
  229. if not os.path.exists(fromPath):
  230. raise RuntimeError("No file at " + fromPath)
  231. if os.path.exists(toPath):
  232. return None # Already there
  233. if not os.path.exists(toDir):
  234. os.makedirs(toDir)
  235. shutil.copy2(fromPath, toPath)
  236. if verbose >= 3:
  237. print "Copied:", fromPath
  238. print " to:", toPath
  239. permissions = os.stat(toPath)
  240. if not permissions.st_mode & stat.S_IWRITE:
  241. os.chmod(toPath, permissions.st_mode | stat.S_IWRITE)
  242. if not framework.isDylib(): # Copy resources for real frameworks
  243. linkfrom = os.path.join(path, "Contents","Frameworks", framework.frameworkName, "Versions", "Current")
  244. linkto = framework.version
  245. if not os.path.exists(linkfrom):
  246. os.symlink(linkto, linkfrom)
  247. if verbose >= 2:
  248. print "Linked:", linkfrom, "->", linkto
  249. fromResourcesDir = framework.sourceResourcesDirectory
  250. if os.path.exists(fromResourcesDir):
  251. toResourcesDir = os.path.join(path, framework.destinationResourcesDirectory)
  252. shutil.copytree(fromResourcesDir, toResourcesDir, symlinks=True)
  253. if verbose >= 3:
  254. print "Copied resources:", fromResourcesDir
  255. print " to:", toResourcesDir
  256. fromContentsDir = framework.sourceVersionContentsDirectory
  257. if not os.path.exists(fromContentsDir):
  258. fromContentsDir = framework.sourceContentsDirectory
  259. if os.path.exists(fromContentsDir):
  260. toContentsDir = os.path.join(path, framework.destinationVersionContentsDirectory)
  261. shutil.copytree(fromContentsDir, toContentsDir, symlinks=True)
  262. contentslinkfrom = os.path.join(path, framework.destinationContentsDirectory)
  263. if verbose >= 3:
  264. print "Copied Contents:", fromContentsDir
  265. print " to:", toContentsDir
  266. elif framework.frameworkName.startswith("libQtGui"): # Copy qt_menu.nib (applies to non-framework layout)
  267. qtMenuNibSourcePath = os.path.join(framework.frameworkDirectory, "Resources", "qt_menu.nib")
  268. qtMenuNibDestinationPath = os.path.join(path, "Contents", "Resources", "qt_menu.nib")
  269. if os.path.exists(qtMenuNibSourcePath) and not os.path.exists(qtMenuNibDestinationPath):
  270. shutil.copytree(qtMenuNibSourcePath, qtMenuNibDestinationPath, symlinks=True)
  271. if verbose >= 3:
  272. print "Copied for libQtGui:", qtMenuNibSourcePath
  273. print " to:", qtMenuNibDestinationPath
  274. return toPath
  275. def deployFrameworks(frameworks, bundlePath, binaryPath, strip, verbose, deploymentInfo=None):
  276. if deploymentInfo is None:
  277. deploymentInfo = DeploymentInfo()
  278. while len(frameworks) > 0:
  279. framework = frameworks.pop(0)
  280. deploymentInfo.deployedFrameworks.append(framework.frameworkName)
  281. if verbose >= 2:
  282. print "Processing", framework.frameworkName, "..."
  283. # Get the Qt path from one of the Qt frameworks
  284. if deploymentInfo.qtPath is None and framework.isQtFramework():
  285. deploymentInfo.detectQtPath(framework.frameworkDirectory)
  286. if framework.installName.startswith("@executable_path") or framework.installName.startswith(bundlePath):
  287. if verbose >= 2:
  288. print framework.frameworkName, "already deployed, skipping."
  289. continue
  290. # install_name_tool the new id into the binary
  291. changeInstallName(framework.installName, framework.deployedInstallName, binaryPath, verbose)
  292. # Copy farmework to app bundle.
  293. deployedBinaryPath = copyFramework(framework, bundlePath, verbose)
  294. # Skip the rest if already was deployed.
  295. if deployedBinaryPath is None:
  296. continue
  297. if strip:
  298. runStrip(deployedBinaryPath, verbose)
  299. # install_name_tool it a new id.
  300. changeIdentification(framework.deployedInstallName, deployedBinaryPath, verbose)
  301. # Check for framework dependencies
  302. dependencies = getFrameworks(deployedBinaryPath, verbose)
  303. for dependency in dependencies:
  304. changeInstallName(dependency.installName, dependency.deployedInstallName, deployedBinaryPath, verbose)
  305. # Deploy framework if necessary.
  306. if dependency.frameworkName not in deploymentInfo.deployedFrameworks and dependency not in frameworks:
  307. frameworks.append(dependency)
  308. return deploymentInfo
  309. def deployFrameworksForAppBundle(applicationBundle, strip, verbose):
  310. frameworks = getFrameworks(applicationBundle.binaryPath, verbose)
  311. if len(frameworks) == 0 and verbose >= 1:
  312. print "Warning: Could not find any external frameworks to deploy in %s." % (applicationBundle.path)
  313. return DeploymentInfo()
  314. else:
  315. return deployFrameworks(frameworks, applicationBundle.path, applicationBundle.binaryPath, strip, verbose)
  316. def deployPlugins(appBundleInfo, deploymentInfo, strip, verbose):
  317. # Lookup available plugins, exclude unneeded
  318. plugins = []
  319. if deploymentInfo.pluginPath is None:
  320. return
  321. for dirpath, dirnames, filenames in os.walk(deploymentInfo.pluginPath):
  322. pluginDirectory = os.path.relpath(dirpath, deploymentInfo.pluginPath)
  323. if pluginDirectory == "designer":
  324. # Skip designer plugins
  325. continue
  326. elif pluginDirectory == "phonon" or pluginDirectory == "phonon_backend":
  327. # Deploy the phonon plugins only if phonon is in use
  328. if not deploymentInfo.usesFramework("phonon"):
  329. continue
  330. elif pluginDirectory == "sqldrivers":
  331. # Deploy the sql plugins only if QtSql is in use
  332. if not deploymentInfo.usesFramework("QtSql"):
  333. continue
  334. elif pluginDirectory == "script":
  335. # Deploy the script plugins only if QtScript is in use
  336. if not deploymentInfo.usesFramework("QtScript"):
  337. continue
  338. elif pluginDirectory == "qmltooling" or pluginDirectory == "qml1tooling":
  339. # Deploy the qml plugins only if QtDeclarative is in use
  340. if not deploymentInfo.usesFramework("QtDeclarative"):
  341. continue
  342. elif pluginDirectory == "bearer":
  343. # Deploy the bearer plugins only if QtNetwork is in use
  344. if not deploymentInfo.usesFramework("QtNetwork"):
  345. continue
  346. elif pluginDirectory == "position":
  347. # Deploy the position plugins only if QtPositioning is in use
  348. if not deploymentInfo.usesFramework("QtPositioning"):
  349. continue
  350. elif pluginDirectory == "sensors" or pluginDirectory == "sensorgestures":
  351. # Deploy the sensor plugins only if QtSensors is in use
  352. if not deploymentInfo.usesFramework("QtSensors"):
  353. continue
  354. elif pluginDirectory == "audio" or pluginDirectory == "playlistformats":
  355. # Deploy the audio plugins only if QtMultimedia is in use
  356. if not deploymentInfo.usesFramework("QtMultimedia"):
  357. continue
  358. elif pluginDirectory == "mediaservice":
  359. # Deploy the mediaservice plugins only if QtMultimediaWidgets is in use
  360. if not deploymentInfo.usesFramework("QtMultimediaWidgets"):
  361. continue
  362. for pluginName in filenames:
  363. pluginPath = os.path.join(pluginDirectory, pluginName)
  364. if pluginName.endswith("_debug.dylib"):
  365. # Skip debug plugins
  366. continue
  367. elif pluginPath == "imageformats/libqsvg.dylib" or pluginPath == "iconengines/libqsvgicon.dylib":
  368. # Deploy the svg plugins only if QtSvg is in use
  369. if not deploymentInfo.usesFramework("QtSvg"):
  370. continue
  371. elif pluginPath == "accessible/libqtaccessiblecompatwidgets.dylib":
  372. # Deploy accessibility for Qt3Support only if the Qt3Support is in use
  373. if not deploymentInfo.usesFramework("Qt3Support"):
  374. continue
  375. elif pluginPath == "graphicssystems/libqglgraphicssystem.dylib":
  376. # Deploy the opengl graphicssystem plugin only if QtOpenGL is in use
  377. if not deploymentInfo.usesFramework("QtOpenGL"):
  378. continue
  379. elif pluginPath == "accessible/libqtaccessiblequick.dylib":
  380. # Deploy the accessible qtquick plugin only if QtQuick is in use
  381. if not deploymentInfo.usesFramework("QtQuick"):
  382. continue
  383. plugins.append((pluginDirectory, pluginName))
  384. for pluginDirectory, pluginName in plugins:
  385. if verbose >= 2:
  386. print "Processing plugin", os.path.join(pluginDirectory, pluginName), "..."
  387. sourcePath = os.path.join(deploymentInfo.pluginPath, pluginDirectory, pluginName)
  388. destinationDirectory = os.path.join(appBundleInfo.pluginPath, pluginDirectory)
  389. if not os.path.exists(destinationDirectory):
  390. os.makedirs(destinationDirectory)
  391. destinationPath = os.path.join(destinationDirectory, pluginName)
  392. shutil.copy2(sourcePath, destinationPath)
  393. if verbose >= 3:
  394. print "Copied:", sourcePath
  395. print " to:", destinationPath
  396. if strip:
  397. runStrip(destinationPath, verbose)
  398. dependencies = getFrameworks(destinationPath, verbose)
  399. for dependency in dependencies:
  400. changeInstallName(dependency.installName, dependency.deployedInstallName, destinationPath, verbose)
  401. # Deploy framework if necessary.
  402. if dependency.frameworkName not in deploymentInfo.deployedFrameworks:
  403. deployFrameworks([dependency], appBundleInfo.path, destinationPath, strip, verbose, deploymentInfo)
  404. qt_conf="""[Paths]
  405. Translations=Resources
  406. Plugins=PlugIns
  407. """
  408. ap = ArgumentParser(description="""Improved version of macdeployqt.
  409. Outputs a ready-to-deploy app in a folder "dist" and optionally wraps it in a .dmg file.
  410. Note, that the "dist" folder will be deleted before deploying on each run.
  411. Optionally, Qt translation files (.qm) and additional resources can be added to the bundle.
  412. Also optionally signs the .app bundle; set the CODESIGNARGS environment variable to pass arguments
  413. to the codesign tool.
  414. E.g. CODESIGNARGS='--sign "Developer ID Application: ..." --keychain /encrypted/foo.keychain'""")
  415. ap.add_argument("app_bundle", nargs=1, metavar="app-bundle", help="application bundle to be deployed")
  416. ap.add_argument("-verbose", type=int, nargs=1, default=[1], metavar="<0-3>", help="0 = no output, 1 = error/warning (default), 2 = normal, 3 = debug")
  417. ap.add_argument("-no-plugins", dest="plugins", action="store_false", default=True, help="skip plugin deployment")
  418. ap.add_argument("-no-strip", dest="strip", action="store_false", default=True, help="don't run 'strip' on the binaries")
  419. ap.add_argument("-sign", dest="sign", action="store_true", default=False, help="sign .app bundle with codesign tool")
  420. ap.add_argument("-dmg", nargs="?", const="", metavar="basename", help="create a .dmg disk image; if basename is not specified, a camel-cased version of the app name is used")
  421. ap.add_argument("-fancy", nargs=1, metavar="plist", default=[], help="make a fancy looking disk image using the given plist file with instructions; requires -dmg to work")
  422. ap.add_argument("-add-qt-tr", nargs=1, metavar="languages", default=[], help="add Qt translation files to the bundle's ressources; the language list must be separated with commas, not with whitespace")
  423. ap.add_argument("-translations-dir", nargs=1, metavar="path", default=None, help="Path to Qt's translation files")
  424. ap.add_argument("-add-resources", nargs="+", metavar="path", default=[], help="list of additional files or folders to be copied into the bundle's resources; must be the last argument")
  425. config = ap.parse_args()
  426. verbose = config.verbose[0]
  427. # ------------------------------------------------
  428. app_bundle = config.app_bundle[0]
  429. if not os.path.exists(app_bundle):
  430. if verbose >= 1:
  431. sys.stderr.write("Error: Could not find app bundle \"%s\"\n" % (app_bundle))
  432. sys.exit(1)
  433. app_bundle_name = os.path.splitext(os.path.basename(app_bundle))[0]
  434. # ------------------------------------------------
  435. translations_dir = None
  436. if config.translations_dir and config.translations_dir[0]:
  437. if os.path.exists(config.translations_dir[0]):
  438. translations_dir = config.translations_dir[0]
  439. else:
  440. if verbose >= 1:
  441. sys.stderr.write("Error: Could not find translation dir \"%s\"\n" % (translations_dir))
  442. sys.exit(1)
  443. # ------------------------------------------------
  444. for p in config.add_resources:
  445. if verbose >= 3:
  446. print "Checking for \"%s\"..." % p
  447. if not os.path.exists(p):
  448. if verbose >= 1:
  449. sys.stderr.write("Error: Could not find additional resource file \"%s\"\n" % (p))
  450. sys.exit(1)
  451. # ------------------------------------------------
  452. if len(config.fancy) == 1:
  453. if verbose >= 3:
  454. print "Fancy: Importing plistlib..."
  455. try:
  456. import plistlib
  457. except ImportError:
  458. if verbose >= 1:
  459. sys.stderr.write("Error: Could not import plistlib which is required for fancy disk images.\n")
  460. sys.exit(1)
  461. p = config.fancy[0]
  462. if verbose >= 3:
  463. print "Fancy: Loading \"%s\"..." % p
  464. if not os.path.exists(p):
  465. if verbose >= 1:
  466. sys.stderr.write("Error: Could not find fancy disk image plist at \"%s\"\n" % (p))
  467. sys.exit(1)
  468. try:
  469. fancy = plistlib.readPlist(p)
  470. except:
  471. if verbose >= 1:
  472. sys.stderr.write("Error: Could not parse fancy disk image plist at \"%s\"\n" % (p))
  473. sys.exit(1)
  474. try:
  475. assert not fancy.has_key("window_bounds") or (isinstance(fancy["window_bounds"], list) and len(fancy["window_bounds"]) == 4)
  476. assert not fancy.has_key("background_picture") or isinstance(fancy["background_picture"], str)
  477. assert not fancy.has_key("icon_size") or isinstance(fancy["icon_size"], int)
  478. assert not fancy.has_key("applications_symlink") or isinstance(fancy["applications_symlink"], bool)
  479. if fancy.has_key("items_position"):
  480. assert isinstance(fancy["items_position"], dict)
  481. for key, value in fancy["items_position"].iteritems():
  482. assert isinstance(value, list) and len(value) == 2 and isinstance(value[0], int) and isinstance(value[1], int)
  483. except:
  484. if verbose >= 1:
  485. sys.stderr.write("Error: Bad format of fancy disk image plist at \"%s\"\n" % (p))
  486. sys.exit(1)
  487. if fancy.has_key("background_picture"):
  488. bp = fancy["background_picture"]
  489. if verbose >= 3:
  490. print "Fancy: Resolving background picture \"%s\"..." % bp
  491. if not os.path.exists(bp):
  492. bp = os.path.join(os.path.dirname(p), bp)
  493. if not os.path.exists(bp):
  494. if verbose >= 1:
  495. sys.stderr.write("Error: Could not find background picture at \"%s\" or \"%s\"\n" % (fancy["background_picture"], bp))
  496. sys.exit(1)
  497. else:
  498. fancy["background_picture"] = bp
  499. else:
  500. fancy = None
  501. # ------------------------------------------------
  502. if os.path.exists("dist"):
  503. if verbose >= 2:
  504. print "+ Removing old dist folder +"
  505. shutil.rmtree("dist")
  506. # ------------------------------------------------
  507. target = os.path.join("dist", app_bundle)
  508. if verbose >= 2:
  509. print "+ Copying source bundle +"
  510. if verbose >= 3:
  511. print app_bundle, "->", target
  512. os.mkdir("dist")
  513. shutil.copytree(app_bundle, target, symlinks=True)
  514. applicationBundle = ApplicationBundleInfo(target)
  515. # ------------------------------------------------
  516. if verbose >= 2:
  517. print "+ Deploying frameworks +"
  518. try:
  519. deploymentInfo = deployFrameworksForAppBundle(applicationBundle, config.strip, verbose)
  520. if deploymentInfo.qtPath is None:
  521. deploymentInfo.qtPath = os.getenv("QTDIR", None)
  522. if deploymentInfo.qtPath is None:
  523. if verbose >= 1:
  524. sys.stderr.write("Warning: Could not detect Qt's path, skipping plugin deployment!\n")
  525. config.plugins = False
  526. except RuntimeError as e:
  527. if verbose >= 1:
  528. sys.stderr.write("Error: %s\n" % str(e))
  529. sys.exit(1)
  530. # ------------------------------------------------
  531. if config.plugins:
  532. if verbose >= 2:
  533. print "+ Deploying plugins +"
  534. try:
  535. deployPlugins(applicationBundle, deploymentInfo, config.strip, verbose)
  536. except RuntimeError as e:
  537. if verbose >= 1:
  538. sys.stderr.write("Error: %s\n" % str(e))
  539. sys.exit(1)
  540. # ------------------------------------------------
  541. if len(config.add_qt_tr) == 0:
  542. add_qt_tr = []
  543. else:
  544. if translations_dir is not None:
  545. qt_tr_dir = translations_dir
  546. else:
  547. if deploymentInfo.qtPath is not None:
  548. qt_tr_dir = os.path.join(deploymentInfo.qtPath, "translations")
  549. else:
  550. sys.stderr.write("Error: Could not find Qt translation path\n")
  551. sys.exit(1)
  552. add_qt_tr = ["qt_%s.qm" % lng for lng in config.add_qt_tr[0].split(",")]
  553. for lng_file in add_qt_tr:
  554. p = os.path.join(qt_tr_dir, lng_file)
  555. if verbose >= 3:
  556. print "Checking for \"%s\"..." % p
  557. if not os.path.exists(p):
  558. if verbose >= 1:
  559. sys.stderr.write("Error: Could not find Qt translation file \"%s\"\n" % (lng_file))
  560. sys.exit(1)
  561. # ------------------------------------------------
  562. if verbose >= 2:
  563. print "+ Installing qt.conf +"
  564. f = open(os.path.join(applicationBundle.resourcesPath, "qt.conf"), "wb")
  565. f.write(qt_conf)
  566. f.close()
  567. # ------------------------------------------------
  568. if len(add_qt_tr) > 0 and verbose >= 2:
  569. print "+ Adding Qt translations +"
  570. for lng_file in add_qt_tr:
  571. if verbose >= 3:
  572. print os.path.join(qt_tr_dir, lng_file), "->", os.path.join(applicationBundle.resourcesPath, lng_file)
  573. shutil.copy2(os.path.join(qt_tr_dir, lng_file), os.path.join(applicationBundle.resourcesPath, lng_file))
  574. # ------------------------------------------------
  575. if len(config.add_resources) > 0 and verbose >= 2:
  576. print "+ Adding additional resources +"
  577. for p in config.add_resources:
  578. t = os.path.join(applicationBundle.resourcesPath, os.path.basename(p))
  579. if verbose >= 3:
  580. print p, "->", t
  581. if os.path.isdir(p):
  582. shutil.copytree(p, t, symlinks=True)
  583. else:
  584. shutil.copy2(p, t)
  585. # ------------------------------------------------
  586. if config.sign and 'CODESIGNARGS' not in os.environ:
  587. print "You must set the CODESIGNARGS environment variable. Skipping signing."
  588. elif config.sign:
  589. if verbose >= 1:
  590. print "Code-signing app bundle %s"%(target,)
  591. subprocess.check_call("codesign --force %s %s"%(os.environ['CODESIGNARGS'], target), shell=True)
  592. # ------------------------------------------------
  593. if config.dmg is not None:
  594. #Patch in check_output for Python 2.6
  595. if "check_output" not in dir( subprocess ):
  596. def f(*popenargs, **kwargs):
  597. if 'stdout' in kwargs:
  598. raise ValueError('stdout argument not allowed, it will be overridden.')
  599. process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
  600. output, unused_err = process.communicate()
  601. retcode = process.poll()
  602. if retcode:
  603. cmd = kwargs.get("args")
  604. if cmd is None:
  605. cmd = popenargs[0]
  606. raise CalledProcessError(retcode, cmd)
  607. return output
  608. subprocess.check_output = f
  609. def runHDIUtil(verb, image_basename, **kwargs):
  610. hdiutil_args = ["hdiutil", verb, image_basename + ".dmg"]
  611. if kwargs.has_key("capture_stdout"):
  612. del kwargs["capture_stdout"]
  613. run = subprocess.check_output
  614. else:
  615. if verbose < 2:
  616. hdiutil_args.append("-quiet")
  617. elif verbose >= 3:
  618. hdiutil_args.append("-verbose")
  619. run = subprocess.check_call
  620. for key, value in kwargs.iteritems():
  621. hdiutil_args.append("-" + key)
  622. if not value is True:
  623. hdiutil_args.append(str(value))
  624. return run(hdiutil_args)
  625. if verbose >= 2:
  626. if fancy is None:
  627. print "+ Creating .dmg disk image +"
  628. else:
  629. print "+ Preparing .dmg disk image +"
  630. if config.dmg != "":
  631. dmg_name = config.dmg
  632. else:
  633. spl = app_bundle_name.split(" ")
  634. dmg_name = spl[0] + "".join(p.capitalize() for p in spl[1:])
  635. if fancy is None:
  636. try:
  637. runHDIUtil("create", dmg_name, srcfolder="dist", format="UDBZ", volname=app_bundle_name, ov=True)
  638. except subprocess.CalledProcessError as e:
  639. sys.exit(e.returncode)
  640. else:
  641. if verbose >= 3:
  642. print "Determining size of \"dist\"..."
  643. size = 0
  644. for path, dirs, files in os.walk("dist"):
  645. for file in files:
  646. size += os.path.getsize(os.path.join(path, file))
  647. size += int(size * 0.1)
  648. if verbose >= 3:
  649. print "Creating temp image for modification..."
  650. try:
  651. runHDIUtil("create", dmg_name + ".temp", srcfolder="dist", format="UDRW", size=size, volname=app_bundle_name, ov=True)
  652. except subprocess.CalledProcessError as e:
  653. sys.exit(e.returncode)
  654. if verbose >= 3:
  655. print "Attaching temp image..."
  656. try:
  657. output = runHDIUtil("attach", dmg_name + ".temp", readwrite=True, noverify=True, noautoopen=True, capture_stdout=True)
  658. except subprocess.CalledProcessError as e:
  659. sys.exit(e.returncode)
  660. m = re.search("/Volumes/(.+$)", output)
  661. disk_root = m.group(0)
  662. disk_name = m.group(1)
  663. if verbose >= 2:
  664. print "+ Applying fancy settings +"
  665. if fancy.has_key("background_picture"):
  666. bg_path = os.path.join(disk_root, os.path.basename(fancy["background_picture"]))
  667. if verbose >= 3:
  668. print fancy["background_picture"], "->", bg_path
  669. shutil.copy2(fancy["background_picture"], bg_path)
  670. else:
  671. bg_path = None
  672. if fancy.get("applications_symlink", False):
  673. os.symlink("/Applications", os.path.join(disk_root, "Applications"))
  674. # The Python appscript package broke with OSX 10.8 and isn't being fixed.
  675. # So we now build up an AppleScript string and use the osascript command
  676. # to make the .dmg file pretty:
  677. appscript = Template( """
  678. on run argv
  679. tell application "Finder"
  680. tell disk "$disk"
  681. open
  682. set current view of container window to icon view
  683. set toolbar visible of container window to false
  684. set statusbar visible of container window to false
  685. set the bounds of container window to {$window_bounds}
  686. set theViewOptions to the icon view options of container window
  687. set arrangement of theViewOptions to not arranged
  688. set icon size of theViewOptions to $icon_size
  689. $background_commands
  690. $items_positions
  691. close -- close/reopen works around a bug...
  692. open
  693. update without registering applications
  694. delay 5
  695. eject
  696. end tell
  697. end tell
  698. end run
  699. """)
  700. itemscript = Template('set position of item "${item}" of container window to {${position}}')
  701. items_positions = []
  702. if fancy.has_key("items_position"):
  703. for name, position in fancy["items_position"].iteritems():
  704. params = { "item" : name, "position" : ",".join([str(p) for p in position]) }
  705. items_positions.append(itemscript.substitute(params))
  706. params = {
  707. "disk" : "Bitcoin-Qt",
  708. "window_bounds" : "300,300,800,620",
  709. "icon_size" : "96",
  710. "background_commands" : "",
  711. "items_positions" : "\n ".join(items_positions)
  712. }
  713. if fancy.has_key("window_bounds"):
  714. params["window.bounds"] = ",".join([str(p) for p in fancy["window_bounds"]])
  715. if fancy.has_key("icon_size"):
  716. params["icon_size"] = str(fancy["icon_size"])
  717. if bg_path is not None:
  718. # Set background file, then call SetFile to make it invisible.
  719. # (note: making it invisible first makes set background picture fail)
  720. bgscript = Template("""set background picture of theViewOptions to file "$bgpic"
  721. do shell script "SetFile -a V /Volumes/$disk/$bgpic" """)
  722. params["background_commands"] = bgscript.substitute({"bgpic" : os.path.basename(bg_path), "disk" : params["disk"]})
  723. s = appscript.substitute(params)
  724. if verbose >= 2:
  725. print("Running AppleScript:")
  726. print(s)
  727. p = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE)
  728. p.communicate(input=s)
  729. if p.returncode:
  730. print("Error running osascript.")
  731. if verbose >= 2:
  732. print "+ Finalizing .dmg disk image +"
  733. time.sleep(5)
  734. try:
  735. runHDIUtil("convert", dmg_name + ".temp", format="UDBZ", o=dmg_name + ".dmg", ov=True)
  736. except subprocess.CalledProcessError as e:
  737. sys.exit(e.returncode)
  738. os.unlink(dmg_name + ".temp.dmg")
  739. # ------------------------------------------------
  740. if verbose >= 2:
  741. print "+ Done +"
  742. sys.exit(0)