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