Salome HOME
Merge changes from 'master' branch.
[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 <Container_init_python.hxx>
29 #include <SALOME_NamingService.hxx>
30 #include <SALOME_ModuleCatalog_impl.hxx>
31 #include <SALOME_LifeCycleCORBA.hxx>
32 #include <SALOME_Event.h>
33
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) && !defined(__APPLE__) && (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 #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
371
372   // RNV: setup the default format:
373   // QSurfaceFormat should be set before creation of QApplication,  
374   // so to avoid conflicts beetween SALOME and ParaView QSurfaceFormats we should merge theirs formats
375   // (see void Qtx::initDefaultSurfaceFormat()) and set the resultant format here.
376   Qtx::initDefaultSurfaceFormat(); 
377
378 #endif
379
380   // Create Qt application instance;
381   // this should be done the very first!
382   SALOME_QApplication _qappl( argc, argv );
383   _qappl.setOrganizationName( "salome" );
384   _qappl.setApplicationName( "salome" );
385   _qappl.setApplicationVersion( salomeVersion() );
386
387   // Add application library path (to search style plugin etc...)
388   QString path = QDir::toNativeSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
389   _qappl.addLibraryPath( path );
390
391   bool isGUI    = isFound( "GUI",    argc, argv );
392   bool isSplash = isFound( "SPLASH", argc, argv );
393   // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
394   // Note, that user preferences are not taken into account for splash settings -
395   // it is a property of the application!
396   QtxSplash* splash = 0;
397   if ( isGUI && isSplash ) {
398     // ...create resource manager
399     SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
400     resMgr.setCurrentFormat( "xml" );
401     resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
402     resMgr.loadLanguage( "LightApp" );
403     //
404     splash = QtxSplash::splash( QPixmap() );
405     splash->readSettings( &resMgr );
406     if ( splash->pixmap().isNull() )
407       splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
408     if ( splash->pixmap().isNull() ) {
409       delete splash;
410       splash = 0;
411     }
412     else {
413       splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
414       splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
415       splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
416       splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
417       splash->show();
418       QApplication::instance()->processEvents();
419     }
420   }
421
422   
423   // Initialization
424   int result = -1;
425
426   CORBA::ORB_var orb;
427   PortableServer::POA_var poa;
428
429   SUIT_Session* aGUISession = 0;
430   SALOME_NamingService* _NS = 0;
431   GetInterfaceThread* guiThread = 0;
432   Session_ServerLauncher* myServerLauncher = 0;
433
434   try {
435     // ...initialize Python (only once)
436     int   _argc   = 1;
437     char* _argv[] = {(char*)""};
438     KERNEL_PYTHON::init_python( _argc,_argv );
439
440     // ...create ORB, get RootPOA object, NamingService, etc.
441     ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
442     ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
443     int orbArgc = 1;
444     orb = init( orbArgc, argv );
445
446     CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
447     poa = PortableServer::POA::_narrow( obj );
448
449     PortableServer::POAManager_var pman = poa->the_POAManager();
450     pman->activate() ;
451     MESSAGE( "pman->activate()" );
452
453     _NS = new SALOME_NamingService( orb );
454
455     result = 0;
456   }
457   catch ( SALOME_Exception& e ) {
458     INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
459   }
460   catch ( CORBA::SystemException& e ) {
461     INFOS( "Caught CORBA::SystemException." );
462   }
463   catch ( CORBA::Exception& e ) {
464     INFOS( "Caught CORBA::Exception." );
465     CORBA::Any tmp;
466     tmp<<= e;
467     CORBA::TypeCode_var tc = tmp.type();
468     const char *p = tc->name();
469     INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
470   }
471   catch ( std::exception& e ) {
472     INFOS( "run(): An exception has been caught: " <<e.what() );
473   }
474   catch (...) {
475     INFOS( "Caught unknown exception." );
476   }
477
478   QMutex _GUIMutex, _SessionMutex, _SplashMutex;
479   QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
480
481   // lock session mutex to ensure that GetInterface is not called
482   // until all initialization is done
483   _SessionMutex.lock();
484
485   if ( !result ) {
486     // Start embedded servers launcher (Registry, SALOMEDS, etc.)
487     // ...lock mutex to block embedded servers launching thread until wait( mutex )
488     _GUIMutex.lock();  
489     // ...create launcher
490     myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
491     // ...block this thread until launcher is ready
492     _ServerLaunch.wait( &_GUIMutex );
493     
494     // Start servers check thread (splash)
495     if ( splash ) {
496       // ...lock mutex to block splash thread until wait( mutex )
497       _SplashMutex.lock();
498       // ...create servers checking thread
499       Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
500       // ... set initial progress
501       splash->setProgress( 0, sc.totalSteps() );
502       // start check loop 
503       while ( true ) {
504         int step    = sc.currentStep();
505         int total   = sc.totalSteps();
506         QString msg = sc.currentMessage();
507         QString err = sc.error();
508         if ( !err.isEmpty() ) {
509           QtxSplash::setError( err );
510           QApplication::instance()->processEvents();
511           result = -1;
512           break;
513         }
514         QtxSplash::setStatus( msg, step );
515         QApplication::instance()->processEvents();
516         if ( step >= total )
517           break;
518         // ...block this thread until servers checking is finished
519         _SplashStarted.wait( &_SplashMutex );
520       }
521       // ...unlock mutex 'cause it is no more needed
522       _SplashMutex.unlock();
523     }
524
525     // Finalize embedded servers launcher 
526     // ...block this thread until launcher is finished
527     _ServerLaunch.wait( &_GUIMutex );
528     // ...unlock mutex 'cause it is no more needed
529     _GUIMutex.unlock();
530   }
531
532   // Obtain Session interface reference
533   CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
534   SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
535
536   bool shutdownAll = false;
537   bool shutdownSession = false;
538   if ( !result ) {
539     // Launch GUI activator
540     if ( isGUI ) {
541       if ( splash )
542         splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
543       // ...create GUI launcher
544       MESSAGE( "Session activated, Launch IAPP..." );
545       guiThread = new GetInterfaceThread( session );
546     }
547
548     // GUI activation
549     // Allow multiple activation/deactivation of GUI
550     while ( true ) {
551       MESSAGE( "waiting wakeAll()" );
552       _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
553       // atomic operation lock - unlock on mutex
554       // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
555       // this thread wakes up, and lock mutex
556
557       _SessionMutex.unlock();
558
559       // Session might be shutdowning here, check status
560       SALOME::StatSession stat = session->GetStatSession();
561       shutdownSession = stat.state == SALOME::shutdown;
562       if ( shutdownSession ) {
563         _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
564         break;
565       }
566
567       // SUIT_Session creation
568       aGUISession = new SALOME_Session( argc, argv );
569
570       // Load SalomeApp dynamic library
571       MESSAGE( "creation SUIT_Application" );
572       SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
573       if ( aGUIApp )
574       {
575 #ifdef USE_SALOME_STYLE
576         Style_Salome::initialize( aGUIApp->resourceMgr() );
577         if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
578           Style_Salome::apply();
579 #endif // USE_SALOME_STYLE
580
581         if ( !isFound( "noexcepthandler", argc, argv ) )
582           _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
583                                                        // aGUISession contains SalomeApp_ExceptionHandler
584         // Run GUI loop
585         MESSAGE( "run(): starting the main event loop" );
586
587         if ( splash )
588           splash->finish( aGUIApp->desktop() );
589
590         result = _qappl.exec();
591         
592         splash = 0;
593
594         if ( result == SUIT_Session::NORMAL ) {
595         // desktop is explicitly closed by user from GUI
596         // exit flags says if it's necessary to shutdown all servers
597         // all session server only
598           shutdownAll = aGUISession->exitFlags();
599         }
600         else {
601           // desktop might be closed from:
602           // - StopSesion() (temporarily) or
603           // - Shutdown() (permanently)
604           stat = session->GetStatSession();
605           shutdownSession = stat.state == SALOME::shutdown;
606           // normally "shutdown standalone servers" flag should be false here, if we come from
607           // StopSesion() or from Shutdown();
608           // but we also have to check if somebody explicitly programmatically closed session,
609           // asking to kill servers also
610           shutdownAll = aGUISession->exitFlags();
611         }
612         if ( shutdownAll || shutdownSession ) {
613           _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
614           break;
615         }
616       }
617
618       delete aGUISession;
619       aGUISession = 0;
620       
621       // Prepare _GUIMutex for a new GUI activation
622       _SessionMutex.lock();
623     }
624   }
625
626   // unlock Session mutex
627   _SessionMutex.unlock();
628   
629   if ( myServerLauncher )
630     myServerLauncher->ShutdownAll(); // shutdown embedded servers
631
632   if ( shutdownAll )                 // shutdown standalone servers
633     shutdownServers( _NS );
634
635   if ( myServerLauncher )
636     myServerLauncher->KillAll();     // kill embedded servers
637
638   // Unregister session server
639   SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
640   if ( sessionServant )
641     sessionServant->NSunregister();
642
643   delete aGUISession;
644   delete guiThread;
645   delete myServerLauncher;
646   delete _NS;
647
648   try  {
649     orb->shutdown(0);
650   }
651   catch (...) {
652     //////////////////////////////////////////////////////////////
653     // VSR: silently skip exception:
654     // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown 
655     // exception is raised when orb->destroy() is called and
656     // cpp continer is launched in the embedded mode
657     //////////////////////////////////////////////////////////////
658     // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
659     if ( shutdownAll )
660       killOmniNames();
661     abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
662   }
663
664     //Destroy orb from python (for chasing memory leaks)
665   //PyRun_SimpleString("from omniORB import CORBA");
666   //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
667   //PyRun_SimpleString("orb.destroy()");
668
669   // Destroy the ORB:
670   sleep(2);
671   //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
672   ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
673   if (init)
674     init->explicit_destroy();
675   //std::cout << "@@@@@ ORB destroyed\n";
676
677   // After ORB destruction
678   if(Py_IsInitialized())
679     {
680       PyGILState_Ensure();
681       //std::cout << "@@@@@ About to PyFinalize\n";
682       Py_Finalize();
683       //std::cout << "@@@@@ DONE PyFinalize\n";
684     }
685
686   if ( shutdownAll )
687     {
688       //std::cout << "@@@@@ About to kill omni\n";
689       killOmniNames();
690       //std::cout << "@@@@@ DONE kill omni\n";
691     }
692
693   MESSAGE( "Salome_Session_Server:endofserver" );
694   return result;
695 }