1 // Copyright (C) 2007-2019 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 )
116 #ifdef QT_DEBUG_MESSAGE
117 MESSAGE( "Debug: " << qPrintable( message ) );
121 MESSAGE( "Warning: " << qPrintable( message ) );
124 MESSAGE( "Critical: " << qPrintable( message ) );
127 MESSAGE( "Fatal: " << qPrintable( message ) );
131 MESSAGE( "Information: " << qPrintable( message ) );
137 //! Get version of SALOME GUI module
138 QString salomeVersion()
140 return GUI_VERSION_STR;
143 //! Custom resources manager, that allows customization of application name/version
144 // via configuration/translation files.
145 class ResourceMgr : public SUIT_ResourceMgr
148 ResourceMgr( const QString& appName = "SalomeApp" ) : SUIT_ResourceMgr( appName, "%1Config" )
150 customize(); // activate customization
151 setCurrentFormat( "xml" );
152 setOption( "translators", QString( "%P_msg_%L.qm|%P_icons.qm|%P_images.qm" ) );
155 QString customName() const { return myCustomAppName; }
156 QString version() const { return myCustomAppVersion; }
159 static void customize()
161 // Try to retrieve actual application name and version from translation files.
162 // We create temporary resource manager and load LightApp and SalomeApp translations.
163 // This procedure is supposed to be done only once, at first call.
164 if ( myCustomAppName.isNull() ) {
165 SUIT_ResourceMgr mgr( "SalomeApp", "%1Config" );
166 mgr.setCurrentFormat( "xml" );
167 mgr.setWorkingMode( IgnoreUserValues ); // prevent reading data from user's file
168 mgr.loadLanguage( "LightApp", "en" );
169 mgr.loadLanguage( "SalomeApp", "en" );
171 // actual application name can be customized via APP_NAME resource key
172 myCustomAppName = QObject::tr( "APP_NAME" ).trimmed();
173 if ( myCustomAppName == "APP_NAME" || myCustomAppName.toLower() == "salome" )
174 myCustomAppName = "SalomeApp"; // fallback name
176 // actual application name can be customized via APP_VERSION resource key
177 myCustomAppVersion = QObject::tr( "APP_VERSION" ).trimmed();
178 if ( myCustomAppVersion == "APP_VERSION" )
179 myCustomAppVersion = myCustomAppName == "SalomeApp" ? salomeVersion() : ""; // fallback version
184 QString userFileName( const QString& appName, const bool forLoad ) const
186 if ( version().isEmpty() ) return "";
187 return SUIT_ResourceMgr::userFileName( myCustomAppName, forLoad );
190 virtual long userFileId( const QString& _fname ) const
192 //////////////////////////////////////////////////////////////////////////////////////////////
193 // In SALOME and SALOME-based applications the user preferences file is named as
194 // - <AppName>.xml.<AppVersion> on Windows
195 // - <AppName>rc.<AppVersion> on Linux
197 // * AppName is application name, defaults to SalomeApp. Can be customized in SALOME-based
198 // applications, see ResourceMgr above for more details.
199 // * AppVersion is application version, defaults to current version of SALOME GUI module
200 // if AppName is not customize, otherwise empty. Can be customized in SALOME-based
201 // applications, see ResourceMgr above for more details.
203 // Since version 6.5.0 of SALOME, user file is stored in the ~/.config/salome
204 // directory. For backward compatibility, when user preferences from nearest
205 // version of application is searched, user home directory is also looked through,
206 // with lower priority.
208 // Since version 6.6.0 of SALOME, user file name on Linux is no more prefixed by dot
209 // symbol since it is stored in the hidden ~/.config/salome directory. However, dot-prefixed
210 // files are also taken into account (with lower priority) for backward compatibility.
213 // - Currently the following format of version number is supported:
214 // <major>[.<minor>[.<release>[<type><dev>]]]
215 // Parts in square brackets are considered optional. Here:
216 // * major - major version id
217 // * minor - minor version id
218 // * release - maintenance version id
219 // * type - dev or patch marker; it can be either one alphabetical symbol (from 'a' to 'z')
220 // or 'rc' to point release candidate (case-insensitive)
221 // * dev - dev version or patch number
222 // All numerical values must be of range [1-99].
223 // Examples: 1.0, 6.5.0, 1.2.0a1, 3.3.3rc3 (release candidate 3), 11.0.0p1 (patch 1)
225 // - Versioning approach can be customized by implementing and using own resource manager class,
226 // see QtxResurceMgr, SUIT_ResourceMgr classes, and ResourceMgr class above in this file.
227 //////////////////////////////////////////////////////////////////////////////////////////////
230 if ( !myCustomAppName.isEmpty() ) {
232 // On Windows, user file name is something like SalomeApp.xml.6.5.0 where
233 // - SalomeApp is an application name (can be customized)
234 // - xml is a file format (xml or ini)
235 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
236 QRegExp exp( QString( "%1\\.%2\\.([a-zA-Z0-9.]+)" ).arg( myCustomAppName ).arg( currentFormat() ) );
238 // On Linux, user file name is something like SalomeApprc.6.5.0 where
239 // - SalomeApp is an application name (can be customized)
240 // - 6.5.0 is an application version, can include alfa/beta/rc marks, e.g. 6.5.0a3, 6.5.0rc1
242 // VSR 24/09/2012: issue 0021781: since version 6.6.0 user filename is not prepended with "."
243 // when it is stored in the ~/.config/<appname> directory;
244 // for backward compatibility we also check files prepended with "." with lower priority
245 QRegExp exp( QString( "\\.?%1rc\\.([a-zA-Z0-9.]+)" ).arg( myCustomAppName ) );
247 QString fname = QFileInfo( _fname ).fileName();
248 if ( exp.exactMatch( fname ) ) {
249 long fid = Qtx::versionToId( exp.cap( 1 ) );
250 if ( fid > 0 ) id = fid;
257 static QString myCustomAppName;
258 static QString myCustomAppVersion;
260 QString ResourceMgr::myCustomAppName;
261 QString ResourceMgr::myCustomAppVersion;
263 //! Custom session, to use custom resource manager class.
264 class Session : public SUIT_Session
267 virtual SUIT_ResourceMgr* createResourceMgr( const QString& appName ) const
269 return new ResourceMgr( appName );
273 //! Custom QApplication class, redefines notify() method, to transfer all events
274 // via centralized exception handling mechanism.
275 class Application : public QApplication
278 Application( int& argc, char** argv )
279 : QApplication( argc, argv ),
282 myDebug = !Qtx::getenv( "SALOME_DEBUG_EXCEPTIONS" ).isEmpty();
285 virtual bool notify( QObject* receiver, QEvent* e )
287 if ( myDebug || !myHandler ) {
288 return QApplication::notify( receiver, e );
292 return myHandler->handle( receiver, e );
294 catch ( std::exception& e ) {
295 std::cerr << "notify(): Caught exception : " << e.what() << std::endl;
297 catch ( CORBA::Exception& e ) {
298 std::cerr << "notify(): Caught CORBA exception : " << handleCorbaException( e ) << std::endl;
301 std::cerr << "notify(): Caught unknown exception : there's probably a bug in SALOME platform" << std::endl;
303 return false; // return false when exception is caught
307 SUIT_ExceptionHandler* handler() const { return myHandler; }
308 void setHandler( SUIT_ExceptionHandler* h ) { myHandler = h; }
311 SUIT_ExceptionHandler* myHandler;
315 //! Class which calls SALOME::Session::GetInterface() from another thread
316 // to avoid mutual lock if called from the same thread as main()
317 class GetInterfaceThread : public QThread
320 GetInterfaceThread( SALOME::Session_var s ) : session ( s )
328 if ( !CORBA::is_nil( session ) )
329 session->GetInterface();
331 std::cerr << "FATAL ERROR: SALOME::Session object is nil! Cannot display GUI" << std::endl;
335 SALOME::Session_var session;
338 //! Checks command line for presense of given option(s).
339 // Option that results to \c true is specified via \a trueOption parameter.
340 // Option that results to \c false is specified via \a falseOption parameter (empty for default).
341 // Default value for the result (returned if both \a trueOption \a falseOption are not given) is specified via \c defValue parameter.
342 bool boolCmdOption( const QString trueOption, const QString falseOption = QString(), bool defValue = false )
344 bool value = defValue;
346 QStringList args = QApplication::arguments();
347 foreach ( QString arg, args )
349 if ( arg == trueOption )
351 else if ( arg == falseOption )
357 // Kill omniNames process
360 SALOME_LifeCycleCORBA::killOmniNames();
363 // Shutdown standalone servers
364 void shutdownServers( SALOME_NamingService* theNS, bool remoteLauncher )
366 SALOME_LifeCycleCORBA lcc( theNS );
367 lcc.shutdownServers( !remoteLauncher );
369 } // end of anonymous namespace
371 // ---------------------------- MAIN -----------------------
372 int main( int argc, char **argv )
374 // Set-up application settings configuration (as for QSettings)
375 // Note: these are default settings which can be customized (see below)
376 QApplication::setOrganizationName( "salome" );
377 QApplication::setApplicationName( "salome" );
378 QApplication::setApplicationVersion( salomeVersion() );
380 // Install Qt debug messages handler
381 MsgHandler msgHandler;
382 qInstallMessageHandler( QtxMsgHandler );
384 // Add <qtdir>/plugins dir to the pluins search path for image plugins
385 QString qtdir = Qtx::qtDir( "plugins" );
386 if ( !qtdir.isEmpty() )
387 QApplication::addLibraryPath( qtdir );
389 // Add application library path (to search style plugin etc...)
390 QString path = SUIT_Tools::addSlash( Qtx::getenv( "GUI_ROOT_DIR" ) ) + "bin/salome";
391 QApplication::addLibraryPath( QDir::toNativeSeparators( path ) );
393 // QSurfaceFormat should be set before creation of QApplication,
394 // so to avoid conflicts beetween SALOME and ParaView QSurfaceFormats we should merge theirs formats
395 // (see void Qtx::initDefaultSurfaceFormat()) and set the resultant format here.
396 Qtx::initDefaultSurfaceFormat();
398 // Create Qt application instance: this should be done as early as possible!
399 // Note: QApplication forces setting locale LC_ALL to system one: setlocale(LC_ALL, "").
400 Application app( argc, argv );
402 // Initialize Python (only once)
403 // Note: Python forces setting locale LC_CTYPE to system one: setlocale(LC_CTYPE, "").
404 char* py_argv[] = {(char*)""};
405 KERNEL_PYTHON::init_python( 1, py_argv );
407 // Create auxiliary resource manager to access application settings
409 resMgr.setWorkingMode( ResourceMgr::IgnoreUserValues );
410 resMgr.loadLanguage( "LightApp", "en" );
411 resMgr.loadLanguage( "SalomeApp", "en" );
412 resMgr.loadLanguage( "Session" );
414 // Set-up application settings configuration possible customized via resources
415 if ( resMgr.customName() != "SalomeApp" ) {
416 QApplication::setApplicationName( resMgr.customName() );
417 QApplication::setApplicationVersion( resMgr.version() );
420 // Force default "C" locale if requested via user's preferences
421 // Note: this does not change whole application locale (changed via setlocale() function),
422 // but only affects GUI behavior
423 resMgr.setWorkingMode( ResourceMgr::AllowUserValues ); // we must take into account user preferences
424 if ( resMgr.booleanValue( "language", "locale", true ) )
425 QLocale::setDefault( QLocale::c() );
426 resMgr.setWorkingMode( ResourceMgr::IgnoreUserValues );
428 bool isGUI = boolCmdOption( "--show-desktop", "--hide-desktop", true ); // true by default
429 bool isSplash = boolCmdOption( "--show-splash", "--hide-splash", true ); // true by default
431 // Show splash screen (only if both the "GUI" and "SPLASH" options are true)
432 QtxSplash* splash = 0;
433 if ( isGUI && isSplash ) {
434 splash = QtxSplash::splash( QPixmap() );
435 splash->readSettings( &resMgr );
436 if ( splash->pixmap().isNull() )
437 splash->setPixmap( resMgr.loadPixmap( "LightApp", QObject::tr( "ABOUT_SPLASH" ) ) );
438 if ( splash->pixmap().isNull() ) {
443 splash->setOption( "%A", QObject::tr( "APP_NAME" ) );
444 splash->setOption( "%V", QObject::tr( "ABOUT_VERSION" ).arg( resMgr.version() ) );
445 splash->setOption( "%L", QObject::tr( "ABOUT_LICENSE" ) );
446 splash->setOption( "%C", QObject::tr( "ABOUT_COPYRIGHT" ) );
448 QApplication::instance()->processEvents();
456 PortableServer::POA_var poa;
458 SUIT_Session* aGUISession = 0;
459 SALOME_NamingService* _NS = 0;
460 GetInterfaceThread* guiThread = 0;
461 Session_ServerLauncher* myServerLauncher = 0;
463 #if defined(WIN32) && defined(UNICODE)
464 char** new_argv = NULL;
467 bool remoteLauncher = false;
470 // ...create ORB, get RootPOA object, NamingService, etc.
471 ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance();
472 ASSERT( SINGLETON_<ORB_INIT>::IsAlreadyExisting() );
474 if( std::string(argv[1]).find("-ORBInitRef") != std::string::npos ){
476 remoteLauncher = true;
478 orb = init( orbArgc, argv );
480 CORBA::Object_var obj = orb->resolve_initial_references( "RootPOA" );
481 poa = PortableServer::POA::_narrow( obj );
483 PortableServer::POAManager_var pman = poa->the_POAManager();
485 MESSAGE( "POA manager activated" );
487 _NS = new SALOME_NamingService( orb );
491 catch ( SALOME_Exception& e ) {
492 INFOS( "run(): Caught SALOME_Exception : " << e.what() );
494 catch ( CORBA::SystemException& e ) {
495 INFOS( "run(): Caught CORBA::SystemException : " << handleCorbaException( e ) );
497 catch ( CORBA::Exception& e ) {
498 INFOS( "run(): Caught CORBA::Exception : " << handleCorbaException( e ) );
500 catch ( std::exception& e ) {
501 INFOS( "run(): Caught exception : " << e.what() );
504 INFOS( "run(): Caught unknown exception" );
507 QMutex _GUIMutex, _SessionMutex, _SplashMutex;
508 QWaitCondition _ServerLaunch, _SessionStarted, _SplashStarted;
510 // lock session mutex to ensure that GetInterface is not called
511 // until all initialization is done
512 _SessionMutex.lock();
515 // Start embedded servers launcher (Registry, SALOMEDS, etc.)
516 // ...lock mutex to block embedded servers launching thread until wait( mutex )
518 // ...create launcher
519 #if defined(WIN32) && defined(UNICODE)
520 LPWSTR *szArglist = NULL;
523 szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
524 new_argv = new char*[nArgs];
525 for (i = 0; i < nArgs; i++) {
526 new_argv[i] = (char*) Kernel_Utils::utf8_encode(szArglist[i]);
528 // Free memory allocated for CommandLineToArgvW arguments.
529 LocalFree(szArglist);
530 myServerLauncher = new Session_ServerLauncher(nArgs, new_argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted);
532 myServerLauncher = new Session_ServerLauncher( argc, argv, orb, poa, &_GUIMutex, &_ServerLaunch, &_SessionMutex, &_SessionStarted );
534 // ...block this thread until launcher is ready
535 _ServerLaunch.wait( &_GUIMutex );
537 // Start servers check thread (splash)
539 // ...lock mutex to block splash thread until wait( mutex )
541 // ...create servers checking thread
542 Session_ServerCheck sc( &_SplashMutex, &_SplashStarted );
543 // ... set initial progress
544 splash->setProgress( 0, sc.totalSteps() );
547 int step = sc.currentStep();
548 int total = sc.totalSteps();
549 QString msg = sc.currentMessage();
550 QString err = sc.error();
551 if ( !err.isEmpty() ) {
552 QtxSplash::setError( err );
553 QApplication::instance()->processEvents();
557 QtxSplash::setStatus( msg, step );
558 QApplication::instance()->processEvents();
561 // ...block this thread until servers checking is finished
562 _SplashStarted.wait( &_SplashMutex );
564 // ...unlock mutex 'cause it is no more needed
565 _SplashMutex.unlock();
568 // Finalize embedded servers launcher
569 // ...block this thread until launcher is finished
570 _ServerLaunch.wait( &_GUIMutex );
571 // ...unlock mutex 'cause it is no more needed
575 // Obtain Session interface reference
576 CORBA::Object_var obj = _NS->Resolve( "/Kernel/Session" );
577 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
579 bool shutdownAll = false;
580 bool shutdownSession = false;
581 bool debugExceptions = boolCmdOption( "--no-exception-handler" ) ||
582 resMgr.booleanValue( "launch", "noexcepthandler", false );
585 // Launch GUI activator
588 splash->setStatus( QObject::tr( "Activating desktop..." ) );
589 // ...create GUI launcher
590 MESSAGE( "Session activated, Launch IAPP..." );
591 guiThread = new GetInterfaceThread( session );
595 // Allow multiple activation/deactivation of GUI
597 MESSAGE( "waiting wakeAll()" );
598 _SessionStarted.wait( &_SessionMutex ); // to be reseased by Launch server thread when ready:
599 // atomic operation lock - unlock on mutex
600 // unlock mutex: serverThread runs, calls _ServerLaunch->wakeAll()
601 // this thread wakes up, and lock mutex
603 _SessionMutex.unlock();
605 // Session might be shutdowning here, check status
606 SALOME::StatSession stat = session->GetStatSession();
607 shutdownSession = stat.state == SALOME::shutdown;
608 if ( shutdownSession ) {
609 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
613 // SUIT_Session creation
614 aGUISession = new Session();
616 // Load SalomeApp dynamic library
617 MESSAGE( "creation SUIT_Application" );
618 SUIT_Application* aGUIApp = aGUISession->startApplication( "SalomeApp", 0, 0 );
621 #ifdef USE_SALOME_STYLE
622 Style_Salome::initialize( aGUIApp->resourceMgr() );
623 if ( aGUIApp->resourceMgr()->booleanValue( "Style", "use_salome_style", true ) )
624 Style_Salome::apply();
625 #endif // USE_SALOME_STYLE
627 if ( !debugExceptions )
628 app.setHandler( aGUISession->handler() ); // after loading SalomeApp application
629 // aGUISession contains SalomeApp_ExceptionHandler
632 MESSAGE( "run(): starting the main event loop" );
635 splash->finish( aGUIApp->desktop() );
641 if ( result == SUIT_Session::NORMAL ) {
642 // desktop is explicitly closed by user from GUI
643 // exit flags says if it's necessary to shutdown all servers
644 // all session server only
645 shutdownAll = aGUISession->exitFlags();
648 // desktop might be closed from:
649 // - StopSesion() (temporarily) or
650 // - Shutdown() (permanently)
651 stat = session->GetStatSession();
652 shutdownSession = stat.state == SALOME::shutdown;
653 // normally "shutdown standalone servers" flag should be false here, if we come from
654 // StopSesion() or from Shutdown();
655 // but we also have to check if somebody explicitly programmatically closed session,
656 // asking to kill servers also
657 shutdownAll = aGUISession->exitFlags();
659 if ( shutdownAll || shutdownSession ) {
660 _SessionMutex.lock(); // lock mutex before leaving loop - it will be unlocked later
668 // Prepare _GUIMutex for a new GUI activation
669 _SessionMutex.lock();
673 // unlock Session mutex
674 _SessionMutex.unlock();
676 // Shutdown embedded servers
677 if ( myServerLauncher )
678 myServerLauncher->ShutdownAll();
680 // Shutdown standalone servers
682 shutdownServers( _NS, remoteLauncher );
684 // Kill embedded servers
685 if ( myServerLauncher )
686 myServerLauncher->KillAll();
688 // Unregister session server
689 SALOME_Session_i* sessionServant =
690 dynamic_cast<SALOME_Session_i*>( poa->reference_to_servant( session.in() ) );
691 if ( sessionServant )
692 sessionServant->NSunregister();
696 delete myServerLauncher;
698 #if defined(WIN32) && defined(UNICODE)
706 //////////////////////////////////////////////////////////////
707 // VSR: silently skip exception:
708 // CORBA.BAD_INV_ORDER.BAD_INV_ORDER_ORBHasShutdown
709 // exception is raised when orb->destroy() is called and
710 // cpp continer is launched in the embedded mode
711 //////////////////////////////////////////////////////////////
714 abort(); //abort program to avoid deadlock in destructors or atexit when shutdown has been interrupted
719 ORB_INIT* init = SINGLETON_<ORB_INIT>::Instance();
721 init->explicit_destroy();
724 if ( Py_IsInitialized() )
730 // Kill omniNames process
736 MESSAGE( "Salome_Session_Server:endofserver" );