MainWindow.cc 46.3 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 36 37 38

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>
#include <QGCHilLink.h>
#include <QGCHilConfiguration.h>
#include <QGCHilFlightGearConfiguration.h>
39
#include <QQuickView>
40 41
#include <QDesktopWidget>

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

74 75 76 77
#ifdef UNITTEST_BUILD
#include "QmlControls/QmlTestWidget.h"
#endif

78 79 80 81 82 83
#ifdef QGC_OSG_ENABLED
#include "Q3DWidgetFactory.h"
#endif

#include "LogCompressor.h"

84 85 86
/// The key under which the Main Window settings are saved
const char* MAIN_SETTINGS_GROUP = "QGC_MAINWINDOW";

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
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";
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";
const char* MainWindow::_debugConsoleDockWidgetName = "COMMUNICATION_CONSOLE_DOCKWIDGET";

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

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

Don Gagne's avatar
Don Gagne committed
114
MainWindow* MainWindow::instance(void)
115
{
Don Gagne's avatar
Don Gagne committed
116
    return _instance;
117 118
}

119 120
void MainWindow::deleteInstance(void)
{
Don Gagne's avatar
Don Gagne committed
121
    delete this;
122 123
}

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

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

dogmaphobic's avatar
dogmaphobic committed
145
    // Setup user interface
146
    loadSettings();
147
    emit initStatusChanged(tr("Setting up user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
dogmaphobic's avatar
dogmaphobic committed
148 149 150 151
    _ui.setupUi(this);
    // Make sure tool bar elements all fit before changing minimum width
    setMinimumWidth(926);
    configureWindowName();
152

153 154
    // Setup central widget with a layout to hold the views
    _centralLayout = new QVBoxLayout();
155
    _centralLayout->setContentsMargins(0,0,0,0);
156
    centralWidget()->setLayout(_centralLayout);
157 158 159
    // Set dock options
    setDockOptions(AnimatedDocks | AllowTabbedDocks | AllowNestedDocks);
    // Setup corners
160
    setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
161

162 163 164 165 166
    // 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
#ifdef Q_OS_LINUX
    menuBar()->setNativeMenuBar(false);
#endif
167 168 169 170
    
#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
171
    _ui.menuTools->addAction(qmlTestAction);
172
#endif
173

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

dogmaphobic's avatar
dogmaphobic committed
184 185 186
    // Setup UI state machines
    _centerStackActionGroup->setExclusive(true);
    // Status Bar
187
    setStatusBar(new QStatusBar(this));
188
    statusBar()->setSizeGripEnabled(true);
189

190
    emit initStatusChanged(tr("Building common widgets."), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
191
    _buildCommonWidgets();
192
    emit initStatusChanged(tr("Building common actions"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
193 194 195
    // Create actions
    connectCommonActions();
    // Connect user interface devices
196
    emit initStatusChanged(tr("Initializing joystick interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
197 198
    joystick = new JoystickInput();

199
#ifdef QGC_MOUSE_ENABLED_WIN
200
    emit initStatusChanged(tr("Initializing 3D mouse interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
201 202
    mouseInput = new Mouse3DInput(this);
    mouse = new Mouse6dofInput(mouseInput);
203
#endif //QGC_MOUSE_ENABLED_WIN
204

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

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

212 213 214 215
    // 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);

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

    // Set low power mode
dogmaphobic's avatar
dogmaphobic committed
223
    enableLowPowerMode(_lowPowerMode);
224
    emit initStatusChanged(tr("Restoring last view state"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
225
    // Restore the window setup
226
    _loadCurrentViewState();
227
    // Restore the window position and size
dogmaphobic's avatar
dogmaphobic committed
228 229
    emit initStatusChanged(tr("Restoring last window size"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
    if (settings.contains(_getWindowGeometryKey()))
230
    {
dogmaphobic's avatar
dogmaphobic committed
231
        restoreGeometry(settings.value(_getWindowGeometryKey()).toByteArray());
232 233 234 235
    }
    else
    {
        // Adjust the size
dogmaphobic's avatar
dogmaphobic committed
236
        const int screenWidth  = QApplication::desktop()->width();
237
        const int screenHeight = QApplication::desktop()->height();
Lorenz Meier's avatar
Lorenz Meier committed
238
        if (screenWidth < 1500)
239
        {
240
            resize(screenWidth, screenHeight - 80);
241 242 243 244 245 246 247
        }
        else
        {
            resize(screenWidth*0.67f, qMin(screenHeight, (int)(screenWidth*0.67f*0.67f)));
        }
    }

248 249 250
    // Make sure the proper fullscreen/normal menu item is checked properly.
    if (isFullScreen())
    {
dogmaphobic's avatar
dogmaphobic committed
251 252
        _ui.actionFullscreen->setChecked(true);
        _ui.actionNormal->setChecked(false);
253 254 255
    }
    else
    {
dogmaphobic's avatar
dogmaphobic committed
256 257
        _ui.actionFullscreen->setChecked(false);
        _ui.actionNormal->setChecked(true);
258 259 260
    }

    // And that they will stay checked properly after user input
261 262 263
    connect(_ui.actionFullscreen, &QAction::triggered, this, &MainWindow::fullScreenActionItemCallback);
    connect(_ui.actionNormal,     &QAction::triggered, this, &MainWindow::normalActionItemCallback);
    connect(_ui.actionStatusBar,  &QAction::triggered, this, &MainWindow::showStatusBarCallback);
264

265 266
    // 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
267
    _ui.actionSetup->setShortcut(QApplication::translate("MainWindow", "Meta+1", 0));
268 269 270
    _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
271 272 273
    _ui.actionLocal3DView->setShortcut(QApplication::translate("MainWindow", "Meta+5", 0));
    _ui.actionTerminalView->setShortcut(QApplication::translate("MainWindow", "Meta+6", 0));
    _ui.actionSimulationView->setShortcut(QApplication::translate("MainWindow", "Meta+7", 0));
dogmaphobic's avatar
dogmaphobic committed
274
    _ui.actionFullscreen->setShortcut(QApplication::translate("MainWindow", "Meta+Return", 0));
275
#else
dogmaphobic's avatar
dogmaphobic committed
276
    _ui.actionSetup->setShortcut(QApplication::translate("MainWindow", "Ctrl+1", 0));
Gus Grubba's avatar
Gus Grubba committed
277
    _ui.actionPlan->setShortcut(QApplication::translate("MainWindow", "Ctrl+2", 0));
278
    _ui.actionFlight->setShortcut(QApplication::translate("MainWindow", "Ctrl+3", 0));
Gus Grubba's avatar
Gus Grubba committed
279
    _ui.actionAnalyze->setShortcut(QApplication::translate("MainWindow", "Ctrl+4", 0));
Don Gagne's avatar
Don Gagne committed
280 281 282
    _ui.actionLocal3DView->setShortcut(QApplication::translate("MainWindow", "Ctrl+5", 0));
    _ui.actionTerminalView->setShortcut(QApplication::translate("MainWindow", "Ctrl+6", 0));
    _ui.actionSimulationView->setShortcut(QApplication::translate("MainWindow", "Ctrl+7", 0));
dogmaphobic's avatar
dogmaphobic committed
283
    _ui.actionFullscreen->setShortcut(QApplication::translate("MainWindow", "Ctrl+Return", 0));
284 285
#endif

286 287
    connect(&windowNameUpdateTimer, SIGNAL(timeout()), this, SLOT(configureWindowName()));
    windowNameUpdateTimer.start(15000);
288
    emit initStatusChanged(tr("Done"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
289 290

    if (!qgcApp()->runningUnitTests()) {
291 292
        _ui.actionStatusBar->setChecked(_showStatusBar);
        showStatusBarCallback(_showStatusBar);
293
        show();
dogmaphobic's avatar
dogmaphobic committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
#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
309
    }
310 311 312 313
}

MainWindow::~MainWindow()
{
dogmaphobic's avatar
dogmaphobic committed
314
    if (_simulationLink)
315
    {
dogmaphobic's avatar
dogmaphobic committed
316 317
        delete _simulationLink;
        _simulationLink = NULL;
318
    }
319 320
    if (joystick)
    {
321 322
        joystick->shutdown();
        joystick->wait(5000);
323 324 325 326
        delete joystick;
        joystick = NULL;
    }
    // Delete all UAS objects
dogmaphobic's avatar
dogmaphobic committed
327
    for (int i=0;i<_commsWidgetList.size();i++)
328
    {
dogmaphobic's avatar
dogmaphobic committed
329
        _commsWidgetList[i]->deleteLater();
330
    }
Don Gagne's avatar
Don Gagne committed
331
    _instance = NULL;
332 333 334 335 336 337 338
}

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

dogmaphobic's avatar
dogmaphobic committed
339
QString MainWindow::_getWindowStateKey()
340
{
341
	return QString::number(_currentView)+"_windowstate_";
342 343
}

dogmaphobic's avatar
dogmaphobic committed
344
QString MainWindow::_getWindowGeometryKey()
345 346 347 348
{
    return "_geometry";
}

349
void MainWindow::_buildCustomWidgets(void)
350
{
351
    Q_ASSERT(_customWidgets.count() == 0);
352
    // Create custom widgets
353 354
    _customWidgets = QGCToolWidget::createWidgetsFromSettings(this);
    if (_customWidgets.size() > 0)
355
    {
dogmaphobic's avatar
dogmaphobic committed
356
        _ui.menuTools->addSeparator();
357
    }
358
    foreach(QGCToolWidget* tool, _customWidgets) {
359 360
        // Check if this widget already has a parent, do not create it in this case
        QDockWidget* dock = dynamic_cast<QDockWidget*>(tool->parentWidget());
361 362
        if (!dock) {
            _createDockWidget(tool->getTitle(), tool->objectName(), Qt::BottomDockWidgetArea, tool);
363 364 365 366
        }
    }
}

367 368 369
void MainWindow::_createDockWidget(const QString& title, const QString& name, Qt::DockWidgetArea area, QWidget* innerWidget)
{
    Q_ASSERT(!_mapName2DockWidget.contains(name));
370
	
371 372 373 374 375
    // 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
376
    _ui.menuTools->addAction(action);
377 378 379 380 381 382 383 384 385 386 387 388 389
	
	// 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);
	}
	
390 391 392 393 394 395
    _mapName2DockWidget[name] = dockWidget;
    _mapDockWidget2Action[dockWidget] = action;
    addDockWidget(area, dockWidget);
}

void MainWindow::_buildCommonWidgets(void)
396 397
{
    // Add generic MAVLink decoder
dogmaphobic's avatar
dogmaphobic committed
398
    // TODO: This is never deleted
399
    mavlinkDecoder = new MAVLinkDecoder(MAVLinkProtocol::instance(), this);
John Tapsell's avatar
John Tapsell committed
400 401
    connect(mavlinkDecoder, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),
                      this, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)));
402

403
    // Log player
dogmaphobic's avatar
dogmaphobic committed
404
    // TODO: Make this optional with a preferences setting or under a "View" menu
405
    logPlayer = new QGCMAVLinkLogPlayer(MAVLinkProtocol::instance(), statusBar());
406
    statusBar()->addPermanentWidget(logPlayer);
407

408 409 410
    // 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.
411

412 413 414 415 416
    struct DockWidgetInfo {
        const char* name;
        const char* title;
        Qt::DockWidgetArea area;
    };
417

418 419 420 421 422
    static const struct DockWidgetInfo rgDockWidgetInfo[] = {
        { _uasControlDockWidgetName,        "Control",                  Qt::LeftDockWidgetArea },
        { _uasListDockWidgetName,           "Unmanned Systems",         Qt::RightDockWidgetArea },
        { _waypointsDockWidgetName,         "Mission Plan",             Qt::BottomDockWidgetArea },
        { _mavlinkDockWidgetName,           "MAVLink Inspector",        Qt::RightDockWidgetArea },
423
        { _parametersDockWidgetName,        "Parameter Editor",			Qt::RightDockWidgetArea },
424 425 426 427 428 429 430 431 432
        { _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 },
433
        { _debugConsoleDockWidgetName,      "Communications Console",   Qt::LeftDockWidgetArea },
434 435
    };
    static const size_t cDockWidgetInfo = sizeof(rgDockWidgetInfo) / sizeof(rgDockWidgetInfo[0]);
436

437 438 439
    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 */);
440 441
    }

442 443
    _buildCustomWidgets();
}
444

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

453
void MainWindow::_buildExperimentalPlanView(void)
454
{
455 456 457 458 459 460 461 462 463
    if (!_experimentalPlanView) {
        _experimentalPlanView = new QGCMapDisplay(this);
        _experimentalPlanView->setVisible(false);
    }
}

void MainWindow::_buildFlightView(void)
{
    if (!_flightView) {
dogmaphobic's avatar
dogmaphobic committed
464
        //_pilotView = new PrimaryFlightDisplay(this);
465 466
        _flightView = new QGCFlightDisplay(this);
        _flightView->setVisible(false);
467
    }
468 469
}

470
void MainWindow::_buildSetupView(void)
471
{
472 473 474 475
    if (!_setupView) {
        _setupView = new SetupView(this);
        _setupView->setVisible(false);
    }
476 477
}

478
void MainWindow::_buildAnalyzeView(void)
479
{
480 481 482
    if (!_analyzeView) {
        _analyzeView = new QGCDataPlot2D(this);
        _analyzeView->setVisible(false);
483 484
    }
}
485

486 487 488 489 490 491
void MainWindow::_buildSimView(void)
{
    if (!_simView) {
        _simView = new QGCMapTool(this);
        _simView->setVisible(false);
    }
492
}
493

494
void MainWindow::_buildTerminalView(void)
495
{
496 497 498 499
    if (!_terminalView) {
        _terminalView = new TerminalConsole(this);
        _terminalView->setVisible(false);
    }
500 501
}

502
void MainWindow::_buildLocal3DView(void)
503
{
504 505 506 507 508 509
#ifdef QGC_OSG_ENABLED
    if (!_local3DView) {
        _local3DView = Q3DWidgetFactory::get("PIXHAWK", this);
        _local3DView->setVisible(false);
    }
#endif
510 511
}

512 513
/// Shows or hides the specified dock widget, creating if necessary
void MainWindow::_showDockWidget(const QString& name, bool show)
514
{
515 516
    if (!_mapName2DockWidget.contains(name)) {
        qWarning() << "Attempt to show unknown dock widget" << name;
517 518
        return;
    }
519

520 521 522
    // Create the inner widget if we need to
    if (!_mapName2DockWidget[name]->widget()) {
        _createInnerDockWidget(name);
523
    }
524 525 526 527

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

529
    dockWidget->setVisible(show);
530

531 532 533 534 535 536 537 538 539
    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
540

541
    QWidget* widget = NULL;
542

543 544 545 546 547 548 549 550 551
    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) {
552
        widget = new ParameterEditorWidget(this);
553 554 555 556 557 558 559 560 561
    } 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) {
562 563 564 565
        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");
566 567
        HDDisplay *hddisplay = new HDDisplay(acceptList,"Flight Display",this);
        hddisplay->addSource(mavlinkDecoder);
568

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

576 577
        widget = hddisplay;
    } else if (widgetName == _pfdDockWidgetName) {
dogmaphobic's avatar
dogmaphobic committed
578 579
        widget = new QGCFlightDisplay(this);
        //widget = new PrimaryFlightDisplay(this);
580 581 582
    } else if (widgetName == _hudDockWidgetName) {
        widget = new HUD(320,240,this);
    } else if (widgetName == _uasInfoViewDockWidgetName) {
583 584 585
        QGCTabbedInfoView* pInfoView = new QGCTabbedInfoView(this);
        pInfoView->addSource(mavlinkDecoder);
        widget = pInfoView;
586 587 588 589
    } else if (widgetName == _debugConsoleDockWidgetName) {
        widget = new DebugConsole(this);
    } else {
        qWarning() << "Attempt to create unknown Inner Dock Widget" << widgetName;
590
    }
591

592 593 594 595 596
    if (widget) {
        QDockWidget* dockWidget = _mapName2DockWidget[widgetName];
        Q_CHECK_PTR(dockWidget);
        widget->setParent(dockWidget);
        dockWidget->setWidget(widget);
597 598
    }
}
599

600
void MainWindow::_showHILConfigurationWidgets(void)
601
{
602
    UASInterface* uas = UASManager::instance()->getActiveUAS();
603

604 605 606
    if (!uas) {
        return;
    }
607

608 609
    UAS* mav = dynamic_cast<UAS*>(uas);
    Q_ASSERT(mav);
610

611
    int uasId = mav->getUASID();
612

613
    if (!_mapUasId2HilDockWidget.contains(uasId)) {
614

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

621 622
        // Create inner widget and set it
        QWidget* widget = new QGCHilConfiguration(mav, dockWidget);
623

624 625
        widget->setParent(dockWidget);
        dockWidget->setWidget(widget);
626

627
        _mapUasId2HilDockWidget[uasId] = dockWidget;
628

629 630
        addDockWidget(Qt::LeftDockWidgetArea, dockWidget);
    }
631

632 633 634 635 636
    if (_currentView == VIEW_SIMULATION) {
        // HIL dock widgets only show up on simulation view
        foreach (QDockWidget* dockWidget, _mapUasId2HilDockWidget) {
            dockWidget->setVisible(true);
        }
637 638 639
    }
}

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

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

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

657 658
void MainWindow::closeEvent(QCloseEvent *event)
{
659
    // Disallow window close if there are active connections
660
    if (LinkManager::instance()->anyConnectedLinks()) {
dogmaphobic's avatar
dogmaphobic committed
661 662 663 664 665 666
        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);
667
        if (button == QMessageBox::Yes) {
668
            LinkManager::instance()->disconnectAll();
669 670 671 672
        } else {
            event->ignore();
            return;
        }
673 674
    }

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

687
void MainWindow::_createNewCustomWidget(void)
688
{
689
    if (QGCToolWidget::instances()->isEmpty())
690 691
    {
        // This is the first widget
dogmaphobic's avatar
dogmaphobic committed
692
        _ui.menuTools->addSeparator();
693
    }
694 695 696 697 698 699 700 701
    QString objectName;
    int customToolIndex = 0;
    //Find the next unique object name that we can use
    do {
        ++customToolIndex;
        objectName = QString("CUSTOM_TOOL_%1").arg(customToolIndex) + "DOCK";
    } while(QGCToolWidget::instances()->contains(objectName));
    QString title = tr("Custom Tool %1").arg(customToolIndex );
702
    QGCToolWidget* tool = new QGCToolWidget(objectName, title);
703 704 705
    tool->resize(100, 100);
    _createDockWidget(title, objectName, Qt::BottomDockWidgetArea, tool);
    _mapName2DockWidget[objectName]->setVisible(true);
706 707
}

708
void MainWindow::_loadCustomWidgetFromFile(void)
709
{
710 711 712
    QString fileName = QGCFileDialog::getOpenFileName(
        this, tr("Load Widget File"),
        QStandardPaths::writableLocation(QStandardPaths::DesktopLocation),
713
        tr("QGroundControl Widgets (*.qgw);;All Files (*)"));
714
    if (!fileName.isEmpty()) {
715 716 717
        QGCToolWidget* tool = new QGCToolWidget("", "", this);
        if (tool->loadSettings(fileName, true)) {
            QString objectName = tool->objectName() + "DOCK";
718

719 720
            _createDockWidget(tool->getTitle(), objectName, Qt::LeftDockWidgetArea, tool);
            _mapName2DockWidget[objectName]->widget()->setVisible(true);
721 722
        }
    }
723
    // TODO Add error dialog if widget could not be loaded
724 725 726 727
}

void MainWindow::loadSettings()
{
728
    // Why the screaming?
729
    QSettings settings;
730
    settings.beginGroup(MAIN_SETTINGS_GROUP);
dogmaphobic's avatar
dogmaphobic committed
731 732
    _autoReconnect = settings.value("AUTO_RECONNECT", _autoReconnect).toBool();
    _lowPowerMode  = settings.value("LOW_POWER_MODE", _lowPowerMode).toBool();
dogmaphobic's avatar
dogmaphobic committed
733
    _showStatusBar = settings.value("SHOW_STATUSBAR", _showStatusBar).toBool();
734
    settings.endGroup();
dogmaphobic's avatar
dogmaphobic committed
735 736 737
    // Select the proper view. Default to the flight view or load the last one used if it's supported.
    VIEW_SECTIONS currentViewCandidate = (VIEW_SECTIONS) settings.value("CURRENT_VIEW", _currentView).toInt();
    switch (currentViewCandidate) {
738 739 740
        case VIEW_ANALYZE:
        case VIEW_PLAN:
        case VIEW_EXPERIMENTAL_PLAN:
dogmaphobic's avatar
dogmaphobic committed
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
        case VIEW_FLIGHT:
        case VIEW_SIMULATION:
        case VIEW_SETUP:
        case VIEW_TERMINAL:
#ifdef QGC_OSG_ENABLED
        case VIEW_LOCAL3D:
#endif
            _currentView = currentViewCandidate;
            break;
        default:
            // Leave _currentView to the default
            break;
    }
    // Put it back, which will set it to a valid value
    settings.setValue("CURRENT_VIEW", _currentView);
756 757 758 759 760
}

void MainWindow::storeSettings()
{
    QSettings settings;
761
    settings.beginGroup(MAIN_SETTINGS_GROUP);
dogmaphobic's avatar
dogmaphobic committed
762 763
    settings.setValue("AUTO_RECONNECT", _autoReconnect);
    settings.setValue("LOW_POWER_MODE", _lowPowerMode);
764
    settings.setValue("SHOW_STATUSBAR", _showStatusBar);
765
    settings.endGroup();
dogmaphobic's avatar
dogmaphobic committed
766
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
767
	
768
    // Save the last current view in any case
769
    settings.setValue("CURRENT_VIEW", _currentView);
770 771
    settings.setValue(_getWindowStateKey(), saveState());
	
772
    // And save any custom weidgets
773
    QGCToolWidget::storeWidgetsToSettings(settings);
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
}

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
798
    _autoReconnect = enabled;
799 800 801 802 803 804 805 806 807
}

/**
* @brief Create all actions associated to the main window
*
**/
void MainWindow::connectCommonActions()
{
    // Bind together the perspective actions
dogmaphobic's avatar
dogmaphobic committed
808
    QActionGroup* perspectives = new QActionGroup(_ui.menuPerspectives);
809 810
    perspectives->addAction(_ui.actionAnalyze);
    perspectives->addAction(_ui.actionFlight);
dogmaphobic's avatar
dogmaphobic committed
811
    perspectives->addAction(_ui.actionSimulationView);
812
    perspectives->addAction(_ui.actionPlan);
dogmaphobic's avatar
dogmaphobic committed
813 814 815
    perspectives->addAction(_ui.actionSetup);
    perspectives->addAction(_ui.actionTerminalView);
    perspectives->addAction(_ui.actionLocal3DView);
816
    perspectives->addAction(_ui.actionExperimentalPlanView);
817 818
    perspectives->setExclusive(true);

819
    /* Hide the actions that are not relevant */
820
#ifndef QGC_OSG_ENABLED
dogmaphobic's avatar
dogmaphobic committed
821
    _ui.actionLocal3DView->setVisible(false);
822 823
#endif

824
    // Mark the right one as selected
825
    if (_currentView == VIEW_ANALYZE)
826
    {
827 828
        _ui.actionAnalyze->setChecked(true);
        _ui.actionAnalyze->activate(QAction::Trigger);
829
    }
830
    if (_currentView == VIEW_FLIGHT)
831
    {
832 833
        _ui.actionFlight->setChecked(true);
        _ui.actionFlight->activate(QAction::Trigger);
834
    }
835
    if (_currentView == VIEW_SIMULATION)
836
    {
dogmaphobic's avatar
dogmaphobic committed
837 838
        _ui.actionSimulationView->setChecked(true);
        _ui.actionSimulationView->activate(QAction::Trigger);
839
    }
840
    if (_currentView == VIEW_PLAN)
841
    {
842 843 844 845 846 847 848
        _ui.actionPlan->setChecked(true);
        _ui.actionPlan->activate(QAction::Trigger);
    }
    if (_currentView == VIEW_EXPERIMENTAL_PLAN)
    {
        _ui.actionExperimentalPlanView->setChecked(true);
        _ui.actionExperimentalPlanView->activate(QAction::Trigger);
849
    }
850
    if (_currentView == VIEW_SETUP)
851
    {
dogmaphobic's avatar
dogmaphobic committed
852 853
        _ui.actionSetup->setChecked(true);
        _ui.actionSetup->activate(QAction::Trigger);
854
    }
855
    if (_currentView == VIEW_TERMINAL)
856
    {
dogmaphobic's avatar
dogmaphobic committed
857 858
        _ui.actionTerminalView->setChecked(true);
        _ui.actionTerminalView->activate(QAction::Trigger);
859
    }
860
    if (_currentView == VIEW_LOCAL3D)
861
    {
dogmaphobic's avatar
dogmaphobic committed
862 863
        _ui.actionLocal3DView->setChecked(true);
        _ui.actionLocal3DView->activate(QAction::Trigger);
864
    }
865 866

    // The UAS actions are not enabled without connection to system
dogmaphobic's avatar
dogmaphobic committed
867 868 869 870 871
    _ui.actionLiftoff->setEnabled(false);
    _ui.actionLand->setEnabled(false);
    _ui.actionEmergency_Kill->setEnabled(false);
    _ui.actionEmergency_Land->setEnabled(false);
    _ui.actionShutdownMAV->setEnabled(false);
872 873

    // Connect actions from ui
dogmaphobic's avatar
dogmaphobic committed
874
    connect(_ui.actionAdd_Link, SIGNAL(triggered()), this, SLOT(manageLinks()));
875 876 877 878 879

    // Connect internal actions
    connect(UASManager::instance(), SIGNAL(UASCreated(UASInterface*)), this, SLOT(UASCreated(UASInterface*)));

    // Unmanned System controls
dogmaphobic's avatar
dogmaphobic committed
880 881 882 883 884
    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()));
885 886

    // Views actions
887
    connect(_ui.actionFlight, SIGNAL(triggered()), this, SLOT(loadFlightView()));
dogmaphobic's avatar
dogmaphobic committed
888
    connect(_ui.actionSimulationView, SIGNAL(triggered()), this, SLOT(loadSimulationView()));
889 890 891
    connect(_ui.actionAnalyze, SIGNAL(triggered()), this, SLOT(loadAnalyzeView()));
    connect(_ui.actionPlan, SIGNAL(triggered()), this, SLOT(loadPlanView()));
    connect(_ui.actionExperimentalPlanView, SIGNAL(triggered()), this, SLOT(loadOldPlanView()));
dogmaphobic's avatar
dogmaphobic committed
892 893
    connect(_ui.actionLocal3DView, SIGNAL(triggered()), this, SLOT(loadLocal3DView()));
    connect(_ui.actionTerminalView,SIGNAL(triggered()),this,SLOT(loadTerminalView()));
894 895

    // Help Actions
dogmaphobic's avatar
dogmaphobic committed
896 897 898
    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()));
899 900

    // Custom widget actions
dogmaphobic's avatar
dogmaphobic committed
901 902
    connect(_ui.actionNewCustomWidget, SIGNAL(triggered()), this, SLOT(_createNewCustomWidget()));
    connect(_ui.actionLoadCustomWidgetFile, SIGNAL(triggered()), this, SLOT(_loadCustomWidgetFromFile()));
903 904

    // Audio output
dogmaphobic's avatar
dogmaphobic committed
905 906 907
    _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)));
908 909

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

dogmaphobic's avatar
dogmaphobic committed
912 913 914
    connect(_ui.actionSimulate, SIGNAL(triggered(bool)), this, SLOT(simulateLink(bool)));

    // Update Tool Bar
915
    _mainToolBar->setCurrentView(_currentView);
916 917
}

Don Gagne's avatar
Don Gagne committed
918
void MainWindow::_openUrl(const QString& url, const QString& errorMessage)
919
{
Don Gagne's avatar
Don Gagne committed
920
    if(!QDesktopServices::openUrl(QUrl(url))) {
dogmaphobic's avatar
dogmaphobic committed
921 922 923 924
        QMessageBox::critical(
            this,
            tr("Could not open information in browser"),
            errorMessage);
925 926 927
    }
}

Don Gagne's avatar
Don Gagne committed
928 929
void MainWindow::showHelp()
{
dogmaphobic's avatar
dogmaphobic committed
930 931 932
    _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
933 934
}

935 936
void MainWindow::showCredits()
{
dogmaphobic's avatar
dogmaphobic committed
937 938 939
    _openUrl(
        "http://qgroundcontrol.org/credits",
        tr("To get to the credits, please open http://qgroundcontrol.org/credits in a browser."));
940 941 942 943
}

void MainWindow::showRoadMap()
{
dogmaphobic's avatar
dogmaphobic committed
944 945 946
    _openUrl(
        "http://qgroundcontrol.org/dev/roadmap",
        tr("To get to the online help, please open http://qgroundcontrol.org/roadmap in a browser."));
947 948 949 950
}

void MainWindow::showSettings()
{
Don Gagne's avatar
Don Gagne committed
951 952
    SettingsDialog settings(joystick, this);
    settings.exec();
953 954
}

955
void MainWindow::simulateLink(bool simulate) {
Don Gagne's avatar
Don Gagne committed
956
    if (simulate) {
dogmaphobic's avatar
dogmaphobic committed
957 958 959
        if (!_simulationLink) {
            _simulationLink = new MAVLinkSimulationLink(":/demo-log.txt");
            Q_CHECK_PTR(_simulationLink);
Don Gagne's avatar
Don Gagne committed
960
        }
dogmaphobic's avatar
dogmaphobic committed
961
        LinkManager::instance()->connectLink(_simulationLink);
Don Gagne's avatar
Don Gagne committed
962
    } else {
dogmaphobic's avatar
dogmaphobic committed
963 964
        Q_ASSERT(_simulationLink);
        LinkManager::instance()->disconnectLink(_simulationLink);
Don Gagne's avatar
Don Gagne committed
965
    }
966 967
}

968 969
void MainWindow::commsWidgetDestroyed(QObject *obj)
{
970 971
    // 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
972
    if (_commsWidgetList.contains(obj))
973
    {
dogmaphobic's avatar
dogmaphobic committed
974
        _commsWidgetList.removeOne(obj);
975 976
    }
}
977 978 979

void MainWindow::UASCreated(UASInterface* uas)
{
980
    // The UAS actions are not enabled without connection to system
dogmaphobic's avatar
dogmaphobic committed
981 982 983 984 985
    _ui.actionLiftoff->setEnabled(true);
    _ui.actionLand->setEnabled(true);
    _ui.actionEmergency_Kill->setEnabled(true);
    _ui.actionEmergency_Land->setEnabled(true);
    _ui.actionShutdownMAV->setEnabled(true);
986

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

990
    // HIL
991
    _showHILConfigurationWidgets();
992

993 994 995
    if (!linechartWidget)
    {
        linechartWidget = new Linecharts(this);
996
        linechartWidget->setVisible(false);
997
    }
998

999
    linechartWidget->addSource(mavlinkDecoder);
1000
    if (_analyzeView != linechartWidget)
1001
    {
1002
        _analyzeView = linechartWidget;
1003
    }
1004 1005
}

1006 1007
/// Stores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_storeCurrentViewState(void)
1008
{
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    // 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;
        }
1022
    }
dogmaphobic's avatar
dogmaphobic committed
1023 1024 1025
    settings.setValue(_getWindowStateKey() + "WIDGETS", widgetNames);
    settings.setValue(_getWindowStateKey(), saveState());
    settings.setValue(_getWindowGeometryKey(), saveGeometry());
1026 1027
}

1028 1029
/// Restores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_loadCurrentViewState(void)
1030
{
Don Gagne's avatar
Don Gagne committed
1031
    QWidget* centerView = NULL;
1032
    QString defaultWidgets;
1033

1034
    switch (_currentView) {
1035
        case VIEW_SETUP:
1036 1037
            _buildSetupView();
            centerView = _setupView;
1038
            break;
1039

1040 1041 1042
        case VIEW_ANALYZE:
            _buildAnalyzeView();
            centerView = _analyzeView;
1043
            defaultWidgets = "MAVLINK_INSPECTOR_DOCKWIDGET,PARAMETER_INTERFACE_DOCKWIDGET,FILE_VIEW_DOCKWIDGET,HEAD_UP_DISPLAY_DOCKWIDGET";
1044
            break;
1045

1046
        case VIEW_FLIGHT:
1047 1048 1049 1050
            _buildFlightView();
            centerView = _flightView;
            //defaultWidgets = "COMMUNICATION_CONSOLE_DOCKWIDGET,UAS_INFO_INFOVIEW_DOCKWIDGET";
            defaultWidgets.clear();
1051
            break;
1052

1053 1054 1055
        case VIEW_PLAN:
            _buildPlanView();
            centerView = _planView;
1056
            defaultWidgets = "UNMANNED_SYSTEM_LIST_DOCKWIDGET,WAYPOINT_LIST_DOCKWIDGET";
1057
            break;
1058

1059 1060 1061 1062 1063 1064
        case VIEW_EXPERIMENTAL_PLAN:
            _buildExperimentalPlanView();
            centerView = _experimentalPlanView;
            defaultWidgets.clear();
            break;

1065
        case VIEW_SIMULATION:
1066 1067 1068
            _buildSimView();
            centerView = _simView;
            defaultWidgets = "UNMANNED_SYSTEM_CONTROL_DOCKWIDGET,WAYPOINT_LIST_DOCKWIDGET,PARAMETER_INTERFACE_DOCKWIDGET,PRIMARY_FLIGHT_DISPLAY_DOCKWIDGET";
1069
            break;
1070

1071
        case VIEW_TERMINAL:
1072 1073
            _buildTerminalView();
            centerView = _terminalView;
1074
            break;
1075

1076
        case VIEW_LOCAL3D:
1077 1078
            _buildLocal3DView();
            centerView = _local3DView;
1079
            break;
1080
    }
1081

1082 1083 1084 1085 1086 1087 1088 1089
    // Remove old view
    if (_currentViewWidget) {
        _currentViewWidget->setVisible(false);
        Q_ASSERT(_centralLayout->count() == 1);
        QLayoutItem *child = _centralLayout->takeAt(0);
        Q_ASSERT(child);
        delete child;
    }
1090

1091 1092 1093 1094 1095
    // Add the new one
    Q_ASSERT(centerView);
    Q_ASSERT(_centralLayout->count() == 0);
    _currentViewWidget = centerView;
    _centralLayout->addWidget(_currentViewWidget);
1096
    _centralLayout->setContentsMargins(0, 0, 0, 0);
1097
    _currentViewWidget->setVisible(true);
1098

1099 1100 1101 1102
    // Hide all widgets from previous view
    _hideAllDockWidgets();

    // Restore the widgets for the new view
dogmaphobic's avatar
dogmaphobic committed
1103
    QString widgetNames = settings.value(_getWindowStateKey() + "WIDGETS", defaultWidgets).toString();
1104 1105 1106 1107 1108
    if (!widgetNames.isEmpty()) {
        QStringList split = widgetNames.split(",");
        foreach (QString widgetName, split) {
            Q_ASSERT(!widgetName.isEmpty());
            _showDockWidget(widgetName, true);
1109 1110 1111
        }
    }

dogmaphobic's avatar
dogmaphobic committed
1112 1113
    if (settings.contains(_getWindowStateKey())) {
        restoreState(settings.value(_getWindowStateKey()).toByteArray());
1114
    }
1115

1116 1117 1118
    // HIL dock widget are dynamic and don't take part in the saved window state, so this
    // need to happen after we restore state
    _showHILConfigurationWidgets();
1119 1120 1121 1122

    // 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();
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
}

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

void MainWindow::_hideAllDockWidgets(void)
{
    foreach(QDockWidget* dockWidget, _mapName2DockWidget) {
        dockWidget->setVisible(false);
1136
    }
1137
    _hideAllHilDockWidgets();
1138
}
1139 1140

void MainWindow::_showDockWidgetAction(bool show)
1141
{
1142 1143 1144
    QAction* action = dynamic_cast<QAction*>(QObject::sender());
    Q_ASSERT(action);
    _showDockWidget(action->data().toString(), show);
1145
}
1146

1147

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
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
1160 1161 1162 1163 1164 1165 1166
    // 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
1167
    if (button == QMessageBox::Ok) {
dogmaphobic's avatar
dogmaphobic committed
1168
        // They want to handle it, make sure this system is selected
1169 1170
        UASManager::instance()->setActiveUAS(uas);
        // Flick to config view
1171
        loadSetupView();
1172 1173 1174
    }
}

1175
void MainWindow::loadAnalyzeView()
1176
{
1177
    if (_currentView != VIEW_ANALYZE)
1178
    {
1179
        _storeCurrentViewState();
1180 1181
        _currentView = VIEW_ANALYZE;
        _ui.actionAnalyze->setChecked(true);
1182
        _loadCurrentViewState();
1183 1184 1185
    }
}

1186
void MainWindow::loadPlanView()
1187
{
1188
    if (_currentView != VIEW_PLAN)
1189
    {
1190
        _storeCurrentViewState();
1191 1192
        _currentView = VIEW_PLAN;
        _ui.actionPlan->setChecked(true);
1193
        _loadCurrentViewState();
1194 1195
    }
}
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207

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

1208
void MainWindow::loadSetupView()
1209
{
1210
    if (_currentView != VIEW_SETUP)
1211
    {
1212 1213
        _storeCurrentViewState();
        _currentView = VIEW_SETUP;
dogmaphobic's avatar
dogmaphobic committed
1214
        _ui.actionSetup->setChecked(true);
1215
        _loadCurrentViewState();
1216 1217 1218
    }
}

1219 1220
void MainWindow::loadTerminalView()
{
1221
    if (_currentView != VIEW_TERMINAL)
1222
    {
1223 1224
        _storeCurrentViewState();
        _currentView = VIEW_TERMINAL;
dogmaphobic's avatar
dogmaphobic committed
1225
        _ui.actionTerminalView->setChecked(true);
1226
        _loadCurrentViewState();
1227 1228 1229
    }
}

1230 1231
void MainWindow::loadLocal3DView()
{
1232
    if (_currentView != VIEW_LOCAL3D)
1233
    {
1234 1235
        _storeCurrentViewState();
        _currentView = VIEW_LOCAL3D;
dogmaphobic's avatar
dogmaphobic committed
1236
        _ui.actionLocal3DView->setChecked(true);
1237
        _loadCurrentViewState();
1238 1239
    }
}
1240

1241
void MainWindow::loadFlightView()
1242
{
1243
    if (_currentView != VIEW_FLIGHT)
1244
    {
1245 1246
        _storeCurrentViewState();
        _currentView = VIEW_FLIGHT;
1247
        _ui.actionFlight->setChecked(true);
1248
        _loadCurrentViewState();
1249 1250 1251
    }
}

1252 1253
void MainWindow::loadSimulationView()
{
1254
    if (_currentView != VIEW_SIMULATION)
1255
    {
1256 1257
        _storeCurrentViewState();
        _currentView = VIEW_SIMULATION;
dogmaphobic's avatar
dogmaphobic committed
1258
        _ui.actionSimulationView->setChecked(true);
1259
        _loadCurrentViewState();
1260 1261 1262
    }
}

Don Gagne's avatar
Don Gagne committed
1263
/// @brief Hides the spash screen if it is currently being shown
1264
void MainWindow::hideSplashScreen(void)
Don Gagne's avatar
Don Gagne committed
1265 1266 1267 1268 1269 1270 1271
{
    if (_splashScreen) {
        _splashScreen->hide();
        _splashScreen = NULL;
    }
}

1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
void MainWindow::manageLinks()
{
    SettingsDialog settings(joystick, this, SettingsDialog::ShowCommLinks);
    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)) {
1298
        QString connection = settings.value(key).toString();
1299
        // Create a link for it
1300
        LinkManager::instance()->createConnectedLink(connection);
1301 1302
    }
}
Don Gagne's avatar
Don Gagne committed
1303

1304 1305 1306 1307 1308
void MainWindow::_linkStateChange(LinkInterface*)
{
    emit repaintCanvas();
}

1309
#ifdef QGC_MOUSE_ENABLED_LINUX
1310 1311 1312
bool MainWindow::x11Event(XEvent *event)
{
    emit x11EventOccured(event);
1313
    return false;
1314
}
1315
#endif // QGC_MOUSE_ENABLED_LINUX
1316 1317 1318 1319 1320 1321 1322

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