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