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