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
#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
    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 316
    for (int i = 0, end = ARRAY_SIZE(rgDockWidgetNames); i < end; i++) {

317
        const char* pDockWidgetName = rgDockWidgetNames[i];
318

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

329 330
/// Shows or hides the specified dock widget, creating if necessary
void MainWindow::_showDockWidget(const QString& name, bool show)
331
{
332
    // Create the inner widget if we need to
333
    if (!_mapName2DockWidget.contains(name)) {
dogmaphobic's avatar
dogmaphobic committed
334
        if(!_createInnerDockWidget(name)) {
DonLakeFlyer's avatar
DonLakeFlyer committed
335
            qWarning() << "Trying to load non existent widget:" << name;
dogmaphobic's avatar
dogmaphobic committed
336 337
            return;
        }
338
    }
339
    Q_ASSERT(_mapName2DockWidget.contains(name));
340
    QGCDockWidget* dockWidget = _mapName2DockWidget[name];
341 342
    Q_ASSERT(dockWidget);
    dockWidget->setVisible(show);
343 344
    Q_ASSERT(_mapName2Action.contains(name));
    _mapName2Action[name]->setChecked(show);
345 346 347
}

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

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

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

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

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

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

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

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

    emit mainWindowClosed();
422 423 424 425
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

540 541 542
            widgetNames += name;
        }
    }
543

544
    QSettings settings;
545

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

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

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