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