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