Salome HOME
Merge remote branch 'origin/V7_dev'
[modules/gui.git] / src / Session / SALOME_Session_Server.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SALOME Session : implementation of Session.idl
24 //  File : SALOME_Session_Server.cxx
25 //  Author : Paul RASCLE, EDF
26 //  Module : SALOME
27
28 #include <SALOME_NamingService.hxx>
29 #include <SALOME_ModuleCatalog_impl.hxx>
30 #include <SALOME_LifeCycleCORBA.hxx>
31 #include <SALOME_Event.h>
32
33 #include <Container_init_python.hxx>
34 #include <ConnectionManager_i.hxx>
35 #include <RegistryService.hxx>
36
37 #include <OpUtil.hxx>
38 #include <Utils_ORB_INIT.hxx>
39 #include <Utils_SINGLETON.hxx>
40 #include <Utils_SALOME_Exception.hxx>
41 #include <Utils_CorbaException.hxx>
42
43 #include <utilities.h>
44 #include "Session_ServerLauncher.hxx"
45 #include "Session_ServerCheck.hxx"
46 #include "Session_Session_i.hxx"
47
48 #include <Qtx.h>
49 #include <QtxSplash.h>
50
51 #ifdef USE_SALOME_STYLE
52 #include <Style_Salome.h>
53 #endif // USE_SALOME_STYLE
54
55 #include "GUI_version.h"
56 #include <SUIT_Tools.h>
57 #include <SUIT_Session.h>
58 #include <SUIT_Application.h>
59 #include <SUIT_Desktop.h>
60 #include <SUIT_ResourceMgr.h>
61 #include <SUIT_ExceptionHandler.h>
62
63 #include <SALOMEconfig.h>
64 #include CORBA_SERVER_HEADER(SALOME_Session)
65 #include CORBA_SERVER_HEADER(SALOMEDS)
66
67 #ifdef WIN32
68 #define sleep _sleep
69 #endif
70
71 #include <time.h>
72
73 #include <QDir>
74 #include <QFile>
75 #include <QApplication>
76 #include <QMutex>
77 #include <QWaitCondition>
78 #include <QRegExp>
79 #include <QTextStream>
80
81 /*! - read arguments, define list of server to launch with their arguments.
82  * - wait for naming service
83  * - create and run a thread for launch of all servers
84  *
85 */
86
87 //! CORBA server for SALOME Session
88 /*!
89  * SALOME_Session Server launches a SALOME session servant.
90  * The servant registers to the Naming Service.
91  * See SALOME_Session.idl for interface specification.
92  *
93  * Main services offered by the servant are:
94  * - launch GUI
95  * - stop Session ( must be idle )
96  * - get session state
97  */
98 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
99 void MessageOutput( QtMsgType type, const char* msg )
100 #else
101 void MessageOutput( QtMsgType type, const QMessageLogContext &context, const QString &msg )
102 #endif
103 {
104   switch ( type )
105   {
106   case QtDebugMsg:
107 #ifdef QT_DEBUG_MESSAGE
108     MESSAGE( "Debug: " << qPrintable( QString(msg) ) );
109 #endif
110     break;
111   case QtWarningMsg:
112     MESSAGE( "Warning: " << qPrintable( QString(msg) ) );
113     break;
114   case QtFatalMsg:
115     MESSAGE( "Fatal: " << qPrintable( QString(msg) ) );
116     break;
117   }
118 }
119
120 QString salomeVersion()
121 {
122   return GUI_VERSION_STR;
123 }
124
125 class SALOME_ResourceMgr : public SUIT_ResourceMgr
126 {
127 public:
128   SALOME_ResourceMgr( const QString& app, const QString& resVarTemplate ) : SUIT_ResourceMgr( app, resVarTemplate )
129   {
130     setCurrentFormat( "xml" );
131     setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
132   }
133   static void initResourceMgr()
134   {
135     if ( myExtAppName.isNull() || myExtAppVersion.isNull() ) {
136       SALOME_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
137       resMgr.loadLanguage( "LightApp",  "en" );
138       resMgr.loadLanguage( "SalomeApp", "en" );
139
140       myExtAppName = QObject::tr( "APP_NAME" ).trimmed();
141       if ( myExtAppName == "APP_NAME" || myExtAppName.toLower() == "salome" ) 
142         myExtAppName = "SalomeApp";
143       myExtAppVersion = QObject::tr( "APP_VERSION" );
144       if ( myExtAppVersion == "APP_VERSION" ) {
145         if ( myExtAppName != "SalomeApp" )
146           myExtAppVersion = "";
147         else myExtAppVersion = salomeVersion();
148       }
149     }
150   }
151   QString version() const { return myExtAppVersion; }
152
153 protected:
154   QString userFileName( const QString& appName, const bool for_load ) const
155   { 
156     if ( version().isEmpty()  ) return ""; 
157     return SUIT_ResourceMgr::userFileName( myExtAppName, for_load );
158   }
159
160   virtual long userFileId( const QString& _fname ) const
161   {
162     //////////////////////////////////////////////////////////////////////////////////////////////
163     // In SALOME and SALOME-based applications the user preferences file is named as
164     // - <AppName>.xml.<AppVersion> on Windows
165     // - <AppName>rc.<AppVersion> on Linux
166     // where
167     //   * AppName is application name, default SalomeApp (can be customized in SALOME-based
168     //     applications
169     //   * AppVersion is application version
170     //
171     // Since version 6.5.0 of SALOME, user file is situated in the ~/.config/salome
172     // directory. For backward compatibility, when user preferences from nearest
173     // version of application is searched, user home directory is also looked through,
174     // with lower priority.
175     // 
176     // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
177     // symbol since it is situated in hidden ~/.config/salome directory. Files with dot
178     // prefix also though taken into account (with lower priority) for backward compatibility.
179     //
180     // Notes:
181     // - Currently the following format of version number is supported:
182     //   <major>[.<minor>[.<release>[<type><dev>]]]
183     //   Parts in square brackets are considered optional. Here:
184     //   * major   - major version id
185     //   * minor   - minor version id
186     //   * release - maintenance version id
187     //   * type    - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
188     //               or 'rc' to point release candidate (case-insensitive)
189     //   * dev     - dev version or patch number
190     //   All numerical values must be of range [1-99].
191     //   Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
192     //
193     // - Versioning approach can be customized by implementing and using own resource manager class,
194     //   see QtxResurceMgr, SUIT_ResourceMgr classes.
195     //////////////////////////////////////////////////////////////////////////////////////////////
196     long id = -1;
197     if ( !myExtAppName.isEmpty() ) {
198 #ifdef WIN32
199       // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
200       // - SalomeApp is an application name (can be customized)
201       // - xml is a file format (xml or ini)
202       // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
203       QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ).arg( currentFormat() ) );
204 #else
205       // On Linux, user file name is something like SalomeApprc.6.5.0 where
206       // - SalomeApp is an application name (can be customized)
207       // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
208
209       // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
210       // when it is stored in the ~/.config/<appname> directory;
211       // for backward compatibility we also check files prepended with "." with lower priority
212       QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ) );
213 #endif
214       QString fname = QFileInfo( _fname ).fileName();
215       if ( exp.exactMatch( fname ) ) {
216         long fid = Qtx::versionToId( exp.cap( 1 ) );
217         if ( fid > 0 ) id = fid;
218       }
219     }
220     return id;
221   }
222
223 public:
224   static QString myExtAppName;
225   static QString myExtAppVersion;
226 };
227
228 QString SALOME_ResourceMgr::myExtAppName    = QString();
229 QString SALOME_ResourceMgr::myExtAppVersion = QString();
230
231 class SALOME_Session : public SUIT_Session
232 {
233 public:
234   SALOME_Session( int argc, char** argv ) : SUIT_Session( argc, argv ) {}
235   virtual ~SALOME_Session() {}
236
237 public:
238   virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
239   {
240     SALOME_ResourceMgr::initResourceMgr();
241     SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
242     return resMgr;
243   }
244 };
245
246 class SALOME_QApplication : public QApplication
247 {
248 public:
249   SALOME_QApplication( int& argc, char** argv )
250 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
251 #if !defined WIN32 && QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
252   // san: Opening an X display and choosing a visual most suitable for 3D visualization
253   // in order to make SALOME viewers work with non-native X servers
254   : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
255 #else
256   : QApplication( argc, argv ), 
257 #endif
258     myHandler ( 0 ) {}
259
260   virtual bool notify( QObject* receiver, QEvent* e )
261   {
262
263     try {
264       return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
265     }
266     catch (std::exception& e) {
267       std::cerr << e.what()  << std::endl;
268     }
269     catch (CORBA::Exception& e) {
270       std::cerr << "Caught CORBA::Exception"  << std::endl;
271       CORBA::Any tmp;
272       tmp<<= e;
273       CORBA::TypeCode_var tc = tmp.type();
274       const char *p = tc->name();
275       std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
276     }
277     catch (...) {
278       std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
279     }
280     return false;  // return false when exception is caught
281   }
282   SUIT_ExceptionHandler* handler() const { return myHandler; }
283   void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
284
285 private:
286   SUIT_ExceptionHandler* myHandler;
287 };
288
289 // class which calls SALOME::Session::GetInterface() from another thread
290 // to avoid mutual lock ( if called from the same thread as main()
291 class GetInterfaceThread : public QThread
292 {
293 public:
294   GetInterfaceThread( SALOME::Session_var s ) : session ( s )
295   {
296     start();
297   }
298 protected:
299   virtual void run()
300   {
301     if ( !CORBA::is_nil( session ) )
302       session->GetInterface();
303     else
304       printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
305   }
306 private:
307   SALOME::Session_var session;
308 };
309
310 // returns true if 'str' is found in argv
311 bool isFound( const char* str, int argc, char** argv )
312 {
313   for ( int i = 1; i <= ( argc-1 ); i++ )
314     if ( !strcmp( argv[i], str ) )
315       return true;
316   return false;
317 }
318
319 void killOmniNames()
320 {
321   SALOME_LifeCycleCORBA::killOmniNames();
322 }
323
324 // shutdown standalone servers
325 void shutdownServers( SALOME_NamingService* theNS )
326 {
327   SALOME_LifeCycleCORBA lcc(theNS);
328   lcc.shutdownServers();
329 }
330
331 // ---------------------------- MAIN -----------------------
332 int main( int argc, char **argv )
333 {
334   // Install Qt debug messages handler
335 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
336   qInstallMsgHandler( MessageOutput );
337 #else
338   qInstallMessageHandler( MessageOutput );
339 #endif
340
341 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
342 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
343   //Set a "native" graphic system in case if application runs on the remote host
344   QString remote(getenv("REMOTEHOST"));
345   QString client(getenv("SSH_CLIENT"));
346   if(remote.length() > 0 || client.length() > 0 ) {
347     QApplication::setGraphicsSystem(QLatin1String("native"));
348   }
349 #endif
350
351   // add <qtdir>/plugins dir to the pluins search path for image plugins
352   QString qtdir = Qtx::qtDir( "plugins" );
353   if ( !qtdir.isEmpty() )
354     QApplication::addLibraryPath( qtdir );
355   
356   // set "C" locale if requested via preferences
357   {
358     SALOME_Session stmp( argc, argv );
359     QApplication::setApplicationName( "salome" );
360     SUIT_ResourceMgr* resMgr = stmp.createResourceMgr( "SalomeApp" );
361     bool isCloc = resMgr->booleanValue( "language", "locale", true );
362     if ( isCloc ) {
363       QLocale::setDefault( QLocale::c() );
364     }
365     else {
366       QLocale::setDefault( QLocale::system() );
367     }
368   }
369
370   // Create Qt application instance;
371   // this should be done the very first!
372   SALOME_QApplication _qappl( argc, argv );
373   _qappl.setOrganizationName( "salome" );
374   _qappl.setApplicationName( "salome" );
375   _qappl.setApplicationVersion( salomeVersion() );
376
377   // Add application library path (to search style plugin etc...)
378   QString path = QDir::toNativeSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
379   _qappl.addLibraryPath( path );
380
381   bool isGUI    = isFound( "GUI",    argc, argv );
382   bool isSplash = isFound( "SPLASH", argc, argv );
383   // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
384   // Note, that user preferences are not taken into account for splash settings -
385   // it is a property of the application!
386   QtxSplash* splash = 0;
387   if ( isGUI && isSplash ) {
388     // ...create resource manager
389     SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
390     resMgr.setCurrentFormat( "xml" );
391     resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
392     resMgr.loadLanguage( "LightApp" );
393     //
394     splash = QtxSplash::splash( QPixmap() );
395     splash->readSettings( &resMgr );
396     if ( splash->pixmap().isNull() )
397       splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
398     if ( splash->pixmap().isNull() ) {
399       delete splash;
400       splash = 0;
401     }
402     else {
403       splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
404       splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
405       splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
406       splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
407       splash->show();
408       QApplication::instance()->processEvents();
409     }
410   }
411
412   
413   // Initialization
414   int result = -1;
415
416   CORBA::ORB_var orb;
417   PortableServer::POA_var poa;
418
419   SUIT_Session* aGUISession = 0;
420   SALOME_NamingService* _NS = 0;
421   GetInterfaceThread* guiThread = 0;
422   Session_ServerLauncher* myServerLauncher = 0;
423
424   try {
425     // ...initialize Python (only once)
426     int   _argc   = 1;
427     char* _argv[] = {(char*)""};
428     KERNEL_PYTHON::init_python( _argc,_argv );
429
430     // ...create ORB, get RootPOA object, NamingService, etc.
431     ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
432     ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
433     int orbArgc = 1;
434     orb = init( orbArgc, argv );
435
436     CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
437     poa = PortableServer::POA::_narrow( obj );
438
439     PortableServer::POAManager_var pman = poa->the_POAManager();
440     pman->activate() ;
441     MESSAGE( "pman->activate()" );
442
443     _NS = new SALOME_NamingService( orb );
444
445     result = 0;
446   }
447   catch ( SALOME_Exception& e ) {
448     INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
449   }
450   catch ( CORBA::SystemException& e ) {
451     INFOS( "Caught CORBA::SystemException." );
452   }
453   catch ( CORBA::Exception& e ) {
454     INFOS( "Caught CORBA::Exception." );
455     CORBA::Any tmp;
456     tmp<<= e;
457     CORBA::TypeCode_var tc = tmp.type();
458     const char *p = tc->name();
459     INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
460   }
461   catch ( std::exception& e ) {
462     INFOS( "run(): An exception has been caught: " <<e.what() );
463   }
464   catch (...) {
465     INFOS( "Caught unknown exception." );
466   }
467
468   QMutex _GUIMutex, _SessionMutex, _SplashMutex;
469   QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
470
471   // lock session mutex to ensure that GetInterface is not called
472   // until all initialization is done
473   _SessionMutex.lock();
474
475   if ( !result ) {
476     // Start embedded servers launcher (Registry, SALOMEDS, etc.)
477     // ...lock mutex to block embedded servers launching thread until wait( mutex )
478     _GUIMutex.lock();  
479     // ...create launcher
480     myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
481     // ...block this thread until launcher is ready
482     _ServerLaunch.wait( &_GUIMutex );
483     
484     // Start servers check thread (splash)
485     if ( splash ) {
486       // ...lock mutex to block splash thread until wait( mutex )
487       _SplashMutex.lock();
488       // ...create servers checking thread
489       Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
490       // ... set initial progress
491       splash->setProgress( 0, sc.totalSteps() );
492       // start check loop 
493       while ( true ) {
494         int step    = sc.currentStep();
495         int total   = sc.totalSteps();
496         QString msg = sc.currentMessage();
497         QString err = sc.error();
498         if ( !err.isEmpty() ) {
499           QtxSplash::setError( err );
500           QApplication::instance()->processEvents();
501           result = -1;
502           break;
503         }
504         QtxSplash::setStatus( msg, step );
505         QApplication::instance()->processEvents();
506         if ( step >= total )
507           break;
508         // ...block this thread until servers checking is finished
509         _SplashStarted.wait( &_SplashMutex );
510       }
511       // ...unlock mutex 'cause it is no more needed
512       _SplashMutex.unlock();
513     }
514
515     // Finalize embedded servers launcher 
516     // ...block this thread until launcher is finished
517     _ServerLaunch.wait( &_GUIMutex );
518     // ...unlock mutex 'cause it is no more needed
519     _GUIMutex.unlock();
520   }
521
522   // Obtain Session interface reference
523   CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
524   SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
525
526   bool shutdownAll = false;
527   bool shutdownSession = false;
528   if ( !result ) {
529     // Launch GUI activator
530     if ( isGUI ) {
531       if ( splash )
532         splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
533       // ...create GUI launcher
534       MESSAGE( "Session activated, Launch IAPP..." );
535       guiThread = new GetInterfaceThread( session );
536     }
537
538     // GUI activation
539     // Allow multiple activation/deactivation of GUI
540     while ( true ) {
541       MESSAGE( "waiting wakeAll()" );
542       _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
543       // atomic operation lock - unlock on mutex
544       // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
545       // this thread wakes up, and lock mutex
546
547       _SessionMutex.unlock();
548
549       // Session might be shutdowning here, check status
550       SALOME::StatSession stat = session->GetStatSession();
551       shutdownSession = stat.state == SALOME::shutdown;
552       if ( shutdownSession ) {
553         _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
554         break;
555       }
556
557       // SUIT_Session creation
558       aGUISession = new SALOME_Session( argc, argv );
559
560       // Load SalomeApp dynamic library
561       MESSAGE( "creation SUIT_Application" );
562       SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
563       if ( aGUIApp )
564       {
565 #ifdef USE_SALOME_STYLE
566         Style_Salome::initialize( aGUIApp->resourceMgr() );
567         if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
568           Style_Salome::apply();
569 #endif // USE_SALOME_STYLE
570
571         if ( !isFound( "noexcepthandler", argc, argv ) )
572           _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
573                                                        // aGUISession contains SalomeApp_ExceptionHandler
574         // Run GUI loop
575         MESSAGE( "run(): starting the main event loop" );
576
577         if ( splash )
578           splash->finish( aGUIApp->desktop() );
579
580         result = _qappl.exec();
581         
582         splash = 0;
583
584         if ( result == SUIT_Session::NORMAL ) {
585         // desktop is explicitly closed by user from GUI
586         // exit flags says if it's necessary to shutdown all servers
587         // all session server only
588           shutdownAll = aGUISession->exitFlags();
589         }
590         else {
591           // desktop might be closed from:
592           // - StopSesion() (temporarily) or
593           // - Shutdown() (permanently)
594           stat = session->GetStatSession();
595           shutdownSession = stat.state == SALOME::shutdown;
596           // normally "shutdown standalone servers" flag should be false here, if we come from
597           // StopSesion() or from Shutdown();
598           // but we also have to check if somebody explicitly programmatically closed session,
599           // asking to kill servers also
600           shutdownAll = aGUISession->exitFlags();
601         }
602         if ( shutdownAll || shutdownSession ) {
603           _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
604           break;
605         }
606       }
607
608       delete aGUISession;
609       aGUISession = 0;
610       
611       // Prepare _GUIMutex for a new GUI activation
612       _SessionMutex.lock();
613     }
614   }
615
616   // unlock Session mutex
617   _SessionMutex.unlock();
618   
619   if ( myServerLauncher )
620     myServerLauncher->ShutdownAll(); // shutdown embedded servers
621
622   if ( shutdownAll )                 // shutdown standalone servers
623     shutdownServers( _NS );
624
625   if ( myServerLauncher )
626     myServerLauncher->KillAll();     // kill embedded servers
627
628   // Unregister session server
629   SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
630   if ( sessionServant )
631     sessionServant->NSunregister();
632
633   delete aGUISession;
634   delete guiThread;
635   delete myServerLauncher;
636   delete _NS;
637
638   try  {
639     orb->shutdown(0);
640   }
641   catch (...) {
642     //////////////////////////////////////////////////////////////
643     // VSR: silently skip exception:
644     // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown 
645     // exception is raised when orb->destroy() is called and
646     // cpp continer is launched in the embedded mode
647     //////////////////////////////////////////////////////////////
648     // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
649     if ( shutdownAll )
650       killOmniNames();
651     abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
652   }
653
654     //Destroy orb from python (for chasing memory leaks)
655   //PyRun_SimpleString("from omniORB import CORBA");
656   //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
657   //PyRun_SimpleString("orb.destroy()");
658
659   // Destroy the ORB:
660   sleep(2);
661   //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
662   ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
663   if (init)
664     init->explicit_destroy();
665   //std::cout << "@@@@@ ORB destroyed\n";
666
667   // After ORB destruction
668   if(Py_IsInitialized())
669     {
670       PyGILState_Ensure();
671       //std::cout << "@@@@@ About to PyFinalize\n";
672       Py_Finalize();
673       //std::cout << "@@@@@ DONE PyFinalize\n";
674     }
675
676   if ( shutdownAll )
677     {
678       //std::cout << "@@@@@ About to kill omni\n";
679       killOmniNames();
680       //std::cout << "@@@@@ DONE kill omni\n";
681     }
682
683   MESSAGE( "Salome_Session_Server:endofserver" );
684   return result;
685 }