MainWindow.cc 17.3 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 112 113 114 115
    : _mavlinkDecoder       (NULL)
    , _lowPowerMode         (false)
    , _showStatusBar        (false)
    , _mainQmlWidgetHolder  (NULL)
    , _forceClose           (false)
116
{
Don Gagne's avatar
Don Gagne committed
117
    _instance = this;
118

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

dogmaphobic's avatar
dogmaphobic committed
207
#ifndef __mobile__
208

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

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

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

    if (!qgcApp()->runningUnitTests()) {
241 242
        _ui.actionStatusBar->setChecked(_showStatusBar);
        showStatusBarCallback(_showStatusBar);
dogmaphobic's avatar
dogmaphobic committed
243
#ifdef __mobile__
244 245
        menuBar()->hide();
#endif
246
        show();
dogmaphobic's avatar
dogmaphobic committed
247
#ifdef __macos__
dogmaphobic's avatar
dogmaphobic committed
248 249 250 251 252 253 254 255 256 257 258 259 260 261
        // 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
262
    }
263

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

MainWindow::~MainWindow()
{
276 277 278 279 280 281 282
    if (_mavlinkDecoder) {
        // Enforce thread-safe shutdown of the mavlink decoder
        _mavlinkDecoder->finish();
        _mavlinkDecoder->wait(1000);
        _mavlinkDecoder->deleteLater();
        _mavlinkDecoder = NULL;
    }
283

284 285 286 287
    // 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
288
    _instance = NULL;
289 290
}

dogmaphobic's avatar
dogmaphobic committed
291
QString MainWindow::_getWindowGeometryKey()
292 293 294 295
{
    return "_geometry";
}

296
#ifndef __mobile__
297
MAVLinkDecoder* MainWindow::_mavLinkDecoderInstance(void)
298
{
299
    if (!_mavlinkDecoder) {
300 301 302
        _mavlinkDecoder = new MAVLinkDecoder(qgcApp()->toolbox()->mavlinkProtocol());
        connect(_mavlinkDecoder, &MAVLinkDecoder::valueChanged, this, &MainWindow::valueChanged);
    }
303

304 305 306 307 308
    return _mavlinkDecoder;
}

void MainWindow::_buildCommonWidgets(void)
{
309
    // Log player
dogmaphobic's avatar
dogmaphobic committed
310
    // TODO: Make this optional with a preferences setting or under a "View" menu
Don Gagne's avatar
Don Gagne committed
311
    logPlayer = new QGCMAVLinkLogPlayer(statusBar());
312
    statusBar()->addPermanentWidget(logPlayer);
313

Don Gagne's avatar
Don Gagne committed
314
    // Populate widget menu
315
    for (int i = 0, end = ARRAY_SIZE(rgDockWidgetNames); i < end; i++) {
Don Gagne's avatar
Don Gagne committed
316 317 318 319
        if (i == ONBOARD_FILES) {
            // Temporarily removed until twe can fix all the problems with it
            continue;
        }
320

321
        const char* pDockWidgetName = rgDockWidgetNames[i];
322

323
        // Add to menu
Don Gagne's avatar
Don Gagne committed
324
        QAction* action = new QAction(pDockWidgetName, this);
325
        action->setCheckable(true);
326
        action->setData(i);
327 328 329
        connect(action, &QAction::triggered, this, &MainWindow::_showDockWidgetAction);
        _ui.menuWidgets->addAction(action);
        _mapName2Action[pDockWidgetName] = action;
330
    }
331
}
332

333 334
/// Shows or hides the specified dock widget, creating if necessary
void MainWindow::_showDockWidget(const QString& name, bool show)
335
{
Don Gagne's avatar
Don Gagne committed
336 337 338 339 340
    if (name == rgDockWidgetNames[ONBOARD_FILES]) {
        // Temporarily disabled due to bugs
        return;
    }

341
    // Create the inner widget if we need to
342
    if (!_mapName2DockWidget.contains(name)) {
dogmaphobic's avatar
dogmaphobic committed
343
        if(!_createInnerDockWidget(name)) {
DonLakeFlyer's avatar
DonLakeFlyer committed
344
            qWarning() << "Trying to load non existent widget:" << name;
dogmaphobic's avatar
dogmaphobic committed
345 346
            return;
        }
347
    }
348
    Q_ASSERT(_mapName2DockWidget.contains(name));
349
    QGCDockWidget* dockWidget = _mapName2DockWidget[name];
350 351
    Q_ASSERT(dockWidget);
    dockWidget->setVisible(show);
352 353
    Q_ASSERT(_mapName2Action.contains(name));
    _mapName2Action[name]->setChecked(show);
354 355 356
}

/// Creates the specified inner dock widget and adds to the QDockWidget
dogmaphobic's avatar
dogmaphobic committed
357
bool MainWindow::_createInnerDockWidget(const QString& widgetName)
358
{
359
    QGCDockWidget* widget = NULL;
360
    QAction *action = _mapName2Action[widgetName];
dogmaphobic's avatar
dogmaphobic committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    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:
376
                widget = new Linecharts(widgetName, action, _mavLinkDecoderInstance(), this);
dogmaphobic's avatar
dogmaphobic committed
377 378 379 380 381
                break;
        }
        if(widget) {
            _mapName2DockWidget[widgetName] = widget;
        }
382
    }
dogmaphobic's avatar
dogmaphobic committed
383
    return widget != NULL;
384
}
385

386 387
void MainWindow::_hideAllDockWidgets(void)
{
388
    foreach(QGCDockWidget* dockWidget, _mapName2DockWidget) {
389 390 391 392 393 394
        dockWidget->setVisible(false);
    }
}

void MainWindow::_showDockWidgetAction(bool show)
{
395
    QAction* action = qobject_cast<QAction*>(QObject::sender());
396
    Q_ASSERT(action);
397
    _showDockWidget(rgDockWidgetNames[action->data().toInt()], show);
398 399 400
}
#endif

401 402 403 404 405 406
void MainWindow::showStatusBarCallback(bool checked)
{
    _showStatusBar = checked;
    checked ? statusBar()->show() : statusBar()->hide();
}

407
void MainWindow::reallyClose(void)
408
{
409 410
    _forceClose = true;
    close();
411 412
}

413 414
void MainWindow::closeEvent(QCloseEvent *event)
{
415
    if (!_forceClose) {
Ricardo de Almeida Gonzaga's avatar
Ricardo de Almeida Gonzaga committed
416
        // Attempt close from within the root Qml item
417
        qgcApp()->qmlAttemptWindowClose();
418 419
        event->ignore();
        return;
420 421 422
    }

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

427
    _storeCurrentViewState();
428
    storeSettings();
429 430

    emit mainWindowClosed();
431 432 433 434
}

void MainWindow::loadSettings()
{
435
    // Why the screaming?
436
    QSettings settings;
437
    settings.beginGroup(MAIN_SETTINGS_GROUP);
438 439
    _lowPowerMode   = settings.value("LOW_POWER_MODE",      _lowPowerMode).toBool();
    _showStatusBar  = settings.value("SHOW_STATUSBAR",      _showStatusBar).toBool();
440 441 442 443 444 445
    settings.endGroup();
}

void MainWindow::storeSettings()
{
    QSettings settings;
446
    settings.beginGroup(MAIN_SETTINGS_GROUP);
447 448
    settings.setValue("LOW_POWER_MODE",     _lowPowerMode);
    settings.setValue("SHOW_STATUSBAR",     _showStatusBar);
449
    settings.endGroup();
dogmaphobic's avatar
dogmaphobic committed
450
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
451

452 453 454
#ifndef __mobile__
    _storeVisibleWidgetsSettings();
#endif
455 456 457 458
}

void MainWindow::configureWindowName()
{
459
    setWindowTitle(qApp->applicationName() + " " + qApp->applicationVersion());
460 461 462 463 464 465 466 467
}

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

Don Gagne's avatar
Don Gagne committed
472
void MainWindow::_openUrl(const QString& url, const QString& errorMessage)
473
{
Don Gagne's avatar
Don Gagne committed
474
    if(!QDesktopServices::openUrl(QUrl(url))) {
475
        qgcApp()->showMessage(QString("Could not open information in browser: %1").arg(errorMessage));
476 477 478
    }
}

479
void MainWindow::_vehicleAdded(Vehicle* vehicle)
480
{
481
    connect(vehicle->uas(), &UAS::valueChanged, this, &MainWindow::valueChanged);
482 483
}

484 485
/// Stores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_storeCurrentViewState(void)
486
{
Don Gagne's avatar
Don Gagne committed
487
#ifndef __mobile__
488 489
    foreach(QGCDockWidget* dockWidget, _mapName2DockWidget) {
        dockWidget->saveSettings();
490
    }
Don Gagne's avatar
Don Gagne committed
491
#endif
492

dogmaphobic's avatar
dogmaphobic committed
493
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
494 495
}

496 497 498 499 500 501 502 503 504
/// @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);
}

505
#ifdef QGC_MOUSE_ENABLED_LINUX
506 507 508
bool MainWindow::x11Event(XEvent *event)
{
    emit x11EventOccured(event);
509
    return false;
510
}
511
#endif // QGC_MOUSE_ENABLED_LINUX
512 513 514 515 516 517 518

#ifdef UNITTEST_BUILD
void MainWindow::_showQmlTestWidget(void)
{
    new QmlTestWidget();
}
#endif
519 520 521 522 523

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

525
    QString widgets = settings.value(_visibleWidgetsKey).toString();
526

527 528
    if (!widgets.isEmpty()) {
        QStringList nameList = widgets.split(",");
529

530
        foreach (const QString &name, nameList) {
531 532 533 534 535 536 537 538 539
            _showDockWidget(name, true);
        }
    }
}

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

541
    foreach (const QString &name, _mapName2DockWidget.keys()) {
542 543 544 545 546 547
        if (_mapName2DockWidget[name]->isVisible()) {
            if (!firstWidget) {
                widgetNames += ",";
            } else {
                firstWidget = false;
            }
548

549 550 551
            widgetNames += name;
        }
    }
552

553
    QSettings settings;
554

555 556 557
    settings.setValue(_visibleWidgetsKey, widgetNames);
}
#endif
558

Don Gagne's avatar
Don Gagne committed
559
QObject* MainWindow::rootQmlObject(void)
560
{
Don Gagne's avatar
Don Gagne committed
561
    return _mainQmlWidgetHolder->getRootObject();
562
}
563 564 565 566 567 568 569 570 571 572

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