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