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
181 //////////////////////////////////////////////////////////////////////////////////////////////
182 // In SALOME and SALOME-based applications the user preferences file is named as
183 // - <AppName>.xml.<AppVersion> on Windows
184 // - <AppName>rc.<AppVersion> on Linux
186 // * AppName is application name, default SalomeApp (can be customized in SALOME-based
188 // * AppVersion is application version
190 // Since version 6.5.0 of SALOME, user file is situated in the ~/.config/salome
191 // directory. For backward compatibility, when user preferences from nearest
192 // version of application is searched, user home directory is also looked through,
193 // with lower priority.
195 // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
196 // symbol since it is situated in hidden ~/.config/salome directory. Files with dot
197 // prefix also though taken into account (with lower priority) for backward compatibility.
200 // - Currently the following format of version number is supported:
201 // <major>[.<minor>[.<release>[<type><dev>]]]
202 // Parts in square brackets are considered optional. Here:
203 // * major - major version id
204 // * minor - minor version id
205 // * release - maintenance version id
206 // * type - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
207 // or 'rc' to point release candidate (case-insensitive)
208 // * dev - dev version or patch number
209 // All numerical values must be of range [1-99].
210 // Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
212 // - Versioning approach can be customized by implementing and using own resource manager class,
213 // see QtxResurceMgr, SUIT_ResourceMgr classes.
214 //////////////////////////////////////////////////////////////////////////////////////////////
216 if ( !myExtAppName.isEmpty() ) {
218 // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
219 // - SalomeApp is an application name (can be customized)
220 // - xml is a file format (xml or ini)
221 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
222 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ).arg( currentFormat() ) );
224 // On Linux, user file name is something like SalomeApprc.6.5.0 where
225 // - SalomeApp is an application name (can be customized)
226 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
228 // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
229 // when it is stored in the ~/.config/<appname> directory;
230 // for backward compatibility we also check files prepended with "." with lower priority
231 QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ) );
233 QRegExp vers_exp( "^([0-9]+)([A-Z]|RC)?([0-9]*)", Qt::CaseInsensitive );
235 QString fname = QFileInfo( _fname ).fileName();
236 if( exp.exactMatch( fname ) ) {
237 QStringList vers = exp.cap( 1 ).split( ".", QString::SkipEmptyParts );
238 int major=0, minor=0;
239 int release = 0, dev1 = 0, dev2 = 0;
240 if ( vers.count() > 0 ) major = vers[0].toInt();
241 if ( vers.count() > 1 ) minor = vers[1].toInt();
242 if ( vers.count() > 2 ) {
243 if ( vers_exp.indexIn( vers[2] ) != -1 ) {
244 release = vers_exp.cap( 1 ).toInt();
245 QString tag = vers_exp.cap( 2 ).toLower();
246 if ( !tag.isEmpty() ) {
247 if ( tag == "rc" ) // release candidate
248 dev1 = 49; // 'rc'=49
250 dev1 = (int)( tag[ 0 ].toLatin1() ) - (int)( QChar('a').toLatin1() ) + 1; // 'a'=1, 'b'=2, ..., 'z'=26
252 if ( !vers_exp.cap( 3 ).isEmpty() )
253 dev2 = vers_exp.cap( 3 ).toInt();
257 int dev = dev1*100+dev2;
260 id*=100; id+=release;
262 if ( dev > 0 ) id-=dev;
269 static QString myExtAppName;
270 static QString myExtAppVersion;
273 QString SALOME_ResourceMgr::myExtAppName = QString();
274 QString SALOME_ResourceMgr::myExtAppVersion = QString();
276 class SALOME_Session : public SUIT_Session
279 SALOME_Session() : SUIT_Session() {}
280 virtual ~SALOME_Session() {}
283 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
285 SALOME_ResourceMgr::initResourceMgr();
286 SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
291 #ifdef ENABLE_TESTRECORDER
292 class SALOME_QApplication : public TestApplication
294 class SALOME_QApplication : public QApplication
298 #ifdef ENABLE_TESTRECORDER
299 SALOME_QApplication( int& argc, char** argv ) : TestApplication( argc, argv ), myHandler ( 0 ) {}
301 SALOME_QApplication( int& argc, char** argv )
303 // san: Opening an X display and choosing a visual most suitable for 3D visualization
304 // in order to make SALOME viewers work with non-native X servers
305 : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
307 : QApplication( argc, argv ),
312 virtual bool notify( QObject* receiver, QEvent* e )
314 #if OCC_VERSION_LARGE < 0x06010100
315 // Disable GUI user actions while python command is executed
316 if (SUIT_Session::IsPythonExecuted()) {
317 // Disable mouse and keyboard events
318 QEvent::Type aType = e->type();
319 if (aType == QEvent::MouseButtonPress || aType == QEvent::MouseButtonRelease ||
320 aType == QEvent::MouseButtonDblClick || aType == QEvent::MouseMove ||
321 aType == QEvent::Wheel || aType == QEvent::ContextMenu ||
322 aType == QEvent::KeyPress || aType == QEvent::KeyRelease ||
323 aType == QEvent::Accel || aType == QEvent::AccelOverride)
328 #ifdef ENABLE_TESTRECORDER
329 return myHandler ? myHandler->handle( receiver, e ) :
330 TestApplication::notify( receiver, e );
333 return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
335 catch (std::exception& e) {
336 std::cerr << e.what() << std::endl;
338 catch (CORBA::Exception& e) {
339 std::cerr << "Caught CORBA::Exception" << std::endl;
342 CORBA::TypeCode_var tc = tmp.type();
343 const char *p = tc->name();
344 std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
347 std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
349 return false; // return false when exception is caught
352 SUIT_ExceptionHandler* handler() const { return myHandler; }
353 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
356 SUIT_ExceptionHandler* myHandler;
359 // class which calls SALOME::Session::GetInterface() from another thread
360 // to avoid mutual lock ( if called from the same thread as main()
361 class GetInterfaceThread : public QThread
364 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
371 if ( !CORBA::is_nil( session ) )
372 session->GetInterface();
374 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
377 SALOME::Session_var session;
380 // returns true if 'str' is found in argv
381 bool isFound( const char* str, int argc, char** argv )
383 for ( int i = 1; i <= ( argc-1 ); i++ )
384 if ( !strcmp( argv[i], str ) )
391 SALOME_LifeCycleCORBA::killOmniNames();
394 // shutdown standalone servers
395 void shutdownServers( SALOME_NamingService* theNS )
397 SALOME_LifeCycleCORBA lcc(theNS);
398 lcc.shutdownServers();
401 // ---------------------------- MAIN -----------------------
402 int main( int argc, char **argv )
404 // Install Qt debug messages handler
405 qInstallMsgHandler( MessageOutput );
407 // add $QTDIR/plugins to the pluins search path for image plugins
408 QString qtdir( ::getenv( "QTDIR" ) );
409 if ( !qtdir.isEmpty() )
410 QApplication::addLibraryPath( QDir( qtdir ).absoluteFilePath( "plugins" ) );
412 // Create Qt application instance;
413 // this should be done the very first!
414 SALOME_QApplication _qappl( argc, argv );
415 _qappl.setOrganizationName( "salome" );
416 _qappl.setApplicationName( "salome" );
417 _qappl.setApplicationVersion( salomeVersion() );
419 // Add application library path (to search style plugin etc...)
420 QString path = QDir::convertSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
421 _qappl.addLibraryPath( path );
423 bool isGUI = isFound( "GUI", argc, argv );
424 bool isSplash = isFound( "SPLASH", argc, argv );
425 // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
426 // Note, that user preferences are not taken into account for splash settings -
427 // it is a property of the application!
428 QtxSplash* splash = 0;
429 if ( isGUI && isSplash ) {
430 // ...create resource manager
431 SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
432 resMgr.setCurrentFormat( "xml" );
433 resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
434 resMgr.loadLanguage( "LightApp" );
436 splash = QtxSplash::splash( QPixmap() );
437 splash->readSettings( &resMgr );
438 if ( splash->pixmap().isNull() )
439 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
440 if ( splash->pixmap().isNull() ) {
445 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
446 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
447 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
448 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
450 QApplication::instance()->processEvents();
459 PortableServer::POA_var poa;
461 SUIT_Session* aGUISession = 0;
462 SALOME_NamingService* _NS = 0;
463 GetInterfaceThread* guiThread = 0;
464 Session_ServerLauncher* myServerLauncher = 0;
467 // ...initialize Python (only once)
469 char* _argv[] = {(char*)""};
470 KERNEL_PYTHON::init_python( _argc,_argv );
471 PyEval_RestoreThread( KERNEL_PYTHON::_gtstate );
472 if ( !KERNEL_PYTHON::salome_shared_modules_module ) // import only once
473 KERNEL_PYTHON::salome_shared_modules_module = PyImport_ImportModule( "salome_shared_modules" );
474 if ( !KERNEL_PYTHON::salome_shared_modules_module ) {
475 INFOS( "salome_shared_modules_module == NULL" );
478 PyEval_ReleaseThread( KERNEL_PYTHON::_gtstate );
480 // ...create ORB, get RootPOA object, NamingService, etc.
481 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
482 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
484 orb = init( orbArgc, argv );
486 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
487 poa = PortableServer::POA::_narrow( obj );
489 PortableServer::POAManager_var pman = poa->the_POAManager();
491 MESSAGE( "pman->activate()" );
493 _NS = new SALOME_NamingService( orb );
497 catch ( SALOME_Exception& e ) {
498 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
500 catch ( CORBA::SystemException& e ) {
501 INFOS( "Caught CORBA::SystemException." );
503 catch ( CORBA::Exception& e ) {
504 INFOS( "Caught CORBA::Exception." );
507 CORBA::TypeCode_var tc = tmp.type();
508 const char *p = tc->name();
509 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
511 catch ( std::exception& e ) {
512 INFOS( "run(): An exception has been caught: " <<e.what() );
515 INFOS( "Caught unknown exception." );
518 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
519 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
521 // lock session mutex to ensure that GetInterface is not called
522 // until all initialization is done
523 _SessionMutex.lock();
526 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
527 // ...lock mutex to block embedded servers launching thread until wait( mutex )
529 // ...create launcher
530 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
531 // ...block this thread until launcher is ready
532 _ServerLaunch.wait( &_GUIMutex );
534 // Start servers check thread (splash)
536 // ...lock mutex to block splash thread until wait( mutex )
538 // ...create servers checking thread
539 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
540 // ... set initial progress
541 splash->setProgress( 0, sc.totalSteps() );
544 int step = sc.currentStep();
545 int total = sc.totalSteps();
546 QString msg = sc.currentMessage();
547 QString err = sc.error();
548 if ( !err.isEmpty() ) {
549 QtxSplash::setError( err );
550 QApplication::instance()->processEvents();
554 QtxSplash::setStatus( msg, step );
555 QApplication::instance()->processEvents();
558 // ...block this thread until servers checking is finished
559 _SplashStarted.wait( &_SplashMutex );
561 // ...unlock mutex 'cause it is no more needed
562 _SplashMutex.unlock();
565 // Finalize embedded servers launcher
566 // ...block this thread until launcher is finished
567 _ServerLaunch.wait( &_GUIMutex );
568 // ...unlock mutex 'cause it is no more needed
572 // Obtain Session interface reference
573 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
574 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
576 bool shutdownAll = false;
577 bool shutdownSession = false;
579 // Launch GUI activator
582 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
583 // ...create GUI launcher
584 MESSAGE( "Session activated, Launch IAPP..." );
585 guiThread = new GetInterfaceThread( session );
589 // Allow multiple activation/deactivation of GUI
591 MESSAGE( "waiting wakeAll()" );
592 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
593 // atomic operation lock - unlock on mutex
594 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
595 // this thread wakes up, and lock mutex
597 _SessionMutex.unlock();
599 // Session might be shutdowning here, check status
600 SALOME::StatSession stat = session->GetStatSession();
601 shutdownSession = stat.state == SALOME::shutdown;
602 if ( shutdownSession ) {
603 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
607 // SUIT_Session creation
608 aGUISession = new SALOME_Session();
610 // Load SalomeApp dynamic library
611 MESSAGE( "creation SUIT_Application" );
612 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
615 Style_Salome::initialize( aGUIApp->resourceMgr() );
616 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
617 Style_Salome::apply();
619 if ( !isFound( "noexcepthandler", argc, argv ) )
620 _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
621 // aGUISession contains SalomeApp_ExceptionHandler
623 MESSAGE( "run(): starting the main event loop" );
626 splash->finish( aGUIApp->desktop() );
628 result = _qappl.exec();
632 if ( result == SUIT_Session::NORMAL ) {
633 // desktop is explicitly closed by user from GUI
634 // exit flags says if it's necessary to shutdown all servers
635 // all session server only
636 shutdownAll = aGUISession->exitFlags();
639 // desktop might be closed from:
640 // - StopSesion() /temporarily/ or
641 // - Shutdown() /permanently/
642 stat = session->GetStatSession();
643 shutdownSession = stat.state == SALOME::shutdown;
645 if ( shutdownAll || shutdownSession ) {
646 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
654 // Prepare _GUIMutex for a new GUI activation
655 _SessionMutex.lock();
659 // unlock Session mutex
660 _SessionMutex.unlock();
663 shutdownServers( _NS );
665 if ( myServerLauncher )
666 myServerLauncher->KillAll(); // kill embedded servers
668 // Unregister session server
669 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
670 if ( sessionServant )
671 sessionServant->NSunregister();
675 delete myServerLauncher;
682 //////////////////////////////////////////////////////////////
683 // VSR: silently skip exception:
684 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
685 // exception is raised when orb->destroy() is called and
686 // cpp continer is launched in the embedded mode
687 //////////////////////////////////////////////////////////////
688 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
691 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
695 //Destroy orb from python (for chasing memory leaks)
696 //PyRun_SimpleString("from omniORB import CORBA");
697 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
698 //PyRun_SimpleString("orb.destroy()");
704 MESSAGE( "Salome_Session_Server:endofserver" );