Salome HOME
Load Qt resources properly: take into account QT_ROOT_DIR instead of (QTDIR)
[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 <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 to the pluins search path for image plugins
354   QString qtdir = qgetenv( "QT_ROOT_DIR" );
355   if ( qtdir.isEmpty() )
356     qtdir = qgetenv( "QTDIR" );
357   if ( !qtdir.isEmpty() )
358     QApplication::addLibraryPath( QDir( qtdir ).absoluteFilePath( "plugins" ) );
359
360   // set "C" locale if requested via preferences
361   {
362     SALOME_Session stmp( argc, argv );
363     QApplication::setApplicationName( "salome" );
364     SUIT_ResourceMgr* resMgr = stmp.createResourceMgr( "SalomeApp" );
365     bool isCloc = resMgr->booleanValue( "language", "locale", true );
366     if ( isCloc ) {
367       QLocale::setDefault( QLocale::c() );
368     }
369     else {
370       QLocale::setDefault( QLocale::system() );
371     }
372   }
373
374   // Create Qt application instance;
375   // this should be done the very first!
376   SALOME_QApplication _qappl( argc, argv );
377   _qappl.setOrganizationName( "salome" );
378   _qappl.setApplicationName( "salome" );
379   _qappl.setApplicationVersion( salomeVersion() );
380
381   // Add application library path (to search style plugin etc...)
382   QString path = QDir::convertSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
383   _qappl.addLibraryPath( path );
384
385   bool isGUI    = isFound( "GUI",    argc, argv );
386   bool isSplash = isFound( "SPLASH", argc, argv );
387   // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
388   // Note, that user preferences are not taken into account for splash settings -
389   // it is a property of the application!
390   QtxSplash* splash = 0;
391   if ( isGUI && isSplash ) {
392     // ...create resource manager
393     SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
394     resMgr.setCurrentFormat( "xml" );
395     resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
396     resMgr.loadLanguage( "LightApp" );
397     //
398     splash = QtxSplash::splash( QPixmap() );
399     splash->readSettings( &resMgr );
400     if ( splash->pixmap().isNull() )
401       splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
402     if ( splash->pixmap().isNull() ) {
403       delete splash;
404       splash = 0;
405     }
406     else {
407       splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
408       splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
409       splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
410       splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
411       splash->show();
412       QApplication::instance()->processEvents();
413     }
414   }
415
416   
417   // Initialization
418   int result = -1;
419
420   CORBA::ORB_var orb;
421   PortableServer::POA_var poa;
422
423   SUIT_Session* aGUISession = 0;
424   SALOME_NamingService* _NS = 0;
425   GetInterfaceThread* guiThread = 0;
426   Session_ServerLauncher* myServerLauncher = 0;
427
428   try {
429     // ...initialize Python (only once)
430     int   _argc   = 1;
431     char* _argv[] = {(char*)""};
432     KERNEL_PYTHON::init_python( _argc,_argv );
433
434     // ...create ORB, get RootPOA object, NamingService, etc.
435     ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
436     ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
437     int orbArgc = 1;
438     orb = init( orbArgc, argv );
439
440     CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
441     poa = PortableServer::POA::_narrow( obj );
442
443     PortableServer::POAManager_var pman = poa->the_POAManager();
444     pman->activate() ;
445     MESSAGE( "pman->activate()" );
446
447     _NS = new SALOME_NamingService( orb );
448
449     result = 0;
450   }
451   catch ( SALOME_Exception& e ) {
452     INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
453   }
454   catch ( CORBA::SystemException& e ) {
455     INFOS( "Caught CORBA::SystemException." );
456   }
457   catch ( CORBA::Exception& e ) {
458     INFOS( "Caught CORBA::Exception." );
459     CORBA::Any tmp;
460     tmp<<= e;
461     CORBA::TypeCode_var tc = tmp.type();
462     const char *p = tc->name();
463     INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
464   }
465   catch ( std::exception& e ) {
466     INFOS( "run(): An exception has been caught: " <<e.what() );
467   }
468   catch (...) {
469     INFOS( "Caught unknown exception." );
470   }
471
472   QMutex _GUIMutex, _SessionMutex, _SplashMutex;
473   QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
474
475   // lock session mutex to ensure that GetInterface is not called
476   // until all initialization is done
477   _SessionMutex.lock();
478
479   if ( !result ) {
480     // Start embedded servers launcher (Registry, SALOMEDS, etc.)
481     // ...lock mutex to block embedded servers launching thread until wait( mutex )
482     _GUIMutex.lock();  
483     // ...create launcher
484     myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
485     // ...block this thread until launcher is ready
486     _ServerLaunch.wait( &_GUIMutex );
487     
488     // Start servers check thread (splash)
489     if ( splash ) {
490       // ...lock mutex to block splash thread until wait( mutex )
491       _SplashMutex.lock();
492       // ...create servers checking thread
493       Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
494       // ... set initial progress
495       splash->setProgress( 0, sc.totalSteps() );
496       // start check loop 
497       while ( true ) {
498         int step    = sc.currentStep();
499         int total   = sc.totalSteps();
500         QString msg = sc.currentMessage();
501         QString err = sc.error();
502         if ( !err.isEmpty() ) {
503           QtxSplash::setError( err );
504           QApplication::instance()->processEvents();
505           result = -1;
506           break;
507         }
508         QtxSplash::setStatus( msg, step );
509         QApplication::instance()->processEvents();
510         if ( step >= total )
511           break;
512         // ...block this thread until servers checking is finished
513         _SplashStarted.wait( &_SplashMutex );
514       }
515       // ...unlock mutex 'cause it is no more needed
516       _SplashMutex.unlock();
517     }
518
519     // Finalize embedded servers launcher 
520     // ...block this thread until launcher is finished
521     _ServerLaunch.wait( &_GUIMutex );
522     // ...unlock mutex 'cause it is no more needed
523     _GUIMutex.unlock();
524   }
525
526   // Obtain Session interface reference
527   CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
528   SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
529
530   bool shutdownAll = false;
531   bool shutdownSession = false;
532   if ( !result ) {
533     // Launch GUI activator
534     if ( isGUI ) {
535       if ( splash )
536         splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
537       // ...create GUI launcher
538       MESSAGE( "Session activated, Launch IAPP..." );
539       guiThread = new GetInterfaceThread( session );
540     }
541
542     // GUI activation
543     // Allow multiple activation/deactivation of GUI
544     while ( true ) {
545       MESSAGE( "waiting wakeAll()" );
546       _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
547       // atomic operation lock - unlock on mutex
548       // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
549       // this thread wakes up, and lock mutex
550
551       _SessionMutex.unlock();
552
553       // Session might be shutdowning here, check status
554       SALOME::StatSession stat = session->GetStatSession();
555       shutdownSession = stat.state == SALOME::shutdown;
556       if ( shutdownSession ) {
557         _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
558         break;
559       }
560
561       // SUIT_Session creation
562       aGUISession = new SALOME_Session( argc, argv );
563
564       // Load SalomeApp dynamic library
565       MESSAGE( "creation SUIT_Application" );
566       SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
567       if ( aGUIApp )
568       {
569         Style_Salome::initialize( aGUIApp->resourceMgr() );
570         if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
571           Style_Salome::apply();
572
573         if ( !isFound( "noexcepthandler", argc, argv ) )
574           _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
575                                                        // aGUISession contains SalomeApp_ExceptionHandler
576         // Run GUI loop
577         MESSAGE( "run(): starting the main event loop" );
578
579         if ( splash )
580           splash->finish( aGUIApp->desktop() );
581
582         result = _qappl.exec();
583         
584         splash = 0;
585
586         if ( result == SUIT_Session::NORMAL ) {
587         // desktop is explicitly closed by user from GUI
588         // exit flags says if it's necessary to shutdown all servers
589         // all session server only
590           shutdownAll = aGUISession->exitFlags();
591         }
592         else {
593           // desktop might be closed from:
594           // - StopSesion() /temporarily/ or
595           // - Shutdown() /permanently/
596           stat = session->GetStatSession();
597           shutdownSession = stat.state == SALOME::shutdown;
598         }
599         if ( shutdownAll || shutdownSession ) {
600           _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
601           break;
602         }
603       }
604
605       delete aGUISession;
606       aGUISession = 0;
607       
608       // Prepare _GUIMutex for a new GUI activation
609       _SessionMutex.lock();
610     }
611   }
612
613   // unlock Session mutex
614   _SessionMutex.unlock();
615   
616   if ( myServerLauncher )
617     myServerLauncher->ShutdownAll(); // shutdown embedded servers
618
619   if ( shutdownAll )                 // shutdown standalone servers
620     shutdownServers( _NS );
621
622   if ( myServerLauncher )
623     myServerLauncher->KillAll();     // kill embedded servers
624
625   // Unregister session server
626   SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
627   if ( sessionServant )
628     sessionServant->NSunregister();
629
630   delete aGUISession;
631   delete guiThread;
632   delete myServerLauncher;
633   delete _NS;
634
635   try  {
636     orb->shutdown(0);
637   }
638   catch (...) {
639     //////////////////////////////////////////////////////////////
640     // VSR: silently skip exception:
641     // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown 
642     // exception is raised when orb->destroy() is called and
643     // cpp continer is launched in the embedded mode
644     //////////////////////////////////////////////////////////////
645     // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
646     if ( shutdownAll )
647       killOmniNames();
648     abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
649   }
650
651     //Destroy orb from python (for chasing memory leaks)
652   //PyRun_SimpleString("from omniORB import CORBA");
653   //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
654   //PyRun_SimpleString("orb.destroy()");
655
656   // Destroy the ORB:
657   sleep(2);
658   //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
659   ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
660   if (init)
661     init->explicit_destroy();
662   //std::cout << "@@@@@ ORB destroyed\n";
663
664   // After ORB destruction
665   if(Py_IsInitialized())
666     {
667       PyGILState_Ensure();
668       //std::cout << "@@@@@ About to PyFinalize\n";
669       Py_Finalize();
670       //std::cout << "@@@@@ DONE PyFinalize\n";
671     }
672
673   if ( shutdownAll )
674     {
675       //std::cout << "@@@@@ About to kill omni\n";
676       killOmniNames();
677       //std::cout << "@@@@@ DONE kill omni\n";
678     }
679
680   MESSAGE( "Salome_Session_Server:endofserver" );
681   return result;
682 }