Back to index

salome-kernel  6.5.0
launchConfigureParser.py
Go to the documentation of this file.
00001 #  -*- coding: iso-8859-1 -*-
00002 # Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
00003 #
00004 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
00005 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
00006 #
00007 # This library is free software; you can redistribute it and/or
00008 # modify it under the terms of the GNU Lesser General Public
00009 # License as published by the Free Software Foundation; either
00010 # version 2.1 of the License.
00011 #
00012 # This library is distributed in the hope that it will be useful,
00013 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00014 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015 # Lesser General Public License for more details.
00016 #
00017 # You should have received a copy of the GNU Lesser General Public
00018 # License along with this library; if not, write to the Free Software
00019 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
00020 #
00021 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
00022 #
00023 
00024 import os, glob, string, sys, re
00025 import xml.sax
00026 import optparse
00027 import types
00028 
00029 from salome_utils import verbose, setVerbose, getPortNumber, getHomeDir
00030 
00031 # names of tags in XML configuration file
00032 doc_tag = "document"
00033 sec_tag = "section"
00034 par_tag = "parameter"
00035 import_tag = "import"
00036 
00037 # names of attributes in XML configuration file
00038 nam_att = "name"
00039 val_att = "value"
00040 
00041 # certain values in XML configuration file ("launch" section)
00042 lanch_nam      = "launch"
00043 help_nam       = "help"
00044 gui_nam        = "gui"
00045 splash_nam     = "splash"
00046 logger_nam     = "logger"
00047 xterm_nam      = "xterm"
00048 file_nam       = "file"
00049 portkill_nam   = "portkill"
00050 killall_nam    = "killall"
00051 modules_nam    = "modules"
00052 embedded_nam   = "embedded"
00053 standalone_nam = "standalone"
00054 key_nam        = "key"
00055 terminal_nam   = "terminal"
00056 interp_nam     = "interp"
00057 except_nam     = "noexcepthandler"
00058 terminal_nam   = "terminal"
00059 pinter_nam     = "pinter"
00060 batch_nam      = "batch"
00061 test_nam       = "test"
00062 play_nam       = "play"
00063 gdb_session_nam = "gdb_session"
00064 ddd_session_nam = "ddd_session"
00065 valgrind_session_nam = "valgrind_session"
00066 shutdown_servers_nam = "shutdown_servers"
00067 foreground_nam = "foreground"
00068 wake_up_session_nam = "wake_up_session"
00069 
00070 # values in XML configuration file giving specific module parameters (<module_name> section)
00071 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
00072 plugins_nam    = "plugins"
00073 
00074 # values passed as arguments, NOT read from XML config file, but set from within this script
00075 appname_nam    = "appname"
00076 port_nam       = "port"
00077 salomecfgname  = "salome"
00078 salomeappname  = "SalomeApp"
00079 script_nam     = "pyscript"
00080 
00081 # possible choices for the "embedded" and "standalone" parameters
00082 embedded_choices   = [ "registry", "study", "moduleCatalog", "cppContainer", "SalomeAppEngine" ]
00083 standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer", "pyContainer"]
00084 
00085 # values of boolean type (must be '0' or '1').
00086 # xml_parser.boolValue() is used for correct setting
00087 boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam, shutdown_servers_nam )
00088 intKeys = ( interp_nam, )
00089 
00090 # values of list type
00091 listKeys = ( embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
00092 
00093 ###
00094 # Get the application version
00095 # Uses GUI_ROOT_DIR (or KERNEL_ROOT_DIR in batch mode) +/bin/salome/VERSION file
00096 ###
00097 def version():
00098     try:
00099         filename = None
00100         root_dir = os.environ.get( 'KERNEL_ROOT_DIR', '' ) # KERNEL_ROOT_DIR or "" if not found
00101         if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
00102             filename = root_dir + "/bin/salome/VERSION"
00103         root_dir = os.environ.get( 'GUI_ROOT_DIR', '' )    # GUI_ROOT_DIR "" if not found
00104         if root_dir and os.path.exists( root_dir + "/bin/salome/VERSION" ):
00105             filename = root_dir + "/bin/salome/VERSION"
00106         if filename:
00107             str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
00108             match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
00109             if match :
00110                 return match.group( 1 )
00111     except:
00112         pass
00113     return ''
00114 
00115 ###
00116 # Calculate and return configuration file unique ID
00117 # For example: for SALOME version 3.1.0a1 the id is 300999701
00118 ###
00119 def version_id(fname):
00120     major = minor = release = dev1 = dev2 = 0
00121     vers = fname.split(".")
00122     if len(vers) > 0: major = int(vers[0])
00123     if len(vers) > 1: minor = int(vers[1])
00124     if len(vers) > 2:
00125         mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
00126         if mr:
00127             release = int(mr.group(1))
00128             if mr.group(2).strip(): dev1 = ord(mr.group(2).strip())
00129             if mr.group(3).strip(): dev2 = int(mr.group(3).strip())
00130             pass
00131         pass
00132     dev = dev1 * 100 + dev2
00133     ver = major
00134     ver = ver * 100 + minor
00135     ver = ver * 100 + release
00136     ver = ver * 10000
00137     if dev > 0: ver = ver - 10000 + dev
00138     return ver
00139 
00140 ###
00141 # Get default user configuration file name
00142 # For SALOME, it is:
00143 # - on Linux:   ~/.config/salome/.SalomeApprc.[version]
00144 # - on Windows: ~/SalomeApp.xml.[version]
00145 # where [version] is a version number
00146 ###
00147 def defaultUserFile(appname=salomeappname, cfgname=salomecfgname):
00148     v = version()
00149     if v: v = ".%s" % v
00150     if sys.platform == "win32":
00151       filename = os.path.join(getHomeDir(), "%s.xml%s" % (appname, v))
00152     else:
00153         if cfgname:
00154             filename = os.path.join(getHomeDir(), ".config", cfgname, ".%src%s" % (appname, v))
00155             pass
00156         else:
00157             filename = os.path.join(getHomeDir(), ".%src%s" % (appname, v))
00158             pass
00159         pass
00160     return filename
00161 
00162 ###
00163 # Get user configuration file name
00164 ###
00165 def userFile(appname, cfgname):
00166     # get app version
00167     v = version()
00168     if not v: return None                        # unknown version
00169     
00170     # get default user file name
00171     filename = defaultUserFile(appname, cfgname)
00172     if not filename: return None                 # default user file name is bad
00173     
00174     # check that default user file exists
00175     if os.path.exists(filename): return filename # user file is found
00176 
00177     # otherwise try to detect any appropriate user file
00178 
00179     # ... calculate default version id
00180     id0 = version_id(v)
00181     if not id0: return None                      # bad version id -> can't detect appropriate file
00182     
00183     # ... get all existing user preferences files
00184     if sys.platform == "win32":
00185         files = glob.glob(os.path.join(getHomeDir(), "%s.xml.*" % appname))
00186     else:
00187         files = []
00188         if cfgname: files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, ".%src.*" % appname))
00189         files             += glob.glob(os.path.join(getHomeDir(), ".%src.*" % appname))
00190         pass
00191 
00192     # ... loop through all files and find most appopriate file (with closest id)
00193     appr_id   = -1
00194     appr_file = ""
00195     for f in files:
00196         if sys.platform == "win32":
00197             match = re.search( r'%s\.xml\.([a-zA-Z0-9.]+)$'%appname, f )
00198         else:
00199             match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, f )
00200         if match:
00201             ver = version_id(match.group(1))
00202             if not ver: continue                 # bad version id -> skip file
00203             if appr_id < 0 or abs(appr_id-id0) > abs(ver-id0):
00204                 appr_id   = ver
00205                 appr_file = f
00206                 pass
00207             pass
00208         pass
00209     return appr_file
00210 
00211 # --
00212 
00213 def process_containers_params( standalone, embedded ):
00214     # 1. filter inappropriate containers names
00215     if standalone is not None:
00216         standalone = filter( lambda x: x in standalone_choices, standalone )
00217     if embedded is not None:
00218         embedded   = filter( lambda x: x in embedded_choices,   embedded )
00219 
00220     # 2. remove containers appearing in 'standalone' parameter from the 'embedded'
00221     # parameter --> i.e. 'standalone' parameter has higher priority
00222     if standalone is not None and embedded is not None:
00223         embedded = filter( lambda x: x not in standalone, embedded )
00224 
00225     # 3. return corrected parameters values
00226     return standalone, embedded
00227 
00228 # -----------------------------------------------------------------------------
00229 
00230 ###
00231 # XML reader for launch configuration file usage
00232 ###
00233 
00234 section_to_skip = ""
00235 
00236 class xml_parser:
00237     def __init__(self, fileName, _opts, _importHistory=[] ):
00238         if verbose(): print "Configure parser: processing %s ..." % fileName
00239         self.fileName = os.path.abspath(fileName)
00240         self.importHistory = _importHistory
00241         self.importHistory.append(self.fileName)
00242         self.space = []
00243         self.opts = _opts
00244         self.section = section_to_skip
00245         parser = xml.sax.make_parser()
00246         parser.setContentHandler(self)
00247         parser.parse(fileName)
00248         standalone, embedded = process_containers_params( self.opts.get( standalone_nam ),
00249                                                           self.opts.get( embedded_nam ) )
00250         if standalone is not None:
00251             self.opts[ standalone_nam ] = standalone
00252         if embedded is not None:
00253             self.opts[ embedded_nam ] = embedded
00254         pass
00255 
00256     def boolValue( self, str ):
00257         strloc = str
00258         if isinstance(strloc, types.UnicodeType):
00259             strloc = strloc.encode().strip()
00260         if isinstance(strloc, types.StringType):
00261             strlow = strloc.lower()
00262             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
00263                 return True
00264             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
00265                 return False
00266         return strloc
00267         pass
00268 
00269     def intValue( self, str ):
00270         strloc = str
00271         if isinstance(strloc, types.UnicodeType):
00272             strloc = strloc.encode().strip()
00273         if isinstance(strloc, types.StringType):
00274             strlow = strloc.lower()
00275             if strlow in   ("1", "yes", "y", "on", "true", "ok"):
00276                 return 1
00277             elif strlow in ("0", "no", "n", "off", "false", "cancel"):
00278                 return 0
00279             else:
00280                 return string.atoi(strloc)
00281         return strloc
00282         pass
00283 
00284     def startElement(self, name, attrs):
00285         self.space.append(name)
00286         self.current = None
00287         
00288         # if we are importing file
00289         if self.space == [doc_tag, import_tag] and nam_att in attrs.getNames():
00290             self.importFile( attrs.getValue(nam_att) )
00291         
00292         # if we are analyzing "section" element and its "name" attribute is
00293         # either "launch" or module name -- set section_name
00294         if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
00295             section_name = attrs.getValue( nam_att )
00296             if section_name == lanch_nam:
00297                 self.section = section_name # launch section
00298             elif self.opts.has_key( modules_nam ) and \
00299                  section_name in self.opts[ modules_nam ]:
00300                 self.section = section_name # <module> section
00301             else:
00302                 self.section = section_to_skip # any other section
00303             pass
00304 
00305         # if we are analyzing "parameter" elements - children of either
00306         # "section launch" or "section "<module>"" element, then store them
00307         # in self.opts assiciative array (key = [<module>_ + ] value of "name" attribute)
00308         elif self.section != section_to_skip           and \
00309              self.space == [doc_tag, sec_tag, par_tag] and \
00310              nam_att in attrs.getNames()               and \
00311              val_att in attrs.getNames():
00312             nam = attrs.getValue( nam_att )
00313             val = attrs.getValue( val_att )
00314             if self.section == lanch_nam: # key for launch section
00315                 key = nam
00316             else:                         # key for <module> section
00317                 key = self.section + "_" + nam
00318             if nam in boolKeys:
00319                 self.opts[key] = self.boolValue( val )  # assign boolean value: 0 or 1
00320             elif nam in intKeys:
00321                 self.opts[key] = self.intValue( val )   # assign integer value
00322             elif nam in listKeys:
00323                 self.opts[key] = filter( lambda a: a.strip(), re.split( "[:;,]", val ) ) # assign list value: []
00324             else:
00325                 self.opts[key] = val
00326             pass
00327         pass
00328 
00329     def endElement(self, name):
00330         p = self.space.pop()
00331         self.current = None
00332         if self.section != section_to_skip and name == sec_tag:
00333             self.section = section_to_skip
00334         pass
00335 
00336     def characters(self, content):
00337         pass
00338 
00339     def processingInstruction(self, target, data):
00340         pass
00341 
00342     def setDocumentLocator(self, locator):
00343         pass
00344 
00345     def startDocument(self):
00346         self.read = None
00347         pass
00348 
00349     def endDocument(self):
00350         self.read = None
00351         pass
00352     
00353     def importFile(self, fname):
00354         # get absolute name
00355         if os.path.isabs (fname) :
00356             absfname = fname
00357         else:
00358             absfname = os.path.join(os.path.dirname(self.fileName), fname)
00359         
00360         # check existing and registry file
00361         for ext in ["", ".xml", ".XML"] :
00362             if os.path.exists(absfname + ext) :
00363                 absfname += ext
00364                 if absfname in self.importHistory :
00365                     if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
00366                     return # already imported
00367                 break
00368             pass
00369         else:
00370             if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
00371             return
00372          
00373         # importing file
00374         try:
00375             # copy current options
00376             import copy
00377             opts = copy.deepcopy(self.opts)
00378             # import file
00379             imp = xml_parser(absfname, opts, self.importHistory)
00380             # merge results
00381             for key in imp.opts.keys():
00382                 if not self.opts.has_key(key):
00383                     self.opts[key] = imp.opts[key]
00384                     pass
00385                 pass
00386             pass
00387         except:
00388             if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
00389         pass
00390       
00391 
00392 # -----------------------------------------------------------------------------
00393 
00394 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok'     : True,
00395              '0': False, 'no' : False, 'n': False, 'off': False, 'false': False, 'cancel' : False }
00396 
00397 boolean_choices = booleans.keys()
00398 
00399 def check_embedded(option, opt, value, parser):
00400     from optparse import OptionValueError
00401     assert value is not None
00402     if parser.values.embedded:
00403         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
00404     else:
00405         embedded = []
00406     if parser.values.standalone:
00407         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
00408     else:
00409         standalone = []
00410     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
00411     for v in vals:
00412         if v not in embedded_choices:
00413             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, embedded_choices ) ) ) )
00414         if v not in embedded:
00415             embedded.append( v )
00416             if v in standalone:
00417                 del standalone[ standalone.index( v ) ]
00418                 pass
00419     parser.values.embedded = ",".join( embedded )
00420     parser.values.standalone = ",".join( standalone )
00421     pass
00422 
00423 def check_standalone(option, opt, value, parser):
00424     from optparse import OptionValueError
00425     assert value is not None
00426     if parser.values.embedded:
00427         embedded = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.embedded ) )
00428     else:
00429         embedded = []
00430     if parser.values.standalone:
00431         standalone = filter( lambda a: a.strip(), re.split( "[:;,]", parser.values.standalone ) )
00432     else:
00433         standalone = []
00434     vals = filter( lambda a: a.strip(), re.split( "[:;,]", value ) )
00435     for v in vals:
00436         if v not in standalone_choices:
00437             raise OptionValueError( "option %s: invalid choice: %r (choose from %s)" % ( opt, v, ", ".join( map( repr, standalone_choices ) ) ) )
00438         if v not in standalone:
00439             standalone.append( v )
00440             if v in embedded:
00441                 del embedded[ embedded.index( v ) ]
00442                 pass
00443     parser.values.embedded = ",".join( embedded )
00444     parser.values.standalone = ",".join( standalone )
00445     pass
00446 
00447 def store_boolean (option, opt, value, parser, *args):
00448     if isinstance(value, types.StringType):
00449         try:
00450             value_conv = booleans[value.strip().lower()]
00451             for attribute in args:
00452                 setattr(parser.values, attribute, value_conv)
00453         except KeyError:
00454             raise optparse.OptionValueError(
00455                 "option %s: invalid boolean value: %s (choose from %s)"
00456                 % (opt, value, boolean_choices))
00457     else:
00458         for attribute in args:
00459             setattr(parser.values, attribute, value)
00460 
00461 def CreateOptionParser (theAdditionalOptions=[]):
00462     # GUI/Terminal. Default: GUI
00463     help_str = "Launch without GUI (in the terminal mode)."
00464     o_t = optparse.Option("-t",
00465                           "--terminal",
00466                           action="store_false",
00467                           dest="gui",
00468                           help=help_str)
00469 
00470     help_str = "Launch in Batch Mode. (Without GUI on batch machine)"
00471     o_b = optparse.Option("-b",
00472                           "--batch",
00473                           action="store_true",
00474                           dest="batch",
00475                           help=help_str)
00476 
00477     help_str = "Launch in GUI mode [default]."
00478     o_g = optparse.Option("-g",
00479                           "--gui",
00480                           action="store_true",
00481                           dest="gui",
00482                           help=help_str)
00483 
00484     # Show Desktop (inly in GUI mode). Default: True
00485     help_str  = "1 to activate GUI desktop [default], "
00486     help_str += "0 to not activate GUI desktop (Session_Server starts, but GUI is not shown). "
00487     help_str += "Ignored in the terminal mode."
00488     o_d = optparse.Option("-d",
00489                           "--show-desktop",
00490                           metavar="<1/0>",
00491                           #type="choice", choices=boolean_choices,
00492                           type="string",
00493                           action="callback", callback=store_boolean, callback_args=('desktop',),
00494                           dest="desktop",
00495                           help=help_str)
00496     help_str  = "Do not activate GUI desktop (Session_Server starts, but GUI is not shown). "
00497     help_str += "The same as --show-desktop=0."
00498     o_o = optparse.Option("-o",
00499                           "--hide-desktop",
00500                           action="store_false",
00501                           dest="desktop",
00502                           help=help_str)
00503 
00504     # Use logger or log-file. Default: nothing.
00505     help_str = "Redirect messages to the CORBA collector."
00506     #o4 = optparse.Option("-l", "--logger", action="store_true", dest="logger", help=help_str)
00507     o_l = optparse.Option("-l",
00508                           "--logger",
00509                           action="store_const", const="CORBA",
00510                           dest="log_file",
00511                           help=help_str)
00512     help_str = "Redirect messages to the <log-file>"
00513     o_f = optparse.Option("-f",
00514                           "--log-file",
00515                           metavar="<log-file>",
00516                           type="string",
00517                           action="store",
00518                           dest="log_file",
00519                           help=help_str)
00520 
00521     # Execute python scripts. Default: None.
00522     help_str  = "Python script(s) to be imported. Python scripts are imported "
00523     help_str += "in the order of their appearance. In GUI mode python scripts "
00524     help_str += "are imported in the embedded python interpreter of current study, "
00525     help_str += "otherwise in an external python interpreter. "
00526     help_str += "Note: this option is obsolete. Instead you can pass Python script(s) "
00527     help_str += "directly as positional parameter."
00528     o_u = optparse.Option("-u",
00529                           "--execute",
00530                           metavar="<script1,script2,...>",
00531                           type="string",
00532                           action="append",
00533                           dest="py_scripts",
00534                           help=help_str)
00535 
00536     # Configuration XML file. Default: see defaultUserFile() function
00537     help_str  = "Parse application settings from the <file> "
00538     help_str += "instead of default %s" % defaultUserFile()
00539     o_r = optparse.Option("-r",
00540                           "--resources",
00541                           metavar="<file>",
00542                           type="string",
00543                           action="store",
00544                           dest="resources",
00545                           help=help_str)
00546 
00547     # Use own xterm for each server. Default: False.
00548     help_str = "Launch each SALOME server in own xterm console"
00549     o_x = optparse.Option("-x",
00550                           "--xterm",
00551                           action="store_true",
00552                           dest="xterm",
00553                           help=help_str)
00554 
00555     # Modules. Default: Like in configuration files.
00556     help_str  = "SALOME modules list (where <module1>, <module2> are the names "
00557     help_str += "of SALOME modules which should be available in the SALOME session)"
00558     o_m = optparse.Option("-m",
00559                           "--modules",
00560                           metavar="<module1,module2,...>",
00561                           type="string",
00562                           action="append",
00563                           dest="modules",
00564                           help=help_str)
00565 
00566     # Embedded servers. Default: Like in configuration files.
00567     help_str  = "CORBA servers to be launched in the Session embedded mode. "
00568     help_str += "Valid values for <serverN>: %s " % ", ".join( embedded_choices )
00569     help_str += "[by default the value from the configuration files is used]"
00570     o_e = optparse.Option("-e",
00571                           "--embedded",
00572                           metavar="<server1,server2,...>",
00573                           type="string",
00574                           action="callback",
00575                           dest="embedded",
00576                           callback=check_embedded,
00577                           help=help_str)
00578 
00579     # Standalone servers. Default: Like in configuration files.
00580     help_str  = "CORBA servers to be launched in the standalone mode (as separate processes). "
00581     help_str += "Valid values for <serverN>: %s " % ", ".join( standalone_choices )
00582     help_str += "[by default the value from the configuration files is used]"
00583     o_s = optparse.Option("-s",
00584                           "--standalone",
00585                           metavar="<server1,server2,...>",
00586                           type="string",
00587                           action="callback",
00588                           dest="standalone",
00589                           callback=check_standalone,
00590                           help=help_str)
00591 
00592     # Kill with port. Default: False.
00593     help_str = "Kill SALOME with the current port"
00594     o_p = optparse.Option("-p",
00595                           "--portkill",
00596                           action="store_true",
00597                           dest="portkill",
00598                           help=help_str)
00599 
00600     # Kill all. Default: False.
00601     help_str = "Kill all running SALOME sessions"
00602     o_k = optparse.Option("-k",
00603                           "--killall",
00604                           action="store_true",
00605                           dest="killall",
00606                           help=help_str)
00607 
00608     # Additional python interpreters. Default: 0.
00609     help_str  = "The number of additional external python interpreters to run. "
00610     help_str += "Each additional python interpreter is run in separate "
00611     help_str += "xterm session with properly set SALOME environment"
00612     o_i = optparse.Option("-i",
00613                           "--interp",
00614                           metavar="<N>",
00615                           type="int",
00616                           action="store",
00617                           dest="interp",
00618                           help=help_str)
00619 
00620     # Splash. Default: True.
00621     help_str  = "1 to display splash screen [default], "
00622     help_str += "0 to disable splash screen. "
00623     help_str += "This option is ignored in the terminal mode. "
00624     help_str += "It is also ignored if --show-desktop=0 option is used."
00625     o_z = optparse.Option("-z",
00626                           "--splash",
00627                           metavar="<1/0>",
00628                           #type="choice", choices=boolean_choices,
00629                           type="string",
00630                           action="callback", callback=store_boolean, callback_args=('splash',),
00631                           dest="splash",
00632                           help=help_str)
00633 
00634     # Catch exceptions. Default: True.
00635     help_str  = "1 (yes,true,on,ok) to enable centralized exception handling [default], "
00636     help_str += "0 (no,false,off,cancel) to disable centralized exception handling."
00637     o_c = optparse.Option("-c",
00638                           "--catch-exceptions",
00639                           metavar="<1/0>",
00640                           #type="choice", choices=boolean_choices,
00641                           type="string",
00642                           action="callback", callback=store_boolean, callback_args=('catch_exceptions',),
00643                           dest="catch_exceptions",
00644                           help=help_str)
00645 
00646     # Print free port and exit
00647     help_str = "Print free port and exit"
00648     o_a = optparse.Option("--print-port",
00649                           action="store_true",
00650                           dest="print_port", default=False,
00651                           help=help_str)
00652 
00653     # Do not relink ${HOME}/.omniORB_last.cfg
00654     help_str = "Do not save current configuration ${HOME}/.omniORB_last.cfg"
00655     o_n = optparse.Option("--nosave-config",
00656                           action="store_false",
00657                           dest="save_config", default=True,
00658                           help=help_str)
00659 
00660     # Launch with interactive python console. Default: False.
00661     help_str = "Launch with interactive python console."
00662     o_pi = optparse.Option("--pinter",
00663                           action="store_true",
00664                           dest="pinter",
00665                           help=help_str)
00666 
00667     # Print Naming service port into a user file. Default: False.
00668     help_str = "Print Naming Service Port into a user file."
00669     o_nspl = optparse.Option("--ns-port-log",
00670                              metavar="<ns_port_log_file>",
00671                              type="string",
00672                              action="store",
00673                              dest="ns_port_log_file",
00674                              help=help_str)
00675 
00676     # Write/read test script file with help of TestRecorder. Default: False.
00677     help_str = "Write/read test script file with help of TestRecorder."
00678     o_test = optparse.Option("--test",
00679                              metavar="<test_script_file>",
00680                              type="string",
00681                              action="store",
00682                              dest="test_script_file",
00683                              help=help_str)
00684 
00685     # Reproducing test script with help of TestRecorder. Default: False.
00686     help_str = "Reproducing test script with help of TestRecorder."
00687     o_play = optparse.Option("--play",
00688                              metavar="<play_script_file>",
00689                              type="string",
00690                              action="store",
00691                              dest="play_script_file",
00692                              help=help_str)
00693 
00694     # gdb session
00695     help_str = "Launch session with gdb"
00696     o_gdb = optparse.Option("--gdb-session",
00697                             action="store_true",
00698                             dest="gdb_session", default=False,
00699                             help=help_str)
00700 
00701     # ddd session
00702     help_str = "Launch session with ddd"
00703     o_ddd = optparse.Option("--ddd-session",
00704                             action="store_true",
00705                             dest="ddd_session", default=False,
00706                             help=help_str)
00707 
00708 
00709     # valgrind session
00710     help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
00711     o_valgrind = optparse.Option("--valgrind-session",
00712                                  action="store_true",
00713                                  dest="valgrind_session", default=False,
00714                                  help=help_str)
00715 
00716     # shutdown-servers. Default: False.
00717     help_str  = "1 to shutdown standalone servers when leaving python interpreter, "
00718     help_str += "0 to keep the standalone servers as daemon [default]. "
00719     help_str += "This option is only useful in batchmode "
00720     help_str += "(terminal mode or without showing desktop)."
00721     o_shutdown = optparse.Option("--shutdown-servers",
00722                                  metavar="<1/0>",
00723                                  #type="choice", choices=boolean_choices,
00724                                  type="string",
00725                                  action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
00726                                  dest="shutdown_servers",
00727                                  help=help_str)
00728 
00729     # foreground. Default: True.
00730     help_str  = "0 and runSalome exits after have launched the gui, "
00731     help_str += "1 to launch runSalome in foreground mode [default]."
00732     o_foreground = optparse.Option("--foreground",
00733                                    metavar="<1/0>",
00734                                    #type="choice", choices=boolean_choices,
00735                                    type="string",
00736                                    action="callback", callback=store_boolean, callback_args=('foreground',),
00737                                    dest="foreground",
00738                                    help=help_str)
00739 
00740     # wake up session
00741     help_str  = "Wake up a previously closed session. "
00742     help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
00743     help_str += "If this variable is not setted, the last configuration is taken. "
00744     o_wake_up = optparse.Option("--wake-up-session",
00745                                 action="store_true",
00746                                 dest="wake_up_session", default=False,
00747                                 help=help_str)
00748 
00749     # server launch mode
00750     help_str = "Mode used to launch server processes (daemon or fork)."
00751     o_slm = optparse.Option("--server-launch-mode",
00752                             metavar="<server_launch_mode>",
00753                             type="choice",
00754                             choices=["daemon","fork"],
00755                             action="store",
00756                             dest="server_launch_mode",
00757                             help=help_str)
00758 
00759     # All options
00760     opt_list = [o_t,o_g, # GUI/Terminal
00761                 o_d,o_o, # Desktop
00762                 o_b,     # Batch
00763                 o_l,o_f, # Use logger or log-file
00764                 o_u,     # Execute python scripts
00765                 o_r,     # Configuration XML file
00766                 o_x,     # xterm
00767                 o_m,     # Modules
00768                 o_e,     # Embedded servers
00769                 o_s,     # Standalone servers
00770                 o_p,     # Kill with port
00771                 o_k,     # Kill all
00772                 o_i,     # Additional python interpreters
00773                 o_z,     # Splash
00774                 o_c,     # Catch exceptions
00775                 o_a,     # Print free port and exit
00776                 o_n,     # --nosave-config
00777                 o_pi,    # Interactive python console
00778                 o_nspl,
00779                 o_test,  # Write/read test script file with help of TestRecorder
00780                 o_play,  # Reproducing test script with help of TestRecorder
00781                 o_gdb,
00782                 o_ddd,
00783                 o_valgrind,
00784                 o_shutdown,
00785                 o_foreground,
00786                 o_wake_up,
00787                 o_slm,   # Server launch mode
00788                 ]
00789 
00790     #std_options = ["gui", "desktop", "log_file", "py_scripts", "resources",
00791     #               "xterm", "modules", "embedded", "standalone",
00792     #               "portkill", "killall", "interp", "splash",
00793     #               "catch_exceptions", "print_port", "save_config", "ns_port_log_file"]
00794 
00795     opt_list += theAdditionalOptions
00796 
00797     a_usage = "%prog [options] [STUDY_FILE] [PYTHON_FILE [PYTHON_FILE ...]]"
00798     version_str = "Salome %s" % version()
00799     pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
00800 
00801     return pars
00802 
00803 # -----------------------------------------------------------------------------
00804 
00805 ###
00806 # Get the environment
00807 ###
00808 
00809 # this attribute is obsolete
00810 args = {}
00811 #def get_env():
00812 #args = []
00813 def get_env(theAdditionalOptions=[], appname=salomeappname, cfgname=salomecfgname):
00814     ###
00815     # Collect launch configuration files:
00816     # - The environment variable "<appname>Config" (SalomeAppConfig) which can
00817     #   define a list of directories (separated by ':' or ';' symbol) is checked
00818     # - If the environment variable "<appname>Config" is not set, only
00819     #   ${GUI_ROOT_DIR}/share/salome/resources/gui is inspected
00820     # - ${GUI_ROOT_DIR}/share/salome/resources/gui directory is always inspected
00821     #   so it is not necessary to put it in the "<appname>Config" variable
00822     # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
00823     #  (SalomeApp.xml) which define SALOME configuration
00824     # - These directories are analyzed beginning from the last one in the list,
00825     #   so the first directory listed in "<appname>Config" environment variable
00826     #   has higher priority: it means that if some configuration options
00827     #   is found in the next analyzed cofiguration file - it will be replaced
00828     # - The last configuration file which is parsed is user configuration file
00829     #   situated in the home directory (if it exists):
00830     #   * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
00831     #   * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
00832     # - Command line options have the highest priority and replace options
00833     #   specified in configuration file(s)
00834     ###
00835 
00836     global args
00837     config_var = appname+'Config'
00838 
00839     separator = ":"
00840     if os.sys.platform == 'win32':
00841         separator = ";"
00842 
00843     # check KERNEL_ROOT_DIR
00844     try:
00845         kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
00846     except:
00847         print """
00848         For each SALOME module, the environment variable <moduleN>_ROOT_DIR must be set.
00849         KERNEL_ROOT_DIR is mandatory.
00850         """
00851         sys.exit(1)
00852         pass
00853 
00854     ############################
00855     # parse command line options
00856     pars = CreateOptionParser(theAdditionalOptions)
00857     (cmd_opts, cmd_args) = pars.parse_args(sys.argv[1:])
00858     ############################
00859 
00860     # Process --print-port option
00861     if cmd_opts.print_port:
00862         from runSalome import searchFreePort
00863         searchFreePort({})
00864         print "port:%s"%(os.environ['NSPORT'])
00865         sys.exit(0)
00866         pass
00867 
00868     # set resources variable SalomeAppConfig if it is not set yet
00869     dirs = []
00870     if os.getenv(config_var):
00871         if sys.platform == 'win32':
00872             dirs += re.split(';', os.getenv(config_var))
00873         else:
00874             dirs += re.split('[;|:]', os.getenv(config_var))
00875 
00876     gui_available = True
00877     if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
00878         dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
00879         pass
00880     else:
00881         gui_available = False
00882         if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ):
00883             dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"]
00884         pass
00885     os.environ[config_var] = separator.join(dirs)
00886 
00887     dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
00888 
00889     try:
00890         dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
00891     except:
00892         pass
00893 
00894     _opts = {} # associative array of options to be filled
00895 
00896     # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
00897     for dir in dirs:
00898         filename = os.path.join(dir, appname+'.xml')
00899         if not os.path.exists(filename):
00900             if verbose(): print "Configure parser: Warning : can not find configuration file %s" % filename
00901         else:
00902             try:
00903                 p = xml_parser(filename, _opts)
00904                 _opts = p.opts
00905             except:
00906                 if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
00907             pass
00908 
00909     # parse user configuration file
00910     # It can be set via --resources=<file> command line option
00911     # or is given from default location (see defaultUserFile() function)
00912     # If user file for the current version is not found the nearest to it is used
00913     user_config = cmd_opts.resources
00914     if not user_config:
00915         user_config = userFile(appname, cfgname)
00916         if verbose(): print "Configure parser: user configuration file is", user_config
00917     if not user_config or not os.path.exists(user_config):
00918         if verbose(): print "Configure parser: Warning : can not find user configuration file"
00919     else:
00920         try:
00921             p = xml_parser(user_config, _opts)
00922             _opts = p.opts
00923         except:
00924             if verbose(): print 'Configure parser: Error : can not read user configuration file'
00925             user_config = ""
00926 
00927     args = _opts
00928 
00929     args['user_config'] = user_config
00930     #print "User Configuration file: ", args['user_config']
00931 
00932     # set default values for options which are NOT set in config files
00933     for aKey in listKeys:
00934         if not args.has_key( aKey ):
00935             args[aKey]=[]
00936 
00937     for aKey in boolKeys:
00938         if not args.has_key( aKey ):
00939             args[aKey]=0
00940 
00941     if args[file_nam]:
00942         afile=args[file_nam]
00943         args[file_nam]=[afile]
00944 
00945     args[appname_nam] = appname
00946 
00947     # get the port number
00948     my_port = getPortNumber()
00949 
00950     args[port_nam] = my_port
00951 
00952     ####################################################
00953     # apply command-line options to the arguments
00954     # each option given in command line overrides the option from xml config file
00955     #
00956     # Options: gui, desktop, log_file, py_scripts, resources,
00957     #          xterm, modules, embedded, standalone,
00958     #          portkill, killall, interp, splash,
00959     #          catch_exceptions, pinter
00960 
00961     # GUI/Terminal, Desktop, Splash, STUDY_HDF
00962     args["session_gui"] = False
00963     args[batch_nam] = False
00964     args["study_hdf"] = None
00965     if cmd_opts.gui is not None:
00966         args[gui_nam] = cmd_opts.gui
00967     if cmd_opts.batch is not None:
00968         args[batch_nam] = True
00969 
00970     if not gui_available:
00971         args[gui_nam] = False
00972 
00973     if args[gui_nam]:
00974         args["session_gui"] = True
00975         if cmd_opts.desktop is not None:
00976             args["session_gui"] = cmd_opts.desktop
00977             args[splash_nam]    = cmd_opts.desktop
00978         if args["session_gui"]:
00979             if cmd_opts.splash is not None:
00980                 args[splash_nam] = cmd_opts.splash
00981     else:
00982         args["session_gui"] = False
00983         args[splash_nam] = False
00984 
00985     # Logger/Log file
00986     if cmd_opts.log_file is not None:
00987         if cmd_opts.log_file == 'CORBA':
00988             args[logger_nam] = True
00989         else:
00990             args[file_nam] = [cmd_opts.log_file]
00991 
00992     # Naming Service port log file
00993     if cmd_opts.ns_port_log_file is not None:
00994       args["ns_port_log_file"] = cmd_opts.ns_port_log_file
00995 
00996     # Python scripts
00997     args[script_nam] = []
00998     if cmd_opts.py_scripts is not None:
00999         listlist = cmd_opts.py_scripts
01000         for listi in listlist:
01001             if os.sys.platform == 'win32':
01002                 args[script_nam] += re.split( "[;,]", listi)
01003             else:
01004                 args[script_nam] += re.split( "[:;,]", listi)
01005     for arg in cmd_args:
01006         if arg[-3:] == ".py":
01007             args[script_nam].append(arg)
01008         elif not args["study_hdf"]:
01009             args["study_hdf"] = arg
01010             pass
01011         pass
01012 
01013     # xterm
01014     if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
01015 
01016     # Modules
01017     if cmd_opts.modules is not None:
01018         args[modules_nam] = []
01019         listlist = cmd_opts.modules
01020         for listi in listlist:
01021             args[modules_nam] += re.split( "[:;,]", listi)
01022     else:
01023         # if --modules (-m) command line option is not given
01024         # try SALOME_MODULES environment variable
01025         if os.getenv( "SALOME_MODULES" ):
01026             args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
01027             pass
01028 
01029     # Embedded
01030     if cmd_opts.embedded is not None:
01031         args[embedded_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.embedded ) )
01032 
01033     # Standalone
01034     if cmd_opts.standalone is not None:
01035         args[standalone_nam] = filter( lambda a: a.strip(), re.split( "[:;,]", cmd_opts.standalone ) )
01036 
01037     # Normalize the '--standalone' and '--embedded' parameters
01038     standalone, embedded = process_containers_params( args.get( standalone_nam ),
01039                                                       args.get( embedded_nam ) )
01040     if standalone is not None:
01041         args[ standalone_nam ] = standalone
01042     if embedded is not None:
01043         args[ embedded_nam ] = embedded
01044 
01045     # Kill
01046     if cmd_opts.portkill is not None: args[portkill_nam] = cmd_opts.portkill
01047     if cmd_opts.killall  is not None: args[killall_nam]  = cmd_opts.killall
01048 
01049     # Interpreter
01050     if cmd_opts.interp is not None:
01051         args[interp_nam] = cmd_opts.interp
01052 
01053     # Exceptions
01054     if cmd_opts.catch_exceptions is not None:
01055         args[except_nam] = not cmd_opts.catch_exceptions
01056 
01057     # Relink config file
01058     if cmd_opts.save_config is not None:
01059         args['save_config'] = cmd_opts.save_config
01060 
01061     # Interactive python console
01062     if cmd_opts.pinter is not None:
01063         args[pinter_nam] = cmd_opts.pinter
01064 
01065     # Gdb session in xterm
01066     if cmd_opts.gdb_session is not None:
01067         args[gdb_session_nam] = cmd_opts.gdb_session
01068 
01069     # Ddd session in xterm
01070     if cmd_opts.ddd_session is not None:
01071         args[ddd_session_nam] = cmd_opts.ddd_session
01072 
01073     # valgrind session
01074     if cmd_opts.valgrind_session is not None:
01075         args[valgrind_session_nam] = cmd_opts.valgrind_session
01076 
01077     # Shutdown servers
01078     if cmd_opts.shutdown_servers is None:
01079         args[shutdown_servers_nam] = 0
01080     else:
01081         args[shutdown_servers_nam] = cmd_opts.shutdown_servers
01082         pass
01083 
01084     # Foreground
01085     if cmd_opts.foreground is None:
01086         args[foreground_nam] = 1
01087     else:
01088         args[foreground_nam] = cmd_opts.foreground
01089         pass
01090 
01091     # wake up session
01092     if cmd_opts.wake_up_session is not None:
01093         args[wake_up_session_nam] = cmd_opts.wake_up_session
01094 
01095     ####################################################
01096     # Add <theAdditionalOptions> values to args
01097     for add_opt in theAdditionalOptions:
01098         cmd = "args[\"%s\"] = cmd_opts.%s"%(add_opt.dest,add_opt.dest)
01099         exec(cmd)
01100     ####################################################
01101 
01102     # disable signals handling
01103     if args[except_nam] == 1:
01104         os.environ["NOT_INTERCEPT_SIGNALS"] = "1"
01105         pass
01106 
01107     # now modify SalomeAppConfig environment variable
01108     # to take into account the SALOME modules
01109     if os.sys.platform == 'win32':
01110         dirs = re.split('[;]', os.environ[config_var] )
01111     else:
01112         dirs = re.split('[;|:]', os.environ[config_var] )
01113     for m in args[modules_nam]:
01114         if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
01115             d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
01116             d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
01117             #if os.path.exists( "%s/%s.xml"%(d1, appname) ):
01118             if os.path.exists( "%s/%s.xml"%(d1, salomeappname) ):
01119                 dirs.append( d1 )
01120             #elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
01121             elif os.path.exists( "%s/%s.xml"%(d2, salomeappname) ):
01122                 dirs.append( d2 )
01123 
01124     # Test
01125     if cmd_opts.test_script_file is not None:
01126         args[test_nam] = []
01127         filename = cmd_opts.test_script_file
01128         args[test_nam] += re.split( "[:;,]", filename )
01129 
01130     # Play
01131     if cmd_opts.play_script_file is not None:
01132         args[play_nam] = []
01133         filename = cmd_opts.play_script_file
01134         args[play_nam] += re.split( "[:;,]", filename )
01135 
01136     # Server launch command
01137     if cmd_opts.server_launch_mode is not None:
01138       args["server_launch_mode"] = cmd_opts.server_launch_mode
01139 
01140     # return arguments
01141     os.environ[config_var] = separator.join(dirs)
01142     #print "Args: ", args
01143     return args