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