MainWindow.cc 15.2 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

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

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
    : _mavlinkDecoder       (nullptr)
110 111
    , _lowPowerMode         (false)
    , _showStatusBar        (false)
112
    , _mainQmlWidgetHolder  (nullptr)
113
    , _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);
    configureWindowName();
135

136 137
    // Setup central widget with a layout to hold the views
    _centralLayout = new QVBoxLayout();
138
    _centralLayout->setContentsMargins(0, 0, 0, 0);
139
    centralWidget()->setLayout(_centralLayout);
140

141 142
    //-- Allow plugin to initialize main QML Widget
    _mainQmlWidgetHolder = qgcApp()->toolbox()->corePlugin()->createMainQmlWidgetHolder(_centralLayout, this);
143

dogmaphobic's avatar
dogmaphobic committed
144 145
    // Image provider
    QQuickImageProvider* pImgProvider = dynamic_cast<QQuickImageProvider*>(qgcApp()->toolbox()->imageProvider());
146
    _mainQmlWidgetHolder->getEngine()->addImageProvider(QStringLiteral("QGCImages"), pImgProvider);
dogmaphobic's avatar
dogmaphobic committed
147

148
    // Set dock options
149
    setDockOptions(nullptr);
150
    // Setup corners
151
    setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
152

dogmaphobic's avatar
dogmaphobic committed
153 154 155
    // On Mobile devices, we don't want any main menus at all.
#ifdef __mobile__
    menuBar()->setNativeMenuBar(false);
dogmaphobic's avatar
dogmaphobic committed
156
#endif
dogmaphobic's avatar
dogmaphobic committed
157

158
#ifdef UNITTEST_BUILD
159
    QAction* qmlTestAction = new QAction("Test QML palette and controls", nullptr);
160
    connect(qmlTestAction, &QAction::triggered, this, &MainWindow::_showQmlTestWidget);
161
    _ui.menuWidgets->addAction(qmlTestAction);
162
#endif
163

164 165 166
    connect(qgcApp()->toolbox()->corePlugin(), &QGCCorePlugin::showAdvancedUIChanged, this, &MainWindow::_showAdvancedUIChanged);
    _showAdvancedUIChanged(qgcApp()->toolbox()->corePlugin()->showAdvancedUI());

dogmaphobic's avatar
dogmaphobic committed
167
    // Status Bar
168
    setStatusBar(new QStatusBar(this));
169
    statusBar()->setSizeGripEnabled(true);
170

171
#ifndef __mobile__
172
    emit initStatusChanged(tr("Building common widgets."), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
173
    _buildCommonWidgets();
174
    emit initStatusChanged(tr("Building common actions"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
175
#endif
176

177 178
    // Create actions
    connectCommonActions();
179

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

dogmaphobic's avatar
dogmaphobic committed
184
#ifndef __mobile__
185

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

211
    connect(_ui.actionStatusBar,  &QAction::triggered, this, &MainWindow::showStatusBarCallback);
212

213
    connect(&windowNameUpdateTimer, &QTimer::timeout, this, &MainWindow::configureWindowName);
214
    windowNameUpdateTimer.start(15000);
215
    emit initStatusChanged(tr("Done"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
216 217

    if (!qgcApp()->runningUnitTests()) {
218 219
        _ui.actionStatusBar->setChecked(_showStatusBar);
        showStatusBarCallback(_showStatusBar);
dogmaphobic's avatar
dogmaphobic committed
220
#ifdef __mobile__
221 222
        menuBar()->hide();
#endif
223 224
        show();
    }
225

226 227 228
#ifndef __mobile__
    _loadVisibleWidgetsSettings();
#endif
229 230 231 232 233
    //-- Enable message handler display of messages in main window
    UASMessageHandler* msgHandler = qgcApp()->toolbox()->uasMessageHandler();
    if(msgHandler) {
        msgHandler->showErrorsInToolbar();
    }
234 235 236 237
}

MainWindow::~MainWindow()
{
238 239 240 241 242
    if (_mavlinkDecoder) {
        // Enforce thread-safe shutdown of the mavlink decoder
        _mavlinkDecoder->finish();
        _mavlinkDecoder->wait(1000);
        _mavlinkDecoder->deleteLater();
243
        _mavlinkDecoder = nullptr;
244
    }
245

246 247 248 249
    // 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;
250
    _instance = nullptr;
251 252
}

dogmaphobic's avatar
dogmaphobic committed
253
QString MainWindow::_getWindowGeometryKey()
254 255 256 257
{
    return "_geometry";
}

258
#ifndef __mobile__
259
MAVLinkDecoder* MainWindow::_mavLinkDecoderInstance(void)
260
{
261
    if (!_mavlinkDecoder) {
262 263 264
        _mavlinkDecoder = new MAVLinkDecoder(qgcApp()->toolbox()->mavlinkProtocol());
        connect(_mavlinkDecoder, &MAVLinkDecoder::valueChanged, this, &MainWindow::valueChanged);
    }
265

266 267 268 269 270
    return _mavlinkDecoder;
}

void MainWindow::_buildCommonWidgets(void)
{
271
    // Log player
dogmaphobic's avatar
dogmaphobic committed
272
    // TODO: Make this optional with a preferences setting or under a "View" menu
Don Gagne's avatar
Don Gagne committed
273
    logPlayer = new QGCMAVLinkLogPlayer(statusBar());
274
    statusBar()->addPermanentWidget(logPlayer);
275

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

279
        const char* pDockWidgetName = rgDockWidgetNames[i];
280

281
        // Add to menu
Don Gagne's avatar
Don Gagne committed
282
        QAction* action = new QAction(pDockWidgetName, this);
283
        action->setCheckable(true);
284
        action->setData(i);
285 286 287
        connect(action, &QAction::triggered, this, &MainWindow::_showDockWidgetAction);
        _ui.menuWidgets->addAction(action);
        _mapName2Action[pDockWidgetName] = action;
288
    }
289
}
290

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

/// Creates the specified inner dock widget and adds to the QDockWidget
dogmaphobic's avatar
dogmaphobic committed
310
bool MainWindow::_createInnerDockWidget(const QString& widgetName)
311
{
312
    QGCDockWidget* widget = nullptr;
313
    QAction *action = _mapName2Action[widgetName];
dogmaphobic's avatar
dogmaphobic committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    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:
329
                widget = new Linecharts(widgetName, action, _mavLinkDecoderInstance(), this);
dogmaphobic's avatar
dogmaphobic committed
330 331 332 333 334
                break;
        }
        if(widget) {
            _mapName2DockWidget[widgetName] = widget;
        }
335
    }
336
    return widget != nullptr;
337
}
338

339 340
void MainWindow::_hideAllDockWidgets(void)
{
341
    for(QGCDockWidget* dockWidget: _mapName2DockWidget) {
342 343 344 345 346 347
        dockWidget->setVisible(false);
    }
}

void MainWindow::_showDockWidgetAction(bool show)
{
348
    QAction* action = qobject_cast<QAction*>(QObject::sender());
349
    Q_ASSERT(action);
350
    _showDockWidget(rgDockWidgetNames[action->data().toInt()], show);
351 352 353
}
#endif

354 355 356 357 358 359
void MainWindow::showStatusBarCallback(bool checked)
{
    _showStatusBar = checked;
    checked ? statusBar()->show() : statusBar()->hide();
}

360
void MainWindow::_reallyClose(void)
361
{
362 363
    _forceClose = true;
    close();
364 365
}

366 367
void MainWindow::closeEvent(QCloseEvent *event)
{
368
    if (!_forceClose) {
Ricardo de Almeida Gonzaga's avatar
Ricardo de Almeida Gonzaga committed
369
        // Attempt close from within the root Qml item
370
        qgcApp()->qmlAttemptWindowClose();
371 372
        event->ignore();
        return;
373 374 375
    }

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

380
    _storeCurrentViewState();
381
    storeSettings();
382 383

    emit mainWindowClosed();
384 385 386 387
}

void MainWindow::loadSettings()
{
388
    // Why the screaming?
389
    QSettings settings;
390
    settings.beginGroup(MAIN_SETTINGS_GROUP);
391 392
    _lowPowerMode   = settings.value("LOW_POWER_MODE",      _lowPowerMode).toBool();
    _showStatusBar  = settings.value("SHOW_STATUSBAR",      _showStatusBar).toBool();
393 394 395 396 397 398
    settings.endGroup();
}

void MainWindow::storeSettings()
{
    QSettings settings;
399
    settings.beginGroup(MAIN_SETTINGS_GROUP);
400 401
    settings.setValue("LOW_POWER_MODE",     _lowPowerMode);
    settings.setValue("SHOW_STATUSBAR",     _showStatusBar);
402
    settings.endGroup();
dogmaphobic's avatar
dogmaphobic committed
403
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
404

405 406 407
#ifndef __mobile__
    _storeVisibleWidgetsSettings();
#endif
408 409 410 411
}

void MainWindow::configureWindowName()
{
412
    setWindowTitle(qApp->applicationName() + " " + qApp->applicationVersion());
413 414 415 416 417 418 419 420
}

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

Don Gagne's avatar
Don Gagne committed
426
void MainWindow::_openUrl(const QString& url, const QString& errorMessage)
427
{
Don Gagne's avatar
Don Gagne committed
428
    if(!QDesktopServices::openUrl(QUrl(url))) {
429
        qgcApp()->showMessage(QString("Could not open information in browser: %1").arg(errorMessage));
430 431 432
    }
}

433
void MainWindow::_vehicleAdded(Vehicle* vehicle)
434
{
435
    connect(vehicle->uas(), &UAS::valueChanged, this, &MainWindow::valueChanged);
436 437
}

438 439
/// Stores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_storeCurrentViewState(void)
440
{
Don Gagne's avatar
Don Gagne committed
441
#ifndef __mobile__
442
    for(QGCDockWidget* dockWidget: _mapName2DockWidget) {
443
        dockWidget->saveSettings();
444
    }
Don Gagne's avatar
Don Gagne committed
445
#endif
446

dogmaphobic's avatar
dogmaphobic committed
447
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
448 449
}

450 451 452 453 454 455 456 457 458
/// @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);
}

459 460 461 462 463 464
#ifdef UNITTEST_BUILD
void MainWindow::_showQmlTestWidget(void)
{
    new QmlTestWidget();
}
#endif
465 466 467 468 469

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

471
    QString widgets = settings.value(_visibleWidgetsKey).toString();
472

473 474
    if (!widgets.isEmpty()) {
        QStringList nameList = widgets.split(",");
475

476
        for (const QString &name: nameList) {
477 478 479 480 481 482 483 484 485
            _showDockWidget(name, true);
        }
    }
}

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

487
    for (const QString &name: _mapName2DockWidget.keys()) {
488 489 490 491 492 493
        if (_mapName2DockWidget[name]->isVisible()) {
            if (!firstWidget) {
                widgetNames += ",";
            } else {
                firstWidget = false;
            }
494

495 496 497
            widgetNames += name;
        }
    }
498

499
    QSettings settings;
500

501 502 503
    settings.setValue(_visibleWidgetsKey, widgetNames);
}
#endif
504

Don Gagne's avatar
Don Gagne committed
505
QObject* MainWindow::rootQmlObject(void)
506
{
507
    return _mainQmlWidgetHolder ? _mainQmlWidgetHolder->getRootObject() : nullptr;
508
}
509 510 511 512 513 514 515 516 517 518

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