Salome HOME
Improve SALOMEDS attributes interfaces:
[modules/kernel.git] / bin / appli_gen.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 #  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
8 #  This library is free software; you can redistribute it and/or
9 #  modify it under the terms of the GNU Lesser General Public
10 #  License as published by the Free Software Foundation; either
11 #  version 2.1 of the License.
12 #
13 #  This library is distributed in the hope that it will be useful,
14 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 #  Lesser General Public License for more details.
17 #
18 #  You should have received a copy of the GNU Lesser General Public
19 #  License along with this library; if not, write to the Free Software
20 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21 #
22 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24 ## \file appli_gen.py
25 #  Create a %SALOME application (virtual Salome installation)
26 #
27 usage="""usage: %prog [options]
28 Typical use is:
29   python appli_gen.py
30 Typical use with options is:
31   python appli_gen.py --verbose --prefix=<install directory> --config=<configuration file>
32 """
33
34 import os, glob, string, sys, re
35 import shutil
36 import xml.sax
37 import optparse
38 import virtual_salome
39
40 # --- names of tags in XML configuration file
41 appli_tag   = "application"
42 prereq_tag  = "prerequisites"
43 modules_tag = "modules"
44 module_tag  = "module"
45 samples_tag = "samples"
46 resources_tag = "resources"
47
48 # --- names of attributes in XML configuration file
49 nam_att  = "name"
50 path_att = "path"
51 gui_att  = "gui"
52
53 # -----------------------------------------------------------------------------
54
55 # --- xml reader for SALOME application configuration file
56
57 class xml_parser:
58     def __init__(self, fileName ):
59         print "Configure parser: processing %s ..." % fileName
60         self.space = []
61         self.config = {}
62         self.config["modules"] = []
63         self.config["guimodules"] = []
64         parser = xml.sax.make_parser()
65         parser.setContentHandler(self)
66         parser.parse(fileName)
67         pass
68
69     def boolValue( self, str ):
70         if str in ("yes", "y", "1"):
71             return 1
72         elif str in ("no", "n", "0"):
73             return 0
74         else:
75             return str
76         pass
77
78     def startElement(self, name, attrs):
79         self.space.append(name)
80         self.current = None
81         # --- if we are analyzing "prerequisites" element then store its "path" attribute
82         if self.space == [appli_tag, prereq_tag] and path_att in attrs.getNames():
83             self.config["prereq_path"] = attrs.getValue( path_att )
84             pass
85         # --- if we are analyzing "resources" element then store its "path" attribute
86         if self.space == [appli_tag, resources_tag] and path_att in attrs.getNames():
87             self.config["resources_path"] = attrs.getValue( path_att )
88             pass
89         # --- if we are analyzing "samples" element then store its "path" attribute
90         if self.space == [appli_tag, samples_tag] and path_att in attrs.getNames():
91             self.config["samples_path"] = attrs.getValue( path_att )
92             pass
93         # --- if we are analyzing "module" element then store its "name" and "path" attributes
94         elif self.space == [appli_tag,modules_tag,module_tag] and \
95             nam_att in attrs.getNames() and \
96             path_att in attrs.getNames():
97             nam = attrs.getValue( nam_att )
98             path = attrs.getValue( path_att )
99             gui = 1
100             if gui_att in attrs.getNames():
101                 gui = self.boolValue(attrs.getValue( gui_att ))
102                 pass
103             self.config["modules"].append(nam)
104             self.config[nam]=path
105             if gui:
106                 self.config["guimodules"].append(nam)
107                 pass
108             pass
109         pass
110
111     def endElement(self, name):
112         p = self.space.pop()
113         self.current = None
114         pass
115
116     def characters(self, content):
117         pass
118
119     def processingInstruction(self, target, data):
120         pass
121
122     def setDocumentLocator(self, locator):
123         pass
124
125     def startDocument(self):
126         self.read = None
127         pass
128
129     def endDocument(self):
130         self.read = None
131         pass
132
133 # -----------------------------------------------------------------------------
134
135 class params:
136     pass
137
138 # -----------------------------------------------------------------------------
139
140 def makedirs(namedir):
141   if os.path.exists(namedir):
142     dirbak=namedir+".bak"
143     if os.path.exists(dirbak):
144       shutil.rmtree(dirbak)
145     os.rename(namedir,dirbak)
146     os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
147   os.makedirs(namedir)
148
149 def install(prefix,config_file,verbose=0):
150     home_dir=os.path.abspath(os.path.expanduser(prefix))
151     filename=os.path.abspath(os.path.expanduser(config_file))
152     _config={}
153     try:
154         p = xml_parser(filename)
155         _config = p.config
156     except xml.sax.SAXParseException, inst:
157         print inst.getMessage()
158         print "Configure parser: parse error in configuration file %s" % filename
159         pass
160     except xml.sax.SAXException, inst:
161         print inst.args
162         print "Configure parser: error in configuration file %s" % filename
163         pass
164     except:
165         print "Configure parser: Error : can not read configuration file %s, check existence and rights" % filename
166         pass
167
168     if verbose:
169         for cle in _config.keys():
170             print cle, _config[cle]
171             pass
172
173     for module in _config["modules"]:
174         print "--- add module ", module, _config[module]
175         options = params()
176         options.verbose=verbose
177         options.clear=0
178         options.prefix=home_dir
179         options.module=_config[module]
180         virtual_salome.link_module(options)
181         pass
182
183     appliskel_dir=os.path.join(home_dir,'bin','salome','appliskel')
184
185     for fn in ('envd',
186                'getAppliPath.py',
187                'searchFreePort.sh',
188                'runRemote.sh',
189                'runAppli',
190                'runConsole',
191                'runSession',
192                'runTests',
193                '.bashrc',
194                ):
195         virtual_salome.symlink("./bin/salome/appliskel/"+fn,os.path.join(home_dir, fn))
196         pass
197
198     if filename != os.path.join(home_dir,"config_appli.xml"):
199         command = "cp -p " + filename + ' ' + os.path.join(home_dir,"config_appli.xml")
200         os.system(command)
201         pass
202
203     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
204     if os.path.isfile(_config["prereq_path"]):
205         command='cp -p ' + _config["prereq_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.sh')
206         os.system(command)
207         pass
208     else:
209         print "WARNING: prerequisite file does not exist"
210         pass
211
212
213     f =open(os.path.join(home_dir,'env.d','configSalome.sh'),'w')
214     for module in _config["modules"]:
215         command='export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
216         f.write(command)
217         pass
218     if _config.has_key("samples_path"):
219         command='export DATA_DIR=' + _config["samples_path"] +'\n'
220         f.write(command)
221         pass
222     if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
223         command='export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
224         f.write(command)
225
226     f.close()
227
228
229     f =open(os.path.join(home_dir,'env.d','configGUI.sh'),'w')
230     command = 'export SalomeAppConfig=${HOME}/${APPLI}\n'
231     f.write(command)
232     command = 'export SUITRoot=${HOME}/${APPLI}/share/salome\n'
233     f.write(command)
234     f.write('export DISABLE_FPE=1\n')
235     f.write('export MMGT_REENTRANT=1\n')
236     f.close()
237
238
239     f =open(os.path.join(home_dir,'SalomeApp.xml'),'w')
240     command="""<document>
241   <section name="launch">
242     <!-- SALOME launching parameters -->
243     <parameter name="gui"        value="yes"/>
244     <parameter name="splash"     value="yes"/>
245     <parameter name="file"       value="no"/>
246     <parameter name="key"        value="no"/>
247     <parameter name="interp"     value="no"/>
248     <parameter name="logger"     value="no"/>
249     <parameter name="xterm"      value="no"/>
250     <parameter name="portkill"   value="no"/>
251     <parameter name="killall"    value="no"/>
252     <parameter name="noexcepthandler"  value="no"/>
253     <parameter name="modules"    value="""
254     f.write(command)
255     f.write('"')
256     for module in _config["guimodules"][:-1]:
257         f.write(module)
258         f.write(',')
259         pass
260     if len(_config["guimodules"]) > 0:
261       f.write(_config["guimodules"][-1])
262     f.write('"/>')
263     command="""
264     <parameter name="pyModules"  value=""/>
265     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
266     <parameter name="standalone" value="pyContainer"/>
267   </section>
268 </document>
269 """
270     f.write(command)
271     f.close()
272
273     #Add default CatalogResources.xml file
274     f =open(os.path.join(home_dir,'CatalogResources.xml'),'w')
275     command="""<!DOCTYPE ResourcesCatalog>
276 <resources>
277    <machine name="localhost"
278             hostname="localhost" />
279 </resources>
280 """
281     f.write(command)
282     f.close()
283
284     #Add USERS directory with 777 permission to store users configuration files
285     users_dir=os.path.join(home_dir,'USERS')
286     makedirs(users_dir)
287     os.chmod(users_dir, 0777)
288
289 def main():
290     parser = optparse.OptionParser(usage=usage)
291
292     parser.add_option('--prefix', dest="prefix", default='.',
293                       help="Installation directory (default .)")
294
295     parser.add_option('--config', dest="config", default='config_appli.xml',
296                       help="XML configuration file (default config_appli.xml)")
297
298     parser.add_option('-v', '--verbose', action='count', dest='verbose',
299                       default=0, help="Increase verbosity")
300
301     options, args = parser.parse_args()
302     install(prefix=options.prefix,config_file=options.config,verbose=options.verbose)
303     pass
304
305 # -----------------------------------------------------------------------------
306
307 if __name__ == '__main__':
308     main()
309     pass