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