Salome HOME
Windows compatibility.
[modules/yacs.git] / bin / runSalome.py
index 0389622f651ab6b46f5f0e7b58c52235e35126f2..e6e79763937eb85ad290b51fa9c2ff262ba0d379 100755 (executable)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 #  -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
+# Copyright (C) 2007-2016  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
@@ -8,7 +8,7 @@
 # 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.
+# version 2.1 of the License, or (at your option) any later version.
 #
 # This library is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -31,6 +31,9 @@ import orbmodule
 import setenv
 from launchConfigureParser import verbose
 from server import process_id, Server
+import json
+import subprocess
+from salomeContextUtils import ScriptAndArgsObjectEncoder
 
 # -----------------------------------------------------------------------------
 
@@ -38,7 +41,7 @@ from killSalome import killAllPorts
 
 def killLocalPort():
     """
-    kill servers from a previous SALOME exection, if needed,
+    kill servers from a previous SALOME execution, if needed,
     on the CORBA port given in args of runSalome
     """
 
@@ -53,7 +56,7 @@ def killLocalPort():
 
 def givenPortKill(port):
     """
-    kill servers from a previous SALOME exection, if needed,
+    kill servers from a previous SALOME execution, if needed,
     on the same CORBA port
     """
 
@@ -62,7 +65,7 @@ def givenPortKill(port):
     try:
         killMyPort(my_port)
     except:
-        print "problem in LocalPortKill(), killMyPort("<<port<<")"
+        print "problem in LocalPortKill(), killMyPort(%s)"%port
         pass
     pass
 
@@ -86,21 +89,21 @@ def kill_salome(args):
 class InterpServer(Server):
     def __init__(self,args):
         self.args=args
-        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:
+        if sys.platform == "win32":
           self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
+        elif sys.platform == "darwin":
+          env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
+          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
+        else:
+          env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
+          self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
 
     def run(self):
         global process_id
         command = self.CMD
         print "INTERPSERVER::command = ", command
-        if sys.platform == "win32":
-          import win32pm
-          pid = win32pm.spawnpid( string.join(command, " "),'-nc' )
-        else:
-          pid = os.spawnvp(os.P_NOWAIT, command[0], command)
+        import subprocess
+        pid = subprocess.Popen(command).pid
         process_id[pid]=self.CMD
         self.PID = pid
 
@@ -137,8 +140,6 @@ def get_cata_path(list_modules,modules_root_dir):
 
     return cata_path
 
-
-
 class CatalogServer(Server):
     def __init__(self,args):
         self.args=args
@@ -188,10 +189,18 @@ class RegistryServer(Server):
 # ---
 
 class ContainerCPPServer(Server):
-    def __init__(self,args):
+    def __init__(self,args,with_gui=False):
         self.args=args
         self.initArgs()
         self.CMD=['SALOME_Container','FactoryServer']
+        if not with_gui and self.args["valgrind_session"]:
+            l = ["valgrind"]
+            val = os.getenv("VALGRIND_OPTIONS")
+            if val:
+                l += val.split()
+                pass
+            self.CMD = l + self.CMD
+            pass
 
 # ---
 
@@ -199,10 +208,8 @@ class LoggerServer(Server):
     def __init__(self,args):
         self.args=args
         self.initArgs()
-        from salome_utils import generateFileName
-        if sys.platform == "win32": dirpath = os.environ["HOME"]
-        else:                       dirpath = "/tmp"
-        logfile = generateFileName( dirpath,
+        from salome_utils import generateFileName, getLogDir
+        logfile = generateFileName( getLogDir(),
                                     prefix="logger",
                                     extension="log",
                                     with_username=True,
@@ -261,7 +268,8 @@ class SessionServer(Server):
                     pass
                 pass
                 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
-                    self.SCMD2+=['--pyscript=%s'%(",".join(self.args['pyscript']))]
+                    msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
+                    self.SCMD2+=['--pyscript=%s'%(msg)]
                     pass
                 pass
             pass
@@ -283,6 +291,8 @@ class SessionServer(Server):
             list_modules.reverse()
             self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
             pass
+        if self.args.has_key('language'):
+            self.SCMD2+=['--language=%s' % self.args['language']]
         pass
 
     def setpath(self,modules_list,modules_root_dir):
@@ -366,21 +376,6 @@ class LauncherServer(Server):
             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
         else:
             self.CMD=self.SCMD1 + self.SCMD2
-
-class NotifyServer(Server):
-    def __init__(self,args,modules_root_dir):
-        self.args=args
-        self.initArgs()
-        self.modules_root_dir=modules_root_dir
-        myLogName = os.environ["LOGNAME"]
-        self.CMD=['notifd','-c',
-                  self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
-                  '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
-                  '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
-                  '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
-                  '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
-                  ]
-
 #
 # -----------------------------------------------------------------------------
 
@@ -414,14 +409,12 @@ def startSalome(args, modules_list, modules_root_dir):
     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")
+            omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
             kwargs={}
-            if appli is not None:
-                home = os.path.join(os.path.realpath(home), appli,"USERS")
-                kwargs["with_username"] = True
-                pass
-            last_running_config = generateFileName(home, prefix="omniORB",
+            if omniorbUserPath is not None:
+                kwargs["with_username"]=True
+
+            last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
                                                    suffix="last",
                                                    extension="cfg",
                                                    hidden=True,
@@ -466,18 +459,6 @@ def startSalome(args, modules_list, modules_root_dir):
         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'):
-      home = os.environ['HOME']
-      appli= os.environ.get("APPLI")
-      if appli is not None:
-        home = os.path.join(os.path.realpath(home), appli, "USERS")
-      file_name = os.path.join(home, args["ns_port_log_file"])
-      f = open(file_name, "w")
-      f.write(os.environ['NSPORT'])
-      f.close()
-
     # Launch Logger Server (optional)
     # and wait until it is registered in naming service
     #
@@ -487,15 +468,6 @@ def startSalome(args, modules_list, modules_root_dir):
         myServer.run()
         clt.waitLogger("Logger")
 
-    # Notify Server launch
-    #
-
-    if sys.platform != "win32":
-      if verbose(): print "Notify Server to launch"
-
-      myServer=NotifyServer(args,modules_root_dir)
-      myServer.run()
-
     # Launch  Session Server (to show splash ASAP)
     #
 
@@ -579,18 +551,13 @@ def startSalome(args, modules_list, modules_root_dir):
     #
 
     if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
-        myServer=ContainerCPPServer(args)
+        myServer=ContainerCPPServer(args, with_gui=args["gui"]!=0)
         myServer.run()
         if sys.platform == "win32":
           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
         else:
           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
 
-    #
-    # Launch local Python Container (FactoryServerPy),
-    # and wait until it is registered in naming service
-    #
-
     if 'pyContainer' in args['standalone']:
         raise Exception('Python containers no longer supported')
 
@@ -620,7 +587,7 @@ def startSalome(args, modules_list, modules_root_dir):
     #    session.GetInterface()
 
     #
-    # additionnal external python interpreters
+    # additional external python interpreters
     #
     nbaddi=0
 
@@ -718,55 +685,37 @@ def useSalome(args, modules_list, modules_root_dir):
                         self.killSalomeWithPort.killMyPort(self.port)
                         return
                     pass
-                args['shutdown_servers'] = __utils__(args['port'])
+                def func(s):
+                    del s
+                import atexit
+                atexit.register(func, __utils__(args['port']))
                 pass
             pass
 
-        # run python scripts, passed via --execute option
+        # run python scripts, passed as command line arguments
         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']:
+        if args.has_key('gui') and args.has_key('session_gui'):
+            if not args['gui'] or not args['session_gui']:
+                if args.has_key('study_hdf'):
+                    toopen = args['study_hdf']
+                    if toopen:
+                        import salome
+                        salome.salome_init(toopen)
+                if args.has_key('pyscript'):
                     toimport = args['pyscript']
+        from salomeContextUtils import formatScriptsAndArgs
+        command = formatScriptsAndArgs(toimport)
+        if command:
+            proc = subprocess.Popen(command, shell=True)
+            addToKillList(proc.pid, command, args['port'])
+            res = proc.wait()
+            if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
 
-        for srcname in toimport :
-            if srcname == 'killall':
-                clt.showNS()
-                killAllPorts()
-                sys.exit(0)
-            else:
-                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:
-                    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))
+    sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
     execfile(script_path,globals())
     del sys.path[0]
 
@@ -777,12 +726,10 @@ def registerEnv(args, modules_list, modules_root_dir):
     Register args, modules_list, modules_root_dir in a file
     for further use, when SALOME is launched embedded in an other application.
     """
-    if sys.platform == "win32":
-      fileEnv = os.getenv('TEMP')
-    else:
-      fileEnv = '/tmp/'
-
-    fileEnv += os.getenv('USER') + "_" + str(args['port']) \
+    from salome_utils import getTmpDir
+    fileEnv = getTmpDir()
+    from salome_utils import getUserName
+    fileEnv += getUserName() + "_" + str(args['port']) \
             + '_' + args['appname'].upper() + '_env'
     fenv=open(fileEnv,'w')
     pickle.dump((args, modules_list, modules_root_dir),fenv)
@@ -805,11 +752,20 @@ def no_main():
 
 # -----------------------------------------------------------------------------
 
-def main():
+def main(exeName=None):
     """Salome launch as a main application"""
+
+    # define folder to store omniorb config (initially in virtual application folder)
+    try:
+        from salomeContextUtils import setOmniOrbUserPath
+        setOmniOrbUserPath()
+    except Exception, e:
+        print e
+        sys.exit(1)
+
     from salome_utils import getHostName
+    args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName)
     print "runSalome running on %s" % getHostName()
-    args, modules_list, modules_root_dir = setenv.get_config()
 
     kill_salome(args)
     save_config = True
@@ -822,7 +778,7 @@ def main():
         pass
     if test:
         from searchFreePort import searchFreePort
-        searchFreePort(args, save_config)
+        searchFreePort(args, save_config, args.get('useport'))
         pass
     # --
     #setenv.main()
@@ -900,7 +856,7 @@ def runSalome():
     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
+    # The next test covers the --pinter option or if var PYTHONINSPECT is set
     # --
     test = test and not os.environ.get('PYTHONINSPECT')
     # --
@@ -919,7 +875,6 @@ def runSalome():
     if test:
         foreGround(clt, args)
         pass
-    # --
     pass
 #