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