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