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