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