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