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 #include <Style_Salome.h>
53 #include "GUI_version.h"
54 #include <SUIT_Tools.h>
55 #include <SUIT_Session.h>
56 #include <SUIT_Application.h>
57 #include <SUIT_Desktop.h>
58 #include <SUIT_ResourceMgr.h>
59 #include <SUIT_ExceptionHandler.h>
61 #include <SALOMEconfig.h>
62 #include CORBA_SERVER_HEADER(SALOME_Session)
63 #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 void MessageOutput( QtMsgType type, const char* msg )
102 #ifdef QT_DEBUG_MESSAGE
103 MESSAGE( "Debug: " << qPrintable( QString(msg) ) );
107 MESSAGE( "Warning: " << qPrintable( QString(msg) ) );
110 MESSAGE( "Fatal: " << qPrintable( QString(msg) ) );
115 QString salomeVersion()
117 return GUI_VERSION_STR;
120 class SALOME_ResourceMgr : public SUIT_ResourceMgr
123 SALOME_ResourceMgr( const QString& app, const QString& resVarTemplate ) : SUIT_ResourceMgr( app, resVarTemplate )
125 setCurrentFormat( "xml" );
126 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
128 static void initResourceMgr()
130 if ( myExtAppName.isNull() || myExtAppVersion.isNull() ) {
131 SALOME_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
132 resMgr.loadLanguage( "LightApp", "en" );
133 resMgr.loadLanguage( "SalomeApp", "en" );
135 myExtAppName = QObject::tr( "APP_NAME" ).trimmed();
136 if ( myExtAppName == "APP_NAME" || myExtAppName.toLower() == "salome" )
137 myExtAppName = "SalomeApp";
138 myExtAppVersion = QObject::tr( "APP_VERSION" );
139 if ( myExtAppVersion == "APP_VERSION" ) {
140 if ( myExtAppName != "SalomeApp" )
141 myExtAppVersion = "";
142 else myExtAppVersion = salomeVersion();
146 QString version() const { return myExtAppVersion; }
149 QString userFileName( const QString& appName, const bool for_load ) const
151 if ( version().isEmpty() ) return "";
152 return SUIT_ResourceMgr::userFileName( myExtAppName, for_load );
155 virtual long userFileId( const QString& _fname ) const
157 //////////////////////////////////////////////////////////////////////////////////////////////
158 // In SALOME and SALOME-based applications the user preferences file is named as
159 // - <AppName>.xml.<AppVersion> on Windows
160 // - <AppName>rc.<AppVersion> on Linux
162 // * AppName is application name, default SalomeApp (can be customized in SALOME-based
164 // * AppVersion is application version
166 // Since version 6.5.0 of SALOME, user file is situated in the ~/.config/salome
167 // directory. For backward compatibility, when user preferences from nearest
168 // version of application is searched, user home directory is also looked through,
169 // with lower priority.
171 // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
172 // symbol since it is situated in hidden ~/.config/salome directory. Files with dot
173 // prefix also though taken into account (with lower priority) for backward compatibility.
176 // - Currently the following format of version number is supported:
177 // <major>[.<minor>[.<release>[<type><dev>]]]
178 // Parts in square brackets are considered optional. Here:
179 // * major - major version id
180 // * minor - minor version id
181 // * release - maintenance version id
182 // * type - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
183 // or 'rc' to point release candidate (case-insensitive)
184 // * dev - dev version or patch number
185 // All numerical values must be of range [1-99].
186 // Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
188 // - Versioning approach can be customized by implementing and using own resource manager class,
189 // see QtxResurceMgr, SUIT_ResourceMgr classes.
190 //////////////////////////////////////////////////////////////////////////////////////////////
192 if ( !myExtAppName.isEmpty() ) {
194 // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
195 // - SalomeApp is an application name (can be customized)
196 // - xml is a file format (xml or ini)
197 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
198 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ).arg( currentFormat() ) );
200 // On Linux, user file name is something like SalomeApprc.6.5.0 where
201 // - SalomeApp is an application name (can be customized)
202 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
204 // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
205 // when it is stored in the ~/.config/<appname> directory;
206 // for backward compatibility we also check files prepended with "." with lower priority
207 QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ) );
209 QString fname = QFileInfo( _fname ).fileName();
210 if ( exp.exactMatch( fname ) ) {
211 long fid = Qtx::versionToId( exp.cap( 1 ) );
212 if ( fid > 0 ) id = fid;
219 static QString myExtAppName;
220 static QString myExtAppVersion;
223 QString SALOME_ResourceMgr::myExtAppName = QString();
224 QString SALOME_ResourceMgr::myExtAppVersion = QString();
226 class SALOME_Session : public SUIT_Session
229 SALOME_Session( int argc, char** argv ) : SUIT_Session( argc, argv ) {}
230 virtual ~SALOME_Session() {}
233 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
235 SALOME_ResourceMgr::initResourceMgr();
236 SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
241 class SALOME_QApplication : public QApplication
244 SALOME_QApplication( int& argc, char** argv )
246 // san: Opening an X display and choosing a visual most suitable for 3D visualization
247 // in order to make SALOME viewers work with non-native X servers
248 : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
250 : QApplication( argc, argv ),
254 virtual bool notify( QObject* receiver, QEvent* e )
258 return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
260 catch (std::exception& e) {
261 std::cerr << e.what() << std::endl;
263 catch (CORBA::Exception& e) {
264 std::cerr << "Caught CORBA::Exception" << std::endl;
267 CORBA::TypeCode_var tc = tmp.type();
268 const char *p = tc->name();
269 std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
272 std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
274 return false; // return false when exception is caught
276 SUIT_ExceptionHandler* handler() const { return myHandler; }
277 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
280 SUIT_ExceptionHandler* myHandler;
283 // class which calls SALOME::Session::GetInterface() from another thread
284 // to avoid mutual lock ( if called from the same thread as main()
285 class GetInterfaceThread : public QThread
288 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
295 if ( !CORBA::is_nil( session ) )
296 session->GetInterface();
298 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
301 SALOME::Session_var session;
304 // returns true if 'str' is found in argv
305 bool isFound( const char* str, int argc, char** argv )
307 for ( int i = 1; i <= ( argc-1 ); i++ )
308 if ( !strcmp( argv[i], str ) )
315 SALOME_LifeCycleCORBA::killOmniNames();
318 // shutdown standalone servers
319 void shutdownServers( SALOME_NamingService* theNS )
321 SALOME_LifeCycleCORBA lcc(theNS);
322 lcc.shutdownServers();
325 // ---------------------------- MAIN -----------------------
326 int main( int argc, char **argv )
328 // Install Qt debug messages handler
329 qInstallMsgHandler( MessageOutput );
331 //Set a "native" graphic system in case if application runs on the remote host
332 QString remote(getenv("REMOTEHOST"));
333 QString client(getenv("SSH_CLIENT"));
334 if(remote.length() > 0 || client.length() > 0 ) {
335 QApplication::setGraphicsSystem(QLatin1String("native"));
338 // add <qtdir>/plugins dir to the pluins search path for image plugins
339 QString qtdir = Qtx::qtDir( "plugins" );
340 if ( !qtdir.isEmpty() )
341 QApplication::addLibraryPath( qtdir );
343 // set "C" locale if requested via preferences
345 SALOME_Session stmp( argc, argv );
346 QApplication::setApplicationName( "salome" );
347 SUIT_ResourceMgr* resMgr = stmp.createResourceMgr( "SalomeApp" );
348 bool isCloc = resMgr->booleanValue( "language", "locale", true );
350 QLocale::setDefault( QLocale::c() );
353 QLocale::setDefault( QLocale::system() );
357 // Create Qt application instance;
358 // this should be done the very first!
359 SALOME_QApplication _qappl( argc, argv );
360 _qappl.setOrganizationName( "salome" );
361 _qappl.setApplicationName( "salome" );
362 _qappl.setApplicationVersion( salomeVersion() );
364 // Add application library path (to search style plugin etc...)
365 QString path = QDir::toNativeSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
366 _qappl.addLibraryPath( path );
368 bool isGUI = isFound( "GUI", argc, argv );
369 bool isSplash = isFound( "SPLASH", argc, argv );
370 // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
371 // Note, that user preferences are not taken into account for splash settings -
372 // it is a property of the application!
373 QtxSplash* splash = 0;
374 if ( isGUI && isSplash ) {
375 // ...create resource manager
376 SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
377 resMgr.setCurrentFormat( "xml" );
378 resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
379 resMgr.loadLanguage( "LightApp" );
381 splash = QtxSplash::splash( QPixmap() );
382 splash->readSettings( &resMgr );
383 if ( splash->pixmap().isNull() )
384 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
385 if ( splash->pixmap().isNull() ) {
390 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
391 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
392 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
393 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
395 QApplication::instance()->processEvents();
404 PortableServer::POA_var poa;
406 SUIT_Session* aGUISession = 0;
407 SALOME_NamingService* _NS = 0;
408 GetInterfaceThread* guiThread = 0;
409 Session_ServerLauncher* myServerLauncher = 0;
412 // ...initialize Python (only once)
414 char* _argv[] = {(char*)""};
415 KERNEL_PYTHON::init_python( _argc,_argv );
417 // ...create ORB, get RootPOA object, NamingService, etc.
418 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
419 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
421 orb = init( orbArgc, argv );
423 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
424 poa = PortableServer::POA::_narrow( obj );
426 PortableServer::POAManager_var pman = poa->the_POAManager();
428 MESSAGE( "pman->activate()" );
430 _NS = new SALOME_NamingService( orb );
434 catch ( SALOME_Exception& e ) {
435 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
437 catch ( CORBA::SystemException& e ) {
438 INFOS( "Caught CORBA::SystemException." );
440 catch ( CORBA::Exception& e ) {
441 INFOS( "Caught CORBA::Exception." );
444 CORBA::TypeCode_var tc = tmp.type();
445 const char *p = tc->name();
446 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
448 catch ( std::exception& e ) {
449 INFOS( "run(): An exception has been caught: " <<e.what() );
452 INFOS( "Caught unknown exception." );
455 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
456 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
458 // lock session mutex to ensure that GetInterface is not called
459 // until all initialization is done
460 _SessionMutex.lock();
463 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
464 // ...lock mutex to block embedded servers launching thread until wait( mutex )
466 // ...create launcher
467 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
468 // ...block this thread until launcher is ready
469 _ServerLaunch.wait( &_GUIMutex );
471 // Start servers check thread (splash)
473 // ...lock mutex to block splash thread until wait( mutex )
475 // ...create servers checking thread
476 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
477 // ... set initial progress
478 splash->setProgress( 0, sc.totalSteps() );
481 int step = sc.currentStep();
482 int total = sc.totalSteps();
483 QString msg = sc.currentMessage();
484 QString err = sc.error();
485 if ( !err.isEmpty() ) {
486 QtxSplash::setError( err );
487 QApplication::instance()->processEvents();
491 QtxSplash::setStatus( msg, step );
492 QApplication::instance()->processEvents();
495 // ...block this thread until servers checking is finished
496 _SplashStarted.wait( &_SplashMutex );
498 // ...unlock mutex 'cause it is no more needed
499 _SplashMutex.unlock();
502 // Finalize embedded servers launcher
503 // ...block this thread until launcher is finished
504 _ServerLaunch.wait( &_GUIMutex );
505 // ...unlock mutex 'cause it is no more needed
509 // Obtain Session interface reference
510 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
511 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
513 bool shutdownAll = false;
514 bool shutdownSession = false;
516 // Launch GUI activator
519 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
520 // ...create GUI launcher
521 MESSAGE( "Session activated, Launch IAPP..." );
522 guiThread = new GetInterfaceThread( session );
526 // Allow multiple activation/deactivation of GUI
528 MESSAGE( "waiting wakeAll()" );
529 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
530 // atomic operation lock - unlock on mutex
531 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
532 // this thread wakes up, and lock mutex
534 _SessionMutex.unlock();
536 // Session might be shutdowning here, check status
537 SALOME::StatSession stat = session->GetStatSession();
538 shutdownSession = stat.state == SALOME::shutdown;
539 if ( shutdownSession ) {
540 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
544 // SUIT_Session creation
545 aGUISession = new SALOME_Session( argc, argv );
547 // Load SalomeApp dynamic library
548 MESSAGE( "creation SUIT_Application" );
549 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
552 Style_Salome::initialize( aGUIApp->resourceMgr() );
553 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
554 Style_Salome::apply();
556 if ( !isFound( "noexcepthandler", argc, argv ) )
557 _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
558 // aGUISession contains SalomeApp_ExceptionHandler
560 MESSAGE( "run(): starting the main event loop" );
563 splash->finish( aGUIApp->desktop() );
565 result = _qappl.exec();
569 if ( result == SUIT_Session::NORMAL ) {
570 // desktop is explicitly closed by user from GUI
571 // exit flags says if it's necessary to shutdown all servers
572 // all session server only
573 shutdownAll = aGUISession->exitFlags();
576 // desktop might be closed from:
577 // - StopSesion() /temporarily/ or
578 // - Shutdown() /permanently/
579 stat = session->GetStatSession();
580 shutdownSession = stat.state == SALOME::shutdown;
582 if ( shutdownAll || shutdownSession ) {
583 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
591 // Prepare _GUIMutex for a new GUI activation
592 _SessionMutex.lock();
596 // unlock Session mutex
597 _SessionMutex.unlock();
599 if ( myServerLauncher )
600 myServerLauncher->ShutdownAll(); // shutdown embedded servers
602 if ( shutdownAll ) // shutdown standalone servers
603 shutdownServers( _NS );
605 if ( myServerLauncher )
606 myServerLauncher->KillAll(); // kill embedded servers
608 // Unregister session server
609 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
610 if ( sessionServant )
611 sessionServant->NSunregister();
615 delete myServerLauncher;
622 //////////////////////////////////////////////////////////////
623 // VSR: silently skip exception:
624 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
625 // exception is raised when orb->destroy() is called and
626 // cpp continer is launched in the embedded mode
627 //////////////////////////////////////////////////////////////
628 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
631 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
634 //Destroy orb from python (for chasing memory leaks)
635 //PyRun_SimpleString("from omniORB import CORBA");
636 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
637 //PyRun_SimpleString("orb.destroy()");
641 //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
642 ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
644 init->explicit_destroy();
645 //std::cout << "@@@@@ ORB destroyed\n";
647 // After ORB destruction
648 if(Py_IsInitialized())
651 //std::cout << "@@@@@ About to PyFinalize\n";
653 //std::cout << "@@@@@ DONE PyFinalize\n";
658 //std::cout << "@@@@@ About to kill omni\n";
660 //std::cout << "@@@@@ DONE kill omni\n";
663 MESSAGE( "Salome_Session_Server:endofserver" );