MainWindow.cc 15.6 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
9 10 11 12 13 14 15 16 17 18 19 20 21


/**
 * @file
 *   @brief Implementation of class MainWindow
 *   @author Lorenz Meier <mail@qgroundcontrol.org>
 */

#include <QSettings>
#include <QNetworkInterface>
#include <QDebug>
#include <QTimer>
#include <QHostInfo>
22
#include <QQuickView>
23
#include <QDesktopWidget>
24 25
#include <QScreen>
#include <QDesktopServices>
26
#include <QDockWidget>
27
#include <QMenuBar>
Don Gagne's avatar
Don Gagne committed
28
#include <QDialog>
29

30 31 32
#include "QGC.h"
#include "MAVLinkProtocol.h"
#include "MainWindow.h"
33
#include "AudioOutput.h"
dogmaphobic's avatar
dogmaphobic committed
34
#ifndef __mobile__
35
#include "QGCMAVLinkLogPlayer.h"
dogmaphobic's avatar
dogmaphobic committed
36
#endif
37
#include "MAVLinkDecoder.h"
Don Gagne's avatar
Don Gagne committed
38
#include "QGCApplication.h"
39
#include "MultiVehicleManager.h"
40
#include "LogCompressor.h"
41
#include "UAS.h"
dogmaphobic's avatar
dogmaphobic committed
42
#include "QGCImageProvider.h"
43
#include "QGCCorePlugin.h"
44 45

#ifndef __mobile__
46
#include "Linecharts.h"
47 48 49
#include "QGCUASFileViewMulti.h"
#include "CustomCommandWidget.h"
#include "QGCDockWidget.h"
50
#include "HILDockWidget.h"
51
#include "AppMessages.h"
52 53
#endif

Gus Grubba's avatar
Gus Grubba committed
54
#ifndef NO_SERIAL_LINK
55 56
#include "SerialLink.h"
#endif
57

58 59 60 61
#ifdef UNITTEST_BUILD
#include "QmlControls/QmlTestWidget.h"
#endif

62 63 64
/// The key under which the Main Window settings are saved
const char* MAIN_SETTINGS_GROUP = "QGC_MAINWINDOW";

65
#ifndef __mobile__
66 67 68
enum DockWidgetTypes {
    MAVLINK_INSPECTOR,
    CUSTOM_COMMAND,
69 70
    ONBOARD_FILES,
    HIL_CONFIG,
71
    ANALYZE
72 73 74 75 76 77 78
};

static const char *rgDockWidgetNames[] = {
    "MAVLink Inspector",
    "Custom Command",
    "Onboard Files",
    "HIL Config",
79
    "Analyze"
80 81 82
};

#define ARRAY_SIZE(ARRAY) (sizeof(ARRAY) / sizeof(ARRAY[0]))
83 84

static const char* _visibleWidgetsKey = "VisibleWidgets";
85
#endif
86

Don Gagne's avatar
Don Gagne committed
87 88
static MainWindow* _instance = NULL;   ///< @brief MainWindow singleton

Lorenz Meier's avatar
Lorenz Meier committed
89
MainWindow* MainWindow::_create()
90
{
Lorenz Meier's avatar
Lorenz Meier committed
91
    new MainWindow();
92 93 94
    return _instance;
}

Don Gagne's avatar
Don Gagne committed
95
MainWindow* MainWindow::instance(void)
96
{
Don Gagne's avatar
Don Gagne committed
97
    return _instance;
98 99
}

100 101
void MainWindow::deleteInstance(void)
{
Don Gagne's avatar
Don Gagne committed
102
    delete this;
103 104
}

Don Gagne's avatar
Don Gagne committed
105 106 107
/// @brief Private constructor for MainWindow. MainWindow singleton is only ever created
///         by MainWindow::_create method. Hence no other code should have access to
///         constructor.
Lorenz Meier's avatar
Lorenz Meier committed
108
MainWindow::MainWindow()
109 110 111 112 113
    : _mavlinkDecoder       (NULL)
    , _lowPowerMode         (false)
    , _showStatusBar        (false)
    , _mainQmlWidgetHolder  (NULL)
    , _forceClose           (false)
114
{
Don Gagne's avatar
Don Gagne committed
115
    _instance = this;
116

117 118 119 120 121 122 123 124
    //-- Load fonts
    if(QFontDatabase::addApplicationFont(":/fonts/opensans") < 0) {
        qWarning() << "Could not load /fonts/opensans font";
    }
    if(QFontDatabase::addApplicationFont(":/fonts/opensans-demibold") < 0) {
        qWarning() << "Could not load /fonts/opensans-demibold font";
    }

125 126 127 128
    // Qt 4/5 on Ubuntu does place the native menubar correctly so on Linux we revert back to in-window menu bar.
#ifdef Q_OS_LINUX
    menuBar()->setNativeMenuBar(false);
#endif
dogmaphobic's avatar
dogmaphobic committed
129
    // Setup user interface
130
    loadSettings();
131
    emit initStatusChanged(tr("Setting up user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
132

dogmaphobic's avatar
dogmaphobic committed
133 134
    _ui.setupUi(this);
    // Make sure tool bar elements all fit before changing minimum width
135 136
    setMinimumWidth(1024);
    setMinimumHeight(620);
dogmaphobic's avatar
dogmaphobic committed
137
    configureWindowName();
138

139 140
    // Setup central widget with a layout to hold the views
    _centralLayout = new QVBoxLayout();
141
    _centralLayout->setContentsMargins(0, 0, 0, 0);
142
    centralWidget()->setLayout(_centralLayout);
143 144 145 146 147

    _mainQmlWidgetHolder = new QGCQmlWidgetHolder(QString(), NULL, this);
    _centralLayout->addWidget(_mainQmlWidgetHolder);
    _mainQmlWidgetHolder->setVisible(true);

148
    QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
149
    _mainQmlWidgetHolder->setContextPropertyObject("controller", this);
150
    _mainQmlWidgetHolder->setContextPropertyObject("debugMessageModel", AppMessages::getModel());
Don Gagne's avatar
Don Gagne committed
151
    _mainQmlWidgetHolder->setSource(QUrl::fromUserInput("qrc:qml/MainWindowHybrid.qml"));
152

dogmaphobic's avatar
dogmaphobic committed
153 154
    // Image provider
    QQuickImageProvider* pImgProvider = dynamic_cast<QQuickImageProvider*>(qgcApp()->toolbox()->imageProvider());
155
    _mainQmlWidgetHolder->getEngine()->addImageProvider(QStringLiteral("QGCImages"), pImgProvider);
dogmaphobic's avatar
dogmaphobic committed
156

157
    // Set dock options
158
    setDockOptions(0);
159
    // Setup corners
160
    setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
161

dogmaphobic's avatar
dogmaphobic committed
162 163 164
    // On Mobile devices, we don't want any main menus at all.
#ifdef __mobile__
    menuBar()->setNativeMenuBar(false);
dogmaphobic's avatar
dogmaphobic committed
165
#endif
dogmaphobic's avatar
dogmaphobic committed
166

167 168 169
#ifdef UNITTEST_BUILD
    QAction* qmlTestAction = new QAction("Test QML palette and controls", NULL);
    connect(qmlTestAction, &QAction::triggered, this, &MainWindow::_showQmlTestWidget);
170
    _ui.menuWidgets->addAction(qmlTestAction);
171
#endif
172

173 174 175
    connect(qgcApp()->toolbox()->corePlugin(), &QGCCorePlugin::showAdvancedUIChanged, this, &MainWindow::_showAdvancedUIChanged);
    _showAdvancedUIChanged(qgcApp()->toolbox()->corePlugin()->showAdvancedUI());

dogmaphobic's avatar
dogmaphobic committed
176
    // Status Bar
177
    setStatusBar(new QStatusBar(this));
178
    statusBar()->setSizeGripEnabled(true);
179

180
#ifndef __mobile__
181
    emit initStatusChanged(tr("Building common widgets."), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
182
    _buildCommonWidgets();
183
    emit initStatusChanged(tr("Building common actions"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
184
#endif
185

186 187
    // Create actions
    connectCommonActions();
188

189
    // Set low power mode
dogmaphobic's avatar
dogmaphobic committed
190
    enableLowPowerMode(_lowPowerMode);
191
    emit initStatusChanged(tr("Restoring last view state"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
192

dogmaphobic's avatar
dogmaphobic committed
193
#ifndef __mobile__
194

195
    // Restore the window position and size
dogmaphobic's avatar
dogmaphobic committed
196 197
    emit initStatusChanged(tr("Restoring last window size"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
    if (settings.contains(_getWindowGeometryKey()))
198
    {
dogmaphobic's avatar
dogmaphobic committed
199
        restoreGeometry(settings.value(_getWindowGeometryKey()).toByteArray());
200 201 202 203
    }
    else
    {
        // Adjust the size
204 205 206
        QScreen* scr = QApplication::primaryScreen();
        QSize scrSize = scr->availableSize();
        if (scrSize.width() <= 1280)
207
        {
208
            resize(scrSize.width(), scrSize.height());
209 210 211
        }
        else
        {
212 213 214
            int w = scrSize.width()  > 1600 ? 1600 : scrSize.width();
            int h = scrSize.height() >  800 ?  800 : scrSize.height();
            resize(w, h);
215
            move((scrSize.width() - w) / 2, (scrSize.height() - h) / 2);
216 217
        }
    }
218 219
#endif

220
    connect(_ui.actionStatusBar,  &QAction::triggered, this, &MainWindow::showStatusBarCallback);
221

222
    connect(&windowNameUpdateTimer, &QTimer::timeout, this, &MainWindow::configureWindowName);
223
    windowNameUpdateTimer.start(15000);
224
    emit initStatusChanged(tr("Done"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
225 226

    if (!qgcApp()->runningUnitTests()) {
227 228
        _ui.actionStatusBar->setChecked(_showStatusBar);
        showStatusBarCallback(_showStatusBar);
dogmaphobic's avatar
dogmaphobic committed
229
#ifdef __mobile__
230 231
        menuBar()->hide();
#endif
232 233
        show();
    }
234

235 236 237
#ifndef __mobile__
    _loadVisibleWidgetsSettings();
#endif
238 239 240 241 242
    //-- Enable message handler display of messages in main window
    UASMessageHandler* msgHandler = qgcApp()->toolbox()->uasMessageHandler();
    if(msgHandler) {
        msgHandler->showErrorsInToolbar();
    }
243 244 245 246
}

MainWindow::~MainWindow()
{
247 248 249 250 251 252 253
    if (_mavlinkDecoder) {
        // Enforce thread-safe shutdown of the mavlink decoder
        _mavlinkDecoder->finish();
        _mavlinkDecoder->wait(1000);
        _mavlinkDecoder->deleteLater();
        _mavlinkDecoder = NULL;
    }
254

255 256 257 258
    // This needs to happen before we get into the QWidget dtor
    // otherwise  the QML engine reads freed data and tries to
    // destroy MainWindow a second time.
    delete _mainQmlWidgetHolder;
Don Gagne's avatar
Don Gagne committed
259
    _instance = NULL;
260 261
}

dogmaphobic's avatar
dogmaphobic committed
262
QString MainWindow::_getWindowGeometryKey()
263 264 265 266
{
    return "_geometry";
}

267
#ifndef __mobile__
268
MAVLinkDecoder* MainWindow::_mavLinkDecoderInstance(void)
269
{
270
    if (!_mavlinkDecoder) {
271 272 273
        _mavlinkDecoder = new MAVLinkDecoder(qgcApp()->toolbox()->mavlinkProtocol());
        connect(_mavlinkDecoder, &MAVLinkDecoder::valueChanged, this, &MainWindow::valueChanged);
    }
274

275 276 277 278 279
    return _mavlinkDecoder;
}

void MainWindow::_buildCommonWidgets(void)
{
280
    // Log player
dogmaphobic's avatar
dogmaphobic committed
281
    // TODO: Make this optional with a preferences setting or under a "View" menu
Don Gagne's avatar
Don Gagne committed
282
    logPlayer = new QGCMAVLinkLogPlayer(statusBar());
283
    statusBar()->addPermanentWidget(logPlayer);
284

Don Gagne's avatar
Don Gagne committed
285
    // Populate widget menu
286 287
    for (int i = 0, end = ARRAY_SIZE(rgDockWidgetNames); i < end; i++) {

288
        const char* pDockWidgetName = rgDockWidgetNames[i];
289

290
        // Add to menu
Don Gagne's avatar
Don Gagne committed
291
        QAction* action = new QAction(pDockWidgetName, this);
292
        action->setCheckable(true);
293
        action->setData(i);
294 295 296
        connect(action, &QAction::triggered, this, &MainWindow::_showDockWidgetAction);
        _ui.menuWidgets->addAction(action);
        _mapName2Action[pDockWidgetName] = action;
297
    }
298
}
299

300 301
/// Shows or hides the specified dock widget, creating if necessary
void MainWindow::_showDockWidget(const QString& name, bool show)
302
{
303
    // Create the inner widget if we need to
304
    if (!_mapName2DockWidget.contains(name)) {
dogmaphobic's avatar
dogmaphobic committed
305
        if(!_createInnerDockWidget(name)) {
DonLakeFlyer's avatar
DonLakeFlyer committed
306
            qWarning() << "Trying to load non existent widget:" << name;
dogmaphobic's avatar
dogmaphobic committed
307 308
            return;
        }
309
    }
310
    Q_ASSERT(_mapName2DockWidget.contains(name));
311
    QGCDockWidget* dockWidget = _mapName2DockWidget[name];
312 313
    Q_ASSERT(dockWidget);
    dockWidget->setVisible(show);
314 315
    Q_ASSERT(_mapName2Action.contains(name));
    _mapName2Action[name]->setChecked(show);
316 317 318
}

/// Creates the specified inner dock widget and adds to the QDockWidget
dogmaphobic's avatar
dogmaphobic committed
319
bool MainWindow::_createInnerDockWidget(const QString& widgetName)
320
{
321
    QGCDockWidget* widget = NULL;
322
    QAction *action = _mapName2Action[widgetName];
dogmaphobic's avatar
dogmaphobic committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    if(action) {
        switch(action->data().toInt()) {
            case MAVLINK_INSPECTOR:
                widget = new QGCMAVLinkInspector(widgetName, action, qgcApp()->toolbox()->mavlinkProtocol(),this);
                break;
            case CUSTOM_COMMAND:
                widget = new CustomCommandWidget(widgetName, action, this);
                break;
            case ONBOARD_FILES:
                widget = new QGCUASFileViewMulti(widgetName, action, this);
                break;
            case HIL_CONFIG:
                widget = new HILDockWidget(widgetName, action, this);
                break;
            case ANALYZE:
338
                widget = new Linecharts(widgetName, action, _mavLinkDecoderInstance(), this);
dogmaphobic's avatar
dogmaphobic committed
339 340 341 342 343
                break;
        }
        if(widget) {
            _mapName2DockWidget[widgetName] = widget;
        }
344
    }
dogmaphobic's avatar
dogmaphobic committed
345
    return widget != NULL;
346
}
347

348 349
void MainWindow::_hideAllDockWidgets(void)
{
350
    foreach(QGCDockWidget* dockWidget, _mapName2DockWidget) {
351 352 353 354 355 356
        dockWidget->setVisible(false);
    }
}

void MainWindow::_showDockWidgetAction(bool show)
{
357
    QAction* action = qobject_cast<QAction*>(QObject::sender());
358
    Q_ASSERT(action);
359
    _showDockWidget(rgDockWidgetNames[action->data().toInt()], show);
360 361 362
}
#endif

363 364 365 366 367 368
void MainWindow::showStatusBarCallback(bool checked)
{
    _showStatusBar = checked;
    checked ? statusBar()->show() : statusBar()->hide();
}

369
void MainWindow::_reallyClose(void)
370
{
371 372
    _forceClose = true;
    close();
373 374
}

375 376
void MainWindow::closeEvent(QCloseEvent *event)
{
377
    if (!_forceClose) {
Ricardo de Almeida Gonzaga's avatar
Ricardo de Almeida Gonzaga committed
378
        // Attempt close from within the root Qml item
379
        qgcApp()->qmlAttemptWindowClose();
380 381
        event->ignore();
        return;
382 383 384
    }

    // Should not be any active connections
385
    if (qgcApp()->toolbox()->multiVehicleManager()->activeVehicle()) {
Don Gagne's avatar
Don Gagne committed
386 387
        qWarning() << "All links should be disconnected by now";
    }
388

389
    _storeCurrentViewState();
390
    storeSettings();
391 392

    emit mainWindowClosed();
393 394 395 396
}

void MainWindow::loadSettings()
{
397
    // Why the screaming?
398
    QSettings settings;
399
    settings.beginGroup(MAIN_SETTINGS_GROUP);
400 401
    _lowPowerMode   = settings.value("LOW_POWER_MODE",      _lowPowerMode).toBool();
    _showStatusBar  = settings.value("SHOW_STATUSBAR",      _showStatusBar).toBool();
402 403 404 405 406 407
    settings.endGroup();
}

void MainWindow::storeSettings()
{
    QSettings settings;
408
    settings.beginGroup(MAIN_SETTINGS_GROUP);
409 410
    settings.setValue("LOW_POWER_MODE",     _lowPowerMode);
    settings.setValue("SHOW_STATUSBAR",     _showStatusBar);
411
    settings.endGroup();
dogmaphobic's avatar
dogmaphobic committed
412
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
413

414 415 416
#ifndef __mobile__
    _storeVisibleWidgetsSettings();
#endif
417 418 419 420
}

void MainWindow::configureWindowName()
{
421
    setWindowTitle(qApp->applicationName() + " " + qApp->applicationVersion());
422 423 424 425 426 427 428 429
}

/**
* @brief Create all actions associated to the main window
*
**/
void MainWindow::connectCommonActions()
{
430
    // Connect internal actions
431
    connect(qgcApp()->toolbox()->multiVehicleManager(), &MultiVehicleManager::vehicleAdded, this, &MainWindow::_vehicleAdded);
432
    connect(this, &MainWindow::reallyClose, this, &MainWindow::_reallyClose, Qt::QueuedConnection); // Queued to allow closeEvent to fully unwind before _reallyClose is called
433 434
}

Don Gagne's avatar
Don Gagne committed
435
void MainWindow::_openUrl(const QString& url, const QString& errorMessage)
436
{
Don Gagne's avatar
Don Gagne committed
437
    if(!QDesktopServices::openUrl(QUrl(url))) {
438
        qgcApp()->showMessage(QString("Could not open information in browser: %1").arg(errorMessage));
439 440 441
    }
}

442
void MainWindow::_vehicleAdded(Vehicle* vehicle)
443
{
444
    connect(vehicle->uas(), &UAS::valueChanged, this, &MainWindow::valueChanged);
445 446
}

447 448
/// Stores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_storeCurrentViewState(void)
449
{
Don Gagne's avatar
Don Gagne committed
450
#ifndef __mobile__
451 452
    foreach(QGCDockWidget* dockWidget, _mapName2DockWidget) {
        dockWidget->saveSettings();
453
    }
Don Gagne's avatar
Don Gagne committed
454
#endif
455

dogmaphobic's avatar
dogmaphobic committed
456
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
457 458
}

459 460 461 462 463 464 465 466 467
/// @brief Saves the last used connection
void MainWindow::saveLastUsedConnection(const QString connection)
{
    QSettings settings;
    QString key(MAIN_SETTINGS_GROUP);
    key += "/LAST_CONNECTION";
    settings.setValue(key, connection);
}

468 469 470 471 472 473
#ifdef UNITTEST_BUILD
void MainWindow::_showQmlTestWidget(void)
{
    new QmlTestWidget();
}
#endif
474 475 476 477 478

#ifndef __mobile__
void MainWindow::_loadVisibleWidgetsSettings(void)
{
    QSettings settings;
479

480
    QString widgets = settings.value(_visibleWidgetsKey).toString();
481

482 483
    if (!widgets.isEmpty()) {
        QStringList nameList = widgets.split(",");
484

485
        foreach (const QString &name, nameList) {
486 487 488 489 490 491 492 493 494
            _showDockWidget(name, true);
        }
    }
}

void MainWindow::_storeVisibleWidgetsSettings(void)
{
    QString widgetNames;
    bool firstWidget = true;
495

496
    foreach (const QString &name, _mapName2DockWidget.keys()) {
497 498 499 500 501 502
        if (_mapName2DockWidget[name]->isVisible()) {
            if (!firstWidget) {
                widgetNames += ",";
            } else {
                firstWidget = false;
            }
503

504 505 506
            widgetNames += name;
        }
    }
507

508
    QSettings settings;
509

510 511 512
    settings.setValue(_visibleWidgetsKey, widgetNames);
}
#endif
513

Don Gagne's avatar
Don Gagne committed
514
QObject* MainWindow::rootQmlObject(void)
515
{
Don Gagne's avatar
Don Gagne committed
516
    return _mainQmlWidgetHolder->getRootObject();
517
}
518 519 520 521 522 523 524 525 526 527

void MainWindow::_showAdvancedUIChanged(bool advanced)
{
    if (advanced) {
        menuBar()->addMenu(_ui.menuFile);
        menuBar()->addMenu(_ui.menuWidgets);
    } else {
        menuBar()->clear();
    }
}