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