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