1 // Copyright (C) 2007-2014 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 <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)
79 #include <QApplication>
81 #include <QWaitCondition>
83 #include <QTextStream>
85 /*! - read arguments, define list of server to launch with their arguments.
86 * - wait for naming service
87 * - create and run a thread for launch of all servers
91 //! CORBA server for SALOME Session
93 * SALOME_Session Server launches a SALOME session servant.
94 * The servant registers to the Naming Service.
95 * See SALOME_Session.idl for interface specification.
97 * Main services offered by the servant are:
99 * - stop Session ( must be idle )
100 * - get session state
103 void MessageOutput( QtMsgType type, const char* msg )
108 //MESSAGE( "Debug: " << msg );
111 MESSAGE( "Warning: " << msg );
114 MESSAGE( "Fatal: " << msg );
119 QString salomeVersion()
121 return GUI_VERSION_STR;
124 class SALOME_ResourceMgr : public SUIT_ResourceMgr
127 SALOME_ResourceMgr( const QString& app, const QString& resVarTemplate ) : SUIT_ResourceMgr( app, resVarTemplate )
129 setCurrentFormat( "xml" );
130 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
132 static void initResourceMgr()
134 if ( myExtAppName.isNull() || myExtAppVersion.isNull() ) {
135 SALOME_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
136 resMgr.loadLanguage( "LightApp", "en" );
137 resMgr.loadLanguage( "SalomeApp", "en" );
139 myExtAppName = QObject::tr( "APP_NAME" ).trimmed();
140 if ( myExtAppName == "APP_NAME" || myExtAppName.toLower() == "salome" )
141 myExtAppName = "SalomeApp";
142 myExtAppVersion = QObject::tr( "APP_VERSION" );
143 if ( myExtAppVersion == "APP_VERSION" ) {
144 if ( myExtAppName != "SalomeApp" )
145 myExtAppVersion = "";
146 else myExtAppVersion = salomeVersion();
150 QString version() const { return myExtAppVersion; }
153 QString userFileName( const QString& appName, const bool for_load ) const
155 if ( version().isEmpty() ) return "";
156 return SUIT_ResourceMgr::userFileName( myExtAppName, for_load );
159 virtual long userFileId( const QString& _fname ) const
161 //////////////////////////////////////////////////////////////////////////////////////////////
162 // In SALOME and SALOME-based applications the user preferences file is named as
163 // - <AppName>.xml.<AppVersion> on Windows
164 // - <AppName>rc.<AppVersion> on Linux
166 // * AppName is application name, default SalomeApp (can be customized in SALOME-based
168 // * AppVersion is application version
170 // Since version 6.5.0 of SALOME, user file is situated in the ~/.config/salome
171 // directory. For backward compatibility, when user preferences from nearest
172 // version of application is searched, user home directory is also looked through,
173 // with lower priority.
175 // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
176 // symbol since it is situated in hidden ~/.config/salome directory. Files with dot
177 // prefix also though taken into account (with lower priority) for backward compatibility.
180 // - Currently the following format of version number is supported:
181 // <major>[.<minor>[.<release>[<type><dev>]]]
182 // Parts in square brackets are considered optional. Here:
183 // * major - major version id
184 // * minor - minor version id
185 // * release - maintenance version id
186 // * type - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
187 // or 'rc' to point release candidate (case-insensitive)
188 // * dev - dev version or patch number
189 // All numerical values must be of range [1-99].
190 // Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
192 // - Versioning approach can be customized by implementing and using own resource manager class,
193 // see QtxResurceMgr, SUIT_ResourceMgr classes.
194 //////////////////////////////////////////////////////////////////////////////////////////////
196 if ( !myExtAppName.isEmpty() ) {
198 // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
199 // - SalomeApp is an application name (can be customized)
200 // - xml is a file format (xml or ini)
201 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
202 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ).arg( currentFormat() ) );
204 // On Linux, user file name is something like SalomeApprc.6.5.0 where
205 // - SalomeApp is an application name (can be customized)
206 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
208 // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
209 // when it is stored in the ~/.config/<appname> directory;
210 // for backward compatibility we also check files prepended with "." with lower priority
211 QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myExtAppName ) );
213 QString fname = QFileInfo( _fname ).fileName();
214 if ( exp.exactMatch( fname ) ) {
215 long fid = Qtx::versionToId( exp.cap( 1 ) );
216 if ( fid > 0 ) id = fid;
223 static QString myExtAppName;
224 static QString myExtAppVersion;
227 QString SALOME_ResourceMgr::myExtAppName = QString();
228 QString SALOME_ResourceMgr::myExtAppVersion = QString();
230 class SALOME_Session : public SUIT_Session
233 SALOME_Session() : SUIT_Session() {}
234 virtual ~SALOME_Session() {}
237 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
239 SALOME_ResourceMgr::initResourceMgr();
240 SALOME_ResourceMgr* resMgr = new SALOME_ResourceMgr( appName, QString( "%1Config" ) );
245 #ifdef ENABLE_TESTRECORDER
246 class SALOME_QApplication : public TestApplication
248 class SALOME_QApplication : public QApplication
252 #ifdef ENABLE_TESTRECORDER
253 SALOME_QApplication( int& argc, char** argv ) : TestApplication( argc, argv ), myHandler ( 0 ) {}
255 SALOME_QApplication( int& argc, char** argv )
257 // san: Opening an X display and choosing a visual most suitable for 3D visualization
258 // in order to make SALOME viewers work with non-native X servers
259 : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
261 : QApplication( argc, argv ),
266 virtual bool notify( QObject* receiver, QEvent* e )
269 #ifdef ENABLE_TESTRECORDER
270 return myHandler ? myHandler->handle( receiver, e ) :
271 TestApplication::notify( receiver, 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
293 SUIT_ExceptionHandler* handler() const { return myHandler; }
294 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
297 SUIT_ExceptionHandler* myHandler;
300 // class which calls SALOME::Session::GetInterface() from another thread
301 // to avoid mutual lock ( if called from the same thread as main()
302 class GetInterfaceThread : public QThread
305 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
312 if ( !CORBA::is_nil( session ) )
313 session->GetInterface();
315 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
318 SALOME::Session_var session;
321 // returns true if 'str' is found in argv
322 bool isFound( const char* str, int argc, char** argv )
324 for ( int i = 1; i <= ( argc-1 ); i++ )
325 if ( !strcmp( argv[i], str ) )
332 SALOME_LifeCycleCORBA::killOmniNames();
335 // shutdown standalone servers
336 void shutdownServers( SALOME_NamingService* theNS )
338 SALOME_LifeCycleCORBA lcc(theNS);
339 lcc.shutdownServers();
342 // ---------------------------- MAIN -----------------------
343 int main( int argc, char **argv )
345 // Install Qt debug messages handler
346 qInstallMsgHandler( MessageOutput );
348 //Set a "native" graphic system in case if application runs on the remote host
349 QString remote(getenv("REMOTEHOST"));
350 QString client(getenv("SSH_CLIENT"));
351 if(remote.length() > 0 || client.length() > 0 ) {
352 QApplication::setGraphicsSystem(QLatin1String("native"));
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" ) );
362 QApplication::setApplicationName( "salome" );
363 SUIT_ResourceMgr* resMgr = s.createResourceMgr( "SalomeApp" );
364 bool isCloc = resMgr->booleanValue( "language", "locale", true );
366 QLocale::setDefault( QLocale::c() );
369 QLocale::setDefault( QLocale::system() );
373 // Create Qt application instance;
374 // this should be done the very first!
375 SALOME_QApplication _qappl( argc, argv );
376 _qappl.setOrganizationName( "salome" );
377 _qappl.setApplicationName( "salome" );
378 _qappl.setApplicationVersion( salomeVersion() );
380 // Add application library path (to search style plugin etc...)
381 QString path = QDir::convertSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
382 _qappl.addLibraryPath( path );
384 bool isGUI = isFound( "GUI", argc, argv );
385 bool isSplash = isFound( "SPLASH", argc, argv );
386 // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
387 // Note, that user preferences are not taken into account for splash settings -
388 // it is a property of the application!
389 QtxSplash* splash = 0;
390 if ( isGUI && isSplash ) {
391 // ...create resource manager
392 SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
393 resMgr.setCurrentFormat( "xml" );
394 resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
395 resMgr.loadLanguage( "LightApp" );
397 splash = QtxSplash::splash( QPixmap() );
398 splash->readSettings( &resMgr );
399 if ( splash->pixmap().isNull() )
400 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
401 if ( splash->pixmap().isNull() ) {
406 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
407 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
408 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
409 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
411 QApplication::instance()->processEvents();
420 PortableServer::POA_var poa;
422 SUIT_Session* aGUISession = 0;
423 SALOME_NamingService* _NS = 0;
424 GetInterfaceThread* guiThread = 0;
425 Session_ServerLauncher* myServerLauncher = 0;
428 // ...initialize Python (only once)
430 char* _argv[] = {(char*)""};
431 KERNEL_PYTHON::init_python( _argc,_argv );
433 // ...create ORB, get RootPOA object, NamingService, etc.
434 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
435 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
437 orb = init( orbArgc, argv );
439 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
440 poa = PortableServer::POA::_narrow( obj );
442 PortableServer::POAManager_var pman = poa->the_POAManager();
444 MESSAGE( "pman->activate()" );
446 _NS = new SALOME_NamingService( orb );
450 catch ( SALOME_Exception& e ) {
451 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
453 catch ( CORBA::SystemException& e ) {
454 INFOS( "Caught CORBA::SystemException." );
456 catch ( CORBA::Exception& e ) {
457 INFOS( "Caught CORBA::Exception." );
460 CORBA::TypeCode_var tc = tmp.type();
461 const char *p = tc->name();
462 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
464 catch ( std::exception& e ) {
465 INFOS( "run(): An exception has been caught: " <<e.what() );
468 INFOS( "Caught unknown exception." );
471 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
472 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
474 // lock session mutex to ensure that GetInterface is not called
475 // until all initialization is done
476 _SessionMutex.lock();
479 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
480 // ...lock mutex to block embedded servers launching thread until wait( mutex )
482 // ...create launcher
483 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
484 // ...block this thread until launcher is ready
485 _ServerLaunch.wait( &_GUIMutex );
487 // Start servers check thread (splash)
489 // ...lock mutex to block splash thread until wait( mutex )
491 // ...create servers checking thread
492 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
493 // ... set initial progress
494 splash->setProgress( 0, sc.totalSteps() );
497 int step = sc.currentStep();
498 int total = sc.totalSteps();
499 QString msg = sc.currentMessage();
500 QString err = sc.error();
501 if ( !err.isEmpty() ) {
502 QtxSplash::setError( err );
503 QApplication::instance()->processEvents();
507 QtxSplash::setStatus( msg, step );
508 QApplication::instance()->processEvents();
511 // ...block this thread until servers checking is finished
512 _SplashStarted.wait( &_SplashMutex );
514 // ...unlock mutex 'cause it is no more needed
515 _SplashMutex.unlock();
518 // Finalize embedded servers launcher
519 // ...block this thread until launcher is finished
520 _ServerLaunch.wait( &_GUIMutex );
521 // ...unlock mutex 'cause it is no more needed
525 // Obtain Session interface reference
526 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
527 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
529 bool shutdownAll = false;
530 bool shutdownSession = false;
532 // Launch GUI activator
535 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
536 // ...create GUI launcher
537 MESSAGE( "Session activated, Launch IAPP..." );
538 guiThread = new GetInterfaceThread( session );
542 // Allow multiple activation/deactivation of GUI
544 MESSAGE( "waiting wakeAll()" );
545 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
546 // atomic operation lock - unlock on mutex
547 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
548 // this thread wakes up, and lock mutex
550 _SessionMutex.unlock();
552 // Session might be shutdowning here, check status
553 SALOME::StatSession stat = session->GetStatSession();
554 shutdownSession = stat.state == SALOME::shutdown;
555 if ( shutdownSession ) {
556 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
560 // SUIT_Session creation
561 aGUISession = new SALOME_Session();
563 // Load SalomeApp dynamic library
564 MESSAGE( "creation SUIT_Application" );
565 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
568 Style_Salome::initialize( aGUIApp->resourceMgr() );
569 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
570 Style_Salome::apply();
572 if ( !isFound( "noexcepthandler", argc, argv ) )
573 _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
574 // aGUISession contains SalomeApp_ExceptionHandler
576 MESSAGE( "run(): starting the main event loop" );
579 splash->finish( aGUIApp->desktop() );
581 result = _qappl.exec();
585 if ( result == SUIT_Session::NORMAL ) {
586 // desktop is explicitly closed by user from GUI
587 // exit flags says if it's necessary to shutdown all servers
588 // all session server only
589 shutdownAll = aGUISession->exitFlags();
592 // desktop might be closed from:
593 // - StopSesion() /temporarily/ or
594 // - Shutdown() /permanently/
595 stat = session->GetStatSession();
596 shutdownSession = stat.state == SALOME::shutdown;
598 if ( shutdownAll || shutdownSession ) {
599 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
607 // Prepare _GUIMutex for a new GUI activation
608 _SessionMutex.lock();
612 // unlock Session mutex
613 _SessionMutex.unlock();
615 if ( myServerLauncher )
616 myServerLauncher->ShutdownAll(); // shutdown embedded servers
618 if ( shutdownAll ) // shutdown standalone servers
619 shutdownServers( _NS );
621 if ( myServerLauncher )
622 myServerLauncher->KillAll(); // kill embedded servers
624 // Unregister session server
625 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
626 if ( sessionServant )
627 sessionServant->NSunregister();
631 delete myServerLauncher;
638 //////////////////////////////////////////////////////////////
639 // VSR: silently skip exception:
640 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
641 // exception is raised when orb->destroy() is called and
642 // cpp continer is launched in the embedded mode
643 //////////////////////////////////////////////////////////////
644 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
647 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
650 //Destroy orb from python (for chasing memory leaks)
651 //PyRun_SimpleString("from omniORB import CORBA");
652 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
653 //PyRun_SimpleString("orb.destroy()");
657 //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
658 ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
660 init->explicit_destroy();
661 //std::cout << "@@@@@ ORB destroyed\n";
663 // After ORB destruction
664 if(Py_IsInitialized())
667 //std::cout << "@@@@@ About to PyFinalize\n";
669 //std::cout << "@@@@@ DONE PyFinalize\n";
674 //std::cout << "@@@@@ About to kill omni\n";
676 //std::cout << "@@@@@ DONE kill omni\n";
679 MESSAGE( "Salome_Session_Server:endofserver" );