WQtGui.cpp 16.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
//---------------------------------------------------------------------------
//
// Project: OpenWalnut ( http://www.openwalnut.org )
//
// Copyright 2009 OpenWalnut Community, BSV@Uni-Leipzig and CNCF@MPI-CBS
// For more information see http://www.openwalnut.org/copying
//
// This file is part of OpenWalnut.
//
// OpenWalnut is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// OpenWalnut is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with OpenWalnut. If not, see <http://www.gnu.org/licenses/>.
//
//---------------------------------------------------------------------------

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/shared_ptr.hpp>

34 35 36
#include <QApplication>
#include <QSplashScreen>
#include <QFileDialog>
37
#include <QtGlobal> // for QCoreApplication::setAttribute
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
#include <QtCore/QDir>
#include <QtCore/QSettings>

#include "WMainWindow.h" // this has to be included before any other includes
#include "WApplication.h"
#include "core/common/WConditionOneShot.h"
#include "core/common/WIOTools.h"
#include "core/common/WPathHelper.h"
#include "core/dataHandler/WDataHandler.h"
#include "core/dataHandler/WSubject.h"
#include "core/graphicsEngine/WGraphicsEngine.h"
#include "core/kernel/WKernel.h"
#include "core/kernel/WModuleContainer.h"
#include "core/kernel/WProjectFile.h"
#include "core/kernel/WROIManager.h"
#include "controlPanel/WQtControlPanel.h"
#include "events/WModuleAssocEvent.h"
#include "events/WModuleConnectEvent.h"
#include "events/WModuleCrashEvent.h"
#include "events/WModuleDisconnectEvent.h"
#include "events/WModuleReadyEvent.h"
#include "events/WModuleRemovedEvent.h"
#include "events/WRoiAssocEvent.h"
#include "events/WRoiRemoveEvent.h"
#include "events/WUpdateTextureSorterEvent.h"
#include "events/WLogEvent.h"
#include "WQtModuleConfig.h"

66
#include "WQtGui.h"
67

68
WMainWindow* WQtGui::m_mainWindow = NULL;
69

70
QSettings* WQtGui::m_settings = NULL;
71

72
WQtGui::WQtGui( const boost::program_options::variables_map& options, int argc, char** argv )
73 74 75 76
    : WUI( argc, argv ),
    m_optionsMap( options ),
    m_loadDeferredOnce( true )
{
77
    QCoreApplication::setAttribute( Qt::AA_X11InitThreads );
78 79
}

80
WQtGui::~WQtGui()
81 82 83 84
{
    delete m_settings;
}

85
void WQtGui::moduleError( boost::shared_ptr< WModule > module, const WException& exception )
86 87 88 89 90
{
    QCoreApplication::postEvent( m_mainWindow, new WModuleCrashEvent( module, exception.what() ) );
    QCoreApplication::postEvent( m_mainWindow->getNetworkEditor(), new WModuleCrashEvent( module, exception.what() ) );
}

91
WMainWindow* WQtGui::getMainWindow()
92 93 94 95
{
    return m_mainWindow;
}

96
WIconManager* WQtGui::getIconManager()
97 98 99 100
{
    return getMainWindow()->getIconManager();
}

101
void WQtGui::deferredLoad()
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
{
    m_deferredLoadMutex.lock();
    if( m_loadDeferredOnce )
    {
        m_loadDeferredOnce = false;
        wlog::debug( "OpenWalnut" ) << "Deferred loading of data and project files.";

        bool useInputFileNameAsProject = false;
        // check if we want to load data due to command line and call the respective function
        if( m_optionsMap.count( "input" ) )
        {
            std::vector< std::string > dataFileNames = m_optionsMap["input"].as< std::vector< std::string > >();
            useInputFileNameAsProject = ( dataFileNames.size() == 1
                                          && ( boost::algorithm::ends_with( dataFileNames[0], ".owp" )
                                               || boost::algorithm::ends_with( dataFileNames[0], ".owproj" ) ) );
            if( !useInputFileNameAsProject )
            {
                m_kernel->loadDataSets( dataFileNames );
            }
        }

        // Load project file
        if( m_optionsMap.count( "project" ) || useInputFileNameAsProject )
        {
            std::string projectFileName;
            if( useInputFileNameAsProject )
            {
                projectFileName = m_optionsMap["input"].as< std::vector< std::string > >()[0];
            }
            else
            {
                projectFileName = m_optionsMap["project"].as< std::string >();
            }

            try
            {
                // This call is asynchronous. It parses the file and the starts a thread to actually do all the stuff
                m_mainWindow->asyncProjectLoad( projectFileName );
            }
            catch( const WException& e )
            {
                wlog::error( "GUI" ) << "Project file \"" << m_optionsMap["project"].as< std::string >() << "\" could not be loaded. Message: " <<
                    e.what();
            }
        }
    }
    m_deferredLoadMutex.unlock();
}

151
int WQtGui::run()
152 153 154
{
    m_splash = NULL;
    // init logger
155
    m_loggerConnection = WLogger::getLogger()->subscribeSignal( WLogger::AddLog, boost::bind( &WQtGui::slotAddLog, this, _1 ) );
156 157

    // make qapp instance before using the applicationDirPath() function
158
#ifdef Q_OS_OSX
159 160 161 162 163 164
    //TODO(mario): this should run on all platforms but crashes at least on Linux right now. Therefore, I only use it on OSX
    WApplication appl( m_argc, m_argv, true );
#else
    // TODO(mario): I want a WApplication here for session handling but that code crashes
    QApplication appl( m_argc, m_argv, true );
#endif
Sebastian Eichelbaum's avatar
[STYLE]  
Sebastian Eichelbaum committed
165

166 167
    // the call path of the application, this uses QApplication which needs to be instantiated.
    boost::filesystem::path walnutBin = boost::filesystem::path( QApplication::applicationDirPath().toStdString() );
Sebastian Eichelbaum's avatar
[STYLE]  
Sebastian Eichelbaum committed
168

169
    // setup path helper which provides several paths to others
170
#ifdef Q_OS_OSX
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    // apple has a special file hierarchy in so-called bundles
    // this code determines whether we are started from a bundle context
    // and sets the paths according to Apple's guidelines inside the bundle
    if( QApplication::applicationDirPath().endsWith( "/MacOS" ) )
    {
        // we are in a bundle
        // TODO(mario): apply default OSX behavior of using $HOME/Library/OpenWalnut ?
        WPathHelper::getPathHelper()->setBasePathsOSXBundle( walnutBin, boost::filesystem::path( QDir::homePath().toStdString() ) / ".OpenWalnut" );
    }
    else
    {
        // assume standard behavior
        WPathHelper::getPathHelper()->setBasePaths( walnutBin, boost::filesystem::path( QDir::homePath().toStdString() ) / ".OpenWalnut" );
    }
#else
    // on all other platforms, get the home directory form Qt and the path from the application binary location
    WPathHelper::getPathHelper()->setBasePaths( walnutBin, boost::filesystem::path( QDir::homePath().toStdString() ) / ".OpenWalnut" );
#endif

190
    QPixmap splashPixmap( QString::fromStdString( ( WPathHelper::getPathHelper()->getSharePath() / "qtgui" / "splash.png" ).string() ) );
191 192 193 194
    m_splash = new QSplashScreen( splashPixmap );
    m_splash->show();

    // with the correct paths, we can load the settings
195
    m_settings = new QSettings( QString::fromStdString( ( WPathHelper::getHomePath() / "config.qtgui" ).string() ), QSettings::IniFormat );
196 197 198 199

    WQtModuleConfig::initPathHelper();

    // get the minimum log level from preferences
200
    LogLevel logLevel = static_cast< LogLevel >( WQtGui::getSettings().value( "qtgui/logLevel", LL_DEBUG ).toInt() );
201 202 203 204 205 206 207 208 209 210 211 212
    WLogger::getLogger()->setDefaultLogLevel( logLevel );

    // print the first output
    wlog::debug( "OpenWalnut" ) << "OpenWalnut binary path: " << walnutBin;
    wlog::info( "GUI" ) << "Bringing up GUI";

    // startup graphics engine
    m_ge = WGraphicsEngine::getGraphicsEngine();

    // and startup kernel
    m_kernel = boost::shared_ptr< WKernel >( WKernel::instance( m_ge, shared_from_this() ) );
    m_kernel->run();
213
    m_kernel->subscribeSignal( WKernel::KERNEL_STARTUPCOMPLETE, boost::bind( &WQtGui::deferredLoad, this ) );
214

215
    t_ModuleErrorSignalHandlerType func = boost::bind( &WQtGui::moduleError, this, _1, _2 );
216 217 218
    m_kernel->getRootContainer()->addDefaultNotifier( WM_ERROR, func );

    // bind the GUI's slot with the signals provided by the kernel
219
    WCondition::t_ConditionNotifierType newDatasetSignal = boost::bind( &WQtGui::slotUpdateTextureSorter, this );
220 221 222
    WDataHandler::getDefaultSubject()->getListChangeCondition()->subscribeSignal( newDatasetSignal );

    // Assoc Event
223
    t_ModuleGenericSignalHandlerType assocSignal = boost::bind( &WQtGui::slotAddDatasetOrModuleToTree, this, _1 );
224 225 226
    m_kernel->getRootContainer()->addDefaultNotifier( WM_ASSOCIATED, assocSignal );

    // Ready Event
227
    t_ModuleGenericSignalHandlerType readySignal = boost::bind( &WQtGui::slotActivateDatasetOrModuleInTree, this, _1 );
228 229 230
    m_kernel->getRootContainer()->addDefaultNotifier( WM_READY, readySignal );

    // Remove Event
231
    t_ModuleGenericSignalHandlerType removedSignal = boost::bind( &WQtGui::slotRemoveDatasetOrModuleInTree, this, _1 );
232 233 234
    m_kernel->getRootContainer()->addDefaultNotifier( WM_REMOVED, removedSignal );

    // Connect Event
235
    t_GenericSignalHandlerType connectionEstablishedSignal = boost::bind( &WQtGui::slotConnectionEstablished, this, _1, _2 );
236 237 238
    m_kernel->getRootContainer()->addDefaultNotifier( CONNECTION_ESTABLISHED, connectionEstablishedSignal );

    // Disconnect Event
239
    t_GenericSignalHandlerType connectionClosedSignal = boost::bind( &WQtGui::slotConnectionClosed, this, _1, _2 );
240 241 242 243 244
    m_kernel->getRootContainer()->addDefaultNotifier( CONNECTION_CLOSED, connectionClosedSignal );

    boost::shared_ptr< boost::function< void( osg::ref_ptr< WROI > ) > > assocRoiSignal;
    assocRoiSignal =
        boost::shared_ptr< boost::function< void( osg::ref_ptr< WROI > ) > >(
245
            new boost::function< void( osg::ref_ptr< WROI > ) > ( boost::bind( &WQtGui::slotAddRoiToTree, this, _1 ) ) );
246 247 248 249 250
    m_kernel->getRoiManager()->addAddNotifier( assocRoiSignal );

    boost::shared_ptr< boost::function< void( osg::ref_ptr< WROI > ) > > removeRoiSignal;
    removeRoiSignal =
        boost::shared_ptr< boost::function< void( osg::ref_ptr< WROI > ) > >(
251
            new boost::function< void( osg::ref_ptr< WROI > ) > ( boost::bind( &WQtGui::slotRemoveRoiFromTree, this, _1 ) ) );
252 253 254 255 256 257 258
    m_kernel->getRoiManager()->addRemoveNotifier( removeRoiSignal );

    // create the window
    m_mainWindow = new WMainWindow( m_splash );

    m_widgetFactory = WUIQtWidgetFactory::SPtr( new WUIQtWidgetFactory( m_mainWindow ) );

259
#ifdef Q_OS_OSX
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    //TODO(mario): this should run on all platforms but crashes at least on Linux right now. Therefore, I only use it on OSX
    appl.setMyMainWidget( m_mainWindow );
#endif
    m_mainWindow->setupGUI();
    m_mainWindow->show();

    // connect loader signal with kernel
#ifdef _WIN32
    getLoadButtonSignal()->connect( boost::bind( &WKernel::loadDataSetsSynchronously, m_kernel, _1, false ) );
#else
    getLoadButtonSignal()->connect( boost::bind( &WKernel::loadDataSets, m_kernel, _1, false ) );
#endif

    // now we are initialized
    m_isInitialized( true );

     // run
    int qtRetCode = appl.exec();

    delete m_mainWindow;
    m_mainWindow = NULL; // the log slot needs this to be null now

    // signal everybody to shut down properly.
    WKernel::getRunningKernel()->wait( true );
    WKernel::getRunningKernel()->getGraphicsEngine()->wait( true );

    m_loggerConnection.disconnect();

    return qtRetCode;
}

291
void WQtGui::slotUpdateTextureSorter()
292 293 294 295 296
{
    // create a new event for this and insert it into event queue
    QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WUpdateTextureSorterEvent() );
}

297
void WQtGui::slotAddLog( const WLogEntry& entry )
298 299 300 301 302 303 304 305 306 307
{
    // emit event but the main window might not be available. Check this.
    // NOTE: we disable debug log messages completely, since their extensive use in some modules causes SEVERE slowdown of the GUI as millions of
    //       events need to be handled each GUI event loop. See issue #283 for details.
    if( m_mainWindow && ( entry.getLogLevel() != LL_DEBUG ) )
    {
        QCoreApplication::postEvent( m_mainWindow, new WLogEvent( entry ) );
    }
}

308
void WQtGui::slotAddDatasetOrModuleToTree( boost::shared_ptr< WModule > module )
309 310 311 312 313 314 315 316 317
{
    // create a new event for this and insert it into event queue
    if( m_mainWindow->getNetworkEditor() )
    {
        QCoreApplication::postEvent( m_mainWindow->getNetworkEditor(), new WModuleAssocEvent( module ) );
    }
    QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WModuleAssocEvent( module ) );
}

318
void WQtGui::slotAddRoiToTree( osg::ref_ptr< WROI > roi )
319 320 321 322
{
    QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WRoiAssocEvent( roi ) );
}

323
void WQtGui::slotRemoveRoiFromTree( osg::ref_ptr< WROI > roi )
324 325 326 327
{
    QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WRoiRemoveEvent( roi ) );
}

328
void WQtGui::slotActivateDatasetOrModuleInTree( boost::shared_ptr< WModule > module )
329 330 331 332 333 334 335 336 337 338
{
    // create a new event for this and insert it into event queue
    if( m_mainWindow->getNetworkEditor() )
    {
        QCoreApplication::postEvent( m_mainWindow->getNetworkEditor(), new WModuleReadyEvent( module ) );
    }
    QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WModuleReadyEvent( module ) );
    QCoreApplication::postEvent( m_mainWindow, new WModuleReadyEvent( module ) );
}

339
void WQtGui::slotRemoveDatasetOrModuleInTree( boost::shared_ptr< WModule > module )
340 341 342 343 344 345 346 347 348 349
{
    // create a new event for this and insert it into event queue
    QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WModuleRemovedEvent( module ) );
    QCoreApplication::postEvent( m_mainWindow, new WModuleRemovedEvent( module ) );
    if( m_mainWindow->getNetworkEditor() )
    {
        QCoreApplication::postEvent( m_mainWindow->getNetworkEditor(), new WModuleRemovedEvent( module ) );
    }
}

350
void WQtGui::slotConnectionEstablished( boost::shared_ptr<WModuleConnector> in, boost::shared_ptr<WModuleConnector> out )
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
{
    // create a new event for this and insert it into event queue
    if( in->isInputConnector() )
    {
        QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WModuleConnectEvent( in, out ) );
        if( m_mainWindow->getNetworkEditor() )
        {
            QCoreApplication::postEvent( m_mainWindow->getNetworkEditor(), new WModuleConnectEvent( in, out ) );
        }
    }
    else
    {
        QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WModuleConnectEvent( out, in ) );
        if( m_mainWindow->getNetworkEditor() )
        {
            QCoreApplication::postEvent( m_mainWindow->getNetworkEditor(), new WModuleConnectEvent( out, in ) );
        }
    }
}

371
void WQtGui::slotConnectionClosed( boost::shared_ptr<WModuleConnector> in, boost::shared_ptr<WModuleConnector> out )
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
{
    // create a new event for this and insert it into event queue
    if( in->isInputConnector() )
    {
        if( m_mainWindow->getNetworkEditor() )
        {
            QCoreApplication::postEvent( m_mainWindow->getNetworkEditor(), new WModuleDisconnectEvent( in, out ) );
        }
        QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WModuleDisconnectEvent( in, out ) );
    }
    else
    {
        if( m_mainWindow->getNetworkEditor() )
        {
            QCoreApplication::postEvent( m_mainWindow->getNetworkEditor(), new WModuleDisconnectEvent( out, in ) );
        }
        QCoreApplication::postEvent( m_mainWindow->getControlPanel(), new WModuleDisconnectEvent( out, in ) );
    }
}

392
boost::shared_ptr< WModule > WQtGui::getSelectedModule()
393 394 395 396
{
    return m_mainWindow->getControlPanel()->getSelectedModule();
}

397
boost::signals2::signal1< void, std::vector< std::string > >* WQtGui::getLoadButtonSignal()
398 399 400 401
{
    return m_mainWindow->getLoaderSignal();
}

402
QSettings& WQtGui::getSettings()
403 404 405 406
{
    return *m_settings;
}

407
const boost::program_options::variables_map& WQtGui::getOptionMap() const
408 409 410 411
{
    return m_optionsMap;
}

412
WUIWidgetFactory::SPtr WQtGui::getWidgetFactory() const
413 414 415 416
{
    return m_widgetFactory;
}

417
void WQtGui::execInGUIThread( boost::function< void( void ) > functor, WCondition::SPtr notify )
418 419 420 421 422 423 424 425 426 427 428
{
    if( !notify )
    {
        // the user did not specify a condition. We create our own
        notify = WCondition::SPtr( new WConditionOneShot() );
    }
    WDeferredCallEvent* ev = new WDeferredCallEvent( functor, notify );
    QCoreApplication::postEvent( getMainWindow(), ev );
    notify->wait();
}

429
void WQtGui::execInGUIThreadAsync( boost::function< void( void ) > functor, WCondition::SPtr notify )
430 431 432 433 434
{
    WDeferredCallEvent* ev = new WDeferredCallEvent( functor, notify );
    QCoreApplication::postEvent( getMainWindow(), ev );
}