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