Salome HOME
Fix possible problems with custom SALOME modules (resources folder does not include...
[modules/kernel.git] / bin / runSalome.py
1 #!/usr/bin/env python
2
3 # Copyright (C) 2005  OPEN CASCADE, CEA, EDF R&D, LEG
4 #           PRINCIPIA R&D, EADS CCR, Lip6, BV, CEDRAT
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either 
8 # version 2.1 of the License.
9
10 # This library is distributed in the hope that it will be useful 
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of 
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
13 # Lesser General Public License for more details.
14
15 # You should have received a copy of the GNU Lesser General Public  
16 # License along with this library; if not, write to the Free Software 
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20
21
22 import sys, os, string, glob, time, pickle
23 import orbmodule
24
25 process_id = {}
26
27 # salome_subdir variable is used for composing paths like $KERNEL_ROOT_DIR/share/salome/resources/kernel, etc.
28 # before moving to SUIT-based gui, instead of salome_subdir there was args['appname'] used.
29 # but after - 'appname'  = "SalomeApp", so using it in making the subdirectory is an error.
30 salome_subdir = "salome"
31
32 # -----------------------------------------------------------------------------
33
34 def add_path(directory, variable_name):
35     """Function helper to add environment variables"""
36     if not os.environ.has_key(variable_name):
37         os.environ[variable_name] = ""
38         pass
39     if os.path.exists(directory):
40         newpath=[]
41         for _dir in os.environ[variable_name].split(":"):
42             if os.path.exists(_dir):
43                 if not os.path.samefile(_dir, directory):
44                   newpath.append(_dir)
45             else:
46                 if os.path.abspath(_dir) != os.path.abspath(directory):
47                   newpath.append(_dir)
48             pass
49         import string
50         newpath[:0] = [ directory ]
51         newpath = string.join(newpath,":")
52         os.environ[variable_name] = newpath
53         if variable_name == "PYTHONPATH":
54             sys.path[:0] = [directory]
55
56 # -----------------------------------------------------------------------------
57
58 def get_config():
59     """
60     Get list of modules, paths.
61     
62     Read args from launch configure xml file and command line options.
63     Check variables <module>_ROOT_DIR and set list of used modules.
64     Return args, modules_list, modules_root_dir    
65     """
66     
67     # read args from launch configure xml file and command line options
68     
69     import launchConfigureParser
70     args = launchConfigureParser.args
71     
72     # Check variables <module>_ROOT_DIR
73     # and set list of used modules (without KERNEL)
74
75     modules_list = []
76     if args.has_key("modules"):
77         modules_list += args["modules"]
78     # KERNEL must be last in the list to locate it at the first place in PATH
79     if args["gui"] :
80         modules_list[:0] = ["GUI"]
81     modules_list[:0] = ["KERNEL"]
82     modules_list.reverse()
83
84     modules_root_dir = {}
85
86     to_remove_list=[]
87     for module in modules_list :
88         module_variable=module+"_ROOT_DIR"
89         if not os.environ.has_key(module_variable):
90             print "*******************************************************"
91             print "*"
92             print "* Environment variable",module_variable,"must be set"
93             print "* Module", module, "will be not available"
94             print "*"
95             print "********************************************************"
96             to_remove_list.append(module)
97             continue
98             pass
99         module_root_dir = os.environ[module_variable]
100         modules_root_dir[module]=module_root_dir
101
102     for to_remove in to_remove_list:
103         modules_list.remove(to_remove)
104
105     while "KERNEL" in modules_list:
106         modules_list.remove("KERNEL")
107         pass
108
109     while "GUI" in modules_list:
110         modules_list.remove("GUI")
111         pass
112
113     if "SUPERV" in modules_list and not 'superv' in args['standalone']:
114         args['standalone'].append("superv")
115         pass
116    
117     return args, modules_list, modules_root_dir
118
119 # -----------------------------------------------------------------------------
120
121 def set_env(args, modules_list, modules_root_dir):
122     """Add to the PATH-variables modules specific paths"""
123     
124     python_version="python%d.%d" % sys.version_info[0:2]
125     modules_root_dir_list = []
126     if args["gui"] :
127         modules_list = modules_list[:] + ["GUI"] 
128     modules_list = modules_list[:] + ["KERNEL"] 
129     for module in modules_list :
130         if modules_root_dir.has_key(module):
131             module_root_dir = modules_root_dir[module]
132             modules_root_dir_list[:0] = [module_root_dir]
133             add_path(os.path.join(module_root_dir,"lib",salome_subdir),
134                      "LD_LIBRARY_PATH")
135             add_path(os.path.join(module_root_dir,"bin",salome_subdir),
136                      "PATH")
137             if os.path.exists(module_root_dir + "/examples") :
138                 add_path(os.path.join(module_root_dir,"examples"),
139                          "PYTHONPATH")
140                 pass
141             add_path(os.path.join(module_root_dir,"bin",salome_subdir),
142                      "PYTHONPATH")
143             add_path(os.path.join(module_root_dir,"lib",
144                                   python_version,"site-packages",
145                                   salome_subdir),
146                      "PYTHONPATH")
147             add_path(os.path.join(module_root_dir,"lib",salome_subdir),
148                      "PYTHONPATH")
149             add_path(os.path.join(module_root_dir,"lib",
150                                   python_version,"site-packages",
151                                   salome_subdir,
152                                   "shared_modules"),
153                      "PYTHONPATH")
154             pass
155         pass
156
157
158     os.environ["SALOMEPATH"]=":".join(modules_root_dir_list)
159     
160     # set trace environment variable
161     
162     if not os.environ.has_key("SALOME_trace"):
163         os.environ["SALOME_trace"]="local"
164     if args['file']:
165         os.environ["SALOME_trace"]="file:"+args['file'][0]
166     if args['logger']:
167         os.environ["SALOME_trace"]="with_logger"
168
169     # set environment for SMESH plugins
170
171     if "SMESH" in modules_list:
172         os.environ["SMESH_MeshersList"]="StdMeshers"
173         if not os.environ.has_key("SALOME_StdMeshersResources"):
174             os.environ["SALOME_StdMeshersResources"] \
175             = modules_root_dir["SMESH"]+"/share/"+args["appname"]+"/resources/smesh"
176             pass
177         if args.has_key("SMESH_plugins"):
178             for plugin in args["SMESH_plugins"]:
179                 plugin_root = ""
180                 if os.environ.has_key(plugin+"_ROOT_DIR"):
181                     plugin_root = os.environ[plugin+"_ROOT_DIR"]
182                 else:
183                     # workaround to avoid modifications of existing environment
184                     if os.environ.has_key(plugin.upper()+"_ROOT_DIR"):
185                         plugin_root = os.environ[plugin.upper()+"_ROOT_DIR"]
186                         pass
187                     pass
188                 if plugin_root != "":
189                     os.environ["SMESH_MeshersList"] \
190                     = os.environ["SMESH_MeshersList"]+":"+plugin
191                     if not os.environ.has_key("SALOME_"+plugin+"Resources"):
192                         os.environ["SALOME_"+plugin+"Resources"] \
193                         = plugin_root+"/share/"+args["appname"]+"/resources/"+plugin.lower()
194                     add_path(os.path.join(plugin_root,"lib",python_version,
195                                           "site-packages",salome_subdir),
196                              "PYTHONPATH")
197                     add_path(os.path.join(plugin_root,"lib",salome_subdir),
198                              "PYTHONPATH")
199                     add_path(os.path.join(plugin_root,"lib",salome_subdir),
200                              "LD_LIBRARY_PATH")
201                     add_path(os.path.join(plugin_root,"bin",salome_subdir),
202                              "PYTHONPATH")
203                     add_path(os.path.join(plugin_root,"bin",salome_subdir),
204                              "PATH")
205             pass
206         pass
207
208     # set environment for SUPERV module
209     os.environ["ENABLE_MACRO_NODE"]="1"
210     # set resources variables if not yet set
211     # Done now by launchConfigureParser.py
212     #if os.getenv("GUI_ROOT_DIR"):
213         #if not os.getenv("SalomeAppConfig"): os.environ["SalomeAppConfig"] =  os.getenv("GUI_ROOT_DIR") + "/share/salome/resources/gui"
214
215     # set CSF_PluginDefaults variable only if it is not customized
216     # by the user
217     if not os.getenv("CSF_PluginDefaults"):
218         os.environ["CSF_PluginDefaults"] \
219         = os.path.join(modules_root_dir["KERNEL"],"share",
220                        salome_subdir,"resources","kernel")
221     os.environ["CSF_SALOMEDS_ResourcesDefaults"] \
222     = os.path.join(modules_root_dir["KERNEL"],"share",
223                    salome_subdir,"resources","kernel")
224
225     if "GEOM" in modules_list:
226         print "GEOM OCAF Resources"
227         os.environ["CSF_GEOMDS_ResourcesDefaults"] \
228         = os.path.join(modules_root_dir["GEOM"],"share",
229                        salome_subdir,"resources","geom")
230         print "GEOM Shape Healing Resources"
231         os.environ["CSF_ShHealingDefaults"] \
232         = os.path.join(modules_root_dir["GEOM"],"share",
233                        salome_subdir,"resources","geom")
234
235 # -----------------------------------------------------------------------------
236
237 from killSalome import killAllPorts
238
239 def killLocalPort():
240     """
241     kill servers from a previous SALOME exection, if needed,
242     on the CORBA port given in args of runSalome
243     """
244     
245     from killSalomeWithPort import killMyPort
246     my_port=str(args['port'])
247     try:
248         killMyPort(my_port)
249     except:
250         print "problem in killLocalPort()"
251         pass
252     pass
253     
254 def givenPortKill(port):
255     """
256     kill servers from a previous SALOME exection, if needed,
257     on the same CORBA port
258     """
259     
260     from killSalomeWithPort import killMyPort
261     my_port=port
262     try:
263         killMyPort(my_port)
264     except:
265         print "problem in LocalPortKill(), killMyPort("<<port<<")"
266         pass
267     pass
268
269 def kill_salome(args):
270     """
271     Kill servers from previous SALOME executions, if needed;
272     depending on args 'killall' or 'portkill', kill all executions,
273     or only execution on the same CORBA port
274     """
275
276     if args['killall']:
277         killAllPorts()
278     elif args['portkill']:
279         givenPortKill(str(args['port']))
280         
281 # -----------------------------------------------------------------------------
282 #
283 # Definition des classes d'objets pour le lancement des Server CORBA
284 #
285
286 class Server:
287     """Generic class for CORBA server launch"""
288
289     def initArgs(self):
290         self.PID=None
291         self.CMD=[]
292         self.ARGS=[]    
293         if self.args['xterm']:
294             self.ARGS=['xterm', '-iconic', '-sb', '-sl', '500', '-hold']
295
296     def __init__(self,args):
297         self.args=args
298         self.initArgs()
299
300
301     def run(self):
302         global process_id
303         myargs=self.ARGS
304         if self.args['xterm']:
305             # (Debian) send LD_LIBRARY_PATH to children shells (xterm)
306             env_ld_library_path=['env', 'LD_LIBRARY_PATH='
307                                  + os.getenv("LD_LIBRARY_PATH")]
308             myargs = myargs +['-T']+self.CMD[:1]+['-e'] + env_ld_library_path
309         command = myargs + self.CMD
310         print "command = ", command
311         pid = os.spawnvp(os.P_NOWAIT, command[0], command)
312         process_id[pid]=self.CMD
313         self.PID = pid
314
315
316 class InterpServer(Server):
317     def __init__(self,args):
318         self.args=args
319         env_ld_library_path=['env', 'LD_LIBRARY_PATH=' + os.getenv("LD_LIBRARY_PATH")]
320         self.CMD=['xterm', '-e']+ env_ld_library_path + ['python']
321         #self.CMD=['xterm', '-e', 'python']
322        
323     def run(self):
324         global process_id
325         command = self.CMD
326         #print "command = ", command
327         pid = os.spawnvp(os.P_NOWAIT, command[0], command)
328         process_id[pid]=self.CMD
329         self.PID = pid
330
331 # ---
332
333 class CatalogServer(Server):
334     def __init__(self,args):
335         self.args=args
336         self.initArgs()
337         self.SCMD1=['SALOME_ModuleCatalog_Server','-common']
338         self.SCMD2=[]
339         home_dir=os.getenv('HOME')
340         if home_dir is not None:
341             self.SCMD2=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
342
343     def setpath(self,modules_list,modules_root_dir):
344         cata_path=[]
345         list_modules = modules_list[:]
346         list_modules.reverse()
347         if self.args["gui"] :
348             list_modules = ["KERNEL", "GUI"] + list_modules
349         else :
350             list_modules = ["KERNEL"] + list_modules
351         for module in list_modules:
352             if modules_root_dir.has_key(module):
353                 module_root_dir=modules_root_dir[module]
354                 module_cata=module+"Catalog.xml"
355                 #print "   ", module_cata
356                 if os.path.exists(os.path.join(module_root_dir,
357                                                "share",salome_subdir,
358                                                "resources",module.lower(),
359                                                module_cata)):
360                     cata_path.extend(
361                         glob.glob(os.path.join(module_root_dir,
362                                                "share",salome_subdir,
363                                                "resources",module.lower(),
364                                                module_cata)))
365                 else:
366                     cata_path.extend(
367                         glob.glob(os.path.join(module_root_dir,
368                                                "share",salome_subdir,
369                                                "resources",
370                                                module_cata)))
371                 pass
372             pass
373         self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
374
375 # ---
376
377 class SalomeDSServer(Server):
378     def __init__(self,args):
379         self.args=args
380         self.initArgs()
381         self.CMD=['SALOMEDS_Server']
382
383 # ---
384
385 class RegistryServer(Server):
386     def __init__(self,args):
387         self.args=args
388         self.initArgs()
389         self.CMD=['SALOME_Registry_Server', '--salome_session','theSession']
390
391 # ---
392
393 class ContainerCPPServer(Server):
394     def __init__(self,args):
395         self.args=args
396         self.initArgs()
397         self.CMD=['SALOME_Container','FactoryServer']
398
399 # ---
400
401 class ContainerPYServer(Server):
402     def __init__(self,args):
403         self.args=args
404         self.initArgs()
405         self.CMD=['SALOME_ContainerPy.py','FactoryServerPy']
406
407 # ---
408
409 class ContainerSUPERVServer(Server):
410     def __init__(self,args):
411         self.args=args
412         self.initArgs()
413         self.CMD=['SALOME_Container','SuperVisionContainer']
414
415 # ---
416
417 class LoggerServer(Server):
418     def __init__(self,args):
419         self.args=args
420         self.initArgs()
421         self.CMD=['SALOME_Logger_Server', 'logger.log']
422
423 # ---
424
425 class SessionServer(Server):
426     def __init__(self,args):
427         self.args = args.copy()
428         # Bug 11512 (Problems with runSalome --xterm on Mandrake and Debian Sarge)
429         self.args['xterm']=0
430         #
431         self.initArgs()
432         self.SCMD1=['SALOME_Session_Server']
433         self.SCMD2=[]
434         if 'registry' in self.args['embedded']:
435             self.SCMD1+=['--with','Registry',
436                          '(','--salome_session','theSession',')']
437         if 'moduleCatalog' in self.args['embedded']:
438             self.SCMD1+=['--with','ModuleCatalog','(','-common']
439             home_dir=os.getenv('HOME')
440             if home_dir is not None:
441                 self.SCMD2+=['-personal',os.path.join(home_dir,'Salome/resources/CatalogModulePersonnel.xml')] 
442             self.SCMD2+=[')']
443         if 'study' in self.args['embedded']:
444             self.SCMD2+=['--with','SALOMEDS','(',')']
445         if 'cppContainer' in self.args['embedded']:
446             self.SCMD2+=['--with','Container','(','FactoryServer',')']
447         if 'SalomeAppEngine' in self.args['embedded']:
448             self.SCMD2+=['--with','SalomeAppEngine','(',')']
449             
450         if 'cppContainer' in self.args['standalone'] or 'cppContainer' in self.args['embedded']:
451             self.SCMD2+=['CPP']
452         if 'pyContainer' in self.args['standalone'] or 'pyContainer' in self.args['embedded']:
453             self.SCMD2+=['PY']
454         if 'supervContainer' in self.args['containers'] or 'supervContainer' in self.args['standalone']:
455             self.SCMD2+=['SUPERV']
456         if self.args['gui']:
457             self.SCMD2+=['GUI']
458         if self.args['splash'] and self.args['gui']:
459             self.SCMD2+=['SPLASH']
460         if self.args['noexcepthandler']:
461             self.SCMD2+=['noexcepthandler']
462         if self.args.has_key('modules'):
463             self.SCMD2+=['--modules (']
464             for mod in self.args['modules']:
465                 self.SCMD2+=[mod + ':']
466             self.SCMD2+=[')']    
467
468     def setpath(self,modules_list,modules_root_dir):
469         cata_path=[]
470         list_modules = modules_list[:]
471         list_modules.reverse()
472         if self.args["gui"] :
473             list_modules = ["KERNEL", "GUI"] + list_modules
474         else :
475             list_modules = ["KERNEL"] + list_modules
476         for module in list_modules:
477             module_root_dir=modules_root_dir[module]
478             module_cata=module+"Catalog.xml"
479             #print "   ", module_cata
480             if os.path.exists(os.path.join(module_root_dir,
481                                            "share",salome_subdir,
482                                            "resources",module.lower(),
483                                            module_cata)):
484                 cata_path.extend(
485                     glob.glob(os.path.join(module_root_dir,"share",
486                                            salome_subdir,"resources",
487                                            module.lower(),module_cata)))
488             else:
489                 cata_path.extend(
490                     glob.glob(os.path.join(module_root_dir,"share",
491                                            salome_subdir,"resources",
492                                            module_cata)))
493             pass
494         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
495             self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
496         else:
497             self.CMD=self.SCMD1 + self.SCMD2
498       
499 # ---
500
501 class ContainerManagerServer(Server):
502     def __init__(self,args):
503         self.args=args
504         self.initArgs()
505         self.SCMD1=['SALOME_ContainerManagerServer']
506         self.SCMD2=[]
507         if args["gui"] :
508             if 'registry' in self.args['embedded']:
509                 self.SCMD1+=['--with','Registry',
510                              '(','--salome_session','theSession',')']
511             if 'moduleCatalog' in self.args['embedded']:
512                 self.SCMD1+=['--with','ModuleCatalog','(','-common']
513                 self.SCMD2+=['-personal',
514                              '${HOME}/Salome/resources/CatalogModulePersonnel.xml',')']
515             if 'study' in self.args['embedded']:
516                 self.SCMD2+=['--with','SALOMEDS','(',')']
517             if 'cppContainer' in self.args['embedded']:
518                 self.SCMD2+=['--with','Container','(','FactoryServer',')']
519         
520     def setpath(self,modules_list,modules_root_dir):
521         cata_path=[]
522         list_modules = modules_list[:]
523         list_modules.reverse()
524         if self.args["gui"] :
525             list_modules = ["GUI"] + list_modules
526         for module in ["KERNEL"] + list_modules:
527             if modules_root_dir.has_key(module):
528                 module_root_dir=modules_root_dir[module]
529                 module_cata=module+"Catalog.xml"
530                 #print "   ", module_cata
531                 if os.path.exists(os.path.join(module_root_dir,
532                                                "share",salome_subdir,
533                                                "resources",module.lower(),
534                                                module_cata)):
535                     cata_path.extend(
536                         glob.glob(os.path.join(module_root_dir,"share",
537                                                self.args['appname'],"resources",
538                                                module.lower(),module_cata)))
539                 else:
540                     cata_path.extend(
541                         glob.glob(os.path.join(module_root_dir,"share",
542                                                self.args['appname'],"resources",
543                                                module_cata)))
544                 pass
545             pass
546         if (self.args["gui"]) & ('moduleCatalog' in self.args['embedded']):
547             self.CMD=self.SCMD1 + [string.join(cata_path,':')] + self.SCMD2
548         else:
549             self.CMD=self.SCMD1 + self.SCMD2
550
551 class NotifyServer(Server):
552     def __init__(self,args,modules_root_dir):
553         self.args=args
554         self.initArgs()
555         self.modules_root_dir=modules_root_dir
556         myLogName = os.environ["LOGNAME"]
557         self.CMD=['notifd','-c',
558                   self.modules_root_dir["KERNEL"] +'/share/salome/resources/kernel/channel.cfg',
559                   '-DFactoryIORFileName=/tmp/'+myLogName+'_rdifact.ior',
560                   '-DChannelIORFileName=/tmp/'+myLogName+'_rdichan.ior',
561                   '-DReportLogFile=/tmp/'+myLogName+'_notifd.report',
562                   '-DDebugLogFile=/tmp/'+myLogName+'_notifd.debug',
563                   ]
564
565 #
566 # -----------------------------------------------------------------------------
567
568 def startGUI():
569     """Salome Session Graphic User Interface activation"""
570     import Engines
571     import SALOME
572     import SALOMEDS
573     import SALOME_ModuleCatalog
574     reload(Engines)
575     reload(SALOME)
576     reload(SALOMEDS)
577     import SALOME_Session_idl
578     session=clt.waitNS("/Kernel/Session",SALOME.Session)
579     session.GetInterface()
580   
581 # -----------------------------------------------------------------------------
582
583 def startSalome(args, modules_list, modules_root_dir):
584     """Launch all SALOME servers requested by args"""
585     init_time = os.times()
586
587     print "startSalome ", args
588     
589     #
590     # Initialisation ORB et Naming Service
591     #
592    
593     clt=orbmodule.client()
594
595     # (non obligatoire) Lancement Logger Server
596     # et attente de sa disponibilite dans le naming service
597     #
598
599     if args['logger']:
600         myServer=LoggerServer(args)
601         myServer.run()
602         clt.waitLogger("Logger")
603
604     # Notify Server launch
605     #
606
607     print "Notify Server to launch"
608
609     myServer=NotifyServer(args,modules_root_dir)
610     myServer.run()
611
612     # Lancement Session Server (to show splash ASAP)
613     #
614
615     if args["gui"]:
616         mySessionServ = SessionServer(args)
617         mySessionServ.setpath(modules_list,modules_root_dir)
618         mySessionServ.run()
619
620     #
621     # Lancement Registry Server,
622     # attente de la disponibilite du Registry dans le Naming Service
623     #
624
625     if ('registry' not in args['embedded']) | (args["gui"] == 0) :
626         myServer=RegistryServer(args)
627         myServer.run()
628         clt.waitNSPID("/Registry",myServer.PID)
629
630     #
631     # Lancement Catalog Server,
632     # attente de la disponibilite du Catalog Server dans le Naming Service
633     #
634     
635
636     if ('moduleCatalog' not in args['embedded']) | (args["gui"] == 0):
637         cataServer=CatalogServer(args)
638         cataServer.setpath(modules_list,modules_root_dir)
639         cataServer.run()
640         import SALOME_ModuleCatalog
641         clt.waitNSPID("/Kernel/ModulCatalog",cataServer.PID,SALOME_ModuleCatalog.ModuleCatalog)
642
643     #
644     # Lancement SalomeDS Server,
645     # attente de la disponibilite du SalomeDS dans le Naming Service
646     #
647
648     #print "ARGS = ",args
649     if ('study' not in args['embedded']) | (args["gui"] == 0):
650         print "RunStudy"
651         myServer=SalomeDSServer(args)
652         myServer.run()
653         clt.waitNSPID("/myStudyManager",myServer.PID)
654
655     #
656     # Lancement ContainerManagerServer
657     #
658     
659     myCmServer = ContainerManagerServer(args)
660     myCmServer.setpath(modules_list,modules_root_dir)
661     myCmServer.run()
662
663
664     from Utils_Identity import getShortHostName
665     
666     if os.getenv("HOSTNAME") == None:
667         if os.getenv("HOST") == None:
668             os.environ["HOSTNAME"]=getShortHostName()
669         else:
670             os.environ["HOSTNAME"]=os.getenv("HOST")
671
672     theComputer = getShortHostName()
673     
674     #
675     # Lancement Container C++ local,
676     # attente de la disponibilite du Container C++ local dans le Naming Service
677     #
678
679     if 'cppContainer' in args['standalone']:
680         myServer=ContainerCPPServer(args)
681         myServer.run()
682         clt.waitNSPID("/Containers/" + theComputer + "/FactoryServer",myServer.PID)
683
684     #
685     # Lancement Container Python local,
686     # attente de la disponibilite du Container Python local
687     # dans le Naming Service
688     #
689
690     if 'pyContainer' in args['standalone']:
691         myServer=ContainerPYServer(args)
692         myServer.run()
693         clt.waitNSPID("/Containers/" + theComputer + "/FactoryServerPy",myServer.PID)
694
695     #
696     # Lancement Container Supervision local,
697     # attente de la disponibilite du Container Supervision local
698     # dans le Naming Service
699     #
700
701     if 'supervContainer' in args['standalone']:
702         myServer=ContainerSUPERVServer(args)
703         myServer.run()
704         clt.waitNSPID("/Containers/" + theComputer + "/SuperVisionContainer",myServer.PID)
705
706     #
707     # Attente de la disponibilite du Session Server dans le Naming Service
708     #
709     
710     if args["gui"]:
711 ##----------------        
712         import Engines
713         import SALOME
714         import SALOMEDS
715         import SALOME_ModuleCatalog
716         reload(Engines)
717         reload(SALOME)
718         reload(SALOMEDS)
719         import SALOME_Session_idl
720         session=clt.waitNSPID("/Kernel/Session",mySessionServ.PID,SALOME.Session)
721
722     end_time = os.times()
723     print
724     print "Start SALOME, elapsed time : %5.1f seconds"% (end_time[4]
725                                                          - init_time[4])
726
727     # ASV start GUI without Loader
728     #if args['gui']:
729     #    session.GetInterface()
730
731     #
732     # additionnal external python interpreters
733     #
734     nbaddi=0
735     
736     try:
737         if 'interp' in args:
738             if args['interp']:
739                 nbaddi = int(args['interp'][0])
740     except:
741         import traceback
742         traceback.print_exc()
743         print "-------------------------------------------------------------"
744         print "-- to get an external python interpreter:runSalome --interp=1"
745         print "-------------------------------------------------------------"
746         
747     print "additional external python interpreters: ", nbaddi
748     if nbaddi:
749         for i in range(nbaddi):
750             print "i=",i
751             anInterp=InterpServer(args)
752             anInterp.run()
753     
754     return clt
755
756 # -----------------------------------------------------------------------------
757
758 def useSalome(args, modules_list, modules_root_dir):
759     """
760     Launch all SALOME servers requested by args,
761     save list of process, give info to user,
762     show registered objects in Naming Service.
763     """
764     
765     clt=None
766     try:
767         clt = startSalome(args, modules_list, modules_root_dir)
768     except:
769         import traceback
770         traceback.print_exc()
771         print
772         print
773         print "--- erreur au lancement Salome ---"
774         
775     #print process_id
776
777     from killSalomeWithPort import getPiDict
778     filedict = getPiDict(args['port'])
779
780     process_ids = []
781     try:
782         fpid=open(filedict, 'r')
783         process_ids=pickle.load(fpid)
784         fpid.close()
785     except:
786         pass
787     
788     fpid=open(filedict, 'w')
789     process_ids.append(process_id)
790     pickle.dump(process_ids,fpid)
791     fpid.close()
792     
793     print """
794     Saving of the dictionary of Salome processes in %s
795     To kill SALOME processes from a console (kill all sessions from all ports):
796       python killSalome.py 
797     To kill SALOME from the present interpreter, if it is not closed :
798       killLocalPort()      --> kill this session
799                                (use CORBA port from args of runSalome)
800       givenPortKill(port)  --> kill a specific session with given CORBA port 
801       killAllPorts()       --> kill all sessions
802     
803     runSalome, with --killall option, starts with killing
804     the processes resulting from the previous execution.
805     """%filedict
806     
807     #
808     #  Impression arborescence Naming Service
809     #
810     
811     if clt != None:
812         print
813         print " --- registered objects tree in Naming Service ---"
814         clt.showNS()
815
816     return clt
817
818 # -----------------------------------------------------------------------------
819
820 def registerEnv(args, modules_list, modules_root_dir):
821     """
822     Register args, modules_list, modules_root_dir in a file
823     for further use, when SALOME is launched embedded in an other application.
824     """
825     fileEnv = '/tmp/' + os.getenv('USER') + "_" + str(args['port']) \
826             + '_' + args['appname'].upper() + '_env'
827     fenv=open(fileEnv,'w')
828     pickle.dump((args, modules_list, modules_root_dir),fenv)
829     fenv.close()
830     os.environ["SALOME_LAUNCH_CONFIG"] = fileEnv
831
832 # -----------------------------------------------------------------------------
833
834 def no_main():
835     """Salome Launch, when embedded in other application"""
836     fileEnv = os.environ["SALOME_LAUNCH_CONFIG"]
837     fenv=open(fileEnv,'r')
838     args, modules_list, modules_root_dir = pickle.load(fenv)
839     fenv.close()
840     kill_salome(args)
841     clt = useSalome(args, modules_list, modules_root_dir)
842     return clt
843
844 # -----------------------------------------------------------------------------
845
846 def main():
847     """Salome launch as a main application"""
848     args, modules_list, modules_root_dir = get_config()
849     kill_salome(args)
850     set_env(args, modules_list, modules_root_dir)
851     clt = useSalome(args, modules_list, modules_root_dir)
852     return clt,args
853
854 # -----------------------------------------------------------------------------
855
856 if __name__ == "__main__":
857    import user
858    clt,args = main()