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