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 "HomePositionManager.h"
41
#include "LogCompressor.h"
42
#include "UAS.h"
dogmaphobic's avatar
dogmaphobic committed
43
#include "QGCImageProvider.h"
44 45

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

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

60 61 62 63
#ifdef UNITTEST_BUILD
#include "QmlControls/QmlTestWidget.h"
#endif

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

67
#ifndef __mobile__
68 69 70
enum DockWidgetTypes {
    MAVLINK_INSPECTOR,
    CUSTOM_COMMAND,
71 72 73
    ONBOARD_FILES,
    INFO_VIEW,
    HIL_CONFIG,
74
    ANALYZE
75 76 77 78 79 80 81 82
};

static const char *rgDockWidgetNames[] = {
    "MAVLink Inspector",
    "Custom Command",
    "Onboard Files",
    "Info View",
    "HIL Config",
83
    "Analyze"
84 85 86
};

#define ARRAY_SIZE(ARRAY) (sizeof(ARRAY) / sizeof(ARRAY[0]))
87 88

static const char* _visibleWidgetsKey = "VisibleWidgets";
89
#endif
90

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

Lorenz Meier's avatar
Lorenz Meier committed
93
MainWindow* MainWindow::_create()
94
{
Don Gagne's avatar
Don Gagne committed
95
    Q_ASSERT(_instance == NULL);
Lorenz Meier's avatar
Lorenz Meier committed
96
    new MainWindow();
Don Gagne's avatar
Don Gagne committed
97 98
    // _instance is set in constructor
    Q_ASSERT(_instance);
99 100 101
    return _instance;
}

Don Gagne's avatar
Don Gagne committed
102
MainWindow* MainWindow::instance(void)
103
{
Don Gagne's avatar
Don Gagne committed
104
    return _instance;
105 106
}

107 108
void MainWindow::deleteInstance(void)
{
Don Gagne's avatar
Don Gagne committed
109
    delete this;
110 111
}

Don Gagne's avatar
Don Gagne committed
112 113 114
/// @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
115
MainWindow::MainWindow()
116
    : _lowPowerMode(false)
117
    , _showStatusBar(false)
118
    , _mainQmlWidgetHolder(NULL)
119
    , _forceClose(false)
120
{
Don Gagne's avatar
Don Gagne committed
121 122
    Q_ASSERT(_instance == NULL);
    _instance = this;
123

124 125 126 127 128 129 130 131
    //-- 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";
    }

132 133 134 135
    // 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
136
    // Setup user interface
137
    loadSettings();
138
    emit initStatusChanged(tr("Setting up user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
139

dogmaphobic's avatar
dogmaphobic committed
140 141
    _ui.setupUi(this);
    // Make sure tool bar elements all fit before changing minimum width
dogmaphobic's avatar
dogmaphobic committed
142
    setMinimumWidth(1008);
dogmaphobic's avatar
dogmaphobic committed
143
    configureWindowName();
144

145 146
    // Setup central widget with a layout to hold the views
    _centralLayout = new QVBoxLayout();
147
    _centralLayout->setContentsMargins(0, 0, 0, 0);
148
    centralWidget()->setLayout(_centralLayout);
149 150 151 152 153

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

154
    QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
155
    _mainQmlWidgetHolder->setContextPropertyObject("controller", this);
156
    _mainQmlWidgetHolder->setContextPropertyObject("debugMessageModel", AppMessages::getModel());
Don Gagne's avatar
Don Gagne committed
157
    _mainQmlWidgetHolder->setSource(QUrl::fromUserInput("qrc:qml/MainWindowHybrid.qml"));
158

dogmaphobic's avatar
dogmaphobic committed
159 160 161 162
    // Image provider
    QQuickImageProvider* pImgProvider = dynamic_cast<QQuickImageProvider*>(qgcApp()->toolbox()->imageProvider());
    _mainQmlWidgetHolder->getEngine()->addImageProvider(QLatin1String("QGCImages"), pImgProvider);

163
    // Set dock options
164
    setDockOptions(0);
165
    // Setup corners
166
    setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
167

dogmaphobic's avatar
dogmaphobic committed
168 169 170
    // On Mobile devices, we don't want any main menus at all.
#ifdef __mobile__
    menuBar()->setNativeMenuBar(false);
dogmaphobic's avatar
dogmaphobic committed
171
#endif
dogmaphobic's avatar
dogmaphobic committed
172

173 174 175
#ifdef UNITTEST_BUILD
    QAction* qmlTestAction = new QAction("Test QML palette and controls", NULL);
    connect(qmlTestAction, &QAction::triggered, this, &MainWindow::_showQmlTestWidget);
176
    _ui.menuWidgets->addAction(qmlTestAction);
177
#endif
178

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

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

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

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

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

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

dogmaphobic's avatar
dogmaphobic committed
209
#ifndef __mobile__
210

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

236
    connect(_ui.actionStatusBar,  &QAction::triggered, this, &MainWindow::showStatusBarCallback);
237

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

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

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

MainWindow::~MainWindow()
{
278 279 280 281
    // 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
282
    _instance = NULL;
283 284
}

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

290
#ifndef __mobile__
291
void MainWindow::_buildCommonWidgets(void)
292 293
{
    // Add generic MAVLink decoder
dogmaphobic's avatar
dogmaphobic committed
294
    // TODO: This is never deleted
295
    mavlinkDecoder = new MAVLinkDecoder(qgcApp()->toolbox()->mavlinkProtocol(), this);
296
    connect(mavlinkDecoder.data(), &MAVLinkDecoder::valueChanged, this, &MainWindow::valueChanged);
297

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

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

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

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

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

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

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

381 382
void MainWindow::_hideAllDockWidgets(void)
{
383
    foreach(QGCDockWidget* dockWidget, _mapName2DockWidget) {
384 385 386 387 388 389
        dockWidget->setVisible(false);
    }
}

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

396 397 398 399 400 401
void MainWindow::showStatusBarCallback(bool checked)
{
    _showStatusBar = checked;
    checked ? statusBar()->show() : statusBar()->hide();
}

402
void MainWindow::reallyClose(void)
403
{
404 405
    _forceClose = true;
    close();
406 407
}

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

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

422
    _storeCurrentViewState();
423
    storeSettings();
424 425

    emit mainWindowClosed();
426 427 428 429
}

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

void MainWindow::storeSettings()
{
    QSettings settings;
441
    settings.beginGroup(MAIN_SETTINGS_GROUP);
442 443
    settings.setValue("LOW_POWER_MODE",     _lowPowerMode);
    settings.setValue("SHOW_STATUSBAR",     _showStatusBar);
444
    settings.endGroup();
dogmaphobic's avatar
dogmaphobic committed
445
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
446

447 448 449
#ifndef __mobile__
    _storeVisibleWidgetsSettings();
#endif
450 451 452 453
}

void MainWindow::configureWindowName()
{
454
    setWindowTitle(qApp->applicationName() + " " + qApp->applicationVersion());
455 456 457 458 459 460 461 462 463
}

/**
* @brief Create all actions associated to the main window
*
**/
void MainWindow::connectCommonActions()
{
    // Audio output
464
    _ui.actionMuteAudioOutput->setChecked(qgcApp()->toolbox()->audioOutput()->isMuted());
465 466
    connect(qgcApp()->toolbox()->audioOutput(), &GAudioOutput::mutedChanged, _ui.actionMuteAudioOutput, &QAction::setChecked);
    connect(_ui.actionMuteAudioOutput, &QAction::triggered, qgcApp()->toolbox()->audioOutput(), &GAudioOutput::mute);
467

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
}