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