MainWindow.cc 17 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 33
#include "QGC.h"
#include "MAVLinkProtocol.h"
#include "MainWindow.h"
#include "GAudioOutput.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
    ONBOARD_FILES,
DonLakeFlyer's avatar
DonLakeFlyer committed
70
    DEPRECATED_WIDGET,
71
    HIL_CONFIG,
72
    ANALYZE
73 74 75 76 77 78
};

static const char *rgDockWidgetNames[] = {
    "MAVLink Inspector",
    "Custom Command",
    "Onboard Files",
DonLakeFlyer's avatar
DonLakeFlyer committed
79
    "Deprecated Widget",
80
    "HIL Config",
81
    "Analyze"
82 83 84
};

#define ARRAY_SIZE(ARRAY) (sizeof(ARRAY) / sizeof(ARRAY[0]))
85 86

static const char* _visibleWidgetsKey = "VisibleWidgets";
87
#endif
88

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

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

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

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

Don Gagne's avatar
Don Gagne committed
107 108 109
/// @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
110
MainWindow::MainWindow()
111
    : _lowPowerMode(false)
112
    , _showStatusBar(false)
113
    , _mainQmlWidgetHolder(NULL)
114
    , _forceClose(false)
115
{
Don Gagne's avatar
Don Gagne committed
116
    _instance = this;
117

118 119 120 121 122 123 124 125
    //-- 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";
    }

126 127 128 129
    // 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
130
    // Setup user interface
131
    loadSettings();
132
    emit initStatusChanged(tr("Setting up user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
133

dogmaphobic's avatar
dogmaphobic committed
134 135
    _ui.setupUi(this);
    // Make sure tool bar elements all fit before changing minimum width
dogmaphobic's avatar
dogmaphobic committed
136
    setMinimumWidth(1008);
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 155 156
    // Image provider
    QQuickImageProvider* pImgProvider = dynamic_cast<QQuickImageProvider*>(qgcApp()->toolbox()->imageProvider());
    _mainQmlWidgetHolder->getEngine()->addImageProvider(QLatin1String("QGCImages"), pImgProvider);

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 188
    // Create actions
    connectCommonActions();
    // Connect user interface devices
189
#ifdef QGC_MOUSE_ENABLED_WIN
190
    emit initStatusChanged(tr("Initializing 3D mouse interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
191 192
    mouseInput = new Mouse3DInput(this);
    mouse = new Mouse6dofInput(mouseInput);
193
#endif //QGC_MOUSE_ENABLED_WIN
194

195
#if QGC_MOUSE_ENABLED_LINUX
196
    emit initStatusChanged(tr("Initializing 3D mouse interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
197 198

    mouse = new Mouse6dofInput(this);
199
    connect(this, &MainWindow::x11EventOccured, mouse, &Mouse6dofInput::handleX11Event);
200
#endif //QGC_MOUSE_ENABLED_LINUX
201

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

dogmaphobic's avatar
dogmaphobic committed
206
#ifndef __mobile__
207

208
    // Restore the window position and size
dogmaphobic's avatar
dogmaphobic committed
209 210
    emit initStatusChanged(tr("Restoring last window size"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
    if (settings.contains(_getWindowGeometryKey()))
211
    {
dogmaphobic's avatar
dogmaphobic committed
212
        restoreGeometry(settings.value(_getWindowGeometryKey()).toByteArray());
213 214 215 216
    }
    else
    {
        // Adjust the size
217 218 219
        QScreen* scr = QApplication::primaryScreen();
        QSize scrSize = scr->availableSize();
        if (scrSize.width() <= 1280)
220
        {
221
            resize(scrSize.width(), scrSize.height());
222 223 224
        }
        else
        {
225 226 227
            int w = scrSize.width()  > 1600 ? 1600 : scrSize.width();
            int h = scrSize.height() >  800 ?  800 : scrSize.height();
            resize(w, h);
228
            move((scrSize.width() - w) / 2, (scrSize.height() - h) / 2);
229 230
        }
    }
231 232
#endif

233
    connect(_ui.actionStatusBar,  &QAction::triggered, this, &MainWindow::showStatusBarCallback);
234

235
    connect(&windowNameUpdateTimer, &QTimer::timeout, this, &MainWindow::configureWindowName);
236
    windowNameUpdateTimer.start(15000);
237
    emit initStatusChanged(tr("Done"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
238 239

    if (!qgcApp()->runningUnitTests()) {
240 241
        _ui.actionStatusBar->setChecked(_showStatusBar);
        showStatusBarCallback(_showStatusBar);
dogmaphobic's avatar
dogmaphobic committed
242
#ifdef __mobile__
243 244
        menuBar()->hide();
#endif
245
        show();
dogmaphobic's avatar
dogmaphobic committed
246
#ifdef __macos__
dogmaphobic's avatar
dogmaphobic committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260
        // TODO HACK
        // This is a really ugly hack. For whatever reason, by having a QQuickWidget inside a
        // QDockWidget (MainToolBar above), the main menu is not shown when the app first
        // starts. I looked everywhere and I could not find a solution. What I did notice was
        // that if any other window gets focus, the menu comes up when you come back to QGC.
        // That is, if you were to click on another window and then back to QGC, the menus
        // would appear. This hack below creates a 0x0 dialog and immediately closes it.
        // That works around the issue and it will do until I find the root of the problem.
        QDialog qd(this);
        qd.show();
        qd.raise();
        qd.activateWindow();
        qd.close();
#endif
261
    }
262

263 264 265
#ifndef __mobile__
    _loadVisibleWidgetsSettings();
#endif
266 267 268 269 270
    //-- Enable message handler display of messages in main window
    UASMessageHandler* msgHandler = qgcApp()->toolbox()->uasMessageHandler();
    if(msgHandler) {
        msgHandler->showErrorsInToolbar();
    }
271 272 273 274
}

MainWindow::~MainWindow()
{
275 276 277 278 279
    // Enforce thread-safe shutdown of the mavlink decoder
    mavlinkDecoder->finish();
    mavlinkDecoder->wait(1000);
    mavlinkDecoder->deleteLater();

280 281 282 283
    // 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
284
    _instance = NULL;
285 286
}

dogmaphobic's avatar
dogmaphobic committed
287
QString MainWindow::_getWindowGeometryKey()
288 289 290 291
{
    return "_geometry";
}

292
#ifndef __mobile__
293
void MainWindow::_buildCommonWidgets(void)
294 295
{
    // Add generic MAVLink decoder
296
    mavlinkDecoder = new MAVLinkDecoder(qgcApp()->toolbox()->mavlinkProtocol());
297
    connect(mavlinkDecoder.data(), &MAVLinkDecoder::valueChanged, this, &MainWindow::valueChanged);
298

299
    // Log player
dogmaphobic's avatar
dogmaphobic committed
300
    // TODO: Make this optional with a preferences setting or under a "View" menu
Don Gagne's avatar
Don Gagne committed
301
    logPlayer = new QGCMAVLinkLogPlayer(statusBar());
302
    statusBar()->addPermanentWidget(logPlayer);
303

Don Gagne's avatar
Don Gagne committed
304
    // Populate widget menu
305
    for (int i = 0, end = ARRAY_SIZE(rgDockWidgetNames); i < end; i++) {
Don Gagne's avatar
Don Gagne committed
306 307 308 309
        if (i == ONBOARD_FILES) {
            // Temporarily removed until twe can fix all the problems with it
            continue;
        }
310

311
        const char* pDockWidgetName = rgDockWidgetNames[i];
312

313
        // Add to menu
Don Gagne's avatar
Don Gagne committed
314
        QAction* action = new QAction(pDockWidgetName, this);
315
        action->setCheckable(true);
316
        action->setData(i);
317 318 319
        connect(action, &QAction::triggered, this, &MainWindow::_showDockWidgetAction);
        _ui.menuWidgets->addAction(action);
        _mapName2Action[pDockWidgetName] = action;
320
    }
321
}
322

323 324
/// Shows or hides the specified dock widget, creating if necessary
void MainWindow::_showDockWidget(const QString& name, bool show)
325
{
Don Gagne's avatar
Don Gagne committed
326 327 328 329 330
    if (name == rgDockWidgetNames[ONBOARD_FILES]) {
        // Temporarily disabled due to bugs
        return;
    }

331
    // Create the inner widget if we need to
332
    if (!_mapName2DockWidget.contains(name)) {
dogmaphobic's avatar
dogmaphobic committed
333
        if(!_createInnerDockWidget(name)) {
DonLakeFlyer's avatar
DonLakeFlyer committed
334
            qWarning() << "Trying to load non existent widget:" << name;
dogmaphobic's avatar
dogmaphobic committed
335 336
            return;
        }
337
    }
338
    Q_ASSERT(_mapName2DockWidget.contains(name));
339
    QGCDockWidget* dockWidget = _mapName2DockWidget[name];
340 341
    Q_ASSERT(dockWidget);
    dockWidget->setVisible(show);
342 343
    Q_ASSERT(_mapName2Action.contains(name));
    _mapName2Action[name]->setChecked(show);
344 345 346
}

/// Creates the specified inner dock widget and adds to the QDockWidget
dogmaphobic's avatar
dogmaphobic committed
347
bool MainWindow::_createInnerDockWidget(const QString& widgetName)
348
{
349
    QGCDockWidget* widget = NULL;
350
    QAction *action = _mapName2Action[widgetName];
dogmaphobic's avatar
dogmaphobic committed
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
    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:
                widget = new Linecharts(widgetName, action, mavlinkDecoder, this);
                break;
        }
        if(widget) {
            _mapName2DockWidget[widgetName] = widget;
        }
372
    }
dogmaphobic's avatar
dogmaphobic committed
373
    return widget != NULL;
374
}
375

376 377
void MainWindow::_hideAllDockWidgets(void)
{
378
    foreach(QGCDockWidget* dockWidget, _mapName2DockWidget) {
379 380 381 382 383 384
        dockWidget->setVisible(false);
    }
}

void MainWindow::_showDockWidgetAction(bool show)
{
385
    QAction* action = qobject_cast<QAction*>(QObject::sender());
386
    Q_ASSERT(action);
387
    _showDockWidget(rgDockWidgetNames[action->data().toInt()], show);
388 389 390
}
#endif

391 392 393 394 395 396
void MainWindow::showStatusBarCallback(bool checked)
{
    _showStatusBar = checked;
    checked ? statusBar()->show() : statusBar()->hide();
}

397
void MainWindow::reallyClose(void)
398
{
399 400
    _forceClose = true;
    close();
401 402
}

403 404
void MainWindow::closeEvent(QCloseEvent *event)
{
405
    if (!_forceClose) {
Ricardo de Almeida Gonzaga's avatar
Ricardo de Almeida Gonzaga committed
406
        // Attempt close from within the root Qml item
407
        qgcApp()->qmlAttemptWindowClose();
408 409
        event->ignore();
        return;
410 411 412
    }

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

417
    _storeCurrentViewState();
418
    storeSettings();
419 420

    emit mainWindowClosed();
421 422 423 424
}

void MainWindow::loadSettings()
{
425
    // Why the screaming?
426
    QSettings settings;
427
    settings.beginGroup(MAIN_SETTINGS_GROUP);
428 429
    _lowPowerMode   = settings.value("LOW_POWER_MODE",      _lowPowerMode).toBool();
    _showStatusBar  = settings.value("SHOW_STATUSBAR",      _showStatusBar).toBool();
430 431 432 433 434 435
    settings.endGroup();
}

void MainWindow::storeSettings()
{
    QSettings settings;
436
    settings.beginGroup(MAIN_SETTINGS_GROUP);
437 438
    settings.setValue("LOW_POWER_MODE",     _lowPowerMode);
    settings.setValue("SHOW_STATUSBAR",     _showStatusBar);
439
    settings.endGroup();
dogmaphobic's avatar
dogmaphobic committed
440
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
441

442 443 444
#ifndef __mobile__
    _storeVisibleWidgetsSettings();
#endif
445 446 447 448
}

void MainWindow::configureWindowName()
{
449
    setWindowTitle(qApp->applicationName() + " " + qApp->applicationVersion());
450 451 452 453 454 455 456 457
}

/**
* @brief Create all actions associated to the main window
*
**/
void MainWindow::connectCommonActions()
{
458
    // Connect internal actions
459
    connect(qgcApp()->toolbox()->multiVehicleManager(), &MultiVehicleManager::vehicleAdded, this, &MainWindow::_vehicleAdded);
460 461
}

Don Gagne's avatar
Don Gagne committed
462
void MainWindow::_openUrl(const QString& url, const QString& errorMessage)
463
{
Don Gagne's avatar
Don Gagne committed
464
    if(!QDesktopServices::openUrl(QUrl(url))) {
465
        qgcApp()->showMessage(QString("Could not open information in browser: %1").arg(errorMessage));
466 467 468
    }
}

469
void MainWindow::_vehicleAdded(Vehicle* vehicle)
470
{
471
    connect(vehicle->uas(), &UAS::valueChanged, this, &MainWindow::valueChanged);
472 473
}

474 475
/// Stores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_storeCurrentViewState(void)
476
{
Don Gagne's avatar
Don Gagne committed
477
#ifndef __mobile__
478 479
    foreach(QGCDockWidget* dockWidget, _mapName2DockWidget) {
        dockWidget->saveSettings();
480
    }
Don Gagne's avatar
Don Gagne committed
481
#endif
482

dogmaphobic's avatar
dogmaphobic committed
483
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
484 485
}

486 487 488 489 490 491 492 493 494
/// @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);
}

495
#ifdef QGC_MOUSE_ENABLED_LINUX
496 497 498
bool MainWindow::x11Event(XEvent *event)
{
    emit x11EventOccured(event);
499
    return false;
500
}
501
#endif // QGC_MOUSE_ENABLED_LINUX
502 503 504 505 506 507 508

#ifdef UNITTEST_BUILD
void MainWindow::_showQmlTestWidget(void)
{
    new QmlTestWidget();
}
#endif
509 510 511 512 513

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

515
    QString widgets = settings.value(_visibleWidgetsKey).toString();
516

517 518
    if (!widgets.isEmpty()) {
        QStringList nameList = widgets.split(",");
519

520
        foreach (const QString &name, nameList) {
521 522 523 524 525 526 527 528 529
            _showDockWidget(name, true);
        }
    }
}

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

531
    foreach (const QString &name, _mapName2DockWidget.keys()) {
532 533 534 535 536 537
        if (_mapName2DockWidget[name]->isVisible()) {
            if (!firstWidget) {
                widgetNames += ",";
            } else {
                firstWidget = false;
            }
538

539 540 541
            widgetNames += name;
        }
    }
542

543
    QSettings settings;
544

545 546 547
    settings.setValue(_visibleWidgetsKey, widgetNames);
}
#endif
548

Don Gagne's avatar
Don Gagne committed
549
QObject* MainWindow::rootQmlObject(void)
550
{
Don Gagne's avatar
Don Gagne committed
551
    return _mainQmlWidgetHolder->getRootObject();
552
}
553 554 555 556 557 558 559 560 561 562

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