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