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