xref: /petsc/systems/Apple/iOS/bin/iosbuilder.py (revision 9895aa37ac365bac650f6bd8bf977519f7222510)
1#!/usr/bin/env python
2#
3#   Builds a iPhone/iPad static library of PETSc
4#
5#   Before using removed /usr/include/mpi.h and /Developer/SDKs/MacOSX10.5.sdk/usr/include/mpi.h or
6#      Xcode will use those instead of the MPIuni one we point to
7#
8#   export PETSC_ARCH=arch-ios
9
10#   ./systems/Apple/iOS/bin/arch-ios.py [use --with-debugging=0 to get iPhone/iPad version, otherwise creates simulator version]
11#      this sets up the appropriate configuration file
12#
13#   ./systems/Apple/iOS/bin/iosbuilder.py
14#      this creates the PETSc iPhone/iPad library
15#      this will open Xcode and give you directions to follow
16#
17#   open xcode/examples/examples.xcodeproj
18#       Project -> Edit Project Setting  -> Configuration (make sure it is Release or Debug depending on if you used --with-debugging=0)
19#       Build -> Build and Debug
20#
21import os, sys
22
23sys.path.insert(0, os.path.join(os.environ['PETSC_DIR'], 'config'))
24sys.path.insert(0, os.path.join(os.environ['PETSC_DIR'], 'config', 'BuildSystem'))
25
26import script
27
28class PETScMaker(script.Script):
29 def __init__(self):
30   import RDict
31   import os
32
33   argDB = RDict.RDict(None, None, 0, 0, readonly = True)
34   argDB.saveFilename = os.path.join(os.environ['PETSC_DIR'], os.environ['PETSC_ARCH'], 'conf', 'RDict.db')
35   argDB.load()
36   script.Script.__init__(self, argDB = argDB)
37   self.log = sys.stdout
38   return
39
40 def setupModules(self):
41   self.mpi           = self.framework.require('config.packages.MPI',         None)
42   self.base          = self.framework.require('config.base',                 None)
43   self.setCompilers  = self.framework.require('config.setCompilers',         None)
44   self.arch          = self.framework.require('PETSc.utilities.arch',        None)
45   self.petscdir      = self.framework.require('PETSc.utilities.petscdir',    None)
46   self.languages     = self.framework.require('PETSc.utilities.languages',   None)
47   self.debugging     = self.framework.require('PETSc.utilities.debugging',   None)
48   self.make          = self.framework.require('config.programs',             None)
49   self.compilers     = self.framework.require('config.compilers',            None)
50   self.types         = self.framework.require('config.types',                None)
51   self.headers       = self.framework.require('config.headers',              None)
52   self.functions     = self.framework.require('config.functions',            None)
53   self.libraries     = self.framework.require('config.libraries',            None)
54   self.scalarType    = self.framework.require('PETSc.utilities.scalarTypes', None)
55   self.memAlign      = self.framework.require('PETSc.utilities.memAlign',    None)
56   self.libraryOptions= self.framework.require('PETSc.utilities.libraryOptions', None)
57   self.compilerFlags = self.framework.require('config.compilerFlags', self)
58   return
59
60 def setupHelp(self, help):
61   import nargs
62
63   help = script.Script.setupHelp(self, help)
64   help.addArgument('RepManager', '-rootDir', nargs.ArgDir(None, os.environ['PETSC_DIR'], 'The root directory for this build', isTemporary = 1))
65   help.addArgument('RepManager', '-dryRun',  nargs.ArgBool(None, False, 'Only output what would be run', isTemporary = 1))
66   help.addArgument('RepManager', '-skipXCode',  nargs.ArgBool(None, False, 'Do not run XCode application/files have not been added/removed', isTemporary = 1))
67   help.addArgument('RepManager', '-verbose', nargs.ArgInt(None, 0, 'The verbosity level', min = 0, isTemporary = 1))
68   return help
69
70 def setup(self):
71   script.Script.setup(self)
72   self.framework = self.loadConfigure()
73   self.setupModules()
74   return
75
76 @property
77 def verbose(self):
78   '''The verbosity level'''
79   return self.argDB['verbose']
80
81 @property
82 def skipXCode(self):
83   '''Skip XCode application'''
84   return self.argDB['skipXCode']
85
86 @property
87 def dryRun(self):
88   '''Flag for only output of what would be run'''
89   return self.argDB['dryRun']
90
91 def getPackageInfo(self):
92   packageIncludes = []
93   packageLibs     = []
94   for p in self.framework.packages:
95     # Could put on compile line, self.addDefine('HAVE_'+i.PACKAGE, 1)
96     if hasattr(p, 'lib'):
97       if not isinstance(p.lib, list):
98         packageLibs.append(p.lib)
99       else:
100         packageLibs.extend(p.lib)
101     if hasattr(p, 'include'):
102       if not isinstance(p.include, list):
103         packageIncludes.append(p.include)
104       else:
105         packageIncludes.extend(p.include)
106   packageLibs     = self.libraries.toStringNoDupes(packageLibs+self.libraries.math)
107   packageIncludes = self.headers.toStringNoDupes(packageIncludes)
108   return packageIncludes, packageLibs
109
110 def buildDir(self, dirname):
111   ''' This is run in a PETSc source directory'''
112   if self.verbose: print 'Entering '+dirname
113   os.chdir(dirname)
114   l = len(os.environ['PETSC_DIR'])
115   basedir = os.path.join(os.environ['PETSC_DIR'],os.environ['PETSC_ARCH'],'xcode-links')
116   #newdirname = os.path.join(basedir,dirname[l+1:])
117   #os.mkdir(newdirname)
118
119
120   # Get list of source files in the directory
121   cnames = []
122   onames = []
123   fnames = []
124   hnames = []
125   for f in os.listdir(dirname):
126     ext = os.path.splitext(f)[1]
127     if ext == '.c':
128       cnames.append(f)
129       onames.append(f.replace('.c', '.o'))
130     if ext == '.h':
131       hnames.append(f)
132   if cnames:
133     if self.verbose: print 'Linking C files',cnames
134     for i in cnames:
135       j = i[l+1:]
136       if not os.path.islink(os.path.join(basedir,i)) and not i.startswith('.'):
137         if i.endswith('openglops.c') and not os.path.islink(os.path.join(basedir,'openglops.m')):
138           os.symlink(os.path.join(dirname,i),os.path.join(basedir,'openglops.m'))
139         else:
140           os.symlink(os.path.join(dirname,i),os.path.join(basedir,i))
141   # do not need to link these because xcode project points to original source code directory
142   #if hnames:
143   #  if self.verbose: print 'Linking h files',hnames
144   #  for i in hnames:
145   #    if not os.path.islink(os.path.join(basedir,i)):
146   #      os.symlink(os.path.join(dirname,i),os.path.join(basedir,i))
147   return
148
149 def checkDir(self, dirname):
150   '''Checks whether we should recurse into this directory
151   - Excludes projects directory
152   - Excludes examples directory
153   - Excludes contrib directory
154   - Excludes tutorials directory
155   - Excludes benchmarks directory
156   - Checks makefile to see if compiler is allowed to visit this directory for this configuration'''
157#   print self.functions.functions
158#   print self.base.defines
159   base = os.path.basename(dirname)
160
161   if base == 'examples': return False
162   if base == 'projects': return False
163   if base.startswith('ftn-') or base.startswith('f90-'): return False
164   if base == 'contrib':  return False
165   if base == 'tutorials':  return False
166   if base == 'benchmarks':  return False
167   if base == 'systems':  return False
168   if base.startswith('arch-'):  return False
169
170   import re
171   reg   = re.compile(' [ ]*')
172   fname = os.path.join(dirname, 'makefile')
173   if not os.path.isfile(fname):
174     if os.path.isfile(os.path.join(dirname, 'Makefile')): print 'ERROR: Change Makefile to makefile in',dirname
175     return False
176   fd = open(fname)
177   text = fd.readline()
178   while text:
179     if text.startswith('#requires'):
180       text = text[9:-1].strip()
181       text = reg.sub(' ',text)
182       rtype = text.split(' ')[0]
183       rvalue = text.split(' ')[1]
184
185       if rvalue == "'"+'PETSC_HAVE_FORTRAN'+"'" or rvalue == "'"+'PETSC_USING_F90'+"'" or rvalue == "'"+'PETSC_USING_F2003'+"'":
186         if not hasattr(self.compilers, 'FC'):
187           if self.verbose: print 'Rejecting',dirname,'because fortran is not being used'
188           return 0
189       elif rvalue == "'"+'PETSC_USE_LOG'+"'":
190         if not self.libraryOptions.useLog:
191           if self.verbose: print 'Rejecting',dirname,'because logging is turned off'
192           return 0
193       elif rvalue == "'"+'PETSC_USE_FORTRAN_KERNELS'+"'":
194         if not self.libraryOptions.useFortranKernels:
195           if self.verbose: print 'Rejecting',dirname,'because fortran kernels are turned off'
196           return 0
197       elif rtype == 'scalar' and not self.scalarType.scalartype == rvalue:
198         if self.verbose: print 'Rejecting',dirname,'because scalar type '+self.scalarType.scalartype+' is not '+rvalue
199         return 0
200       elif rtype == 'language':
201         if rvalue == 'CXXONLY' and self.languages.clanguage == 'C':
202           if self.verbose: print 'Rejecting',dirname,'because language is '+self.languages.clanguage+' is not C++'
203           return 0
204       elif rtype == 'precision' and not rvalue == self.scalarType.precision:
205         if self.verbose: print 'Rejecting',dirname,'because precision '+self.scalarType.precision+' is not '+rvalue
206         return 0
207       elif rtype == 'package':
208         found = 0
209         if self.mpi.usingMPIUni:
210           pname = 'PETSC_HAVE_MPIUNI'
211           pname = "'"+pname+"'"
212           if pname == rvalue: found = 1
213         for i in self.framework.packages:
214           pname = 'PETSC_HAVE_'+i.PACKAGE
215           pname = "'"+pname+"'"
216           if pname == rvalue: found = 1
217         if not found:
218           if self.verbose: print 'Rejecting',dirname,'because package '+rvalue+' does not exist'
219           return 0
220       elif rtype == 'define':
221         found = 0
222         for i in self.base.defines:
223           pname = 'PETSC_'+i.upper()
224           pname = "'"+pname+"'"
225           if pname == rvalue: found = 1
226         if not found:
227           if self.verbose: print 'Rejecting',dirname,'because define '+rvalue+' does not exist'
228           return 0
229       elif rtype == 'function':
230         found = 0
231         for i in self.functions.functions:
232           pname = 'PETSC_HAVE_'+i.upper()
233           pname = "'"+pname+"'"
234#           print pname
235#           print rvalue
236           if pname == rvalue: found = 1
237         if not found:
238           if self.verbose: print 'Rejecting',dirname,'because function '+rvalue+' does not exist'
239           return 0
240
241     text = fd.readline()
242   fd.close()
243   return True
244
245 def buildAll(self, rootDir = None):
246   import shutil
247   self.setup()
248   if rootDir is None:
249     rootDir = self.argDB['rootDir']
250   if not self.checkDir(rootDir):
251     print 'Nothing to be done'
252   if rootDir == os.environ['PETSC_DIR']:
253     basedir = os.path.join(self.petscdir.dir, self.arch.arch, 'xcode-links')
254     if os.path.isdir(basedir):
255       if self.verbose: print 'Removing '+basedir
256       shutil.rmtree(basedir)
257   os.mkdir(basedir)
258   for root, dirs, files in os.walk(rootDir):
259     self.buildDir(root)
260     for badDir in [d for d in dirs if not self.checkDir(os.path.join(root, d))]:
261       dirs.remove(badDir)
262
263   if not self.skipXCode:
264
265     print 'In Xcode mouse click on xcode-links and the delete key, then'
266     print 'control mouse click on "Other Sources" and select "Add files to PETSc ...", then'
267     print 'in the finder window locate ${PETSC_DIR}/arch-ios/xcode-links and select it. Now'
268     print 'exit Xcode'
269
270     try:
271       import subprocess
272       subprocess.call('cd '+os.path.join(os.environ['PETSC_DIR'],'systems','Apple','iOS','PETSc')+';open -W PETSc.xcodeproj', shell=True)
273     except RuntimeError, e:
274       raise RuntimeError('Error opening xcode project '+str(e))
275
276
277   sdk         = ' -sdk iphonesimulator5.1 '
278   destination = 'iphonesimulator'
279   debug       = 'Debug'
280   debugdir    = 'Debug-'+destination
281   if not self.compilerFlags.debugging:
282     debug = 'Release'
283     debugdir = 'Release-'+destination
284   try:
285     output,err,ret  = self.executeShellCommand('cd '+os.path.join(os.environ['PETSC_DIR'],'systems','Apple','iOS','PETSc')+';xcodebuild -configuration '+debug+sdk, timeout=3000, log = self.log)
286   except RuntimeError, e:
287     raise RuntimeError('Error making iPhone/iPad version of PETSc libraries: '+str(e))
288
289   liblocation = os.path.join(os.environ['PETSC_DIR'],'systems','Apple','iOS','PETSc','build',debugdir,'libPETSc.a')
290   if not os.path.exists(liblocation):
291     raise RuntimeError('Error library '+liblocation+' not created')
292   try:
293     output,err,ret  = self.executeShellCommand('mv -f '+liblocation+' '+os.path.join(os.environ['PETSC_DIR'],os.environ['PETSC_ARCH'],'lib'), timeout=30, log = self.log)
294   except RuntimeError, e:
295     raise RuntimeError('Error copying iPhone/iPad version of PETSc libraries: '+str(e))
296
297   return
298
299def noCheckCommand(command, status, output, error):
300  ''' Do no check result'''
301  return
302  noCheckCommand = staticmethod(noCheckCommand)
303
304if __name__ == '__main__':
305  PETScMaker().buildAll()
306