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