Salome HOME
Merge from V6_3_BR 19/07/2011
[modules/kernel.git] / bin / runSalome.py
index a0bc816969b0a4ecbebe5dfc19678120e48f5682..e8dd6845ca01affceceb9bd1e52bdd88e4008dc4 100755 (executable)
@@ -1,36 +1,42 @@
 #!/usr/bin/env python
-#  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+#  -*- coding: iso-8859-1 -*-
+# Copyright (C) 2007-2011  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
 #
+
 ## @package runSalome
 # \brief Module that provides services to launch SALOME
 #
-#
 
 import sys, os, string, glob, time, pickle, re
 import orbmodule
 import setenv
 from server import *
 from launchConfigureParser import verbose
-#process_id = {} move to server.py
+from server import process_id
+
+if sys.platform == "win32":
+    SEP = ";"
+else:
+    SEP = ":"
 
 # -----------------------------------------------------------------------------
 
@@ -80,15 +86,17 @@ def kill_salome(args):
 
 # -----------------------------------------------------------------------------
 #
-# Definition des classes d'objets pour le lancement des Server CORBA
+# Class definitions to launch CORBA Servers
 #
 
 class InterpServer(Server):
     def __init__(self,args):
         self.args=args
-        env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
-        self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
-        #self.CMD=['xterm', '-e', 'python']
+        if sys.platform != "win32":
+          env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
+          self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
+        else:
+          self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
        
     def run(self):
         global process_id
@@ -104,13 +112,43 @@ class InterpServer(Server):
 
 # ---
 
+def get_cata_path(list_modules,modules_root_dir):
+    """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
+    """
+    modules_cata={}
+    cata_path=[]
+
+    for module in list_modules:
+        if modules_root_dir.has_key(module):
+            module_root_dir=modules_root_dir[module]
+            module_cata=module+"Catalog.xml"
+            cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
+
+            if os.path.exists(cata_file):
+                cata_path.append(cata_file)
+                modules_cata[module]=cata_file
+            else:
+                cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
+                if os.path.exists(cata_file):
+                    cata_path.append(cata_file)
+                    modules_cata[module]=cata_file
+
+    for path in os.getenv("SALOME_CATALOGS_PATH","").split(SEP):
+        if os.path.exists(path):
+            for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
+                module_name= os.path.basename(cata_file)[:-11]
+                if not modules_cata.has_key(module_name):
+                    cata_path.append(cata_file)
+                    modules_cata[module_name]=cata_file
+
+    return cata_path
+
+
+
 class CatalogServer(Server):
     def __init__(self,args):
         self.args=args
         self.initArgs()
-        #if sys.platform == "win32":
-        #        self.SCMD1=[os.environ["KERNEL_ROOT_DIR"] + "/win32/" + os.environ["BIN_ENV"] + "/" + 'SALOME_ModuleCatalog_Server' + ".exe",'-common']
-        #else:
         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
         self.SCMD2=[]
         home_dir=os.getenv('HOME')
@@ -118,37 +156,16 @@ class CatalogServer(Server):
             self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
 
     def setpath(self,modules_list,modules_root_dir):
-        cata_path=[]
         list_modules = modules_list[:]
         list_modules.reverse()
         if self.args["gui"] :
             list_modules = ["KERNEL", "GUI"] + list_modules
         else :
             list_modules = ["KERNEL"] + list_modules
-        for module in list_modules:
-            if modules_root_dir.has_key(module):
-                module_root_dir=modules_root_dir[module]
-                module_cata=module+"Catalog.xml"
-                #print "   ", module_cata
-                if os.path.exists(os.path.join(module_root_dir,
-                                               "share",setenv.salome_subdir,
-                                               "resources",module.lower(),
-                                               module_cata)):
-                    cata_path.extend(
-                        glob.glob(os.path.join(module_root_dir,
-                                               "share",setenv.salome_subdir,
-                                               "resources",module.lower(),
-                                               module_cata)))
-                else:
-                    cata_path.extend(
-                        glob.glob(os.path.join(module_root_dir,
-                                               "share",setenv.salome_subdir,
-                                               "resources",
-                                               module_cata)))
-                pass
-            pass
-        #self.CMD=self.SCMD1 + ['\"']+[string.join(cata_path,'\"::\"')] + ['\"'] + self.SCMD2
-        self.CMD=self.SCMD1 + ['\"' + string.join(cata_path,'\"::\"') + '\"'] + self.SCMD2
+
+        cata_path=get_cata_path(list_modules,modules_root_dir)
+
+        self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
 
 # ---
 
@@ -195,17 +212,6 @@ class ContainerPYServer(Server):
 
 # ---
 
-class ContainerSUPERVServer(Server):
-    def __init__(self,args):
-        self.args=args
-        self.initArgs()
-   #  if sys.platform == "win32":
-#          self.CMD=[os.environ["KERNEL_ROOT_DIR"] + "/win32/" + os.environ["BIN_ENV"] + "/" + 'SALOME_Container' + ".exe",'SuperVisionContainer']
-# else:
-        self.CMD=['SALOME_Container','SuperVisionContainer']
-
-# ---
-
 class LoggerServer(Server):
     def __init__(self,args):
         self.args=args
@@ -230,7 +236,7 @@ class LoggerServer(Server):
 # ---
 
 class SessionServer(Server):
-    def __init__(self,args):
+    def __init__(self,args,modules_list,modules_root_dir):
         self.args = args.copy()
         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
         #self.args['xterm']=0
@@ -258,8 +264,6 @@ class SessionServer(Server):
             self.SCMD2+=['CPP']
         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
             self.SCMD2+=['PY']
-        if 'supervContainer' in self.args['standalone']:
-            self.SCMD2+=['SUPERV']
         if self.args['gui']:
             session_gui = True
             if self.args.has_key('session_gui'):
@@ -279,40 +283,35 @@ class SessionServer(Server):
         if self.args.has_key('user_config'):
             self.SCMD2+=['--resources=%s'%self.args['user_config']]
         if self.args.has_key('modules'):
-            self.SCMD2+=['--modules (%s)'%":".join(self.args['modules'])]
+            list_modules = []
+            #keep only modules with GUI
+            for m in modules_list:
+              if m not in modules_root_dir:
+                list_modules.insert(0,m)
+              else:
+                fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
+                fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
+                if os.path.exists(fr1) or os.path.exists(fr2):
+                  list_modules.insert(0,m)
+            list_modules.reverse()
+            self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
+
         if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
             self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))]
 
     def setpath(self,modules_list,modules_root_dir):
-        cata_path=[]
         list_modules = modules_list[:]
         list_modules.reverse()
         if self.args["gui"] :
             list_modules = ["KERNEL", "GUI"] + list_modules
         else :
             list_modules = ["KERNEL"] + list_modules
-        for module in list_modules:
-            module_root_dir=modules_root_dir[module]
-            module_cata=module+"Catalog.xml"
-            #print "   ", module_cata
-            if os.path.exists(os.path.join(module_root_dir,
-                                           "share",setenv.salome_subdir,
-                                           "resources",module.lower(),
-                                           module_cata)):
-                cata_path.extend(
-                    glob.glob(os.path.join(module_root_dir,"share",
-                                           setenv.salome_subdir,"resources",
-                                           module.lower(),module_cata)))
-            else:
-                cata_path.extend(
-                    glob.glob(os.path.join(module_root_dir,"share",
-                                           setenv.salome_subdir,"resources",
-                                           module_cata)))
-            pass
+
+        cata_path=get_cata_path(list_modules,modules_root_dir)
+
         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
-            #self.CMD=self.SCMD1 + ['\"']+[string.join(cata_path,'\"::\"')] + ['\"'] + self.SCMD2
-            self.CMD=self.SCMD1 + ['\"' + string.join(cata_path,'\"::\"') + '\"'] + self.SCMD2
+            self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
         else:
             self.CMD=self.SCMD1 + self.SCMD2
         if self.args.has_key('test'):
@@ -336,6 +335,15 @@ class SessionServer(Server):
                 pass
             pass
         
+        if self.args["valgrind_session"]:
+            l = ["valgrind"]
+            val = os.getenv("VALGRIND_OPTIONS")
+            if val:
+                l += val.split()
+                pass
+            self.CMD = l + self.CMD
+            pass
+        
 # ---
 
 class LauncherServer(Server):
@@ -356,35 +364,20 @@ class LauncherServer(Server):
                 self.SCMD2+=['--with','SALOMEDS','(',')']
             if 'cppContainer' in self.args['embedded']:
                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
-        
+
     def setpath(self,modules_list,modules_root_dir):
-        cata_path=[]
         list_modules = modules_list[:]
         list_modules.reverse()
         if self.args["gui"] :
-            list_modules = ["GUI"] + list_modules
-        for module in ["KERNEL"] + list_modules:
-            if modules_root_dir.has_key(module):
-                module_root_dir=modules_root_dir[module]
-                module_cata=module+"Catalog.xml"
-                #print "   ", module_cata
-                if os.path.exists(os.path.join(module_root_dir,
-                                               "share",setenv.salome_subdir,
-                                               "resources",module.lower(),
-                                               module_cata)):
-                    cata_path.extend(
-                        glob.glob(os.path.join(module_root_dir,"share",
-                                               setenv.salome_subdir,"resources",
-                                               module.lower(),module_cata)))
-                else:
-                    cata_path.extend(
-                        glob.glob(os.path.join(module_root_dir,"share",
-                                               setenv.salome_subdir,"resources",
-                                               module_cata)))
-                pass
-            pass
+            list_modules = ["KERNEL", "GUI"] + list_modules
+        else :
+            list_modules = ["KERNEL"] + list_modules
+
+        cata_path=get_cata_path(list_modules,modules_root_dir)
+
         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
-            self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
+            #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
+            self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
         else:
             self.CMD=self.SCMD1 + self.SCMD2
 
@@ -405,15 +398,12 @@ class NotifyServer(Server):
 #
 # -----------------------------------------------------------------------------
 
-def startGUI():
+def startGUI(clt):
     """Salome Session Graphic User Interface activation"""
     import Engines
     import SALOME
     import SALOMEDS
     import SALOME_ModuleCatalog
-    reload(Engines)
-    reload(SALOME)
-    reload(SALOMEDS)
     import SALOME_Session_idl
     session=clt.waitNS("/Kernel/Session",SALOME.Session)
     session.GetInterface()
@@ -427,10 +417,63 @@ def startSalome(args, modules_list, modules_root_dir):
     if verbose(): print "startSalome ", args
     
     #
-    # Initialisation ORB et Naming Service
+    # Wake up session option
+    #
+    if args['wake_up_session']:
+        if "OMNIORB_CONFIG" not in os.environ:
+            from salome_utils import generateFileName
+            home  = os.getenv("HOME")
+            appli = os.getenv("APPLI")
+            kwargs={}
+            if appli is not None: 
+                home = os.path.join(home, appli,"USERS")
+                kwargs["with_username"] = True
+                pass
+            last_running_config = generateFileName(home, prefix="omniORB",
+                                                   suffix="last",
+                                                   extension="cfg",
+                                                   hidden=True,
+                                                   **kwargs)
+            os.environ['OMNIORB_CONFIG'] = last_running_config
+            pass
+        pass
+    
+    #
+    # Initialisation ORB and Naming Service
     #
    
     clt=orbmodule.client(args)
+
+    #
+    # Wake up session option
+    #
+    if args['wake_up_session']:
+        import Engines
+        import SALOME
+        import SALOMEDS
+        import SALOME_ModuleCatalog
+        import SALOME_Session_idl
+        session = clt.waitNS("/Kernel/Session",SALOME.Session)
+        status = session.GetStatSession()
+        if status.activeGUI:
+            from salome_utils import getPortNumber
+            port = getPortNumber()
+            msg  = "Warning :"
+            msg += "\n"
+            msg += "Session GUI for port number %s is already active."%(port)
+            msg += "\n"
+            msg += "If you which to wake up another session,"
+            msg += "\n"
+            msg += "please use variable OMNIORB_CONFIG"
+            msg += "\n"
+            msg += "to get the correct session object in naming service."
+            sys.stdout.write(msg+"\n")
+            sys.stdout.flush()
+            return clt
+        session.GetInterface()
+        args["session_object"] = session
+        return clt
+    
     # Save Naming service port name into
     # the file args["ns_port_log_file"]
     if args.has_key('ns_port_log_file'):
@@ -444,8 +487,8 @@ def startSalome(args, modules_list, modules_root_dir):
       f.write(os.environ['NSPORT'])
       f.close()
 
-    # (non obligatoire) Lancement Logger Server
-    # et attente de sa disponibilite dans le naming service
+    # Launch Logger Server (optional)
+    # and wait until it is registered in naming service
     #
 
     if args['logger']:
@@ -462,17 +505,17 @@ def startSalome(args, modules_list, modules_root_dir):
       myServer=NotifyServer(args,modules_root_dir)
       myServer.run()
 
-    # Lancement Session Server (to show splash ASAP)
+    # Launch  Session Server (to show splash ASAP)
     #
 
     if args["gui"]:
-        mySessionServ = SessionServer(args)
+        mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
         mySessionServ.setpath(modules_list,modules_root_dir)
         mySessionServ.run()
 
     #
-    # Lancement Registry Server,
-    # attente de la disponibilite du Registry dans le Naming Service
+    # Launch Registry Server,
+    # and wait until it is registered in naming service
     #
 
     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
@@ -484,10 +527,9 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/Registry",myServer.PID)
 
     #
-    # Lancement Catalog Server,
-    # attente de la disponibilite du Catalog Server dans le Naming Service
+    # Launch Catalog Server,
+    # and wait until it is registered in naming service
     #
-    
 
     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
         cataServer=CatalogServer(args)
@@ -500,8 +542,8 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
 
     #
-    # Lancement SalomeDS Server,
-    # attente de la disponibilite du SalomeDS dans le Naming Service
+    # Launch SalomeDS Server,
+    # and wait until it is registered in naming service
     #
 
     #print "ARGS = ",args
@@ -515,7 +557,7 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/myStudyManager",myServer.PID)
 
     #
-    # Lancement LauncherServer
+    # Launch LauncherServer
     #
     
     myCmServer = LauncherServer(args)
@@ -541,8 +583,8 @@ def startSalome(args, modules_list, modules_root_dir):
     theComputer = getShortHostName()
     
     #
-    # Lancement Container C++ local,
-    # attente de la disponibilite du Container C++ local dans le Naming Service
+    # Launch local C++ Container (FactoryServer),
+    # and wait until it is registered in naming service
     #
 
     if ('cppContainer' in args['standalone']) | (args["gui"] == 0) : 
@@ -554,9 +596,8 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
 
     #
-    # Lancement Container Python local,
-    # attente de la disponibilite du Container Python local
-    # dans le Naming Service
+    # Launch local Python Container (FactoryServerPy),
+    # and wait until it is registered in naming service
     #
 
     if 'pyContainer' in args['standalone']:
@@ -568,21 +609,7 @@ def startSalome(args, modules_list, modules_root_dir):
           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
 
     #
-    # Lancement Container Supervision local,
-    # attente de la disponibilite du Container Supervision local
-    # dans le Naming Service
-    #
-
-    if 'supervContainer' in args['standalone']:
-        myServer=ContainerSUPERVServer(args)
-        myServer.run()
-        if sys.platform == "win32":
-          clt.waitNS("/Containers/" + theComputer + "/SuperVisionContainer")
-        else:
-          clt.waitNSPID("/Containers/" + theComputer + "/SuperVisionContainer",myServer.PID)
-  
-    #
-    # Attente de la disponibilite du Session Server dans le Naming Service
+    # Wait until Session Server is registered in naming service
     #
     
     if args["gui"]:
@@ -591,14 +618,12 @@ def startSalome(args, modules_list, modules_root_dir):
         import SALOME
         import SALOMEDS
         import SALOME_ModuleCatalog
-        reload(Engines)
-        reload(SALOME)
-        reload(SALOMEDS)
         import SALOME_Session_idl
         if sys.platform == "win32":
           session=clt.waitNS("/Kernel/Session",SALOME.Session)
         else:
           session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
+        args["session_object"] = session
     end_time = os.times()
     if verbose(): print
     print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
@@ -623,17 +648,20 @@ def startSalome(args, modules_list, modules_root_dir):
         print "-- to get an external python interpreter:runSalome --interp=1"
         print "-------------------------------------------------------------"
         
-    print "additional external python interpreters: ", nbaddi
+    if verbose(): print "additional external python interpreters: ", nbaddi
     if nbaddi:
         for i in range(nbaddi):
             print "i=",i
             anInterp=InterpServer(args)
             anInterp.run()
 
-    # set PYTHONINSPECT variable
+    # set PYTHONINSPECT variable (python interpreter in interactive mode)
     if args['pinter']:
         os.environ["PYTHONINSPECT"]="1"
-        import readline
+        try:
+            import readline
+        except ImportError:
+            pass
         
     return clt
 
@@ -682,7 +710,7 @@ def useSalome(args, modules_list, modules_root_dir):
     """%filedict
     
     #
-    #  Impression arborescence Naming Service
+    #  Print Naming Service directory list
     #
     
     if clt != None:
@@ -692,31 +720,69 @@ def useSalome(args, modules_list, modules_root_dir):
             clt.showNS()
             pass
         
+        if not args['gui'] or not args['session_gui']:
+            if args['shutdown_servers']:
+                class __utils__(object):
+                    def __init__(self, port):
+                        self.port = port
+                        import killSalomeWithPort
+                        self.killSalomeWithPort = killSalomeWithPort
+                        return
+                    def __del__(self):
+                        self.killSalomeWithPort.killMyPort(self.port)
+                        return
+                    pass
+                args['shutdown_servers'] = __utils__(args['port'])
+                pass
+            pass
+        
         # run python scripts, passed via --execute option
         toimport = []
         if args.has_key('pyscript'):
             if args.has_key('gui') and args.has_key('session_gui'):
                 if not args['gui'] or not args['session_gui']:
                     toimport = args['pyscript']
-        i = 0
-        while i < len( toimport ) :
-            if toimport[ i ] == 'killall':
+
+        for srcname in toimport :
+            if srcname == 'killall':
                 clt.showNS()
                 killAllPorts()
-                import sys
                 sys.exit(0)
             else:
-                scrname = toimport[ i ]
-                if len(scrname) > 2 and (len(scrname) - string.rfind(scrname, ".py") == 3):
-                    print 'executing',scrname
-                    execfile(scrname,globals())
+                if os.path.isabs(srcname):
+                    if os.path.exists(srcname):
+                        execScript(srcname)
+                    elif os.path.exists(srcname+".py"):
+                        execScript(srcname+".py")
+                    else:
+                        print "Can't execute file %s" % srcname
+                    pass
                 else:
-                    print 'importing',scrname
-                    doimport = 'import ' + scrname
-                    exec doimport
-            i = i + 1
-
+                    found = False
+                    for path in [os.getcwd()] + sys.path:
+                        if os.path.exists(os.path.join(path,srcname)):
+                            execScript(os.path.join(path,srcname))
+                            found = True
+                            break
+                        elif os.path.exists(os.path.join(path,srcname+".py")):
+                            execScript(os.path.join(path,srcname+".py"))
+                            found = True
+                            break
+                        pass
+                    if not found:
+                        print "Can't execute file %s" % srcname
+                        pass
+                    pass
+                pass
+            pass
+        pass
     return clt
+    
+def execScript(script_path):
+    print 'executing', script_path
+    sys.path.insert(0, os.path.dirname(script_path))
+    execfile(script_path,globals())
+    del sys.path[0]
 
 # -----------------------------------------------------------------------------
 
@@ -860,7 +926,6 @@ def no_main():
 
 def main():
     """Salome launch as a main application"""
-    import sys
     from salome_utils import getHostName
     print "runSalome running on %s" % getHostName()
     args, modules_list, modules_root_dir = setenv.get_config()
@@ -868,7 +933,15 @@ def main():
     save_config = True
     if args.has_key('save_config'):
         save_config = args['save_config']
-    searchFreePort(args, save_config)
+    # --
+    test = True
+    if args['wake_up_session']:
+        test = False
+        pass
+    if test:
+        searchFreePort(args, save_config)
+        pass
+    # --
     #setenv.main()
     setenv.set_env(args, modules_list, modules_root_dir)
     clt = useSalome(args, modules_list, modules_root_dir)
@@ -876,6 +949,93 @@ def main():
 
 # -----------------------------------------------------------------------------
 
+def foreGround(clt, args):
+    # --
+    if "session_object" not in args:
+        return
+    session = args["session_object"]
+    # --
+    # Wait until gui is arrived
+    # tmax = nbtot * dt
+    # --
+    gui_detected = False
+    dt = 0.1
+    nbtot = 100
+    nb = 0
+    while 1:
+        try:
+            status = session.GetStatSession()
+            gui_detected = status.activeGUI
+        except:
+            pass
+        if gui_detected:
+            break
+        from time import sleep
+        sleep(dt)
+        nb += 1
+        if nb == nbtot:
+            break
+        pass
+    # --
+    if not gui_detected:
+        return
+    # --
+    from salome_utils import getPortNumber
+    port = getPortNumber()
+    # --
+    server = Server({})
+    if sys.platform == "win32":
+      server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
+    else:
+      server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
+    server.run()   
+    # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
+    # --
+    dt = 1.0
+    try:
+        while 1:
+            try:
+                status = session.GetStatSession()
+                assert status.activeGUI
+            except:
+                break
+            from time import sleep
+            sleep(dt)
+            pass
+        pass
+    except KeyboardInterrupt:
+        from killSalomeWithPort import killMyPort
+        killMyPort(port)
+        pass
+    return
+
+# -----------------------------------------------------------------------------
+
 if __name__ == "__main__":
-   import user
-   clt,args = main()
+    import user
+    clt,args = main()
+    # --
+    test = args['gui'] and args['session_gui']
+    test = test or args['wake_up_session']
+    # --
+    # The next test covers the --pinter option or var PYTHONINSPECT setted
+    # --
+    test = test and not os.environ.get('PYTHONINSPECT')
+    # --
+    # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
+    # --
+    try:
+        from ctypes import POINTER, c_int, cast, pythonapi
+        iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
+        test = test and not iflag_ptr.contents.value
+    except:
+        pass
+    # --
+    test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
+    test = test and args['foreground']
+    # --
+    if test:
+        foreGround(clt, args)
+        pass
+    # --
+    pass