Salome HOME
Fix problem with unicode symbols in path to home directory
[modules/yacs.git] / bin / launchConfigureParser.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2015  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 os, glob, string, sys, re
25 import xml.sax
26 import optparse
27 import types
28
29 from salome_utils import verbose, getPortNumber, getHomeDir
30
31 # names of tags in XML configuration file
32 doc_tag = "document"
33 sec_tag = "section"
34 par_tag = "parameter"
35 import_tag = "import"
36
37 # names of attributes in XML configuration file
38 nam_att = "name"
39 val_att = "value"
40
41 # certain values in XML configuration file ("launch" section)
42 lanch_nam      = "launch"
43 help_nam       = "help"
44 gui_nam        = "gui"
45 splash_nam     = "splash"
46 logger_nam     = "logger"
47 xterm_nam      = "xterm"
48 file_nam       = "file"
49 portkill_nam   = "portkill"
50 killall_nam    = "killall"
51 modules_nam    = "modules"
52 embedded_nam   = "embedded"
53 standalone_nam = "standalone"
54 key_nam        = "key"
55 terminal_nam   = "terminal"
56 interp_nam     = "interp"
57 except_nam     = "noexcepthandler"
58 terminal_nam   = "terminal"
59 pinter_nam     = "pinter"
60 batch_nam      = "batch"
61 test_nam       = "test"
62 play_nam       = "play"
63 gdb_session_nam = "gdb_session"
64 ddd_session_nam = "ddd_session"
65 valgrind_session_nam = "valgrind_session"
66 shutdown_servers_nam = "shutdown_servers"
67 foreground_nam = "foreground"
68 wake_up_session_nam = "wake_up_session"
69 siman_nam = "siman"
70 siman_study_nam = "siman_study"
71 siman_scenario_nam = "siman_scenario"
72 siman_user_nam = "siman_user"
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 appopriate 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 = filter( lambda x: x in standalone_choices, standalone )
248     if embedded is not None:
249         embedded   = filter( lambda x: x in embedded_choices,   embedded )
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 = filter( lambda x: x not in standalone, embedded )
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, str ):
289         strloc = str
290         if isinstance(strloc, types.UnicodeType):
291             strloc = strloc.encode().strip()
292         if isinstance(strloc, types.StringType):
293             strlow = strloc.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, str ):
302         strloc = str
303         if isinstance(strloc, types.UnicodeType):
304             strloc = strloc.encode().strip()
305         if isinstance(strloc, types.StringType):
306             strlow = strloc.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 string.atoi(strloc)
313         return strloc
314         pass
315     
316     def strValue( self, str ):
317         strloc = str
318         try:
319             if isinstance(strloc, types.UnicodeType): strloc = strloc.encode().strip()
320             else: strloc = strloc.strip()
321         except:
322             pass
323         return strloc
324
325     def startElement(self, name, attrs):
326         self.space.append(name)
327         self.current = None
328
329         # if we are importing file
330         if self.space == [doc_tag, import_tag] and nam_att in attrs.getNames():
331             self.importFile( attrs.getValue(nam_att) )
332
333         # if we are analyzing "section" element and its "name" attribute is
334         # either "launch" or module name -- set section_name
335         if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
336             section_name = attrs.getValue( nam_att )
337             if section_name == lanch_nam:
338                 self.section = section_name # launch section
339             elif self.opts.has_key( modules_nam ) and \
340                  section_name in self.opts[ modules_nam ]:
341                 self.section = section_name # <module> section
342             else:
343                 self.section = section_to_skip # any other section
344             pass
345
346         # if we are analyzing "parameter" elements - children of either
347         # "section launch" or "section "<module>"" element, then store them
348         # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
349         elif self.section != section_to_skip           and \
350              self.space == [doc_tag, sec_tag, par_tag] and \
351              nam_att in attrs.getNames()               and \
352              val_att in attrs.getNames():
353             nam = attrs.getValue( nam_att )
354             val = attrs.getValue( val_att )
355             if self.section == lanch_nam: # key for launch section
356                 key = nam
357             else:                         # key for <module> section
358                 key = self.section + "_" + nam
359             key = self.strValue( key )
360             if nam in boolKeys:
361                 self.opts[key] = self.boolValue( val )  # assign boolean value: 0 or 1
362             elif nam in intKeys:
363                 self.opts[key] = self.intValue( val )   # assign integer value
364             elif nam in listKeys:
365                 self.opts[key] = [ self.strValue( a ) for a in re.split( "[:;,]", val ) ] # assign list value: []
366             else:
367                 self.opts[key] = self.strValue( val ) # string value
368             pass
369         pass
370
371     def endElement(self, name):
372         self.space.pop()
373         self.current = None
374         if self.section != section_to_skip and name == sec_tag:
375             self.section = section_to_skip
376         pass
377
378     def characters(self, content):
379         pass
380
381     def processingInstruction(self, target, data):
382         pass
383
384     def setDocumentLocator(self, locator):
385         pass
386
387     def startDocument(self):
388         self.read = None
389         pass
390
391     def endDocument(self):
392         self.read = None
393         pass
394
395     def importFile(self, fname):
396         # get absolute name
397         if os.path.isabs (fname) :
398             absfname = fname
399         else:
400             absfname = os.path.join(os.path.dirname(self.fileName), fname)
401
402         # check existing and registry file
403         for ext in ["", ".xml", ".XML"] :
404             if os.path.exists(absfname + ext) :
405                 absfname += ext
406                 if absfname in self.importHistory :
407                     if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
408                     return # already imported
409                 break
410             pass
411         else:
412             if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
413             return
414
415         # importing file
416         try:
417             # copy current options
418             import copy
419             opts = copy.deepcopy(self.opts)
420             # import file
421             imp = xml_parser(absfname, opts, self.importHistory)
422             # merge results
423             for key in imp.opts.keys():
424                 if not self.opts.has_key(key):
425                     self.opts[key] = imp.opts[key]
426                     pass
427                 pass
428             pass
429         except:
430             if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
431         pass
432
433
434 # -----------------------------------------------------------------------------
435
436 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok'     : True,
437              '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
438
439 boolean_choices = booleans.keys()
440
441 def check_embedded(option, opt, value, parser):
442     from optparse import OptionValueError
443     assert value is not None
444     if parser.values.embedded:
445         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
446     else:
447         embedded = []
448     if parser.values.standalone:
449         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
450     else:
451         standalone = []
452     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
453     for v in vals:
454         if v not in embedded_choices:
455             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
456         if v not in embedded:
457             embedded.append( v )
458             if v in standalone:
459                 del standalone[ standalone.index( v ) ]
460                 pass
461     parser.values.embedded = ",".join( embedded )
462     parser.values.standalone = ",".join( standalone )
463     pass
464
465 def check_standalone(option, opt, value, parser):
466     from optparse import OptionValueError
467     assert value is not None
468     if parser.values.embedded:
469         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
470     else:
471         embedded = []
472     if parser.values.standalone:
473         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
474     else:
475         standalone = []
476     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
477     for v in vals:
478         if v not in standalone_choices:
479             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
480         if v not in standalone:
481             standalone.append( v )
482             if v in embedded:
483                 del embedded[ embedded.index( v ) ]
484                 pass
485     parser.values.embedded = ",".join( embedded )
486     parser.values.standalone = ",".join( standalone )
487     pass
488
489 def store_boolean (option, opt, value, parser, *args):
490     if isinstance(value, types.StringType):
491         try:
492             value_conv = booleans[value.strip().lower()]
493             for attribute in args:
494                 setattr(parser.values, attribute, value_conv)
495         except KeyError:
496             raise optparse.OptionValueError(
497                 "option %s: invalid boolean value: %s (choose from %s)"
498                 % (opt, value, boolean_choices))
499     else:
500         for attribute in args:
501             setattr(parser.values, attribute, value)
502
503 def CreateOptionParser (theAdditionalOptions=None):
504     if theAdditionalOptions is None:
505         theAdditionalOptions = []
506     # GUI/Terminal. Default: GUI
507     help_str = "Launch without GUI (in the terminal mode)."
508     o_t = optparse.Option("-t",
509                           "--terminal",
510                           action="store_false",
511                           dest="gui",
512                           help=help_str)
513
514     help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
515     o_b = optparse.Option("-b",
516                           "--batch",
517                           action="store_true",
518                           dest="batch",
519                           help=help_str)
520
521     help_str = "Launch in GUI mode [default]."
522     o_g = optparse.Option("-g",
523                           "--gui",
524                           action="store_true",
525                           dest="gui",
526                           help=help_str)
527
528     # Show Desktop (inly in GUI mode). Default: True
529     help_str  = "1 to activate GUI desktop [default], "
530     help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
531     help_str += "Ignored in the terminal mode."
532     o_d = optparse.Option("-d",
533                           "--show-desktop",
534                           metavar="<1/0>",
535                           #type="choice", choices=boolean_choices,
536                           type="string",
537                           action="callback", callback=store_boolean, callback_args=('desktop',),
538                           dest="desktop",
539                           help=help_str)
540     help_str  = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
541     help_str += "The same as --show-desktop=0."
542     o_o = optparse.Option("-o",
543                           "--hide-desktop",
544                           action="store_false",
545                           dest="desktop",
546                           help=help_str)
547
548     # Use logger or log-file. Default: nothing.
549     help_str = "Redirect messages to the CORBA collector."
550     #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
551     o_l = optparse.Option("-l",
552                           "--logger",
553                           action="store_const", const="CORBA",
554                           dest="log_file",
555                           help=help_str)
556     help_str = "Redirect messages to the <log-file>"
557     o_f = optparse.Option("-f",
558                           "--log-file",
559                           metavar="<log-file>",
560                           type="string",
561                           action="store",
562                           dest="log_file",
563                           help=help_str)
564
565     # Configuration XML file. Default: see defaultUserFile() function
566     help_str  = "Parse application settings from the <file> "
567     help_str += "instead of default %s" % defaultUserFile()
568     o_r = optparse.Option("-r",
569                           "--resources",
570                           metavar="<file>",
571                           type="string",
572                           action="store",
573                           dest="resources",
574                           help=help_str)
575
576     # Use own xterm for each server. Default: False.
577     help_str = "Launch each SALOME server in own xterm console"
578     o_x = optparse.Option("-x",
579                           "--xterm",
580                           action="store_true",
581                           dest="xterm",
582                           help=help_str)
583
584     # Modules. Default: Like in configuration files.
585     help_str  = "SALOME modules list (where <module1>, <module2> are the names "
586     help_str += "of SALOME modules which should be available in the SALOME session)"
587     o_m = optparse.Option("-m",
588                           "--modules",
589                           metavar="<module1,module2,...>",
590                           type="string",
591                           action="append",
592                           dest="modules",
593                           help=help_str)
594
595     # Embedded servers. Default: Like in configuration files.
596     help_str  = "CORBA servers to be launched in the Session embedded mode. "
597     help_str += "Valid values for <serverN>: %s " % ", ".join( embedded_choices )
598     help_str += "[by default the value from the configuration files is used]"
599     o_e = optparse.Option("-e",
600                           "--embedded",
601                           metavar="<server1,server2,...>",
602                           type="string",
603                           action="callback",
604                           dest="embedded",
605                           callback=check_embedded,
606                           help=help_str)
607
608     # Standalone servers. Default: Like in configuration files.
609     help_str  = "CORBA servers to be launched in the standalone mode (as separate processes). "
610     help_str += "Valid values for <serverN>: %s " % ", ".join( standalone_choices )
611     help_str += "[by default the value from the configuration files is used]"
612     o_s = optparse.Option("-s",
613                           "--standalone",
614                           metavar="<server1,server2,...>",
615                           type="string",
616                           action="callback",
617                           dest="standalone",
618                           callback=check_standalone,
619                           help=help_str)
620
621     # Kill with port. Default: False.
622     help_str = "Kill SALOME with the current port"
623     o_p = optparse.Option("-p",
624                           "--portkill",
625                           action="store_true",
626                           dest="portkill",
627                           help=help_str)
628
629     # Kill all. Default: False.
630     help_str = "Kill all running SALOME sessions"
631     o_k = optparse.Option("-k",
632                           "--killall",
633                           action="store_true",
634                           dest="killall",
635                           help=help_str)
636
637     # Additional python interpreters. Default: 0.
638     help_str  = "The number of additional external python interpreters to run. "
639     help_str += "Each additional python interpreter is run in separate "
640     help_str += "xterm session with properly set SALOME environment"
641     o_i = optparse.Option("-i",
642                           "--interp",
643                           metavar="<N>",
644                           type="int",
645                           action="store",
646                           dest="interp",
647                           help=help_str)
648
649     # Splash. Default: True.
650     help_str  = "1 to display splash screen [default], "
651     help_str += "0 to disable splash screen. "
652     help_str += "This option is ignored in the terminal mode. "
653     help_str += "It is also ignored if --show-desktop=0 option is used."
654     o_z = optparse.Option("-z",
655                           "--splash",
656                           metavar="<1/0>",
657                           #type="choice", choices=boolean_choices,
658                           type="string",
659                           action="callback", callback=store_boolean, callback_args=('splash',),
660                           dest="splash",
661                           help=help_str)
662
663     # Catch exceptions. Default: True.
664     help_str  = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
665     help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
666     o_c = optparse.Option("-c",
667                           "--catch-exceptions",
668                           metavar="<1/0>",
669                           #type="choice", choices=boolean_choices,
670                           type="string",
671                           action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
672                           dest="catch_exceptions",
673                           help=help_str)
674
675     # Print free port and exit
676     help_str = "Print free port and exit"
677     o_a = optparse.Option("--print-port",
678                           action="store_true",
679                           dest="print_port", default=False,
680                           help=help_str)
681
682     # Do not relink ${HOME}/.omniORB_last.cfg
683     help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
684     o_n = optparse.Option("--nosave-config",
685                           action="store_false",
686                           dest="save_config", default=True,
687                           help=help_str)
688
689     # Launch with interactive python console. Default: False.
690     help_str = "Launch with interactive python console."
691     o_pi = optparse.Option("--pinter",
692                           action="store_true",
693                           dest="pinter",
694                           help=help_str)
695
696     # Print Naming service port into a user file. Default: False.
697     help_str = "Print Naming Service Port into a user file."
698     o_nspl = optparse.Option("--ns-port-log",
699                              metavar="<ns_port_log_file>",
700                              type="string",
701                              action="store",
702                              dest="ns_port_log_file",
703                              help=help_str)
704
705     # Write/read test script file with help of TestRecorder. Default: False.
706     help_str = "Write/read test script file with help of TestRecorder."
707     o_test = optparse.Option("--test",
708                              metavar="<test_script_file>",
709                              type="string",
710                              action="store",
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     o_play = optparse.Option("--play",
717                              metavar="<play_script_file>",
718                              type="string",
719                              action="store",
720                              dest="play_script_file",
721                              help=help_str)
722
723     # gdb session
724     help_str = "Launch session with gdb"
725     o_gdb = optparse.Option("--gdb-session",
726                             action="store_true",
727                             dest="gdb_session", default=False,
728                             help=help_str)
729
730     # ddd session
731     help_str = "Launch session with ddd"
732     o_ddd = optparse.Option("--ddd-session",
733                             action="store_true",
734                             dest="ddd_session", default=False,
735                             help=help_str)
736
737
738     # valgrind session
739     help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
740     o_valgrind = optparse.Option("--valgrind-session",
741                                  action="store_true",
742                                  dest="valgrind_session", default=False,
743                                  help=help_str)
744
745     # shutdown-servers. Default: False.
746     help_str  = "1 to shutdown standalone servers when leaving python interpreter, "
747     help_str += "0 to keep the standalone servers as daemon [default]. "
748     help_str += "This option is only useful in batchmode "
749     help_str += "(terminal mode or without showing desktop)."
750     o_shutdown = optparse.Option("-w",
751                                  "--shutdown-servers",
752                                  metavar="<1/0>",
753                                  #type="choice", choices=boolean_choices,
754                                  type="string",
755                                  action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
756                                  dest="shutdown_servers",
757                                  help=help_str)
758
759     # foreground. Default: True.
760     help_str  = "0 and runSalome exits after have launched the gui, "
761     help_str += "1 to launch runSalome in foreground mode [default]."
762     o_foreground = optparse.Option("--foreground",
763                                    metavar="<1/0>",
764                                    #type="choice", choices=boolean_choices,
765                                    type="string",
766                                    action="callback", callback=store_boolean, callback_args=('foreground',),
767                                    dest="foreground",
768                                    help=help_str)
769
770     # wake up session
771     help_str  = "Wake up a previously closed session. "
772     help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
773     help_str += "If this variable is not setted, the last configuration is taken. "
774     o_wake_up = optparse.Option("--wake-up-session",
775                                 action="store_true",
776                                 dest="wake_up_session", default=False,
777                                 help=help_str)
778
779     # server launch mode
780     help_str = "Mode used to launch server processes (daemon or fork)."
781     o_slm = optparse.Option("--server-launch-mode",
782                             metavar="<server_launch_mode>",
783                             type="choice",
784                             choices=["daemon","fork"],
785                             action="store",
786                             dest="server_launch_mode",
787                             help=help_str)
788
789     # use port
790     help_str  = "Preferable port SALOME to be started on. "
791     help_str += "If specified port is not busy, SALOME session will start on it; "
792     help_str += "otherwise, any available port will be searched and used."
793     o_port = optparse.Option("--port",
794                              metavar="<port>",
795                              type="int",
796                                    action="store",
797                              dest="use_port",
798                                    help=help_str)
799
800     # SIMAN launch mode
801     help_str = "Special mode for interacting with SIMAN."
802     o_siman = optparse.Option("--siman",
803                               action="store_true",
804                               dest="siman",
805                               help=help_str)
806
807     # SIMAN study
808     help_str = "SIMAN study identifier."
809     o_siman_study = optparse.Option("--siman-study",
810                                     metavar="<id>",
811                                     type="string",
812                                     action="store",
813                                     dest="siman_study",
814                                     help=help_str)
815
816     # SIMAN scenario
817     help_str = "SIMAN scenario identifier."
818     o_siman_scenario = optparse.Option("--siman-scenario",
819                                        metavar="<id>",
820                                        type="string",
821                                        action="store",
822                                        dest="siman_scenario",
823                                        help=help_str)
824
825     # SIMAN user
826     help_str = "SIMAN user identifier."
827     o_siman_user = optparse.Option("--siman-user",
828                                    metavar="<id>",
829                                    type="string",
830                                    action="store",
831                                    dest="siman_user",
832                                    help=help_str)
833
834     # All options
835     opt_list = [o_t,o_g, # GUI/Terminal
836                 o_d,o_o, # Desktop
837                 o_b,     # Batch
838                 o_l,o_f, # Use logger or log-file
839                 o_r,     # Configuration XML file
840                 o_x,     # xterm
841                 o_m,     # Modules
842                 o_e,     # Embedded servers
843                 o_s,     # Standalone servers
844                 o_p,     # Kill with port
845                 o_k,     # Kill all
846                 o_i,     # Additional python interpreters
847                 o_z,     # Splash
848                 o_c,     # Catch exceptions
849                 o_a,     # Print free port and exit
850                 o_n,     # --nosave-config
851                 o_pi,    # Interactive python console
852                 o_nspl,
853                 o_test,  # Write/read test script file with help of TestRecorder
854                 o_play,  # Reproducing test script with help of TestRecorder
855                 o_gdb,
856                 o_ddd,
857                 o_valgrind,
858                 o_shutdown,
859                 o_foreground,
860                 o_wake_up,
861                 o_slm,   # Server launch mode
862                 o_port,  # Use port
863                 o_siman,         # Siman launch mode
864                 o_siman_study,   # Siman study
865                 o_siman_scenario,# Siman scenario
866                 o_siman_user,    # Siman user
867                 ]
868
869     #std_options = ["gui", "desktop", "log_file", "resources",
870     #               "xterm", "modules", "embedded", "standalone",
871     #               "portkill", "killall", "interp", "splash",
872     #               "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
873
874     opt_list += theAdditionalOptions
875
876     a_usage = """%prog [options] [STUDY_FILE] [PYTHON_FILE [args] [PYTHON_FILE [args]...]]
877 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,...
878 """
879     version_str = "Salome %s" % version()
880     pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
881
882     return pars
883
884 # -----------------------------------------------------------------------------
885
886 ###
887 # Get the environment
888 ###
889
890 # this attribute is obsolete
891 args = {}
892 #def get_env():
893 #args = []
894 def get_env(theAdditionalOptions=None, appname=salomeappname, cfgname=salomecfgname):
895     ###
896     # Collect launch configuration files:
897     # - The environment variable "<appname>Config" (SalomeAppConfig) which can
898     #   define a list of directories (separated by ':' or ';' symbol) is checked
899     # - If the environment variable "<appname>Config" is not set, only
900     #   ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
901     # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
902     #   so it is not necessary to put it in the "<appname>Config" variable
903     # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
904     #  (SalomeApp.xml) which define SALOME configuration
905     # - These directories are analyzed beginning from the last one in the list,
906     #   so the first directory listed in "<appname>Config" environment variable
907     #   has higher priority: it means that if some configuration options
908     #   is found in the next analyzed cofiguration file - it will be replaced
909     # - The last configuration file which is parsed is user configuration file
910     #   situated in the home directory (if it exists):
911     #   * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
912     #   * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
913     # - Command line options have the highest priority and replace options
914     #   specified in configuration file(s)
915     ###
916
917     if theAdditionalOptions is None:
918         theAdditionalOptions = []
919
920     global args
921     config_var = appname+'Config'
922
923     # check KERNEL_ROOT_DIR
924     kernel_root_dir = os.environ.get("KERNEL_ROOT_DIR", None)
925     if kernel_root_dir is None:
926         print """
927         For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
928         KERNEL_ROOT_DIR is mandatory.
929         """
930         sys.exit(1)
931
932     ############################
933     # parse command line options
934     pars = CreateOptionParser(theAdditionalOptions)
935     (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
936     ############################
937
938     # Process --print-port option
939     if cmd_opts.print_port:
940         from searchFreePort import searchFreePort
941         searchFreePort({})
942         print "port:%s"%(os.environ['NSPORT'])
943
944         try:
945             import PortManager
946             PortManager.releasePort(os.environ['NSPORT'])
947         except ImportError:
948             pass
949
950         sys.exit(0)
951         pass
952
953     # set resources variable SalomeAppConfig if it is not set yet
954     dirs = []
955     if os.getenv(config_var):
956         if sys.platform == 'win32':
957             dirs += re.split(os.pathsep, os.getenv(config_var))
958         else:
959             dirs += re.split('[;|:]', os.getenv(config_var))
960
961     gui_available = False
962     if os.getenv("GUI_ROOT_DIR"):
963         gui_resources_dir = os.path.join(os.getenv("GUI_ROOT_DIR"),'share','salome','resources','gui')
964         if os.path.isdir( gui_resources_dir ):
965             gui_available = True
966             dirs.append(gui_resources_dir)
967         pass
968     if not gui_available:
969         kernel_resources_dir = os.path.join(os.getenv("KERNEL_ROOT_DIR"),'bin','salome','appliskel')
970         if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( kernel_resources_dir ):
971           dirs.append(kernel_resources_dir)
972         pass
973     os.environ[config_var] = os.pathsep.join(dirs)
974
975     dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
976
977     try:
978         dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
979     except:
980         pass
981
982     _opts = {} # associative array of options to be filled
983
984     # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
985     for dir in dirs:
986         filename = os.path.join(dir, appname+'.xml')
987         if not os.path.exists(filename):
988             if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
989         else:
990             try:
991                 p = xml_parser(filename, _opts, [])
992                 _opts = p.opts
993             except:
994                 if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
995             pass
996
997     # parse user configuration file
998     # It can be set via --resources=<file> command line option
999     # or is given from default location (see defaultUserFile() function)
1000     # If user file for the current version is not found the nearest to it is used
1001     user_config = cmd_opts.resources
1002     if not user_config:
1003         user_config = userFile(appname, cfgname)
1004         if verbose(): print "Configure parser: user configuration file is", user_config
1005     if not user_config or not os.path.exists(user_config):
1006         if verbose(): print "Configure parser: Warning : can not find user configuration file"
1007     else:
1008         try:
1009             p = xml_parser(user_config, _opts, [])
1010             _opts = p.opts
1011         except:
1012             if verbose(): print 'Configure parser: Error : can not read user configuration file'
1013             user_config = ""
1014
1015     args = _opts
1016
1017     args['user_config'] = user_config
1018     #print "User Configuration file: ", args['user_config']
1019
1020     # set default values for options which are NOT set in config files
1021     for aKey in listKeys:
1022         if not args.has_key( aKey ):
1023             args[aKey] = []
1024
1025     for aKey in boolKeys:
1026         if not args.has_key( aKey ):
1027             args[aKey] = 0
1028
1029     if args[file_nam]:
1030         afile=args[file_nam]
1031         args[file_nam] = [afile]
1032
1033     args[appname_nam] = appname
1034
1035     # get the port number
1036     my_port = getPortNumber()
1037
1038     args[port_nam] = my_port
1039
1040     ####################################################
1041     # apply command-line options to the arguments
1042     # each option given in command line overrides the option from xml config file
1043     #
1044     # Options: gui, desktop, log_file, resources,
1045     #          xterm, modules, embedded, standalone,
1046     #          portkill, killall, interp, splash,
1047     #          catch_exceptions, pinter
1048
1049     # GUI/Terminal, Desktop, Splash, STUDY_HDF
1050     args["session_gui"] = False
1051     args[batch_nam] = False
1052     args["study_hdf"] = None
1053     if cmd_opts.gui is not None:
1054         args[gui_nam] = cmd_opts.gui
1055     if cmd_opts.batch is not None:
1056         args[batch_nam] = True
1057
1058     if not gui_available:
1059         args[gui_nam] = False
1060
1061     if args[gui_nam]:
1062         args["session_gui"] = True
1063         if cmd_opts.desktop is not None:
1064             args["session_gui"] = cmd_opts.desktop
1065             args[splash_nam]    = cmd_opts.desktop
1066         if args["session_gui"]:
1067             if cmd_opts.splash is not None:
1068                 args[splash_nam] = cmd_opts.splash
1069     else:
1070         args["session_gui"] = False
1071         args[splash_nam] = False
1072
1073     # Logger/Log file
1074     if cmd_opts.log_file is not None:
1075         if cmd_opts.log_file == 'CORBA':
1076             args[logger_nam] = True
1077         else:
1078             args[file_nam] = [cmd_opts.log_file]
1079
1080     # Naming Service port log file
1081     if cmd_opts.ns_port_log_file is not None:
1082       args["ns_port_log_file"] = cmd_opts.ns_port_log_file
1083
1084     # Study files
1085     for arg in cmd_args:
1086         if arg[-4:] == ".hdf" and not args["study_hdf"]:
1087             args["study_hdf"] = arg
1088
1089     # Python scripts
1090     from salomeContextUtils import getScriptsAndArgs, ScriptAndArgs
1091     args[script_nam] = getScriptsAndArgs(cmd_args)
1092     if args[gui_nam] and args["session_gui"]:
1093         new_args = []
1094         for sa_obj in args[script_nam]: # args[script_nam] is a list of ScriptAndArgs objects
1095             script = re.sub(r'^python.*\s+', r'', sa_obj.script)
1096             new_args.append(ScriptAndArgs(script=script, args=sa_obj.args, out=sa_obj.out))
1097         #
1098         args[script_nam] = new_args
1099
1100     # xterm
1101     if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
1102
1103     # Modules
1104     if cmd_opts.modules is not None:
1105         args[modules_nam] = []
1106         listlist = cmd_opts.modules
1107         for listi in listlist:
1108             args[modules_nam] += re.split( "[:;,]", listi)
1109     else:
1110         # if --modules (-m) command line option is not given
1111         # try SALOME_MODULES environment variable
1112         if os.getenv( "SALOME_MODULES" ):
1113             args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
1114             pass
1115
1116     # Embedded
1117     if cmd_opts.embedded is not None:
1118         args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
1119
1120     # Standalone
1121     if cmd_opts.standalone is not None:
1122         args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
1123
1124     # Normalize the '--standalone' and '--embedded' parameters
1125     standalone, embedded = process_containers_params( args.get( standalone_nam ),
1126                                                       args.get( embedded_nam ) )
1127     if standalone is not None:
1128         args[ standalone_nam ] = standalone
1129     if embedded is not None:
1130         args[ embedded_nam ] = embedded
1131
1132     # Kill
1133     if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
1134     if cmd_opts.killall  is not None: args[killall_nam]  = cmd_opts.killall
1135
1136     # Interpreter
1137     if cmd_opts.interp is not None:
1138         args[interp_nam] = cmd_opts.interp
1139
1140     # Exceptions
1141     if cmd_opts.catch_exceptions is not None:
1142         args[except_nam] = not cmd_opts.catch_exceptions
1143
1144     # Relink config file
1145     if cmd_opts.save_config is not None:
1146         args['save_config'] = cmd_opts.save_config
1147
1148     # Interactive python console
1149     if cmd_opts.pinter is not None:
1150         args[pinter_nam] = cmd_opts.pinter
1151
1152     # Gdb session in xterm
1153     if cmd_opts.gdb_session is not None:
1154         args[gdb_session_nam] = cmd_opts.gdb_session
1155
1156     # Ddd session in xterm
1157     if cmd_opts.ddd_session is not None:
1158         args[ddd_session_nam] = cmd_opts.ddd_session
1159
1160     # valgrind session
1161     if cmd_opts.valgrind_session is not None:
1162         args[valgrind_session_nam] = cmd_opts.valgrind_session
1163
1164     # Shutdown servers
1165     if cmd_opts.shutdown_servers is None:
1166         args[shutdown_servers_nam] = 0
1167     else:
1168         args[shutdown_servers_nam] = cmd_opts.shutdown_servers
1169         pass
1170
1171     # Foreground
1172     if cmd_opts.foreground is None:
1173         args[foreground_nam] = 1
1174     else:
1175         args[foreground_nam] = cmd_opts.foreground
1176         pass
1177
1178     # wake up session
1179     if cmd_opts.wake_up_session is not None:
1180         args[wake_up_session_nam] = cmd_opts.wake_up_session
1181
1182     # siman options
1183     if cmd_opts.siman is not None:
1184         args[siman_nam] = cmd_opts.siman
1185     if cmd_opts.siman_study is not None:
1186         args[siman_study_nam] = cmd_opts.siman_study
1187     if cmd_opts.siman_scenario is not None:
1188         args[siman_scenario_nam] = cmd_opts.siman_scenario
1189     if cmd_opts.siman_user is not None:
1190         args[siman_user_nam] = cmd_opts.siman_user
1191
1192     ####################################################
1193     # Add <theAdditionalOptions> values to args
1194     for add_opt in theAdditionalOptions:
1195         cmd = "args[\"{0}\"] = cmd_opts.{0}".format(add_opt.dest)
1196         exec(cmd)
1197     ####################################################
1198
1199     # disable signals handling
1200     if args[except_nam] == 1:
1201         os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
1202         pass
1203
1204     # now modify SalomeAppConfig environment variable
1205     # to take into account the SALOME modules
1206     if os.sys.platform == 'win32':
1207         dirs = re.split('[;]', os.environ[config_var] )
1208     else:
1209         dirs = re.split('[;|:]', os.environ[config_var] )
1210     for module in args[modules_nam]:
1211         if module not in ["KERNEL", "GUI", ""] and os.getenv("{0}_ROOT_DIR".format(module)):
1212             d1 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources",module.lower())
1213             d2 = os.path.join(os.getenv("{0}_ROOT_DIR".format(module)),"share","salome","resources")
1214             #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
1215             if os.path.exists( os.path.join(d1,"{0}.xml".format(salomeappname)) ):
1216                 dirs.append( d1 )
1217             #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
1218             elif os.path.exists( os.path.join(d2,"{0}.xml".format(salomeappname)) ):
1219                 dirs.append( d2 )
1220         else:
1221             #print "* '"+m+"' should be deleted from ",args[modules_nam]
1222             pass
1223
1224     # Test
1225     if cmd_opts.test_script_file is not None:
1226         args[test_nam] = []
1227         filename = cmd_opts.test_script_file
1228         args[test_nam] += re.split( "[:;,]", filename )
1229
1230     # Play
1231     if cmd_opts.play_script_file is not None:
1232         args[play_nam] = []
1233         filename = cmd_opts.play_script_file
1234         args[play_nam] += re.split( "[:;,]", filename )
1235
1236     # Server launch command
1237     if cmd_opts.server_launch_mode is not None:
1238         args["server_launch_mode"] = cmd_opts.server_launch_mode
1239
1240     # Server launch command
1241     if cmd_opts.use_port is not None:
1242         min_port = 2810
1243         max_port = min_port + 100
1244         if cmd_opts.use_port not in xrange(min_port, max_port+1):
1245             print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
1246             sys.exit(1)
1247         args[useport_nam] = cmd_opts.use_port
1248
1249     # return arguments
1250     os.environ[config_var] = os.pathsep.join(dirs)
1251     #print "Args: ", args
1252     return args