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