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