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