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