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>
80 #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
81 #include <QSurfaceFormat>
84 /*! - read arguments, define list of server to launch with their arguments.
85 * - wait for naming service
86 * - create and run a thread for launch of all servers
90 //! CORBA server for SALOME Session
92 * SALOME_Session Server launches a SALOME session servant.
93 * The servant registers to the Naming Service.
94 * See SALOME_Session.idl for interface specification.
96 * Main services offered by the servant are:
98 * - stop Session ( must be idle )
101 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
102 void MessageOutput( QtMsgType type, const char* msg )
104 void MessageOutput( QtMsgType type, const QMessageLogContext &context, const QString &msg )
110 #ifdef QT_DEBUG_MESSAGE
111 MESSAGE( "Debug: " << qPrintable( QString(msg) ) );
115 MESSAGE( "Warning: " << qPrintable( QString(msg) ) );
118 MESSAGE( "Fatal: " << qPrintable( QString(msg) ) );
123 QString salomeVersion()
125 return GUI_VERSION_STR;
128 class SALOME_ResourceMgr : public SUIT_ResourceMgr
131 SALOME_ResourceMgr( const QString& app, const QString& resVarTemplate ) : SUIT_ResourceMgr( app, resVarTemplate )
133 setCurrentFormat( "xml" );
134 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
136 static void initResourceMgr()
138 if ( myExtAppName.isNull() || myExtAppVersion.isNull() ) {
139 SALOME_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
140 resMgr.loadLanguage( "LightApp", "en" );
141 resMgr.loadLanguage( "SalomeApp", "en" );
143 myExtAppName = QObject::tr( "APP_NAME" ).trimmed();
144 if ( myExtAppName == "APP_NAME" || myExtAppName.toLower() == "salome" )
145 myExtAppName = "SalomeApp";
146 myExtAppVersion = QObject::tr( "APP_VERSION" );
147 if ( myExtAppVersion == "APP_VERSION" ) {
148 if ( myExtAppName != "SalomeApp" )
149 myExtAppVersion = "";
150 else myExtAppVersion = salomeVersion();
154 QString version() const { return myExtAppVersion; }
157 QString userFileName( const QString& appName, const bool for_load ) const
159 if ( version().isEmpty() ) return "";
160 return SUIT_ResourceMgr::userFileName( myExtAppName, for_load );
163 virtual long userFileId( const QString& _fname ) const
165 //////////////////////////////////////////////////////////////////////////////////////////////
166 // In SALOME and SALOME-based applications the user preferences file is named as
167 // - <AppName>.xml.<AppVersion> on Windows
168 // - <AppName>rc.<AppVersion> on Linux
170 // * AppName is application name, default SalomeApp (can be customized in SALOME-based
172 // * AppVersion is application version
174 // Since version 6.5.0 of SALOME, user file is situated in the ~/.config/salome
175 // directory. For backward compatibility, when user preferences from nearest
176 // version of application is searched, user home directory is also looked through,
177 // with lower priority.
179 // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
180 // symbol since it is situated in hidden ~/.config/salome directory. Files with dot
181 // prefix also though taken into account (with lower priority) for backward compatibility.
184 // - Currently the following format of version number is supported:
185 // <major>[.<minor>[.<release>[<type><dev>]]]
186 // Parts in square brackets are considered optional. Here:
187 // * major - major version id
188 // * minor - minor version id
189 // * release - maintenance version id
190 // * type - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
191 // or 'rc' to point release candidate (case-insensitive)
192 // * dev - dev version or patch number
193 // All numerical values must be of range [1-99].
194 // Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
196 // - Versioning approach can be customized by implementing and using own resource manager class,
197 // see QtxResurceMgr, SUIT_ResourceMgr classes.
198 //////////////////////////////////////////////////////////////////////////////////////////////
200 if ( !myExtAppName.isEmpty() ) {
202 // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
203 // - SalomeApp is an application name (can be customized)
204 // - xml is a file format (xml or ini)
205 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
206 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ).arg( currentFormat() ) );
208 // On Linux, user file name is something like SalomeApprc.6.5.0 where
209 // - SalomeApp is an application name (can be customized)
210 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
212 // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
213 // when it is stored in the ~/.config/<appname> directory;
214 // for backward compatibility we also check files prepended with "." with lower priority
215 QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ) );
217 QString fname = QFileInfo( _fname ).fileName();
218 if ( exp.exactMatch( fname ) ) {
219 long fid = Qtx::versionToId( exp.cap( 1 ) );
220 if ( fid > 0 ) id = fid;
227 static QString myExtAppName;
228 static QString myExtAppVersion;
231 QString SALOME_ResourceMgr::myExtAppName = QString();
232 QString SALOME_ResourceMgr::myExtAppVersion = QString();
234 class SALOME_Session : public SUIT_Session
237 SALOME_Session( int argc, char** argv ) : SUIT_Session( argc, argv ) {}
238 virtual ~SALOME_Session() {}
241 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
243 SALOME_ResourceMgr::initResourceMgr();
244 SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
249 class SALOME_QApplication : public QApplication
252 SALOME_QApplication( int& argc, char** argv )
253 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
254 #if !defined(WIN32) && !defined(__APPLE__) && (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
255 // san: Opening an X display and choosing a visual most suitable for 3D visualization
256 // in order to make SALOME viewers work with non-native X servers
257 : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
259 : QApplication( argc, argv ),
263 virtual bool notify( QObject* receiver, QEvent* e )
267 return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
269 catch (std::exception& e) {
270 std::cerr << e.what() << std::endl;
272 catch (CORBA::Exception& e) {
273 std::cerr << "Caught CORBA::Exception" << std::endl;
276 CORBA::TypeCode_var tc = tmp.type();
277 const char *p = tc->name();
278 std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
281 std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
283 return false; // return false when exception is caught
285 SUIT_ExceptionHandler* handler() const { return myHandler; }
286 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
289 SUIT_ExceptionHandler* myHandler;
292 // class which calls SALOME::Session::GetInterface() from another thread
293 // to avoid mutual lock ( if called from the same thread as main()
294 class GetInterfaceThread : public QThread
297 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
304 if ( !CORBA::is_nil( session ) )
305 session->GetInterface();
307 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
310 SALOME::Session_var session;
313 // returns true if 'str' is found in argv
314 bool isFound( const char* str, int argc, char** argv )
316 for ( int i = 1; i <= ( argc-1 ); i++ )
317 if ( !strcmp( argv[i], str ) )
324 SALOME_LifeCycleCORBA::killOmniNames();
327 // shutdown standalone servers
328 void shutdownServers( SALOME_NamingService* theNS )
330 SALOME_LifeCycleCORBA lcc(theNS);
331 lcc.shutdownServers();
334 // ---------------------------- MAIN -----------------------
335 int main( int argc, char **argv )
337 // Install Qt debug messages handler
338 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
339 qInstallMsgHandler( MessageOutput );
341 qInstallMessageHandler( MessageOutput );
344 // TODO (QT5 PORTING) Below is a temporary solution, to allow compiling with Qt 5
345 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
346 //Set a "native" graphic system in case if application runs on the remote host
347 QString remote(getenv("REMOTEHOST"));
348 QString client(getenv("SSH_CLIENT"));
349 if(remote.length() > 0 || client.length() > 0 ) {
350 QApplication::setGraphicsSystem(QLatin1String("native"));
354 // add <qtdir>/plugins dir to the pluins search path for image plugins
355 QString qtdir = Qtx::qtDir( "plugins" );
356 if ( !qtdir.isEmpty() )
357 QApplication::addLibraryPath( qtdir );
359 // set "C" locale if requested via preferences
361 SALOME_Session stmp( argc, argv );
362 QApplication::setApplicationName( "salome" );
363 SUIT_ResourceMgr* resMgr = stmp.createResourceMgr( "SalomeApp" );
364 bool isCloc = resMgr->booleanValue( "language", "locale", true );
366 QLocale::setDefault( QLocale::c() );
369 QLocale::setDefault( QLocale::system() );
373 #if QT_VERSION > QT_VERSION_CHECK(5, 0, 0)
375 // RNV: setup the default format:
376 // QSurfaceFormat should be set before creation of QApplication,
377 // so to avoid conflicts beetween SALOME and ParaView QSurfaceFormats we should merge theirs formats
378 // (see comments below) and set the resultant format here.
380 // Settings from Paraview:
381 // This piece of code was taken from QVTKOpenGLWidget::defaultFormat() method in
382 // order to avoid dependency of the SALOME_Session_Server on vtk libraries
384 fmt.setRenderableType(QSurfaceFormat::OpenGL);
385 fmt.setVersion(3, 2);
386 fmt.setProfile(QSurfaceFormat::CoreProfile);
387 fmt.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
388 fmt.setRedBufferSize(1);
389 fmt.setGreenBufferSize(1);
390 fmt.setBlueBufferSize(1);
391 fmt.setDepthBufferSize(1);
392 fmt.setStencilBufferSize(0);
393 fmt.setAlphaBufferSize(1);
394 fmt.setStereo(false);
397 // Settings for OCCT viewer window:
398 fmt.setDepthBufferSize(16);
399 fmt.setStencilBufferSize(1);
400 // fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
402 QSurfaceFormat::setDefaultFormat(fmt);
406 // Create Qt application instance;
407 // this should be done the very first!
408 SALOME_QApplication _qappl( argc, argv );
409 _qappl.setOrganizationName( "salome" );
410 _qappl.setApplicationName( "salome" );
411 _qappl.setApplicationVersion( salomeVersion() );
413 // Add application library path (to search style plugin etc...)
414 QString path = QDir::toNativeSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
415 _qappl.addLibraryPath( path );
417 bool isGUI = isFound( "GUI", argc, argv );
418 bool isSplash = isFound( "SPLASH", argc, argv );
419 // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
420 // Note, that user preferences are not taken into account for splash settings -
421 // it is a property of the application!
422 QtxSplash* splash = 0;
423 if ( isGUI && isSplash ) {
424 // ...create resource manager
425 SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
426 resMgr.setCurrentFormat( "xml" );
427 resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
428 resMgr.loadLanguage( "LightApp" );
430 splash = QtxSplash::splash( QPixmap() );
431 splash->readSettings( &resMgr );
432 if ( splash->pixmap().isNull() )
433 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
434 if ( splash->pixmap().isNull() ) {
439 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
440 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
441 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
442 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
444 QApplication::instance()->processEvents();
453 PortableServer::POA_var poa;
455 SUIT_Session* aGUISession = 0;
456 SALOME_NamingService* _NS = 0;
457 GetInterfaceThread* guiThread = 0;
458 Session_ServerLauncher* myServerLauncher = 0;
461 // ...initialize Python (only once)
463 char* _argv[] = {(char*)""};
464 KERNEL_PYTHON::init_python( _argc,_argv );
466 // ...create ORB, get RootPOA object, NamingService, etc.
467 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
468 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
470 orb = init( orbArgc, argv );
472 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
473 poa = PortableServer::POA::_narrow( obj );
475 PortableServer::POAManager_var pman = poa->the_POAManager();
477 MESSAGE( "pman->activate()" );
479 _NS = new SALOME_NamingService( orb );
483 catch ( SALOME_Exception& e ) {
484 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
486 catch ( CORBA::SystemException& e ) {
487 INFOS( "Caught CORBA::SystemException." );
489 catch ( CORBA::Exception& e ) {
490 INFOS( "Caught CORBA::Exception." );
493 CORBA::TypeCode_var tc = tmp.type();
494 const char *p = tc->name();
495 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
497 catch ( std::exception& e ) {
498 INFOS( "run(): An exception has been caught: " <<e.what() );
501 INFOS( "Caught unknown exception." );
504 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
505 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
507 // lock session mutex to ensure that GetInterface is not called
508 // until all initialization is done
509 _SessionMutex.lock();
512 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
513 // ...lock mutex to block embedded servers launching thread until wait( mutex )
515 // ...create launcher
516 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
517 // ...block this thread until launcher is ready
518 _ServerLaunch.wait( &_GUIMutex );
520 // Start servers check thread (splash)
522 // ...lock mutex to block splash thread until wait( mutex )
524 // ...create servers checking thread
525 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
526 // ... set initial progress
527 splash->setProgress( 0, sc.totalSteps() );
530 int step = sc.currentStep();
531 int total = sc.totalSteps();
532 QString msg = sc.currentMessage();
533 QString err = sc.error();
534 if ( !err.isEmpty() ) {
535 QtxSplash::setError( err );
536 QApplication::instance()->processEvents();
540 QtxSplash::setStatus( msg, step );
541 QApplication::instance()->processEvents();
544 // ...block this thread until servers checking is finished
545 _SplashStarted.wait( &_SplashMutex );
547 // ...unlock mutex 'cause it is no more needed
548 _SplashMutex.unlock();
551 // Finalize embedded servers launcher
552 // ...block this thread until launcher is finished
553 _ServerLaunch.wait( &_GUIMutex );
554 // ...unlock mutex 'cause it is no more needed
558 // Obtain Session interface reference
559 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
560 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
562 bool shutdownAll = false;
563 bool shutdownSession = false;
565 // Launch GUI activator
568 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
569 // ...create GUI launcher
570 MESSAGE( "Session activated, Launch IAPP..." );
571 guiThread = new GetInterfaceThread( session );
575 // Allow multiple activation/deactivation of GUI
577 MESSAGE( "waiting wakeAll()" );
578 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
579 // atomic operation lock - unlock on mutex
580 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
581 // this thread wakes up, and lock mutex
583 _SessionMutex.unlock();
585 // Session might be shutdowning here, check status
586 SALOME::StatSession stat = session->GetStatSession();
587 shutdownSession = stat.state == SALOME::shutdown;
588 if ( shutdownSession ) {
589 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
593 // SUIT_Session creation
594 aGUISession = new SALOME_Session( argc, argv );
596 // Load SalomeApp dynamic library
597 MESSAGE( "creation SUIT_Application" );
598 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
601 #ifdef USE_SALOME_STYLE
602 Style_Salome::initialize( aGUIApp->resourceMgr() );
603 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
604 Style_Salome::apply();
605 #endif // USE_SALOME_STYLE
607 if ( !isFound( "noexcepthandler", argc, argv ) )
608 _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
609 // aGUISession contains SalomeApp_ExceptionHandler
611 MESSAGE( "run(): starting the main event loop" );
614 splash->finish( aGUIApp->desktop() );
616 result = _qappl.exec();
620 if ( result == SUIT_Session::NORMAL ) {
621 // desktop is explicitly closed by user from GUI
622 // exit flags says if it's necessary to shutdown all servers
623 // all session server only
624 shutdownAll = aGUISession->exitFlags();
627 // desktop might be closed from:
628 // - StopSesion() (temporarily) or
629 // - Shutdown() (permanently)
630 stat = session->GetStatSession();
631 shutdownSession = stat.state == SALOME::shutdown;
632 // normally "shutdown standalone servers" flag should be false here, if we come from
633 // StopSesion() or from Shutdown();
634 // but we also have to check if somebody explicitly programmatically closed session,
635 // asking to kill servers also
636 shutdownAll = aGUISession->exitFlags();
638 if ( shutdownAll || shutdownSession ) {
639 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
647 // Prepare _GUIMutex for a new GUI activation
648 _SessionMutex.lock();
652 // unlock Session mutex
653 _SessionMutex.unlock();
655 if ( myServerLauncher )
656 myServerLauncher->ShutdownAll(); // shutdown embedded servers
658 if ( shutdownAll ) // shutdown standalone servers
659 shutdownServers( _NS );
661 if ( myServerLauncher )
662 myServerLauncher->KillAll(); // kill embedded servers
664 // Unregister session server
665 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
666 if ( sessionServant )
667 sessionServant->NSunregister();
671 delete myServerLauncher;
678 //////////////////////////////////////////////////////////////
679 // VSR: silently skip exception:
680 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
681 // exception is raised when orb->destroy() is called and
682 // cpp continer is launched in the embedded mode
683 //////////////////////////////////////////////////////////////
684 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
687 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
690 //Destroy orb from python (for chasing memory leaks)
691 //PyRun_SimpleString("from omniORB import CORBA");
692 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
693 //PyRun_SimpleString("orb.destroy()");
697 //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
698 ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
700 init->explicit_destroy();
701 //std::cout << "@@@@@ ORB destroyed\n";
703 // After ORB destruction
704 if(Py_IsInitialized())
707 //std::cout << "@@@@@ About to PyFinalize\n";
709 //std::cout << "@@@@@ DONE PyFinalize\n";
714 //std::cout << "@@@@@ About to kill omni\n";
716 //std::cout << "@@@@@ DONE kill omni\n";
719 MESSAGE( "Salome_Session_Server:endofserver" );