1 // Copyright (C) 2007-2012 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.
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 <Basics_OCCTVersion.hxx>
35 #include <Container_init_python.hxx>
36 #include <ConnectionManager_i.hxx>
37 #include <RegistryService.hxx>
39 #ifdef ENABLE_TESTRECORDER
40 #include <TestApplication.h>
44 #include <Utils_ORB_INIT.hxx>
45 #include <Utils_SINGLETON.hxx>
46 #include <Utils_SALOME_Exception.hxx>
47 #include <Utils_CorbaException.hxx>
49 #include <utilities.h>
50 #include "Session_ServerLauncher.hxx"
51 #include "Session_ServerCheck.hxx"
52 #include "Session_Session_i.hxx"
55 #include <QtxSplash.h>
57 #include <Style_Salome.h>
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)
73 #include <QApplication>
75 #include <QWaitCondition>
77 #include <QTextStream>
79 /*! - read arguments, define list of server to launch with their arguments.
80 * - wait for naming service
81 * - create and run a thread for launch of all servers
85 //! CORBA server for SALOME Session
87 * SALOME_Session Server launches a SALOME session servant.
88 * The servant registers to the Naming Service.
89 * See SALOME_Session.idl for interface specification.
91 * Main services offered by the servant are:
93 * - stop Session ( must be idle )
97 PyObject* salome_shared_modules_module = 0;
99 void MessageOutput( QtMsgType type, const char* msg )
104 //MESSAGE( "Debug: " << msg );
107 MESSAGE( "Warning: " << msg );
110 MESSAGE( "Fatal: " << msg );
116 static const char* pixmap_not_found_xpm[] = {
138 QString salomeVersion()
140 return GUI_VERSION_STR;
143 class SALOME_ResourceMgr : public SUIT_ResourceMgr
146 SALOME_ResourceMgr( const QString& app, const QString& resVarTemplate ) : SUIT_ResourceMgr( app, resVarTemplate )
148 setCurrentFormat( "xml" );
149 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
150 setDefaultPixmap( QPixmap( pixmap_not_found_xpm ) );
152 static void initResourceMgr()
154 if ( myExtAppName.isNull() || myExtAppVersion.isNull() ) {
155 SALOME_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
156 resMgr.loadLanguage( "LightApp", "en" );
157 resMgr.loadLanguage( "SalomeApp", "en" );
159 myExtAppName = QObject::tr( "APP_NAME" ).trimmed();
160 if ( myExtAppName == "APP_NAME" || myExtAppName.toLower() == "salome" )
161 myExtAppName = "SalomeApp";
162 myExtAppVersion = QObject::tr( "APP_VERSION" );
163 if ( myExtAppVersion == "APP_VERSION" ) {
164 if ( myExtAppName != "SalomeApp" )
165 myExtAppVersion = "";
166 else myExtAppVersion = salomeVersion();
170 QString version() const { return myExtAppVersion; }
173 QString userFileName( const QString& appName, const bool for_load ) const
175 if ( version().isEmpty() ) return "";
176 return SUIT_ResourceMgr::userFileName( myExtAppName, for_load );
179 virtual long userFileId( const QString& _fname ) const
182 if ( !myExtAppName.isEmpty() ) {
184 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)$" ).arg( myExtAppName ).arg( currentFormat() ) );
186 QRegExp exp( QString( "\\.%1rc\\.([a-zA-Z0-9.]+)$" ).arg( myExtAppName ) );
188 QRegExp vers_exp( "^([0-9]+)([A-Za-z]?)([0-9]*)$" );
190 QString fname = QFileInfo( _fname ).fileName();
191 if( exp.exactMatch( fname ) ) {
192 QStringList vers = exp.cap( 1 ).split( ".", QString::SkipEmptyParts );
193 int major=0, minor=0;
194 int release = 0, dev1 = 0, dev2 = 0;
195 if ( vers.count() > 0 ) major = vers[0].toInt();
196 if ( vers.count() > 1 ) minor = vers[1].toInt();
197 if ( vers.count() > 2 ) {
198 if( vers_exp.indexIn( vers[2] ) != -1 ) {
199 release = vers_exp.cap( 1 ).toInt();
200 dev1 = vers_exp.cap( 2 )[ 0 ].toLatin1();
201 dev2 = vers_exp.cap( 3 ).toInt();
205 int dev = dev1*100+dev2;
208 id*=100; id+=release;
210 if ( dev > 0 ) id+=dev-10000;
217 static QString myExtAppName;
218 static QString myExtAppVersion;
221 QString SALOME_ResourceMgr::myExtAppName = QString();
222 QString SALOME_ResourceMgr::myExtAppVersion = QString();
224 class SALOME_Session : public SUIT_Session
227 SALOME_Session() : SUIT_Session() {}
228 virtual ~SALOME_Session() {}
231 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
233 SALOME_ResourceMgr::initResourceMgr();
234 SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
239 #ifdef ENABLE_TESTRECORDER
240 class SALOME_QApplication : public TestApplication
242 class SALOME_QApplication : public QApplication
246 #ifdef ENABLE_TESTRECORDER
247 SALOME_QApplication( int& argc, char** argv ) : TestApplication( argc, argv ), myHandler ( 0 ) {}
249 SALOME_QApplication( int& argc, char** argv )
251 // san: Opening an X display and choosing a visual most suitable for 3D visualization
252 // in order to make SALOME viewers work with non-native X servers
253 : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
255 : QApplication( argc, argv ),
260 virtual bool notify( QObject* receiver, QEvent* e )
262 #if OCC_VERSION_LARGE < 0x06010100
263 // Disable GUI user actions while python command is executed
264 if (SUIT_Session::IsPythonExecuted()) {
265 // Disable mouse and keyboard events
266 QEvent::Type aType = e->type();
267 if (aType == QEvent::MouseButtonPress || aType == QEvent::MouseButtonRelease ||
268 aType == QEvent::MouseButtonDblClick || aType == QEvent::MouseMove ||
269 aType == QEvent::Wheel || aType == QEvent::ContextMenu ||
270 aType == QEvent::KeyPress || aType == QEvent::KeyRelease ||
271 aType == QEvent::Accel || aType == QEvent::AccelOverride)
276 #ifdef ENABLE_TESTRECORDER
277 return myHandler ? myHandler->handle( receiver, e ) :
278 TestApplication::notify( receiver, e );
281 return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
283 catch (std::exception& e) {
284 std::cerr << e.what() << std::endl;
286 catch (CORBA::Exception& e) {
287 std::cerr << "Caught CORBA::Exception" << std::endl;
290 CORBA::TypeCode_var tc = tmp.type();
291 const char *p = tc->name();
292 std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
295 std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
297 return false; // return false when exception is caught
300 SUIT_ExceptionHandler* handler() const { return myHandler; }
301 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
304 SUIT_ExceptionHandler* myHandler;
307 // class which calls SALOME::Session::GetInterface() from another thread
308 // to avoid mutual lock ( if called from the same thread as main()
309 class GetInterfaceThread : public QThread
312 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
319 if ( !CORBA::is_nil( session ) )
320 session->GetInterface();
322 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
325 SALOME::Session_var session;
328 // returns true if 'str' is found in argv
329 bool isFound( const char* str, int argc, char** argv )
331 for ( int i = 1; i <= ( argc-1 ); i++ )
332 if ( !strcmp( argv[i], str ) )
339 SALOME_LifeCycleCORBA::killOmniNames();
342 // shutdown standalone servers
343 void shutdownServers( SALOME_NamingService* theNS )
345 SALOME_LifeCycleCORBA lcc(theNS);
346 lcc.shutdownServers();
349 // ---------------------------- MAIN -----------------------
350 int main( int argc, char **argv )
352 // Install Qt debug messages handler
353 qInstallMsgHandler( MessageOutput );
355 // add $QTDIR/plugins to the pluins search path for image plugins
356 QString qtdir( ::getenv( "QTDIR" ) );
357 if ( !qtdir.isEmpty() )
358 QApplication::addLibraryPath( QDir( qtdir ).absoluteFilePath( "plugins" ) );
360 // Create Qt application instance;
361 // this should be done the very first!
362 SALOME_QApplication _qappl( argc, argv );
363 _qappl.setOrganizationName( "salome" );
364 _qappl.setApplicationName( "salome" );
365 _qappl.setApplicationVersion( salomeVersion() );
367 // Add application library path (to search style plugin etc...)
368 QString path = QDir::convertSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
369 _qappl.addLibraryPath( path );
371 bool isGUI = isFound( "GUI", argc, argv );
372 bool isSplash = isFound( "SPLASH", argc, argv );
373 // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
374 // Note, that user preferences are not taken into account for splash settings -
375 // it is a property of the application!
376 QtxSplash* splash = 0;
377 if ( isGUI && isSplash ) {
378 // ...create resource manager
379 SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
380 resMgr.setCurrentFormat( "xml" );
381 resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
382 resMgr.loadLanguage( "LightApp" );
384 splash = QtxSplash::splash( QPixmap() );
385 splash->readSettings( &resMgr );
386 if ( splash->pixmap().isNull() )
387 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
388 if ( splash->pixmap().isNull() ) {
393 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
394 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
395 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
396 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
398 QApplication::instance()->processEvents();
407 PortableServer::POA_var poa;
409 SUIT_Session* aGUISession = 0;
410 SALOME_NamingService* _NS = 0;
411 GetInterfaceThread* guiThread = 0;
412 Session_ServerLauncher* myServerLauncher = 0;
415 // ...initialize Python (only once)
417 char* _argv[] = {(char*)""};
418 KERNEL_PYTHON::init_python( _argc,_argv );
419 PyEval_RestoreThread( KERNEL_PYTHON::_gtstate );
420 if ( !KERNEL_PYTHON::salome_shared_modules_module ) // import only once
421 KERNEL_PYTHON::salome_shared_modules_module = PyImport_ImportModule( "salome_shared_modules" );
422 if ( !KERNEL_PYTHON::salome_shared_modules_module ) {
423 INFOS( "salome_shared_modules_module == NULL" );
426 PyEval_ReleaseThread( KERNEL_PYTHON::_gtstate );
428 // ...create ORB, get RootPOA object, NamingService, etc.
429 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
430 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
432 orb = init( orbArgc, argv );
434 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
435 poa = PortableServer::POA::_narrow( obj );
437 PortableServer::POAManager_var pman = poa->the_POAManager();
439 MESSAGE( "pman->activate()" );
441 _NS = new SALOME_NamingService( orb );
445 catch ( SALOME_Exception& e ) {
446 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
448 catch ( CORBA::SystemException& e ) {
449 INFOS( "Caught CORBA::SystemException." );
451 catch ( CORBA::Exception& e ) {
452 INFOS( "Caught CORBA::Exception." );
455 CORBA::TypeCode_var tc = tmp.type();
456 const char *p = tc->name();
457 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
459 catch ( std::exception& e ) {
460 INFOS( "run(): An exception has been caught: " <<e.what() );
463 INFOS( "Caught unknown exception." );
466 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
467 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
469 // lock session mutex to ensure that GetInterface is not called
470 // until all initialization is done
471 _SessionMutex.lock();
474 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
475 // ...lock mutex to block embedded servers launching thread until wait( mutex )
477 // ...create launcher
478 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
479 // ...block this thread until launcher is ready
480 _ServerLaunch.wait( &_GUIMutex );
482 // Start servers check thread (splash)
484 // ...lock mutex to block splash thread until wait( mutex )
486 // ...create servers checking thread
487 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
488 // ... set initial progress
489 splash->setProgress( 0, sc.totalSteps() );
492 int step = sc.currentStep();
493 int total = sc.totalSteps();
494 QString msg = sc.currentMessage();
495 QString err = sc.error();
496 if ( !err.isEmpty() ) {
497 QtxSplash::setError( err );
498 QApplication::instance()->processEvents();
502 QtxSplash::setStatus( msg, step );
503 QApplication::instance()->processEvents();
506 // ...block this thread until servers checking is finished
507 _SplashStarted.wait( &_SplashMutex );
509 // ...unlock mutex 'cause it is no more needed
510 _SplashMutex.unlock();
513 // Finalize embedded servers launcher
514 // ...block this thread until launcher is finished
515 _ServerLaunch.wait( &_GUIMutex );
516 // ...unlock mutex 'cause it is no more needed
520 // Obtain Session interface reference
521 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
522 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
524 bool shutdownAll = false;
525 bool shutdownSession = false;
527 // Launch GUI activator
530 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
531 // ...create GUI launcher
532 MESSAGE( "Session activated, Launch IAPP..." );
533 guiThread = new GetInterfaceThread( session );
537 // Allow multiple activation/deactivation of GUI
539 MESSAGE( "waiting wakeAll()" );
540 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
541 // atomic operation lock - unlock on mutex
542 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
543 // this thread wakes up, and lock mutex
545 _SessionMutex.unlock();
547 // Session might be shutdowning here, check status
548 SALOME::StatSession stat = session->GetStatSession();
549 shutdownSession = stat.state == SALOME::shutdown;
550 if ( shutdownSession ) {
551 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
555 // SUIT_Session creation
556 aGUISession = new SALOME_Session();
558 // Load SalomeApp dynamic library
559 MESSAGE( "creation SUIT_Application" );
560 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
563 Style_Salome::initialize( aGUIApp->resourceMgr() );
564 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
565 Style_Salome::apply();
567 if ( !isFound( "noexcepthandler", argc, argv ) )
568 _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
569 // aGUISession contains SalomeApp_ExceptionHandler
571 MESSAGE( "run(): starting the main event loop" );
574 splash->finish( aGUIApp->desktop() );
576 result = _qappl.exec();
580 if ( result == SUIT_Session::NORMAL ) {
581 // desktop is explicitly closed by user from GUI
582 // exit flags says if it's necessary to shutdown all servers
583 // all session server only
584 shutdownAll = aGUISession->exitFlags();
587 // desktop might be closed from:
588 // - StopSesion() /temporarily/ or
589 // - Shutdown() /permanently/
590 stat = session->GetStatSession();
591 shutdownSession = stat.state == SALOME::shutdown;
593 if ( shutdownAll || shutdownSession ) {
594 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
602 // Prepare _GUIMutex for a new GUI activation
603 _SessionMutex.lock();
607 // unlock Session mutex
608 _SessionMutex.unlock();
611 shutdownServers( _NS );
613 if ( myServerLauncher )
614 myServerLauncher->KillAll(); // kill embedded servers
616 // Unregister session server
617 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
618 if ( sessionServant )
619 sessionServant->NSunregister();
623 delete myServerLauncher;
630 //////////////////////////////////////////////////////////////
631 // VSR: silently skip exception:
632 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
633 // exception is raised when orb->destroy() is called and
634 // cpp continer is launched in the embedded mode
635 //////////////////////////////////////////////////////////////
636 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
639 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
643 //Destroy orb from python (for chasing memory leaks)
644 //PyRun_SimpleString("from omniORB import CORBA");
645 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
646 //PyRun_SimpleString("orb.destroy()");
652 MESSAGE( "Salome_Session_Server:endofserver" );