Salome HOME
Merge branch 'gdd_env_modules_in_config_appli' into gdd/merge_gdd_env_modules_in_conf...
[modules/kernel.git] / bin / runSalome.py
1 #!/usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21 #
22 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24
25 ## @package runSalome
26 # \brief Module that provides services to launch SALOME
27 #
28
29 import sys, os, string, glob, time, pickle, re
30 import orbmodule
31 import setenv
32 from launchConfigureParser import verbose
33 from server import process_id, Server
34 import json
35 import subprocess
36 from salomeContextUtils import ScriptAndArgsObjectEncoder
37
38 # -----------------------------------------------------------------------------
39
40 from killSalome import killAllPorts
41
42 def killLocalPort():
43     """
44     kill servers from a previous SALOME exection, if needed,
45     on the CORBA port given in args of runSalome
46     """
47
48     from killSalomeWithPort import killMyPort
49     my_port=str(args['port'])
50     try:
51         killMyPort(my_port)
52     except:
53         print "problem in killLocalPort()"
54         pass
55     pass
56
57 def givenPortKill(port):
58     """
59     kill servers from a previous SALOME exection, if needed,
60     on the same CORBA port
61     """
62
63     from killSalomeWithPort import killMyPort
64     my_port=port
65     try:
66         killMyPort(my_port)
67     except:
68         print "problem in LocalPortKill(), killMyPort(%s)"%port
69         pass
70     pass
71
72 def kill_salome(args):
73     """
74     Kill servers from previous SALOME executions, if needed;
75     depending on args 'killall' or 'portkill', kill all executions,
76     or only execution on the same CORBA port
77     """
78
79     if args['killall']:
80         killAllPorts()
81     elif args['portkill']:
82         givenPortKill(str(args['port']))
83
84 # -----------------------------------------------------------------------------
85 #
86 # Class definitions to launch CORBA Servers
87 #
88
89 class InterpServer(Server):
90     def __init__(self,args):
91         self.args=args
92         if sys.platform == "win32":
93           self.CMD=['cmd', '/c', 'start cmd.exe', '/K', 'python']
94         elif sys.platform == "darwin":
95           env_ld_library_path=['env', 'DYLD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
96           self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
97         else:
98           env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
99           self.CMD=['xterm', '-e'] + env_ld_library_path + ['python']
100
101     def run(self):
102         global process_id
103         command = self.CMD
104         print "INTERPSERVER::command = ", command
105         import subprocess
106         pid = subprocess.Popen(command).pid
107         process_id[pid]=self.CMD
108         self.PID = pid
109
110 # ---
111
112 def get_cata_path(list_modules,modules_root_dir):
113     """Build a list of catalog paths (cata_path) to initialize the ModuleCatalog server
114     """
115     modules_cata={}
116     cata_path=[]
117
118     for module in list_modules:
119         if modules_root_dir.has_key(module):
120             module_root_dir=modules_root_dir[module]
121             module_cata=module+"Catalog.xml"
122             cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources",module.lower(), module_cata)
123
124             if os.path.exists(cata_file):
125                 cata_path.append(cata_file)
126                 modules_cata[module]=cata_file
127             else:
128                 cata_file=os.path.join(module_root_dir, "share",setenv.salome_subdir, "resources", module_cata)
129                 if os.path.exists(cata_file):
130                     cata_path.append(cata_file)
131                     modules_cata[module]=cata_file
132
133     for path in os.getenv("SALOME_CATALOGS_PATH","").split(os.pathsep):
134         if os.path.exists(path):
135             for cata_file in glob.glob(os.path.join(path,"*Catalog.xml")):
136                 module_name= os.path.basename(cata_file)[:-11]
137                 if not modules_cata.has_key(module_name):
138                     cata_path.append(cata_file)
139                     modules_cata[module_name]=cata_file
140
141     return cata_path
142
143 class CatalogServer(Server):
144     def __init__(self,args):
145         self.args=args
146         self.initArgs()
147         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
148         self.SCMD2=[]
149         home_dir=os.getenv('HOME')
150         if home_dir is not None:
151             self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
152
153     def setpath(self,modules_list,modules_root_dir):
154         list_modules = modules_list[:]
155         list_modules.reverse()
156         if self.args["gui"] :
157             list_modules = ["KERNEL", "GUI"] + list_modules
158         else :
159             list_modules = ["KERNEL"] + list_modules
160
161         cata_path=get_cata_path(list_modules,modules_root_dir)
162
163         self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
164
165 # ---
166
167 class SalomeDSServer(Server):
168     def __init__(self,args):
169         self.args=args
170         self.initArgs()
171         self.CMD=['SALOMEDS_Server']
172
173 # ---
174
175 class ConnectionManagerServer(Server):
176     def __init__(self,args):
177         self.args=args
178         self.initArgs()
179         self.CMD=['SALOME_ConnectionManagerServer']
180
181 # ---
182
183 class RegistryServer(Server):
184     def __init__(self,args):
185         self.args=args
186         self.initArgs()
187         self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
188
189 # ---
190
191 class ContainerCPPServer(Server):
192     def __init__(self,args,with_gui=False):
193         self.args=args
194         self.initArgs()
195         self.CMD=['SALOME_Container','FactoryServer']
196         if not with_gui and self.args["valgrind_session"]:
197             l = ["valgrind"]
198             val = os.getenv("VALGRIND_OPTIONS")
199             if val:
200                 l += val.split()
201                 pass
202             self.CMD = l + self.CMD
203             pass
204
205 # ---
206
207 class LoggerServer(Server):
208     def __init__(self,args):
209         self.args=args
210         self.initArgs()
211         from salome_utils import generateFileName, getLogDir
212         logfile = generateFileName( getLogDir(),
213                                     prefix="logger",
214                                     extension="log",
215                                     with_username=True,
216                                     with_hostname=True,
217                                     with_port=True)
218         print "==========================================================="
219         print "Logger server: put log to the file:"
220         print logfile
221         print "==========================================================="
222         self.CMD=['SALOME_Logger_Server', logfile]
223         pass
224     pass # end of LoggerServer class
225
226 # ---
227
228 class SessionServer(Server):
229     def __init__(self,args,modules_list,modules_root_dir):
230         self.args = args.copy()
231         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
232         #self.args['xterm']=0
233         #
234         self.initArgs()
235         self.SCMD1=['SALOME_Session_Server']
236         self.SCMD2=[]
237         if 'registry' in self.args['embedded']:
238             self.SCMD1+=['--with','Registry',
239                          '(','--salome_session','theSession',')']
240         if 'moduleCatalog' in self.args['embedded']:
241             self.SCMD1+=['--with','ModuleCatalog','(','-common']
242             home_dir=os.getenv('HOME')
243             if home_dir is not None:
244                 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')]
245             self.SCMD2+=[')']
246         if 'study' in self.args['embedded']:
247             self.SCMD2+=['--with','SALOMEDS','(',')']
248         if 'cppContainer' in self.args['embedded']:
249             self.SCMD2+=['--with','Container','(','FactoryServer',')']
250         if 'SalomeAppEngine' in self.args['embedded']:
251             self.SCMD2+=['--with','SalomeAppEngine','(',')']
252
253         if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
254             self.SCMD2+=['CPP']
255         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
256             raise Exception('Python containers no longer supported')
257         if self.args['gui']:
258             session_gui = True
259             if self.args.has_key('session_gui'):
260                 session_gui = self.args['session_gui']
261             if session_gui:
262                 self.SCMD2+=['GUI']
263                 if self.args['splash']:
264                     self.SCMD2+=['SPLASH']
265                     pass
266                 if self.args['study_hdf'] is not None:
267                     self.SCMD2+=['--study-hdf=%s'%self.args['study_hdf']]
268                     pass
269                 pass
270                 if self.args.has_key('pyscript') and len(self.args['pyscript']) > 0:
271                     msg = json.dumps(self.args['pyscript'], cls=ScriptAndArgsObjectEncoder)
272                     self.SCMD2+=['--pyscript=%s'%(msg)]
273                     pass
274                 pass
275             pass
276         if self.args['noexcepthandler']:
277             self.SCMD2+=['noexcepthandler']
278         if self.args.has_key('user_config'):
279             self.SCMD2+=['--resources=%s'%self.args['user_config']]
280         if self.args.has_key('modules'):
281             list_modules = []
282             #keep only modules with GUI
283             for m in modules_list:
284               if m not in modules_root_dir:
285                 list_modules.insert(0,m)
286               else:
287                 fr1 = os.path.join(modules_root_dir[m],"share","salome","resources",m.lower(),"SalomeApp.xml")
288                 fr2 = os.path.join(modules_root_dir[m],"share","salome","resources","SalomeApp.xml")
289                 if os.path.exists(fr1) or os.path.exists(fr2):
290                   list_modules.insert(0,m)
291             list_modules.reverse()
292             self.SCMD2+=['--modules (%s)' % ":".join(list_modules)]
293             pass
294         if self.args.has_key('language'):
295             self.SCMD2+=['--language=%s' % self.args['language']]
296         pass
297
298     def setpath(self,modules_list,modules_root_dir):
299         list_modules = modules_list[:]
300         list_modules.reverse()
301         if self.args["gui"] :
302             list_modules = ["KERNEL", "GUI"] + list_modules
303         else :
304             list_modules = ["KERNEL"] + list_modules
305
306         cata_path=get_cata_path(list_modules,modules_root_dir)
307
308         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
309             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
310             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
311         else:
312             self.CMD=self.SCMD1 + self.SCMD2
313         if self.args.has_key('test'):
314             self.CMD+=['-test'] + self.args['test']
315         elif self.args.has_key('play'):
316             self.CMD+=['-play'] + self.args['play']
317
318         if self.args["gdb_session"] or self.args["ddd_session"]:
319             f = open(".gdbinit4salome", "w")
320             f.write("set args ")
321             args = " ".join(self.CMD[1:])
322             args = args.replace("(", "\(")
323             args = args.replace(")", "\)")
324             f.write(args)
325             f.write("\n")
326             f.close()
327             if self.args["ddd_session"]:
328                 self.CMD = ["ddd", "--command=.gdbinit4salome", self.CMD[0]]
329             elif self.args["gdb_session"]:
330                 self.CMD = ["xterm", "-e", "gdb", "--command=.gdbinit4salome", self.CMD[0]]
331                 pass
332             pass
333
334         if self.args["valgrind_session"]:
335             l = ["valgrind"]
336             val = os.getenv("VALGRIND_OPTIONS")
337             if val:
338                 l += val.split()
339                 pass
340             self.CMD = l + self.CMD
341             pass
342
343 # ---
344
345 class LauncherServer(Server):
346     def __init__(self,args):
347         self.args=args
348         self.initArgs()
349         self.SCMD1=['SALOME_LauncherServer']
350         self.SCMD2=[]
351         if args["gui"] :
352             if 'registry' in self.args['embedded']:
353                 self.SCMD1+=['--with','Registry',
354                              '(','--salome_session','theSession',')']
355             if 'moduleCatalog' in self.args['embedded']:
356                 self.SCMD1+=['--with','ModuleCatalog','(','-common']
357                 self.SCMD2+=['-personal',
358                              '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
359             if 'study' in self.args['embedded']:
360                 self.SCMD2+=['--with','SALOMEDS','(',')']
361             if 'cppContainer' in self.args['embedded']:
362                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
363
364     def setpath(self,modules_list,modules_root_dir):
365         list_modules = modules_list[:]
366         list_modules.reverse()
367         if self.args["gui"] :
368             list_modules = ["KERNEL", "GUI"] + list_modules
369         else :
370             list_modules = ["KERNEL"] + list_modules
371
372         cata_path=get_cata_path(list_modules,modules_root_dir)
373
374         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
375             #Use '::' instead ":" because drive path with "D:\" is invalid on windows platform
376             self.CMD=self.SCMD1 + ['"' + string.join(cata_path,'"::"') + '"'] + self.SCMD2
377         else:
378             self.CMD=self.SCMD1 + self.SCMD2
379 #
380 # -----------------------------------------------------------------------------
381
382 def startGUI(clt):
383     """Salome Session Graphic User Interface activation"""
384     import Engines
385     import SALOME
386     import SALOMEDS
387     import SALOME_ModuleCatalog
388     import SALOME_Session_idl
389     session=clt.waitNS("/Kernel/Session",SALOME.Session)
390     session.GetInterface()
391
392 # -----------------------------------------------------------------------------
393
394 def startSalome(args, modules_list, modules_root_dir):
395     """Launch all SALOME servers requested by args"""
396     init_time = os.times()
397
398     if verbose(): print "startSalome ", args
399
400     #
401     # Set server launch command
402     #
403     if args.has_key('server_launch_mode'):
404         Server.set_server_launch_mode(args['server_launch_mode'])
405
406     #
407     # Wake up session option
408     #
409     if args['wake_up_session']:
410         if "OMNIORB_CONFIG" not in os.environ:
411             from salome_utils import generateFileName
412             omniorbUserPath = os.getenv("OMNIORB_USER_PATH")
413             kwargs={}
414             if omniorbUserPath is not None:
415                 kwargs["with_username"]=True
416
417             last_running_config = generateFileName(omniorbUserPath, prefix="omniORB",
418                                                    suffix="last",
419                                                    extension="cfg",
420                                                    hidden=True,
421                                                    **kwargs)
422             os.environ['OMNIORB_CONFIG'] = last_running_config
423             pass
424         pass
425
426     #
427     # Initialisation ORB and Naming Service
428     #
429
430     clt=orbmodule.client(args)
431
432     #
433     # Wake up session option
434     #
435     if args['wake_up_session']:
436         import Engines
437         import SALOME
438         import SALOMEDS
439         import SALOME_ModuleCatalog
440         import SALOME_Session_idl
441         session = clt.waitNS("/Kernel/Session",SALOME.Session)
442         status = session.GetStatSession()
443         if status.activeGUI:
444             from salome_utils import getPortNumber
445             port = getPortNumber()
446             msg  = "Warning :"
447             msg += "\n"
448             msg += "Session GUI for port number %s is already active."%(port)
449             msg += "\n"
450             msg += "If you which to wake up another session,"
451             msg += "\n"
452             msg += "please use variable OMNIORB_CONFIG"
453             msg += "\n"
454             msg += "to get the correct session object in naming service."
455             sys.stdout.write(msg+"\n")
456             sys.stdout.flush()
457             return clt
458         session.GetInterface()
459         args["session_object"] = session
460         return clt
461
462     # Launch Logger Server (optional)
463     # and wait until it is registered in naming service
464     #
465
466     if args['logger']:
467         myServer=LoggerServer(args)
468         myServer.run()
469         clt.waitLogger("Logger")
470
471     # Launch  Session Server (to show splash ASAP)
472     #
473
474     if args["gui"]:
475         mySessionServ = SessionServer(args,args['modules'],modules_root_dir)
476         mySessionServ.setpath(modules_list,modules_root_dir)
477         mySessionServ.run()
478
479     #
480     # Launch Registry Server,
481     # and wait until it is registered in naming service
482     #
483
484     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
485         myServer=RegistryServer(args)
486         myServer.run()
487         if sys.platform == "win32":
488           clt.waitNS("/Registry")
489         else:
490           clt.waitNSPID("/Registry",myServer.PID)
491
492     #
493     # Launch Catalog Server,
494     # and wait until it is registered in naming service
495     #
496
497     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
498         cataServer=CatalogServer(args)
499         cataServer.setpath(modules_list,modules_root_dir)
500         cataServer.run()
501         import SALOME_ModuleCatalog
502         if sys.platform == "win32":
503           clt.waitNS("/Kernel/ModulCatalog",SALOME_ModuleCatalog.ModuleCatalog)
504         else:
505           clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
506
507     #
508     # Launch SalomeDS Server,
509     # and wait until it is registered in naming service
510     #
511
512     #print "ARGS = ",args
513     if ('study' not in args['embedded']) | (args["gui"] == 0):
514         print "RunStudy"
515         myServer=SalomeDSServer(args)
516         myServer.run()
517         if sys.platform == "win32":
518           clt.waitNS("/myStudyManager")
519         else:
520           clt.waitNSPID("/myStudyManager",myServer.PID)
521
522     #
523     # Launch LauncherServer
524     #
525
526     myCmServer = LauncherServer(args)
527     myCmServer.setpath(modules_list,modules_root_dir)
528     myCmServer.run()
529
530     #
531     # Launch ConnectionManagerServer
532     #
533
534     myConnectionServer = ConnectionManagerServer(args)
535     myConnectionServer.run()
536
537
538     from Utils_Identity import getShortHostName
539
540     if os.getenv("HOSTNAME") == None:
541         if os.getenv("HOST") == None:
542             os.environ["HOSTNAME"]=getShortHostName()
543         else:
544             os.environ["HOSTNAME"]=os.getenv("HOST")
545
546     theComputer = getShortHostName()
547
548     #
549     # Launch local C++ Container (FactoryServer),
550     # and wait until it is registered in naming service
551     #
552
553     if ('cppContainer' in args['standalone']) | (args["gui"] == 0) :
554         myServer=ContainerCPPServer(args, with_gui=args["gui"]!=0)
555         myServer.run()
556         if sys.platform == "win32":
557           clt.waitNS("/Containers/" + theComputer + "/FactoryServer")
558         else:
559           clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
560
561     if 'pyContainer' in args['standalone']:
562         raise Exception('Python containers no longer supported')
563
564     #
565     # Wait until Session Server is registered in naming service
566     #
567
568     if args["gui"]:
569 ##----------------
570         import Engines
571         import SALOME
572         import SALOMEDS
573         import SALOME_ModuleCatalog
574         import SALOME_Session_idl
575         if sys.platform == "win32":
576           session=clt.waitNS("/Kernel/Session",SALOME.Session)
577         else:
578           session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
579         args["session_object"] = session
580     end_time = os.times()
581     if verbose(): print
582     print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
583                                                          - init_time[4])
584
585     # ASV start GUI without Loader
586     #if args['gui']:
587     #    session.GetInterface()
588
589     #
590     # additionnal external python interpreters
591     #
592     nbaddi=0
593
594     try:
595         if 'interp' in args:
596             nbaddi = args['interp']
597     except:
598         import traceback
599         traceback.print_exc()
600         print "-------------------------------------------------------------"
601         print "-- to get an external python interpreter:runSalome --interp=1"
602         print "-------------------------------------------------------------"
603
604     if verbose(): print "additional external python interpreters: ", nbaddi
605     if nbaddi:
606         for i in range(nbaddi):
607             print "i=",i
608             anInterp=InterpServer(args)
609             anInterp.run()
610
611     # set PYTHONINSPECT variable (python interpreter in interactive mode)
612     if args['pinter']:
613         os.environ["PYTHONINSPECT"]="1"
614         try:
615             import readline
616         except ImportError:
617             pass
618
619     return clt
620
621 # -----------------------------------------------------------------------------
622
623 def useSalome(args, modules_list, modules_root_dir):
624     """
625     Launch all SALOME servers requested by args,
626     save list of process, give info to user,
627     show registered objects in Naming Service.
628     """
629     global process_id
630
631     clt=None
632     try:
633         clt = startSalome(args, modules_list, modules_root_dir)
634     except:
635         import traceback
636         traceback.print_exc()
637         print
638         print
639         print "--- Error during Salome launch ---"
640
641     #print process_id
642
643     from addToKillList import addToKillList
644     from killSalomeWithPort import getPiDict
645
646     filedict = getPiDict(args['port'])
647     for pid, cmd in process_id.items():
648         addToKillList(pid, cmd, args['port'])
649         pass
650
651     if verbose(): print """
652     Saving of the dictionary of Salome processes in %s
653     To kill SALOME processes from a console (kill all sessions from all ports):
654       python killSalome.py
655     To kill SALOME from the present interpreter, if it is not closed :
656       killLocalPort()      --> kill this session
657                                (use CORBA port from args of runSalome)
658       givenPortKill(port)  --> kill a specific session with given CORBA port
659       killAllPorts()       --> kill all sessions
660
661     runSalome, with --killall option, starts with killing
662     the processes resulting from the previous execution.
663     """%filedict
664
665     #
666     #  Print Naming Service directory list
667     #
668
669     if clt != None:
670         if verbose():
671             print
672             print " --- registered objects tree in Naming Service ---"
673             clt.showNS()
674             pass
675
676         if not args['gui'] or not args['session_gui']:
677             if args['shutdown_servers']:
678                 class __utils__(object):
679                     def __init__(self, port):
680                         self.port = port
681                         import killSalomeWithPort
682                         self.killSalomeWithPort = killSalomeWithPort
683                         return
684                     def __del__(self):
685                         self.killSalomeWithPort.killMyPort(self.port)
686                         return
687                     pass
688                 def func(s):
689                     del s
690                 import atexit
691                 atexit.register(func, __utils__(args['port']))
692                 pass
693             pass
694
695         # run python scripts, passed as command line arguments
696         toimport = []
697         if args.has_key('gui') and args.has_key('session_gui'):
698             if not args['gui'] or not args['session_gui']:
699                 if args.has_key('study_hdf'):
700                     toopen = args['study_hdf']
701                     if toopen:
702                         import salome
703                         salome.salome_init(toopen)
704                 if args.has_key('pyscript'):
705                     toimport = args['pyscript']
706         from salomeContextUtils import formatScriptsAndArgs
707         command = formatScriptsAndArgs(toimport)
708         if command:
709             proc = subprocess.Popen(command, shell=True)
710             addToKillList(proc.pid, command, args['port'])
711             res = proc.wait()
712             if res: sys.exit(1) # if there's an error when executing script, we should explicitly exit
713
714     return clt
715
716 def execScript(script_path):
717     print 'executing', script_path
718     sys.path.insert(0, os.path.realpath(os.path.dirname(script_path)))
719     execfile(script_path,globals())
720     del sys.path[0]
721
722 # -----------------------------------------------------------------------------
723
724 def registerEnv(args, modules_list, modules_root_dir):
725     """
726     Register args, modules_list, modules_root_dir in a file
727     for further use, when SALOME is launched embedded in an other application.
728     """
729     from salome_utils import getTmpDir
730     fileEnv = getTmpDir()
731     from salome_utils import getUserName
732     fileEnv += getUserName() + "_" + str(args['port']) \
733             + '_' + args['appname'].upper() + '_env'
734     fenv=open(fileEnv,'w')
735     pickle.dump((args, modules_list, modules_root_dir),fenv)
736     fenv.close()
737     os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
738
739 # -----------------------------------------------------------------------------
740
741 def no_main():
742     """Salome Launch, when embedded in other application"""
743     fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
744     fenv=open(fileEnv,'r')
745     args, modules_list, modules_root_dir = pickle.load(fenv)
746     fenv.close()
747     kill_salome(args)
748     from searchFreePort import searchFreePort
749     searchFreePort(args, 0)
750     clt = useSalome(args, modules_list, modules_root_dir)
751     return clt
752
753 # -----------------------------------------------------------------------------
754
755 def main(exeName=None):
756     """Salome launch as a main application"""
757
758     # define folder to store omniorb config (initially in virtual application folder)
759     try:
760         from salomeContextUtils import setOmniOrbUserPath
761         setOmniOrbUserPath()
762     except Exception, e:
763         print e
764         sys.exit(1)
765
766     from salome_utils import getHostName
767     args, modules_list, modules_root_dir = setenv.get_config(exeName=exeName)
768     print "runSalome running on %s" % getHostName()
769
770     kill_salome(args)
771     save_config = True
772     if args.has_key('save_config'):
773         save_config = args['save_config']
774     # --
775     test = True
776     if args['wake_up_session']:
777         test = False
778         pass
779     if test:
780         from searchFreePort import searchFreePort
781         searchFreePort(args, save_config, args.get('useport'))
782         pass
783     # --
784     #setenv.main()
785     setenv.set_env(args, modules_list, modules_root_dir)
786     clt = useSalome(args, modules_list, modules_root_dir)
787     return clt,args
788
789 # -----------------------------------------------------------------------------
790
791 def foreGround(clt, args):
792     # --
793     if "session_object" not in args:
794         return
795     session = args["session_object"]
796     # --
797     # Wait until gui is arrived
798     # tmax = nbtot * dt
799     # --
800     gui_detected = False
801     dt = 0.1
802     nbtot = 100
803     nb = 0
804     while 1:
805         try:
806             status = session.GetStatSession()
807             gui_detected = status.activeGUI
808         except:
809             pass
810         if gui_detected:
811             break
812         from time import sleep
813         sleep(dt)
814         nb += 1
815         if nb == nbtot:
816             break
817         pass
818     # --
819     if not gui_detected:
820         return
821     # --
822     from salome_utils import getPortNumber
823     port = getPortNumber()
824     # --
825     server = Server({})
826     if sys.platform == "win32":
827       server.CMD = [os.getenv("PYTHONBIN"), "-m", "killSalomeWithPort", "--spy", "%s"%(os.getpid()), "%s"%(port)]
828     else:
829       server.CMD = ["killSalomeWithPort.py", "--spy", "%s"%(os.getpid()), "%s"%(port)]
830     server.run()
831     # os.system("killSalomeWithPort.py --spy %s %s &"%(os.getpid(), port))
832     # --
833     dt = 1.0
834     try:
835         while 1:
836             try:
837                 status = session.GetStatSession()
838                 assert status.activeGUI
839             except:
840                 break
841             from time import sleep
842             sleep(dt)
843             pass
844         pass
845     except KeyboardInterrupt:
846         from killSalomeWithPort import killMyPort
847         killMyPort(port)
848         pass
849     return
850 #
851
852 def runSalome():
853     import user
854     clt,args = main()
855     # --
856     test = args['gui'] and args['session_gui']
857     test = test or args['wake_up_session']
858     # --
859     # The next test covers the --pinter option or var PYTHONINSPECT setted
860     # --
861     test = test and not os.environ.get('PYTHONINSPECT')
862     # --
863     # The next test covers the python -i $KERNEL_ROOT_DIR/bin/salome/runSalome.py case
864     # --
865     try:
866         from ctypes import POINTER, c_int, cast, pythonapi
867         iflag_ptr = cast(pythonapi.Py_InteractiveFlag, POINTER(c_int))
868         test = test and not iflag_ptr.contents.value
869     except:
870         pass
871     # --
872     test = test and os.getenv("SALOME_TEST_MODE", "0") != "1"
873     test = test and args['foreground']
874     # --
875     if test:
876         foreGround(clt, args)
877         pass
878     pass
879 #
880
881 # -----------------------------------------------------------------------------
882
883 if __name__ == "__main__":
884     runSalome()
885 #