Salome HOME
New CMake procedure.
[modules/kernel.git] / bin / launchConfigureParser.py
index 87630757e733c92f460f1922530f6275e530e197..4d484ffd0918e0685ecec0d9a0a534e547c55f2d 100755 (executable)
@@ -1,33 +1,38 @@
-#  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+#  -*- coding: iso-8859-1 -*-
+# Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
 #
-#  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
-#  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+# Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
 #
-#  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 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.
+# 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
+# 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
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
 #
+
 import os, glob, string, sys, re
 import xml.sax
 import optparse
 import types
 
+from salome_utils import verbose, setVerbose, getPortNumber, getHomeDir
+
 # names of tags in XML configuration file
 doc_tag = "document"
 sec_tag = "section"
 par_tag = "parameter"
+import_tag = "import"
 
 # names of attributes in XML configuration file
 nam_att = "name"
@@ -56,6 +61,11 @@ batch_nam      = "batch"
 test_nam       = "test"
 play_nam       = "play"
 gdb_session_nam = "gdb_session"
+ddd_session_nam = "ddd_session"
+valgrind_session_nam = "valgrind_session"
+shutdown_servers_nam = "shutdown_servers"
+foreground_nam = "foreground"
+wake_up_session_nam = "wake_up_session"
 
 # 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)
@@ -64,16 +74,18 @@ plugins_nam    = "plugins"
 # values passed as arguments, NOT read from XML config file, but set from within this script
 appname_nam    = "appname"
 port_nam       = "port"
+useport_nam    = "useport"
+salomecfgname  = "salome"
 salomeappname  = "SalomeApp"
 script_nam     = "pyscript"
 
 # possible choices for the "embedded" and "standalone" parameters
 embedded_choices   = [ "registry", "study", "moduleCatalog", "cppContainer", "SalomeAppEngine" ]
-standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer", "pyContainer", "supervContainer"]
+standalone_choices = [ "registry", "study", "moduleCatalog", "cppContainer"]
 
 # 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, except_nam, pinter_nam )
+boolKeys = ( gui_nam, splash_nam, logger_nam, file_nam, xterm_nam, portkill_nam, killall_nam, except_nam, pinter_nam, shutdown_servers_nam )
 intKeys = ( interp_nam, )
 
 # values of list type
@@ -105,83 +117,114 @@ def version():
 # Calculate and return configuration file unique ID
 # For example: for SALOME version 3.1.0a1 the id is 300999701
 ###
-def version_id( fname ):
+def version_id(fname):
+    major = minor = release = dev1 = dev2 = 0
     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
+    if len(vers) > 0: major = int(vers[0])
+    if len(vers) > 1: minor = int(vers[1])
+    if len(vers) > 2:
+        mr = re.search(r'^([0-9]+)([A-Z]|RC)?([0-9]*)',vers[2], re.I)
+        if mr:
+            release = int(mr.group(1))
+            if mr.group(2):
+                tag = mr.group(2).strip().lower()
+                if tag == "rc":
+                    dev1 = 49 # release candidate
+                elif tag:
+                    dev1 = ord(tag)-ord('a')+1
+                pass
+            if mr.group(3):
+                dev2 = int(mr.group(3).strip())
+            pass
+        pass
+    dev = dev1 * 100 + dev2
     ver = major
     ver = ver * 100 + minor
     ver = ver * 100 + release
     ver = ver * 10000
-    if dev > 0: ver = ver - 10000 + dev
+    if dev > 0: ver = ver - dev
     return ver
 
 ###
-# Get user configuration file name
+# Get default user configuration file name
+# For SALOME, it is:
+# - on Linux:   ~/.config/salome/SalomeApprc[.<version>]
+# - on Windows: ~/SalomeApp.xml[.<version>]
+# where <version> is an optional version number
 ###
-def userFile(appname):
+def defaultUserFile(appname=salomeappname, cfgname=salomecfgname):
     v = version()
-    if not v:
-        return ""        # not unknown version
+    if v: v = ".%s" % v
     if sys.platform == "win32":
-      filename = "%s\%s.xml.%s" % (os.environ['HOME'], appname, v)
+      filename = os.path.join(getHomeDir(), "%s.xml%s" % (appname, v))
     else:
-      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
-    if sys.platform == "win32":
-      files = glob.glob( os.environ['HOME'] + "\." + appname + ".xml.*" )
-    else:
-      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
+        if cfgname:
+            filename = os.path.join(getHomeDir(), ".config", cfgname, "%src%s" % (appname, v))
+            pass
+        else:
+            filename = os.path.join(getHomeDir(), ".%src%s" % (appname, v))
+            pass
+        pass
+    return filename
 
-# --
+###
+# Get user configuration file name
+###
+def userFile(appname, cfgname):
+    # get app version
+    v = version()
+    if not v: return None                        # unknown version
 
-_verbose = None
+    # get default user file name
+    filename = defaultUserFile(appname, cfgname)
+    if not filename: return None                 # default user file name is bad
 
-def verbose():
-    global _verbose
-    # verbose has already been called
-    if _verbose is not None:
-        return _verbose
-    # first time
-    try:
-        from os import getenv
-        _verbose = int(getenv('SALOME_VERBOSE'))
-    except:
-        _verbose = 0
+    # check that default user file exists
+    if os.path.exists(filename): return filename # user file is found
+
+    # otherwise try to detect any appropriate user file
+
+    # ... calculate default version id
+    id0 = version_id(v)
+    if not id0: return None                      # bad version id -> can't detect appropriate file
+
+    # ... get all existing user preferences files
+    if sys.platform == "win32":
+        files = glob.glob(os.path.join(getHomeDir(), "%s.xml.*" % appname))
+    else:
+        files = []
+        if cfgname:
+            # Since v6.6.0 - in ~/.config/salome directory, without dot prefix
+            files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, "%src.*" % appname))
+            # Since v6.5.0 - in ~/.config/salome directory, dot-prefixed (backward compatibility)
+            files += glob.glob(os.path.join(getHomeDir(), ".config", cfgname, ".%src.*" % appname))
+            pass
+        # old style (before v6.5.0) - in ~ directory, dot-prefixed
+        files += glob.glob(os.path.join(getHomeDir(), ".%src.*" % appname))
         pass
-    #
-    return _verbose
 
-def setVerbose(level):
-    global _verbose
-    _verbose = level
-    return
+    # ... loop through all files and find most appopriate file (with closest id)
+    appr_id   = -1
+    appr_file = ""
+    for f in files:
+        ff = os.path.basename( f )
+        if sys.platform == "win32":
+            match = re.search( r'^%s\.xml\.([a-zA-Z0-9.]+)$'%appname, ff )
+        else:
+            match = re.search( r'^\.?%src\.([a-zA-Z0-9.]+)$'%appname, ff )
+        if match:
+            ver = version_id(match.group(1))
+            if not ver: continue                 # bad version id -> skip file
+            if appr_id < 0 or abs(appr_id-id0) > abs(ver-id0):
+                appr_id   = ver
+                appr_file = f
+                pass
+            elif abs(appr_id-id0) == abs(ver-id0):
+                if not os.path.basename(f).startswith("."): appr_file = f
+                pass
+            pass
+        pass
+    return appr_file
 
 # --
 
@@ -199,7 +242,7 @@ def process_containers_params( standalone, embedded ):
 
     # 3. return corrected parameters values
     return standalone, embedded
-    
+
 # -----------------------------------------------------------------------------
 
 ###
@@ -209,8 +252,11 @@ def process_containers_params( standalone, embedded ):
 section_to_skip = ""
 
 class xml_parser:
-    def __init__(self, fileName, _opts ):
+    def __init__(self, fileName, _opts, _importHistory=[] ):
         if verbose(): print "Configure parser: processing %s ..." % fileName
+        self.fileName = os.path.abspath(fileName)
+        self.importHistory = _importHistory
+        self.importHistory.append(self.fileName)
         self.space = []
         self.opts = _opts
         self.section = section_to_skip
@@ -257,6 +303,10 @@ class xml_parser:
         self.space.append(name)
         self.current = None
 
+        # if we are importing file
+        if self.space == [doc_tag, import_tag] and nam_att in attrs.getNames():
+            self.importFile( attrs.getValue(nam_att) )
+
         # if we are analyzing "section" element and its "name" attribute is
         # either "launch" or module name -- set section_name
         if self.space == [doc_tag, sec_tag] and nam_att in attrs.getNames():
@@ -318,6 +368,45 @@ class xml_parser:
         self.read = None
         pass
 
+    def importFile(self, fname):
+        # get absolute name
+        if os.path.isabs (fname) :
+            absfname = fname
+        else:
+            absfname = os.path.join(os.path.dirname(self.fileName), fname)
+
+        # check existing and registry file
+        for ext in ["", ".xml", ".XML"] :
+            if os.path.exists(absfname + ext) :
+                absfname += ext
+                if absfname in self.importHistory :
+                    if verbose(): print "Configure parser: Warning : file %s is already imported" % absfname
+                    return # already imported
+                break
+            pass
+        else:
+            if verbose(): print "Configure parser: Error : file %s does not exist" % absfname
+            return
+
+        # importing file
+        try:
+            # copy current options
+            import copy
+            opts = copy.deepcopy(self.opts)
+            # import file
+            imp = xml_parser(absfname, opts, self.importHistory)
+            # merge results
+            for key in imp.opts.keys():
+                if not self.opts.has_key(key):
+                    self.opts[key] = imp.opts[key]
+                    pass
+                pass
+            pass
+        except:
+            if verbose(): print "Configure parser: Error : can not read configuration file %s" % absfname
+        pass
+
+
 # -----------------------------------------------------------------------------
 
 booleans = { '1': True , 'yes': True , 'y': True , 'on' : True , 'true' : True , 'ok'     : True,
@@ -451,7 +540,9 @@ def CreateOptionParser (theAdditionalOptions=[]):
     help_str  = "Python script(s) to be imported. Python scripts are imported "
     help_str += "in the order of their appearance. In GUI mode python scripts "
     help_str += "are imported in the embedded python interpreter of current study, "
-    help_str += "otherwise in an external python interpreter"
+    help_str += "otherwise in an external python interpreter. "
+    help_str += "Note: this option is obsolete. Instead you can pass Python script(s) "
+    help_str += "directly as positional parameter."
     o_u = optparse.Option("-u",
                           "--execute",
                           metavar="<script1,script2,...>",
@@ -460,9 +551,9 @@ def CreateOptionParser (theAdditionalOptions=[]):
                           dest="py_scripts",
                           help=help_str)
 
-    # Configuration XML file. Default: $(HOME)/.SalomeApprc.$(version).
+    # Configuration XML file. Default: see defaultUserFile() function
     help_str  = "Parse application settings from the <file> "
-    help_str += "instead of default $(HOME)/.SalomeApprc.$(version)"
+    help_str += "instead of default %s" % defaultUserFile()
     o_r = optparse.Option("-r",
                           "--resources",
                           metavar="<file>",
@@ -608,7 +699,7 @@ def CreateOptionParser (theAdditionalOptions=[]):
                              action="store",
                              dest="test_script_file",
                              help=help_str)
+
     # Reproducing test script with help of TestRecorder. Default: False.
     help_str = "Reproducing test script with help of TestRecorder."
     o_play = optparse.Option("--play",
@@ -624,7 +715,76 @@ def CreateOptionParser (theAdditionalOptions=[]):
                             action="store_true",
                             dest="gdb_session", default=False,
                             help=help_str)
-    
+
+    # ddd session
+    help_str = "Launch session with ddd"
+    o_ddd = optparse.Option("--ddd-session",
+                            action="store_true",
+                            dest="ddd_session", default=False,
+                            help=help_str)
+
+
+    # valgrind session
+    help_str = "Launch session with valgrind $VALGRIND_OPTIONS"
+    o_valgrind = optparse.Option("--valgrind-session",
+                                 action="store_true",
+                                 dest="valgrind_session", default=False,
+                                 help=help_str)
+
+    # shutdown-servers. Default: False.
+    help_str  = "1 to shutdown standalone servers when leaving python interpreter, "
+    help_str += "0 to keep the standalone servers as daemon [default]. "
+    help_str += "This option is only useful in batchmode "
+    help_str += "(terminal mode or without showing desktop)."
+    o_shutdown = optparse.Option("--shutdown-servers",
+                                 metavar="<1/0>",
+                                 #type="choice", choices=boolean_choices,
+                                 type="string",
+                                 action="callback", callback=store_boolean, callback_args=('shutdown_servers',),
+                                 dest="shutdown_servers",
+                                 help=help_str)
+
+    # foreground. Default: True.
+    help_str  = "0 and runSalome exits after have launched the gui, "
+    help_str += "1 to launch runSalome in foreground mode [default]."
+    o_foreground = optparse.Option("--foreground",
+                                   metavar="<1/0>",
+                                   #type="choice", choices=boolean_choices,
+                                   type="string",
+                                   action="callback", callback=store_boolean, callback_args=('foreground',),
+                                   dest="foreground",
+                                   help=help_str)
+
+    # wake up session
+    help_str  = "Wake up a previously closed session. "
+    help_str += "The session object is found in the naming service pointed by the variable OMNIORB_CONFIG. "
+    help_str += "If this variable is not setted, the last configuration is taken. "
+    o_wake_up = optparse.Option("--wake-up-session",
+                                action="store_true",
+                                dest="wake_up_session", default=False,
+                                help=help_str)
+
+    # server launch mode
+    help_str = "Mode used to launch server processes (daemon or fork)."
+    o_slm = optparse.Option("--server-launch-mode",
+                            metavar="<server_launch_mode>",
+                            type="choice",
+                            choices=["daemon","fork"],
+                            action="store",
+                            dest="server_launch_mode",
+                            help=help_str)
+
+    # use port
+    help_str  = "Preferable port SALOME to be started on. "
+    help_str += "If specified port is not busy, SALOME session will start on it; "
+    help_str += "otherwise, any available port will be searched and used."
+    o_port = optparse.Option("--port",
+                             metavar="<port>",
+                             type="int",
+                             action="store",
+                             dest="use_port",
+                             help=help_str)
+
     # All options
     opt_list = [o_t,o_g, # GUI/Terminal
                 o_d,o_o, # Desktop
@@ -647,7 +807,15 @@ def CreateOptionParser (theAdditionalOptions=[]):
                 o_nspl,
                 o_test,  # Write/read test script file with help of TestRecorder
                 o_play,  # Reproducing test script with help of TestRecorder
-                o_gdb]
+                o_gdb,
+                o_ddd,
+                o_valgrind,
+                o_shutdown,
+                o_foreground,
+                o_wake_up,
+                o_slm,   # Server launch mode
+                o_port,  # Use port
+                ]
 
     #std_options = ["gui", "desktop", "log_file", "py_scripts", "resources",
     #               "xterm", "modules", "embedded", "standalone",
@@ -656,7 +824,7 @@ def CreateOptionParser (theAdditionalOptions=[]):
 
     opt_list += theAdditionalOptions
 
-    a_usage = "%prog [options] [STUDY_FILE]"
+    a_usage = "%prog [options] [STUDY_FILE] [PYTHON_FILE [PYTHON_FILE ...]]"
     version_str = "Salome %s" % version()
     pars = optparse.OptionParser(usage=a_usage, version=version_str, option_list=opt_list)
 
@@ -672,7 +840,7 @@ def CreateOptionParser (theAdditionalOptions=[]):
 args = {}
 #def get_env():
 #args = []
-def get_env(theAdditionalOptions=[], appname="SalomeApp"):
+def get_env(theAdditionalOptions=[], appname=salomeappname, cfgname=salomecfgname):
     ###
     # Collect launch configuration files:
     # - The environment variable "<appname>Config" (SalomeAppConfig) which can
@@ -684,12 +852,13 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
     # - The directories which are inspected are checked for files "<appname?salomeappname>.xml"
     #  (SalomeApp.xml) which define SALOME configuration
     # - These directories are analyzed beginning from the last one in the list,
-    #   so the first directory listed in "<appname>Config" environment variable 
+    #   so the first directory listed in "<appname>Config" environment variable
     #   has higher priority: it means that if some configuration options
     #   is found in the next analyzed cofiguration file - it will be replaced
     # - The last configuration file which is parsed is user configuration file
-    #   situated in the home directory: "~/.<appname>rc[.<version>]" (~/SalomeApprc.3.2.0)
-    #   (if it exists)
+    #   situated in the home directory (if it exists):
+    #   * ~/.config/salome/.<appname>rc[.<version>]" for Linux (e.g. ~/.config/salome/.SalomeApprc.6.4.0)
+    #   * ~/<appname>.xml[.<version>] for Windows (e.g. ~/SalomeApp.xml.6.4.0)
     # - Command line options have the highest priority and replace options
     #   specified in configuration file(s)
     ###
@@ -720,13 +889,13 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
 
     # Process --print-port option
     if cmd_opts.print_port:
-        from runSalome import searchFreePort
+        from searchFreePort import searchFreePort
         searchFreePort({})
         print "port:%s"%(os.environ['NSPORT'])
         sys.exit(0)
         pass
 
-    # set resources variable SalomeAppConfig if it is not set yet 
+    # set resources variable SalomeAppConfig if it is not set yet
     dirs = []
     if os.getenv(config_var):
         if sys.platform == 'win32':
@@ -737,12 +906,12 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
     gui_available = True
     if os.getenv("GUI_ROOT_DIR") and os.path.isdir( os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui" ):
         dirs += [os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"]
-       pass
+        pass
     else:
-       gui_available = False
-       if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ):
-           dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"]
-       pass
+        gui_available = False
+        if os.getenv("KERNEL_ROOT_DIR") and os.path.isdir( os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel" ):
+            dirs += [os.getenv("KERNEL_ROOT_DIR") + "/bin/salome/appliskel"]
+        pass
     os.environ[config_var] = separator.join(dirs)
 
     dirs.reverse() # reverse order, like in "path" variable - FILO-style processing
@@ -751,38 +920,38 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
         dirs.remove('') # to remove empty dirs if the variable terminate by ":" or if there are "::" inside
     except:
         pass
-    
+
     _opts = {} # associative array of options to be filled
 
     # parse SalomeApp.xml files in directories specified by SalomeAppConfig env variable
     for dir in dirs:
-        #filename = dir+'/'+appname+'.xml'
-        filename = dir+'/'+salomeappname+'.xml'
+        filename = os.path.join(dir, appname+'.xml')
         if not os.path.exists(filename):
-            print "Configure parser: Warning : could not find configuration file %s" % filename
+            if verbose(): print "Configure parser: Warning : can 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
+                if verbose(): print "Configure parser: Error : can not read configuration file %s" % filename
             pass
 
     # parse user configuration file
     # It can be set via --resources=<file> command line option
-    # or is given by default from ${HOME}/.<appname>rc.<version>
+    # or is given from default location (see defaultUserFile() function)
     # If user file for the current version is not found the nearest to it is used
     user_config = cmd_opts.resources
     if not user_config:
-        user_config = userFile(appname)
+        user_config = userFile(appname, cfgname)
+        if verbose(): print "Configure parser: user configuration file is", user_config
     if not user_config or not os.path.exists(user_config):
-        print "Configure parser: Warning : could not find user configuration file"
+        if verbose(): print "Configure parser: Warning : can not find user configuration file"
     else:
         try:
             p = xml_parser(user_config, _opts)
             _opts = p.opts
         except:
-            print 'Configure parser: Error : can not read user configuration file'
+            if verbose(): print 'Configure parser: Error : can not read user configuration file'
             user_config = ""
 
     args = _opts
@@ -806,19 +975,7 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
     args[appname_nam] = appname
 
     # get the port number
-    my_port = 2809
-    try:
-      file = open(os.environ["OMNIORB_CONFIG"], "r")
-      s = file.read()
-      while len(s):
-        l = string.split(s, ":")
-        if string.split(l[0], " ")[0] == "ORBInitRef" or string.split(l[0], " ")[0] == "InitRef" :
-          my_port = int(l[len(l)-1])
-          pass
-        s = file.read()
-        pass
-    except:
-      pass
+    my_port = getPortNumber()
 
     args[port_nam] = my_port
 
@@ -841,8 +998,8 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
         args[batch_nam] = True
 
     if not gui_available:
-       args[gui_nam] = False
-       
+        args[gui_nam] = False
+
     if args[gui_nam]:
         args["session_gui"] = True
         if cmd_opts.desktop is not None:
@@ -851,8 +1008,6 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
         if args["session_gui"]:
             if cmd_opts.splash is not None:
                 args[splash_nam] = cmd_opts.splash
-        if len(cmd_args) > 0:
-            args["study_hdf"] = cmd_args[0]
     else:
         args["session_gui"] = False
         args[splash_nam] = False
@@ -873,7 +1028,17 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
     if cmd_opts.py_scripts is not None:
         listlist = cmd_opts.py_scripts
         for listi in listlist:
-            args[script_nam] += re.split( "[:;,]", listi)
+            if os.sys.platform == 'win32':
+                args[script_nam] += re.split( "[;,]", listi)
+            else:
+                args[script_nam] += re.split( "[:;,]", listi)
+    for arg in cmd_args:
+        if arg[-3:] == ".py":
+            args[script_nam].append(arg)
+        elif not args["study_hdf"]:
+            args["study_hdf"] = arg
+            pass
+        pass
 
     # xterm
     if cmd_opts.xterm is not None: args[xterm_nam] = cmd_opts.xterm
@@ -926,11 +1091,37 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
     # Interactive python console
     if cmd_opts.pinter is not None:
         args[pinter_nam] = cmd_opts.pinter
-       
+
     # Gdb session in xterm
     if cmd_opts.gdb_session is not None:
         args[gdb_session_nam] = cmd_opts.gdb_session
 
+    # Ddd session in xterm
+    if cmd_opts.ddd_session is not None:
+        args[ddd_session_nam] = cmd_opts.ddd_session
+
+    # valgrind session
+    if cmd_opts.valgrind_session is not None:
+        args[valgrind_session_nam] = cmd_opts.valgrind_session
+
+    # Shutdown servers
+    if cmd_opts.shutdown_servers is None:
+        args[shutdown_servers_nam] = 0
+    else:
+        args[shutdown_servers_nam] = cmd_opts.shutdown_servers
+        pass
+
+    # Foreground
+    if cmd_opts.foreground is None:
+        args[foreground_nam] = 1
+    else:
+        args[foreground_nam] = cmd_opts.foreground
+        pass
+
+    # wake up session
+    if cmd_opts.wake_up_session is not None:
+        args[wake_up_session_nam] = cmd_opts.wake_up_session
+
     ####################################################
     # Add <theAdditionalOptions> values to args
     for add_opt in theAdditionalOptions:
@@ -965,13 +1156,26 @@ def get_env(theAdditionalOptions=[], appname="SalomeApp"):
         args[test_nam] = []
         filename = cmd_opts.test_script_file
         args[test_nam] += re.split( "[:;,]", filename )
+
     # Play
     if cmd_opts.play_script_file is not None:
         args[play_nam] = []
         filename = cmd_opts.play_script_file
         args[play_nam] += re.split( "[:;,]", filename )
 
+    # Server launch command
+    if cmd_opts.server_launch_mode is not None:
+        args["server_launch_mode"] = cmd_opts.server_launch_mode
+
+    # Server launch command
+    if cmd_opts.use_port is not None:
+        min_port = 2810
+        max_port = min_port + 100
+        if cmd_opts.use_port not in xrange(min_port, max_port+1):
+            print "Error: port number should be in range [%d, %d])" % (min_port, max_port)
+            sys.exit(1)
+        args[useport_nam] = cmd_opts.use_port
+
     # return arguments
     os.environ[config_var] = separator.join(dirs)
     #print "Args: ", args