Salome HOME
PR: ROOT_DIR to virtual link = APPLI directory
[modules/kernel.git] / bin / launchConfigureParser.py
index f1bd606db4da0ddd7d4a8e39e42f2006a045c1a7..f1ae79eaaefdcaacd505ef7126e9909472c16b18 100755 (executable)
@@ -1,12 +1,30 @@
+# Copyright (C) 2005  OPEN CASCADE, CEA, EDF R&D, LEG
+#           PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
 import os, glob, string, sys, re
 import xml.sax
 
-# names of tags in XML configuration file 
+# names of tags in XML configuration file
 doc_tag = "document"
 sec_tag = "section"
 par_tag = "parameter"
 
-# names of attributes in XML configuration file 
+# names of attributes in XML configuration file
 nam_att = "name"
 val_att = "value"
 
@@ -20,12 +38,12 @@ file_nam       = "file"
 portkill_nam   = "portkill"
 killall_nam    = "killall"
 modules_nam    = "modules"
-pyModules_nam  = "pyModules"
 embedded_nam   = "embedded"
 standalone_nam = "standalone"
 containers_nam = "containers"
 key_nam        = "key"
 interp_nam     = "interp"
+except_nam     = "noexcepthandler"
 
 # values in XML configuration file giving specific module parameters (<module_name> section)
 # which are stored in opts with key <module_name>_<parameter> (eg SMESH_plugins)
@@ -35,10 +53,11 @@ plugins_nam    = "plugins"
 appname_nam    = "appname"
 port_nam       = "port"
 appname        = "SalomeApp"
+script_nam     = "pyscript"
 
 # values of boolean type (must be '0' or '1').
 # xml_parser.boolValue() is used for correct setting
-boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, interp_nam )
+boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, interp_nam, except_nam )
 
 # values of list type
 listKeys = ( containers_nam, embedded_nam, key_nam, modules_nam, standalone_nam, plugins_nam )
@@ -49,11 +68,59 @@ def version():
     root_dir = os.environ.get( 'GUI_ROOT_DIR', root_dir )  # GUI_ROOT_DIR or KERNEL_ROOT_DIR or "" if both not found
     filename = root_dir+'/bin/salome/VERSION'
     str = open( filename, "r" ).readline() # str = "THIS IS SALOME - SALOMEGUI VERSION: 3.0.0"
-    match = re.search( r':\s+([\d\.]+)\s*$', str )
+    match = re.search( r':\s+([a-zA-Z0-9.]+)\s*$', str )
     if match :
         return match.group( 1 )
     return ''
-    
+
+# calculate and return configuration file id in order to unically identify it
+# for example: for 3.1.0a1 the id is 301000101
+def version_id( fname ):
+    vers = fname.split(".")
+    major   = int(vers[0])
+    minor   = int(vers[1])
+    mr = re.search(r'^([0-9]+)([A-Za-z]?)([0-9]*)',vers[2])
+    release = dev = 0
+    if mr:
+        release = int(mr.group(1))
+        dev1 = dev2 = 0
+        if len(mr.group(2)): dev1 = ord(mr.group(2))
+        if len(mr.group(3)): dev2 = int(mr.group(3))
+        dev = dev1 * 100 + dev2
+    else:
+        return None
+    ver = major
+    ver = ver * 100 + minor
+    ver = ver * 100 + release
+    ver = ver * 10000
+    if dev > 0: ver = ver - 10000 + dev
+    return ver
+
+# get user configuration file name
+def userFile():
+    v = version()
+    if not v:
+        return ""        # not unknown version
+    filename = "%s/.%src.%s" % (os.environ['HOME'], appname, v)
+    if os.path.exists(filename):
+        return filename  # user preferences file for the current version exists
+    # initial id
+    id0 = version_id( v )
+    # get all existing user preferences files
+    files = glob.glob( os.environ['HOME'] + "/." + appname + "rc.*" )
+    f2v = {}
+    for file in files:
+        match = re.search( r'\.%src\.([a-zA-Z0-9.]+)$'%appname, file )
+        if match: f2v[file] = match.group(1)
+    last_file = ""
+    last_version = 0
+    for file in f2v:
+        ver = version_id( f2v[file] )
+        if ver and abs(last_version-id0) > abs(ver-id0):
+            last_version = ver
+            last_file = file
+    return last_file
+
 # -----------------------------------------------------------------------------
 
 ### xml reader for launch configuration file usage
@@ -62,7 +129,7 @@ section_to_skip = ""
 
 class xml_parser:
     def __init__(self, fileName, _opts ):
-        print "Processing ",fileName 
+        print "Configure parser: processing %s ..." % fileName
         self.space = []
         self.opts = _opts
         self.section = section_to_skip
@@ -160,8 +227,14 @@ class xml_parser:
 # -     command line
 
 config_var = appname+'Config'
-dirs = os.environ[config_var]
-dirs = dirs.split( ';' )
+# set resources variables if not yet set
+dirs = []
+if os.getenv(config_var):
+    dirs += re.split('[;|:]', os.getenv(config_var))
+if os.getenv("GUI_ROOT_DIR"):
+    dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
+os.environ[config_var] = ":".join(dirs)
+
 dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
 
 _opts = {} # assiciative array of options to be filled
@@ -169,21 +242,26 @@ _opts = {} # assiciative array of options to be filled
 # SalomeApp.xml files in directories specified by SalomeAppConfig env variable
 for dir in dirs:
     filename = dir+'/'+appname+'.xml'
+    if not os.path.exists(filename):
+        print "Configure parser: Warning : could not find configuration file %s" % filename
+    else:
+        try:
+            p = xml_parser(filename, _opts)
+            _opts = p.opts
+        except:
+            print "Configure parser: Error : can not read configuration file %s" % filename
+        pass
+
+# SalomeApprc file in user's catalogue
+filename = userFile()
+if not filename or not os.path.exists(filename):
+    print "Configure parser: Warning : could not find user configuration file"
+else:
     try:
         p = xml_parser(filename, _opts)
         _opts = p.opts
     except:
-        print 'Can not read launch configuration file ', filename
-        continue
-
-# SalomeApprc file in user's catalogue
-filename = os.environ['HOME']+'/.'+appname+'rc.'+version()
-try:
-    p = xml_parser(filename, _opts)
-    _opts = p.opts
-except:
-    print 'Can not read launch configuration file ', filename
-
+        print 'Configure parser: Error : can not read user configuration file'
 
 args = _opts
 
@@ -191,15 +269,15 @@ args = _opts
 for aKey in listKeys:
     if not args.has_key( aKey ):
         args[aKey]=[]
-        
+
 for aKey in boolKeys:
     if not args.has_key( aKey ):
         args[aKey]=0
-        
+
 if args[file_nam]:
     afile=args[file_nam]
     args[file_nam]=[afile]
-    
+
 args[appname_nam] = appname
 
 ### searching for my port
@@ -235,8 +313,6 @@ def options_parser(line):
     list = []
     pass
 
-  #print "source=",source
-  
   result = {}
   i = 0
   while i < len(source):
@@ -247,7 +323,7 @@ def options_parser(line):
     else:
       key = source[i][1]
       pass
-    
+
     result[key] = []
     if key:
       i += 1
@@ -265,7 +341,6 @@ def options_parser(line):
 cmd_opts = {}
 try:
     cmd_opts = options_parser(sys.argv[1:])
-    #print "opts=",cmd_opts
     kernel_root_dir=os.environ["KERNEL_ROOT_DIR"]
 except:
     cmd_opts["h"] = 1
@@ -275,8 +350,8 @@ except:
 
 opterror=0
 for opt in cmd_opts:
-    if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i"):
-        print "command line error: -", opt
+    if not opt in ("h","g","l","f","x","m","e","s","c","p","k","t","i","r"):
+        print "Configure parser: Error : command line error : -%s" % opt
         opterror=1
 
 if opterror == 1:
@@ -288,8 +363,10 @@ if cmd_opts.has_key("h"):
     --help or -h                  : print this help
     --gui or -g                   : launching with GUI
     --terminal -t                 : launching without gui (to deny --gui)
+    or -t=PythonScript[,...]
+                                  : import of PythonScript(s)
     --logger or -l                : redirect messages in a CORBA collector
-    --file=filename or -f=filename: redirect messages in a log file  
+    --file=filename or -f=filename: redirect messages in a log file
     --xterm or -x                 : execute servers in xterm console (messages appear in xterm windows)
     --modules=module1,module2,... : salome module list (modulen is the name of Salome module to load)
     or -m=module1,module2,...
@@ -306,7 +383,8 @@ if cmd_opts.has_key("h"):
     --killall or -k               : kill all salome sessions
     --interp=n or -i=n            : number of additional xterm to open, with session environment
     -z                            : display splash screen
-    
+    -r                            : disable centralized exception handling mechanism
+
     For each Salome module, the environment variable <modulen>_ROOT_DIR must be set.
     The module name (<modulen>) must be uppercase.
     KERNEL_ROOT_DIR is mandatory.
@@ -320,6 +398,8 @@ for opt in cmd_opts:
         args[gui_nam] = 1
     elif opt == 'z':
        args[splash_nam] = 1
+    elif opt == 'r':
+       args[except_nam] = 1
     elif opt == 'l':
         args[logger_nam] = 1
     elif opt == 'f':
@@ -343,9 +423,32 @@ for opt in cmd_opts:
         pass
     pass
 
+# if --modules (-m) command line option is not given
+# try SALOME_MODULES environment variable
+if not cmd_opts.has_key( "m" ) and os.getenv( "SALOME_MODULES" ):
+    args[modules_nam] = re.split( "[:;,]", os.getenv( "SALOME_MODULES" ) )
+    pass
+
 # 'terminal' must be processed in the end: to deny any 'gui' options
+args[script_nam] = []
 if 't' in cmd_opts:
     args[gui_nam] = 0
+    args[script_nam] = cmd_opts['t']
+    pass
+
+if args[except_nam] == 1:
+    os.environ["DISABLE_FPE"] = "1"
     pass
 
-#print "args=",args
+# now modify SalomeAppConfig environment variable
+dirs = re.split('[;|:]', os.environ[config_var] )
+
+for m in args[modules_nam]:
+    if m not in ["KERNEL", "GUI", ""] and os.getenv("%s_ROOT_DIR"%m):
+        d1 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources/" + m.lower()
+        d2 = os.getenv("%s_ROOT_DIR"%m) + "/share/salome/resources"
+        if os.path.exists( "%s/%s.xml"%(d1, appname) ):
+            dirs.append( d1 )
+        elif os.path.exists( "%s/%s.xml"%(d2, appname) ):
+            dirs.append( d2 )
+os.environ[config_var] = ":".join(dirs)