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