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