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() : SUIT_Session() {}
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" ) );
360 QApplication::setApplicationName( "salome" );
361 SUIT_ResourceMgr* resMgr = s.createResourceMgr( "SalomeApp" );
362 bool isCloc = resMgr->booleanValue( "language", "locale", true );
364 QLocale::setDefault( QLocale::c() );
367 QLocale::setDefault( QLocale::system() );
371 // Create Qt application instance;
372 // this should be done the very first!
373 SALOME_QApplication _qappl( argc, argv );
374 _qappl.setOrganizationName( "salome" );
375 _qappl.setApplicationName( "salome" );
376 _qappl.setApplicationVersion( salomeVersion() );
378 // Add application library path (to search style plugin etc...)
379 QString path = QDir::convertSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
380 _qappl.addLibraryPath( path );
382 bool isGUI = isFound( "GUI", argc, argv );
383 bool isSplash = isFound( "SPLASH", argc, argv );
384 // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
385 // Note, that user preferences are not taken into account for splash settings -
386 // it is a property of the application!
387 QtxSplash* splash = 0;
388 if ( isGUI && isSplash ) {
389 // ...create resource manager
390 SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
391 resMgr.setCurrentFormat( "xml" );
392 resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
393 resMgr.loadLanguage( "LightApp" );
395 splash = QtxSplash::splash( QPixmap() );
396 splash->readSettings( &resMgr );
397 if ( splash->pixmap().isNull() )
398 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
399 if ( splash->pixmap().isNull() ) {
404 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
405 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
406 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
407 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
409 QApplication::instance()->processEvents();
418 PortableServer::POA_var poa;
420 SUIT_Session* aGUISession = 0;
421 SALOME_NamingService* _NS = 0;
422 GetInterfaceThread* guiThread = 0;
423 Session_ServerLauncher* myServerLauncher = 0;
426 // ...initialize Python (only once)
428 char* _argv[] = {(char*)""};
429 KERNEL_PYTHON::init_python( _argc,_argv );
431 // ...create ORB, get RootPOA object, NamingService, etc.
432 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
433 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
435 orb = init( orbArgc, argv );
437 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
438 poa = PortableServer::POA::_narrow( obj );
440 PortableServer::POAManager_var pman = poa->the_POAManager();
442 MESSAGE( "pman->activate()" );
444 _NS = new SALOME_NamingService( orb );
448 catch ( SALOME_Exception& e ) {
449 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
451 catch ( CORBA::SystemException& e ) {
452 INFOS( "Caught CORBA::SystemException." );
454 catch ( CORBA::Exception& e ) {
455 INFOS( "Caught CORBA::Exception." );
458 CORBA::TypeCode_var tc = tmp.type();
459 const char *p = tc->name();
460 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
462 catch ( std::exception& e ) {
463 INFOS( "run(): An exception has been caught: " <<e.what() );
466 INFOS( "Caught unknown exception." );
469 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
470 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
472 // lock session mutex to ensure that GetInterface is not called
473 // until all initialization is done
474 _SessionMutex.lock();
477 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
478 // ...lock mutex to block embedded servers launching thread until wait( mutex )
480 // ...create launcher
481 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
482 // ...block this thread until launcher is ready
483 _ServerLaunch.wait( &_GUIMutex );
485 // Start servers check thread (splash)
487 // ...lock mutex to block splash thread until wait( mutex )
489 // ...create servers checking thread
490 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
491 // ... set initial progress
492 splash->setProgress( 0, sc.totalSteps() );
495 int step = sc.currentStep();
496 int total = sc.totalSteps();
497 QString msg = sc.currentMessage();
498 QString err = sc.error();
499 if ( !err.isEmpty() ) {
500 QtxSplash::setError( err );
501 QApplication::instance()->processEvents();
505 QtxSplash::setStatus( msg, step );
506 QApplication::instance()->processEvents();
509 // ...block this thread until servers checking is finished
510 _SplashStarted.wait( &_SplashMutex );
512 // ...unlock mutex 'cause it is no more needed
513 _SplashMutex.unlock();
516 // Finalize embedded servers launcher
517 // ...block this thread until launcher is finished
518 _ServerLaunch.wait( &_GUIMutex );
519 // ...unlock mutex 'cause it is no more needed
523 // Obtain Session interface reference
524 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
525 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
527 bool shutdownAll = false;
528 bool shutdownSession = false;
530 // Launch GUI activator
533 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
534 // ...create GUI launcher
535 MESSAGE( "Session activated, Launch IAPP..." );
536 guiThread = new GetInterfaceThread( session );
540 // Allow multiple activation/deactivation of GUI
542 MESSAGE( "waiting wakeAll()" );
543 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
544 // atomic operation lock - unlock on mutex
545 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
546 // this thread wakes up, and lock mutex
548 _SessionMutex.unlock();
550 // Session might be shutdowning here, check status
551 SALOME::StatSession stat = session->GetStatSession();
552 shutdownSession = stat.state == SALOME::shutdown;
553 if ( shutdownSession ) {
554 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
558 // SUIT_Session creation
559 aGUISession = new SALOME_Session();
561 // Load SalomeApp dynamic library
562 MESSAGE( "creation SUIT_Application" );
563 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
566 Style_Salome::initialize( aGUIApp->resourceMgr() );
567 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
568 Style_Salome::apply();
570 if ( !isFound( "noexcepthandler", argc, argv ) )
571 _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
572 // aGUISession contains SalomeApp_ExceptionHandler
574 MESSAGE( "run(): starting the main event loop" );
577 splash->finish( aGUIApp->desktop() );
579 result = _qappl.exec();
583 if ( result == SUIT_Session::NORMAL ) {
584 // desktop is explicitly closed by user from GUI
585 // exit flags says if it's necessary to shutdown all servers
586 // all session server only
587 shutdownAll = aGUISession->exitFlags();
590 // desktop might be closed from:
591 // - StopSesion() /temporarily/ or
592 // - Shutdown() /permanently/
593 stat = session->GetStatSession();
594 shutdownSession = stat.state == SALOME::shutdown;
596 if ( shutdownAll || shutdownSession ) {
597 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
605 // Prepare _GUIMutex for a new GUI activation
606 _SessionMutex.lock();
610 // unlock Session mutex
611 _SessionMutex.unlock();
613 if ( myServerLauncher )
614 myServerLauncher->ShutdownAll(); // shutdown embedded servers
616 if ( shutdownAll ) // shutdown standalone servers
617 shutdownServers( _NS );
619 if ( myServerLauncher )
620 myServerLauncher->KillAll(); // kill embedded servers
622 // Unregister session server
623 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
624 if ( sessionServant )
625 sessionServant->NSunregister();
629 delete myServerLauncher;
636 //////////////////////////////////////////////////////////////
637 // VSR: silently skip exception:
638 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
639 // exception is raised when orb->destroy() is called and
640 // cpp continer is launched in the embedded mode
641 //////////////////////////////////////////////////////////////
642 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
645 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
648 //Destroy orb from python (for chasing memory leaks)
649 //PyRun_SimpleString("from omniORB import CORBA");
650 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
651 //PyRun_SimpleString("orb.destroy()");
655 //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
656 ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
658 init->explicit_destroy();
659 //std::cout << "@@@@@ ORB destroyed\n";
661 // After ORB destruction
662 if(Py_IsInitialized())
665 //std::cout << "@@@@@ About to PyFinalize\n";
667 //std::cout << "@@@@@ DONE PyFinalize\n";
672 //std::cout << "@@@@@ About to kill omni\n";
674 //std::cout << "@@@@@ DONE kill omni\n";
677 MESSAGE( "Salome_Session_Server:endofserver" );