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