MapWidget.cc 43.4 KB
Newer Older
1
/*==================================================================
pixhawk's avatar
pixhawk committed
2 3 4 5
======================================================================*/

/**
 * @file
lm's avatar
lm committed
6
 *   @brief Implementation of MapWidget
pixhawk's avatar
pixhawk committed
7 8
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
lm's avatar
lm committed
9
 *   @author Mariano Lizarraga
pixhawk's avatar
pixhawk committed
10 11 12
 *
 */

lm's avatar
lm committed
13 14
#include <QComboBox>
#include <QGridLayout>
15
#include <QDir>
16

17
#include "QGC.h"
pixhawk's avatar
pixhawk committed
18 19
#include "MapWidget.h"
#include "ui_MapWidget.h"
lm's avatar
lm committed
20 21
#include "UASInterface.h"
#include "UASManager.h"
22 23
#include "MAV2DIcon.h"
#include "Waypoint2DIcon.h"
24
#include "UASWaypointManager.h"
pixhawk's avatar
pixhawk committed
25

pixhawk's avatar
pixhawk committed
26 27
#include "MG.h"

28

pixhawk's avatar
pixhawk committed
29 30
MapWidget::MapWidget(QWidget *parent) :
        QWidget(parent),
31
        mc(NULL),
pixhawk's avatar
pixhawk committed
32
        zoomLevel(0),
33 34
        uasIcons(),
        uasTrails(),
35
        mav(NULL),
36
        lastUpdate(0),
37
        initialized(false),
pixhawk's avatar
pixhawk committed
38 39 40
        m_ui(new Ui::MapWidget)
{
    m_ui->setupUi(this);
lm's avatar
lm committed
41
    init();
42 43 44 45
}

void MapWidget::init()
{
lm's avatar
lm committed
46 47 48 49 50 51 52 53 54 55 56 57 58
    if (!initialized)
    {
        mc = new qmapcontrol::MapControl(this->size());
        // display the MapControl in the application
        QGridLayout* layout = new QGridLayout(this);
        layout->setMargin(0);
        layout->setSpacing(0);
        layout->addWidget(mc, 0, 0);
        setLayout(layout);

        //   VISUAL MAP STYLE
        QString buttonStyle("QAbstractButton { background-color: rgba(20, 20, 20, 45%); border-color: rgba(10, 10, 10, 50%)} QAbstractButton:checked { border: 2px solid #379AC3; }");
        mc->setPen(QGC::colorCyan.darker(400));
59

lm's avatar
lm committed
60
        waypointIsDrag = false;
61

lm's avatar
lm committed
62 63
        // Accept focus by clicking or keyboard
        this->setFocusPolicy(Qt::StrongFocus);
pixhawk's avatar
pixhawk committed
64

lm's avatar
lm committed
65 66 67 68 69 70
        // create MapControl

        mc->showScale(true);
        mc->showCoord(true);
        mc->enablePersistentCache();
        mc->setMouseTracking(true); // required to update the mouse position for diplay and capture
pixhawk's avatar
pixhawk committed
71

lm's avatar
lm committed
72 73
        // create MapAdapter to get maps from
        //TileMapAdapter* osmAdapter = new TileMapAdapter("tile.openstreetmap.org", "/%1/%2/%3.png", 256, 0, 17);
pixhawk's avatar
pixhawk committed
74

lm's avatar
lm committed
75
        qmapcontrol::MapAdapter* mapadapter_overlay = new qmapcontrol::YahooMapAdapter("us.maps3.yimg.com", "/aerial.maps.yimg.com/png?v=2.2&t=h&s=256&x=%2&y=%3&z=%1");
pixhawk's avatar
pixhawk committed
76

lm's avatar
lm committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        // MAP BACKGROUND
        mapadapter = new qmapcontrol::GoogleSatMapAdapter();
        l = new qmapcontrol::MapLayer("Google Satellite", mapadapter);
        mc->addLayer(l);

        // STREET OVERLAY
        overlay = new qmapcontrol::MapLayer("Overlay", mapadapter_overlay);
        overlay->setVisible(false);
        mc->addLayer(overlay);

        // MAV FLIGHT TRACKS
        tracks = new qmapcontrol::MapLayer("Tracking", mapadapter);
        mc->addLayer(tracks);

        // WAYPOINT LAYER
        // create a layer with the mapadapter and type GeometryLayer (for waypoints)
        geomLayer = new qmapcontrol::GeometryLayer("Waypoints", mapadapter);
        mc->addLayer(geomLayer);

96 97
        homePosition = new qmapcontrol::GeometryLayer("Station", mapadapter);
        mc->addLayer(homePosition);
lm's avatar
lm committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117


        //
        //    Layer* gsatLayer = new Layer("Google Satellite", gsat, Layer::MapLayer);
        //    mc->addLayer(gsatLayer);


        // Zurich, ETH

        int lastZoom = 16;
        double lastLat = 47.376889;
        double lastLon = 8.548056;

        QSettings settings;
        settings.beginGroup("QGC_MAPWIDGET");
        lastLat = settings.value("LAST_LATITUDE", lastLat).toDouble();
        lastLon = settings.value("LAST_LONGITUDE", lastLon).toDouble();
        lastZoom = settings.value("LAST_ZOOM", lastZoom).toInt();
        settings.endGroup();

118 119 120 121 122
        index = 0;
        settings.beginGroup("QGC_MAPINDEX");
        index = settings.value("MAP_INDEX", index).toInt();
        settings.endGroup();

123 124 125 126 127
        settings.beginGroup("QGC_HOMEPOSITION");
        homeCoordinate.setY(settings.value("HOME_LATITUDE", homeCoordinate.y()).toDouble());
        homeCoordinate.setX(settings.value("HOME_LONGITUDE", homeCoordinate.x()).toDouble());
        settings.endGroup();

lm's avatar
lm committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        // SET INITIAL POSITION AND ZOOM
        // Set default zoom level
        mc->setZoom(lastZoom);
        mc->setView(QPointF(lastLon, lastLat));

        // Veracruz Mexico
        //mc->setView(QPointF(-96.105208,19.138955));

        // Add controls to select map provider
        /////////////////////////////////////////////////
        QActionGroup* mapproviderGroup = new QActionGroup(this);
        osmAction = new QAction(QIcon(":/images/mapproviders/openstreetmap.png"), tr("OpenStreetMap"), mapproviderGroup);
        yahooActionMap = new QAction(QIcon(":/images/mapproviders/yahoo.png"), tr("Yahoo: Map"), mapproviderGroup);
        yahooActionSatellite = new QAction(QIcon(":/images/mapproviders/yahoo.png"), tr("Yahoo: Satellite"), mapproviderGroup);
        googleActionMap = new QAction(QIcon(":/images/mapproviders/google.png"), tr("Google: Map"), mapproviderGroup);
        googleSatAction = new QAction(QIcon(":/images/mapproviders/google.png"), tr("Google: Sat"), mapproviderGroup);
        osmAction->setCheckable(true);
        yahooActionMap->setCheckable(true);
        yahooActionSatellite->setCheckable(true);
        googleActionMap->setCheckable(true);
        googleSatAction->setCheckable(true);
        googleSatAction->setChecked(true);
        connect(mapproviderGroup, SIGNAL(triggered(QAction*)),
                this, SLOT(mapproviderSelected(QAction*)));

153 154 155 156 157 158 159 160

        //mapSettings.beginGroup("Map_Widget");
        //QAction *act = new QAction(mapSettings.value("QAction").toString(), this);
        //mapproviderSelected(act);
        //mapSettings.endGroup();



lm's avatar
lm committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        // Overlay seems currently broken
        //    yahooActionOverlay = new QAction(tr("Yahoo: street overlay"), this);
        //    yahooActionOverlay->setCheckable(true);
        //    yahooActionOverlay->setChecked(overlay->isVisible());
        //    connect(yahooActionOverlay, SIGNAL(toggled(bool)),
        //            overlay, SLOT(setVisible(bool)));

        //    mapproviderGroup->addAction(googleSatAction);
        //    mapproviderGroup->addAction(osmAction);
        //    mapproviderGroup->addAction(yahooActionOverlay);
        //    mapproviderGroup->addAction(googleActionMap);
        //    mapproviderGroup->addAction(yahooActionMap);
        //    mapproviderGroup->addAction(yahooActionSatellite);

        // Create map provider selection menu
        mapMenu = new QMenu(this);
        mapMenu->addActions(mapproviderGroup->actions());
        mapMenu->addSeparator();
        //    mapMenu->addAction(yahooActionOverlay);

        mapButton = new QPushButton(this);
        mapButton->setText("Map Source");
        mapButton->setMenu(mapMenu);
        mapButton->setStyleSheet(buttonStyle);

        // create buttons to control the map (zoom, GPS tracking and WP capture)
        QPushButton* zoomin = new QPushButton(QIcon(":/images/actions/list-add.svg"), "", this);
        zoomin->setStyleSheet(buttonStyle);
        QPushButton* zoomout = new QPushButton(QIcon(":/images/actions/list-remove.svg"), "", this);
        zoomout->setStyleSheet(buttonStyle);
        createPath = new QPushButton(QIcon(":/images/actions/go-bottom.svg"), "", this);
        createPath->setStyleSheet(buttonStyle);
        createPath->setToolTip(tr("Start / end waypoint add mode"));
        createPath->setStatusTip(tr("Start / end waypoint add mode"));
        //    clearTracking = new QPushButton(QIcon(""), "", this);
        //    clearTracking->setStyleSheet(buttonStyle);
        followgps = new QPushButton(QIcon(":/images/actions/system-lock-screen.svg"), "", this);
        followgps->setStyleSheet(buttonStyle);
        followgps->setToolTip(tr("Follow the position of the current MAV with the map center"));
        followgps->setStatusTip(tr("Follow the position of the current MAV with the map center"));
        QPushButton* goToButton = new QPushButton(QIcon(""), "T", this);
        goToButton->setStyleSheet(buttonStyle);
        goToButton->setToolTip(tr("Enter a latitude/longitude position to move the map to"));
        goToButton->setStatusTip(tr("Enter a latitude/longitude position to move the map to"));

206 207 208 209 210
        setHome = new QPushButton(QIcon(":/images/actions/go-home.svg"), "", this);
        setHome->setStyleSheet(buttonStyle);
        setHome->setToolTip(tr("Set home"));
        setHome->setStatusTip(tr("Set home"));

lm's avatar
lm committed
211 212 213 214 215
        zoomin->setMaximumWidth(30);
        zoomout->setMaximumWidth(30);
        createPath->setMaximumWidth(30);
        //    clearTracking->setMaximumWidth(30);
        followgps->setMaximumWidth(30);
216
        setHome->setMaximumWidth(30);
lm's avatar
lm committed
217 218 219 220 221 222 223
        goToButton->setMaximumWidth(30);

        // Set checkable buttons
        // TODO: Currently checked buttons are are very difficult to distinguish when checked.
        //       create a style and the slots to change the background so it is easier to distinguish
        followgps->setCheckable(true);
        createPath->setCheckable(true);
224
        setHome->setCheckable(true);
lm's avatar
lm committed
225 226 227 228 229 230 231 232 233

        // add buttons to control the map (zoom, GPS tracking and WP capture)
        QGridLayout* innerlayout = new QGridLayout(mc);
        innerlayout->setMargin(3);
        innerlayout->setSpacing(3);
        innerlayout->addWidget(zoomin, 0, 0);
        innerlayout->addWidget(zoomout, 1, 0);
        innerlayout->addWidget(followgps, 2, 0);
        innerlayout->addWidget(createPath, 3, 0);
234
        innerlayout->addWidget(setHome, 4, 0);
lm's avatar
lm committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        //innerlayout->addWidget(clearTracking, 4, 0);
        // Add spacers to compress buttons on the top left
        innerlayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Expanding), 5, 0);
        innerlayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Expanding), 0, 1, 0, 7);
        innerlayout->addWidget(mapButton, 0, 6);
        innerlayout->addWidget(goToButton, 0, 7);
        innerlayout->setRowStretch(0, 1);
        innerlayout->setRowStretch(1, 100);
        mc->setLayout(innerlayout);

        // Configure the WP Path's pen
        pointPen = new QPen(QColor(0, 255,0));
        pointPen->setWidth(3);
        waypointPath = new qmapcontrol::LineString (wps, "Waypoint path", pointPen);
        mc->layer("Waypoints")->addGeometry(waypointPath);

        // Done set state
        initialized = true;


        // Connect the required signals-slots
        connect(zoomin, SIGNAL(clicked(bool)),
                mc, SLOT(zoomIn()));

        connect(zoomout, SIGNAL(clicked(bool)),
                mc, SLOT(zoomOut()));

        connect(goToButton, SIGNAL(clicked()), this, SLOT(goTo()));

        QList<UASInterface*> systems = UASManager::instance()->getUASList();
        foreach(UASInterface* system, systems)
        {
            addUAS(system);
        }
pixhawk's avatar
pixhawk committed
269

lm's avatar
lm committed
270 271
        connect(UASManager::instance(), SIGNAL(UASCreated(UASInterface*)),
                this, SLOT(addUAS(UASInterface*)));
pixhawk's avatar
pixhawk committed
272

lm's avatar
lm committed
273 274
        activeUASSet(UASManager::instance()->getActiveUAS());
        connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(activeUASSet(UASInterface*)));
pixhawk's avatar
pixhawk committed
275

lm's avatar
lm committed
276 277
        connect(mc, SIGNAL(mouseEventCoordinate(const QMouseEvent*, const QPointF)),
                this, SLOT(captureMapClick(const QMouseEvent*, const QPointF)));
pixhawk's avatar
pixhawk committed
278

lm's avatar
lm committed
279 280
        connect(createPath, SIGNAL(clicked(bool)),
                this, SLOT(createPathButtonClicked(bool)));
pixhawk's avatar
pixhawk committed
281

282 283 284 285 286 287
        connect(setHome, SIGNAL(clicked(bool)), this, SLOT(createHomePositionClick(bool)));

        connect(mc, SIGNAL(mouseEventCoordinate(const QMouseEvent*,QPointF)), this,
                SLOT(createHomePosition(const QMouseEvent*,QPointF)));
        //connect(setHome, SIGNAL(clicked(bool)), this, SLOT(createHomePosition(bool)));

lm's avatar
lm committed
288 289 290 291 292 293 294 295 296 297

        connect(geomLayer, SIGNAL(geometryClicked(Geometry*,QPoint)),
                this, SLOT(captureGeometryClick(Geometry*, QPoint)));

        connect(geomLayer, SIGNAL(geometryDragged(Geometry*, QPointF)),
                this, SLOT(captureGeometryDrag(Geometry*, QPointF)));

        connect(geomLayer, SIGNAL(geometryEndDrag(Geometry*, QPointF)),
                this, SLOT(captureGeometryEndDrag(Geometry*, QPointF)));

298 299 300 301 302 303 304 305 306
        connect(homePosition, SIGNAL(geometryClicked(Geometry*,QPoint)),
                this, SLOT(captureGeometryClick(Geometry*, QPoint)));

        connect(homePosition, SIGNAL(geometryDragged(Geometry*, QPointF)),
                this, SLOT(captureGeometryDragHome(Geometry*, QPointF)));

        connect(homePosition, SIGNAL(geometryEndDrag(Geometry*, QPointF)),
                this, SLOT(captureGeometryEndDrag(Geometry*, QPointF)));

307
        this->loadSettingsMap(index);
308 309
        this->createHomePosition(homeCoordinate);

lm's avatar
lm committed
310 311
        qDebug() << "CHECK END";
    }
lm's avatar
lm committed
312 313
}

314
void MapWidget::loadSettingsMap(int8_t index)
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
{
    switch(index)
    {
    case 0:
        mapproviderSelected(osmAction);
        break;
    case 1:
        mapproviderSelected(yahooActionMap);
        break;
    case 2:
        mapproviderSelected(yahooActionSatellite);
        break;
    case 3:
        mapproviderSelected(googleActionMap);
        break;
    case 4:
        mapproviderSelected(googleSatAction);
        break;
    }
}

336 337 338
void MapWidget::goTo()
{
    bool ok;
339 340
    QString text = QInputDialog::getText(this, tr("Please enter coordinates"),
                                         tr("Coordinates (Lat,Lon):"), QLineEdit::Normal,
341
                                         QString("%1,%2").arg(mc->currentCoordinate().y()).arg(mc->currentCoordinate().x()), &ok);
342 343 344 345 346 347 348 349 350 351 352 353 354
    if (ok && !text.isEmpty())
    {
        QStringList split = text.split(",");
        if (split.length() == 2)
        {
            bool convert;
            double latitude = split.first().toDouble(&convert);
            ok &= convert;
            double longitude = split.last().toDouble(&convert);
            ok &= convert;

            if (ok)
            {
355
                mc->setView(QPointF(longitude, latitude));
356 357 358
            }
        }
    }
359 360
}

361

lm's avatar
lm committed
362 363
void MapWidget::mapproviderSelected(QAction* action)
{
lm's avatar
lm committed
364
    if (mc)
lm's avatar
lm committed
365
    {
lm's avatar
lm committed
366 367 368 369 370 371
        //delete mapadapter;
        mapButton->setText(action->text());
        if (action == osmAction)
        {
            int zoom = mapadapter->adaptedZoom();
            mc->setZoom(0);
pixhawk's avatar
pixhawk committed
372

lm's avatar
lm committed
373 374 375
            mapadapter = new qmapcontrol::OSMMapAdapter();
            l->setMapAdapter(mapadapter);
            geomLayer->setMapAdapter(mapadapter);
376
            homePosition->setMapAdapter(mapadapter);
377
            index = 0;
pixhawk's avatar
pixhawk committed
378

lm's avatar
lm committed
379 380 381 382 383
            if (isVisible()) mc->updateRequestNew();
            mc->setZoom(zoom);
            //        yahooActionOverlay->setEnabled(false);
            overlay->setVisible(false);
            //        yahooActionOverlay->setChecked(false);
pixhawk's avatar
pixhawk committed
384

lm's avatar
lm committed
385 386 387 388 389 390 391 392 393
        }
        else if (action == yahooActionMap)
        {
            int zoom = mapadapter->adaptedZoom();
            mc->setZoom(0);

            mapadapter = new qmapcontrol::YahooMapAdapter();
            l->setMapAdapter(mapadapter);
            geomLayer->setMapAdapter(mapadapter);
394
            homePosition->setMapAdapter(mapadapter);
395
            index = 1;
lm's avatar
lm committed
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411

            if (isVisible()) mc->updateRequestNew();
            mc->setZoom(zoom);
            //        yahooActionOverlay->setEnabled(false);
            overlay->setVisible(false);
            //        yahooActionOverlay->setChecked(false);
        }
        else if (action == yahooActionSatellite)
        {
            int zoom = mapadapter->adaptedZoom();
            QPointF a = mc->currentCoordinate();
            mc->setZoom(0);

            mapadapter = new qmapcontrol::YahooMapAdapter("us.maps3.yimg.com", "/aerial.maps.yimg.com/png?v=1.7&t=a&s=256&x=%2&y=%3&z=%1");
            l->setMapAdapter(mapadapter);
            geomLayer->setMapAdapter(mapadapter);
412
            homePosition->setMapAdapter(mapadapter);
413
            index = 2;
lm's avatar
lm committed
414 415 416 417 418 419 420 421 422 423 424 425 426

            if (isVisible()) mc->updateRequestNew();
            mc->setZoom(zoom);
            overlay->setVisible(false);
            //        yahooActionOverlay->setEnabled(true);
        }
        else if (action == googleActionMap)
        {
            int zoom = mapadapter->adaptedZoom();
            mc->setZoom(0);
            mapadapter = new qmapcontrol::GoogleMapAdapter();
            l->setMapAdapter(mapadapter);
            geomLayer->setMapAdapter(mapadapter);
427
            homePosition->setMapAdapter(mapadapter);
428
            index = 3;
lm's avatar
lm committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442

            if (isVisible()) mc->updateRequestNew();
            mc->setZoom(zoom);
            //        yahooActionOverlay->setEnabled(false);
            overlay->setVisible(false);
            //        yahooActionOverlay->setChecked(false);
        }
        else if (action == googleSatAction)
        {
            int zoom = mapadapter->adaptedZoom();
            mc->setZoom(0);
            mapadapter = new qmapcontrol::GoogleSatMapAdapter();
            l->setMapAdapter(mapadapter);
            geomLayer->setMapAdapter(mapadapter);
443
            homePosition->setMapAdapter(mapadapter);
444
            index = 4;
lm's avatar
lm committed
445 446 447 448 449 450 451 452 453 454 455

            if (isVisible()) mc->updateRequestNew();
            mc->setZoom(zoom);
            //        yahooActionOverlay->setEnabled(false);
            overlay->setVisible(false);
            //        yahooActionOverlay->setChecked(false);
        }
        else
        {
            mapButton->setText("Select..");
        }
lm's avatar
lm committed
456
    }
457
}
lm's avatar
lm committed
458

lm's avatar
lm committed
459

460
void MapWidget::createPathButtonClicked(bool checked)
lm's avatar
lm committed
461
{
lm's avatar
lm committed
462
    if (mc)
lm's avatar
lm committed
463
    {
lm's avatar
lm committed
464
        Q_UNUSED(checked);
pixhawk's avatar
pixhawk committed
465

lm's avatar
lm committed
466 467 468 469 470
        if (createPath->isChecked())
        {
            // change the cursor shape
            this->setCursor(Qt::PointingHandCursor);
            mc->setMouseMode(qmapcontrol::MapControl::None);
pixhawk's avatar
pixhawk committed
471 472


lm's avatar
lm committed
473 474
            // emit signal start to create a Waypoint global
            //emit createGlobalWP(true, mc->currentCoordinate());
pixhawk's avatar
pixhawk committed
475

lm's avatar
lm committed
476 477 478 479 480 481 482 483 484 485
            //        // Clear the previous WP track
            //        // TODO: Move this to an actual clear track button and add a warning dialog
            //        mc->layer("Waypoints")->clearGeometries();
            //        wps.clear();
            //        path->setPoints(wps);
            //        mc->layer("Waypoints")->addGeometry(path);
            //        wpIndex.clear();
        }
        else
        {
pixhawk's avatar
pixhawk committed
486

lm's avatar
lm committed
487 488 489 490
            this->setCursor(Qt::ArrowCursor);
            mc->setMouseMode(qmapcontrol::MapControl::Panning);
        }
    }
491
}
492

493 494 495 496 497 498 499
/**
 * Captures a click on the map and if in create WP path mode, it adds the WP on MouseButtonRelease
 *
 * @param event The mouse event
 * @param coordinate The coordinate in which it occured the mouse event
 * @note  This slot is connected to the mouseEventCoordinate of the QMapControl object
 */
500 501
void MapWidget::captureMapClick(const QMouseEvent* event, const QPointF coordinate)
{
502
    if (QEvent::MouseButtonRelease == event->type() && createPath->isChecked())
503
    {
504 505
        // Create waypoint name
        QString str;
pixhawk's avatar
pixhawk committed
506

507 508
        // create the WP and set everything in the LineString to display the path
        Waypoint2DIcon* tempCirclePoint;
pixhawk's avatar
pixhawk committed
509

510 511
        if (mav)
        {
512 513 514 515 516 517 518 519 520
            double altitude = 0.0;
            double yaw = 0.0;
            int wpListCount = mav->getWaypointManager()->getWaypointList().count();
            if (wpListCount > 0)
            {
                altitude = mav->getWaypointManager()->getWaypointList().at(wpListCount-1)->getAltitude();
                yaw = mav->getWaypointManager()->getWaypointList().at(wpListCount-1)->getYaw();
            }
            mav->getWaypointManager()->addWaypoint(new Waypoint(wpListCount, coordinate.y(), coordinate.x(), altitude, yaw, true));
521 522 523
        }
        else
        {
524
            str = QString("%1").arg(waypointPath->numberOfPoints());
525
            tempCirclePoint = new Waypoint2DIcon(coordinate.x(), coordinate.y(), 20, str, qmapcontrol::Point::Middle);
526
            wpIcons.append(tempCirclePoint);
pixhawk's avatar
pixhawk committed
527

528
            mc->layer("Waypoints")->addGeometry(tempCirclePoint);
pixhawk's avatar
pixhawk committed
529

530 531 532 533 534
            qmapcontrol::Point* tempPoint = new qmapcontrol::Point(coordinate.x(), coordinate.y(),str);
            wps.append(tempPoint);
            waypointPath->addPoint(tempPoint);

            // Refresh the screen
535
            if (isVisible()) mc->updateRequest(tempPoint->boundingBox().toRect());
536
        }
537
        // emit signal mouse was clicked
538 539 540 541 542 543
        //emit captureMapCoordinateClick(coordinate);
    }
}

void MapWidget::updateWaypoint(int uas, Waypoint* wp)
{
544
    // Update waypoint list and redraw map (last parameter)
545 546 547
    updateWaypoint(uas, wp, true);
}

548 549 550 551
/**
 * This function is called if a a single waypoint is updated and
 * also if the whole list changes.
 */
552 553
void MapWidget::updateWaypoint(int uas, Waypoint* wp, bool updateView)
{
lm's avatar
lm committed
554
    if (mc)
555
    {
lm's avatar
lm committed
556 557
        // Make sure this is the right UAS
        if (uas == this->mav->getUASID())
558
        {
lm's avatar
lm committed
559 560 561 562
            // Only accept waypoints in global coordinate frame
            if (wp->getFrame() == MAV_FRAME_GLOBAL)
            {
                // We're good, this is a global waypoint
563

lm's avatar
lm committed
564 565 566 567 568 569
                // Get the index of this waypoint
                // note the call to getGlobalFrameIndexOf()
                // as we're only handling global waypoints
                int wpindex = UASManager::instance()->getUASForId(uas)->getWaypointManager()->getGlobalFrameIndexOf(wp);
                // If not found, return (this should never happen, but helps safety)
                if (wpindex == -1) return;
570

lm's avatar
lm committed
571 572
                // Check if wp exists yet in map
                if (!(wpIcons.count() > wpindex))
573
                {
lm's avatar
lm committed
574
                    // Waypoint is new, a new icon is created
575
                    QPointF coordinate;
576 577
                    coordinate.setX(wp->getLongitude());
                    coordinate.setY(wp->getLatitude());
lm's avatar
lm committed
578 579 580 581 582 583 584
                    createWaypointGraphAtMap(wpindex, coordinate);
                }
                else
                {
                    // Waypoint exists, update it if we're not
                    // currently dragging it with the mouse
                    if(!waypointIsDrag)
585
                    {
lm's avatar
lm committed
586 587 588 589 590 591 592
                        QPointF coordinate;
                        coordinate.setX(wp->getLongitude());
                        coordinate.setY(wp->getLatitude());

                        Point* waypoint;
                        waypoint = wps.at(wpindex);
                        if (waypoint)
593
                        {
lm's avatar
lm committed
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
                            // First set waypoint coordinate
                            waypoint->setCoordinate(coordinate);
                            // Now update icon position
                            wpIcons.at(wpindex)->setCoordinate(coordinate);
                            // Update pen
                            wpIcons.at(wpindex)->setPen(mavPens.value(uas));
                            // Then waypoint line coordinate
                            Point* linesegment = NULL;
                            // If the line segment already exists, just update it
                            // else create a new one
                            if (waypointPath->points().size() > wpindex)
                            {
                                linesegment = waypointPath->points().at(wpindex);
                                if (linesegment) linesegment->setCoordinate(coordinate);
                            }
                            else
                            {
                                waypointPath->addPoint(waypoint);
                            }

                            // Update view
                            if (updateView) if (isVisible()) mc->updateRequest(waypoint->boundingBox().toRect());
616
                        }
617 618 619
                    }
                }
            }
lm's avatar
lm committed
620
            else
621
            {
lm's avatar
lm committed
622 623 624 625 626 627 628 629
                // Check if the index of this waypoint is larger than the global
                // waypoint list. This implies that the coordinate frame of this
                // waypoint was changed and the list containing only global
                // waypoints was shortened. Thus update the whole list
                if (waypointPath->points().count() > UASManager::instance()->getUASForId(uas)->getWaypointManager()->getGlobalFrameCount())
                {
                    updateWaypointList(uas);
                }
630
            }
631
        }
632
    }
pixhawk's avatar
pixhawk committed
633 634
}

635
void MapWidget::createWaypointGraphAtMap(int id, const QPointF coordinate)
636
{
637
    //if (!wpExists(coordinate))
638
    {
639 640
        // Create waypoint name
        QString str;
pixhawk's avatar
pixhawk committed
641

642 643 644
        // create the WP and set everything in the LineString to display the path
        //CirclePoint* tempCirclePoint = new CirclePoint(coordinate.x(), coordinate.y(), 10, str);
        Waypoint2DIcon* tempCirclePoint;
pixhawk's avatar
pixhawk committed
645

646 647
        if (mav)
        {
648
            int uas = mav->getUASID();
649
            str = QString("%1").arg(id);
650 651
            qDebug() << "Waypoint list count:" << str;
            tempCirclePoint = new Waypoint2DIcon(coordinate.x(), coordinate.y(), 20, str, qmapcontrol::Point::Middle, mavPens.value(uas));
652 653 654
        }
        else
        {
655
            str = QString("%1").arg(id);
656 657
            tempCirclePoint = new Waypoint2DIcon(coordinate.x(), coordinate.y(), 20, str, qmapcontrol::Point::Middle);
        }
pixhawk's avatar
pixhawk committed
658 659


660
        mc->layer("Waypoints")->addGeometry(tempCirclePoint);
pixhawk's avatar
pixhawk committed
661
        wpIcons.append(tempCirclePoint);
pixhawk's avatar
pixhawk committed
662

663 664
        Point* tempPoint = new Point(coordinate.x(), coordinate.y(),str);
        wps.append(tempPoint);
665
        waypointPath->addPoint(tempPoint);
pixhawk's avatar
pixhawk committed
666

667
        //wpIndex.insert(str,tempPoint);
tecnosapiens's avatar
tecnosapiens committed
668
        qDebug()<<"Funcion createWaypointGraphAtMap WP= "<<str<<" -> x= "<<tempPoint->latitude()<<" y= "<<tempPoint->longitude();
pixhawk's avatar
pixhawk committed
669

tecnosapiens's avatar
tecnosapiens committed
670
        // Refresh the screen
671
        if (isVisible()) if (isVisible()) mc->updateRequest(tempPoint->boundingBox().toRect());
672
    }
pixhawk's avatar
pixhawk committed
673

674 675
    ////    // emit signal mouse was clicked
    //    emit captureMapCoordinateClick(coordinate);
676 677
}

678 679
int MapWidget::wpExists(const QPointF coordinate)
{
lm's avatar
lm committed
680 681 682 683 684 685 686 687
    if (mc)
    {
        for (int i = 0; i < wps.size(); i++){
            if (wps.at(i)->latitude() == coordinate.y() &&
                wps.at(i)->longitude()== coordinate.x())
            {
                return 1;
            }
688
        }
689
    }
690
    return 0;
691 692
}

693

694 695
void MapWidget::captureGeometryClick(Geometry* geom, QPoint point)
{
696 697
    Q_UNUSED(geom);
    Q_UNUSED(point);
pixhawk's avatar
pixhawk committed
698

lm's avatar
lm committed
699
    if (mc) mc->setMouseMode(qmapcontrol::MapControl::None);
700 701
}

702 703
void MapWidget::captureGeometryDrag(Geometry* geom, QPointF coordinate)
{
704
    waypointIsDrag = true;
pixhawk's avatar
pixhawk committed
705

706
    // Refresh the screen
707
    if (isVisible()) mc->updateRequest(geom->boundingBox().toRect());
pixhawk's avatar
pixhawk committed
708

709
    int temp = 0;
710 711 712 713 714

    // Get waypoint index in list
    bool wpIndexOk;
    int index = geom->name().toInt(&wpIndexOk);

715
    Waypoint2DIcon* point2Find = dynamic_cast <Waypoint2DIcon*> (geom);
pixhawk's avatar
pixhawk committed
716

717
    if (wpIndexOk && point2Find && wps.count() > index)
718
    {
719
        // Update visual
720
        point2Find->setCoordinate(coordinate);
721 722
        waypointPath->points().at(index)->setCoordinate(coordinate);
        if (isVisible()) mc->updateRequest(waypointPath->boundingBox().toRect());
pixhawk's avatar
pixhawk committed
723

724 725
        // Update waypoint data storage
        if (mav)
726
        {
727
            QVector<Waypoint*> wps = mav->getWaypointManager()->getGlobalFrameWaypointList();
pixhawk's avatar
pixhawk committed
728

729
            if (wps.size() > index)
730
            {
731
                Waypoint* wp = wps.at(index);
732 733
                wp->setLatitude(coordinate.y());
                wp->setLongitude(coordinate.x());
734
                mav->getWaypointManager()->notifyOfChange(wp);
735
            }
736
        }
737 738 739 740 741

        // qDebug() << geom->name();
        temp = geom->get_myIndex();
        //qDebug() << temp;
        emit sendGeometryEndDrag(coordinate,temp);
742
    }
pixhawk's avatar
pixhawk committed
743

744
    waypointIsDrag = false;
745 746
}

747
void MapWidget::captureGeometryEndDrag(Geometry* geom, QPointF coordinate)
748
{
749 750 751
    Q_UNUSED(geom);
    Q_UNUSED(coordinate);
    // TODO: Investigate why when creating the waypoint path this slot is being called
pixhawk's avatar
pixhawk committed
752

753 754 755 756 757 758
    // Only change the mouse mode back to panning when not creating a WP path
    if (!createPath->isChecked())
    {
        waypointIsDrag = false;
        mc->setMouseMode(qmapcontrol::MapControl::Panning);
    }
pixhawk's avatar
pixhawk committed
759

760 761 762 763 764 765 766 767
    if (!setHome->isChecked())
    {
        mc->setMouseMode(qmapcontrol::MapControl::Panning);

        if(mav)
        {
            // Update homePosition
            UASManager::instance()->setHomePosition(
Alejandro's avatar
Alejandro committed
768 769
                                static_cast<double>(homeCoordinate.y()),
                                static_cast<double>(homeCoordinate.x()), 0);
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
        }
    }

}

void MapWidget::captureGeometryDragHome(Geometry *geom, QPointF coordinate)
{
    if (isVisible()) mc->updateRequest(geom->boundingBox().toRect());

    Waypoint2DIcon* point2Find = dynamic_cast <Waypoint2DIcon*> (geom);

    if (point2Find)// && wps.count() > index)
    {
        // Update visual
        point2Find->setCoordinate(coordinate);
        homeCoordinate.setX(coordinate.x());
        homeCoordinate.setY(coordinate.y());

        qmapcontrol::Point* tempPoint = new qmapcontrol::Point(homeCoordinate.x(), homeCoordinate.y(),"g");

        if (isVisible()) mc->updateRequest(tempPoint->boundingBox().toRect());
    }
792 793
}

pixhawk's avatar
pixhawk committed
794 795
MapWidget::~MapWidget()
{
lm's avatar
lm committed
796
    delete mc;
pixhawk's avatar
pixhawk committed
797 798
    delete m_ui;
}
Alejandro's avatar
Alejandro committed
799

lm's avatar
lm committed
800 801 802 803 804 805
/**
 *
 * @param uas the UAS/MAV to monitor/display with the HUD
 */
void MapWidget::addUAS(UASInterface* uas)
{
806
    connect(uas, SIGNAL(globalPositionChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateGlobalPosition(UASInterface*,double,double,double,quint64)));
807
    connect(uas, SIGNAL(attitudeChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*,double,double,double,quint64)));
808
    connect(uas, SIGNAL(systemSpecsChanged(int)), this, SLOT(updateSystemSpecs(int)));
809 810
}

811 812 813 814 815
/**
 * Update the whole list of waypoints. This is e.g. necessary if the list order changed.
 * The UAS manager will emit the appropriate signal whenever updating the list
 * is necessary.
 */
816 817
void MapWidget::updateWaypointList(int uas)
{
lm's avatar
lm committed
818
    if (mc)
819
    {
lm's avatar
lm committed
820 821 822 823 824 825 826
        // Get already existing waypoints
        UASInterface* uasInstance = UASManager::instance()->getUASForId(uas);
        if (uasInstance)
        {
            // Get update rect of old content, this is what will be redrawn
            // in the last step
            QRect updateRect = waypointPath->boundingBox().toRect();
827

lm's avatar
lm committed
828 829
            // Get all waypoints, including non-global waypoints
            QVector<Waypoint*> wpList = uasInstance->getWaypointManager()->getWaypointList();
830

lm's avatar
lm committed
831 832 833 834 835 836
            // Clear if necessary
            if (wpList.count() == 0)
            {
                clearWaypoints(uas);
                return;
            }
837

lm's avatar
lm committed
838 839 840
            // Trim internal list to number of global waypoints in the waypoint manager list
            int overSize = waypointPath->points().count() - uasInstance->getWaypointManager()->getGlobalFrameCount();
            if (overSize > 0)
841
            {
lm's avatar
lm committed
842 843 844 845 846 847 848 849 850 851
                // Remove n waypoints at the end of the list
                // the remaining waypoints will be updated
                // in the next step
                for (int i = 0; i < overSize; ++i)
                {
                    wps.removeLast();
                    mc->layer("Waypoints")->removeGeometry(wpIcons.last());
                    wpIcons.removeLast();
                    waypointPath->points().removeLast();
                }
852
            }
pixhawk's avatar
pixhawk committed
853

lm's avatar
lm committed
854 855 856 857 858 859 860 861
            // Load all existing waypoints into map view
            foreach (Waypoint* wp, wpList)
            {
                // Block map draw updates, since we update everything in the next step
                // but update internal data structures.
                // Please note that updateWaypoint() ignores non-global waypoints
                updateWaypoint(mav->getUASID(), wp, false);
            }
862

lm's avatar
lm committed
863 864 865
            // Update view
            if (isVisible()) mc->updateRequest(updateRect);
        }
866 867 868 869 870 871 872 873 874 875 876 877
    }
}

void MapWidget::redoWaypoints(int uas)
{
    //    QObject* sender = QObject::sender();
    //    UASWaypointManager* manager = dynamic_cast<UASWaypointManager*>(sender);
    //    if (sender)
    //    {
    // Get waypoint list for this MAV

    // Clear all waypoints
878
    //clearWaypoints();
879 880 881 882 883
    // Re-add the updated waypoints

    //    }

    updateWaypointList(uas);
lm's avatar
lm committed
884 885
}

886 887
void MapWidget::activeUASSet(UASInterface* uas)
{
888 889 890
    // Disconnect old MAV
    if (mav)
    {
891
        // Disconnect the waypoint manager / data storage from the UI
892
        disconnect(mav->getWaypointManager(), SIGNAL(waypointListChanged(int)), this, SLOT(updateWaypointList(int)));
893
        disconnect(mav->getWaypointManager(), SIGNAL(waypointChanged(int, Waypoint*)), this, SLOT(updateWaypoint(int,Waypoint*)));
894 895 896
        disconnect(this, SIGNAL(waypointCreated(Waypoint*)), mav->getWaypointManager(), SLOT(addWaypoint(Waypoint*)));
    }

lm's avatar
lm committed
897
    if (uas && mc)
898 899
    {
        mav = uas;
900 901
        QColor color = mav->getColor();
        color.setAlphaF(0.9);
902
        QPen* pen = new QPen(color);
903
        pen->setWidth(3.0);
904 905 906 907
        mavPens.insert(mav->getUASID(), pen);
        // FIXME Remove after refactoring
        waypointPath->setPen(pen);

908
        // Delete all waypoints and add waypoint from new system
909 910
        //redoWaypoints();
        updateWaypointList(uas->getUASID());
911

912
        // Connect the waypoint manager / data storage to the UI
913
        connect(mav->getWaypointManager(), SIGNAL(waypointListChanged(int)), this, SLOT(updateWaypointList(int)));
914
        connect(mav->getWaypointManager(), SIGNAL(waypointChanged(int, Waypoint*)), this, SLOT(updateWaypoint(int,Waypoint*)));
915
        connect(this, SIGNAL(waypointCreated(Waypoint*)), mav->getWaypointManager(), SLOT(addWaypoint(Waypoint*)));
916

917
        updateSystemSpecs(mav->getUASID());
918
        updateSelectedSystem(mav->getUASID());
919
        mc->updateRequest(waypointPath->boundingBox().toRect());
920 921 922
    }
}

923 924
void MapWidget::updateSystemSpecs(int uas)
{
lm's avatar
lm committed
925
    if (mc)
926
    {
lm's avatar
lm committed
927
        foreach (qmapcontrol::Point* p, uasIcons.values())
928
        {
lm's avatar
lm committed
929 930 931 932 933 934 935
            MAV2DIcon* icon = dynamic_cast<MAV2DIcon*>(p);
            if (icon && icon->getUASId() == uas)
            {
                // Set new airframe
                icon->setAirframe(UASManager::instance()->getUASForId(uas)->getAirframe());
                icon->drawIcon();
            }
936 937 938 939
        }
    }
}

940 941
void MapWidget::updateSelectedSystem(int uas)
{
lm's avatar
lm committed
942
    if (mc)
943
    {
lm's avatar
lm committed
944
        foreach (qmapcontrol::Point* p, uasIcons.values())
945
        {
lm's avatar
lm committed
946 947 948 949 950 951
            MAV2DIcon* icon = dynamic_cast<MAV2DIcon*>(p);
            if (icon)
            {
                // Set as selected if ids match
                icon->setSelectedUAS((icon->getUASId() == uas));
            }
952
        }
953 954 955
    }
}

956 957 958 959 960
void MapWidget::updateAttitude(UASInterface* uas, double roll, double pitch, double yaw, quint64 usec)
{
    Q_UNUSED(roll);
    Q_UNUSED(pitch);
    Q_UNUSED(usec);
lm's avatar
lm committed
961
    if (mc)
962
    {
lm's avatar
lm committed
963 964

        if (uas)
965
        {
lm's avatar
lm committed
966 967 968 969 970
            MAV2DIcon* icon = dynamic_cast<MAV2DIcon*>(uasIcons.value(uas->getUASID(), NULL));
            if (icon)
            {
                icon->setYaw(yaw);
            }
971 972 973 974
        }
    }
}

lm's avatar
lm committed
975 976 977 978 979 980 981 982 983
/**
 * Updates the global position of one MAV and append the last movement to the trail
 *
 * @param uas The unmanned air system
 * @param lat Latitude in WGS84 ellipsoid
 * @param lon Longitutde in WGS84 ellipsoid
 * @param alt Altitude over mean sea level
 * @param usec Timestamp of the position message in milliseconds FIXME will move to microseconds
 */
lm's avatar
lm committed
984 985 986
void MapWidget::updateGlobalPosition(UASInterface* uas, double lat, double lon, double alt, quint64 usec)
{
    Q_UNUSED(usec);
987
    Q_UNUSED(alt); // FIXME Use altitude
lm's avatar
lm committed
988
    if (mc)
989
    {
lm's avatar
lm committed
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
        // create a LineString
        //QList<Point*> points;
        // Points with a circle
        // A QPen can be used to customize the
        //pointpen->setWidth(3);
        //points.append(new CirclePoint(lat, lon, 10, uas->getUASName(), Point::Middle, pointpen));

        qmapcontrol::Point* p;
        QPointF coordinate;
        coordinate.setX(lon);
        coordinate.setY(lat);

        if (!uasIcons.contains(uas->getUASID()))
        {
            // Get the UAS color
            QColor uasColor = uas->getColor();

            // Icon
            //QPen* pointpen = new QPen(uasColor);
            qDebug() << "2D MAP: ADDING" << uas->getUASName() << __FILE__ << __LINE__;
            p = new MAV2DIcon(uas, 68, uas->getSystemType(), uas->getColor(), QString("%1").arg(uas->getUASID()), qmapcontrol::Point::Middle);
            uasIcons.insert(uas->getUASID(), p);
            mc->layer("Waypoints")->addGeometry(p);

            // Line
            // A QPen also can use transparency

            //        QList<qmapcontrol::Point*> points;
            //        points.append(new qmapcontrol::Point(coordinate.x(), coordinate.y()));
            //        QPen* linepen = new QPen(uasColor.darker());
            //        linepen->setWidth(2);

            //        // Create tracking line string
            //        qmapcontrol::LineString* ls = new qmapcontrol::LineString(points, QString("%1").arg(uas->getUASID()), linepen);
            //        uasTrails.insert(uas->getUASID(), ls);

            //        // Add the LineString to the layer
            //        mc->layer("Waypoints")->addGeometry(ls);
        }
        else
        {
            //        p = dynamic_cast<MAV2DIcon*>(uasIcons.value(uas->getUASID()));
            //        if (p)
            //        {
            p = uasIcons.value(uas->getUASID());
            p->setCoordinate(QPointF(lon, lat));
            //p->setYaw(uas->getYaw());
            //        }
            // Extend trail
            //        uasTrails.value(uas->getUASID())->addPoint(new qmapcontrol::Point(coordinate.x(), coordinate.y()));
        }
1041

lm's avatar
lm committed
1042
        if (isVisible()) mc->updateRequest(p->boundingBox().toRect());
1043

lm's avatar
lm committed
1044
        //if (isVisible()) mc->updateRequestNew();//(uasTrails.value(uas->getUASID())->boundingBox().toRect());
1045

lm's avatar
lm committed
1046
        if (this->mav && uas->getUASID() == this->mav->getUASID())
1047
        {
lm's avatar
lm committed
1048 1049 1050
            // Limit the position update rate
            quint64 currTime = MG::TIME::getGroundTimeNow();
            if (currTime - lastUpdate > 120)
1051
            {
lm's avatar
lm committed
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
                lastUpdate = currTime;
                // Sets the view to the interesting area
                if (followgps->isChecked())
                {
                    updatePosition(0, lon, lat);
                }
                else
                {
                    // Refresh the screen
                    //if (isVisible()) mc->updateRequestNew();
                }
1063
            }
1064
        }
pixhawk's avatar
pixhawk committed
1065 1066
    }
}
pixhawk's avatar
pixhawk committed
1067

lm's avatar
lm committed
1068 1069 1070
/**
 * Center the view on this position
 */
lm's avatar
lm committed
1071
void MapWidget::updatePosition(float time, double lat, double lon)
pixhawk's avatar
pixhawk committed
1072
{
lm's avatar
lm committed
1073
    Q_UNUSED(time);
1074
    //gpsposition->setText(QString::number(time) + " / " + QString::number(lat) + " / " + QString::number(lon));
lm's avatar
lm committed
1075
    if (followgps->isChecked() && isVisible() && mc)
pixhawk's avatar
pixhawk committed
1076
    {
1077
        if (mc) mc->setView(QPointF(lat, lon));
pixhawk's avatar
pixhawk committed
1078 1079 1080 1081 1082
    }
}

void MapWidget::wheelEvent(QWheelEvent *event)
{
lm's avatar
lm committed
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    if (mc)
    {
        int numDegrees = event->delta() / 8;
        int numSteps = numDegrees / 15;
        // Calculate new zoom level
        int newZoom = mc->currentZoom()+numSteps;
        // Set new zoom level, level is bounded by map control
        mc->setZoom(newZoom);
        // Detail zoom level is the number of steps zoomed in further
        // after the bounding has taken effect
        detailZoom = qAbs(qMin(0, mc->currentZoom()-newZoom));

        // visual field of camera
1096
        //updateCameraPosition(20*newZoom,0,"no");
lm's avatar
lm committed
1097
    }
pixhawk's avatar
pixhawk committed
1098 1099 1100 1101
}

void MapWidget::keyPressEvent(QKeyEvent *event)
{
lm's avatar
lm committed
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    if (mc)
    {
        switch (event->key()) {
        case Qt::Key_Plus:
            mc->zoomIn();
            break;
        case Qt::Key_Minus:
            mc->zoomOut();
            break;
        case Qt::Key_Left:
            mc->scrollLeft(this->width()/scrollStep);
            break;
        case Qt::Key_Right:
            mc->scrollRight(this->width()/scrollStep);
            break;
        case Qt::Key_Down:
            mc->scrollDown(this->width()/scrollStep);
            break;
        case Qt::Key_Up:
            mc->scrollUp(this->width()/scrollStep);
            break;
        default:
            QWidget::keyPressEvent(event);
        }
pixhawk's avatar
pixhawk committed
1126 1127 1128
    }
}

1129
void MapWidget::resizeEvent(QResizeEvent* event )
pixhawk's avatar
pixhawk committed
1130
{
1131
    Q_UNUSED(event);
lm's avatar
lm committed
1132 1133 1134 1135
        if (!initialized)
        {
            init();
        }
1136
    if (mc) mc->resize(this->size());
pixhawk's avatar
pixhawk committed
1137 1138
}

1139 1140 1141
void MapWidget::showEvent(QShowEvent* event)
{
    Q_UNUSED(event);
lm's avatar
lm committed
1142 1143 1144 1145 1146 1147 1148
//    if (isVisible())
//    {
//	if (!initialized)
//	{
//            init();
//	}
//    }
1149 1150 1151 1152 1153
}

void MapWidget::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
lm's avatar
lm committed
1154 1155 1156 1157 1158 1159 1160 1161 1162
    if (mc)
    {
        QSettings settings;
        settings.beginGroup("QGC_MAPWIDGET");
        QPointF currentPos = mc->currentCoordinate();
        settings.setValue("LAST_LATITUDE", currentPos.y());
        settings.setValue("LAST_LONGITUDE", currentPos.x());
        settings.setValue("LAST_ZOOM", mc->currentZoom());
        settings.endGroup();
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

        settings.beginGroup("QGC_MAPINDEX");
        settings.setValue("MAP_INDEX", index);
        settings.endGroup();

        settings.beginGroup("QGC_HOMEPOSITION");
        settings.setValue("HOME_LATITUDE", homeCoordinate.y());
        settings.setValue("HOME_LONGITUDE", homeCoordinate.x());
        settings.endGroup();

lm's avatar
lm committed
1173
        settings.sync();
1174 1175


lm's avatar
lm committed
1176
    }
1177 1178
}

pixhawk's avatar
pixhawk committed
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190

void MapWidget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
1191

1192
void MapWidget::clearWaypoints(int uas)
1193
{
lm's avatar
lm committed
1194
    if (mc)
1195
    {
lm's avatar
lm committed
1196 1197
        Q_UNUSED(uas);
        // Clear the previous WP track
1198

lm's avatar
lm committed
1199 1200 1201 1202 1203 1204 1205
        //mc->layer("Waypoints")->clearGeometries();
        wps.clear();
        foreach (Point* p, wpIcons)
        {
            mc->layer("Waypoints")->removeGeometry(p);
        }
        wpIcons.clear();
1206

lm's avatar
lm committed
1207 1208
        // Get bounding box of this object BEFORE deleting the content
        QRect box = waypointPath->boundingBox().toRect();
1209

lm's avatar
lm committed
1210 1211
        // Delete the content
        waypointPath->points().clear();
pixhawk's avatar
pixhawk committed
1212

lm's avatar
lm committed
1213 1214 1215 1216 1217
        //delete waypointPath;
        //waypointPath = new
        //mc->layer("Waypoints")->addGeometry(waypointPath);
        //wpIndex.clear();
        if (isVisible()) mc->updateRequest(box);//(waypointPath->boundingBox().toRect());
1218

lm's avatar
lm committed
1219 1220 1221 1222 1223
        if(createPath->isChecked())
        {
            createPath->click();
        }
    }
1224
}
pixhawk's avatar
pixhawk committed
1225

1226
void MapWidget::clearPath(int uas)
1227
{
pixhawk's avatar
pixhawk committed
1228
    Q_UNUSED(uas);
lm's avatar
lm committed
1229
    if (mc)
1230
    {
lm's avatar
lm committed
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        mc->layer("Tracking")->clearGeometries();
        foreach (qmapcontrol::LineString* ls, uasTrails)
        {
            QPen* linepen = ls->pen();
            delete ls;
            qmapcontrol::LineString* lsNew = new qmapcontrol::LineString(QList<qmapcontrol::Point*>(), "", linepen);
            mc->layer("Tracking")->addGeometry(lsNew);
        }
        // FIXME update this with update request only for bounding box of trails
        if (isVisible()) mc->updateRequestNew();//(QRect(0, 0, width(), height()));
1241
    }
1242
}
1243

1244 1245 1246 1247
void MapWidget::createHomePosition(const QMouseEvent *event, const QPointF coordinate)
{
    if (QEvent::MouseButtonRelease == event->type() && setHome->isChecked())
    {
1248 1249 1250
        this->createHomePosition(coordinate);
    }
}
1251

1252 1253 1254 1255
void MapWidget::createHomePosition(const QPointF coordinate)
{
    homeCoordinate= coordinate;
    Waypoint2DIcon* tempCirclePoint;
1256

1257 1258
    double latitude = homeCoordinate.y();
    double longitude = homeCoordinate.x();
1259

1260 1261 1262 1263
    tempCirclePoint = new Waypoint2DIcon(
             longitude,
             latitude,
             20, "g", qmapcontrol::Point::Middle);
1264

1265 1266
    QPen* pencil = new QPen(Qt::blue);
    tempCirclePoint->setPen(pencil);
1267

1268 1269
    mc->layer("Station")->clearGeometries();
    mc->layer("Station")->addGeometry(tempCirclePoint);
1270

1271 1272 1273 1274 1275
    qmapcontrol::Point* tempPoint = new qmapcontrol::Point(latitude, longitude,"g");

    if (isVisible())
    {
        mc->updateRequest(tempPoint->boundingBox().toRect());
1276 1277 1278 1279 1280 1281 1282 1283 1284
    }
}

void MapWidget::createHomePositionClick(bool click)
{
    Q_UNUSED(click);

    if (!setHome->isChecked())
    {
1285 1286 1287 1288 1289 1290
        if(mav)
        {
            UASManager::instance()->setHomePosition(
                    static_cast<double>(homeCoordinate.y()),
                    static_cast<double>(homeCoordinate.x()), 0);

1291

1292
            //qDebug()<<"Set home position "<<homeCoordinate.y()<<" "<<homeCoordinate.x();
1293
        }
1294 1295
    }
}