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