1 // Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // SALOME Session : implementation of Session.idl
24 // File : SALOME_Session_Server.cxx
25 // Author : Paul RASCLE, EDF
28 #include <SALOME_NamingService.hxx>
29 #include <SALOME_ModuleCatalog_impl.hxx>
30 #include <SALOME_LifeCycleCORBA.hxx>
31 #include <SALOME_Event.h>
33 #include <Container_init_python.hxx>
34 #include <ConnectionManager_i.hxx>
35 #include <RegistryService.hxx>
37 #ifdef ENABLE_TESTRECORDER
38 #include <TestApplication.h>
42 #include <Utils_ORB_INIT.hxx>
43 #include <Utils_SINGLETON.hxx>
44 #include <Utils_SALOME_Exception.hxx>
45 #include <Utils_CorbaException.hxx>
47 #include <utilities.h>
48 #include "Session_ServerLauncher.hxx"
49 #include "Session_ServerCheck.hxx"
50 #include "Session_Session_i.hxx"
53 #include <QtxSplash.h>
55 #include <Style_Salome.h>
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>
65 #include <SALOMEconfig.h>
66 #include CORBA_SERVER_HEADER(SALOME_Session)
67 #include CORBA_SERVER_HEADER(SALOMEDS)
77 #include <QApplication>
79 #include <QWaitCondition>
81 #include <QTextStream>
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
89 //! CORBA server for SALOME Session
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.
95 * Main services offered by the servant are:
97 * - stop Session ( must be idle )
101 void MessageOutput( QtMsgType type, const char* msg )
106 //MESSAGE( "Debug: " << msg );
109 MESSAGE( "Warning: " << msg );
112 MESSAGE( "Fatal: " << msg );
117 QString salomeVersion()
119 return GUI_VERSION_STR;
122 class SALOME_ResourceMgr : public SUIT_ResourceMgr
125 SALOME_ResourceMgr( const QString& app, const QString& resVarTemplate ) : SUIT_ResourceMgr( app, resVarTemplate )
127 setCurrentFormat( "xml" );
128 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
130 static void initResourceMgr()
132 if ( myExtAppName.isNull() || myExtAppVersion.isNull() ) {
133 SALOME_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
134 resMgr.loadLanguage( "LightApp", "en" );
135 resMgr.loadLanguage( "SalomeApp", "en" );
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();
148 QString version() const { return myExtAppVersion; }
151 QString userFileName( const QString& appName, const bool for_load ) const
153 if ( version().isEmpty() ) return "";
154 return SUIT_ResourceMgr::userFileName( myExtAppName, for_load );
157 virtual long userFileId( const QString& _fname ) const
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
164 // * AppName is application name, default SalomeApp (can be customized in SALOME-based
166 // * AppVersion is application version
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.
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.
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)
190 // - Versioning approach can be customized by implementing and using own resource manager class,
191 // see QtxResurceMgr, SUIT_ResourceMgr classes.
192 //////////////////////////////////////////////////////////////////////////////////////////////
194 if ( !myExtAppName.isEmpty() ) {
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() ) );
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
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 ) );
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;
221 static QString myExtAppName;
222 static QString myExtAppVersion;
225 QString SALOME_ResourceMgr::myExtAppName = QString();
226 QString SALOME_ResourceMgr::myExtAppVersion = QString();
228 class SALOME_Session : public SUIT_Session
231 SALOME_Session( int argc, char** argv ) : SUIT_Session( argc, argv ) {}
232 virtual ~SALOME_Session() {}
235 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
237 SALOME_ResourceMgr::initResourceMgr();
238 SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
243 #ifdef ENABLE_TESTRECORDER
244 class SALOME_QApplication : public TestApplication
246 class SALOME_QApplication : public QApplication
250 #ifdef ENABLE_TESTRECORDER
251 SALOME_QApplication( int& argc, char** argv ) : TestApplication( argc, argv ), myHandler ( 0 ) {}
253 SALOME_QApplication( int& argc, char** argv )
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() ),
259 : QApplication( argc, argv ),
264 virtual bool notify( QObject* receiver, QEvent* e )
267 #ifdef ENABLE_TESTRECORDER
268 return myHandler ? myHandler->handle( receiver, e ) :
269 TestApplication::notify( receiver, e );
272 return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
274 catch (std::exception& e) {
275 std::cerr << e.what() << std::endl;
277 catch (CORBA::Exception& e) {
278 std::cerr << "Caught CORBA::Exception" << std::endl;
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;
286 std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
288 return false; // return false when exception is caught
291 SUIT_ExceptionHandler* handler() const { return myHandler; }
292 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
295 SUIT_ExceptionHandler* myHandler;
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
303 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
310 if ( !CORBA::is_nil( session ) )
311 session->GetInterface();
313 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
316 SALOME::Session_var session;
319 // returns true if 'str' is found in argv
320 bool isFound( const char* str, int argc, char** argv )
322 for ( int i = 1; i <= ( argc-1 ); i++ )
323 if ( !strcmp( argv[i], str ) )
330 SALOME_LifeCycleCORBA::killOmniNames();
333 // shutdown standalone servers
334 void shutdownServers( SALOME_NamingService* theNS )
336 SALOME_LifeCycleCORBA lcc(theNS);
337 lcc.shutdownServers();
340 // ---------------------------- MAIN -----------------------
341 int main( int argc, char **argv )
343 // Install Qt debug messages handler
344 qInstallMsgHandler( MessageOutput );
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"));
353 // add $QTDIR/plugins to the pluins search path for image plugins
354 QString qtdir( ::getenv( "QTDIR" ) );
355 if ( !qtdir.isEmpty() )
356 QApplication::addLibraryPath( QDir( qtdir ).absoluteFilePath( "plugins" ) );
358 // set "C" locale if requested via preferences
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 );
365 QLocale::setDefault( QLocale::c() );
368 QLocale::setDefault( QLocale::system() );
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() );
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 );
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" );
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() ) {
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" ) );
410 QApplication::instance()->processEvents();
419 PortableServer::POA_var poa;
421 SUIT_Session* aGUISession = 0;
422 SALOME_NamingService* _NS = 0;
423 GetInterfaceThread* guiThread = 0;
424 Session_ServerLauncher* myServerLauncher = 0;
427 // ...initialize Python (only once)
429 char* _argv[] = {(char*)""};
430 KERNEL_PYTHON::init_python( _argc,_argv );
432 // ...create ORB, get RootPOA object, NamingService, etc.
433 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
434 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
436 orb = init( orbArgc, argv );
438 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
439 poa = PortableServer::POA::_narrow( obj );
441 PortableServer::POAManager_var pman = poa->the_POAManager();
443 MESSAGE( "pman->activate()" );
445 _NS = new SALOME_NamingService( orb );
449 catch ( SALOME_Exception& e ) {
450 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
452 catch ( CORBA::SystemException& e ) {
453 INFOS( "Caught CORBA::SystemException." );
455 catch ( CORBA::Exception& e ) {
456 INFOS( "Caught CORBA::Exception." );
459 CORBA::TypeCode_var tc = tmp.type();
460 const char *p = tc->name();
461 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
463 catch ( std::exception& e ) {
464 INFOS( "run(): An exception has been caught: " <<e.what() );
467 INFOS( "Caught unknown exception." );
470 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
471 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
473 // lock session mutex to ensure that GetInterface is not called
474 // until all initialization is done
475 _SessionMutex.lock();
478 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
479 // ...lock mutex to block embedded servers launching thread until wait( mutex )
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 );
486 // Start servers check thread (splash)
488 // ...lock mutex to block splash thread until wait( mutex )
490 // ...create servers checking thread
491 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
492 // ... set initial progress
493 splash->setProgress( 0, sc.totalSteps() );
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();
506 QtxSplash::setStatus( msg, step );
507 QApplication::instance()->processEvents();
510 // ...block this thread until servers checking is finished
511 _SplashStarted.wait( &_SplashMutex );
513 // ...unlock mutex 'cause it is no more needed
514 _SplashMutex.unlock();
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
524 // Obtain Session interface reference
525 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
526 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
528 bool shutdownAll = false;
529 bool shutdownSession = false;
531 // Launch GUI activator
534 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
535 // ...create GUI launcher
536 MESSAGE( "Session activated, Launch IAPP..." );
537 guiThread = new GetInterfaceThread( session );
541 // Allow multiple activation/deactivation of GUI
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
549 _SessionMutex.unlock();
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
559 // SUIT_Session creation
560 aGUISession = new SALOME_Session( argc, argv );
562 // Load SalomeApp dynamic library
563 MESSAGE( "creation SUIT_Application" );
564 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
567 Style_Salome::initialize( aGUIApp->resourceMgr() );
568 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
569 Style_Salome::apply();
571 if ( !isFound( "noexcepthandler", argc, argv ) )
572 _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
573 // aGUISession contains SalomeApp_ExceptionHandler
575 MESSAGE( "run(): starting the main event loop" );
578 splash->finish( aGUIApp->desktop() );
580 result = _qappl.exec();
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();
591 // desktop might be closed from:
592 // - StopSesion() /temporarily/ or
593 // - Shutdown() /permanently/
594 stat = session->GetStatSession();
595 shutdownSession = stat.state == SALOME::shutdown;
597 if ( shutdownAll || shutdownSession ) {
598 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
606 // Prepare _GUIMutex for a new GUI activation
607 _SessionMutex.lock();
611 // unlock Session mutex
612 _SessionMutex.unlock();
614 if ( myServerLauncher )
615 myServerLauncher->ShutdownAll(); // shutdown embedded servers
617 if ( shutdownAll ) // shutdown standalone servers
618 shutdownServers( _NS );
620 if ( myServerLauncher )
621 myServerLauncher->KillAll(); // kill embedded servers
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();
630 delete myServerLauncher;
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;
646 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
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()");
656 //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
657 ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
659 init->explicit_destroy();
660 //std::cout << "@@@@@ ORB destroyed\n";
662 // After ORB destruction
663 if(Py_IsInitialized())
666 //std::cout << "@@@@@ About to PyFinalize\n";
668 //std::cout << "@@@@@ DONE PyFinalize\n";
673 //std::cout << "@@@@@ About to kill omni\n";
675 //std::cout << "@@@@@ DONE kill omni\n";
678 MESSAGE( "Salome_Session_Server:endofserver" );