1 // Copyright (C) 2007-2015 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 #ifdef USE_SALOME_STYLE
56 #include <Style_Salome.h>
57 #endif // USE_SALOME_STYLE
59 #include "GUI_version.h"
60 #include <SUIT_Tools.h>
61 #include <SUIT_Session.h>
62 #include <SUIT_Application.h>
63 #include <SUIT_Desktop.h>
64 #include <SUIT_ResourceMgr.h>
65 #include <SUIT_ExceptionHandler.h>
67 #include <SALOMEconfig.h>
68 #include CORBA_SERVER_HEADER(SALOME_Session)
69 #include CORBA_SERVER_HEADER(SALOMEDS)
79 #include <QApplication>
81 #include <QWaitCondition>
83 #include <QTextStream>
85 /*! - read arguments, define list of server to launch with their arguments.
86 * - wait for naming service
87 * - create and run a thread for launch of all servers
91 //! CORBA server for SALOME Session
93 * SALOME_Session Server launches a SALOME session servant.
94 * The servant registers to the Naming Service.
95 * See SALOME_Session.idl for interface specification.
97 * Main services offered by the servant are:
99 * - stop Session ( must be idle )
100 * - get session state
102 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
103 void MessageOutput( QtMsgType type, const char* msg )
105 void MessageOutput( QtMsgType type, const QMessageLogContext &context, const QString &msg )
111 #ifdef QT_DEBUG_MESSAGE
112 MESSAGE( "Debug: " << qPrintable( QString(msg) ) );
116 MESSAGE( "Warning: " << qPrintable( QString(msg) ) );
119 MESSAGE( "Fatal: " << qPrintable( QString(msg) ) );
124 QString salomeVersion()
126 return GUI_VERSION_STR;
129 class SALOME_ResourceMgr : public SUIT_ResourceMgr
132 SALOME_ResourceMgr( const QString& app, const QString& resVarTemplate ) : SUIT_ResourceMgr( app, resVarTemplate )
134 setCurrentFormat( "xml" );
135 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
137 static void initResourceMgr()
139 if ( myExtAppName.isNull() || myExtAppVersion.isNull() ) {
140 SALOME_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
141 resMgr.loadLanguage( "LightApp", "en" );
142 resMgr.loadLanguage( "SalomeApp", "en" );
144 myExtAppName = QObject::tr( "APP_NAME" ).trimmed();
145 if ( myExtAppName == "APP_NAME" || myExtAppName.toLower() == "salome" )
146 myExtAppName = "SalomeApp";
147 myExtAppVersion = QObject::tr( "APP_VERSION" );
148 if ( myExtAppVersion == "APP_VERSION" ) {
149 if ( myExtAppName != "SalomeApp" )
150 myExtAppVersion = "";
151 else myExtAppVersion = salomeVersion();
155 QString version() const { return myExtAppVersion; }
158 QString userFileName( const QString& appName, const bool for_load ) const
160 if ( version().isEmpty() ) return "";
161 return SUIT_ResourceMgr::userFileName( myExtAppName, for_load );
164 virtual long userFileId( const QString& _fname ) const
166 //////////////////////////////////////////////////////////////////////////////////////////////
167 // In SALOME and SALOME-based applications the user preferences file is named as
168 // - <AppName>.xml.<AppVersion> on Windows
169 // - <AppName>rc.<AppVersion> on Linux
171 // * AppName is application name, default SalomeApp (can be customized in SALOME-based
173 // * AppVersion is application version
175 // Since version 6.5.0 of SALOME, user file is situated in the ~/.config/salome
176 // directory. For backward compatibility, when user preferences from nearest
177 // version of application is searched, user home directory is also looked through,
178 // with lower priority.
180 // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
181 // symbol since it is situated in hidden ~/.config/salome directory. Files with dot
182 // prefix also though taken into account (with lower priority) for backward compatibility.
185 // - Currently the following format of version number is supported:
186 // <major>[.<minor>[.<release>[<type><dev>]]]
187 // Parts in square brackets are considered optional. Here:
188 // * major - major version id
189 // * minor - minor version id
190 // * release - maintenance version id
191 // * type - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
192 // or 'rc' to point release candidate (case-insensitive)
193 // * dev - dev version or patch number
194 // All numerical values must be of range [1-99].
195 // Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
197 // - Versioning approach can be customized by implementing and using own resource manager class,
198 // see QtxResurceMgr, SUIT_ResourceMgr classes.
199 //////////////////////////////////////////////////////////////////////////////////////////////
201 if ( !myExtAppName.isEmpty() ) {
203 // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
204 // - SalomeApp is an application name (can be customized)
205 // - xml is a file format (xml or ini)
206 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
207 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ).arg( currentFormat() ) );
209 // On Linux, user file name is something like SalomeApprc.6.5.0 where
210 // - SalomeApp is an application name (can be customized)
211 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
213 // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
214 // when it is stored in the ~/.config/<appname> directory;
215 // for backward compatibility we also check files prepended with "." with lower priority
216 QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ) );
218 QString fname = QFileInfo( _fname ).fileName();
219 if ( exp.exactMatch( fname ) ) {
220 long fid = Qtx::versionToId( exp.cap( 1 ) );
221 if ( fid > 0 ) id = fid;
228 static QString myExtAppName;
229 static QString myExtAppVersion;
232 QString SALOME_ResourceMgr::myExtAppName = QString();
233 QString SALOME_ResourceMgr::myExtAppVersion = QString();
235 class SALOME_Session : public SUIT_Session
238 SALOME_Session( int argc, char** argv ) : SUIT_Session( argc, argv ) {}
239 virtual ~SALOME_Session() {}
242 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
244 SALOME_ResourceMgr::initResourceMgr();
245 SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
250 #ifdef ENABLE_TESTRECORDER
251 class SALOME_QApplication : public TestApplication
253 class SALOME_QApplication : public QApplication
257 #ifdef ENABLE_TESTRECORDER
258 SALOME_QApplication( int& argc, char** argv ) : TestApplication( argc, argv ), myHandler ( 0 ) {}
260 SALOME_QApplication( int& argc, char** argv )
261 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
262 #if !defined WIN32 && QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
263 // san: Opening an X display and choosing a visual most suitable for 3D visualization
264 // in order to make SALOME viewers work with non-native X servers
265 : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
267 : QApplication( argc, argv ),
272 virtual bool notify( QObject* receiver, QEvent* e )
275 #ifdef ENABLE_TESTRECORDER
276 return myHandler ? myHandler->handle( receiver, e ) :
277 TestApplication::notify( receiver, e );
280 return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
282 catch (std::exception& e) {
283 std::cerr << e.what() << std::endl;
285 catch (CORBA::Exception& e) {
286 std::cerr << "Caught CORBA::Exception" << std::endl;
289 CORBA::TypeCode_var tc = tmp.type();
290 const char *p = tc->name();
291 std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
294 std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
296 return false; // return false when exception is caught
299 SUIT_ExceptionHandler* handler() const { return myHandler; }
300 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
303 SUIT_ExceptionHandler* myHandler;
306 // class which calls SALOME::Session::GetInterface() from another thread
307 // to avoid mutual lock ( if called from the same thread as main()
308 class GetInterfaceThread : public QThread
311 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
318 if ( !CORBA::is_nil( session ) )
319 session->GetInterface();
321 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
324 SALOME::Session_var session;
327 // returns true if 'str' is found in argv
328 bool isFound( const char* str, int argc, char** argv )
330 for ( int i = 1; i <= ( argc-1 ); i++ )
331 if ( !strcmp( argv[i], str ) )
338 SALOME_LifeCycleCORBA::killOmniNames();
341 // shutdown standalone servers
342 void shutdownServers( SALOME_NamingService* theNS )
344 SALOME_LifeCycleCORBA lcc(theNS);
345 lcc.shutdownServers();
348 // ---------------------------- MAIN -----------------------
349 int main( int argc, char **argv )
351 // Install Qt debug messages handler
352 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
353 qInstallMsgHandler( MessageOutput );
355 qInstallMessageHandler( MessageOutput );
358 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
359 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
360 //Set a "native" graphic system in case if application runs on the remote host
361 QString remote(getenv("REMOTEHOST"));
362 QString client(getenv("SSH_CLIENT"));
363 if(remote.length() > 0 || client.length() > 0 ) {
364 QApplication::setGraphicsSystem(QLatin1String("native"));
368 // add <qtdir>/plugins dir to the pluins search path for image plugins
369 QString qtdir = Qtx::qtDir( "plugins" );
370 if ( !qtdir.isEmpty() )
371 QApplication::addLibraryPath( qtdir );
373 // set "C" locale if requested via preferences
375 SALOME_Session stmp( argc, argv );
376 QApplication::setApplicationName( "salome" );
377 SUIT_ResourceMgr* resMgr = stmp.createResourceMgr( "SalomeApp" );
378 bool isCloc = resMgr->booleanValue( "language", "locale", true );
380 QLocale::setDefault( QLocale::c() );
383 QLocale::setDefault( QLocale::system() );
387 // Create Qt application instance;
388 // this should be done the very first!
389 SALOME_QApplication _qappl( argc, argv );
390 _qappl.setOrganizationName( "salome" );
391 _qappl.setApplicationName( "salome" );
392 _qappl.setApplicationVersion( salomeVersion() );
394 // Add application library path (to search style plugin etc...)
395 QString path = QDir::toNativeSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
396 _qappl.addLibraryPath( path );
398 bool isGUI = isFound( "GUI", argc, argv );
399 bool isSplash = isFound( "SPLASH", argc, argv );
400 // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
401 // Note, that user preferences are not taken into account for splash settings -
402 // it is a property of the application!
403 QtxSplash* splash = 0;
404 if ( isGUI && isSplash ) {
405 // ...create resource manager
406 SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
407 resMgr.setCurrentFormat( "xml" );
408 resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
409 resMgr.loadLanguage( "LightApp" );
411 splash = QtxSplash::splash( QPixmap() );
412 splash->readSettings( &resMgr );
413 if ( splash->pixmap().isNull() )
414 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
415 if ( splash->pixmap().isNull() ) {
420 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
421 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
422 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
423 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
425 QApplication::instance()->processEvents();
434 PortableServer::POA_var poa;
436 SUIT_Session* aGUISession = 0;
437 SALOME_NamingService* _NS = 0;
438 GetInterfaceThread* guiThread = 0;
439 Session_ServerLauncher* myServerLauncher = 0;
442 // ...initialize Python (only once)
444 char* _argv[] = {(char*)""};
445 KERNEL_PYTHON::init_python( _argc,_argv );
447 // ...create ORB, get RootPOA object, NamingService, etc.
448 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
449 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
451 orb = init( orbArgc, argv );
453 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
454 poa = PortableServer::POA::_narrow( obj );
456 PortableServer::POAManager_var pman = poa->the_POAManager();
458 MESSAGE( "pman->activate()" );
460 _NS = new SALOME_NamingService( orb );
464 catch ( SALOME_Exception& e ) {
465 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
467 catch ( CORBA::SystemException& e ) {
468 INFOS( "Caught CORBA::SystemException." );
470 catch ( CORBA::Exception& e ) {
471 INFOS( "Caught CORBA::Exception." );
474 CORBA::TypeCode_var tc = tmp.type();
475 const char *p = tc->name();
476 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
478 catch ( std::exception& e ) {
479 INFOS( "run(): An exception has been caught: " <<e.what() );
482 INFOS( "Caught unknown exception." );
485 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
486 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
488 // lock session mutex to ensure that GetInterface is not called
489 // until all initialization is done
490 _SessionMutex.lock();
493 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
494 // ...lock mutex to block embedded servers launching thread until wait( mutex )
496 // ...create launcher
497 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
498 // ...block this thread until launcher is ready
499 _ServerLaunch.wait( &_GUIMutex );
501 // Start servers check thread (splash)
503 // ...lock mutex to block splash thread until wait( mutex )
505 // ...create servers checking thread
506 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
507 // ... set initial progress
508 splash->setProgress( 0, sc.totalSteps() );
511 int step = sc.currentStep();
512 int total = sc.totalSteps();
513 QString msg = sc.currentMessage();
514 QString err = sc.error();
515 if ( !err.isEmpty() ) {
516 QtxSplash::setError( err );
517 QApplication::instance()->processEvents();
521 QtxSplash::setStatus( msg, step );
522 QApplication::instance()->processEvents();
525 // ...block this thread until servers checking is finished
526 _SplashStarted.wait( &_SplashMutex );
528 // ...unlock mutex 'cause it is no more needed
529 _SplashMutex.unlock();
532 // Finalize embedded servers launcher
533 // ...block this thread until launcher is finished
534 _ServerLaunch.wait( &_GUIMutex );
535 // ...unlock mutex 'cause it is no more needed
539 // Obtain Session interface reference
540 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
541 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
543 bool shutdownAll = false;
544 bool shutdownSession = false;
546 // Launch GUI activator
549 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
550 // ...create GUI launcher
551 MESSAGE( "Session activated, Launch IAPP..." );
552 guiThread = new GetInterfaceThread( session );
556 // Allow multiple activation/deactivation of GUI
558 MESSAGE( "waiting wakeAll()" );
559 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
560 // atomic operation lock - unlock on mutex
561 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
562 // this thread wakes up, and lock mutex
564 _SessionMutex.unlock();
566 // Session might be shutdowning here, check status
567 SALOME::StatSession stat = session->GetStatSession();
568 shutdownSession = stat.state == SALOME::shutdown;
569 if ( shutdownSession ) {
570 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
574 // SUIT_Session creation
575 aGUISession = new SALOME_Session( argc, argv );
577 // Load SalomeApp dynamic library
578 MESSAGE( "creation SUIT_Application" );
579 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
582 #ifdef USE_SALOME_STYLE
583 Style_Salome::initialize( aGUIApp->resourceMgr() );
584 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
585 Style_Salome::apply();
586 #endif // USE_SALOME_STYLE
588 if ( !isFound( "noexcepthandler", argc, argv ) )
589 _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
590 // aGUISession contains SalomeApp_ExceptionHandler
592 MESSAGE( "run(): starting the main event loop" );
595 splash->finish( aGUIApp->desktop() );
597 result = _qappl.exec();
601 if ( result == SUIT_Session::NORMAL ) {
602 // desktop is explicitly closed by user from GUI
603 // exit flags says if it's necessary to shutdown all servers
604 // all session server only
605 shutdownAll = aGUISession->exitFlags();
608 // desktop might be closed from:
609 // - StopSesion() /temporarily/ or
610 // - Shutdown() /permanently/
611 stat = session->GetStatSession();
612 shutdownSession = stat.state == SALOME::shutdown;
614 if ( shutdownAll || shutdownSession ) {
615 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
623 // Prepare _GUIMutex for a new GUI activation
624 _SessionMutex.lock();
628 // unlock Session mutex
629 _SessionMutex.unlock();
631 if ( myServerLauncher )
632 myServerLauncher->ShutdownAll(); // shutdown embedded servers
634 if ( shutdownAll ) // shutdown standalone servers
635 shutdownServers( _NS );
637 if ( myServerLauncher )
638 myServerLauncher->KillAll(); // kill embedded servers
640 // Unregister session server
641 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
642 if ( sessionServant )
643 sessionServant->NSunregister();
647 delete myServerLauncher;
654 //////////////////////////////////////////////////////////////
655 // VSR: silently skip exception:
656 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
657 // exception is raised when orb->destroy() is called and
658 // cpp continer is launched in the embedded mode
659 //////////////////////////////////////////////////////////////
660 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
663 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
666 //Destroy orb from python (for chasing memory leaks)
667 //PyRun_SimpleString("from omniORB import CORBA");
668 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
669 //PyRun_SimpleString("orb.destroy()");
673 //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
674 ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
676 init->explicit_destroy();
677 //std::cout << "@@@@@ ORB destroyed\n";
679 // After ORB destruction
680 if(Py_IsInitialized())
683 //std::cout << "@@@@@ About to PyFinalize\n";
685 //std::cout << "@@@@@ DONE PyFinalize\n";
690 //std::cout << "@@@@@ About to kill omni\n";
692 //std::cout << "@@@@@ DONE kill omni\n";
695 MESSAGE( "Salome_Session_Server:endofserver" );