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