Salome HOME
Small fix for Windows
[modules/kernel.git] / bin / appli_gen.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2013  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
25 ## \file appli_gen.py
26 #  Create a %SALOME application (virtual Salome installation)
27 #
28 usage="""usage: %prog [options]
29 Typical use is:
30   python appli_gen.py
31 Typical use with options is:
32   python appli_gen.py --verbose --prefix=<install directory> --config=<configuration file>
33 """
34
35 import os, glob, string, sys, re
36 import shutil
37 import xml.sax
38 import optparse
39 import virtual_salome
40
41 # --- names of tags in XML configuration file
42 appli_tag   = "application"
43 prereq_tag  = "prerequisites"
44 system_conf_tag  = "system_conf"
45 modules_tag = "modules"
46 module_tag  = "module"
47 samples_tag = "samples"
48 resources_tag = "resources"
49
50 # --- names of attributes in XML configuration file
51 nam_att  = "name"
52 path_att = "path"
53 gui_att  = "gui"
54
55 # -----------------------------------------------------------------------------
56
57 # --- xml reader for SALOME application configuration file
58
59 class xml_parser:
60     def __init__(self, fileName ):
61         print "Configure parser: processing %s ..." % fileName
62         self.space = []
63         self.config = {}
64         self.config["modules"] = []
65         self.config["guimodules"] = []
66         parser = xml.sax.make_parser()
67         parser.setContentHandler(self)
68         parser.parse(fileName)
69         pass
70
71     def boolValue( self, str ):
72         if str in ("yes", "y", "1"):
73             return 1
74         elif str in ("no", "n", "0"):
75             return 0
76         else:
77             return str
78         pass
79
80     def startElement(self, name, attrs):
81         self.space.append(name)
82         self.current = None
83         # --- if we are analyzing "prerequisites" element then store its "path" attribute
84         if self.space == [appli_tag, prereq_tag] and path_att in attrs.getNames():
85             self.config["prereq_path"] = attrs.getValue( path_att )
86             pass
87         # --- if we are analyzing "system_conf" element then store its "path" attribute
88         if self.space == [appli_tag, system_conf_tag] and path_att in attrs.getNames():
89             self.config["system_conf_path"] = attrs.getValue( path_att )
90             pass
91         # --- if we are analyzing "resources" element then store its "path" attribute
92         if self.space == [appli_tag, resources_tag] and path_att in attrs.getNames():
93             self.config["resources_path"] = attrs.getValue( path_att )
94             pass
95         # --- if we are analyzing "samples" element then store its "path" attribute
96         if self.space == [appli_tag, samples_tag] and path_att in attrs.getNames():
97             self.config["samples_path"] = attrs.getValue( path_att )
98             pass
99         # --- if we are analyzing "module" element then store its "name" and "path" attributes
100         elif self.space == [appli_tag,modules_tag,module_tag] and \
101             nam_att in attrs.getNames() and \
102             path_att in attrs.getNames():
103             nam = attrs.getValue( nam_att )
104             path = attrs.getValue( path_att )
105             gui = 1
106             if gui_att in attrs.getNames():
107                 gui = self.boolValue(attrs.getValue( gui_att ))
108                 pass
109             self.config["modules"].append(nam)
110             self.config[nam]=path
111             if gui:
112                 self.config["guimodules"].append(nam)
113                 pass
114             pass
115         pass
116
117     def endElement(self, name):
118         p = self.space.pop()
119         self.current = None
120         pass
121
122     def characters(self, content):
123         pass
124
125     def processingInstruction(self, target, data):
126         pass
127
128     def setDocumentLocator(self, locator):
129         pass
130
131     def startDocument(self):
132         self.read = None
133         pass
134
135     def endDocument(self):
136         self.read = None
137         pass
138
139 # -----------------------------------------------------------------------------
140
141 class params:
142     pass
143
144 # -----------------------------------------------------------------------------
145
146 def makedirs(namedir):
147   if os.path.exists(namedir):
148     dirbak=namedir+".bak"
149     if os.path.exists(dirbak):
150       shutil.rmtree(dirbak)
151     os.rename(namedir,dirbak)
152     os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
153   os.makedirs(namedir)
154
155 def install(prefix,config_file,verbose=0):
156     home_dir=os.path.abspath(os.path.expanduser(prefix))
157     filename=os.path.abspath(os.path.expanduser(config_file))
158     _config={}
159     try:
160         p = xml_parser(filename)
161         _config = p.config
162     except xml.sax.SAXParseException, inst:
163         print inst.getMessage()
164         print "Configure parser: parse error in configuration file %s" % filename
165         pass
166     except xml.sax.SAXException, inst:
167         print inst.args
168         print "Configure parser: error in configuration file %s" % filename
169         pass
170     except:
171         print "Configure parser: Error : can not read configuration file %s, check existence and rights" % filename
172         pass
173
174     if verbose:
175         for cle in _config.keys():
176             print cle, _config[cle]
177             pass
178
179     for module in _config["modules"]:
180         print "--- add module ", module, _config[module]
181         options = params()
182         options.verbose=verbose
183         options.clear=0
184         options.prefix=home_dir
185         options.module=_config[module]
186         virtual_salome.link_module(options)
187         pass
188
189     appliskel_dir=os.path.join(home_dir,'bin','salome','appliskel')
190
191     for fn in ('envd',
192                'getAppliPath.py',
193                'kill_remote_containers.py',
194                'runAppli',           # OBSOLETE (replaced by salome)
195                'runConsole',         # OBSOLETE (replaced by salome)
196                'runRemote.sh',
197                'runSalomeScript',
198                'runSession',         # OBSOLETE (replaced by salome)
199                'salome',
200                'update_catalogs.py',
201                '.bashrc',
202                ):
203         virtual_salome.symlink( os.path.join( appliskel_dir, fn ), os.path.join( home_dir, fn) )
204         pass
205
206     if filename != os.path.join(home_dir,"config_appli.xml"):
207         command = "cp -p " + filename + ' ' + os.path.join(home_dir,"config_appli.xml")
208         os.system(command)
209         pass
210
211     # Creation of env.d directory
212     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
213     if os.path.isfile(_config["prereq_path"]):
214         command='cp -p ' + _config["prereq_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.sh')
215         os.system(command)
216         pass
217     else:
218         print "WARNING: prerequisite file does not exist"
219         pass
220     # :NOTE: For the new launch procedure, we do not use a "physical" .cfg
221     # file for prerequisites; the launch procedure automatically reads and
222     # converts the envProducts.sh file.
223
224     if _config.has_key("system_conf_path") and os.path.isfile(_config["system_conf_path"]):
225         command='cp -p ' + _config["system_conf_path"] + ' ' + os.path.join(home_dir,'env.d','envConfSystem.sh')
226         os.system(command)
227         pass
228
229     # Create environment file: configSalome.sh
230     f =open(os.path.join(home_dir,'env.d','configSalome.sh'),'w')
231     for module in _config["modules"]:
232         command='export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
233         f.write(command)
234         pass
235     if _config.has_key("samples_path"):
236         command='export DATA_DIR=' + _config["samples_path"] +'\n'
237         f.write(command)
238         pass
239     if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
240         command='export USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
241         f.write(command)
242
243     f.close()
244
245     # Create configuration file: configSalome.cfg
246     f =open(os.path.join(home_dir,'env.d','configSalome.cfg'),'w')
247     command = "[SALOME ROOT_DIR (modules) Configuration]\n"
248     f.write(command)
249     for module in _config["modules"]:
250         command=module + '_ROOT_DIR=${HOME}/${APPLI}\n'
251         f.write(command)
252         pass
253     if _config.has_key("samples_path"):
254         command='DATA_DIR=' + _config["samples_path"] +'\n'
255         f.write(command)
256         pass
257     if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
258         command='USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
259         f.write(command)
260
261     f.close()
262
263
264     # Create environment file: configGUI.sh
265     f =open(os.path.join(home_dir,'env.d','configGUI.sh'),'w')
266     command = """export SalomeAppConfig=${HOME}/${APPLI}
267 export SUITRoot=${HOME}/${APPLI}/share/salome
268 export DISABLE_FPE=1
269 export MMGT_REENTRANT=1
270 """
271     f.write(command)
272     f.close()
273
274     # Create configuration file: configGUI.cfg
275     f =open(os.path.join(home_dir,'env.d','configGUI.cfg'),'w')
276     command = """[SALOME GUI Configuration]
277 SalomeAppConfig=${HOME}/${APPLI}
278 SUITRoot=${HOME}/${APPLI}/share/salome
279 DISABLE_FPE=1
280 MMGT_REENTRANT=1
281 """
282     f.write(command)
283     f.close()
284
285     #SalomeApp.xml file
286     f =open(os.path.join(home_dir,'SalomeApp.xml'),'w')
287     command="""<document>
288   <section name="launch">
289     <!-- SALOME launching parameters -->
290     <parameter name="gui"        value="yes"/>
291     <parameter name="splash"     value="yes"/>
292     <parameter name="file"       value="no"/>
293     <parameter name="key"        value="no"/>
294     <parameter name="interp"     value="no"/>
295     <parameter name="logger"     value="no"/>
296     <parameter name="xterm"      value="no"/>
297     <parameter name="portkill"   value="no"/>
298     <parameter name="killall"    value="no"/>
299     <parameter name="noexcepthandler"  value="no"/>
300     <parameter name="modules"    value="%s"/>
301     <parameter name="pyModules"  value=""/>
302     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
303     <parameter name="standalone" value="pyContainer"/>
304   </section>
305 </document>
306 """
307     mods=[]
308     #Keep all modules except KERNEL and GUI
309     for m in _config["modules"]:
310       if m in ("KERNEL","GUI"):continue
311       mods.append(m)
312     f.write(command % ",".join(mods))
313     f.close()
314
315     #Add USERS directory with 777 permission to store users configuration files
316     users_dir=os.path.join(home_dir,'USERS')
317     makedirs(users_dir)
318     os.chmod(users_dir, 0777)
319
320 def main():
321     parser = optparse.OptionParser(usage=usage)
322
323     parser.add_option('--prefix', dest="prefix", default='.',
324                       help="Installation directory (default .)")
325
326     parser.add_option('--config', dest="config", default='config_appli.xml',
327                       help="XML configuration file (default config_appli.xml)")
328
329     parser.add_option('-v', '--verbose', action='count', dest='verbose',
330                       default=0, help="Increase verbosity")
331
332     options, args = parser.parse_args()
333     if not os.path.exists(options.config):
334       print "ERROR: config file %s does not exist. It is mandatory." % options.config
335       sys.exit(1)
336
337     install(prefix=options.prefix,config_file=options.config,verbose=options.verbose)
338     pass
339
340 # -----------------------------------------------------------------------------
341
342 if __name__ == '__main__':
343     main()
344     pass