Merge pull request #136 from sandsmark/sonnet
[quassel.git] / scripts / build / macosx_DeployApp.py
1 #!/usr/bin/python
2 # -*- coding: iso-8859-1 -*-
3
4 ################################################################################
5 #                                                                              #
6 # 2008 June 27th by Marcus 'EgS' Eggenberger <egs@quassel-irc.org>             #
7 #                                                                              #
8 # The author disclaims copyright to this source code.                          #
9 # This Python Script is in the PUBLIC DOMAIN.                                  #
10 #                                                                              #
11 ################################################################################
12
13 # ==============================
14 #  Imports
15 # ==============================
16 import sys
17 import os
18 import os.path
19
20 from subprocess import Popen, PIPE
21
22 # ==============================
23 #  Constants
24 # ==============================
25 QT_CONFIG = """[Paths]
26  Plugins = plugins
27 """
28
29 QT_CONFIG_NOBUNDLE = """[Paths]
30  Prefix = ../
31  Plugins = plugins
32 """
33
34
35 class InstallQt(object):
36     def __init__(self, appdir, bundle=True, requestedPlugins=[]):
37         self.appDir = appdir
38         self.bundle = bundle
39         self.frameworkDir = self.appDir + "/Frameworks"
40         self.pluginDir = self.appDir + "/plugins"
41         self.executableDir = self.appDir
42         if bundle:
43             self.executableDir += "/MacOS"
44
45         self.installedFrameworks = set()
46
47         self.findFrameworkPath()
48
49         executables = [self.executableDir + "/" + executable for executable in os.listdir(self.executableDir)]
50         for executable in executables:
51             self.resolveDependancies(executable)
52
53         self.findPluginsPath()
54         self.installPlugins(requestedPlugins)
55         self.installQtConf()
56
57     def qtProperty(self, qtProperty):
58         """
59         Query persistent property of Qt via qmake
60         """
61         VALID_PROPERTIES = ['QT_INSTALL_PREFIX',
62                             'QT_INSTALL_DATA',
63                             'QT_INSTALL_DOCS',
64                             'QT_INSTALL_HEADERS',
65                             'QT_INSTALL_LIBS',
66                             'QT_INSTALL_BINS',
67                             'QT_INSTALL_PLUGINS',
68                             'QT_INSTALL_IMPORTS',
69                             'QT_INSTALL_TRANSLATIONS',
70                             'QT_INSTALL_CONFIGURATION',
71                             'QT_INSTALL_EXAMPLES',
72                             'QT_INSTALL_DEMOS',
73                             'QMAKE_MKSPECS',
74                             'QMAKE_VERSION',
75                             'QT_VERSION'
76                             ]
77         if qtProperty not in VALID_PROPERTIES:
78             return None
79
80         qmakeProcess = Popen('qmake -query %s' % qtProperty, shell=True, stdout=PIPE, stderr=PIPE)
81         result = qmakeProcess.stdout.read().strip()
82         qmakeProcess.stdout.close()
83         qmakeProcess.wait()
84         return result
85
86     def findFrameworkPath(self):
87         self.sourceFrameworkPath = self.qtProperty('QT_INSTALL_LIBS')
88
89     def findPluginsPath(self):
90         self.sourcePluginsPath = self.qtProperty('QT_INSTALL_PLUGINS')
91
92     def findPlugin(self, pluginname):
93         qmakeProcess = Popen('find %s -name %s' % (self.sourcePluginsPath, pluginname), shell=True, stdout=PIPE, stderr=PIPE)
94         result = qmakeProcess.stdout.read().strip()
95         qmakeProcess.stdout.close()
96         qmakeProcess.wait()
97         if not result:
98             raise OSError
99         return result
100
101     def installPlugins(self, requestedPlugins):
102         try:
103             os.mkdir(self.pluginDir)
104         except:
105             pass
106
107         for plugin in requestedPlugins:
108             if not plugin.isalnum():
109                 print "Skipping library '%s'..." % plugin
110                 continue
111
112             pluginName = "lib%s.dylib" % plugin
113             pluginSource = ''
114             try:
115                 pluginSource = self.findPlugin(pluginName)
116             except OSError:
117                 print "WARNING: Requested library does not exist: '%s'" % plugin
118                 continue
119
120             pluginSubDir = os.path.dirname(pluginSource)
121             pluginSubDir = pluginSubDir.replace(self.sourcePluginsPath, '').strip('/')
122             try:
123                 os.mkdir("%s/%s" % (self.pluginDir, pluginSubDir))
124             except OSError:
125                 pass
126
127             os.system('cp "%s" "%s/%s"' % (pluginSource, self.pluginDir, pluginSubDir))
128
129             self.resolveDependancies("%s/%s/%s" % (self.pluginDir, pluginSubDir, pluginName))
130
131     def installQtConf(self):
132         qtConfName = self.appDir + "/qt.conf"
133         qtConfContent = QT_CONFIG_NOBUNDLE
134         if self.bundle:
135             qtConfContent = QT_CONFIG
136             qtConfName = self.appDir + "/Resources/qt.conf"
137
138         qtConf = open(qtConfName, 'w')
139         qtConf.write(qtConfContent)
140         qtConf.close()
141
142     def resolveDependancies(self, obj):
143         # obj must be either an application binary or a framework library
144         # print "resolving deps for:", obj
145         for framework, lib in self.determineDependancies(obj):
146             self.installFramework(framework)
147             self.changeDylPath(obj, framework, lib)
148
149     def installFramework(self, framework):
150         # skip if framework is already installed.
151         if framework in self.installedFrameworks:
152             return
153
154         self.installedFrameworks.add(framework)
155
156         # ensure that the framework directory exists
157         try:
158             os.mkdir(self.frameworkDir)
159         except:
160             pass
161
162         if not framework.startswith('/'):
163             framework = "%s/%s" % (self.sourceFrameworkPath, framework)
164
165         # Copy Framework
166         os.system('cp -R "%s" "%s"' % (framework, self.frameworkDir))
167
168         frameworkname = framework.split('/')[-1]
169         localframework = self.frameworkDir + "/" + frameworkname
170
171         # De-Myllify
172         os.system('find "%s" -name *debug* -exec rm -f {} \;' % localframework)
173         os.system('find "%s" -name Headers -exec rm -rf {} \; 2>/dev/null' % localframework)
174
175         # Install new Lib ID and Change Path to Frameworks for the Dynamic linker
176         for lib in os.listdir(localframework + "/Versions/Current"):
177             lib = "%s/Versions/Current/%s" % (localframework, lib)
178             otoolProcess = Popen('otool -D "%s"' % lib, shell=True, stdout=PIPE, stderr=PIPE)
179             try:
180                 libname = [line for line in otoolProcess.stdout][1].strip()
181             except:
182                 libname = ''
183             otoolProcess.stdout.close()
184             if otoolProcess.wait() == 1:  # we found some Resource dir or similar -> skip
185                 continue
186             frameworkpath, libpath = libname.split(frameworkname)
187             if self.bundle:
188                 newlibname = "@executable_path/../%s%s" % (frameworkname, libpath)
189             else:
190                 newlibname = "@executable_path/%s%s" % (frameworkname, libpath)
191             # print 'install_name_tool -id "%s" "%s"' % (newlibname, lib)
192             os.system('install_name_tool -id "%s" "%s"' % (newlibname, lib))
193
194             self.resolveDependancies(lib)
195
196     def determineDependancies(self, app):
197         otoolPipe = Popen('otool -L "%s"' % app, shell=True, stdout=PIPE).stdout
198         otoolOutput = [line for line in otoolPipe]
199         otoolPipe.close()
200         libs = [line.split()[0] for line in otoolOutput[1:] if ("Qt" in line or "phonon" in line) and "@executable_path" not in line]
201         frameworks = [lib[:lib.find(".framework") + len(".framework")] for lib in libs]
202         frameworks = [framework[framework.rfind('/') + 1:] for framework in frameworks]
203         return zip(frameworks, libs)
204
205     def changeDylPath(self, obj, framework, lib):
206         newlibname = framework + lib.split(framework)[1]
207         if self.bundle:
208             newlibname = "@executable_path/../Frameworks/%s" % newlibname
209         else:
210             newlibname = "@executable_path/Frameworks/%s" % newlibname
211
212         # print 'install_name_tool -change "%s" "%s" "%s"' % (lib, newlibname, obj)
213         os.system('install_name_tool -change "%s" "%s" "%s"' % (lib, newlibname, obj))
214
215 if __name__ == "__main__":
216     if len(sys.argv) < 2:
217         print "Wrong Argument Count (Syntax: %s [--nobundle] [--plugins=plugin1,plugin2,...] $TARGET_APP)" % sys.argv[0]
218         sys.exit(1)
219     else:
220         bundle = True
221         plugins = []
222         offset = 1
223
224         while offset < len(sys.argv) and sys.argv[offset].startswith("--"):
225             if sys.argv[offset] == "--nobundle":
226                 bundle = False
227
228             if sys.argv[offset].startswith("--plugins="):
229                 plugins = sys.argv[offset].split('=')[1].split(',')
230
231             offset += 1
232
233         targetDir = sys.argv[offset]
234         if bundle:
235             targetDir += "/Contents"
236
237         InstallQt(targetDir, bundle, plugins)