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