MainWindow.cc 38.7 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 51 52
#include "MAVLinkProtocol.h"
#include "QGCWaypointListMulti.h"
#include "MainWindow.h"
#include "GAudioOutput.h"
#include "QGCMAVLinkLogPlayer.h"
Don Gagne's avatar
Don Gagne committed
53
#include "SettingsDialog.h"
54
#include "QGCMapTool.h"
55
#include "QGCMapDisplay.h"
56 57 58
#include "MAVLinkDecoder.h"
#include "QGCMAVLinkMessageSender.h"
#include "QGCRGBDView.h"
59
#include "UASQuickView.h"
60 61
#include "QGCDataPlot2D.h"
#include "Linecharts.h"
62 63
#include "QGCTabbedInfoView.h"
#include "UASRawStatusView.h"
64 65
#include "FlightDisplayView.h"
#include "FlightDisplayWidget.h"
66
#include "SetupView.h"
67
#include "QGCUASFileViewMulti.h"
Don Gagne's avatar
Don Gagne committed
68
#include "QGCApplication.h"
69
#include "QGCFileDialog.h"
Don Gagne's avatar
Don Gagne committed
70
#include "QGCMessageBox.h"
71
#include "QGCDockWidget.h"
72
#include "MultiVehicleManager.h"
Don Gagne's avatar
Don Gagne committed
73
#include "CustomCommandWidget.h"
74
#include "HomePositionManager.h"
Don Gagne's avatar
Don Gagne committed
75
#include "MissionEditor.h"
76

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

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

#include "LogCompressor.h"

87 88 89
/// The key under which the Main Window settings are saved
const char* MAIN_SETTINGS_GROUP = "QGC_MAINWINDOW";

90 91 92 93 94
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
95
const char* MainWindow::_customCommandWidgetName = "CUSTOM_COMMAND_DOCKWIDGET";
96 97 98 99 100 101 102 103 104 105
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
106 107
static MainWindow* _instance = NULL;   ///< @brief MainWindow singleton

108
MainWindow* MainWindow::_create(QSplashScreen* splashScreen)
109
{
Don Gagne's avatar
Don Gagne committed
110
    Q_ASSERT(_instance == NULL);
111
    new MainWindow(splashScreen);
Don Gagne's avatar
Don Gagne committed
112 113
    // _instance is set in constructor
    Q_ASSERT(_instance);
114 115 116
    return _instance;
}

Don Gagne's avatar
Don Gagne committed
117
MainWindow* MainWindow::instance(void)
118
{
Don Gagne's avatar
Don Gagne committed
119
    return _instance;
120 121
}

122 123
void MainWindow::deleteInstance(void)
{
Don Gagne's avatar
Don Gagne committed
124
    delete this;
125 126
}

Don Gagne's avatar
Don Gagne committed
127 128 129
/// @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
130 131 132
MainWindow::MainWindow(QSplashScreen* splashScreen)
    : _autoReconnect(false)
    , _lowPowerMode(false)
133
    , _showStatusBar(false)
dogmaphobic's avatar
dogmaphobic committed
134 135 136 137 138
    , _centerStackActionGroup(new QActionGroup(this))
    , _centralLayout(NULL)
    , _currentViewWidget(NULL)
    , _splashScreen(splashScreen)
    , _currentView(VIEW_SETUP)
139
{
Don Gagne's avatar
Don Gagne committed
140 141
    Q_ASSERT(_instance == NULL);
    _instance = this;
142

143 144 145
    if (splashScreen) {
        connect(this, &MainWindow::initStatusChanged, splashScreen, &QSplashScreen::showMessage);
    }
146

147 148 149 150
    // 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
151
    // Setup user interface
152
    loadSettings();
153
    emit initStatusChanged(tr("Setting up user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
dogmaphobic's avatar
dogmaphobic committed
154 155
    _ui.setupUi(this);
    // Make sure tool bar elements all fit before changing minimum width
dogmaphobic's avatar
dogmaphobic committed
156
    setMinimumWidth(1008);
dogmaphobic's avatar
dogmaphobic committed
157
    configureWindowName();
158

159 160
    // Setup central widget with a layout to hold the views
    _centralLayout = new QVBoxLayout();
161
    _centralLayout->setContentsMargins(0,0,0,0);
162
    centralWidget()->setLayout(_centralLayout);
163 164 165
    // Set dock options
    setDockOptions(AnimatedDocks | AllowTabbedDocks | AllowNestedDocks);
    // 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);
dogmaphobic's avatar
dogmaphobic committed
176
    _ui.menuTools->addAction(qmlTestAction);
177
#endif
178

dogmaphobic's avatar
dogmaphobic committed
179 180 181 182
    // Load QML Toolbar
    QDockWidget* widget = new QDockWidget(this);
    widget->setObjectName("ToolBarDockWidget");
    qmlRegisterType<MainToolBar>("QGroundControl.MainToolBar", 1, 0, "MainToolBar");
183
    _mainToolBar = new MainToolBar(widget);
dogmaphobic's avatar
dogmaphobic committed
184 185 186 187
    widget->setWidget(_mainToolBar);
    widget->setFeatures(QDockWidget::NoDockWidgetFeatures);
    widget->setTitleBarWidget(new QWidget(this)); // Disables the title bar
    addDockWidget(Qt::TopDockWidgetArea, widget);
188

dogmaphobic's avatar
dogmaphobic committed
189 190 191
    // Setup UI state machines
    _centerStackActionGroup->setExclusive(true);
    // Status Bar
192
    setStatusBar(new QStatusBar(this));
193
    statusBar()->setSizeGripEnabled(true);
194

195
    emit initStatusChanged(tr("Building common widgets."), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
196
    _buildCommonWidgets();
197
    emit initStatusChanged(tr("Building common actions"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
198 199 200
    // Create actions
    connectCommonActions();
    // Connect user interface devices
201
#ifdef QGC_MOUSE_ENABLED_WIN
202
    emit initStatusChanged(tr("Initializing 3D mouse interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
203 204
    mouseInput = new Mouse3DInput(this);
    mouse = new Mouse6dofInput(mouseInput);
205
#endif //QGC_MOUSE_ENABLED_WIN
206

207
#if QGC_MOUSE_ENABLED_LINUX
208
    emit initStatusChanged(tr("Initializing 3D mouse interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
209 210

    mouse = new Mouse6dofInput(this);
211
    connect(this, SIGNAL(x11EventOccured(XEvent*)), mouse, SLOT(handleX11Event(XEvent*)));
212
#endif //QGC_MOUSE_ENABLED_LINUX
213

214 215 216 217
    // 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);

218
    // Connect link
dogmaphobic's avatar
dogmaphobic committed
219
    if (_autoReconnect)
220
    {
221
        restoreLastUsedConnection();
222 223 224
    }

    // Set low power mode
dogmaphobic's avatar
dogmaphobic committed
225
    enableLowPowerMode(_lowPowerMode);
226
    emit initStatusChanged(tr("Restoring last view state"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
227
    // Restore the window setup
228
    _loadCurrentViewState();
dogmaphobic's avatar
dogmaphobic committed
229
#ifndef __mobile__
230

231
    // Restore the window position and size
dogmaphobic's avatar
dogmaphobic committed
232 233
    emit initStatusChanged(tr("Restoring last window size"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
    if (settings.contains(_getWindowGeometryKey()))
234
    {
dogmaphobic's avatar
dogmaphobic committed
235
        restoreGeometry(settings.value(_getWindowGeometryKey()).toByteArray());
236 237 238 239
    }
    else
    {
        // Adjust the size
240 241 242
        QScreen* scr = QApplication::primaryScreen();
        QSize scrSize = scr->availableSize();
        if (scrSize.width() <= 1280)
243
        {
244
            resize(scrSize.width(), scrSize.height());
245 246 247
        }
        else
        {
248 249 250
            int w = scrSize.width()  > 1600 ? 1600 : scrSize.width();
            int h = scrSize.height() >  800 ?  800 : scrSize.height();
            resize(w, h);
251
            move((scrSize.width() - w) / 2, (scrSize.height() - h) / 2);
252 253 254
        }
    }

255 256 257
    // Make sure the proper fullscreen/normal menu item is checked properly.
    if (isFullScreen())
    {
dogmaphobic's avatar
dogmaphobic committed
258 259
        _ui.actionFullscreen->setChecked(true);
        _ui.actionNormal->setChecked(false);
260 261 262
    }
    else
    {
dogmaphobic's avatar
dogmaphobic committed
263 264
        _ui.actionFullscreen->setChecked(false);
        _ui.actionNormal->setChecked(true);
265 266 267
    }

    // And that they will stay checked properly after user input
268 269
    connect(_ui.actionFullscreen, &QAction::triggered, this, &MainWindow::fullScreenActionItemCallback);
    connect(_ui.actionNormal,     &QAction::triggered, this, &MainWindow::normalActionItemCallback);
270 271
#endif

272
    connect(_ui.actionStatusBar,  &QAction::triggered, this, &MainWindow::showStatusBarCallback);
273

274 275
    // 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
276
    _ui.actionSetup->setShortcut(QApplication::translate("MainWindow", "Meta+1", 0));
277 278 279
    _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
280
    _ui.actionSimulationView->setShortcut(QApplication::translate("MainWindow", "Meta+5", 0));
dogmaphobic's avatar
dogmaphobic committed
281
    _ui.actionFullscreen->setShortcut(QApplication::translate("MainWindow", "Meta+Return", 0));
282
#else
dogmaphobic's avatar
dogmaphobic committed
283
    _ui.actionSetup->setShortcut(QApplication::translate("MainWindow", "Ctrl+1", 0));
Gus Grubba's avatar
Gus Grubba committed
284
    _ui.actionPlan->setShortcut(QApplication::translate("MainWindow", "Ctrl+2", 0));
285
    _ui.actionFlight->setShortcut(QApplication::translate("MainWindow", "Ctrl+3", 0));
Gus Grubba's avatar
Gus Grubba committed
286
    _ui.actionAnalyze->setShortcut(QApplication::translate("MainWindow", "Ctrl+4", 0));
Don Gagne's avatar
Don Gagne committed
287
    _ui.actionSimulationView->setShortcut(QApplication::translate("MainWindow", "Ctrl+5", 0));
dogmaphobic's avatar
dogmaphobic committed
288
    _ui.actionFullscreen->setShortcut(QApplication::translate("MainWindow", "Ctrl+Return", 0));
289 290
#endif

291 292
    connect(&windowNameUpdateTimer, SIGNAL(timeout()), this, SLOT(configureWindowName()));
    windowNameUpdateTimer.start(15000);
293
    emit initStatusChanged(tr("Done"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
294 295

    if (!qgcApp()->runningUnitTests()) {
296 297
        _ui.actionStatusBar->setChecked(_showStatusBar);
        showStatusBarCallback(_showStatusBar);
dogmaphobic's avatar
dogmaphobic committed
298
#ifdef __mobile__
299 300
        menuBar()->hide();
#endif
301
        show();
dogmaphobic's avatar
dogmaphobic committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
#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
317
    }
318 319 320 321 322
}

MainWindow::~MainWindow()
{
    // Delete all UAS objects
dogmaphobic's avatar
dogmaphobic committed
323
    for (int i=0;i<_commsWidgetList.size();i++)
324
    {
dogmaphobic's avatar
dogmaphobic committed
325
        _commsWidgetList[i]->deleteLater();
326
    }
Don Gagne's avatar
Don Gagne committed
327
    _instance = NULL;
328 329 330 331 332 333 334
}

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

dogmaphobic's avatar
dogmaphobic committed
335
QString MainWindow::_getWindowStateKey()
336
{
337
	return QString::number(_currentView)+"_windowstate_";
338 339
}

dogmaphobic's avatar
dogmaphobic committed
340
QString MainWindow::_getWindowGeometryKey()
341 342 343 344
{
    return "_geometry";
}

345 346 347
void MainWindow::_createDockWidget(const QString& title, const QString& name, Qt::DockWidgetArea area, QWidget* innerWidget)
{
    Q_ASSERT(!_mapName2DockWidget.contains(name));
348
	
349 350 351 352 353
    // 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
354
    _ui.menuTools->addAction(action);
355 356 357 358 359 360 361 362 363 364 365 366 367
	
	// 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);
	}
	
368 369 370 371 372 373
    _mapName2DockWidget[name] = dockWidget;
    _mapDockWidget2Action[dockWidget] = action;
    addDockWidget(area, dockWidget);
}

void MainWindow::_buildCommonWidgets(void)
374 375
{
    // Add generic MAVLink decoder
dogmaphobic's avatar
dogmaphobic committed
376
    // TODO: This is never deleted
377
    mavlinkDecoder = new MAVLinkDecoder(MAVLinkProtocol::instance(), this);
John Tapsell's avatar
John Tapsell committed
378 379
    connect(mavlinkDecoder, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),
                      this, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)));
380

381
    // Log player
dogmaphobic's avatar
dogmaphobic committed
382
    // TODO: Make this optional with a preferences setting or under a "View" menu
Don Gagne's avatar
Don Gagne committed
383
    logPlayer = new QGCMAVLinkLogPlayer(statusBar());
384
    statusBar()->addPermanentWidget(logPlayer);
385

386 387 388
    // 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.
389

390 391 392 393 394
    struct DockWidgetInfo {
        const char* name;
        const char* title;
        Qt::DockWidgetArea area;
    };
395

396 397 398 399 400
    static const struct DockWidgetInfo rgDockWidgetInfo[] = {
        { _uasControlDockWidgetName,        "Control",                  Qt::LeftDockWidgetArea },
        { _uasListDockWidgetName,           "Unmanned Systems",         Qt::RightDockWidgetArea },
        { _waypointsDockWidgetName,         "Mission Plan",             Qt::BottomDockWidgetArea },
        { _mavlinkDockWidgetName,           "MAVLink Inspector",        Qt::RightDockWidgetArea },
401
        { _parametersDockWidgetName,        "Parameter Editor",			Qt::RightDockWidgetArea },
Don Gagne's avatar
Don Gagne committed
402
        { _customCommandWidgetName,         "Custom Command",			Qt::RightDockWidgetArea },
403 404 405 406 407 408 409 410 411 412 413
        { _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]);
414

415 416 417
    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 */);
418
    }
419
}
420

421
void MainWindow::_buildPlanView(void)
422
{
423 424 425
    if (!_planView) {
        _planView = new QGCMapTool(this);
        _planView->setVisible(false);
426
    }
427
}
428

Don Gagne's avatar
Don Gagne committed
429 430 431 432 433 434 435 436
void MainWindow::_buildMissionEditorView(void)
{
    if (!_missionEditorView) {
        _missionEditorView = new MissionEditor(this);
        _missionEditorView->setVisible(false);
    }
}

437 438 439
void MainWindow::_buildFlightView(void)
{
    if (!_flightView) {
440
        _flightView = new FlightDisplayView(this);
441
        _flightView->setVisible(false);
442
    }
443 444
}

445
void MainWindow::_buildSetupView(void)
446
{
447 448 449 450
    if (!_setupView) {
        _setupView = new SetupView(this);
        _setupView->setVisible(false);
    }
451 452
}

453
void MainWindow::_buildAnalyzeView(void)
454
{
455 456 457
    if (!_analyzeView) {
        _analyzeView = new QGCDataPlot2D(this);
        _analyzeView->setVisible(false);
458 459
    }
}
460

461 462 463 464 465 466
void MainWindow::_buildSimView(void)
{
    if (!_simView) {
        _simView = new QGCMapTool(this);
        _simView->setVisible(false);
    }
467
}
468

469 470
/// Shows or hides the specified dock widget, creating if necessary
void MainWindow::_showDockWidget(const QString& name, bool show)
471
{
472
    if (!_mapName2DockWidget.contains(name)) {
Don Gagne's avatar
Don Gagne committed
473 474
        // 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.
475 476
        return;
    }
477

478 479 480
    // Create the inner widget if we need to
    if (!_mapName2DockWidget[name]->widget()) {
        _createInnerDockWidget(name);
481
    }
482 483 484 485

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

487
    dockWidget->setVisible(show);
488

489 490 491 492 493 494 495 496 497
    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
498

499
    QWidget* widget = NULL;
500

501 502 503 504 505 506 507 508 509
    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) {
510
        widget = new ParameterEditorWidget(this);
Don Gagne's avatar
Don Gagne committed
511 512
    } else if (widgetName == _customCommandWidgetName) {
        widget = new CustomCommandWidget(this);
513 514 515 516 517 518 519 520 521
    } 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) {
522 523 524 525
        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");
526 527
        HDDisplay *hddisplay = new HDDisplay(acceptList,"Flight Display",this);
        hddisplay->addSource(mavlinkDecoder);
528

529 530
        widget = hddisplay;
    } else if (widgetName == _hdd2DockWidgetName) {
531 532 533
        QStringList acceptList;
        acceptList.append("0,RAW_PRESSURE.pres_abs,hPa,65500");
        HDDisplay *hddisplay = new HDDisplay(acceptList,"Actuator Status",this);
534
        hddisplay->addSource(mavlinkDecoder);
535

536 537
        widget = hddisplay;
    } else if (widgetName == _pfdDockWidgetName) {
538
        widget = new FlightDisplayWidget(this);
539 540 541
    } else if (widgetName == _hudDockWidgetName) {
        widget = new HUD(320,240,this);
    } else if (widgetName == _uasInfoViewDockWidgetName) {
542 543 544
        QGCTabbedInfoView* pInfoView = new QGCTabbedInfoView(this);
        pInfoView->addSource(mavlinkDecoder);
        widget = pInfoView;
545 546
    } else {
        qWarning() << "Attempt to create unknown Inner Dock Widget" << widgetName;
547
    }
548

549 550 551 552 553
    if (widget) {
        QDockWidget* dockWidget = _mapName2DockWidget[widgetName];
        Q_CHECK_PTR(dockWidget);
        widget->setParent(dockWidget);
        dockWidget->setWidget(widget);
554 555
    }
}
556

dogmaphobic's avatar
dogmaphobic committed
557
#ifndef __mobile__
558
void MainWindow::_showHILConfigurationWidgets(void)
559
{
560
    Vehicle* vehicle = MultiVehicleManager::instance()->activeVehicle();
561

562
    if (!vehicle) {
563 564
        return;
    }
565

566
    UAS* mav = vehicle->uas();
567
    Q_ASSERT(mav);
568

569
    int uasId = mav->getUASID();
570

571
    if (!_mapUasId2HilDockWidget.contains(uasId)) {
572

573
        // Create QDockWidget
574
        QGCDockWidget* dockWidget = new QGCDockWidget(tr("HIL Config %1").arg(uasId), NULL, this);
575 576 577
        Q_CHECK_PTR(dockWidget);
        dockWidget->setObjectName(tr("HIL_CONFIG_%1").arg(uasId));
        dockWidget->setVisible (false);
578

579 580
        // Create inner widget and set it
        QWidget* widget = new QGCHilConfiguration(mav, dockWidget);
581

582 583
        widget->setParent(dockWidget);
        dockWidget->setWidget(widget);
584

585
        _mapUasId2HilDockWidget[uasId] = dockWidget;
586

587 588
        addDockWidget(Qt::LeftDockWidgetArea, dockWidget);
    }
589

590 591 592 593 594
    if (_currentView == VIEW_SIMULATION) {
        // HIL dock widgets only show up on simulation view
        foreach (QDockWidget* dockWidget, _mapUasId2HilDockWidget) {
            dockWidget->setVisible(true);
        }
595 596
    }
}
dogmaphobic's avatar
dogmaphobic committed
597
#endif
598

599
void MainWindow::fullScreenActionItemCallback(bool)
600
{
dogmaphobic's avatar
dogmaphobic committed
601
    _ui.actionNormal->setChecked(false);
602 603
}

604
void MainWindow::normalActionItemCallback(bool)
605
{
dogmaphobic's avatar
dogmaphobic committed
606
    _ui.actionFullscreen->setChecked(false);
607 608
}

609 610 611 612 613 614
void MainWindow::showStatusBarCallback(bool checked)
{
    _showStatusBar = checked;
    checked ? statusBar()->show() : statusBar()->hide();
}

615 616
void MainWindow::closeEvent(QCloseEvent *event)
{
617
    // Disallow window close if there are active connections
618
    if (LinkManager::instance()->anyConnectedLinks()) {
dogmaphobic's avatar
dogmaphobic committed
619 620 621 622 623 624
        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);
625 626 627 628 629 630 631 632 633 634
		if (button == QMessageBox::Yes) {
			LinkManager::instance()->disconnectAll();
			// The above disconnect causes a flurry of activity as the vehicle components are removed. This in turn
			// causes the Windows Version of Qt to crash if you allow the close event to be accepted. In order to prevent
			// the crash, we ignore the close event and setup a delayed timer to close the window after things settle down.
			QTimer::singleShot(1500, this, &MainWindow::_closeWindow);
		}

        event->ignore();
        return;
635 636
    }

637 638
    // This will process any remaining flight log save dialogs
    qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
639
    
640
    // Should not be any active connections
641 642
    Q_ASSERT(!LinkManager::instance()->anyConnectedLinks());
    
643
    _storeCurrentViewState();
644
    storeSettings();
645
    HomePositionManager::instance()->storeSettings();
646
    event->accept();
647 648 649 650
}

void MainWindow::loadSettings()
{
651
    // Why the screaming?
652
    QSettings settings;
653
    settings.beginGroup(MAIN_SETTINGS_GROUP);
654 655 656
    _autoReconnect  = settings.value("AUTO_RECONNECT",      _autoReconnect).toBool();
    _lowPowerMode   = settings.value("LOW_POWER_MODE",      _lowPowerMode).toBool();
    _showStatusBar  = settings.value("SHOW_STATUSBAR",      _showStatusBar).toBool();
657 658 659 660 661 662
    settings.endGroup();
}

void MainWindow::storeSettings()
{
    QSettings settings;
663
    settings.beginGroup(MAIN_SETTINGS_GROUP);
664 665 666
    settings.setValue("AUTO_RECONNECT",     _autoReconnect);
    settings.setValue("LOW_POWER_MODE",     _lowPowerMode);
    settings.setValue("SHOW_STATUSBAR",     _showStatusBar);
667
    settings.endGroup();
dogmaphobic's avatar
dogmaphobic committed
668
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
669
	
670
    // Save the last current view in any case
671
    settings.setValue("CURRENT_VIEW", _currentView);
672
    settings.setValue(_getWindowStateKey(), saveState());
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
}

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
697
    _autoReconnect = enabled;
698 699 700 701 702 703 704 705 706
}

/**
* @brief Create all actions associated to the main window
*
**/
void MainWindow::connectCommonActions()
{
    // Bind together the perspective actions
dogmaphobic's avatar
dogmaphobic committed
707
    QActionGroup* perspectives = new QActionGroup(_ui.menuPerspectives);
708 709
    perspectives->addAction(_ui.actionAnalyze);
    perspectives->addAction(_ui.actionFlight);
dogmaphobic's avatar
dogmaphobic committed
710
    perspectives->addAction(_ui.actionSimulationView);
711
    perspectives->addAction(_ui.actionPlan);
dogmaphobic's avatar
dogmaphobic committed
712
    perspectives->addAction(_ui.actionSetup);
713 714 715
    perspectives->setExclusive(true);

    // Mark the right one as selected
716
    if (_currentView == VIEW_ANALYZE)
717
    {
718 719
        _ui.actionAnalyze->setChecked(true);
        _ui.actionAnalyze->activate(QAction::Trigger);
720
    }
721
    if (_currentView == VIEW_FLIGHT)
722
    {
723 724
        _ui.actionFlight->setChecked(true);
        _ui.actionFlight->activate(QAction::Trigger);
725
    }
726
    if (_currentView == VIEW_SIMULATION)
727
    {
dogmaphobic's avatar
dogmaphobic committed
728 729
        _ui.actionSimulationView->setChecked(true);
        _ui.actionSimulationView->activate(QAction::Trigger);
730
    }
731
    if (_currentView == VIEW_PLAN || _currentView == VIEW_MISSIONEDITOR)
732
    {
733 734 735
        _ui.actionPlan->setChecked(true);
        _ui.actionPlan->activate(QAction::Trigger);
    }
736
    if (_currentView == VIEW_SETUP)
737
    {
dogmaphobic's avatar
dogmaphobic committed
738 739
        _ui.actionSetup->setChecked(true);
        _ui.actionSetup->activate(QAction::Trigger);
740
    }
741 742

    // Connect actions from ui
dogmaphobic's avatar
dogmaphobic committed
743
    connect(_ui.actionAdd_Link, SIGNAL(triggered()), this, SLOT(manageLinks()));
744 745

    // Connect internal actions
746 747
    connect(MultiVehicleManager::instance(), &MultiVehicleManager::vehicleAdded, this, &MainWindow::_vehicleAdded);
    connect(MultiVehicleManager::instance(), &MultiVehicleManager::vehicleRemoved, this, &MainWindow::_vehicleRemoved);
748 749

    // Views actions
Don Gagne's avatar
Don Gagne committed
750 751 752 753
    connect(_ui.actionFlight,           SIGNAL(triggered()), this, SLOT(loadFlightView()));
    connect(_ui.actionSimulationView,   SIGNAL(triggered()), this, SLOT(loadSimulationView()));
    connect(_ui.actionAnalyze,          SIGNAL(triggered()), this, SLOT(loadAnalyzeView()));
    connect(_ui.actionPlan,             SIGNAL(triggered()), this, SLOT(loadPlanView()));
754 755 756
    
    _ui.actionUseMissionEditor->setChecked(qgcApp()->useNewMissionEditor());
    connect(_ui.actionUseMissionEditor, &QAction::triggered, this, &MainWindow::_setUseMissionEditor);
Don Gagne's avatar
Don Gagne committed
757
    
758
    // Help Actions
dogmaphobic's avatar
dogmaphobic committed
759 760 761
    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()));
762 763

    // Audio output
dogmaphobic's avatar
dogmaphobic committed
764 765 766
    _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)));
767 768

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

dogmaphobic's avatar
dogmaphobic committed
771
    // Update Tool Bar
772
    _mainToolBar->setCurrentView(_currentView);
773 774
}

Don Gagne's avatar
Don Gagne committed
775
void MainWindow::_openUrl(const QString& url, const QString& errorMessage)
776
{
Don Gagne's avatar
Don Gagne committed
777
    if(!QDesktopServices::openUrl(QUrl(url))) {
dogmaphobic's avatar
dogmaphobic committed
778 779 780 781
        QMessageBox::critical(
            this,
            tr("Could not open information in browser"),
            errorMessage);
782 783 784
    }
}

Don Gagne's avatar
Don Gagne committed
785 786
void MainWindow::showHelp()
{
dogmaphobic's avatar
dogmaphobic committed
787 788 789
    _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
790 791
}

792 793
void MainWindow::showCredits()
{
dogmaphobic's avatar
dogmaphobic committed
794 795 796
    _openUrl(
        "http://qgroundcontrol.org/credits",
        tr("To get to the credits, please open http://qgroundcontrol.org/credits in a browser."));
797 798 799 800
}

void MainWindow::showRoadMap()
{
dogmaphobic's avatar
dogmaphobic committed
801 802 803
    _openUrl(
        "http://qgroundcontrol.org/dev/roadmap",
        tr("To get to the online help, please open http://qgroundcontrol.org/roadmap in a browser."));
804 805 806 807
}

void MainWindow::showSettings()
{
dogmaphobic's avatar
dogmaphobic committed
808
    SettingsDialog settings(this);
Don Gagne's avatar
Don Gagne committed
809
    settings.exec();
810 811
}

812 813
void MainWindow::commsWidgetDestroyed(QObject *obj)
{
814 815
    // 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
816
    if (_commsWidgetList.contains(obj))
817
    {
dogmaphobic's avatar
dogmaphobic committed
818
        _commsWidgetList.removeOne(obj);
819 820
    }
}
821

822
void MainWindow::_vehicleAdded(Vehicle* vehicle)
823
{
824
    connect(vehicle->uas(), SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)), this, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)));
825

826
    // HIL
dogmaphobic's avatar
dogmaphobic committed
827
#ifndef __mobile__
828
    _showHILConfigurationWidgets();
dogmaphobic's avatar
dogmaphobic committed
829
#endif
830

831 832 833
    if (!linechartWidget)
    {
        linechartWidget = new Linecharts(this);
834
        linechartWidget->setVisible(false);
835
    }
836

837
    linechartWidget->addSource(mavlinkDecoder);
838
    if (_analyzeView != linechartWidget)
839
    {
840
        _analyzeView = linechartWidget;
841
    }
842 843
}

844
void MainWindow::_vehicleRemoved(Vehicle* vehicle)
845
{
846 847 848 849 850
    int vehicleId = vehicle->id();
    
    if (_mapUasId2HilDockWidget.contains(vehicleId)) {
        _mapUasId2HilDockWidget[vehicleId]->deleteLater();
        _mapUasId2HilDockWidget.remove(vehicleId);
851 852 853
    }
}

854 855
/// Stores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_storeCurrentViewState(void)
856
{
857 858 859 860 861 862 863 864 865 866 867 868 869
    // 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;
        }
870
    }
dogmaphobic's avatar
dogmaphobic committed
871 872 873
    settings.setValue(_getWindowStateKey() + "WIDGETS", widgetNames);
    settings.setValue(_getWindowStateKey(), saveState());
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
874 875
}

876 877
/// Restores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_loadCurrentViewState(void)
878
{
Don Gagne's avatar
Don Gagne committed
879
    QWidget* centerView = NULL;
880
    QString defaultWidgets;
881

882
    switch (_currentView) {
883
        case VIEW_SETUP:
884 885
            _buildSetupView();
            centerView = _setupView;
886
            break;
887

888 889 890
        case VIEW_ANALYZE:
            _buildAnalyzeView();
            centerView = _analyzeView;
891
            defaultWidgets = "PARAMETER_INTERFACE_DOCKWIDGET,FILE_VIEW_DOCKWIDGET";
892
            break;
893

894
        case VIEW_FLIGHT:
895 896
            _buildFlightView();
            centerView = _flightView;
897
            defaultWidgets = "COMMUNICATION_CONSOLE_DOCKWIDGET,UAS_INFO_INFOVIEW_DOCKWIDGET";
898
            break;
899

900 901 902
        case VIEW_PLAN:
            _buildPlanView();
            centerView = _planView;
903
            defaultWidgets = "WAYPOINT_LIST_DOCKWIDGET";
904
            break;
905

Don Gagne's avatar
Don Gagne committed
906 907 908 909 910
        case VIEW_MISSIONEDITOR:
            _buildMissionEditorView();
            centerView = _missionEditorView;
            break;

911
        case VIEW_SIMULATION:
912 913 914
            _buildSimView();
            centerView = _simView;
            defaultWidgets = "UNMANNED_SYSTEM_CONTROL_DOCKWIDGET,WAYPOINT_LIST_DOCKWIDGET,PARAMETER_INTERFACE_DOCKWIDGET,PRIMARY_FLIGHT_DISPLAY_DOCKWIDGET";
915
            break;
916

917 918
        default:
            Q_ASSERT(false);
919
            break;
920
    }
921

922 923 924 925 926 927 928 929
    // Remove old view
    if (_currentViewWidget) {
        _currentViewWidget->setVisible(false);
        Q_ASSERT(_centralLayout->count() == 1);
        QLayoutItem *child = _centralLayout->takeAt(0);
        Q_ASSERT(child);
        delete child;
    }
930

931 932 933 934 935
    // Add the new one
    Q_ASSERT(centerView);
    Q_ASSERT(_centralLayout->count() == 0);
    _currentViewWidget = centerView;
    _centralLayout->addWidget(_currentViewWidget);
936
    _centralLayout->setContentsMargins(0, 0, 0, 0);
937
    _currentViewWidget->setVisible(true);
938

939 940 941 942
    // Hide all widgets from previous view
    _hideAllDockWidgets();

    // Restore the widgets for the new view
dogmaphobic's avatar
dogmaphobic committed
943
    QString widgetNames = settings.value(_getWindowStateKey() + "WIDGETS", defaultWidgets).toString();
944
    qDebug() << widgetNames;
945 946 947 948 949
    if (!widgetNames.isEmpty()) {
        QStringList split = widgetNames.split(",");
        foreach (QString widgetName, split) {
            Q_ASSERT(!widgetName.isEmpty());
            _showDockWidget(widgetName, true);
950 951 952
        }
    }

dogmaphobic's avatar
dogmaphobic committed
953 954
    if (settings.contains(_getWindowStateKey())) {
        restoreState(settings.value(_getWindowStateKey()).toByteArray());
955
    }
956

957 958
    // 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
959
#ifndef __mobile__
960
    _showHILConfigurationWidgets();
dogmaphobic's avatar
dogmaphobic committed
961
#endif
962 963 964 965

    // 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();
966 967 968 969 970 971 972 973 974 975 976 977 978
}

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

void MainWindow::_hideAllDockWidgets(void)
{
    foreach(QDockWidget* dockWidget, _mapName2DockWidget) {
        dockWidget->setVisible(false);
979
    }
980
    _hideAllHilDockWidgets();
981
}
982 983

void MainWindow::_showDockWidgetAction(bool show)
984
{
985 986 987
    QAction* action = dynamic_cast<QAction*>(QObject::sender());
    Q_ASSERT(action);
    _showDockWidget(action->data().toString(), show);
988
}
989

990

991
void MainWindow::loadAnalyzeView()
992
{
993
    if (_currentView != VIEW_ANALYZE)
994
    {
995
        _storeCurrentViewState();
996 997
        _currentView = VIEW_ANALYZE;
        _ui.actionAnalyze->setChecked(true);
998
        _loadCurrentViewState();
999 1000 1001
    }
}

1002
void MainWindow::loadPlanView()
1003
{
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    if (qgcApp()->useNewMissionEditor()) {
        if (_currentView != VIEW_MISSIONEDITOR)
        {
            _storeCurrentViewState();
            _currentView = VIEW_MISSIONEDITOR;
            _ui.actionPlan->setChecked(true);
            _loadCurrentViewState();
        }
    } else {
        if (_currentView != VIEW_PLAN)
        {
            _storeCurrentViewState();
            _currentView = VIEW_PLAN;
            _ui.actionPlan->setChecked(true);
            _loadCurrentViewState();
        }
Don Gagne's avatar
Don Gagne committed
1020 1021 1022
    }
}

1023
void MainWindow::loadSetupView()
1024
{
1025
    if (_currentView != VIEW_SETUP)
1026
    {
1027 1028
        _storeCurrentViewState();
        _currentView = VIEW_SETUP;
dogmaphobic's avatar
dogmaphobic committed
1029
        _ui.actionSetup->setChecked(true);
1030
        _loadCurrentViewState();
1031 1032 1033
    }
}

1034
void MainWindow::loadFlightView()
1035
{
1036
    if (_currentView != VIEW_FLIGHT)
1037
    {
1038 1039
        _storeCurrentViewState();
        _currentView = VIEW_FLIGHT;
1040
        _ui.actionFlight->setChecked(true);
1041
        _loadCurrentViewState();
1042 1043 1044
    }
}

1045 1046
void MainWindow::loadSimulationView()
{
1047
    if (_currentView != VIEW_SIMULATION)
1048
    {
1049 1050
        _storeCurrentViewState();
        _currentView = VIEW_SIMULATION;
dogmaphobic's avatar
dogmaphobic committed
1051
        _ui.actionSimulationView->setChecked(true);
1052
        _loadCurrentViewState();
1053 1054 1055
    }
}

Don Gagne's avatar
Don Gagne committed
1056
/// @brief Hides the spash screen if it is currently being shown
1057
void MainWindow::hideSplashScreen(void)
Don Gagne's avatar
Don Gagne committed
1058 1059 1060 1061 1062 1063 1064
{
    if (_splashScreen) {
        _splashScreen->hide();
        _splashScreen = NULL;
    }
}

1065 1066
void MainWindow::manageLinks()
{
dogmaphobic's avatar
dogmaphobic committed
1067
    SettingsDialog settings(this, SettingsDialog::ShowCommLinks);
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    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)) {
1091
        QString connection = settings.value(key).toString();
1092
        // Create a link for it
1093
        LinkManager::instance()->createConnectedLink(connection);
1094 1095
    }
}
Don Gagne's avatar
Don Gagne committed
1096

1097 1098 1099 1100 1101
void MainWindow::_linkStateChange(LinkInterface*)
{
    emit repaintCanvas();
}

1102
#ifdef QGC_MOUSE_ENABLED_LINUX
1103 1104 1105
bool MainWindow::x11Event(XEvent *event)
{
    emit x11EventOccured(event);
1106
    return false;
1107
}
1108
#endif // QGC_MOUSE_ENABLED_LINUX
1109 1110 1111 1112 1113 1114 1115

#ifdef UNITTEST_BUILD
void MainWindow::_showQmlTestWidget(void)
{
    new QmlTestWidget();
}
#endif
1116 1117 1118 1119 1120

void MainWindow::_setUseMissionEditor(bool checked)
{
    qgcApp()->setUseNewMissionEditor(checked);
}