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