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)
75 #include <QApplication>
77 #include <QWaitCondition>
79 #include <QTextStream>
81 /*! - read arguments, define list of server to launch with their arguments.
82 * - wait for naming service
83 * - create and run a thread for launch of all servers
87 //! CORBA server for SALOME Session
89 * SALOME_Session Server launches a SALOME session servant.
90 * The servant registers to the Naming Service.
91 * See SALOME_Session.idl for interface specification.
93 * Main services offered by the servant are:
95 * - stop Session ( must be idle )
99 void MessageOutput( QtMsgType type, const char* msg )
104 //MESSAGE( "Debug: " << msg );
107 MESSAGE( "Warning: " << msg );
110 MESSAGE( "Fatal: " << 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() : SUIT_Session() {}
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 #ifdef ENABLE_TESTRECORDER
242 class SALOME_QApplication : public TestApplication
244 class SALOME_QApplication : public QApplication
248 #ifdef ENABLE_TESTRECORDER
249 SALOME_QApplication( int& argc, char** argv ) : TestApplication( argc, argv ), myHandler ( 0 ) {}
251 SALOME_QApplication( int& argc, char** argv )
253 // san: Opening an X display and choosing a visual most suitable for 3D visualization
254 // in order to make SALOME viewers work with non-native X servers
255 : QApplication( (Display*)Qtx::getDisplay(), argc, argv, Qtx::getVisual() ),
257 : QApplication( argc, argv ),
262 virtual bool notify( QObject* receiver, QEvent* e )
265 #ifdef ENABLE_TESTRECORDER
266 return myHandler ? myHandler->handle( receiver, e ) :
267 TestApplication::notify( receiver, e );
270 return myHandler ? myHandler->handle( receiver, e ) : QApplication::notify( receiver, e );
272 catch (std::exception& e) {
273 std::cerr << e.what() << std::endl;
275 catch (CORBA::Exception& e) {
276 std::cerr << "Caught CORBA::Exception" << std::endl;
279 CORBA::TypeCode_var tc = tmp.type();
280 const char *p = tc->name();
281 std::cerr << "notify(): CORBA exception of the kind : " << p << " is caught" << std::endl;
284 std::cerr << "Unknown exception caught in Qt handler: it's probably a bug in SALOME platform" << std::endl;
286 return false; // return false when exception is caught
289 SUIT_ExceptionHandler* handler() const { return myHandler; }
290 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
293 SUIT_ExceptionHandler* myHandler;
296 // class which calls SALOME::Session::GetInterface() from another thread
297 // to avoid mutual lock ( if called from the same thread as main()
298 class GetInterfaceThread : public QThread
301 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
308 if ( !CORBA::is_nil( session ) )
309 session->GetInterface();
311 printf( "\nFATAL ERROR: SALOME::Session object is nil! Can not display GUI\n\n" );
314 SALOME::Session_var session;
317 // returns true if 'str' is found in argv
318 bool isFound( const char* str, int argc, char** argv )
320 for ( int i = 1; i <= ( argc-1 ); i++ )
321 if ( !strcmp( argv[i], str ) )
328 SALOME_LifeCycleCORBA::killOmniNames();
331 // shutdown standalone servers
332 void shutdownServers( SALOME_NamingService* theNS )
334 SALOME_LifeCycleCORBA lcc(theNS);
335 lcc.shutdownServers();
338 // ---------------------------- MAIN -----------------------
339 int main( int argc, char **argv )
341 // Install Qt debug messages handler
342 qInstallMsgHandler( MessageOutput );
344 //Set a "native" graphic system in case if application runs on the remote host
345 QString remote(getenv("REMOTEHOST"));
346 QString client(getenv("SSH_CLIENT"));
347 if(remote.length() > 0 || client.length() > 0 ) {
348 QApplication::setGraphicsSystem(QLatin1String("native"));
351 // add $QTDIR/plugins to the pluins search path for image plugins
352 QString qtdir( ::getenv( "QTDIR" ) );
353 if ( !qtdir.isEmpty() )
354 QApplication::addLibraryPath( QDir( qtdir ).absoluteFilePath( "plugins" ) );
358 QApplication::setApplicationName( "salome" );
359 SUIT_ResourceMgr* resMgr = s.createResourceMgr( "SalomeApp" );
360 bool isCloc = resMgr->booleanValue( "language", "locale", true );
362 QLocale::setDefault( QLocale::c() );
365 QLocale::setDefault( QLocale::system() );
369 // Create Qt application instance;
370 // this should be done the very first!
371 SALOME_QApplication _qappl( argc, argv );
372 _qappl.setOrganizationName( "salome" );
373 _qappl.setApplicationName( "salome" );
374 _qappl.setApplicationVersion( salomeVersion() );
376 // Add application library path (to search style plugin etc...)
377 QString path = QDir::convertSeparators( SUIT_Tools::addSlash( QString( ::getenv( "GUI_ROOT_DIR" ) ) ) + QString( "bin/salome" ) );
378 _qappl.addLibraryPath( path );
380 bool isGUI = isFound( "GUI", argc, argv );
381 bool isSplash = isFound( "SPLASH", argc, argv );
382 // Show splash screen (only if both the "GUI" and "SPLASH" parameters are set)
383 // Note, that user preferences are not taken into account for splash settings -
384 // it is a property of the application!
385 QtxSplash* splash = 0;
386 if ( isGUI && isSplash ) {
387 // ...create resource manager
388 SUIT_ResourceMgr resMgr( "SalomeApp", QString( "%1Config" ) );
389 resMgr.setCurrentFormat( "xml" );
390 resMgr.setWorkingMode( QtxResourceMgr::IgnoreUserValues );
391 resMgr.loadLanguage( "LightApp" );
393 splash = QtxSplash::splash( QPixmap() );
394 splash->readSettings( &resMgr );
395 if ( splash->pixmap().isNull() )
396 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
397 if ( splash->pixmap().isNull() ) {
402 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
403 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( salomeVersion() ) );
404 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
405 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
407 QApplication::instance()->processEvents();
416 PortableServer::POA_var poa;
418 SUIT_Session* aGUISession = 0;
419 SALOME_NamingService* _NS = 0;
420 GetInterfaceThread* guiThread = 0;
421 Session_ServerLauncher* myServerLauncher = 0;
424 // ...initialize Python (only once)
426 char* _argv[] = {(char*)""};
427 KERNEL_PYTHON::init_python( _argc,_argv );
429 // ...create ORB, get RootPOA object, NamingService, etc.
430 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
431 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
433 orb = init( orbArgc, argv );
435 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
436 poa = PortableServer::POA::_narrow( obj );
438 PortableServer::POAManager_var pman = poa->the_POAManager();
440 MESSAGE( "pman->activate()" );
442 _NS = new SALOME_NamingService( orb );
446 catch ( SALOME_Exception& e ) {
447 INFOS( "run(): SALOME::SALOME_Exception is caught: "<<e.what() );
449 catch ( CORBA::SystemException& e ) {
450 INFOS( "Caught CORBA::SystemException." );
452 catch ( CORBA::Exception& e ) {
453 INFOS( "Caught CORBA::Exception." );
456 CORBA::TypeCode_var tc = tmp.type();
457 const char *p = tc->name();
458 INFOS ( "run(): CORBA exception of the kind : "<<p<< " is caught" );
460 catch ( std::exception& e ) {
461 INFOS( "run(): An exception has been caught: " <<e.what() );
464 INFOS( "Caught unknown exception." );
467 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
468 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
470 // lock session mutex to ensure that GetInterface is not called
471 // until all initialization is done
472 _SessionMutex.lock();
475 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
476 // ...lock mutex to block embedded servers launching thread until wait( mutex )
478 // ...create launcher
479 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
480 // ...block this thread until launcher is ready
481 _ServerLaunch.wait( &_GUIMutex );
483 // Start servers check thread (splash)
485 // ...lock mutex to block splash thread until wait( mutex )
487 // ...create servers checking thread
488 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
489 // ... set initial progress
490 splash->setProgress( 0, sc.totalSteps() );
493 int step = sc.currentStep();
494 int total = sc.totalSteps();
495 QString msg = sc.currentMessage();
496 QString err = sc.error();
497 if ( !err.isEmpty() ) {
498 QtxSplash::setError( err );
499 QApplication::instance()->processEvents();
503 QtxSplash::setStatus( msg, step );
504 QApplication::instance()->processEvents();
507 // ...block this thread until servers checking is finished
508 _SplashStarted.wait( &_SplashMutex );
510 // ...unlock mutex 'cause it is no more needed
511 _SplashMutex.unlock();
514 // Finalize embedded servers launcher
515 // ...block this thread until launcher is finished
516 _ServerLaunch.wait( &_GUIMutex );
517 // ...unlock mutex 'cause it is no more needed
521 // Obtain Session interface reference
522 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
523 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
525 bool shutdownAll = false;
526 bool shutdownSession = false;
528 // Launch GUI activator
531 splash->setStatus( QApplication::translate( "", "Activating desktop..." ) );
532 // ...create GUI launcher
533 MESSAGE( "Session activated, Launch IAPP..." );
534 guiThread = new GetInterfaceThread( session );
538 // Allow multiple activation/deactivation of GUI
540 MESSAGE( "waiting wakeAll()" );
541 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
542 // atomic operation lock - unlock on mutex
543 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
544 // this thread wakes up, and lock mutex
546 _SessionMutex.unlock();
548 // Session might be shutdowning here, check status
549 SALOME::StatSession stat = session->GetStatSession();
550 shutdownSession = stat.state == SALOME::shutdown;
551 if ( shutdownSession ) {
552 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
556 // SUIT_Session creation
557 aGUISession = new SALOME_Session();
559 // Load SalomeApp dynamic library
560 MESSAGE( "creation SUIT_Application" );
561 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
564 Style_Salome::initialize( aGUIApp->resourceMgr() );
565 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
566 Style_Salome::apply();
568 if ( !isFound( "noexcepthandler", argc, argv ) )
569 _qappl.setHandler( aGUISession->handler() ); // after loading SalomeApp application
570 // aGUISession contains SalomeApp_ExceptionHandler
572 MESSAGE( "run(): starting the main event loop" );
575 splash->finish( aGUIApp->desktop() );
577 result = _qappl.exec();
581 if ( result == SUIT_Session::NORMAL ) {
582 // desktop is explicitly closed by user from GUI
583 // exit flags says if it's necessary to shutdown all servers
584 // all session server only
585 shutdownAll = aGUISession->exitFlags();
588 // desktop might be closed from:
589 // - StopSesion() /temporarily/ or
590 // - Shutdown() /permanently/
591 stat = session->GetStatSession();
592 shutdownSession = stat.state == SALOME::shutdown;
594 if ( shutdownAll || shutdownSession ) {
595 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
603 // Prepare _GUIMutex for a new GUI activation
604 _SessionMutex.lock();
608 // unlock Session mutex
609 _SessionMutex.unlock();
611 if ( myServerLauncher )
612 myServerLauncher->ShutdownAll(); // shutdown embedded servers
614 if ( shutdownAll ) // shutdown standalone servers
615 shutdownServers( _NS );
617 if ( myServerLauncher )
618 myServerLauncher->KillAll(); // kill embedded servers
620 // Unregister session server
621 SALOME_Session_i* sessionServant = dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
622 if ( sessionServant )
623 sessionServant->NSunregister();
627 delete myServerLauncher;
634 //////////////////////////////////////////////////////////////
635 // VSR: silently skip exception:
636 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
637 // exception is raised when orb->destroy() is called and
638 // cpp continer is launched in the embedded mode
639 //////////////////////////////////////////////////////////////
640 // std::cerr << "Caught unexpected exception on shutdown : ignored !!" << std::endl;
643 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
646 //Destroy orb from python (for chasing memory leaks)
647 //PyRun_SimpleString("from omniORB import CORBA");
648 //PyRun_SimpleString("orb=CORBA.ORB_init([''], CORBA.ORB_ID)");
649 //PyRun_SimpleString("orb.destroy()");
653 //std::cout << "@@@@@ Explicitely destroying the ORB (hoping to kill omniORB threads ...)\n";
654 ORB_INIT * init = SINGLETON_<ORB_INIT>::Instance();
656 init->explicit_destroy();
657 //std::cout << "@@@@@ ORB destroyed\n";
659 // After ORB destruction
660 if(Py_IsInitialized())
663 //std::cout << "@@@@@ About to PyFinalize\n";
665 //std::cout << "@@@@@ DONE PyFinalize\n";
670 //std::cout << "@@@@@ About to kill omni\n";
672 //std::cout << "@@@@@ DONE kill omni\n";
675 MESSAGE( "Salome_Session_Server:endofserver" );