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