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