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