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