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