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