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