Salome HOME
0022856: EDF 9971 PARAVIS: Error message not displayed in Paravis
[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 <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
273     try {
274       return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
275     }
276     catch (std::exception& e) {
277       std::cerr << e.what()  << std::endl;
278     }
279     catch (CORBA::Exception& e) {
280       std::cerr << "Caught CORBA::Exception"  << std::endl;
281       CORBA::Any tmp;
282       tmp<<= e;
283       CORBA::TypeCode_var tc = tmp.type();
284       const char *p = tc->name();
285       std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
286     }
287     catch (...) {
288       std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
289     }
290     return false;  // return false when exception is caught
291   }
292   SUIT_ExceptionHandler* handler() const { return myHandler; }
293   void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
294
295 private:
296   SUIT_ExceptionHandler* myHandler;
297 };
298
299 // class which calls SALOME::Session::GetInterface() from another thread
300 // to avoid mutual lock ( if called from the same thread as main()
301 class GetInterfaceThread : public QThread
302 {
303 public:
304   GetInterfaceThread( SALOME::Session_var s ) : session ( s )
305   {
306     start();
307   }
308 protected:
309   virtual void run()
310   {
311     if ( !CORBA::is_nil( session ) )
312       session->GetInterface();
313     else
314       printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
315   }
316 private:
317   SALOME::Session_var session;
318 };
319
320 // returns true if 'str' is found in argv
321 bool isFound( const char* str, int argc, char** argv )
322 {
323   for ( int i = 1; i <= ( argc-1 ); i++ )
324     if ( !strcmp( argv[i], str ) )
325       return true;
326   return false;
327 }
328
329 void killOmniNames()
330 {
331   SALOME_LifeCycleCORBA::killOmniNames();
332 }
333
334 // shutdown standalone servers
335 void shutdownServers( SALOME_NamingService* theNS )
336 {
337   SALOME_LifeCycleCORBA lcc(theNS);
338   lcc.shutdownServers();
339 }
340
341 // ---------------------------- MAIN -----------------------
342 int main( int argc, char **argv )
343 {
344   // Install Qt debug messages handler
345   SessionMsgHandler msgHandler;
346   qInstallMessageHandler(QtxMsgHandler);
347
348 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
349 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
350   //Set a "native" graphic system in case if application runs on the remote host
351   QString remote(getenv("REMOTEHOST"));
352   QString client(getenv("SSH_CLIENT"));
353   if(remote.length() > 0 || client.length() > 0 ) {
354     QApplication::setGraphicsSystem(QLatin1String("native"));
355   }
356 #endif
357
358   // add <qtdir>/plugins dir to the pluins search path for image plugins
359   QString qtdir = Qtx::qtDir( "plugins" );
360   if ( !qtdir.isEmpty() )
361     QApplication::addLibraryPath( qtdir );
362   
363   // set "C" locale if requested via preferences
364   {
365     SALOME_Session stmp( argc, argv );
366     QApplication::setApplicationName( "salome" );
367     SUIT_ResourceMgr* resMgr = stmp.createResourceMgr( "SalomeApp" );
368     bool isCloc = resMgr->booleanValue( "language", "locale", true );
369     if ( isCloc ) {
370       QLocale::setDefault( QLocale::c() );
371     }
372     else {
373       QLocale::setDefault( QLocale::system() );
374     }
375   }
376   
377 #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
378
379   // RNV: setup the default format:
380   // QSurfaceFormat should be set before creation of QApplication,  
381   // so to avoid conflicts beetween SALOME and ParaView QSurfaceFormats we should merge theirs formats
382   // (see void Qtx::initDefaultSurfaceFormat()) and set the resultant format here.
383   Qtx::initDefaultSurfaceFormat(); 
384
385 #endif
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           // normally "shutdown standalone servers" flag should be false here, if we come from
614           // StopSesion() or from Shutdown();
615           // but we also have to check if somebody explicitly programmatically closed session,
616           // asking to kill servers also
617           shutdownAll = aGUISession->exitFlags();
618         }
619         if ( shutdownAll || shutdownSession ) {
620           _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
621           break;
622         }
623       }
624
625       delete aGUISession;
626       aGUISession = 0;
627       
628       // Prepare _GUIMutex for a new GUI activation
629       _SessionMutex.lock();
630     }
631   }
632
633   // unlock Session mutex
634   _SessionMutex.unlock();
635   
636   if ( myServerLauncher )
637     myServerLauncher->ShutdownAll(); // shutdown embedded servers
638
639   if ( shutdownAll )                 // shutdown standalone servers
640     shutdownServers( _NS );
641
642   if ( myServerLauncher )
643     myServerLauncher->KillAll();     // kill embedded servers
644
645   // Unregister session server
646   SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
647   if ( sessionServant )
648     sessionServant->NSunregister();
649
650   delete aGUISession;
651   delete guiThread;
652   delete myServerLauncher;
653   delete _NS;
654
655   try  {
656     orb->shutdown(0);
657   }
658   catch (...) {
659     //////////////////////////////////////////////////////////////
660     // VSR: silently skip exception:
661     // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown 
662     // exception is raised when orb->destroy() is called and
663     // cpp continer is launched in the embedded mode
664     //////////////////////////////////////////////////////////////
665     // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
666     if ( shutdownAll )
667       killOmniNames();
668     abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
669   }
670
671     //Destroy orb from python (for chasing memory leaks)
672   //PyRun_SimpleString("from omniORB import CORBA");
673   //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
674   //PyRun_SimpleString("orb.destroy()");
675
676   // Destroy the ORB:
677   sleep(2);
678   //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
679   ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
680   if (init)
681     init->explicit_destroy();
682   //std::cout << "@@@@@ ORB destroyed\n";
683
684   // After ORB destruction
685   if(Py_IsInitialized())
686     {
687       PyGILState_Ensure();
688       //std::cout << "@@@@@ About to PyFinalize\n";
689       Py_Finalize();
690       //std::cout << "@@@@@ DONE PyFinalize\n";
691     }
692
693   if ( shutdownAll )
694     {
695       //std::cout << "@@@@@ About to kill omni\n";
696       killOmniNames();
697       //std::cout << "@@@@@ DONE kill omni\n";
698     }
699
700   MESSAGE( "Salome_Session_Server:endofserver" );
701   return result;
702 }