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