MainWindow.cc 51.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 52 53
#include "QGC.h"
#include "MAVLinkSimulationLink.h"
#include "SerialLink.h"
#include "UDPLink.h"
#include "MAVLinkProtocol.h"
#include "CommConfigurationWindow.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
54
#include "SettingsDialog.h"
55 56 57 58
#include "QGCMapTool.h"
#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
#include "PrimaryFlightDisplay.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 78 79

#ifdef QGC_OSG_ENABLED
#include "Q3DWidgetFactory.h"
#endif

#include "LogCompressor.h"

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
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
96 97 98
static MainWindow* _instance = NULL;   ///< @brief MainWindow singleton

MainWindow* MainWindow::_create(QSplashScreen* splashScreen, enum MainWindow::CUSTOM_MODE mode)
99
{
Don Gagne's avatar
Don Gagne committed
100 101 102 103 104 105 106
    Q_ASSERT(_instance == NULL);
    
    new MainWindow(splashScreen, mode);
    
    // _instance is set in constructor
    Q_ASSERT(_instance);

107 108 109
    return _instance;
}

Don Gagne's avatar
Don Gagne committed
110
MainWindow* MainWindow::instance(void)
111
{
Don Gagne's avatar
Don Gagne committed
112
    return _instance;
113 114
}

115 116
void MainWindow::deleteInstance(void)
{
Don Gagne's avatar
Don Gagne committed
117
    delete this;
118 119
}

Don Gagne's avatar
Don Gagne committed
120 121 122 123
/// @brief Private constructor for MainWindow. MainWindow singleton is only ever created
///         by MainWindow::_create method. Hence no other code should have access to
///         constructor.
MainWindow::MainWindow(QSplashScreen* splashScreen, enum MainWindow::CUSTOM_MODE mode) :
124 125
    centerStackActionGroup(new QActionGroup(this)),
    autoReconnect(false),
126
    simulationLink(NULL),
127
    lowPowerMode(false),
Don Gagne's avatar
Don Gagne committed
128
    customMode(mode),
129 130
    _currentView(VIEW_FLIGHT),
    _currentViewWidget(NULL),
Don Gagne's avatar
Don Gagne committed
131
    _splashScreen(splashScreen)
132
{
Don Gagne's avatar
Don Gagne committed
133 134 135
    Q_ASSERT(_instance == NULL);
    _instance = this;
    
136 137 138
    if (splashScreen) {
        connect(this, &MainWindow::initStatusChanged, splashScreen, &QSplashScreen::showMessage);
    }
Don Gagne's avatar
Don Gagne committed
139
    
140
    loadSettings();
Don Gagne's avatar
Don Gagne committed
141
    
142
    // Select the proper view. Default to the flight view or load the last one used if it's supported.
143 144 145 146 147 148 149 150
    VIEW_SECTIONS currentViewCandidate = (VIEW_SECTIONS) settings.value("CURRENT_VIEW", _currentView).toInt();
    switch (currentViewCandidate) {
        case VIEW_ENGINEER:
        case VIEW_MISSION:
        case VIEW_FLIGHT:
        case VIEW_SIMULATION:
        case VIEW_SETUP:
        case VIEW_TERMINAL:
151
#ifdef QGC_OSG_ENABLED
152
        case VIEW_LOCAL3D:
153 154
#endif
#ifdef QGC_GOOGLE_EARTH_ENABLED
155
        case VIEW_GOOGLEEARTH:
156
#endif
157 158 159 160 161 162
            _currentView = currentViewCandidate;
            break;
            
        default:
            // Leave _currentView to the default
            break;
163
    }
164 165 166
    
    // Put it back, which will set it to a valid value
    settings.setValue("CURRENT_VIEW", _currentView);
167

168
    emit initStatusChanged(tr("Setting up user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
169 170 171

    // Setup user interface
    ui.setupUi(this);
172 173 174 175
    
    // Setup central widget with a layout to hold the views
    _centralLayout = new QVBoxLayout();
    centralWidget()->setLayout(_centralLayout);
176

177 178 179 180 181 182
    // Set dock options
    setDockOptions(AnimatedDocks | AllowTabbedDocks | AllowNestedDocks);

    configureWindowName();

    // Setup corners
183
    setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);
184

185 186 187 188 189 190
    // 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

191
    // Setup UI state machines
192
    centerStackActionGroup->setExclusive(true);
193 194

    // Load Toolbar
Don Gagne's avatar
Don Gagne committed
195 196
    toolBar = new QGCToolBar(this);
    this->addToolBar(toolBar);
197

Bryant's avatar
Bryant committed
198
    // Add the perspectives to the toolbar
Don Gagne's avatar
Don Gagne committed
199
    QList<QAction*> actions;
200
    actions << ui.actionSetup;
Don Gagne's avatar
Don Gagne committed
201 202
    actions << ui.actionMissionView;
    actions << ui.actionFlightView;
203
    actions << ui.actionEngineersView;
Don Gagne's avatar
Don Gagne committed
204
    toolBar->setPerspectiveChangeActions(actions);
205

Don Gagne's avatar
Don Gagne committed
206 207 208 209 210 211 212
    // Add actions for advanced users (displayed in dropdown under "advanced")
    QList<QAction*> advancedActions;
    advancedActions << ui.actionGoogleEarthView;
    advancedActions << ui.actionLocal3DView;
    advancedActions << ui.actionTerminalView;
    advancedActions << ui.actionSimulationView;
    toolBar->setPerspectiveChangeAdvancedActions(advancedActions);
213

214
    setStatusBar(new QStatusBar(this));
215
    statusBar()->setSizeGripEnabled(true);
216

217
    emit initStatusChanged(tr("Building common widgets."), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
218

219
    _buildCommonWidgets();
220

221
    emit initStatusChanged(tr("Building common actions"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
222 223 224 225 226

    // Create actions
    connectCommonActions();

    // Populate link menu
227
    emit initStatusChanged(tr("Populating link menu"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
228 229 230
    QList<LinkInterface*> links = LinkManager::instance()->getLinks();
    foreach(LinkInterface* link, links)
    {
231
        _addLinkMenu(link);
232 233
    }

234 235
    connect(LinkManager::instance(), &LinkManager::newLink, this, &MainWindow::_addLinkMenu);
    
236
    // Connect user interface devices
237
    emit initStatusChanged(tr("Initializing joystick interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
238 239
    joystick = new JoystickInput();

240
#ifdef QGC_MOUSE_ENABLED_WIN
241
    emit initStatusChanged(tr("Initializing 3D mouse interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
242 243 244

    mouseInput = new Mouse3DInput(this);
    mouse = new Mouse6dofInput(mouseInput);
245
#endif //QGC_MOUSE_ENABLED_WIN
246

247
#if QGC_MOUSE_ENABLED_LINUX
248
    emit initStatusChanged(tr("Initializing 3D mouse interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
249 250

    mouse = new Mouse6dofInput(this);
251
    connect(this, SIGNAL(x11EventOccured(XEvent*)), mouse, SLOT(handleX11Event(XEvent*)));
252
#endif //QGC_MOUSE_ENABLED_LINUX
253

254 255 256
    // Connect link
    if (autoReconnect)
    {
Don Gagne's avatar
Don Gagne committed
257 258 259
        LinkManager* linkMgr = LinkManager::instance();
        Q_ASSERT(linkMgr);
        
260
        SerialLink* link = new SerialLink();
Don Gagne's avatar
Don Gagne committed
261
        
262
        // Add to registry
263
        linkMgr->addLink(link);
Don Gagne's avatar
Don Gagne committed
264
        linkMgr->connectLink(link);
265 266 267 268 269
    }

    // Set low power mode
    enableLowPowerMode(lowPowerMode);

270
    emit initStatusChanged(tr("Restoring last view state"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
271 272

    // Restore the window setup
273
    _loadCurrentViewState();
274

275
    emit initStatusChanged(tr("Restoring last window size"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
276 277 278 279 280 281 282 283 284 285 286 287
    // Restore the window position and size
    if (settings.contains(getWindowGeometryKey()))
    {
        // Restore the window geometry
        restoreGeometry(settings.value(getWindowGeometryKey()).toByteArray());
    }
    else
    {
        // Adjust the size
        const int screenWidth = QApplication::desktop()->width();
        const int screenHeight = QApplication::desktop()->height();

Lorenz Meier's avatar
Lorenz Meier committed
288
        if (screenWidth < 1500)
289
        {
290
            resize(screenWidth, screenHeight - 80);
291 292 293 294 295 296 297 298
        }
        else
        {
            resize(screenWidth*0.67f, qMin(screenHeight, (int)(screenWidth*0.67f*0.67f)));
        }

    }

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    // Make sure the proper fullscreen/normal menu item is checked properly.
    if (isFullScreen())
    {
        ui.actionFullscreen->setChecked(true);
        ui.actionNormal->setChecked(false);
    }
    else
    {
        ui.actionFullscreen->setChecked(false);
        ui.actionNormal->setChecked(true);
    }

    // And that they will stay checked properly after user input
    QObject::connect(ui.actionFullscreen, SIGNAL(triggered()), this, SLOT(fullScreenActionItemCallback()));
    QObject::connect(ui.actionNormal, SIGNAL(triggered()), this,SLOT(normalActionItemCallback()));


316 317
    // Set OS dependent keyboard shortcuts for the main window, non OS dependent shortcuts are set in MainWindow.ui
#ifdef Q_OS_MACX
318 319 320
    ui.actionSetup->setShortcut(QApplication::translate("MainWindow", "Meta+1", 0));
    ui.actionMissionView->setShortcut(QApplication::translate("MainWindow", "Meta+2", 0));
    ui.actionFlightView->setShortcut(QApplication::translate("MainWindow", "Meta+3", 0));
321 322 323 324 325
    ui.actionEngineersView->setShortcut(QApplication::translate("MainWindow", "Meta+4", 0));
    ui.actionGoogleEarthView->setShortcut(QApplication::translate("MainWindow", "Meta+5", 0));
    ui.actionLocal3DView->setShortcut(QApplication::translate("MainWindow", "Meta+6", 0));
    ui.actionTerminalView->setShortcut(QApplication::translate("MainWindow", "Meta+7", 0));
    ui.actionSimulationView->setShortcut(QApplication::translate("MainWindow", "Meta+8", 0));
326
    ui.actionFullscreen->setShortcut(QApplication::translate("MainWindow", "Meta+Return", 0));
327
#else
328 329 330
    ui.actionSetup->setShortcut(QApplication::translate("MainWindow", "Ctrl+1", 0));
    ui.actionMissionView->setShortcut(QApplication::translate("MainWindow", "Ctrl+2", 0));
    ui.actionFlightView->setShortcut(QApplication::translate("MainWindow", "Ctrl+3", 0));
331 332 333 334 335
    ui.actionEngineersView->setShortcut(QApplication::translate("MainWindow", "Ctrl+4", 0));
    ui.actionGoogleEarthView->setShortcut(QApplication::translate("MainWindow", "Ctrl+5", 0));
    ui.actionLocal3DView->setShortcut(QApplication::translate("MainWindow", "Ctrl+6", 0));
    ui.actionTerminalView->setShortcut(QApplication::translate("MainWindow", "Ctrl+7", 0));
    ui.actionSimulationView->setShortcut(QApplication::translate("MainWindow", "Ctrl+8", 0));
336
    ui.actionFullscreen->setShortcut(QApplication::translate("MainWindow", "Ctrl+Return", 0));
337 338
#endif

339 340
    connect(&windowNameUpdateTimer, SIGNAL(timeout()), this, SLOT(configureWindowName()));
    windowNameUpdateTimer.start(15000);
341
    emit initStatusChanged(tr("Done"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
342 343 344 345

	if (!qgcApp()->runningUnitTests()) {
		show();
	}
346 347 348 349
}

MainWindow::~MainWindow()
{
350 351 352 353 354
    if (simulationLink)
    {
        delete simulationLink;
        simulationLink = NULL;
    }
355 356
    if (joystick)
    {
357 358
        joystick->shutdown();
        joystick->wait(5000);
359 360 361 362 363
        delete joystick;
        joystick = NULL;
    }

    // Delete all UAS objects
364 365 366 367
    for (int i=0;i<commsWidgetList.size();i++)
    {
        commsWidgetList[i]->deleteLater();
    }
Don Gagne's avatar
Don Gagne committed
368 369
    
    _instance = NULL;
370 371 372 373 374 375 376 377 378
}

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

QString MainWindow::getWindowStateKey()
{
379 380
    if (UASManager::instance()->getActiveUAS())
    {
381
        return QString::number(_currentView)+"_windowstate_" + QString::number(getCustomMode()) + "_" + UASManager::instance()->getActiveUAS()->getAutopilotTypeName();
382 383
    }
    else
384
        return QString::number(_currentView)+"_windowstate_" + QString::number(getCustomMode());
385 386 387 388 389 390 391
}

QString MainWindow::getWindowGeometryKey()
{
    return "_geometry";
}

392
void MainWindow::_buildCustomWidgets(void)
393
{
394 395
    Q_ASSERT(_customWidgets.count() == 0);
    
396
    // Create custom widgets
397
    _customWidgets = QGCToolWidget::createWidgetsFromSettings(this);
398

399
    if (_customWidgets.size() > 0)
400 401 402
    {
        ui.menuTools->addSeparator();
    }
403 404
    
    foreach(QGCToolWidget* tool, _customWidgets) {
405 406
        // Check if this widget already has a parent, do not create it in this case
        QDockWidget* dock = dynamic_cast<QDockWidget*>(tool->parentWidget());
407 408 409
        
        if (!dock) {
            _createDockWidget(tool->getTitle(), tool->objectName(), Qt::BottomDockWidgetArea, tool);
410 411 412 413
        }
    }
}

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
void MainWindow::_createDockWidget(const QString& title, const QString& name, Qt::DockWidgetArea area, QWidget* innerWidget)
{
    Q_ASSERT(!_mapName2DockWidget.contains(name));
    
    QGCDockWidget* dockWidget = new QGCDockWidget(title, 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);
    }
    
    // Add to menu
    
    QAction* action = new QAction(title, NULL);
    action->setCheckable(true);
    action->setData(name);
    
    connect(action, &QAction::triggered, this, &MainWindow::_showDockWidgetAction);
    
    ui.menuTools->addAction(action);
    
    _mapName2DockWidget[name] = dockWidget;
    _mapDockWidget2Action[dockWidget] = action;
    
    addDockWidget(area, dockWidget);
}

void MainWindow::_buildCommonWidgets(void)
447 448
{
    // Add generic MAVLink decoder
449
    mavlinkDecoder = new MAVLinkDecoder(MAVLinkProtocol::instance(), this);
John Tapsell's avatar
John Tapsell committed
450 451
    connect(mavlinkDecoder, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)),
                      this, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)));
452

453
    // Log player
454
    logPlayer = new QGCMAVLinkLogPlayer(MAVLinkProtocol::instance(), statusBar());
455
    statusBar()->addPermanentWidget(logPlayer);
456

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    // 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.
    
    struct DockWidgetInfo {
        const char* name;
        const char* title;
        Qt::DockWidgetArea area;
    };
    
    static const struct DockWidgetInfo rgDockWidgetInfo[] = {
        { _uasControlDockWidgetName,        "Control",                  Qt::LeftDockWidgetArea },
        { _uasListDockWidgetName,           "Unmanned Systems",         Qt::RightDockWidgetArea },
        { _waypointsDockWidgetName,         "Mission Plan",             Qt::BottomDockWidgetArea },
        { _mavlinkDockWidgetName,           "MAVLink Inspector",        Qt::RightDockWidgetArea },
        { _parametersDockWidgetName,        "Onboard Parameters",       Qt::RightDockWidgetArea },
        { _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 },
        { _debugConsoleDockWidgetName,      "Communications Console",   Qt::LeftDockWidgetArea }
    };
    static const size_t cDockWidgetInfo = sizeof(rgDockWidgetInfo) / sizeof(rgDockWidgetInfo[0]);
    
    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 */);
490 491
    }

492 493
    _buildCustomWidgets();
}
494

495 496 497 498 499
void MainWindow::_buildPlannerView(void)
{
    if (!_plannerView) {
        _plannerView = new QGCMapTool(this);
        _plannerView->setVisible(false);
500
    }
501
}
502

503 504 505 506 507 508
void MainWindow::_buildPilotView(void)
{
    if (!_pilotView) {
        _pilotView = new PrimaryFlightDisplay(this);
        _pilotView->setVisible(false);
    }
509 510
}

511
void MainWindow::_buildSetupView(void)
512
{
513 514 515 516
    if (!_setupView) {
        _setupView = new SetupView(this);
        _setupView->setVisible(false);
    }
517 518
}

519
void MainWindow::_buildEngineeringView(void)
520
{
521 522 523 524 525
    if (!_engineeringView) {
        _engineeringView = new QGCDataPlot2D(this);
        _engineeringView->setVisible(false);
    }
}
526

527 528 529 530 531 532
void MainWindow::_buildSimView(void)
{
    if (!_simView) {
        _simView = new QGCMapTool(this);
        _simView->setVisible(false);
    }
533
}
534

535
void MainWindow::_buildTerminalView(void)
536
{
537 538 539 540
    if (!_terminalView) {
        _terminalView = new TerminalConsole(this);
        _terminalView->setVisible(false);
    }
541 542
}

543
void MainWindow::_buildGoogleEarthView(void)
544
{
545 546 547 548 549 550
#ifdef QGC_GOOGLE_EARTH_ENABLED
    if (!_googleEarthView) {
        _googleEarthView = new QGCGoogleEarthView(this);
        _googleEarthView->setVisible(false);
    }
#endif
551 552
}

553
void MainWindow::_buildLocal3DView(void)
554
{
555 556 557 558 559 560
#ifdef QGC_OSG_ENABLED
    if (!_local3DView) {
        _local3DView = Q3DWidgetFactory::get("PIXHAWK", this);
        _local3DView->setVisible(false);
    }
#endif
561 562
}

563 564
/// Shows or hides the specified dock widget, creating if necessary
void MainWindow::_showDockWidget(const QString& name, bool show)
565
{
566 567
    if (!_mapName2DockWidget.contains(name)) {
        qWarning() << "Attempt to show unknown dock widget" << name;
568 569
        return;
    }
570 571 572 573
    
    // Create the inner widget if we need to
    if (!_mapName2DockWidget[name]->widget()) {
        _createInnerDockWidget(name);
574
    }
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

    Q_ASSERT(_mapName2DockWidget.contains(name));
    QDockWidget* dockWidget = _mapName2DockWidget[name];
    Q_ASSERT(dockWidget);
    
    dockWidget->setVisible(show);
    
    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
    
    QWidget* widget = NULL;
    
    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) {
        widget = new ParameterInterface(this);
    } 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) {
613 614 615 616
        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");
617 618
        HDDisplay *hddisplay = new HDDisplay(acceptList,"Flight Display",this);
        hddisplay->addSource(mavlinkDecoder);
619 620 621
        
        widget = hddisplay;
    } else if (widgetName == _hdd2DockWidgetName) {
622 623 624
        QStringList acceptList;
        acceptList.append("0,RAW_PRESSURE.pres_abs,hPa,65500");
        HDDisplay *hddisplay = new HDDisplay(acceptList,"Actuator Status",this);
625
        hddisplay->addSource(mavlinkDecoder);
626 627 628 629 630 631 632 633 634 635 636 637
        
        widget = hddisplay;
    } else if (widgetName == _pfdDockWidgetName) {
        widget = new PrimaryFlightDisplay(this);
    } else if (widgetName == _hudDockWidgetName) {
        widget = new HUD(320,240,this);
    } else if (widgetName == _uasInfoViewDockWidgetName) {
        widget = new QGCTabbedInfoView(this);
    } else if (widgetName == _debugConsoleDockWidgetName) {
        widget = new DebugConsole(this);
    } else {
        qWarning() << "Attempt to create unknown Inner Dock Widget" << widgetName;
638
    }
639 640 641 642 643 644 645
    
    if (widget) {
        QDockWidget* dockWidget = _mapName2DockWidget[widgetName];
        Q_CHECK_PTR(dockWidget);
        
        widget->setParent(dockWidget);
        dockWidget->setWidget(widget);
646 647
    }
}
648

649
void MainWindow::_showHILConfigurationWidgets(void)
650
{
651 652 653 654 655 656 657 658 659 660
    UASInterface* uas = UASManager::instance()->getActiveUAS();
    
    if (!uas) {
        return;
    }
    
    UAS* mav = dynamic_cast<UAS*>(uas);
    Q_ASSERT(mav);
    
    int uasId = mav->getUASID();
661

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    if (!_mapUasId2HilDockWidget.contains(uasId)) {
        
        // Create QDockWidget
        QGCDockWidget* dockWidget = new QGCDockWidget(tr("HIL Config %1").arg(uasId), this);
        Q_CHECK_PTR(dockWidget);
        dockWidget->setObjectName(tr("HIL_CONFIG_%1").arg(uasId));
        dockWidget->setVisible (false);
        
        // Create inner widget and set it
        QWidget* widget = new QGCHilConfiguration(mav, dockWidget);
        
        widget->setParent(dockWidget);
        dockWidget->setWidget(widget);
        
        _mapUasId2HilDockWidget[uasId] = dockWidget;
        
        addDockWidget(Qt::LeftDockWidgetArea, dockWidget);
    }
    
    if (_currentView == VIEW_SIMULATION) {
        // HIL dock widgets only show up on simulation view
        foreach (QDockWidget* dockWidget, _mapUasId2HilDockWidget) {
            dockWidget->setVisible(true);
        }
686 687 688
    }
}

689
void MainWindow::fullScreenActionItemCallback()
690
{
691
    ui.actionNormal->setChecked(false);
692 693
}

694
void MainWindow::normalActionItemCallback()
695
{
696
    ui.actionFullscreen->setChecked(false);
697 698 699 700
}

void MainWindow::closeEvent(QCloseEvent *event)
{
701 702 703 704 705 706 707 708 709 710 711
    // Disallow window close if there are active connections
    
    bool foundConnections = false;
    foreach(LinkInterface* link, LinkManager::instance()->getLinks()) {
        if (link->isConnected()) {
            foundConnections = true;
            break;
        }
    }
    
    if (foundConnections) {
712 713 714 715 716 717 718 719 720 721 722 723
        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);
        if (button == QMessageBox::Yes) {
            foreach(LinkInterface* link, LinkManager::instance()->getLinks()) {
                LinkManager::instance()->disconnectLink(link);
            }
        } else {
            event->ignore();
            return;
        }
724 725
    }

726 727 728
    // This will process any remaining flight log save dialogs
    qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);

729 730
    // Should not be any active connections
    foreach(LinkInterface* link, LinkManager::instance()->getLinks()) {
Don Gagne's avatar
Don Gagne committed
731
        Q_UNUSED(link);
732 733 734
        Q_ASSERT(!link->isConnected());
    }

735
    _storeCurrentViewState();
736
    storeSettings();
737
    UASManager::instance()->storeSettings();
738
    event->accept();
739 740
}

741
void MainWindow::_createNewCustomWidget(void)
742
{
743
    if (QGCToolWidget::instances()->isEmpty())
744 745 746 747
    {
        // This is the first widget
        ui.menuTools->addSeparator();
    }
748 749 750 751 752 753 754 755 756 757
    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 );

758
    QGCToolWidget* tool = new QGCToolWidget(objectName, title);
759 760 761 762
    tool->resize(100, 100);
    _createDockWidget(title, objectName, Qt::BottomDockWidgetArea, tool);
    
    _mapName2DockWidget[objectName]->setVisible(true);
763 764
}

765
void MainWindow::_loadCustomWidgetFromFile(void)
766 767
{
    QString widgetFileExtension(".qgw");
768
    QString fileName = QGCFileDialog::getOpenFileName(this, tr("Specify Widget File Name"), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation), tr("QGroundControl Widget (*%1);;").arg(widgetFileExtension));
769 770 771 772 773 774 775
    if (fileName != "") {
        QGCToolWidget* tool = new QGCToolWidget("", "", this);
        if (tool->loadSettings(fileName, true)) {
            QString objectName = tool->objectName() + "DOCK";
            
            _createDockWidget(tool->getTitle(), objectName, Qt::LeftDockWidgetArea, tool);
            _mapName2DockWidget[objectName]->widget()->setVisible(true);
776 777 778 779 780 781 782
        }
    }
}

void MainWindow::loadSettings()
{
    QSettings settings;
783

784
    customMode = static_cast<enum MainWindow::CUSTOM_MODE>(settings.value("QGC_CUSTOM_MODE", (unsigned int)MainWindow::CUSTOM_MODE_NONE).toInt());
785

786 787 788 789 790 791 792 793 794
    settings.beginGroup("QGC_MAINWINDOW");
    autoReconnect = settings.value("AUTO_RECONNECT", autoReconnect).toBool();
    lowPowerMode = settings.value("LOW_POWER_MODE", lowPowerMode).toBool();
    settings.endGroup();
}

void MainWindow::storeSettings()
{
    QSettings settings;
795 796 797

    settings.setValue("QGC_CUSTOM_MODE", (int)customMode);

798 799 800
    settings.beginGroup("QGC_MAINWINDOW");
    settings.setValue("AUTO_RECONNECT", autoReconnect);
    settings.setValue("LOW_POWER_MODE", lowPowerMode);
801 802 803 804 805
    settings.endGroup();

    settings.setValue(getWindowGeometryKey(), saveGeometry());

    // Save the last current view in any case
806
    settings.setValue("CURRENT_VIEW", _currentView);
807 808 809 810 811

    // Save the current window state, but only if a system is connected (else no real number of widgets would be present))
    if (UASManager::instance()->getUASList().length() > 0) settings.setValue(getWindowStateKey(), saveState());

    // Save the current UAS view if a UAS is connected
812
    if (UASManager::instance()->getUASList().length() > 0) settings.setValue("CURRENT_VIEW_WITH_UAS_CONNECTED", _currentView);
813 814

    // And save any custom weidgets
815
    QGCToolWidget::storeWidgetsToSettings(settings);
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
}

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::startVideoCapture()
{
    QString format = "bmp";
    QString initialPath = QDir::currentPath() + tr("/untitled.") + format;

847
    QString screenFileName = QGCFileDialog::getSaveFileName(this, tr("Save As"),
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
                                                          initialPath,
                                                          tr("%1 Files (*.%2);;All Files (*)")
                                                          .arg(format.toUpper())
                                                          .arg(format));
    delete videoTimer;
    videoTimer = new QTimer(this);
}

void MainWindow::stopVideoCapture()
{
    videoTimer->stop();

    // TODO Convert raw images to PNG
}

void MainWindow::saveScreen()
{
    QPixmap window = QPixmap::grabWindow(this->winId());
    QString format = "bmp";

    if (!screenFileName.isEmpty())
    {
870
        window.save(screenFileName, format.toLatin1());
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
    }
}

void MainWindow::enableAutoReconnect(bool enabled)
{
    autoReconnect = enabled;
}

/**
* @brief Create all actions associated to the main window
*
**/
void MainWindow::connectCommonActions()
{
    // Bind together the perspective actions
    QActionGroup* perspectives = new QActionGroup(ui.menuPerspectives);
    perspectives->addAction(ui.actionEngineersView);
888
    perspectives->addAction(ui.actionFlightView);
889
    perspectives->addAction(ui.actionSimulationView);
890
    perspectives->addAction(ui.actionMissionView);
891
    perspectives->addAction(ui.actionSetup);
892
    perspectives->addAction(ui.actionTerminalView);
Lorenz Meier's avatar
Lorenz Meier committed
893 894
    perspectives->addAction(ui.actionGoogleEarthView);
    perspectives->addAction(ui.actionLocal3DView);
895 896
    perspectives->setExclusive(true);

897
    /* Hide the actions that are not relevant */
898 899 900 901 902 903 904
#ifndef QGC_GOOGLE_EARTH_ENABLED
    ui.actionGoogleEarthView->setVisible(false);
#endif
#ifndef QGC_OSG_ENABLED
    ui.actionLocal3DView->setVisible(false);
#endif

905
    // Mark the right one as selected
906
    if (_currentView == VIEW_ENGINEER)
907 908 909 910
    {
        ui.actionEngineersView->setChecked(true);
        ui.actionEngineersView->activate(QAction::Trigger);
    }
911
    if (_currentView == VIEW_FLIGHT)
912 913 914 915
    {
        ui.actionFlightView->setChecked(true);
        ui.actionFlightView->activate(QAction::Trigger);
    }
916
    if (_currentView == VIEW_SIMULATION)
917
    {
918 919
        ui.actionSimulationView->setChecked(true);
        ui.actionSimulationView->activate(QAction::Trigger);
920
    }
921
    if (_currentView == VIEW_MISSION)
922 923 924 925
    {
        ui.actionMissionView->setChecked(true);
        ui.actionMissionView->activate(QAction::Trigger);
    }
926
    if (_currentView == VIEW_SETUP)
927
    {
928 929
        ui.actionSetup->setChecked(true);
        ui.actionSetup->activate(QAction::Trigger);
930
    }
931
    if (_currentView == VIEW_TERMINAL)
932 933 934 935
    {
        ui.actionTerminalView->setChecked(true);
        ui.actionTerminalView->activate(QAction::Trigger);
    }
936
    if (_currentView == VIEW_GOOGLEEARTH)
937 938 939 940
    {
        ui.actionGoogleEarthView->setChecked(true);
        ui.actionGoogleEarthView->activate(QAction::Trigger);
    }
941
    if (_currentView == VIEW_LOCAL3D)
942 943 944 945
    {
        ui.actionLocal3DView->setChecked(true);
        ui.actionLocal3DView->activate(QAction::Trigger);
    }
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968

    // The UAS actions are not enabled without connection to system
    ui.actionLiftoff->setEnabled(false);
    ui.actionLand->setEnabled(false);
    ui.actionEmergency_Kill->setEnabled(false);
    ui.actionEmergency_Land->setEnabled(false);
    ui.actionShutdownMAV->setEnabled(false);

    // Connect actions from ui
    connect(ui.actionAdd_Link, SIGNAL(triggered()), this, SLOT(addLink()));

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

    // Unmanned System controls
    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()));

    // Views actions
969
    connect(ui.actionFlightView, SIGNAL(triggered()), this, SLOT(loadPilotView()));
970
    connect(ui.actionSimulationView, SIGNAL(triggered()), this, SLOT(loadSimulationView()));
971
    connect(ui.actionEngineersView, SIGNAL(triggered()), this, SLOT(loadEngineerView()));
972
    connect(ui.actionMissionView, SIGNAL(triggered()), this, SLOT(loadOperatorView()));
973
    connect(ui.actionSetup,SIGNAL(triggered()),this,SLOT(loadSetupView()));
974 975
    connect(ui.actionGoogleEarthView, SIGNAL(triggered()), this, SLOT(loadGoogleEarthView()));
    connect(ui.actionLocal3DView, SIGNAL(triggered()), this, SLOT(loadLocal3DView()));
976
    connect(ui.actionTerminalView,SIGNAL(triggered()),this,SLOT(loadTerminalView()));
977 978 979 980

    // Help Actions
    connect(ui.actionOnline_Documentation, SIGNAL(triggered()), this, SLOT(showHelp()));
    connect(ui.actionDeveloper_Credits, SIGNAL(triggered()), this, SLOT(showCredits()));
981
    connect(ui.actionProject_Roadmap, SIGNAL(triggered()), this, SLOT(showRoadMap()));
982 983

    // Custom widget actions
984 985
    connect(ui.actionNewCustomWidget, SIGNAL(triggered()), this, SLOT(_createNewCustomWidget()));
    connect(ui.actionLoadCustomWidgetFile, SIGNAL(triggered()), this, SLOT(_loadCustomWidgetFromFile()));
986 987 988 989 990 991 992 993

    // Audio output
    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)));

    // Application Settings
    connect(ui.actionSettings, SIGNAL(triggered()), this, SLOT(showSettings()));
994 995

    connect(ui.actionSimulate, SIGNAL(triggered(bool)), this, SLOT(simulateLink(bool)));
996 997
}

Don Gagne's avatar
Don Gagne committed
998
void MainWindow::_openUrl(const QString& url, const QString& errorMessage)
999
{
Don Gagne's avatar
Don Gagne committed
1000 1001 1002 1003
    if(!QDesktopServices::openUrl(QUrl(url))) {
        QMessageBox::critical(this,
                              tr("Could not open information in browser"),
                              errorMessage);
1004 1005 1006
    }
}

Don Gagne's avatar
Don Gagne committed
1007 1008 1009 1010 1011 1012
void MainWindow::showHelp()
{
    _openUrl("http://qgroundcontrol.org/users/start",
             tr("To get to the online help, please open http://qgroundcontrol.org/user_guide in a browser."));
}

1013 1014
void MainWindow::showCredits()
{
Don Gagne's avatar
Don Gagne committed
1015 1016
    _openUrl("http://qgroundcontrol.org/credits",
             tr("To get to the credits, please open http://qgroundcontrol.org/credits in a browser."));
1017 1018 1019 1020
}

void MainWindow::showRoadMap()
{
Don Gagne's avatar
Don Gagne committed
1021 1022
    _openUrl("http://qgroundcontrol.org/dev/roadmap",
             tr("To get to the online help, please open http://qgroundcontrol.org/roadmap in a browser."));
1023 1024 1025 1026
}

void MainWindow::showSettings()
{
Don Gagne's avatar
Don Gagne committed
1027 1028
    SettingsDialog settings(joystick, this);
    settings.exec();
1029 1030
}

1031
// FIXME: Where is this called from
1032
LinkInterface* MainWindow::addLink()
1033 1034 1035 1036
{
    SerialLink* link = new SerialLink();
    // TODO This should be only done in the dialog itself

1037
    LinkManager::instance()->addLink(link);
1038 1039 1040 1041

    // Go fishing for this link's configuration window
    QList<QAction*> actions = ui.menuNetwork->actions();

1042 1043
    const int32_t& linkIndex(LinkManager::instance()->getLinks().indexOf(link));
    const int32_t& linkID(LinkManager::instance()->getLinks()[linkIndex]->getId());
1044 1045 1046 1047

    foreach (QAction* act, actions)
    {
        if (act->data().toInt() == linkID)
1048
        {
1049 1050 1051 1052
            act->trigger();
            break;
        }
    }
1053 1054

    return link;
1055 1056
}

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

bool MainWindow::configLink(LinkInterface *link)
{
    // Go searching for this link's configuration window
    QList<QAction*> actions = ui.menuNetwork->actions();

    bool found(false);

    const int32_t& linkIndex(LinkManager::instance()->getLinks().indexOf(link));
    const int32_t& linkID(LinkManager::instance()->getLinks()[linkIndex]->getId());

    foreach (QAction* action, actions)
    {
        if (action->data().toInt() == linkID)
1071
        {
1072 1073 1074 1075 1076 1077 1078 1079
            found = true;
            action->trigger(); // Show the Link Config Dialog
        }
    }

    return found;
}

1080
void MainWindow::_addLinkMenu(LinkInterface *link)
1081 1082 1083 1084
{
    // Go fishing for this link's configuration window
    QList<QAction*> actions = ui.menuNetwork->actions();

1085
    bool alreadyAdded = false;
1086

1087 1088
    const int32_t& linkIndex(LinkManager::instance()->getLinks().indexOf(link));
    const int32_t& linkID(LinkManager::instance()->getLinks()[linkIndex]->getId());
1089

1090 1091 1092 1093
    foreach (QAction* act, actions) {
        if (act->data().toInt() == linkID) {
            alreadyAdded = true;
            break;
1094 1095 1096
        }
    }

1097 1098
    if (!alreadyAdded) {
        CommConfigurationWindow* commWidget = new CommConfigurationWindow(link, this);
1099 1100
        commsWidgetList.append(commWidget);
        connect(commWidget,SIGNAL(destroyed(QObject*)),this,SLOT(commsWidgetDestroyed(QObject*)));
1101 1102 1103 1104
        QAction* action = commWidget->getAction();
        ui.menuNetwork->addAction(action);
    }
}
1105

1106
void MainWindow::simulateLink(bool simulate) {
Don Gagne's avatar
Don Gagne committed
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    if (simulate) {
        if (!simulationLink) {
            simulationLink = new MAVLinkSimulationLink(":/demo-log.txt");
            Q_CHECK_PTR(simulationLink);
        }
        LinkManager::instance()->connectLink(simulationLink);
    } else {
        Q_ASSERT(simulationLink);
        LinkManager::instance()->disconnectLink(simulationLink);
    }
1117 1118
}

1119 1120
void MainWindow::commsWidgetDestroyed(QObject *obj)
{
1121 1122 1123
    // Do not dynamic cast or de-reference QObject, since object is either in destructor or may have already
    // been destroyed.

1124 1125 1126 1127 1128
    if (commsWidgetList.contains(obj))
    {
        commsWidgetList.removeOne(obj);
    }
}
1129 1130 1131

void MainWindow::setActiveUAS(UASInterface* uas)
{
1132
    Q_UNUSED(uas);
1133 1134
    if (settings.contains(getWindowStateKey()))
    {
1135
        restoreState(settings.value(getWindowStateKey()).toByteArray());
1136 1137
    }

1138 1139 1140 1141
}

void MainWindow::UASSpecsChanged(int uas)
{
1142 1143
    Q_UNUSED(uas);
    // TODO: Update UAS properties if its specs change
1144 1145 1146 1147
}

void MainWindow::UASCreated(UASInterface* uas)
{
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    // The UAS actions are not enabled without connection to system
    ui.actionLiftoff->setEnabled(true);
    ui.actionLand->setEnabled(true);
    ui.actionEmergency_Kill->setEnabled(true);
    ui.actionEmergency_Land->setEnabled(true);
    ui.actionShutdownMAV->setEnabled(true);

    QIcon icon;
    // Set matching icon
    switch (uas->getSystemType())
    {
    case MAV_TYPE_GENERIC:
        icon = QIcon(":files/images/mavs/generic.svg");
        break;
    case MAV_TYPE_FIXED_WING:
        icon = QIcon(":files/images/mavs/fixed-wing.svg");
        break;
    case MAV_TYPE_QUADROTOR:
        icon = QIcon(":files/images/mavs/quadrotor.svg");
        break;
    case MAV_TYPE_COAXIAL:
        icon = QIcon(":files/images/mavs/coaxial.svg");
        break;
    case MAV_TYPE_HELICOPTER:
        icon = QIcon(":files/images/mavs/helicopter.svg");
        break;
    case MAV_TYPE_ANTENNA_TRACKER:
        icon = QIcon(":files/images/mavs/antenna-tracker.svg");
        break;
    case MAV_TYPE_GCS:
        icon = QIcon(":files/images/mavs/groundstation.svg");
        break;
    case MAV_TYPE_AIRSHIP:
        icon = QIcon(":files/images/mavs/airship.svg");
        break;
    case MAV_TYPE_FREE_BALLOON:
        icon = QIcon(":files/images/mavs/free-balloon.svg");
        break;
    case MAV_TYPE_ROCKET:
        icon = QIcon(":files/images/mavs/rocket.svg");
        break;
    case MAV_TYPE_GROUND_ROVER:
        icon = QIcon(":files/images/mavs/ground-rover.svg");
        break;
    case MAV_TYPE_SURFACE_BOAT:
        icon = QIcon(":files/images/mavs/surface-boat.svg");
        break;
    case MAV_TYPE_SUBMARINE:
        icon = QIcon(":files/images/mavs/submarine.svg");
        break;
    case MAV_TYPE_HEXAROTOR:
        icon = QIcon(":files/images/mavs/hexarotor.svg");
        break;
    case MAV_TYPE_OCTOROTOR:
        icon = QIcon(":files/images/mavs/octorotor.svg");
        break;
    case MAV_TYPE_TRICOPTER:
        icon = QIcon(":files/images/mavs/tricopter.svg");
        break;
    case MAV_TYPE_FLAPPING_WING:
        icon = QIcon(":files/images/mavs/flapping-wing.svg");
        break;
    case MAV_TYPE_KITE:
        icon = QIcon(":files/images/mavs/kite.svg");
        break;
    default:
        icon = QIcon(":files/images/mavs/unknown.svg");
        break;
    }
1217

1218
    connect(uas, SIGNAL(systemSpecsChanged(int)), this, SLOT(UASSpecsChanged(int)));
John Tapsell's avatar
John Tapsell committed
1219
    connect(uas, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)), this, SIGNAL(valueChanged(int,QString,QString,QVariant,quint64)));
1220
    connect(uas, SIGNAL(misconfigurationDetected(UASInterface*)), this, SLOT(handleMisconfiguration(UASInterface*)));
1221

1222
    // HIL
1223
    _showHILConfigurationWidgets();
1224

1225 1226 1227
    if (!linechartWidget)
    {
        linechartWidget = new Linecharts(this);
1228
        linechartWidget->setVisible(false);
1229
    }
1230

1231
    linechartWidget->addSource(mavlinkDecoder);
1232
    if (_engineeringView != linechartWidget)
1233
    {
1234
        _engineeringView = linechartWidget;
1235
    }
1236 1237

    // Reload view state in case new widgets were added
1238
    _loadCurrentViewState();
1239 1240 1241 1242
}

void MainWindow::UASDeleted(UASInterface* uas)
{
1243
    Q_UNUSED(uas);
1244
    // TODO: Update the UI when a UAS is deleted
1245 1246
}

1247 1248
/// Stores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_storeCurrentViewState(void)
1249
{
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
    // 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;
        }
1265
    }
1266 1267 1268
    
    settings.setValue(getWindowStateKey() + "WIDGETS", widgetNames);
    settings.setValue(getWindowStateKey(), saveState());
1269
    settings.setValue(getWindowGeometryKey(), saveGeometry());
1270 1271
}

1272 1273
/// Restores the state of the toolbar, status bar and widgets associated with the current view
void MainWindow::_loadCurrentViewState(void)
1274
{
Don Gagne's avatar
Don Gagne committed
1275
    QWidget* centerView = NULL;
1276 1277 1278
    QString defaultWidgets;
    
    switch (_currentView) {
1279
        case VIEW_SETUP:
1280 1281
            _buildSetupView();
            centerView = _setupView;
1282
            break;
1283
            
1284
        case VIEW_ENGINEER:
1285 1286 1287
            _buildEngineeringView();
            centerView = _engineeringView;
            defaultWidgets = "MAVLINK_INSPECTOR_DOCKWIDGET,PARAMETER_INTERFACE_DOCKWIDGET,FILE_VIEW_DOCKWIDGET,HEAD_UP_DISPLAY_DOCKWIDGET";
1288
            break;
1289
            
1290
        case VIEW_FLIGHT:
1291 1292 1293
            _buildPilotView();
            centerView = _pilotView;
            defaultWidgets = "COMMUNICATION_CONSOLE_DOCKWIDGET,UAS_INFO_INFOVIEW_DOCKWIDGET";
1294
            break;
1295
            
1296
        case VIEW_MISSION:
1297 1298 1299
            _buildPlannerView();
            centerView = _plannerView;
            defaultWidgets = "UNMANNED_SYSTEM_LIST_DOCKWIDGET,WAYPOINT_LIST_DOCKWIDGET";
1300
            break;
1301
            
1302
        case VIEW_SIMULATION:
1303 1304 1305
            _buildSimView();
            centerView = _simView;
            defaultWidgets = "UNMANNED_SYSTEM_CONTROL_DOCKWIDGET,WAYPOINT_LIST_DOCKWIDGET,PARAMETER_INTERFACE_DOCKWIDGET,PRIMARY_FLIGHT_DISPLAY_DOCKWIDGET";
1306
            break;
1307
            
1308
        case VIEW_TERMINAL:
1309 1310
            _buildTerminalView();
            centerView = _terminalView;
1311
            break;
1312
            
1313
        case VIEW_GOOGLEEARTH:
1314 1315
            _buildGoogleEarthView();
            centerView = _googleEarthView;
1316
            break;
1317
            
1318
        case VIEW_LOCAL3D:
1319 1320
            _buildLocal3DView();
            centerView = _local3DView;
1321
            break;
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    }
    
    // Remove old view
    if (_currentViewWidget) {
        _currentViewWidget->setVisible(false);
        Q_ASSERT(_centralLayout->count() == 1);
        QLayoutItem *child = _centralLayout->takeAt(0);
        Q_ASSERT(child);
        delete child;
    }
    
    // Add the new one
    Q_ASSERT(centerView);
    Q_ASSERT(_centralLayout->count() == 0);
    _currentViewWidget = centerView;
    _centralLayout->addWidget(_currentViewWidget);
    _currentViewWidget->setVisible(true);
    
    // Hide all widgets from previous view
    _hideAllDockWidgets();

    // Restore the widgets for the new view
    QString widgetNames = settings.value(getWindowStateKey() + "WIDGETS", defaultWidgets).toString();
    if (!widgetNames.isEmpty()) {
        QStringList split = widgetNames.split(",");
        foreach (QString widgetName, split) {
            Q_ASSERT(!widgetName.isEmpty());
            _showDockWidget(widgetName, true);
1350 1351 1352
        }
    }

1353 1354
    if (settings.contains(getWindowStateKey())) {
        restoreState(settings.value(getWindowStateKey()).toByteArray());
1355
    }
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
    
    // 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();
}

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

void MainWindow::_hideAllDockWidgets(void)
{
    foreach(QDockWidget* dockWidget, _mapName2DockWidget) {
        dockWidget->setVisible(false);
1373
    }
1374 1375
    
    _hideAllHilDockWidgets();
1376
}
1377 1378

void MainWindow::_showDockWidgetAction(bool show)
1379
{
1380 1381 1382 1383
    QAction* action = dynamic_cast<QAction*>(QObject::sender());
    Q_ASSERT(action);
    
    _showDockWidget(action->data().toString(), show);
1384
}
1385

1386

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
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;
        }
    }
Don Gagne's avatar
Don Gagne committed
1400
    
1401
    // Ask user if he wants to handle this now
Don Gagne's avatar
Don Gagne committed
1402 1403 1404 1405 1406
    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);
    if (button == QMessageBox::Ok) {
1407 1408 1409 1410
        // He wants to handle it, make sure this system is selected
        UASManager::instance()->setActiveUAS(uas);

        // Flick to config view
1411
        loadSetupView();
1412 1413 1414
    }
}

1415 1416
void MainWindow::loadEngineerView()
{
1417
    if (_currentView != VIEW_ENGINEER)
1418
    {
1419 1420
        _storeCurrentViewState();
        _currentView = VIEW_ENGINEER;
1421
        ui.actionEngineersView->setChecked(true);
1422
        _loadCurrentViewState();
1423 1424 1425 1426 1427
    }
}

void MainWindow::loadOperatorView()
{
1428
    if (_currentView != VIEW_MISSION)
1429
    {
1430 1431
        _storeCurrentViewState();
        _currentView = VIEW_MISSION;
1432
        ui.actionMissionView->setChecked(true);
1433
        _loadCurrentViewState();
1434 1435
    }
}
1436
void MainWindow::loadSetupView()
1437
{
1438
    if (_currentView != VIEW_SETUP)
1439
    {
1440 1441
        _storeCurrentViewState();
        _currentView = VIEW_SETUP;
1442
        ui.actionSetup->setChecked(true);
1443
        _loadCurrentViewState();
1444 1445 1446
    }
}

1447 1448
void MainWindow::loadTerminalView()
{
1449
    if (_currentView != VIEW_TERMINAL)
1450
    {
1451 1452
        _storeCurrentViewState();
        _currentView = VIEW_TERMINAL;
1453
        ui.actionTerminalView->setChecked(true);
1454
        _loadCurrentViewState();
1455 1456 1457
    }
}

1458 1459
void MainWindow::loadGoogleEarthView()
{
1460
    if (_currentView != VIEW_GOOGLEEARTH)
1461
    {
1462 1463
        _storeCurrentViewState();
        _currentView = VIEW_GOOGLEEARTH;
1464
        ui.actionGoogleEarthView->setChecked(true);
1465
        _loadCurrentViewState();
1466 1467 1468 1469 1470
    }
}

void MainWindow::loadLocal3DView()
{
1471
    if (_currentView != VIEW_LOCAL3D)
1472
    {
1473 1474
        _storeCurrentViewState();
        _currentView = VIEW_LOCAL3D;
1475
        ui.actionLocal3DView->setChecked(true);
1476
        _loadCurrentViewState();
1477 1478
    }
}
1479

1480 1481
void MainWindow::loadPilotView()
{
1482
    if (_currentView != VIEW_FLIGHT)
1483
    {
1484 1485
        _storeCurrentViewState();
        _currentView = VIEW_FLIGHT;
1486
        ui.actionFlightView->setChecked(true);
1487
        _loadCurrentViewState();
1488 1489 1490
    }
}

1491 1492
void MainWindow::loadSimulationView()
{
1493
    if (_currentView != VIEW_SIMULATION)
1494
    {
1495 1496
        _storeCurrentViewState();
        _currentView = VIEW_SIMULATION;
1497
        ui.actionSimulationView->setChecked(true);
1498
        _loadCurrentViewState();
1499 1500 1501
    }
}

1502
QList<QAction*> MainWindow::listLinkMenuActions()
1503 1504 1505
{
    return ui.menuNetwork->actions();
}
1506

Don Gagne's avatar
Don Gagne committed
1507
/// @brief Hides the spash screen if it is currently being shown
1508
void MainWindow::hideSplashScreen(void)
Don Gagne's avatar
Don Gagne committed
1509 1510 1511 1512 1513 1514 1515 1516
{
    if (_splashScreen) {
        _splashScreen->hide();
        _splashScreen = NULL;
    }
}


1517
#ifdef QGC_MOUSE_ENABLED_LINUX
1518 1519 1520
bool MainWindow::x11Event(XEvent *event)
{
    emit x11EventOccured(event);
1521
    return false;
1522
}
1523
#endif // QGC_MOUSE_ENABLED_LINUX