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