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