1 // Copyright (C) 2007-2020 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 #include <Container_init_python.hxx> // this include must be the first one as it includes Python.h
24 #include <Basics_Utils.hxx>
25 #include <ConnectionManager_i.hxx>
27 #include <RegistryService.hxx>
28 #include <SALOME_LifeCycleCORBA.hxx>
29 #include <SALOME_ModuleCatalog_impl.hxx>
30 #include <SALOME_NamingService.hxx>
31 #include <Utils_CorbaException.hxx>
32 #include <Utils_ORB_INIT.hxx>
33 #include <Utils_SALOME_Exception.hxx>
34 #include <Utils_SINGLETON.hxx>
35 #include <utilities.h>
37 #include "Session_Session_i.hxx"
38 #include "Session_ServerCheck.hxx"
39 #include "Session_ServerLauncher.hxx"
41 #include "GUI_version.h"
43 #include "QtxMsgHandler.h"
44 #include "QtxSplash.h"
45 #include "SALOME_Event.h"
46 #ifdef USE_SALOME_STYLE
47 #include "Style_Salome.h"
48 #endif // USE_SALOME_STYLE
49 #include "SUIT_Application.h"
50 #include "SUIT_Desktop.h"
51 #include "SUIT_ExceptionHandler.h"
52 #include "SUIT_ResourceMgr.h"
53 #include "SUIT_Session.h"
54 #include "SUIT_Tools.h"
56 #include <SALOMEconfig.h>
57 #include CORBA_SERVER_HEADER(SALOME_Session)
58 #include CORBA_SERVER_HEADER(SALOMEDS)
68 #include <QApplication>
73 #include <QTextStream>
74 #include <QWaitCondition>
76 //! CORBA server for SALOME GUI session
78 * SALOME_Session_Server launches a SALOME session servant.
79 * The servant registers to the Naming Service.
80 * See SALOME_Session.idl for interface specification.
81 * Main services offered by the servant are:
83 * - stop Session ( must be idle )
86 * Also, session server:
88 * - defines list of embedded services to launch with their arguments,
89 * - defines list of standalone services to connect/wait,
90 * - waits for naming service to finish its initalization,
91 * - creates and runs a separate thread to launch/initialize all services.
96 std::string handleCorbaException( const CORBA::Exception& e )
101 CORBA::TypeCode_var tc = tmp.type();
102 message += tc->name();
106 //! Custom handler to manage Qt messages
107 class MsgHandler: public QtxMsgHandlerCallback
111 void qtMessage( QtMsgType type, const QMessageLogContext& /*context*/, const QString& message )
113 (void)message; // unused in debug mode
117 #ifdef QT_DEBUG_MESSAGE
118 MESSAGE( "Debug: " << qPrintable( message ) );
122 MESSAGE( "Warning: " << qPrintable( message ) );
125 MESSAGE( "Critical: " << qPrintable( message ) );
128 MESSAGE( "Fatal: " << qPrintable( message ) );
132 MESSAGE( "Information: " << qPrintable( message ) );
138 //! Get version of SALOME GUI module
139 QString salomeVersion()
141 return GUI_VERSION_STR;
144 //! Custom resources manager, that allows customization of application name/version
145 // via configuration/translation files.
146 class ResourceMgr : public SUIT_ResourceMgr
149 ResourceMgr( const QString& appName = "SalomeApp" ) : SUIT_ResourceMgr( appName, "%1Config" )
151 customize(); // activate customization
152 setCurrentFormat( "xml" );
153 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
156 QString customName() const { return myCustomAppName; }
157 QString version() const { return myCustomAppVersion; }
160 static void customize()
162 // Try to retrieve actual application name and version from translation files.
163 // We create temporary resource manager and load LightApp and SalomeApp translations.
164 // This procedure is supposed to be done only once, at first call.
165 if ( myCustomAppName.isNull() ) {
166 SUIT_ResourceMgr mgr( "SalomeApp", "%1Config" );
167 mgr.setCurrentFormat( "xml" );
168 mgr.setWorkingMode( IgnoreUserValues ); // prevent reading data from user's file
169 mgr.loadLanguage( "LightApp", "en" );
170 mgr.loadLanguage( "SalomeApp", "en" );
172 // actual application name can be customized via APP_NAME resource key
173 myCustomAppName = QObject::tr( "APP_NAME" ).trimmed();
174 if ( myCustomAppName == "APP_NAME" || myCustomAppName.toLower() == "salome" )
175 myCustomAppName = "SalomeApp"; // fallback name
177 // actual application name can be customized via APP_VERSION resource key
178 myCustomAppVersion = QObject::tr( "APP_VERSION" ).trimmed();
179 if ( myCustomAppVersion == "APP_VERSION" )
180 myCustomAppVersion = myCustomAppName == "SalomeApp" ? salomeVersion() : ""; // fallback version
185 QString userFileName( const QString& /*appName*/, const bool forLoad ) const
187 if ( version().isEmpty() ) return "";
188 return SUIT_ResourceMgr::userFileName( myCustomAppName, forLoad );
191 virtual long userFileId( const QString& _fname ) const
193 //////////////////////////////////////////////////////////////////////////////////////////////
194 // In SALOME and SALOME-based applications the user preferences file is named as
195 // - <AppName>.xml.<AppVersion> on Windows
196 // - <AppName>rc.<AppVersion> on Linux
198 // * AppName is application name, defaults to SalomeApp. Can be customized in SALOME-based
199 // applications, see ResourceMgr above for more details.
200 // * AppVersion is application version, defaults to current version of SALOME GUI module
201 // if AppName is not customize, otherwise empty. Can be customized in SALOME-based
202 // applications, see ResourceMgr above for more details.
204 // Since version 6.5.0 of SALOME, user file is stored in the ~/.config/salome
205 // directory. For backward compatibility, when user preferences from nearest
206 // version of application is searched, user home directory is also looked through,
207 // with lower priority.
209 // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
210 // symbol since it is stored in the hidden ~/.config/salome directory. However, dot-prefixed
211 // files are also taken into account (with lower priority) for backward compatibility.
214 // - Currently the following format of version number is supported:
215 // <major>[.<minor>[.<release>[<type><dev>]]]
216 // Parts in square brackets are considered optional. Here:
217 // * major - major version id
218 // * minor - minor version id
219 // * release - maintenance version id
220 // * type - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
221 // or 'rc' to point release candidate (case-insensitive)
222 // * dev - dev version or patch number
223 // All numerical values must be of range [1-99].
224 // Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
226 // - Versioning approach can be customized by implementing and using own resource manager class,
227 // see QtxResurceMgr, SUIT_ResourceMgr classes, and ResourceMgr class above in this file.
228 //////////////////////////////////////////////////////////////////////////////////////////////
231 if ( !myCustomAppName.isEmpty() ) {
233 // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
234 // - SalomeApp is an application name (can be customized)
235 // - xml is a file format (xml or ini)
236 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
237 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myCustomAppName ).arg( currentFormat() ) );
239 // On Linux, user file name is something like SalomeApprc.6.5.0 where
240 // - SalomeApp is an application name (can be customized)
241 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
243 // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
244 // when it is stored in the ~/.config/<appname> directory;
245 // for backward compatibility we also check files prepended with "." with lower priority
246 QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myCustomAppName ) );
248 QString fname = QFileInfo( _fname ).fileName();
249 if ( exp.exactMatch( fname ) ) {
250 long fid = Qtx::versionToId( exp.cap( 1 ) );
251 if ( fid > 0 ) id = fid;
258 static QString myCustomAppName;
259 static QString myCustomAppVersion;
261 QString ResourceMgr::myCustomAppName;
262 QString ResourceMgr::myCustomAppVersion;
264 //! Custom session, to use custom resource manager class.
265 class Session : public SUIT_Session
268 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
270 return new ResourceMgr( appName );
274 //! Custom QApplication class, redefines notify() method, to transfer all events
275 // via centralized exception handling mechanism.
276 class Application : public QApplication
279 Application( int& argc, char** argv )
280 : QApplication( argc, argv ),
283 myDebug = !Qtx::getenv( "SALOME_DEBUG_EXCEPTIONS" ).isEmpty();
286 virtual bool notify( QObject* receiver, QEvent* e )
288 if ( myDebug || !myHandler ) {
289 return QApplication::notify( receiver, e );
293 return myHandler->handle( receiver, e );
295 catch ( std::exception& e ) {
296 std::cerr << "notify(): Caught exception : " << e.what() << std::endl;
298 catch ( CORBA::Exception& e ) {
299 std::cerr << "notify(): Caught CORBA exception : " << handleCorbaException( e ) << std::endl;
302 std::cerr << "notify(): Caught unknown exception : there's probably a bug in SALOME platform" << std::endl;
304 return false; // return false when exception is caught
308 SUIT_ExceptionHandler* handler() const { return myHandler; }
309 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
312 SUIT_ExceptionHandler* myHandler;
316 //! Class which calls SALOME::Session::GetInterface() from another thread
317 // to avoid mutual lock if called from the same thread as main()
318 class GetInterfaceThread : public QThread
321 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
329 if ( !CORBA::is_nil( session ) )
330 session->GetInterface();
332 std::cerr << "FATAL ERROR: SALOME::Session object is nil! Cannot display GUI" << std::endl;
336 SALOME::Session_var session;
339 //! Checks command line for presense of given option(s).
340 // Option that results to \c true is specified via \a trueOption parameter.
341 // Option that results to \c false is specified via \a falseOption parameter (empty for default).
342 // Default value for the result (returned if both \a trueOption \a falseOption are not given) is specified via \c defValue parameter.
343 bool boolCmdOption( const QString trueOption, const QString falseOption = QString(), bool defValue = false )
345 bool value = defValue;
347 QStringList args = QApplication::arguments();
348 foreach ( QString arg, args )
350 if ( arg == trueOption )
352 else if ( arg == falseOption )
358 // Kill omniNames process
361 SALOME_LifeCycleCORBA::killOmniNames();
364 // Shutdown standalone servers
365 void shutdownServers( SALOME_NamingService* theNS, bool remoteLauncher )
367 SALOME_LifeCycleCORBA lcc( theNS );
368 lcc.shutdownServers( !remoteLauncher );
370 } // end of anonymous namespace
372 // ---------------------------- MAIN -----------------------
373 int main( int argc, char **argv )
375 // Set-up application settings configuration (as for QSettings)
376 // Note: these are default settings which can be customized (see below)
377 QApplication::setOrganizationName( "salome" );
378 QApplication::setApplicationName( "salome" );
379 QApplication::setApplicationVersion( salomeVersion() );
381 // Install Qt debug messages handler
382 MsgHandler msgHandler;
383 qInstallMessageHandler( QtxMsgHandler );
385 // Add <qtdir>/plugins dir to the pluins search path for image plugins
386 QString qtdir = Qtx::qtDir( "plugins" );
387 if ( !qtdir.isEmpty() )
388 QApplication::addLibraryPath( qtdir );
390 // Add application library path (to search style plugin etc...)
391 QString path = SUIT_Tools::addSlash( Qtx::getenv( "GUI_ROOT_DIR" ) ) + "bin/salome";
392 QApplication::addLibraryPath( QDir::toNativeSeparators( path ) );
394 // QSurfaceFormat should be set before creation of QApplication,
395 // so to avoid conflicts beetween SALOME and ParaView QSurfaceFormats we should merge theirs formats
396 // (see void Qtx::initDefaultSurfaceFormat()) and set the resultant format here.
397 Qtx::initDefaultSurfaceFormat();
399 // Create Qt application instance: this should be done as early as possible!
400 // Note: QApplication forces setting locale LC_ALL to system one: setlocale(LC_ALL, "").
401 Application app( argc, argv );
403 // Initialize Python (only once)
404 // Note: Python forces setting locale LC_CTYPE to system one: setlocale(LC_CTYPE, "").
405 char* py_argv[] = {(char*)""};
406 KERNEL_PYTHON::init_python( 1, py_argv );
408 // Create auxiliary resource manager to access application settings
410 resMgr.setWorkingMode( ResourceMgr::IgnoreUserValues );
411 resMgr.loadLanguage( "LightApp", "en" );
412 resMgr.loadLanguage( "SalomeApp", "en" );
413 resMgr.loadLanguage( "Session" );
415 // Set-up application settings configuration possible customized via resources
416 if ( resMgr.customName() != "SalomeApp" ) {
417 QApplication::setApplicationName( resMgr.customName() );
418 QApplication::setApplicationVersion( resMgr.version() );
421 // Force default "C" locale if requested via user's preferences
422 // Note: this does not change whole application locale (changed via setlocale() function),
423 // but only affects GUI behavior
424 resMgr.setWorkingMode( ResourceMgr::AllowUserValues ); // we must take into account user preferences
425 if ( resMgr.booleanValue( "language", "locale", true ) )
426 QLocale::setDefault( QLocale::c() );
427 resMgr.setWorkingMode( ResourceMgr::IgnoreUserValues );
429 bool isGUI = boolCmdOption( "--show-desktop", "--hide-desktop", true ); // true by default
430 bool isSplash = boolCmdOption( "--show-splash", "--hide-splash", true ); // true by default
432 // Show splash screen (only if both the "GUI" and "SPLASH" options are true)
433 QtxSplash* splash = 0;
434 if ( isGUI && isSplash ) {
435 splash = QtxSplash::splash( QPixmap() );
436 splash->readSettings( &resMgr );
437 if ( splash->pixmap().isNull() )
438 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
439 if ( splash->pixmap().isNull() ) {
444 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
445 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( resMgr.version() ) );
446 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
447 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
449 QApplication::instance()->processEvents();
457 PortableServer::POA_var poa;
459 SUIT_Session* aGUISession = 0;
460 SALOME_NamingService* _NS = 0;
461 GetInterfaceThread* guiThread = 0;
462 Session_ServerLauncher* myServerLauncher = 0;
464 #if defined(WIN32) && defined(UNICODE)
465 char** new_argv = NULL;
468 bool remoteLauncher = false;
471 // ...create ORB, get RootPOA object, NamingService, etc.
472 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
473 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
475 if( std::string(argv[1]).find("-ORBInitRef") != std::string::npos ){
477 remoteLauncher = true;
479 orb = init( orbArgc, argv );
481 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
482 poa = PortableServer::POA::_narrow( obj );
484 PortableServer::POAManager_var pman = poa->the_POAManager();
486 MESSAGE( "POA manager activated" );
488 _NS = new SALOME_NamingService( orb );
492 catch ( SALOME_Exception& e ) {
493 INFOS( "run(): Caught SALOME_Exception : " << e.what() );
495 catch ( CORBA::SystemException& e ) {
496 INFOS( "run(): Caught CORBA::SystemException : " << handleCorbaException( e ) );
498 catch ( CORBA::Exception& e ) {
499 INFOS( "run(): Caught CORBA::Exception : " << handleCorbaException( e ) );
501 catch ( std::exception& e ) {
502 INFOS( "run(): Caught exception : " << e.what() );
505 INFOS( "run(): Caught unknown exception" );
508 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
509 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
511 // lock session mutex to ensure that GetInterface is not called
512 // until all initialization is done
513 _SessionMutex.lock();
516 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
517 // ...lock mutex to block embedded servers launching thread until wait( mutex )
519 // ...create launcher
520 #if defined(WIN32) && defined(UNICODE)
521 LPWSTR *szArglist = NULL;
524 szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
525 new_argv = new char*[nArgs];
526 for (i = 0; i < nArgs; i++) {
527 new_argv[i] = (char*) Kernel_Utils::utf8_encode(szArglist[i]);
529 // Free memory allocated for CommandLineToArgvW arguments.
530 LocalFree(szArglist);
531 myServerLauncher = new Session_ServerLauncher(nArgs, new_argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted);
533 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
535 // ...block this thread until launcher is ready
536 _ServerLaunch.wait( &_GUIMutex );
538 // Start servers check thread (splash)
540 // ...lock mutex to block splash thread until wait( mutex )
542 // ...create servers checking thread
543 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
544 // ... set initial progress
545 splash->setProgress( 0, sc.totalSteps() );
548 int step = sc.currentStep();
549 int total = sc.totalSteps();
550 QString msg = sc.currentMessage();
551 QString err = sc.error();
552 if ( !err.isEmpty() ) {
553 QtxSplash::setError( err );
554 QApplication::instance()->processEvents();
558 QtxSplash::setStatus( msg, step );
559 QApplication::instance()->processEvents();
562 // ...block this thread until servers checking is finished
563 _SplashStarted.wait( &_SplashMutex );
565 // ...unlock mutex 'cause it is no more needed
566 _SplashMutex.unlock();
569 // Finalize embedded servers launcher
570 // ...block this thread until launcher is finished
571 _ServerLaunch.wait( &_GUIMutex );
572 // ...unlock mutex 'cause it is no more needed
576 // Obtain Session interface reference
577 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
578 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
580 bool shutdownAll = false;
581 bool shutdownSession = false;
582 bool debugExceptions = boolCmdOption( "--no-exception-handler" ) ||
583 resMgr.booleanValue( "launch", "noexcepthandler", false );
586 // Launch GUI activator
589 splash->setStatus( QObject::tr( "Activating desktop..." ) );
590 // ...create GUI launcher
591 MESSAGE( "Session activated, Launch IAPP..." );
592 guiThread = new GetInterfaceThread( session );
596 // Allow multiple activation/deactivation of GUI
598 MESSAGE( "waiting wakeAll()" );
599 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
600 // atomic operation lock - unlock on mutex
601 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
602 // this thread wakes up, and lock mutex
604 _SessionMutex.unlock();
606 // Session might be shutdowning here, check status
607 SALOME::StatSession stat = session->GetStatSession();
608 shutdownSession = stat.state == SALOME::shutdown;
609 if ( shutdownSession ) {
610 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
614 // SUIT_Session creation
615 aGUISession = new Session();
617 // Load SalomeApp dynamic library
618 MESSAGE( "creation SUIT_Application" );
619 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
622 #ifdef USE_SALOME_STYLE
623 Style_Salome::initialize( aGUIApp->resourceMgr() );
624 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
625 Style_Salome::apply();
626 #endif // USE_SALOME_STYLE
628 if ( !debugExceptions )
629 app.setHandler( aGUISession->handler() ); // after loading SalomeApp application
630 // aGUISession contains SalomeApp_ExceptionHandler
633 MESSAGE( "run(): starting the main event loop" );
636 splash->finish( aGUIApp->desktop() );
642 if ( result == SUIT_Session::NORMAL ) {
643 // desktop is explicitly closed by user from GUI
644 // exit flags says if it's necessary to shutdown all servers
645 // all session server only
646 shutdownAll = aGUISession->exitFlags();
649 // desktop might be closed from:
650 // - StopSesion() (temporarily) or
651 // - Shutdown() (permanently)
652 stat = session->GetStatSession();
653 shutdownSession = stat.state == SALOME::shutdown;
654 // normally "shutdown standalone servers" flag should be false here, if we come from
655 // StopSesion() or from Shutdown();
656 // but we also have to check if somebody explicitly programmatically closed session,
657 // asking to kill servers also
658 shutdownAll = aGUISession->exitFlags();
660 if ( shutdownAll || shutdownSession ) {
661 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
669 // Prepare _GUIMutex for a new GUI activation
670 _SessionMutex.lock();
674 // unlock Session mutex
675 _SessionMutex.unlock();
677 // Shutdown embedded servers
678 if ( myServerLauncher )
679 myServerLauncher->ShutdownAll();
681 // Shutdown standalone servers
683 shutdownServers( _NS, remoteLauncher );
685 // Kill embedded servers
686 if ( myServerLauncher )
687 myServerLauncher->KillAll();
689 // Unregister session server
690 SALOME_Session_i* sessionServant =
691 dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
692 if ( sessionServant )
693 sessionServant->NSunregister();
697 delete myServerLauncher;
699 #if defined(WIN32) && defined(UNICODE)
707 //////////////////////////////////////////////////////////////
708 // VSR: silently skip exception:
709 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
710 // exception is raised when orb->destroy() is called and
711 // cpp continer is launched in the embedded mode
712 //////////////////////////////////////////////////////////////
715 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
720 ORB_INIT* init = SINGLETON_<ORB_INIT>::Instance();
722 init->explicit_destroy();
725 if ( Py_IsInitialized() )
731 // Kill omniNames process
737 MESSAGE( "Salome_Session_Server:endofserver" );