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 <Container_init_python.hxx>
29 #include <SALOME_NamingService.hxx>
30 #include <SALOME_ModuleCatalog_impl.hxx>
31 #include <SALOME_LifeCycleCORBA.hxx>
32 #include <SALOME_Event.h>
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 <QtxMsgHandler.h>
50 #include <QtxSplash.h>
52 #ifdef USE_SALOME_STYLE
53 #include <Style_Salome.h>
54 #endif // USE_SALOME_STYLE
56 #include "GUI_version.h"
57 #include <SUIT_Tools.h>
58 #include <SUIT_Session.h>
59 #include <SUIT_Application.h>
60 #include <SUIT_Desktop.h>
61 #include <SUIT_ResourceMgr.h>
62 #include <SUIT_ExceptionHandler.h>
64 #include <SALOMEconfig.h>
65 #include CORBA_SERVER_HEADER(SALOME_Session)
66 #include CORBA_SERVER_HEADER(SALOMEDS)
76 #include <QApplication>
78 #include <QWaitCondition>
80 #include <QTextStream>
82 /*! - read arguments, define list of server to launch with their arguments.
83 * - wait for naming service
84 * - create and run a thread for launch of all servers
88 //! CORBA server for SALOME Session
90 * SALOME_Session Server launches a SALOME session servant.
91 * The servant registers to the Naming Service.
92 * See SALOME_Session.idl for interface specification.
94 * Main services offered by the servant are:
96 * - stop Session ( must be idle )
100 class SessionMsgHandler: public QtxMsgHandlerCallback
103 SessionMsgHandler() {}
104 void qtMessage(QtMsgType type, const QMessageLogContext& context, const QString& message)
109 #ifdef QT_DEBUG_MESSAGE
110 MESSAGE( "Debug: " << qPrintable( message ) );
114 MESSAGE( "Warning: " << qPrintable( message ) );
117 MESSAGE( "Critical: " << qPrintable( message ) );
120 MESSAGE( "Fatal: " << qPrintable( message ) );
124 MESSAGE( "Information: " << qPrintable( message ) );
130 QString salomeVersion()
132 return GUI_VERSION_STR;
135 class SALOME_ResourceMgr : public SUIT_ResourceMgr
138 SALOME_ResourceMgr( const QString& app, const QString& resVarTemplate ) : SUIT_ResourceMgr( app, resVarTemplate )
140 setCurrentFormat( "xml" );
141 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
143 static void initResourceMgr()
145 if ( myExtAppName.isNull() || myExtAppVersion.isNull() ) {
146 SALOME_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
147 resMgr.loadLanguage( "LightApp", "en" );
148 resMgr.loadLanguage( "SalomeApp", "en" );
150 myExtAppName = QObject::tr( "APP_NAME" ).trimmed();
151 if ( myExtAppName == "APP_NAME" || myExtAppName.toLower() == "salome" )
152 myExtAppName = "SalomeApp";
153 myExtAppVersion = QObject::tr( "APP_VERSION" );
154 if ( myExtAppVersion == "APP_VERSION" ) {
155 if ( myExtAppName != "SalomeApp" )
156 myExtAppVersion = "";
157 else myExtAppVersion = salomeVersion();
161 QString version() const { return myExtAppVersion; }
164 QString userFileName( const QString& appName, const bool for_load ) const
166 if ( version().isEmpty() ) return "";
167 return SUIT_ResourceMgr::userFileName( myExtAppName, for_load );
170 virtual long userFileId( const QString& _fname ) const
172 //////////////////////////////////////////////////////////////////////////////////////////////
173 // In SALOME and SALOME-based applications the user preferences file is named as
174 // - <AppName>.xml.<AppVersion> on Windows
175 // - <AppName>rc.<AppVersion> on Linux
177 // * AppName is application name, default SalomeApp (can be customized in SALOME-based
179 // * AppVersion is application version
181 // Since version 6.5.0 of SALOME, user file is situated in the ~/.config/salome
182 // directory. For backward compatibility, when user preferences from nearest
183 // version of application is searched, user home directory is also looked through,
184 // with lower priority.
186 // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
187 // symbol since it is situated in hidden ~/.config/salome directory. Files with dot
188 // prefix also though taken into account (with lower priority) for backward compatibility.
191 // - Currently the following format of version number is supported:
192 // <major>[.<minor>[.<release>[<type><dev>]]]
193 // Parts in square brackets are considered optional. Here:
194 // * major - major version id
195 // * minor - minor version id
196 // * release - maintenance version id
197 // * type - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
198 // or 'rc' to point release candidate (case-insensitive)
199 // * dev - dev version or patch number
200 // All numerical values must be of range [1-99].
201 // Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
203 // - Versioning approach can be customized by implementing and using own resource manager class,
204 // see QtxResurceMgr, SUIT_ResourceMgr classes.
205 //////////////////////////////////////////////////////////////////////////////////////////////
207 if ( !myExtAppName.isEmpty() ) {
209 // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
210 // - SalomeApp is an application name (can be customized)
211 // - xml is a file format (xml or ini)
212 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
213 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ).arg( currentFormat() ) );
215 // On Linux, user file name is something like SalomeApprc.6.5.0 where
216 // - SalomeApp is an application name (can be customized)
217 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
219 // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
220 // when it is stored in the ~/.config/<appname> directory;
221 // for backward compatibility we also check files prepended with "." with lower priority
222 QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ) );
224 QString fname = QFileInfo( _fname ).fileName();
225 if ( exp.exactMatch( fname ) ) {
226 long fid = Qtx::versionToId( exp.cap( 1 ) );
227 if ( fid > 0 ) id = fid;
234 static QString myExtAppName;
235 static QString myExtAppVersion;
238 QString SALOME_ResourceMgr::myExtAppName = QString();
239 QString SALOME_ResourceMgr::myExtAppVersion = QString();
241 class SALOME_Session : public SUIT_Session
244 SALOME_Session( int argc, char** argv ) : SUIT_Session( argc, argv ) {}
245 virtual ~SALOME_Session() {}
248 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
250 SALOME_ResourceMgr::initResourceMgr();
251 SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
256 class SALOME_QApplication : public QApplication
259 SALOME_QApplication( int& argc, char** argv )
260 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
261 #if !defined(WIN32) && !defined(__APPLE__) && (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
262 // san: Opening an X display and choosing a visual most suitable for 3D visualization
263 // in order to make SALOME viewers work with non-native X servers
264 : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
266 : QApplication( argc, argv ),
270 virtual bool notify( QObject* receiver, QEvent* e )
274 return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
276 catch (std::exception& e) {
277 std::cerr << e.what() << std::endl;
279 catch (CORBA::Exception& e) {
280 std::cerr << "Caught CORBA::Exception" << std::endl;
283 CORBA::TypeCode_var tc = tmp.type();
284 const char *p = tc->name();
285 std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
288 std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
290 return false; // return false when exception is caught
292 SUIT_ExceptionHandler* handler() const { return myHandler; }
293 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
296 SUIT_ExceptionHandler* myHandler;
299 // class which calls SALOME::Session::GetInterface() from another thread
300 // to avoid mutual lock ( if called from the same thread as main()
301 class GetInterfaceThread : public QThread
304 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
311 if ( !CORBA::is_nil( session ) )
312 session->GetInterface();
314 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
317 SALOME::Session_var session;
320 // returns true if 'str' is found in argv
321 bool isFound( const char* str, int argc, char** argv )
323 for ( int i = 1; i <= ( argc-1 ); i++ )
324 if ( !strcmp( argv[i], str ) )
331 SALOME_LifeCycleCORBA::killOmniNames();
334 // shutdown standalone servers
335 void shutdownServers( SALOME_NamingService* theNS )
337 SALOME_LifeCycleCORBA lcc(theNS);
338 lcc.shutdownServers();
341 // ---------------------------- MAIN -----------------------
342 int main( int argc, char **argv )
344 // Install Qt debug messages handler
345 SessionMsgHandler msgHandler;
346 qInstallMessageHandler(QtxMsgHandler);
348 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
349 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
350 //Set a "native" graphic system in case if application runs on the remote host
351 QString remote(getenv("REMOTEHOST"));
352 QString client(getenv("SSH_CLIENT"));
353 if(remote.length() > 0 || client.length() > 0 ) {
354 QApplication::setGraphicsSystem(QLatin1String("native"));
358 // add <qtdir>/plugins dir to the pluins search path for image plugins
359 QString qtdir = Qtx::qtDir( "plugins" );
360 if ( !qtdir.isEmpty() )
361 QApplication::addLibraryPath( qtdir );
363 // set "C" locale if requested via preferences
365 SALOME_Session stmp( argc, argv );
366 QApplication::setApplicationName( "salome" );
367 SUIT_ResourceMgr* resMgr = stmp.createResourceMgr( "SalomeApp" );
368 bool isCloc = resMgr->booleanValue( "language", "locale", true );
370 QLocale::setDefault( QLocale::c() );
373 QLocale::setDefault( QLocale::system() );
377 #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
379 // RNV: setup the default format:
380 // QSurfaceFormat should be set before creation of QApplication,
381 // so to avoid conflicts beetween SALOME and ParaView QSurfaceFormats we should merge theirs formats
382 // (see void Qtx::initDefaultSurfaceFormat()) and set the resultant format here.
383 Qtx::initDefaultSurfaceFormat();
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;
613 // normally "shutdown standalone servers" flag should be false here, if we come from
614 // StopSesion() or from Shutdown();
615 // but we also have to check if somebody explicitly programmatically closed session,
616 // asking to kill servers also
617 shutdownAll = aGUISession->exitFlags();
619 if ( shutdownAll || shutdownSession ) {
620 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
628 // Prepare _GUIMutex for a new GUI activation
629 _SessionMutex.lock();
633 // unlock Session mutex
634 _SessionMutex.unlock();
636 if ( myServerLauncher )
637 myServerLauncher->ShutdownAll(); // shutdown embedded servers
639 if ( shutdownAll ) // shutdown standalone servers
640 shutdownServers( _NS );
642 if ( myServerLauncher )
643 myServerLauncher->KillAll(); // kill embedded servers
645 // Unregister session server
646 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
647 if ( sessionServant )
648 sessionServant->NSunregister();
652 delete myServerLauncher;
659 //////////////////////////////////////////////////////////////
660 // VSR: silently skip exception:
661 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
662 // exception is raised when orb->destroy() is called and
663 // cpp continer is launched in the embedded mode
664 //////////////////////////////////////////////////////////////
665 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
668 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
671 //Destroy orb from python (for chasing memory leaks)
672 //PyRun_SimpleString("from omniORB import CORBA");
673 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
674 //PyRun_SimpleString("orb.destroy()");
678 //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
679 ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
681 init->explicit_destroy();
682 //std::cout << "@@@@@ ORB destroyed\n";
684 // After ORB destruction
685 if(Py_IsInitialized())
688 //std::cout << "@@@@@ About to PyFinalize\n";
690 //std::cout << "@@@@@ DONE PyFinalize\n";
695 //std::cout << "@@@@@ About to kill omni\n";
697 //std::cout << "@@@@@ DONE kill omni\n";
700 MESSAGE( "Salome_Session_Server:endofserver" );