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