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