Salome HOME
Fix Salome launch when there are config files named SalomeApprc.DEV.7 for instance
[modules/kernel.git] / bin / launchConfigureParser.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2015  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, or (at your option) any later version.
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
24 import os, glob, string, sys, re
25 import xml.sax
26 import optparse
27 import types
28
29 from salome_utils import verbose, getPortNumber, getHomeDir
30
31 # names of tags in XML configuration file
32 doc_tag = "document"
33 sec_tag = "section"
34 par_tag = "parameter"
35 import_tag = "import"
36
37 # names of attributes in XML configuration file
38 nam_att = "name"
39 val_att = "value"
40
41 # certain values in XML configuration file ("launch" section)
42 lanch_nam      = "launch"
43 help_nam       = "help"
44 gui_nam        = "gui"
45 splash_nam     = "splash"
46 logger_nam     = "logger"
47 xterm_nam      = "xterm"
48 file_nam       = "file"
49 portkill_nam   = "portkill"
50 killall_nam    = "killall"
51 modules_nam    = "modules"
52 embedded_nam   = "embedded"
53 standalone_nam = "standalone"
54 key_nam        = "key"
55 terminal_nam   = "terminal"
56 interp_nam     = "interp"
57 except_nam     = "noexcepthandler"
58 terminal_nam   = "terminal"
59 pinter_nam     = "pinter"
60 batch_nam      = "batch"
61 test_nam       = "test"
62 play_nam       = "play"
63 gdb_session_nam = "gdb_session"
64 ddd_session_nam = "ddd_session"
65 valgrind_session_nam = "valgrind_session"
66 shutdown_servers_nam = "shutdown_servers"
67 foreground_nam = "foreground"
68 wake_up_session_nam = "wake_up_session"
69 siman_nam = "siman"
70 siman_study_nam = "siman_study"
71 siman_scenario_nam = "siman_scenario"
72 siman_user_nam = "siman_user"
73
74 # values in XML configuration file giving specific module parameters (<module_name> section)
75 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
76 plugins_nam    = "plugins"
77
78 # values passed as arguments, NOT read from XML config file, but set from within this script
79 appname_nam    = "appname"
80 port_nam       = "port"
81 useport_nam    = "useport"
82 salomecfgname  = "salome"
83 salomeappname  = "SalomeApp"
84 script_nam     = "pyscript"
85
86 # possible choices for the "embedded" and "standalone" parameters
87 embedded_choices   = [ "registry", "study", "moduleCatalog", "cppContainer", "SalomeAppEngine" ]
88 standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer"]
89
90 # values of boolean type (must be '0' or '1').
91 # xml_parser.boolValue() is used for correct setting
92 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam, shutdown_servers_nam )
93 intKeys = ( interp_nam, )
94
95 # values of list type
96 listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
97
98 ###
99 # Get the application version
100 # Uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION file
101 ###
102 def version():
103     try:
104         filename = None
105         root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
106         version_file = os.path.join(root_dir, 'bin', 'salome', 'VERSION')
107         if root_dir and os.path.exists( version_file ):
108             filename = version_file
109         root_dir = os.environ.get( 'GUI_ROOT_DIR', '' )    # GUI_ROOT_DIR "" if not found
110         version_file = os.path.join(root_dir, 'bin', 'salome', 'VERSION')
111         if root_dir and os.path.exists( version_file ):
112             filename = version_file
113         if filename:
114             str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
115             match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
116             if match :
117                 return match.group( 1 )
118     except:
119         pass
120     return ''
121
122 ###
123 # Calculate and return configuration file unique ID
124 # For example: for SALOME version 3.1.0a1 the id is 300999701
125 ###
126 def version_id(fname):
127     major = minor = release = dev1 = dev2 = 0
128     vers = fname.split(".")
129     if len(vers) > 0:
130       try:
131         major = int(vers[0])
132       except ValueError:
133         # If salome version given is DEV, the call to int('DEV') will fail with
134         # a ValueError exception
135         pass
136     try:
137       if len(vers) > 1: minor = int(vers[1])
138     except ValueError:
139       # If salome version given is 7.DEV, the call to int('DEV') will fail with
140       # a ValueError exception
141       pass
142     if len(vers) > 2:
143         mr = re.search(r'^([0-9]+)([A-Z]|RC)?([0-9]*)',vers[2], re.I)
144         if mr:
145             release = int(mr.group(1))
146             if mr.group(2):
147                 tag = mr.group(2).strip().lower()
148                 if tag == "rc":
149                     dev1 = 49 # release candidate
150                 elif tag:
151                     dev1 = ord(tag)-ord('a')+1
152                 pass
153             if mr.group(3):
154                 dev2 = int(mr.group(3).strip())
155             pass
156         pass
157     dev = dev1 * 100 + dev2
158     ver = major
159     ver = ver * 100 + minor
160     ver = ver * 100 + release
161     ver = ver * 10000
162     if dev > 0: ver = ver - dev
163     return ver
164
165 ###
166 # Get default user configuration file name
167 # For SALOME, it is:
168 # - on Linux:   ~/.config/salome/SalomeApprc[.<version>]
169 # - on Windows: ~/SalomeApp.xml[.<version>]
170 # where <version> is an optional version number
171 ###
172 def defaultUserFile(appname=salomeappname, cfgname=salomecfgname):
173     v = version()
174     filetmpl = sys.platform == "win32" and "{0}.xml.{1}" or "{0}rc.{1}"
175     paths = []
176     paths.append(getHomeDir())
177     paths.append(".config")
178     if cfgname: paths.append(cfgname)
179     paths.append(filetmpl.format(appname, v))
180     return os.path.join(*paths)
181
182 ###
183 # Get user configuration file name
184 ###
185 def userFile(appname, cfgname):
186     # get app version
187     v = version()
188     if not v: return None                        # unknown version
189
190     # get default user file name
191     filename = defaultUserFile(appname, cfgname)
192     if not filename: return None                 # default user file name is bad
193
194     # check that default user file exists
195     if os.path.exists(filename): return filename # user file is found
196
197     # otherwise try to detect any appropriate user file
198
199     # ... calculate default version id
200     id0 = version_id(v)
201     if not id0: return None                      # bad version id -> can't detect appropriate file
202
203     # ... get all existing user preferences files
204     filetmpl1 = sys.platform == "win32" and "{0}.xml.*" or "{0}rc.*"
205     filetmpl2 = sys.platform == "win32" and filetmpl1 or "." + filetmpl1
206     files = []
207     if cfgname:
208         # Since v6.6.0 - in ~/.config/salome directory, without dot prefix
209         files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, filetmpl1.format(appname)))
210         # Since v6.5.0 - in ~/.config/salome directory, dot-prefixed (backward compatibility)
211         if filetmpl2 and filetmpl2 != filetmpl1:
212             files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, filetmpl2.format(appname)))
213         pass
214     # old style (before v6.5.0) - in ~ directory, dot-prefixed
215     if filetmpl2 and filetmpl2 != filetmpl1:
216         files += glob.glob(os.path.join(getHomeDir(), filetmpl2.format(appname)))
217     pass
218
219     # ... loop through all files and find most appopriate file (with closest id)
220     appr_id   = -1
221     appr_file = ""
222     for f in files:
223         ff = os.path.basename( f )
224         if sys.platform == "win32":
225             match = re.search( r'^{0}\.xml\.([a-zA-Z0-9.]+)$'.format(appname), ff )
226         else:
227             match = re.search( r'^\.?{0}rc\.([a-zA-Z0-9.]+)$'.format(appname), ff )
228         if match:
229             ver = version_id(match.group(1))
230             if not ver: continue                 # bad version id -> skip file
231             if appr_id < 0 or abs(appr_id-id0) > abs(ver-id0):
232                 appr_id   = ver
233                 appr_file = f
234                 pass
235             elif abs(appr_id-id0) == abs(ver-id0):
236                 if not os.path.basename(f).startswith("."): appr_file = f
237                 pass
238             pass
239         pass
240     return appr_file
241
242 # --
243
244 def process_containers_params( standalone, embedded ):
245     # 1. filter inappropriate containers names
246     if standalone is not None:
247         standalone = filter( lambda x: x in standalone_choices, standalone )
248     if embedded is not None:
249         embedded   = filter( lambda x: x in embedded_choices,   embedded )
250
251     # 2. remove containers appearing in 'standalone' parameter from the 'embedded'
252     # parameter --> i.e. 'standalone' parameter has higher priority
253     if standalone is not None and embedded is not None:
254         embedded = filter( lambda x: x not in standalone, embedded )
255
256     # 3. return corrected parameters values
257     return standalone, embedded
258
259 # -----------------------------------------------------------------------------
260
261 ###
262 # XML reader for launch configuration file usage
263 ###
264
265 section_to_skip = ""
266
267 class xml_parser:
268     def __init__(self, fileName, _opts, _importHistory):
269         #warning _importHistory=[] is NOT good: is NOT empty,reinitialized after first call
270         if verbose(): print "Configure parser: processing %s ..." % fileName
271         self.fileName = os.path.abspath(fileName)
272         self.importHistory = _importHistory
273         self.importHistory.append(self.fileName)
274         self.space = []
275         self.opts = _opts
276         self.section = section_to_skip
277         parser = xml.sax.make_parser()
278         parser.setContentHandler(self)
279         parser.parse(fileName)
280         standalone, embedded = process_containers_params( self.opts.get( standalone_nam ),
281                                                           self.opts.get( embedded_nam ) )
282         if standalone is not None:
283             self.opts[ standalone_nam ] = standalone
284         if embedded is not None:
285             self.opts[ embedded_nam ] = embedded
286         pass
287
288     def boolValue( self, str ):
289         strloc = str
290         if isinstance(strloc, types.UnicodeType):
291             strloc = strloc.encode().strip()
292         if isinstance(strloc, types.StringType):
293             strlow = strloc.lower()
294             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
295                 return True
296             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
297                 return False
298         return strloc
299         pass
300
301     def intValue( self, str ):
302         strloc = str
303         if isinstance(strloc, types.UnicodeType):
304             strloc = strloc.encode().strip()
305         if isinstance(strloc, types.StringType):
306             strlow = strloc.lower()
307             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
308                 return 1
309             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
310                 return 0
311             else:
312                 return string.atoi(strloc)
313         return strloc
314         pass
315
316     def startElement(self, name, attrs):
317         self.space.append(name)
318         self.current = None
319
320         # if we are importing file
321         if self.space == [doc_tag, import_tag] and nam_att in attrs.getNames():
322             self.importFile( attrs.getValue(nam_att) )
323
324         # if we are analyzing "section" element and its "name" attribute is
325         # either "launch" or module name -- set section_name
326         if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
327             section_name = attrs.getValue( nam_att )
328             if section_name == lanch_nam:
329                 self.section = section_name # launch section
330             elif self.opts.has_key( modules_nam ) and \
331                  section_name in self.opts[ modules_nam ]:
332                 self.section = section_name # <module> section
333             else:
334                 self.section = section_to_skip # any other section
335             pass
336
337         # if we are analyzing "parameter" elements - children of either
338         # "section launch" or "section "<module>"" element, then store them
339         # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
340         elif self.section != section_to_skip           and \
341              self.space == [doc_tag, sec_tag, par_tag] and \
342              nam_att in attrs.getNames()               and \
343              val_att in attrs.getNames():
344             nam = attrs.getValue( nam_att )
345             val = attrs.getValue( val_att )
346             if self.section == lanch_nam: # key for launch section
347                 key = nam
348             else:                         # key for <module> section
349                 key = self.section + "_" + nam
350             if nam in boolKeys:
351                 self.opts[key] = self.boolValue( val )  # assign boolean value: 0 or 1
352             elif nam in intKeys:
353                 self.opts[key] = self.intValue( val )   # assign integer value
354             elif nam in listKeys:
355                 self.opts[key] = filter( lambda a: a.strip(), re.split( "[:;,]", val ) ) # assign list value: []
356             else:
357                 self.opts[key] = val
358             pass
359         pass
360
361     def endElement(self, name):
362         self.space.pop()
363         self.current = None
364         if self.section != section_to_skip and name == sec_tag:
365             self.section = section_to_skip
366         pass
367
368     def characters(self, content):
369         pass
370
371     def processingInstruction(self, target, data):
372         pass
373
374     def setDocumentLocator(self, locator):
375         pass
376
377     def startDocument(self):
378         self.read = None
379         pass
380
381     def endDocument(self):
382         self.read = None
383         pass
384
385     def importFile(self, fname):
386         # get absolute name
387         if os.path.isabs (fname) :
388             absfname = fname
389         else:
390             absfname = os.path.join(os.path.dirname(self.fileName), fname)
391
392         # check existing and registry file
393         for ext in ["", ".xml", ".XML"] :
394             if os.path.exists(absfname + ext) :
395                 absfname += ext
396                 if absfname in self.importHistory :
397                     if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
398                     return # already imported
399                 break
400             pass
401         else:
402             if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
403             return
404
405         # importing file
406         try:
407             # copy current options
408             import copy
409             opts = copy.deepcopy(self.opts)
410             # import file
411             imp = xml_parser(absfname, opts, self.importHistory)
412             # merge results
413             for key in imp.opts.keys():
414                 if not self.opts.has_key(key):
415                     self.opts[key] = imp.opts[key]
416                     pass
417                 pass
418             pass
419         except:
420             if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
421         pass
422
423
424 # -----------------------------------------------------------------------------
425
426 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok'     : True,
427              '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
428
429 boolean_choices = booleans.keys()
430
431 def check_embedded(option, opt, value, parser):
432     from optparse import OptionValueError
433     assert value is not None
434     if parser.values.embedded:
435         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
436     else:
437         embedded = []
438     if parser.values.standalone:
439         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
440     else:
441         standalone = []
442     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
443     for v in vals:
444         if v not in embedded_choices:
445             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
446         if v not in embedded:
447             embedded.append( v )
448             if v in standalone:
449                 del standalone[ standalone.index( v ) ]
450                 pass
451     parser.values.embedded = ",".join( embedded )
452     parser.values.standalone = ",".join( standalone )
453     pass
454
455 def check_standalone(option, opt, value, parser):
456     from optparse import OptionValueError
457     assert value is not None
458     if parser.values.embedded:
459         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
460     else:
461         embedded = []
462     if parser.values.standalone:
463         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
464     else:
465         standalone = []
466     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
467     for v in vals:
468         if v not in standalone_choices:
469             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
470         if v not in standalone:
471             standalone.append( v )
472             if v in embedded:
473                 del embedded[ embedded.index( v ) ]
474                 pass
475     parser.values.embedded = ",".join( embedded )
476     parser.values.standalone = ",".join( standalone )
477     pass
478
479 def store_boolean (option, opt, value, parser, *args):
480     if isinstance(value, types.StringType):
481         try:
482             value_conv = booleans[value.strip().lower()]
483             for attribute in args:
484                 setattr(parser.values, attribute, value_conv)
485         except KeyError:
486             raise optparse.OptionValueError(
487                 "option %s: invalid boolean value: %s (choose from %s)"
488                 % (opt, value, boolean_choices))
489     else:
490         for attribute in args:
491             setattr(parser.values, attribute, value)
492
493 def CreateOptionParser (theAdditionalOptions=None):
494     if theAdditionalOptions is None:
495         theAdditionalOptions = []
496     # GUI/Terminal. Default: GUI
497     help_str = "Launch without GUI (in the terminal mode)."
498     o_t = optparse.Option("-t",
499                           "--terminal",
500                           action="store_false",
501                           dest="gui",
502                           help=help_str)
503
504     help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
505     o_b = optparse.Option("-b",
506                           "--batch",
507                           action="store_true",
508                           dest="batch",
509                           help=help_str)
510
511     help_str = "Launch in GUI mode [default]."
512     o_g = optparse.Option("-g",
513                           "--gui",
514                           action="store_true",
515                           dest="gui",
516                           help=help_str)
517
518     # Show Desktop (inly in GUI mode). Default: True
519     help_str  = "1 to activate GUI desktop [default], "
520     help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
521     help_str += "Ignored in the terminal mode."
522     o_d = optparse.Option("-d",
523                           "--show-desktop",
524                           metavar="<1/0>",
525                           #type="choice", choices=boolean_choices,
526                           type="string",
527                           action="callback", callback=store_boolean, callback_args=('desktop',),
528                           dest="desktop",
529                           help=help_str)
530     help_str  = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
531     help_str += "The same as --show-desktop=0."
532     o_o = optparse.Option("-o",
533                           "--hide-desktop",
534                           action="store_false",
535                           dest="desktop",
536                           help=help_str)
537
538     # Use logger or log-file. Default: nothing.
539     help_str = "Redirect messages to the CORBA collector."
540     #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
541     o_l = optparse.Option("-l",
542                           "--logger",
543                           action="store_const", const="CORBA",
544                           dest="log_file",
545                           help=help_str)
546     help_str = "Redirect messages to the <log-file>"
547     o_f = optparse.Option("-f",
548                           "--log-file",
549                           metavar="<log-file>",
550                           type="string",
551                           action="store",
552                           dest="log_file",
553                           help=help_str)
554
555     # Configuration XML file. Default: see defaultUserFile() function
556     help_str  = "Parse application settings from the <file> "
557     help_str += "instead of default %s" % defaultUserFile()
558     o_r = optparse.Option("-r",
559                           "--resources",
560                           metavar="<file>",
561                           type="string",
562                           action="store",
563                           dest="resources",
564                           help=help_str)
565
566     # Use own xterm for each server. Default: False.
567     help_str = "Launch each SALOME server in own xterm console"
568     o_x = optparse.Option("-x",
569                           "--xterm",
570                           action="store_true",
571                           dest="xterm",
572                           help=help_str)
573
574     # Modules. Default: Like in configuration files.
575     help_str  = "SALOME modules list (where <module1>, <module2> are the names "
576     help_str += "of SALOME modules which should be available in the SALOME session)"
577     o_m = optparse.Option("-m",
578                           "--modules",
579                           metavar="<module1,module2,...>",
580                           type="string",
581                           action="append",
582                           dest="modules",
583                           help=help_str)
584
585     # Embedded servers. Default: Like in configuration files.
586     help_str  = "CORBA servers to be launched in the Session embedded mode. "
587     help_str += "Valid values for <serverN>: %s " % ", ".join( embedded_choices )
588     help_str += "[by default the value from the configuration files is used]"
589     o_e = optparse.Option("-e",
590                           "--embedded",
591                           metavar="<server1,server2,...>",
592                           type="string",
593                           action="callback",
594                           dest="embedded",
595                           callback=check_embedded,
596                           help=help_str)
597
598     # Standalone servers. Default: Like in configuration files.
599     help_str  = "CORBA servers to be launched in the standalone mode (as separate processes). "
600     help_str += "Valid values for <serverN>: %s " % ", ".join( standalone_choices )
601     help_str += "[by default the value from the configuration files is used]"
602     o_s = optparse.Option("-s",
603                           "--standalone",
604                           metavar="<server1,server2,...>",
605                           type="string",
606                           action="callback",
607                           dest="standalone",
608                           callback=check_standalone,
609                           help=help_str)
610
611     # Kill with port. Default: False.
612     help_str = "Kill SALOME with the current port"
613     o_p = optparse.Option("-p",
614                           "--portkill",
615                           action="store_true",
616                           dest="portkill",
617                           help=help_str)
618
619     # Kill all. Default: False.
620     help_str = "Kill all running SALOME sessions"
621     o_k = optparse.Option("-k",
622                           "--killall",
623                           action="store_true",
624                           dest="killall",
625                           help=help_str)
626
627     # Additional python interpreters. Default: 0.
628     help_str  = "The number of additional external python interpreters to run. "
629     help_str += "Each additional python interpreter is run in separate "
630     help_str += "xterm session with properly set SALOME environment"
631     o_i = optparse.Option("-i",
632                           "--interp",
633                           metavar="<N>",
634                           type="int",
635                           action="store",
636                           dest="interp",
637                           help=help_str)
638
639     # Splash. Default: True.
640     help_str  = "1 to display splash screen [default], "
641     help_str += "0 to disable splash screen. "
642     help_str += "This option is ignored in the terminal mode. "
643     help_str += "It is also ignored if --show-desktop=0 option is used."
644     o_z = optparse.Option("-z",
645                           "--splash",
646                           metavar="<1/0>",
647                           #type="choice", choices=boolean_choices,
648                           type="string",
649                           action="callback", callback=store_boolean, callback_args=('splash',),
650                           dest="splash",
651                           help=help_str)
652
653     # Catch exceptions. Default: True.
654     help_str  = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
655     help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
656     o_c = optparse.Option("-c",
657                           "--catch-exceptions",
658                           metavar="<1/0>",
659                           #type="choice", choices=boolean_choices,
660                           type="string",
661                           action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
662                           dest="catch_exceptions",
663                           help=help_str)
664
665     # Print free port and exit
666     help_str = "Print free port and exit"
667     o_a = optparse.Option("--print-port",
668                           action="store_true",
669                           dest="print_port", default=False,
670                           help=help_str)
671
672     # Do not relink ${HOME}/.omniORB_last.cfg
673     help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
674     o_n = optparse.Option("--nosave-config",
675                           action="store_false",
676                           dest="save_config", default=True,
677                           help=help_str)
678
679     # Launch with interactive python console. Default: False.
680     help_str = "Launch with interactive python console."
681     o_pi = optparse.Option("--pinter",
682                           action="store_true",
683                           dest="pinter",
684                           help=help_str)
685
686     # Print Naming service port into a user file. Default: False.
687     help_str = "Print Naming Service Port into a user file."
688     o_nspl = optparse.Option("--ns-port-log",
689                              metavar="<ns_port_log_file>",
690                              type="string",
691                              action="store",
692                              dest="ns_port_log_file",
693                              help=help_str)
694
695     # Write/read test script file with help of TestRecorder. Default: False.
696     help_str = "Write/read test script file with help of TestRecorder."
697     o_test = optparse.Option("--test",
698                              metavar="<test_script_file>",
699                              type="string",
700                              action="store",
701                              dest="test_script_file",
702                              help=help_str)
703
704     # Reproducing test script with help of TestRecorder. Default: False.
705     help_str = "Reproducing test script with help of TestRecorder."
706     o_play = optparse.Option("--play",
707                              metavar="<play_script_file>",
708                              type="string",
709                              action="store",
710                              dest="play_script_file",
711                              help=help_str)
712
713     # gdb session
714     help_str = "Launch session with gdb"
715     o_gdb = optparse.Option("--gdb-session",
716                             action="store_true",
717                             dest="gdb_session", default=False,
718                             help=help_str)
719
720     # ddd session
721     help_str = "Launch session with ddd"
722     o_ddd = optparse.Option("--ddd-session",
723                             action="store_true",
724                             dest="ddd_session", default=False,
725                             help=help_str)
726
727
728     # valgrind session
729     help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
730     o_valgrind = optparse.Option("--valgrind-session",
731                                  action="store_true",
732                                  dest="valgrind_session", default=False,
733                                  help=help_str)
734
735     # shutdown-servers. Default: False.
736     help_str  = "1 to shutdown standalone servers when leaving python interpreter, "
737     help_str += "0 to keep the standalone servers as daemon [default]. "
738     help_str += "This option is only useful in batchmode "
739     help_str += "(terminal mode or without showing desktop)."
740     o_shutdown = optparse.Option("-w",
741                                  "--shutdown-servers",
742                                  metavar="<1/0>",
743                                  #type="choice", choices=boolean_choices,
744                                  type="string",
745                                  action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
746                                  dest="shutdown_servers",
747                                  help=help_str)
748
749     # foreground. Default: True.
750     help_str  = "0 and runSalome exits after have launched the gui, "
751     help_str += "1 to launch runSalome in foreground mode [default]."
752     o_foreground = optparse.Option("--foreground",
753                                    metavar="<1/0>",
754                                    #type="choice", choices=boolean_choices,
755                                    type="string",
756                                    action="callback", callback=store_boolean, callback_args=('foreground',),
757                                    dest="foreground",
758                                    help=help_str)
759
760     # wake up session
761     help_str  = "Wake up a previously closed session. "
762     help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
763     help_str += "If this variable is not setted, the last configuration is taken. "
764     o_wake_up = optparse.Option("--wake-up-session",
765                                 action="store_true",
766                                 dest="wake_up_session", default=False,
767                                 help=help_str)
768
769     # server launch mode
770     help_str = "Mode used to launch server processes (daemon or fork)."
771     o_slm = optparse.Option("--server-launch-mode",
772                             metavar="<server_launch_mode>",
773                             type="choice",
774                             choices=["daemon","fork"],
775                             action="store",
776                             dest="server_launch_mode",
777                             help=help_str)
778
779     # use port
780     help_str  = "Preferable port SALOME to be started on. "
781     help_str += "If specified port is not busy, SALOME session will start on it; "
782     help_str += "otherwise, any available port will be searched and used."
783     o_port = optparse.Option("--port",
784                              metavar="<port>",
785                              type="int",
786                                    action="store",
787                              dest="use_port",
788                                    help=help_str)
789
790     # SIMAN launch mode
791     help_str = "Special mode for interacting with SIMAN."
792     o_siman = optparse.Option("--siman",
793                               action="store_true",
794                               dest="siman",
795                               help=help_str)
796
797     # SIMAN study
798     help_str = "SIMAN study identifier."
799     o_siman_study = optparse.Option("--siman-study",
800                                     metavar="<id>",
801                                     type="string",
802                                     action="store",
803                                     dest="siman_study",
804                                     help=help_str)
805
806     # SIMAN scenario
807     help_str = "SIMAN scenario identifier."
808     o_siman_scenario = optparse.Option("--siman-scenario",
809                                        metavar="<id>",
810                                        type="string",
811                                        action="store",
812                                        dest="siman_scenario",
813                                        help=help_str)
814
815     # SIMAN user
816     help_str = "SIMAN user identifier."
817     o_siman_user = optparse.Option("--siman-user",
818                                    metavar="<id>",
819                                    type="string",
820                                    action="store",
821                                    dest="siman_user",
822                                    help=help_str)
823
824     # All options
825     opt_list = [o_t,o_g, # GUI/Terminal
826                 o_d,o_o, # Desktop
827                 o_b,     # Batch
828                 o_l,o_f, # Use logger or log-file
829                 o_r,     # Configuration XML file
830                 o_x,     # xterm
831                 o_m,     # Modules
832                 o_e,     # Embedded servers
833                 o_s,     # Standalone servers
834                 o_p,     # Kill with port
835                 o_k,     # Kill all
836                 o_i,     # Additional python interpreters
837                 o_z,     # Splash
838                 o_c,     # Catch exceptions
839                 o_a,     # Print free port and exit
840                 o_n,     # --nosave-config
841                 o_pi,    # Interactive python console
842                 o_nspl,
843                 o_test,  # Write/read test script file with help of TestRecorder
844                 o_play,  # Reproducing test script with help of TestRecorder
845                 o_gdb,
846                 o_ddd,
847                 o_valgrind,
848                 o_shutdown,
849                 o_foreground,
850                 o_wake_up,
851                 o_slm,   # Server launch mode
852                 o_port,  # Use port
853                 o_siman,         # Siman launch mode
854                 o_siman_study,   # Siman study
855                 o_siman_scenario,# Siman scenario
856                 o_siman_user,    # Siman user
857                 ]
858
859     #std_options = ["gui", "desktop", "log_file", "resources",
860     #               "xterm", "modules", "embedded", "standalone",
861     #               "portkill", "killall", "interp", "splash",
862     #               "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
863
864     opt_list += theAdditionalOptions
865
866     a_usage = """%prog [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
867 Python file arguments, if any, must be comma-separated (without blank characters) and prefixed by "args:" (without quotes), e.g. myscript.py args:arg1,arg2=val,...
868 """
869     version_str = "Salome %s" % version()
870     pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
871
872     return pars
873
874 # -----------------------------------------------------------------------------
875
876 ###
877 # Get the environment
878 ###
879
880 # this attribute is obsolete
881 args = {}
882 #def get_env():
883 #args = []
884 def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgname):
885     ###
886     # Collect launch configuration files:
887     # - The environment variable "<appname>Config" (SalomeAppConfig) which can
888     #   define a list of directories (separated by ':' or ';' symbol) is checked
889     # - If the environment variable "<appname>Config" is not set, only
890     #   ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
891     # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
892     #   so it is not necessary to put it in the "<appname>Config" variable
893     # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
894     #  (SalomeApp.xml) which define SALOME configuration
895     # - These directories are analyzed beginning from the last one in the list,
896     #   so the first directory listed in "<appname>Config" environment variable
897     #   has higher priority: it means that if some configuration options
898     #   is found in the next analyzed cofiguration file - it will be replaced
899     # - The last configuration file which is parsed is user configuration file
900     #   situated in the home directory (if it exists):
901     #   * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
902     #   * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
903     # - Command line options have the highest priority and replace options
904     #   specified in configuration file(s)
905     ###
906
907     if theAdditionalOptions is None:
908         theAdditionalOptions = []
909
910     global args
911     config_var = appname+'Config'
912
913     # check KERNEL_ROOT_DIR
914     kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
915     if kernel_root_dir is None:
916         print """
917         For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
918         KERNEL_ROOT_DIR is mandatory.
919         """
920         sys.exit(1)
921
922     ############################
923     # parse command line options
924     pars = CreateOptionParser(theAdditionalOptions)
925     (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
926     ############################
927
928     # Process --print-port option
929     if cmd_opts.print_port:
930         from searchFreePort import searchFreePort
931         searchFreePort({})
932         print "port:%s"%(os.environ['NSPORT'])
933
934         try:
935             import PortManager
936             PortManager.releasePort(os.environ['NSPORT'])
937         except ImportError:
938             pass
939
940         sys.exit(0)
941         pass
942
943     # set resources variable SalomeAppConfig if it is not set yet
944     dirs = []
945     if os.getenv(config_var):
946         if sys.platform == 'win32':
947             dirs += re.split(os.pathsep, os.getenv(config_var))
948         else:
949             dirs += re.split('[;|:]', os.getenv(config_var))
950
951     gui_available = False
952     if os.getenv("GUI_ROOT_DIR"):
953         gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"),'share','salome','resources','gui')
954         if os.path.isdir( gui_resources_dir ):
955             gui_available = True
956             dirs.append(gui_resources_dir)
957         pass
958     if not gui_available:
959         kernel_resources_dir = os.path.join(os.getenv("KERNEL_ROOT_DIR"),'bin','salome','appliskel')
960         if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( kernel_resources_dir ):
961           dirs.append(kernel_resources_dir)
962         pass
963     os.environ[config_var] = os.pathsep.join(dirs)
964
965     dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
966
967     try:
968         dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
969     except:
970         pass
971
972     _opts = {} # associative array of options to be filled
973
974     # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
975     for dir in dirs:
976         filename = os.path.join(dir, appname+'.xml')
977         if not os.path.exists(filename):
978             if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
979         else:
980             try:
981                 p = xml_parser(filename, _opts, [])
982                 _opts = p.opts
983             except:
984                 if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
985             pass
986
987     # parse user configuration file
988     # It can be set via --resources=<file> command line option
989     # or is given from default location (see defaultUserFile() function)
990     # If user file for the current version is not found the nearest to it is used
991     user_config = cmd_opts.resources
992     if not user_config:
993         user_config = userFile(appname, cfgname)
994         if verbose(): print "Configure parser: user configuration file is", user_config
995     if not user_config or not os.path.exists(user_config):
996         if verbose(): print "Configure parser: Warning : can not find user configuration file"
997     else:
998         try:
999             p = xml_parser(user_config, _opts, [])
1000             _opts = p.opts
1001         except:
1002             if verbose(): print 'Configure parser: Error : can not read user configuration file'
1003             user_config = ""
1004
1005     args = _opts
1006
1007     args['user_config'] = user_config
1008     #print "User Configuration file: ", args['user_config']
1009
1010     # set default values for options which are NOT set in config files
1011     for aKey in listKeys:
1012         if not args.has_key( aKey ):
1013             args[aKey] = []
1014
1015     for aKey in boolKeys:
1016         if not args.has_key( aKey ):
1017             args[aKey] = 0
1018
1019     if args[file_nam]:
1020         afile=args[file_nam]
1021         args[file_nam] = [afile]
1022
1023     args[appname_nam] = appname
1024
1025     # get the port number
1026     my_port = getPortNumber()
1027
1028     args[port_nam] = my_port
1029
1030     ####################################################
1031     # apply command-line options to the arguments
1032     # each option given in command line overrides the option from xml config file
1033     #
1034     # Options: gui, desktop, log_file, resources,
1035     #          xterm, modules, embedded, standalone,
1036     #          portkill, killall, interp, splash,
1037     #          catch_exceptions, pinter
1038
1039     # GUI/Terminal, Desktop, Splash, STUDY_HDF
1040     args["session_gui"] = False
1041     args[batch_nam] = False
1042     args["study_hdf"] = None
1043     if cmd_opts.gui is not None:
1044         args[gui_nam] = cmd_opts.gui
1045     if cmd_opts.batch is not None:
1046         args[batch_nam] = True
1047
1048     if not gui_available:
1049         args[gui_nam] = False
1050
1051     if args[gui_nam]:
1052         args["session_gui"] = True
1053         if cmd_opts.desktop is not None:
1054             args["session_gui"] = cmd_opts.desktop
1055             args[splash_nam]    = cmd_opts.desktop
1056         if args["session_gui"]:
1057             if cmd_opts.splash is not None:
1058                 args[splash_nam] = cmd_opts.splash
1059     else:
1060         args["session_gui"] = False
1061         args[splash_nam] = False
1062
1063     # Logger/Log file
1064     if cmd_opts.log_file is not None:
1065         if cmd_opts.log_file == 'CORBA':
1066             args[logger_nam] = True
1067         else:
1068             args[file_nam] = [cmd_opts.log_file]
1069
1070     # Naming Service port log file
1071     if cmd_opts.ns_port_log_file is not None:
1072       args["ns_port_log_file"] = cmd_opts.ns_port_log_file
1073
1074     # Study files
1075     for arg in cmd_args:
1076         if arg[-4:] == ".hdf" and not args["study_hdf"]:
1077             args["study_hdf"] = arg
1078
1079     # Python scripts
1080     from salomeContextUtils import getScriptsAndArgs, ScriptAndArgs
1081     args[script_nam] = getScriptsAndArgs(cmd_args)
1082     if args[gui_nam] and args["session_gui"]:
1083         new_args = []
1084         for sa_obj in args[script_nam]: # args[script_nam] is a list of ScriptAndArgs objects
1085             script = re.sub(r'^python.*\s+', r'', sa_obj.script)
1086             new_args.append(ScriptAndArgs(script=script, args=sa_obj.args, out=sa_obj.out))
1087         #
1088         args[script_nam] = new_args
1089
1090     # xterm
1091     if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
1092
1093     # Modules
1094     if cmd_opts.modules is not None:
1095         args[modules_nam] = []
1096         listlist = cmd_opts.modules
1097         for listi in listlist:
1098             args[modules_nam] += re.split( "[:;,]", listi)
1099     else:
1100         # if --modules (-m) command line option is not given
1101         # try SALOME_MODULES environment variable
1102         if os.getenv( "SALOME_MODULES" ):
1103             args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
1104             pass
1105
1106     # Embedded
1107     if cmd_opts.embedded is not None:
1108         args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
1109
1110     # Standalone
1111     if cmd_opts.standalone is not None:
1112         args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
1113
1114     # Normalize the '--standalone' and '--embedded' parameters
1115     standalone, embedded = process_containers_params( args.get( standalone_nam ),
1116                                                       args.get( embedded_nam ) )
1117     if standalone is not None:
1118         args[ standalone_nam ] = standalone
1119     if embedded is not None:
1120         args[ embedded_nam ] = embedded
1121
1122     # Kill
1123     if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
1124     if cmd_opts.killall  is not None: args[killall_nam]  = cmd_opts.killall
1125
1126     # Interpreter
1127     if cmd_opts.interp is not None:
1128         args[interp_nam] = cmd_opts.interp
1129
1130     # Exceptions
1131     if cmd_opts.catch_exceptions is not None:
1132         args[except_nam] = not cmd_opts.catch_exceptions
1133
1134     # Relink config file
1135     if cmd_opts.save_config is not None:
1136         args['save_config'] = cmd_opts.save_config
1137
1138     # Interactive python console
1139     if cmd_opts.pinter is not None:
1140         args[pinter_nam] = cmd_opts.pinter
1141
1142     # Gdb session in xterm
1143     if cmd_opts.gdb_session is not None:
1144         args[gdb_session_nam] = cmd_opts.gdb_session
1145
1146     # Ddd session in xterm
1147     if cmd_opts.ddd_session is not None:
1148         args[ddd_session_nam] = cmd_opts.ddd_session
1149
1150     # valgrind session
1151     if cmd_opts.valgrind_session is not None:
1152         args[valgrind_session_nam] = cmd_opts.valgrind_session
1153
1154     # Shutdown servers
1155     if cmd_opts.shutdown_servers is None:
1156         args[shutdown_servers_nam] = 0
1157     else:
1158         args[shutdown_servers_nam] = cmd_opts.shutdown_servers
1159         pass
1160
1161     # Foreground
1162     if cmd_opts.foreground is None:
1163         args[foreground_nam] = 1
1164     else:
1165         args[foreground_nam] = cmd_opts.foreground
1166         pass
1167
1168     # wake up session
1169     if cmd_opts.wake_up_session is not None:
1170         args[wake_up_session_nam] = cmd_opts.wake_up_session
1171
1172     # siman options
1173     if cmd_opts.siman is not None:
1174         args[siman_nam] = cmd_opts.siman
1175     if cmd_opts.siman_study is not None:
1176         args[siman_study_nam] = cmd_opts.siman_study
1177     if cmd_opts.siman_scenario is not None:
1178         args[siman_scenario_nam] = cmd_opts.siman_scenario
1179     if cmd_opts.siman_user is not None:
1180         args[siman_user_nam] = cmd_opts.siman_user
1181
1182     ####################################################
1183     # Add <theAdditionalOptions> values to args
1184     for add_opt in theAdditionalOptions:
1185         cmd = "args[\"{0}\"] = cmd_opts.{0}".format(add_opt.dest)
1186         exec(cmd)
1187     ####################################################
1188
1189     # disable signals handling
1190     if args[except_nam] == 1:
1191         os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
1192         pass
1193
1194     # now modify SalomeAppConfig environment variable
1195     # to take into account the SALOME modules
1196     if os.sys.platform == 'win32':
1197         dirs = re.split('[;]', os.environ[config_var] )
1198     else:
1199         dirs = re.split('[;|:]', os.environ[config_var] )
1200     for module in args[modules_nam]:
1201         if module not in ["KERNEL", "GUI", ""] and os.getenv("{0}_ROOT_DIR".format(module)):
1202             d1 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources",module.lower())
1203             d2 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources")
1204             #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
1205             if os.path.exists( os.path.join(d1,"{0}.xml".format(salomeappname)) ):
1206                 dirs.append( d1 )
1207             #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
1208             elif os.path.exists( os.path.join(d2,"{0}.xml".format(salomeappname)) ):
1209                 dirs.append( d2 )
1210         else:
1211             #print "* '"+m+"' should be deleted from ",args[modules_nam]
1212             pass
1213
1214     # Test
1215     if cmd_opts.test_script_file is not None:
1216         args[test_nam] = []
1217         filename = cmd_opts.test_script_file
1218         args[test_nam] += re.split( "[:;,]", filename )
1219
1220     # Play
1221     if cmd_opts.play_script_file is not None:
1222         args[play_nam] = []
1223         filename = cmd_opts.play_script_file
1224         args[play_nam] += re.split( "[:;,]", filename )
1225
1226     # Server launch command
1227     if cmd_opts.server_launch_mode is not None:
1228         args["server_launch_mode"] = cmd_opts.server_launch_mode
1229
1230     # Server launch command
1231     if cmd_opts.use_port is not None:
1232         min_port = 2810
1233         max_port = min_port + 100
1234         if cmd_opts.use_port not in xrange(min_port, max_port+1):
1235             print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
1236             sys.exit(1)
1237         args[useport_nam] = cmd_opts.use_port
1238
1239     # return arguments
1240     os.environ[config_var] = os.pathsep.join(dirs)
1241     #print "Args: ", args
1242     return args