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