1 // Copyright (C) 2007-2016 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>
38 #include <Utils_ORB_INIT.hxx>
39 #include <Utils_SINGLETON.hxx>
40 #include <Utils_SALOME_Exception.hxx>
41 #include <Utils_CorbaException.hxx>
43 #include <utilities.h>
44 #include "Session_ServerLauncher.hxx"
45 #include "Session_ServerCheck.hxx"
46 #include "Session_Session_i.hxx"
49 #include <QtxSplash.h>
51 #ifdef USE_SALOME_STYLE
52 #include <Style_Salome.h>
53 #endif // USE_SALOME_STYLE
55 #include "GUI_version.h"
56 #include <SUIT_Tools.h>
57 #include <SUIT_Session.h>
58 #include <SUIT_Application.h>
59 #include <SUIT_Desktop.h>
60 #include <SUIT_ResourceMgr.h>
61 #include <SUIT_ExceptionHandler.h>
63 #include <SALOMEconfig.h>
64 #include CORBA_SERVER_HEADER(SALOME_Session)
65 #include CORBA_SERVER_HEADER(SALOMEDS)
75 #include <QApplication>
77 #include <QWaitCondition>
79 #include <QTextStream>
81 /*! - read arguments, define list of server to launch with their arguments.
82 * - wait for naming service
83 * - create and run a thread for launch of all servers
87 //! CORBA server for SALOME Session
89 * SALOME_Session Server launches a SALOME session servant.
90 * The servant registers to the Naming Service.
91 * See SALOME_Session.idl for interface specification.
93 * Main services offered by the servant are:
95 * - stop Session ( must be idle )
98 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
99 void MessageOutput( QtMsgType type, const char* msg )
101 void MessageOutput( QtMsgType type, const QMessageLogContext &context, const QString &msg )
107 #ifdef QT_DEBUG_MESSAGE
108 MESSAGE( "Debug: " << qPrintable( QString(msg) ) );
112 MESSAGE( "Warning: " << qPrintable( QString(msg) ) );
115 MESSAGE( "Fatal: " << qPrintable( QString(msg) ) );
120 QString salomeVersion()
122 return GUI_VERSION_STR;
125 class SALOME_ResourceMgr : public SUIT_ResourceMgr
128 SALOME_ResourceMgr( const QString& app, const QString& resVarTemplate ) : SUIT_ResourceMgr( app, resVarTemplate )
130 setCurrentFormat( "xml" );
131 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
133 static void initResourceMgr()
135 if ( myExtAppName.isNull() || myExtAppVersion.isNull() ) {
136 SALOME_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
137 resMgr.loadLanguage( "LightApp", "en" );
138 resMgr.loadLanguage( "SalomeApp", "en" );
140 myExtAppName = QObject::tr( "APP_NAME" ).trimmed();
141 if ( myExtAppName == "APP_NAME" || myExtAppName.toLower() == "salome" )
142 myExtAppName = "SalomeApp";
143 myExtAppVersion = QObject::tr( "APP_VERSION" );
144 if ( myExtAppVersion == "APP_VERSION" ) {
145 if ( myExtAppName != "SalomeApp" )
146 myExtAppVersion = "";
147 else myExtAppVersion = salomeVersion();
151 QString version() const { return myExtAppVersion; }
154 QString userFileName( const QString& appName, const bool for_load ) const
156 if ( version().isEmpty() ) return "";
157 return SUIT_ResourceMgr::userFileName( myExtAppName, for_load );
160 virtual long userFileId( const QString& _fname ) const
162 //////////////////////////////////////////////////////////////////////////////////////////////
163 // In SALOME and SALOME-based applications the user preferences file is named as
164 // - <AppName>.xml.<AppVersion> on Windows
165 // - <AppName>rc.<AppVersion> on Linux
167 // * AppName is application name, default SalomeApp (can be customized in SALOME-based
169 // * AppVersion is application version
171 // Since version 6.5.0 of SALOME, user file is situated in the ~/.config/salome
172 // directory. For backward compatibility, when user preferences from nearest
173 // version of application is searched, user home directory is also looked through,
174 // with lower priority.
176 // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
177 // symbol since it is situated in hidden ~/.config/salome directory. Files with dot
178 // prefix also though taken into account (with lower priority) for backward compatibility.
181 // - Currently the following format of version number is supported:
182 // <major>[.<minor>[.<release>[<type><dev>]]]
183 // Parts in square brackets are considered optional. Here:
184 // * major - major version id
185 // * minor - minor version id
186 // * release - maintenance version id
187 // * type - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
188 // or 'rc' to point release candidate (case-insensitive)
189 // * dev - dev version or patch number
190 // All numerical values must be of range [1-99].
191 // Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
193 // - Versioning approach can be customized by implementing and using own resource manager class,
194 // see QtxResurceMgr, SUIT_ResourceMgr classes.
195 //////////////////////////////////////////////////////////////////////////////////////////////
197 if ( !myExtAppName.isEmpty() ) {
199 // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
200 // - SalomeApp is an application name (can be customized)
201 // - xml is a file format (xml or ini)
202 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
203 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ).arg( currentFormat() ) );
205 // On Linux, user file name is something like SalomeApprc.6.5.0 where
206 // - SalomeApp is an application name (can be customized)
207 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
209 // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
210 // when it is stored in the ~/.config/<appname> directory;
211 // for backward compatibility we also check files prepended with "." with lower priority
212 QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ) );
214 QString fname = QFileInfo( _fname ).fileName();
215 if ( exp.exactMatch( fname ) ) {
216 long fid = Qtx::versionToId( exp.cap( 1 ) );
217 if ( fid > 0 ) id = fid;
224 static QString myExtAppName;
225 static QString myExtAppVersion;
228 QString SALOME_ResourceMgr::myExtAppName = QString();
229 QString SALOME_ResourceMgr::myExtAppVersion = QString();
231 class SALOME_Session : public SUIT_Session
234 SALOME_Session( int argc, char** argv ) : SUIT_Session( argc, argv ) {}
235 virtual ~SALOME_Session() {}
238 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
240 SALOME_ResourceMgr::initResourceMgr();
241 SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
246 class SALOME_QApplication : public QApplication
249 SALOME_QApplication( int& argc, char** argv )
250 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
251 #if !defined(WIN32) && !defined(__APPLE__) && (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
252 // san: Opening an X display and choosing a visual most suitable for 3D visualization
253 // in order to make SALOME viewers work with non-native X servers
254 : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
256 : QApplication( argc, argv ),
260 virtual bool notify( QObject* receiver, QEvent* e )
264 return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
266 catch (std::exception& e) {
267 std::cerr << e.what() << std::endl;
269 catch (CORBA::Exception& e) {
270 std::cerr << "Caught CORBA::Exception" << std::endl;
273 CORBA::TypeCode_var tc = tmp.type();
274 const char *p = tc->name();
275 std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
278 std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
280 return false; // return false when exception is caught
282 SUIT_ExceptionHandler* handler() const { return myHandler; }
283 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
286 SUIT_ExceptionHandler* myHandler;
289 // class which calls SALOME::Session::GetInterface() from another thread
290 // to avoid mutual lock ( if called from the same thread as main()
291 class GetInterfaceThread : public QThread
294 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
301 if ( !CORBA::is_nil( session ) )
302 session->GetInterface();
304 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
307 SALOME::Session_var session;
310 // returns true if 'str' is found in argv
311 bool isFound( const char* str, int argc, char** argv )
313 for ( int i = 1; i <= ( argc-1 ); i++ )
314 if ( !strcmp( argv[i], str ) )
321 SALOME_LifeCycleCORBA::killOmniNames();
324 // shutdown standalone servers
325 void shutdownServers( SALOME_NamingService* theNS )
327 SALOME_LifeCycleCORBA lcc(theNS);
328 lcc.shutdownServers();
331 // ---------------------------- MAIN -----------------------
332 int main( int argc, char **argv )
334 // Install Qt debug messages handler
335 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
336 qInstallMsgHandler( MessageOutput );
338 qInstallMessageHandler( MessageOutput );
341 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
342 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
343 //Set a "native" graphic system in case if application runs on the remote host
344 QString remote(getenv("REMOTEHOST"));
345 QString client(getenv("SSH_CLIENT"));
346 if(remote.length() > 0 || client.length() > 0 ) {
347 QApplication::setGraphicsSystem(QLatin1String("native"));
351 // add <qtdir>/plugins dir to the pluins search path for image plugins
352 QString qtdir = Qtx::qtDir( "plugins" );
353 if ( !qtdir.isEmpty() )
354 QApplication::addLibraryPath( qtdir );
356 // set "C" locale if requested via preferences
358 SALOME_Session stmp( argc, argv );
359 QApplication::setApplicationName( "salome" );
360 SUIT_ResourceMgr* resMgr = stmp.createResourceMgr( "SalomeApp" );
361 bool isCloc = resMgr->booleanValue( "language", "locale", true );
363 QLocale::setDefault( QLocale::c() );
366 QLocale::setDefault( QLocale::system() );
370 // Create Qt application instance;
371 // this should be done the very first!
372 SALOME_QApplication _qappl( argc, argv );
373 _qappl.setOrganizationName( "salome" );
374 _qappl.setApplicationName( "salome" );
375 _qappl.setApplicationVersion( salomeVersion() );
377 // Add application library path (to search style plugin etc...)
378 QString path = QDir::toNativeSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
379 _qappl.addLibraryPath( path );
381 bool isGUI = isFound( "GUI", argc, argv );
382 bool isSplash = isFound( "SPLASH", argc, argv );
383 // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
384 // Note, that user preferences are not taken into account for splash settings -
385 // it is a property of the application!
386 QtxSplash* splash = 0;
387 if ( isGUI && isSplash ) {
388 // ...create resource manager
389 SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
390 resMgr.setCurrentFormat( "xml" );
391 resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
392 resMgr.loadLanguage( "LightApp" );
394 splash = QtxSplash::splash( QPixmap() );
395 splash->readSettings( &resMgr );
396 if ( splash->pixmap().isNull() )
397 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
398 if ( splash->pixmap().isNull() ) {
403 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
404 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
405 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
406 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
408 QApplication::instance()->processEvents();
417 PortableServer::POA_var poa;
419 SUIT_Session* aGUISession = 0;
420 SALOME_NamingService* _NS = 0;
421 GetInterfaceThread* guiThread = 0;
422 Session_ServerLauncher* myServerLauncher = 0;
425 // ...initialize Python (only once)
427 char* _argv[] = {(char*)""};
428 KERNEL_PYTHON::init_python( _argc,_argv );
430 // ...create ORB, get RootPOA object, NamingService, etc.
431 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
432 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
434 orb = init( orbArgc, argv );
436 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
437 poa = PortableServer::POA::_narrow( obj );
439 PortableServer::POAManager_var pman = poa->the_POAManager();
441 MESSAGE( "pman->activate()" );
443 _NS = new SALOME_NamingService( orb );
447 catch ( SALOME_Exception& e ) {
448 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
450 catch ( CORBA::SystemException& e ) {
451 INFOS( "Caught CORBA::SystemException." );
453 catch ( CORBA::Exception& e ) {
454 INFOS( "Caught CORBA::Exception." );
457 CORBA::TypeCode_var tc = tmp.type();
458 const char *p = tc->name();
459 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
461 catch ( std::exception& e ) {
462 INFOS( "run(): An exception has been caught: " <<e.what() );
465 INFOS( "Caught unknown exception." );
468 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
469 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
471 // lock session mutex to ensure that GetInterface is not called
472 // until all initialization is done
473 _SessionMutex.lock();
476 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
477 // ...lock mutex to block embedded servers launching thread until wait( mutex )
479 // ...create launcher
480 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
481 // ...block this thread until launcher is ready
482 _ServerLaunch.wait( &_GUIMutex );
484 // Start servers check thread (splash)
486 // ...lock mutex to block splash thread until wait( mutex )
488 // ...create servers checking thread
489 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
490 // ... set initial progress
491 splash->setProgress( 0, sc.totalSteps() );
494 int step = sc.currentStep();
495 int total = sc.totalSteps();
496 QString msg = sc.currentMessage();
497 QString err = sc.error();
498 if ( !err.isEmpty() ) {
499 QtxSplash::setError( err );
500 QApplication::instance()->processEvents();
504 QtxSplash::setStatus( msg, step );
505 QApplication::instance()->processEvents();
508 // ...block this thread until servers checking is finished
509 _SplashStarted.wait( &_SplashMutex );
511 // ...unlock mutex 'cause it is no more needed
512 _SplashMutex.unlock();
515 // Finalize embedded servers launcher
516 // ...block this thread until launcher is finished
517 _ServerLaunch.wait( &_GUIMutex );
518 // ...unlock mutex 'cause it is no more needed
522 // Obtain Session interface reference
523 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
524 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
526 bool shutdownAll = false;
527 bool shutdownSession = false;
529 // Launch GUI activator
532 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
533 // ...create GUI launcher
534 MESSAGE( "Session activated, Launch IAPP..." );
535 guiThread = new GetInterfaceThread( session );
539 // Allow multiple activation/deactivation of GUI
541 MESSAGE( "waiting wakeAll()" );
542 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
543 // atomic operation lock - unlock on mutex
544 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
545 // this thread wakes up, and lock mutex
547 _SessionMutex.unlock();
549 // Session might be shutdowning here, check status
550 SALOME::StatSession stat = session->GetStatSession();
551 shutdownSession = stat.state == SALOME::shutdown;
552 if ( shutdownSession ) {
553 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
557 // SUIT_Session creation
558 aGUISession = new SALOME_Session( argc, argv );
560 // Load SalomeApp dynamic library
561 MESSAGE( "creation SUIT_Application" );
562 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
565 #ifdef USE_SALOME_STYLE
566 Style_Salome::initialize( aGUIApp->resourceMgr() );
567 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
568 Style_Salome::apply();
569 #endif // USE_SALOME_STYLE
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;
596 // normally "shutdown standalone servers" flag should be false here, if we come from
597 // StopSesion() or from Shutdown();
598 // but we also have to check if somebody explicitly programmatically closed session,
599 // asking to kill servers also
600 shutdownAll = aGUISession->exitFlags();
602 if ( shutdownAll || shutdownSession ) {
603 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
611 // Prepare _GUIMutex for a new GUI activation
612 _SessionMutex.lock();
616 // unlock Session mutex
617 _SessionMutex.unlock();
619 if ( myServerLauncher )
620 myServerLauncher->ShutdownAll(); // shutdown embedded servers
622 if ( shutdownAll ) // shutdown standalone servers
623 shutdownServers( _NS );
625 if ( myServerLauncher )
626 myServerLauncher->KillAll(); // kill embedded servers
628 // Unregister session server
629 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
630 if ( sessionServant )
631 sessionServant->NSunregister();
635 delete myServerLauncher;
642 //////////////////////////////////////////////////////////////
643 // VSR: silently skip exception:
644 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
645 // exception is raised when orb->destroy() is called and
646 // cpp continer is launched in the embedded mode
647 //////////////////////////////////////////////////////////////
648 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
651 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
654 //Destroy orb from python (for chasing memory leaks)
655 //PyRun_SimpleString("from omniORB import CORBA");
656 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
657 //PyRun_SimpleString("orb.destroy()");
661 //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
662 ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
664 init->explicit_destroy();
665 //std::cout << "@@@@@ ORB destroyed\n";
667 // After ORB destruction
668 if(Py_IsInitialized())
671 //std::cout << "@@@@@ About to PyFinalize\n";
673 //std::cout << "@@@@@ DONE PyFinalize\n";
678 //std::cout << "@@@@@ About to kill omni\n";
680 //std::cout << "@@@@@ DONE kill omni\n";
683 MESSAGE( "Salome_Session_Server:endofserver" );