MainWindow.cc 42.5 KB
Newer Older
1 2 3 4
/*=====================================================================

QGroundControl Open Source Ground Control Station

5
(c) 2009 - 2013 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

This file is part of the QGROUNDCONTROL project

    QGROUNDCONTROL is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    QGROUNDCONTROL is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Implementation of class MainWindow
 *   @author Lorenz Meier <mail@qgroundcontrol.org>
 */

#include <QSettings>
#include <QNetworkInterface>
#include <QDebug>
#include <QTimer>
#include <QHostInfo>
#include <QSplashScreen>
dogmaphobic's avatar
dogmaphobic committed
36
#ifndef __mobile__
37 38 39
#include <QGCHilLink.h>
#include <QGCHilConfiguration.h>
#include <QGCHilFlightGearConfiguration.h>
dogmaphobic's avatar
dogmaphobic committed
40
#endif
41
#include <QQuickView>
42 43
#include <QDesktopWidget>

44
#include "QGC.h"
dogmaphobic's avatar
dogmaphobic committed
45
#ifndef __ios__
46
#include "SerialLink.h"
dogmaphobic's avatar
dogmaphobic committed
47
#endif
48 49 50
#include "MAVLinkProtocol.h"
#include "QGCWaypointListMulti.h"
#include "MainWindow.h"
dogmaphobic's avatar
dogmaphobic committed
51
#ifndef __mobile__
52
#include "JoystickWidget.h"
dogmaphobic's avatar
dogmaphobic committed
53
#endif
54 55
#include "GAudioOutput.h"
#include "QGCMAVLinkLogPlayer.h"
Don Gagne's avatar
Don Gagne committed
56
#include "SettingsDialog.h"
57
#include "QGCMapTool.h"
58
#include "QGCMapDisplay.h"
59 60 61
#include "MAVLinkDecoder.h"
#include "QGCMAVLinkMessageSender.h"
#include "QGCRGBDView.h"
62
#include "UASQuickView.h"
63 64
#include "QGCDataPlot2D.h"
#include "Linecharts.h"
65 66
#include "QGCTabbedInfoView.h"
#include "UASRawStatusView.h"
67
#include "FlightDisplay.h"
68
#include "SetupView.h"
69
#include "QGCUASFileViewMulti.h"
Don Gagne's avatar
Don Gagne committed
70
#include "QGCApplication.h"
71
#include "QGCFileDialog.h"
Don Gagne's avatar
Don Gagne committed
72
#include "QGCMessageBox.h"
73
#include "QGCDockWidget.h"
Don Gagne's avatar
Don Gagne committed
74
#include "CustomCommandWidget.h"
75

76 77 78 79
#ifdef UNITTEST_BUILD
#include "QmlControls/QmlTestWidget.h"
#endif

80 81 82 83 84 85
#ifdef QGC_OSG_ENABLED
#include "Q3DWidgetFactory.h"
#endif

#include "LogCompressor.h"

86 87 88 89 90 91 92 93 94
// Pixel size, instead of a physical thing is actually a philosophical question when
// it comes to Qt. Fonts are that and some heavy Kabalistic Voodoo added to the mix.
// The values below came from actually measuring the elements on the screen on these
// devices. I have yet to find a constant from Qt so these things can be properly
// computed at runtime.

#if defined(Q_OS_OSX)
double MainWindow::_pixelFactor    = 1.0;
double MainWindow::_fontFactor     = 1.0;
dogmaphobic's avatar
dogmaphobic committed
95 96 97
#elif defined(__ios__)
double MainWindow::_pixelFactor    = 1.0;
double MainWindow::_fontFactor     = 1.0;
98 99 100 101 102 103 104 105 106 107 108
#elif defined(Q_OS_WIN)
double MainWindow::_pixelFactor    = 0.86;
double MainWindow::_fontFactor     = 0.63;
#elif defined(__android__)
double MainWindow::_pixelFactor    = 2.0;
double MainWindow::_fontFactor     = 1.23;
#elif defined(Q_OS_LINUX)
double MainWindow::_pixelFactor    = 1.0;
double MainWindow::_fontFactor     = 0.85;
#endif

109 110 111
/// The key under which the Main Window settings are saved
const char* MAIN_SETTINGS_GROUP = "QGC_MAINWINDOW";

112 113 114 115 116
const char* MainWindow::_uasControlDockWidgetName = "UNMANNED_SYSTEM_CONTROL_DOCKWIDGET";
const char* MainWindow::_uasListDockWidgetName = "UNMANNED_SYSTEM_LIST_DOCKWIDGET";
const char* MainWindow::_waypointsDockWidgetName = "WAYPOINT_LIST_DOCKWIDGET";
const char* MainWindow::_mavlinkDockWidgetName = "MAVLINK_INSPECTOR_DOCKWIDGET";
const char* MainWindow::_parametersDockWidgetName = "PARAMETER_INTERFACE_DOCKWIDGET";
Don Gagne's avatar
Don Gagne committed
117
const char* MainWindow::_customCommandWidgetName = "CUSTOM_COMMAND_DOCKWIDGET";
118 119 120 121 122 123 124 125 126 127
const char* MainWindow::_filesDockWidgetName = "FILE_VIEW_DOCKWIDGET";
const char* MainWindow::_uasStatusDetailsDockWidgetName = "UAS_STATUS_DETAILS_DOCKWIDGET";
const char* MainWindow::_mapViewDockWidgetName = "MAP_VIEW_DOCKWIDGET";
const char* MainWindow::_hsiDockWidgetName = "HORIZONTAL_SITUATION_INDICATOR_DOCKWIDGET";
const char* MainWindow::_hdd1DockWidgetName = "HEAD_DOWN_DISPLAY_1_DOCKWIDGET";
const char* MainWindow::_hdd2DockWidgetName = "HEAD_DOWN_DISPLAY_2_DOCKWIDGET";
const char* MainWindow::_pfdDockWidgetName = "PRIMARY_FLIGHT_DISPLAY_DOCKWIDGET";
const char* MainWindow::_hudDockWidgetName = "HEAD_UP_DISPLAY_DOCKWIDGET";
const char* MainWindow::_uasInfoViewDockWidgetName = "UAS_INFO_INFOVIEW_DOCKWIDGET";

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

130
MainWindow* MainWindow::_create(QSplashScreen* splashScreen)
131
{
Don Gagne's avatar
Don Gagne committed
132
    Q_ASSERT(_instance == NULL);
133
    new MainWindow(splashScreen);
Don Gagne's avatar
Don Gagne committed
134 135
    // _instance is set in constructor
    Q_ASSERT(_instance);
136 137 138
    return _instance;
}

Don Gagne's avatar
Don Gagne committed
139
MainWindow* MainWindow::instance(void)
140
{
Don Gagne's avatar
Don Gagne committed
141
    return _instance;
142 143
}

144 145
void MainWindow::deleteInstance(void)
{
Don Gagne's avatar
Don Gagne committed
146
    delete this;
147 148
}

Don Gagne's avatar
Don Gagne committed
149 150 151
/// @brief Private constructor for MainWindow. MainWindow singleton is only ever created
///         by MainWindow::_create method. Hence no other code should have access to
///         constructor.
dogmaphobic's avatar
dogmaphobic committed
152 153 154
MainWindow::MainWindow(QSplashScreen* splashScreen)
    : _autoReconnect(false)
    , _lowPowerMode(false)
155
    , _showStatusBar(false)
dogmaphobic's avatar
dogmaphobic committed
156 157 158 159 160
    , _centerStackActionGroup(new QActionGroup(this))
    , _centralLayout(NULL)
    , _currentViewWidget(NULL)
    , _splashScreen(splashScreen)
    , _currentView(VIEW_SETUP)
161
{
Don Gagne's avatar
Don Gagne committed
162 163
    Q_ASSERT(_instance == NULL);
    _instance = this;
164

165 166 167
    if (splashScreen) {
        connect(this, &MainWindow::initStatusChanged, splashScreen, &QSplashScreen::showMessage);
    }
168

dogmaphobic's avatar
dogmaphobic committed
169
    // Setup user interface
170
    loadSettings();
171
    emit initStatusChanged(tr("Setting up user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
dogmaphobic's avatar
dogmaphobic committed
172 173
    _ui.setupUi(this);
    // Make sure tool bar elements all fit before changing minimum width
dogmaphobic's avatar
dogmaphobic committed
174
    setMinimumWidth(1008);
dogmaphobic's avatar
dogmaphobic committed
175
    configureWindowName();
176

177 178
    // Setup central widget with a layout to hold the views
    _centralLayout = new QVBoxLayout();
179
    _centralLayout->setContentsMargins(0,0,0,0);
180
    centralWidget()->setLayout(_centralLayout);
181 182 183
    // Set dock options
    setDockOptions(AnimatedDocks | AllowTabbedDocks | AllowNestedDocks);
    // Setup corners
184
    setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
185

186 187
    // Qt 4 on Ubuntu does place the native menubar correctly so on Linux we revert back to in-window menu bar.
    // TODO: Check that this is still necessary on Qt5 on Ubuntu
dogmaphobic's avatar
dogmaphobic committed
188

189 190 191
#ifdef Q_OS_LINUX
    menuBar()->setNativeMenuBar(false);
#endif
dogmaphobic's avatar
dogmaphobic committed
192 193 194 195

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

198 199 200
#ifdef UNITTEST_BUILD
    QAction* qmlTestAction = new QAction("Test QML palette and controls", NULL);
    connect(qmlTestAction, &QAction::triggered, this, &MainWindow::_showQmlTestWidget);
dogmaphobic's avatar
dogmaphobic committed
201
    _ui.menuTools->addAction(qmlTestAction);
202
#endif
203

dogmaphobic's avatar
dogmaphobic committed
204 205 206 207
    // Load QML Toolbar
    QDockWidget* widget = new QDockWidget(this);
    widget->setObjectName("ToolBarDockWidget");
    qmlRegisterType<MainToolBar>("QGroundControl.MainToolBar", 1, 0, "MainToolBar");
208
    _mainToolBar = new MainToolBar(widget);
dogmaphobic's avatar
dogmaphobic committed
209 210 211 212
    widget->setWidget(_mainToolBar);
    widget->setFeatures(QDockWidget::NoDockWidgetFeatures);
    widget->setTitleBarWidget(new QWidget(this)); // Disables the title bar
    addDockWidget(Qt::TopDockWidgetArea, widget);
213

dogmaphobic's avatar
dogmaphobic committed
214 215 216
    // Setup UI state machines
    _centerStackActionGroup->setExclusive(true);
    // Status Bar
217
    setStatusBar(new QStatusBar(this));
218
    statusBar()->setSizeGripEnabled(true);
219

220
    emit initStatusChanged(tr("Building common widgets."), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
221
    _buildCommonWidgets();
222
    emit initStatusChanged(tr("Building common actions"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
223 224 225
    // Create actions
    connectCommonActions();
    // Connect user interface devices
226
    emit initStatusChanged(tr("Initializing joystick interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
dogmaphobic's avatar
dogmaphobic committed
227
#ifndef __mobile__
228
    joystick = new JoystickInput();
dogmaphobic's avatar
dogmaphobic committed
229
#endif
230
#ifdef QGC_MOUSE_ENABLED_WIN
231
    emit initStatusChanged(tr("Initializing 3D mouse interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
232 233
    mouseInput = new Mouse3DInput(this);
    mouse = new Mouse6dofInput(mouseInput);
234
#endif //QGC_MOUSE_ENABLED_WIN
235

236
#if QGC_MOUSE_ENABLED_LINUX
237
    emit initStatusChanged(tr("Initializing 3D mouse interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
238 239

    mouse = new Mouse6dofInput(this);
240
    connect(this, SIGNAL(x11EventOccured(XEvent*)), mouse, SLOT(handleX11Event(XEvent*)));
241
#endif //QGC_MOUSE_ENABLED_LINUX
242

243 244 245 246
    // These also cause the screen to redraw so we need to update any OpenGL canvases in QML controls
    connect(LinkManager::instance(), &LinkManager::linkConnected,    this, &MainWindow::_linkStateChange);
    connect(LinkManager::instance(), &LinkManager::linkDisconnected, this, &MainWindow::_linkStateChange);

247
    // Connect link
dogmaphobic's avatar
dogmaphobic committed
248
    if (_autoReconnect)
249
    {
250
        restoreLastUsedConnection();
251 252 253
    }

    // Set low power mode
dogmaphobic's avatar
dogmaphobic committed
254
    enableLowPowerMode(_lowPowerMode);
255
    emit initStatusChanged(tr("Restoring last view state"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
256
    // Restore the window setup
257
    _loadCurrentViewState();
dogmaphobic's avatar
dogmaphobic committed
258
#ifndef __mobile__
259

260
    // Restore the window position and size
dogmaphobic's avatar
dogmaphobic committed
261 262
    emit initStatusChanged(tr("Restoring last window size"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
    if (settings.contains(_getWindowGeometryKey()))
263
    {
dogmaphobic's avatar
dogmaphobic committed
264
        restoreGeometry(settings.value(_getWindowGeometryKey()).toByteArray());
265 266 267 268
    }
    else
    {
        // Adjust the size
269 270 271
        QScreen* scr = QApplication::primaryScreen();
        QSize scrSize = scr->availableSize();
        if (scrSize.width() <= 1280)
272
        {
273
            resize(scrSize.width(), scrSize.height());
274 275 276
        }
        else
        {
277 278 279
            int w = scrSize.width()  > 1600 ? 1600 : scrSize.width();
            int h = scrSize.height() >  800 ?  800 : scrSize.height();
            resize(w, h);
280
            move((scrSize.width() - w) / 2, (scrSize.height() - h) / 2);
281 282 283
        }
    }

284 285 286
    // Make sure the proper fullscreen/normal menu item is checked properly.
    if (isFullScreen())
    {
dogmaphobic's avatar
dogmaphobic committed
287 288
        _ui.actionFullscreen->setChecked(true);
        _ui.actionNormal->setChecked(false);
289 290 291
    }
    else
    {
dogmaphobic's avatar
dogmaphobic committed
292 293
        _ui.actionFullscreen->setChecked(false);
        _ui.actionNormal->setChecked(true);
294 295 296
    }

    // And that they will stay checked properly after user input
297 298
    connect(_ui.actionFullscreen, &QAction::triggered, this, &MainWindow::fullScreenActionItemCallback);
    connect(_ui.actionNormal,     &QAction::triggered, this, &MainWindow::normalActionItemCallback);
299 300
#endif

301
    connect(_ui.actionStatusBar,  &QAction::triggered, this, &MainWindow::showStatusBarCallback);
302

303 304
    // Set OS dependent keyboard shortcuts for the main window, non OS dependent shortcuts are set in MainWindow.ui
#ifdef Q_OS_MACX
dogmaphobic's avatar
dogmaphobic committed
305
    _ui.actionSetup->setShortcut(QApplication::translate("MainWindow", "Meta+1", 0));
306 307 308
    _ui.actionPlan->setShortcut(QApplication::translate("MainWindow", "Meta+2", 0));
    _ui.actionFlight->setShortcut(QApplication::translate("MainWindow", "Meta+3", 0));
    _ui.actionAnalyze->setShortcut(QApplication::translate("MainWindow", "Meta+4", 0));
Don Gagne's avatar
Don Gagne committed
309
    _ui.actionSimulationView->setShortcut(QApplication::translate("MainWindow", "Meta+5", 0));
dogmaphobic's avatar
dogmaphobic committed
310
    _ui.actionFullscreen->setShortcut(QApplication::translate("MainWindow", "Meta+Return", 0));
311
#else
dogmaphobic's avatar
dogmaphobic committed
312
    _ui.actionSetup->setShortcut(QApplication::translate("MainWindow", "Ctrl+1", 0));
Gus Grubba's avatar
Gus Grubba committed
313
    _ui.actionPlan->setShortcut(QApplication::translate("MainWindow", "Ctrl+2", 0));
314
    _ui.actionFlight->setShortcut(QApplication::translate("MainWindow", "Ctrl+3", 0));
Gus Grubba's avatar
Gus Grubba committed
315
    _ui.actionAnalyze->setShortcut(QApplication::translate("MainWindow", "Ctrl+4", 0));
Don Gagne's avatar
Don Gagne committed
316
    _ui.actionSimulationView->setShortcut(QApplication::translate("MainWindow", "Ctrl+5", 0));
dogmaphobic's avatar
dogmaphobic committed
317
    _ui.actionFullscreen->setShortcut(QApplication::translate("MainWindow", "Ctrl+Return", 0));
318 319
#endif

320 321
    connect(&windowNameUpdateTimer, SIGNAL(timeout()), this, SLOT(configureWindowName()));
    windowNameUpdateTimer.start(15000);
322
    emit initStatusChanged(tr("Done"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
323 324

    if (!qgcApp()->runningUnitTests()) {
325 326
        _ui.actionStatusBar->setChecked(_showStatusBar);
        showStatusBarCallback(_showStatusBar);
dogmaphobic's avatar
dogmaphobic committed
327
#ifdef __mobile__
328 329
        menuBar()->hide();
#endif
330
        show();
dogmaphobic's avatar
dogmaphobic committed
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
#ifdef Q_OS_MAC
        // 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
346
    }
347 348 349 350
}

MainWindow::~MainWindow()
{
dogmaphobic's avatar
dogmaphobic committed
351
#ifndef __mobile__
352 353
    if (joystick)
    {
354 355
        joystick->shutdown();
        joystick->wait(5000);
Lorenz Meier's avatar
Lorenz Meier committed
356
        joystick->deleteLater();
357 358
        joystick = NULL;
    }
dogmaphobic's avatar
dogmaphobic committed
359
#endif
360
    // Delete all UAS objects
dogmaphobic's avatar
dogmaphobic committed
361
    for (int i=0;i<_commsWidgetList.size();i++)
362
    {
dogmaphobic's avatar
dogmaphobic committed
363
        _commsWidgetList[i]->deleteLater();
364
    }
Don Gagne's avatar
Don Gagne committed
365
    _instance = NULL;
366 367 368 369 370 371 372
}

void MainWindow::resizeEvent(QResizeEvent * event)
{
    QMainWindow::resizeEvent(event);
}

dogmaphobic's avatar
dogmaphobic committed
373
QString MainWindow::_getWindowStateKey()
374
{
375
	return QString::number(_currentView)+"_windowstate_";
376 377
}

dogmaphobic's avatar
dogmaphobic committed
378
QString MainWindow::_getWindowGeometryKey()
379 380 381 382
{
    return "_geometry";
}

383 384 385
void MainWindow::_createDockWidget(const QString& title, const QString& name, Qt::DockWidgetArea area, QWidget* innerWidget)
{
    Q_ASSERT(!_mapName2DockWidget.contains(name));
386
	
387 388 389 390 391
    // Add to menu
    QAction* action = new QAction(title, NULL);
    action->setCheckable(true);
    action->setData(name);
    connect(action, &QAction::triggered, this, &MainWindow::_showDockWidgetAction);
dogmaphobic's avatar
dogmaphobic committed
392
    _ui.menuTools->addAction(action);
393 394 395 396 397 398 399 400 401 402 403 404 405
	
	// Create widget
	QGCDockWidget* dockWidget = new QGCDockWidget(title, action, this);
	Q_CHECK_PTR(dockWidget);
	dockWidget->setObjectName(name);
	dockWidget->setVisible (false);
	if (innerWidget) {
		// Put inner widget inside QDockWidget
		innerWidget->setParent(dockWidget);
		dockWidget->setWidget(innerWidget);
		innerWidget->setVisible(true);
	}
	
406 407 408 409 410 411
    _mapName2DockWidget[name] = dockWidget;
    _mapDockWidget2Action[dockWidget] = action;
    addDockWidget(area, dockWidget);
}

void MainWindow::_buildCommonWidgets(void)
412 413
{
    // Add generic MAVLink decoder
dogmaphobic's avatar
dogmaphobic committed
414
    // TODO: This is never deleted
415
    mavlinkDecoder = new MAVLinkDecoder(MAVLinkProtocol::instance(), this);
John Tapsell's avatar
John Tapsell committed
416 417
    connect(mavlinkDecoder, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),
                      this, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)));
418

419
    // Log player
dogmaphobic's avatar
dogmaphobic committed
420
    // TODO: Make this optional with a preferences setting or under a "View" menu
421
    logPlayer = new QGCMAVLinkLogPlayer(MAVLinkProtocol::instance(), statusBar());
422
    statusBar()->addPermanentWidget(logPlayer);
423

424 425 426
    // In order for Qt to save and restore state of widgets all widgets must be created ahead of time. We only create the QDockWidget
    // holders. We do not create the actual inner widget until it is needed. This saves memory and cpu from running widgets that are
    // never shown.
427

428 429 430 431 432
    struct DockWidgetInfo {
        const char* name;
        const char* title;
        Qt::DockWidgetArea area;
    };
433

434 435 436 437 438
    static const struct DockWidgetInfo rgDockWidgetInfo[] = {
        { _uasControlDockWidgetName,        "Control",                  Qt::LeftDockWidgetArea },
        { _uasListDockWidgetName,           "Unmanned Systems",         Qt::RightDockWidgetArea },
        { _waypointsDockWidgetName,         "Mission Plan",             Qt::BottomDockWidgetArea },
        { _mavlinkDockWidgetName,           "MAVLink Inspector",        Qt::RightDockWidgetArea },
439
        { _parametersDockWidgetName,        "Parameter Editor",			Qt::RightDockWidgetArea },
Don Gagne's avatar
Don Gagne committed
440
        { _customCommandWidgetName,         "Custom Command",			Qt::RightDockWidgetArea },
441 442 443 444 445 446 447 448 449 450 451
        { _filesDockWidgetName,             "Onboard Files",            Qt::RightDockWidgetArea },
        { _uasStatusDetailsDockWidgetName,  "Status Details",           Qt::RightDockWidgetArea },
        { _mapViewDockWidgetName,           "Map view",                 Qt::RightDockWidgetArea },
        { _hsiDockWidgetName,               "Horizontal Situation",     Qt::BottomDockWidgetArea },
        { _hdd1DockWidgetName,              "Flight Display",           Qt::RightDockWidgetArea },
        { _hdd2DockWidgetName,              "Actuator Status",          Qt::RightDockWidgetArea },
        { _pfdDockWidgetName,               "Primary Flight Display",   Qt::RightDockWidgetArea },
        { _hudDockWidgetName,               "Video Downlink",           Qt::RightDockWidgetArea },
        { _uasInfoViewDockWidgetName,       "Info View",                Qt::LeftDockWidgetArea },
    };
    static const size_t cDockWidgetInfo = sizeof(rgDockWidgetInfo) / sizeof(rgDockWidgetInfo[0]);
452

453 454 455
    for (size_t i=0; i<cDockWidgetInfo; i++) {
        const struct DockWidgetInfo* pDockInfo = &rgDockWidgetInfo[i];
        _createDockWidget(pDockInfo->title, pDockInfo->name, pDockInfo->area, NULL /* no inner widget yet */);
456
    }
457
}
458

459
void MainWindow::_buildPlanView(void)
460
{
461 462 463
    if (!_planView) {
        _planView = new QGCMapTool(this);
        _planView->setVisible(false);
464
    }
465
}
466

467
void MainWindow::_buildExperimentalPlanView(void)
468
{
469 470 471 472 473 474 475 476 477
    if (!_experimentalPlanView) {
        _experimentalPlanView = new QGCMapDisplay(this);
        _experimentalPlanView->setVisible(false);
    }
}

void MainWindow::_buildFlightView(void)
{
    if (!_flightView) {
478
        _flightView = new FlightDisplay(this);
479
        _flightView->setVisible(false);
480
    }
481 482
}

483
void MainWindow::_buildSetupView(void)
484
{
485 486 487 488
    if (!_setupView) {
        _setupView = new SetupView(this);
        _setupView->setVisible(false);
    }
489 490
}

491
void MainWindow::_buildAnalyzeView(void)
492
{
493 494 495
    if (!_analyzeView) {
        _analyzeView = new QGCDataPlot2D(this);
        _analyzeView->setVisible(false);
496 497
    }
}
498

499 500 501 502 503 504
void MainWindow::_buildSimView(void)
{
    if (!_simView) {
        _simView = new QGCMapTool(this);
        _simView->setVisible(false);
    }
505
}
506

507 508
/// Shows or hides the specified dock widget, creating if necessary
void MainWindow::_showDockWidget(const QString& name, bool show)
509
{
510
    if (!_mapName2DockWidget.contains(name)) {
Don Gagne's avatar
Don Gagne committed
511 512
        // Don't show any sort of warning here. Dock Widgets which have been remove could still be in settings.
        // Which would cause us to end up here.
513 514
        return;
    }
515

516 517 518
    // Create the inner widget if we need to
    if (!_mapName2DockWidget[name]->widget()) {
        _createInnerDockWidget(name);
519
    }
520 521 522 523

    Q_ASSERT(_mapName2DockWidget.contains(name));
    QDockWidget* dockWidget = _mapName2DockWidget[name];
    Q_ASSERT(dockWidget);
524

525
    dockWidget->setVisible(show);
526

527 528 529 530 531 532 533 534 535
    Q_ASSERT(_mapDockWidget2Action.contains(dockWidget));
    _mapDockWidget2Action[dockWidget]->setChecked(show);
}

/// Creates the specified inner dock widget and adds to the QDockWidget
void MainWindow::_createInnerDockWidget(const QString& widgetName)
{
    Q_ASSERT(_mapName2DockWidget.contains(widgetName)); // QDockWidget should already exist
    Q_ASSERT(!_mapName2DockWidget[widgetName]->widget());     // Inner widget should not
536

537
    QWidget* widget = NULL;
538

539 540 541 542 543 544 545 546 547
    if (widgetName == _uasControlDockWidgetName) {
        widget = new UASControlWidget(this);
    } else if (widgetName == _uasListDockWidgetName) {
        widget = new UASListWidget(this);
    } else if (widgetName == _waypointsDockWidgetName) {
        widget = new QGCWaypointListMulti(this);
    } else if (widgetName == _mavlinkDockWidgetName) {
        widget = new QGCMAVLinkInspector(MAVLinkProtocol::instance(),this);
    } else if (widgetName == _parametersDockWidgetName) {
548
        widget = new ParameterEditorWidget(this);
Don Gagne's avatar
Don Gagne committed
549 550
    } else if (widgetName == _customCommandWidgetName) {
        widget = new CustomCommandWidget(this);
551 552 553 554 555 556 557 558 559
    } else if (widgetName == _filesDockWidgetName) {
        widget = new QGCUASFileViewMulti(this);
    } else if (widgetName == _uasStatusDetailsDockWidgetName) {
        widget = new UASInfoWidget(this);
    } else if (widgetName == _mapViewDockWidgetName) {
        widget = new QGCMapTool(this);
    } else if (widgetName == _hsiDockWidgetName) {
        widget = new HSIDisplay(this);
    } else if (widgetName == _hdd1DockWidgetName) {
560 561 562 563
        QStringList acceptList;
        acceptList.append("-3.3,ATTITUDE.roll,rad,+3.3,s");
        acceptList.append("-3.3,ATTITUDE.pitch,deg,+3.3,s");
        acceptList.append("-3.3,ATTITUDE.yaw,deg,+3.3,s");
564 565
        HDDisplay *hddisplay = new HDDisplay(acceptList,"Flight Display",this);
        hddisplay->addSource(mavlinkDecoder);
566

567 568
        widget = hddisplay;
    } else if (widgetName == _hdd2DockWidgetName) {
569 570 571
        QStringList acceptList;
        acceptList.append("0,RAW_PRESSURE.pres_abs,hPa,65500");
        HDDisplay *hddisplay = new HDDisplay(acceptList,"Actuator Status",this);
572
        hddisplay->addSource(mavlinkDecoder);
573

574 575
        widget = hddisplay;
    } else if (widgetName == _pfdDockWidgetName) {
576
        widget = new FlightDisplay(this);
577 578 579
    } else if (widgetName == _hudDockWidgetName) {
        widget = new HUD(320,240,this);
    } else if (widgetName == _uasInfoViewDockWidgetName) {
580 581 582
        QGCTabbedInfoView* pInfoView = new QGCTabbedInfoView(this);
        pInfoView->addSource(mavlinkDecoder);
        widget = pInfoView;
583 584
    } else {
        qWarning() << "Attempt to create unknown Inner Dock Widget" << widgetName;
585
    }
586

587 588 589 590 591
    if (widget) {
        QDockWidget* dockWidget = _mapName2DockWidget[widgetName];
        Q_CHECK_PTR(dockWidget);
        widget->setParent(dockWidget);
        dockWidget->setWidget(widget);
592 593
    }
}
594

dogmaphobic's avatar
dogmaphobic committed
595
#ifndef __mobile__
596
void MainWindow::_showHILConfigurationWidgets(void)
597
{
598
    UASInterface* uas = UASManager::instance()->getActiveUAS();
599

600 601 602
    if (!uas) {
        return;
    }
603

604 605
    UAS* mav = dynamic_cast<UAS*>(uas);
    Q_ASSERT(mav);
606

607
    int uasId = mav->getUASID();
608

609
    if (!_mapUasId2HilDockWidget.contains(uasId)) {
610

611
        // Create QDockWidget
612
        QGCDockWidget* dockWidget = new QGCDockWidget(tr("HIL Config %1").arg(uasId), NULL, this);
613 614 615
        Q_CHECK_PTR(dockWidget);
        dockWidget->setObjectName(tr("HIL_CONFIG_%1").arg(uasId));
        dockWidget->setVisible (false);
616

617 618
        // Create inner widget and set it
        QWidget* widget = new QGCHilConfiguration(mav, dockWidget);
619

620 621
        widget->setParent(dockWidget);
        dockWidget->setWidget(widget);
622

623
        _mapUasId2HilDockWidget[uasId] = dockWidget;
624

625 626
        addDockWidget(Qt::LeftDockWidgetArea, dockWidget);
    }
627

628 629 630 631 632
    if (_currentView == VIEW_SIMULATION) {
        // HIL dock widgets only show up on simulation view
        foreach (QDockWidget* dockWidget, _mapUasId2HilDockWidget) {
            dockWidget->setVisible(true);
        }
633 634
    }
}
dogmaphobic's avatar
dogmaphobic committed
635
#endif
636

637
void MainWindow::fullScreenActionItemCallback(bool)
638
{
dogmaphobic's avatar
dogmaphobic committed
639
    _ui.actionNormal->setChecked(false);
640 641
}

642
void MainWindow::normalActionItemCallback(bool)
643
{
dogmaphobic's avatar
dogmaphobic committed
644
    _ui.actionFullscreen->setChecked(false);
645 646
}

647 648 649 650
void MainWindow::showStatusBarCallback(bool checked)
{
    _showStatusBar = checked;
    checked ? statusBar()->show() : statusBar()->hide();
651
    _ui.actionStatusBar->setText(checked ? "Hide Status Bar" : "Show Status Bar");
652 653
}

654 655
void MainWindow::closeEvent(QCloseEvent *event)
{
656
    // Disallow window close if there are active connections
657
    if (LinkManager::instance()->anyConnectedLinks()) {
dogmaphobic's avatar
dogmaphobic committed
658 659 660 661 662 663
        QGCMessageBox::StandardButton button =
            QGCMessageBox::warning(
                tr("QGroundControl close"),
                tr("There are still active connections to vehicles. Do you want to disconnect these before closing?"),
                QMessageBox::Yes | QMessageBox::Cancel,
                QMessageBox::Cancel);
664
        if (button == QMessageBox::Yes) {
665
            LinkManager::instance()->disconnectAll();
666 667 668 669
        } else {
            event->ignore();
            return;
        }
670 671
    }

672 673
    // This will process any remaining flight log save dialogs
    qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
674
    
675
    // Should not be any active connections
676 677
    Q_ASSERT(!LinkManager::instance()->anyConnectedLinks());
    
678
    _storeCurrentViewState();
679
    storeSettings();
680
    UASManager::instance()->storeSettings();
681
    event->accept();
682 683 684 685
}

void MainWindow::loadSettings()
{
686
    // Why the screaming?
687
    QSettings settings;
688
    settings.beginGroup(MAIN_SETTINGS_GROUP);
689 690 691 692 693
    _autoReconnect  = settings.value("AUTO_RECONNECT",      _autoReconnect).toBool();
    _lowPowerMode   = settings.value("LOW_POWER_MODE",      _lowPowerMode).toBool();
    _showStatusBar  = settings.value("SHOW_STATUSBAR",      _showStatusBar).toBool();
    _fontFactor     = settings.value("FONT_SIZE_FACTOR",    _fontFactor).toDouble();
    _pixelFactor    = settings.value("PIXEL_SIZE_FACTOR",   _pixelFactor).toDouble();
694 695 696 697 698 699
    settings.endGroup();
}

void MainWindow::storeSettings()
{
    QSettings settings;
700
    settings.beginGroup(MAIN_SETTINGS_GROUP);
701 702 703 704 705
    settings.setValue("AUTO_RECONNECT",     _autoReconnect);
    settings.setValue("LOW_POWER_MODE",     _lowPowerMode);
    settings.setValue("SHOW_STATUSBAR",     _showStatusBar);
    settings.setValue("FONT_SIZE_FACTOR",   _fontFactor);
    settings.setValue("PIXEL_SIZE_FACTOR",  _pixelFactor);
706
    settings.endGroup();
dogmaphobic's avatar
dogmaphobic committed
707
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
708
	
709
    // Save the last current view in any case
710
    settings.setValue("CURRENT_VIEW", _currentView);
711
    settings.setValue(_getWindowStateKey(), saveState());
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
}

void MainWindow::configureWindowName()
{
    QList<QHostAddress> hostAddresses = QNetworkInterface::allAddresses();
    QString windowname = qApp->applicationName() + " " + qApp->applicationVersion();
    bool prevAddr = false;
    windowname.append(" (" + QHostInfo::localHostName() + ": ");
    for (int i = 0; i < hostAddresses.size(); i++)
    {
        // Exclude loopback IPv4 and all IPv6 addresses
        if (hostAddresses.at(i) != QHostAddress("127.0.0.1") && !hostAddresses.at(i).toString().contains(":"))
        {
            if(prevAddr) windowname.append("/");
            windowname.append(hostAddresses.at(i).toString());
            prevAddr = true;
        }
    }
    windowname.append(")");
    setWindowTitle(windowname);
}

void MainWindow::enableAutoReconnect(bool enabled)
{
dogmaphobic's avatar
dogmaphobic committed
736
    _autoReconnect = enabled;
737 738 739 740 741 742 743 744 745
}

/**
* @brief Create all actions associated to the main window
*
**/
void MainWindow::connectCommonActions()
{
    // Bind together the perspective actions
dogmaphobic's avatar
dogmaphobic committed
746
    QActionGroup* perspectives = new QActionGroup(_ui.menuPerspectives);
747 748
    perspectives->addAction(_ui.actionAnalyze);
    perspectives->addAction(_ui.actionFlight);
dogmaphobic's avatar
dogmaphobic committed
749
    perspectives->addAction(_ui.actionSimulationView);
750
    perspectives->addAction(_ui.actionPlan);
dogmaphobic's avatar
dogmaphobic committed
751
    perspectives->addAction(_ui.actionSetup);
752
    perspectives->addAction(_ui.actionExperimentalPlanView);
753 754 755
    perspectives->setExclusive(true);

    // Mark the right one as selected
756
    if (_currentView == VIEW_ANALYZE)
757
    {
758 759
        _ui.actionAnalyze->setChecked(true);
        _ui.actionAnalyze->activate(QAction::Trigger);
760
    }
761
    if (_currentView == VIEW_FLIGHT)
762
    {
763 764
        _ui.actionFlight->setChecked(true);
        _ui.actionFlight->activate(QAction::Trigger);
765
    }
766
    if (_currentView == VIEW_SIMULATION)
767
    {
dogmaphobic's avatar
dogmaphobic committed
768 769
        _ui.actionSimulationView->setChecked(true);
        _ui.actionSimulationView->activate(QAction::Trigger);
770
    }
771
    if (_currentView == VIEW_PLAN)
772
    {
773 774 775 776 777 778 779
        _ui.actionPlan->setChecked(true);
        _ui.actionPlan->activate(QAction::Trigger);
    }
    if (_currentView == VIEW_EXPERIMENTAL_PLAN)
    {
        _ui.actionExperimentalPlanView->setChecked(true);
        _ui.actionExperimentalPlanView->activate(QAction::Trigger);
780
    }
781
    if (_currentView == VIEW_SETUP)
782
    {
dogmaphobic's avatar
dogmaphobic committed
783 784
        _ui.actionSetup->setChecked(true);
        _ui.actionSetup->activate(QAction::Trigger);
785
    }
786 787

    // The UAS actions are not enabled without connection to system
dogmaphobic's avatar
dogmaphobic committed
788 789 790 791 792
    _ui.actionLiftoff->setEnabled(false);
    _ui.actionLand->setEnabled(false);
    _ui.actionEmergency_Kill->setEnabled(false);
    _ui.actionEmergency_Land->setEnabled(false);
    _ui.actionShutdownMAV->setEnabled(false);
793 794

    // Connect actions from ui
dogmaphobic's avatar
dogmaphobic committed
795
    connect(_ui.actionAdd_Link, SIGNAL(triggered()), this, SLOT(manageLinks()));
796 797 798

    // Connect internal actions
    connect(UASManager::instance(), SIGNAL(UASCreated(UASInterface*)), this, SLOT(UASCreated(UASInterface*)));
799
    connect(UASManager::instance(), SIGNAL(UASDeleted(int)), this, SLOT(UASDeleted(int)));
800 801

    // Unmanned System controls
dogmaphobic's avatar
dogmaphobic committed
802 803 804 805 806
    connect(_ui.actionLiftoff, SIGNAL(triggered()), UASManager::instance(), SLOT(launchActiveUAS()));
    connect(_ui.actionLand, SIGNAL(triggered()), UASManager::instance(), SLOT(returnActiveUAS()));
    connect(_ui.actionEmergency_Land, SIGNAL(triggered()), UASManager::instance(), SLOT(stopActiveUAS()));
    connect(_ui.actionEmergency_Kill, SIGNAL(triggered()), UASManager::instance(), SLOT(killActiveUAS()));
    connect(_ui.actionShutdownMAV, SIGNAL(triggered()), UASManager::instance(), SLOT(shutdownActiveUAS()));
807 808

    // Views actions
809
    connect(_ui.actionFlight, SIGNAL(triggered()), this, SLOT(loadFlightView()));
dogmaphobic's avatar
dogmaphobic committed
810
    connect(_ui.actionSimulationView, SIGNAL(triggered()), this, SLOT(loadSimulationView()));
811 812 813
    connect(_ui.actionAnalyze, SIGNAL(triggered()), this, SLOT(loadAnalyzeView()));
    connect(_ui.actionPlan, SIGNAL(triggered()), this, SLOT(loadPlanView()));
    connect(_ui.actionExperimentalPlanView, SIGNAL(triggered()), this, SLOT(loadOldPlanView()));
814 815

    // Help Actions
dogmaphobic's avatar
dogmaphobic committed
816 817 818
    connect(_ui.actionOnline_Documentation, SIGNAL(triggered()), this, SLOT(showHelp()));
    connect(_ui.actionDeveloper_Credits, SIGNAL(triggered()), this, SLOT(showCredits()));
    connect(_ui.actionProject_Roadmap, SIGNAL(triggered()), this, SLOT(showRoadMap()));
819 820

    // Audio output
dogmaphobic's avatar
dogmaphobic committed
821 822 823
    _ui.actionMuteAudioOutput->setChecked(GAudioOutput::instance()->isMuted());
    connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), _ui.actionMuteAudioOutput, SLOT(setChecked(bool)));
    connect(_ui.actionMuteAudioOutput, SIGNAL(triggered(bool)), GAudioOutput::instance(), SLOT(mute(bool)));
824 825

    // Application Settings
dogmaphobic's avatar
dogmaphobic committed
826
    connect(_ui.actionSettings, SIGNAL(triggered()), this, SLOT(showSettings()));
827

dogmaphobic's avatar
dogmaphobic committed
828
    // Update Tool Bar
829
    _mainToolBar->setCurrentView(_currentView);
830 831
}

Don Gagne's avatar
Don Gagne committed
832
void MainWindow::_openUrl(const QString& url, const QString& errorMessage)
833
{
Don Gagne's avatar
Don Gagne committed
834
    if(!QDesktopServices::openUrl(QUrl(url))) {
dogmaphobic's avatar
dogmaphobic committed
835 836 837 838
        QMessageBox::critical(
            this,
            tr("Could not open information in browser"),
            errorMessage);
839 840 841
    }
}

Don Gagne's avatar
Don Gagne committed
842 843
void MainWindow::showHelp()
{
dogmaphobic's avatar
dogmaphobic committed
844 845 846
    _openUrl(
        "http://qgroundcontrol.org/users/start",
        tr("To get to the online help, please open http://qgroundcontrol.org/user_guide in a browser."));
Don Gagne's avatar
Don Gagne committed
847 848
}

849 850
void MainWindow::showCredits()
{
dogmaphobic's avatar
dogmaphobic committed
851 852 853
    _openUrl(
        "http://qgroundcontrol.org/credits",
        tr("To get to the credits, please open http://qgroundcontrol.org/credits in a browser."));
854 855 856 857
}

void MainWindow::showRoadMap()
{
dogmaphobic's avatar
dogmaphobic committed
858 859 860
    _openUrl(
        "http://qgroundcontrol.org/dev/roadmap",
        tr("To get to the online help, please open http://qgroundcontrol.org/roadmap in a browser."));
861 862 863 864
}

void MainWindow::showSettings()
{
dogmaphobic's avatar
dogmaphobic committed
865
#ifndef __mobile__
Don Gagne's avatar
Don Gagne committed
866
    SettingsDialog settings(joystick, this);
dogmaphobic's avatar
dogmaphobic committed
867 868 869
#else
    SettingsDialog settings(this);
#endif
Don Gagne's avatar
Don Gagne committed
870
    settings.exec();
871 872
}

873 874
void MainWindow::commsWidgetDestroyed(QObject *obj)
{
875 876
    // Do not dynamic cast or de-reference QObject, since object is either in destructor or may have already
    // been destroyed.
dogmaphobic's avatar
dogmaphobic committed
877
    if (_commsWidgetList.contains(obj))
878
    {
dogmaphobic's avatar
dogmaphobic committed
879
        _commsWidgetList.removeOne(obj);
880 881
    }
}
882 883 884

void MainWindow::UASCreated(UASInterface* uas)
{
885
    // The UAS actions are not enabled without connection to system
dogmaphobic's avatar
dogmaphobic committed
886 887 888 889 890
    _ui.actionLiftoff->setEnabled(true);
    _ui.actionLand->setEnabled(true);
    _ui.actionEmergency_Kill->setEnabled(true);
    _ui.actionEmergency_Land->setEnabled(true);
    _ui.actionShutdownMAV->setEnabled(true);
891

John Tapsell's avatar
John Tapsell committed
892
    connect(uas, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)), this, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)));
893
    connect(uas, SIGNAL(misconfigurationDetected(UASInterface*)), this, SLOT(handleMisconfiguration(UASInterface*)));
894

895
    // HIL
dogmaphobic's avatar
dogmaphobic committed
896
#ifndef __mobile__
897
    _showHILConfigurationWidgets();
dogmaphobic's avatar
dogmaphobic committed
898
#endif
899

900 901 902
    if (!linechartWidget)
    {
        linechartWidget = new Linecharts(this);
903
        linechartWidget->setVisible(false);
904
    }
905

906
    linechartWidget->addSource(mavlinkDecoder);
907
    if (_analyzeView != linechartWidget)
908
    {
909
        _analyzeView = linechartWidget;
910
    }
911 912
}

913 914 915 916 917 918 919 920
void MainWindow::UASDeleted(int uasId)
{
    if (_mapUasId2HilDockWidget.contains(uasId)) {
        _mapUasId2HilDockWidget[uasId]->deleteLater();
        _mapUasId2HilDockWidget.remove(uasId);
    }
}

921 922
/// Stores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_storeCurrentViewState(void)
923
{
924 925 926 927 928 929 930 931 932 933 934 935 936
    // HIL dock widgets are dynamic and are not part of the saved state
    _hideAllHilDockWidgets();
    // Save list of visible widgets
    bool firstWidget = true;
    QString widgetNames = "";
    foreach(QDockWidget* dockWidget, _mapName2DockWidget) {
        if (dockWidget->isVisible()) {
            if (!firstWidget) {
                widgetNames += ",";
            }
            widgetNames += dockWidget->objectName();
            firstWidget = false;
        }
937
    }
dogmaphobic's avatar
dogmaphobic committed
938 939 940
    settings.setValue(_getWindowStateKey() + "WIDGETS", widgetNames);
    settings.setValue(_getWindowStateKey(), saveState());
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
941 942
}

943 944
/// Restores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_loadCurrentViewState(void)
945
{
Don Gagne's avatar
Don Gagne committed
946
    QWidget* centerView = NULL;
947
    QString defaultWidgets;
948

949
    switch (_currentView) {
950
        case VIEW_SETUP:
951 952
            _buildSetupView();
            centerView = _setupView;
953
            break;
954

955 956 957
        case VIEW_ANALYZE:
            _buildAnalyzeView();
            centerView = _analyzeView;
958
            defaultWidgets = "PARAMETER_INTERFACE_DOCKWIDGET,FILE_VIEW_DOCKWIDGET";
959
            break;
960

961
        case VIEW_FLIGHT:
962 963
            _buildFlightView();
            centerView = _flightView;
964
            defaultWidgets = "COMMUNICATION_CONSOLE_DOCKWIDGET,UAS_INFO_INFOVIEW_DOCKWIDGET";
965
            break;
966

967 968 969
        case VIEW_PLAN:
            _buildPlanView();
            centerView = _planView;
970
            defaultWidgets = "WAYPOINT_LIST_DOCKWIDGET";
971
            break;
972

973 974 975 976 977 978
        case VIEW_EXPERIMENTAL_PLAN:
            _buildExperimentalPlanView();
            centerView = _experimentalPlanView;
            defaultWidgets.clear();
            break;

979
        case VIEW_SIMULATION:
980 981 982
            _buildSimView();
            centerView = _simView;
            defaultWidgets = "UNMANNED_SYSTEM_CONTROL_DOCKWIDGET,WAYPOINT_LIST_DOCKWIDGET,PARAMETER_INTERFACE_DOCKWIDGET,PRIMARY_FLIGHT_DISPLAY_DOCKWIDGET";
983
            break;
984

985 986
        default:
            Q_ASSERT(false);
987
            break;
988
    }
989

990 991 992 993 994 995 996 997
    // Remove old view
    if (_currentViewWidget) {
        _currentViewWidget->setVisible(false);
        Q_ASSERT(_centralLayout->count() == 1);
        QLayoutItem *child = _centralLayout->takeAt(0);
        Q_ASSERT(child);
        delete child;
    }
998

999 1000 1001 1002 1003
    // Add the new one
    Q_ASSERT(centerView);
    Q_ASSERT(_centralLayout->count() == 0);
    _currentViewWidget = centerView;
    _centralLayout->addWidget(_currentViewWidget);
1004
    _centralLayout->setContentsMargins(0, 0, 0, 0);
1005
    _currentViewWidget->setVisible(true);
1006

1007 1008 1009 1010
    // Hide all widgets from previous view
    _hideAllDockWidgets();

    // Restore the widgets for the new view
dogmaphobic's avatar
dogmaphobic committed
1011
    QString widgetNames = settings.value(_getWindowStateKey() + "WIDGETS", defaultWidgets).toString();
1012
    qDebug() << widgetNames;
1013 1014 1015 1016 1017
    if (!widgetNames.isEmpty()) {
        QStringList split = widgetNames.split(",");
        foreach (QString widgetName, split) {
            Q_ASSERT(!widgetName.isEmpty());
            _showDockWidget(widgetName, true);
1018 1019 1020
        }
    }

dogmaphobic's avatar
dogmaphobic committed
1021 1022
    if (settings.contains(_getWindowStateKey())) {
        restoreState(settings.value(_getWindowStateKey()).toByteArray());
1023
    }
1024

1025 1026
    // HIL dock widget are dynamic and don't take part in the saved window state, so this
    // need to happen after we restore state
dogmaphobic's avatar
dogmaphobic committed
1027
#ifndef __mobile__
1028
    _showHILConfigurationWidgets();
dogmaphobic's avatar
dogmaphobic committed
1029
#endif
1030 1031 1032 1033

    // There is a bug in Qt where a Canvas element inside a QQuickWidget does not
    // receive update requests. Here we emit a signal for them to get repainted.
    emit repaintCanvas();
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
}

void MainWindow::_hideAllHilDockWidgets(void)
{
    foreach(QDockWidget* dockWidget, _mapUasId2HilDockWidget) {
        dockWidget->setVisible(false);
    }
}

void MainWindow::_hideAllDockWidgets(void)
{
    foreach(QDockWidget* dockWidget, _mapName2DockWidget) {
        dockWidget->setVisible(false);
1047
    }
1048
    _hideAllHilDockWidgets();
1049
}
1050 1051

void MainWindow::_showDockWidgetAction(bool show)
1052
{
1053 1054 1055
    QAction* action = dynamic_cast<QAction*>(QObject::sender());
    Q_ASSERT(action);
    _showDockWidget(action->data().toString(), show);
1056
}
1057

1058

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
void MainWindow::handleMisconfiguration(UASInterface* uas)
{
    static QTime lastTime;
    // We have to debounce this signal
    if (!lastTime.isValid()) {
        lastTime.start();
    } else {
        if (lastTime.elapsed() < 10000) {
            lastTime.start();
            return;
        }
    }
dogmaphobic's avatar
dogmaphobic committed
1071 1072 1073 1074 1075 1076 1077
    // Ask user if they want to handle this now
    QMessageBox::StandardButton button =
        QGCMessageBox::question(
            tr("Missing or Invalid Onboard Configuration"),
            tr("The onboard system configuration is missing or incomplete. Do you want to resolve this now?"),
            QMessageBox::Ok | QMessageBox::Cancel,
            QMessageBox::Ok);
Don Gagne's avatar
Don Gagne committed
1078
    if (button == QMessageBox::Ok) {
dogmaphobic's avatar
dogmaphobic committed
1079
        // They want to handle it, make sure this system is selected
1080 1081
        UASManager::instance()->setActiveUAS(uas);
        // Flick to config view
1082
        loadSetupView();
1083 1084 1085
    }
}

1086
void MainWindow::loadAnalyzeView()
1087
{
1088
    if (_currentView != VIEW_ANALYZE)
1089
    {
1090
        _storeCurrentViewState();
1091 1092
        _currentView = VIEW_ANALYZE;
        _ui.actionAnalyze->setChecked(true);
1093
        _loadCurrentViewState();
1094 1095 1096
    }
}

1097
void MainWindow::loadPlanView()
1098
{
1099
    if (_currentView != VIEW_PLAN)
1100
    {
1101
        _storeCurrentViewState();
1102 1103
        _currentView = VIEW_PLAN;
        _ui.actionPlan->setChecked(true);
1104
        _loadCurrentViewState();
1105 1106
    }
}
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

void MainWindow::loadOldPlanView()
{
    if (_currentView != VIEW_EXPERIMENTAL_PLAN)
    {
        _storeCurrentViewState();
        _currentView = VIEW_EXPERIMENTAL_PLAN;
        _ui.actionExperimentalPlanView->setChecked(true);
        _loadCurrentViewState();
    }
}

1119
void MainWindow::loadSetupView()
1120
{
1121
    if (_currentView != VIEW_SETUP)
1122
    {
1123 1124
        _storeCurrentViewState();
        _currentView = VIEW_SETUP;
dogmaphobic's avatar
dogmaphobic committed
1125
        _ui.actionSetup->setChecked(true);
1126
        _loadCurrentViewState();
1127 1128 1129
    }
}

1130
void MainWindow::loadFlightView()
1131
{
1132
    if (_currentView != VIEW_FLIGHT)
1133
    {
1134 1135
        _storeCurrentViewState();
        _currentView = VIEW_FLIGHT;
1136
        _ui.actionFlight->setChecked(true);
1137
        _loadCurrentViewState();
1138 1139 1140
    }
}

1141 1142
void MainWindow::loadSimulationView()
{
1143
    if (_currentView != VIEW_SIMULATION)
1144
    {
1145 1146
        _storeCurrentViewState();
        _currentView = VIEW_SIMULATION;
dogmaphobic's avatar
dogmaphobic committed
1147
        _ui.actionSimulationView->setChecked(true);
1148
        _loadCurrentViewState();
1149 1150 1151
    }
}

Don Gagne's avatar
Don Gagne committed
1152
/// @brief Hides the spash screen if it is currently being shown
1153
void MainWindow::hideSplashScreen(void)
Don Gagne's avatar
Don Gagne committed
1154 1155 1156 1157 1158 1159 1160
{
    if (_splashScreen) {
        _splashScreen->hide();
        _splashScreen = NULL;
    }
}

1161 1162
void MainWindow::manageLinks()
{
dogmaphobic's avatar
dogmaphobic committed
1163
#ifndef __mobile__
1164
    SettingsDialog settings(joystick, this, SettingsDialog::ShowCommLinks);
dogmaphobic's avatar
dogmaphobic committed
1165 1166 1167
#else
    SettingsDialog settings(this, SettingsDialog::ShowCommLinks);
#endif
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    settings.exec();
}

/// @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);
}

/// @brief Restore (and connects) the last used connection (if any)
void MainWindow::restoreLastUsedConnection()
{
    // TODO This should check and see of the port/whatever is present
    // first. That is, if the last connection was to a PX4 on some serial
    // port, it should check and see if the port is present before making
    // the connection.
    QSettings settings;
    QString key(MAIN_SETTINGS_GROUP);
    key += "/LAST_CONNECTION";
    if(settings.contains(key)) {
1191
        QString connection = settings.value(key).toString();
1192
        // Create a link for it
1193
        LinkManager::instance()->createConnectedLink(connection);
1194 1195
    }
}
Don Gagne's avatar
Don Gagne committed
1196

1197 1198 1199 1200 1201
void MainWindow::_linkStateChange(LinkInterface*)
{
    emit repaintCanvas();
}

1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
void MainWindow::setPixelSizeFactor(double size) {
    if(size < 0.1) {
        size = 0.1;
    }
    _pixelFactor = size;
    emit pixelSizeChanged();
}

void MainWindow::setFontSizeFactor(double size) {
    if(size < 0.1) {
        size = 0.1;
    }
    _fontFactor = size;
    emit fontSizeChanged();
}

1218
#ifdef QGC_MOUSE_ENABLED_LINUX
1219 1220 1221
bool MainWindow::x11Event(XEvent *event)
{
    emit x11EventOccured(event);
1222
    return false;
1223
}
1224
#endif // QGC_MOUSE_ENABLED_LINUX
1225 1226 1227 1228 1229 1230 1231

#ifdef UNITTEST_BUILD
void MainWindow::_showQmlTestWidget(void)
{
    new QmlTestWidget();
}
#endif