QGCMapPolygonVisuals.qml 19.9 KB
Newer Older
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1
/****************************************************************************
2 3 4 5 6 7 8 9 10 11 12 13
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

import QtQuick          2.3
import QtQuick.Controls 1.2
import QtLocation       5.3
import QtPositioning    5.3
14
import QtQuick.Dialogs  1.2
15

16 17 18 19 20 21
import QGroundControl                   1.0
import QGroundControl.ScreenTools       1.0
import QGroundControl.Palette           1.0
import QGroundControl.Controls          1.0
import QGroundControl.FlightMap         1.0
import QGroundControl.ShapeFileHelper   1.0
22 23 24 25 26

/// QGCMapPolygon map visuals
Item {
    id: _root

DonLakeFlyer's avatar
DonLakeFlyer committed
27 28 29
    property var    qgcView                                     ///< QGCView for popping dialogs
    property var    mapControl                                  ///< Map control to place item in
    property var    mapPolygon                                  ///< QGCMapPolygon object
30
    property bool   interactive:        mapPolygon.interactive
31 32 33 34
    property color  interiorColor:      "transparent"
    property real   interiorOpacity:    1
    property int    borderWidth:        0
    property color  borderColor:        "black"
35
    property bool   initPolygon:        false
36

37 38 39 40
    property var    _polygonComponent
    property var    _dragHandlesComponent
    property var    _splitHandlesComponent
    property var    _centerDragHandleComponent
41 42
    property bool   _circle:                    false
    property real   _circleRadius
43
    property bool   _editCircleRadius:          false
44

Don Gagne's avatar
Don Gagne committed
45 46 47
    property real _zorderDragHandle:    QGroundControl.zOrderMapItems + 3   // Highest to prevent splitting when items overlap
    property real _zorderSplitHandle:   QGroundControl.zOrderMapItems + 2
    property real _zorderCenterHandle:  QGroundControl.zOrderMapItems + 1   // Lowest such that drag or split takes precedence
48

49 50 51 52 53 54 55 56 57 58
    function addVisuals() {
        _polygonComponent = polygonComponent.createObject(mapControl)
        mapControl.addMapItem(_polygonComponent)
    }

    function removeVisuals() {
        _polygonComponent.destroy()
    }

    function addHandles() {
59 60 61 62 63
        if (!_dragHandlesComponent) {
            _dragHandlesComponent = dragHandlesComponent.createObject(mapControl)
            _splitHandlesComponent = splitHandlesComponent.createObject(mapControl)
            _centerDragHandleComponent = centerDragHandleComponent.createObject(mapControl)
        }
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    }

    function removeHandles() {
        if (_dragHandlesComponent) {
            _dragHandlesComponent.destroy()
            _dragHandlesComponent = undefined
        }
        if (_splitHandlesComponent) {
            _splitHandlesComponent.destroy()
            _splitHandlesComponent = undefined
        }
        if (_centerDragHandleComponent) {
            _centerDragHandleComponent.destroy()
            _centerDragHandleComponent = undefined
        }
    }

81 82 83
    /// Calculate the default/initial 4 sided polygon
    function defaultPolygonVertices() {
        // Initial polygon is inset to take 2/3rds space
84
        var rect = Qt.rect(mapControl.centerViewport.x, mapControl.centerViewport.y, mapControl.centerViewport.width, mapControl.centerViewport.height)
85 86 87 88 89
        rect.x += (rect.width * 0.25) / 2
        rect.y += (rect.height * 0.25) / 2
        rect.width *= 0.75
        rect.height *= 0.75

90 91 92 93 94
        var centerCoord =       mapControl.toCoordinate(Qt.point(rect.x + (rect.width / 2), rect.y + (rect.height / 2)),   false /* clipToViewPort */)
        var topLeftCoord =      mapControl.toCoordinate(Qt.point(rect.x, rect.y),                                          false /* clipToViewPort */)
        var topRightCoord =     mapControl.toCoordinate(Qt.point(rect.x + rect.width, rect.y),                             false /* clipToViewPort */)
        var bottomLeftCoord =   mapControl.toCoordinate(Qt.point(rect.x, rect.y + rect.height),                            false /* clipToViewPort */)
        var bottomRightCoord =  mapControl.toCoordinate(Qt.point(rect.x + rect.width, rect.y + rect.height),               false /* clipToViewPort */)
95 96 97 98 99 100 101 102 103 104 105 106

        // Initial polygon has max width and height of 3000 meters
        var halfWidthMeters =   Math.min(topLeftCoord.distanceTo(topRightCoord), 3000) / 2
        var halfHeightMeters =  Math.min(topLeftCoord.distanceTo(bottomLeftCoord), 3000) / 2
        topLeftCoord =      centerCoord.atDistanceAndAzimuth(halfWidthMeters, -90).atDistanceAndAzimuth(halfHeightMeters, 0)
        topRightCoord =     centerCoord.atDistanceAndAzimuth(halfWidthMeters, 90).atDistanceAndAzimuth(halfHeightMeters, 0)
        bottomLeftCoord =   centerCoord.atDistanceAndAzimuth(halfWidthMeters, -90).atDistanceAndAzimuth(halfHeightMeters, 180)
        bottomRightCoord =  centerCoord.atDistanceAndAzimuth(halfWidthMeters, 90).atDistanceAndAzimuth(halfHeightMeters, 180)

        return [ topLeftCoord, topRightCoord, bottomRightCoord, bottomLeftCoord, centerCoord  ]
    }

107 108 109
    /// Add an initial 4 sided polygon
    function addInitialPolygon() {
        if (mapPolygon.count < 3) {
110
            var initialVertices = defaultPolygonVertices()
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
            mapPolygon.appendVertex(initialVertices[0])
            mapPolygon.appendVertex(initialVertices[1])
            mapPolygon.appendVertex(initialVertices[2])
            mapPolygon.appendVertex(initialVertices[3])
        }
    }

    /// Reset polygon back to initial default
    function resetPolygon() {
        var initialVertices = defaultPolygonVertices()
        mapPolygon.clear()
        for (var i=0; i<4; i++) {
            mapPolygon.appendVertex(initialVertices[i])
        }
        _circle = false
    }

    function setCircleRadius(center, radius) {
        var unboundCenter = center.atDistanceAndAzimuth(0, 0)
        _circleRadius = radius
        var segments = 16
        var angleIncrement = 360 / segments
        var angle = 0
        mapPolygon.clear()
        for (var i=0; i<segments; i++) {
            var vertex = unboundCenter.atDistanceAndAzimuth(_circleRadius, angle)
            mapPolygon.appendVertex(vertex)
            angle += angleIncrement
139
        }
140 141 142 143 144 145 146 147 148 149 150
        _circle = true
    }

    /// Reset polygon to a circle which fits within initial polygon
    function resetCircle() {
        var initialVertices = defaultPolygonVertices()
        var width = initialVertices[0].distanceTo(initialVertices[1])
        var height = initialVertices[1].distanceTo(initialVertices[2])
        var radius = Math.min(width, height) / 2
        var center = initialVertices[4]
        setCircleRadius(center, radius)
151 152 153 154 155 156 157 158 159 160 161
    }

    onInteractiveChanged: {
        if (interactive) {
            addHandles()
        } else {
            removeHandles()
        }
    }

    Component.onCompleted: {
162 163 164 165
        if(initPolygon){
            addInitialPolygon()
        }

166
        addVisuals()
167 168 169 170 171
        if (interactive) {
            addHandles()
        }
    }

172 173 174 175 176
    Component.onDestruction: {
        removeVisuals()
        removeHandles()
    }

177 178
    QGCPalette { id: qgcPal }

DonLakeFlyer's avatar
DonLakeFlyer committed
179
    QGCFileDialog {
180
        id:             kmlOrSHPLoadDialog
181
        qgcView:        _root.qgcView
DonLakeFlyer's avatar
DonLakeFlyer committed
182
        folder:         QGroundControl.settingsManager.appSettings.missionSavePath
183
        title:          qsTr("Select Polygon File")
DonLakeFlyer's avatar
DonLakeFlyer committed
184
        selectExisting: true
185
        nameFilters:    ShapeFileHelper.fileDialogKMLOrSHPFilters
186
        fileExtension:  QGroundControl.settingsManager.appSettings.kmlFileExtension
187
        fileExtension2: QGroundControl.settingsManager.appSettings.shpFileExtension
DonLakeFlyer's avatar
DonLakeFlyer committed
188 189

        onAcceptedForLoad: {
190
            mapPolygon.loadKMLOrSHPFile(file)
191
            mapFitFunctions.fitMapViewportToMissionItems()
DonLakeFlyer's avatar
DonLakeFlyer committed
192 193 194 195
            close()
        }
    }

196 197 198
    Menu {
        id: menu

199
        property int _editingVertexIndex: -1
200

201 202 203 204 205 206 207
        function popupVertex(curIndex) {
            menu._editingVertexIndex = curIndex
            removeVertexItem.visible = (mapPolygon.count > 3 && menu._editingVertexIndex >= 0)
            menu.popup()
        }

        function popupCenter() {
208 209 210 211 212
            menu.popup()
        }

        MenuItem {
            id:             removeVertexItem
213
            visible:        !_circle
214 215
            text:           qsTr("Remove vertex")
            onTriggered: {
216 217
                if (menu._editingVertexIndex >= 0) {
                    mapPolygon.removeVertex(menu._editingVertexIndex)
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
                }
            }
        }

        MenuSeparator {
            visible:        removeVertexItem.visible
        }

        MenuItem {
            text:           qsTr("Circle" )
            onTriggered:    resetCircle()
        }

        MenuItem {
            text:           qsTr("Polygon")
            onTriggered:    resetPolygon()
        }

        MenuItem {
            text:           qsTr("Set radius..." )
            visible:        _circle
239
            onTriggered:    _editCircleRadius = true
240 241 242 243
        }

        MenuItem {
            text:           qsTr("Edit position..." )
244 245 246 247 248 249 250 251
            visible:        _circle
            onTriggered:    qgcView.showDialog(editCenterPositionDialog, qsTr("Edit Center Position"), qgcView.showDialogDefaultWidth, StandardButton.Close)
        }

        MenuItem {
            text:           qsTr("Edit position..." )
            visible:        !_circle && menu._editingVertexIndex >= 0
            onTriggered:    qgcView.showDialog(editVertexPositionDialog, qsTr("Edit Vertex Position"), qgcView.showDialogDefaultWidth, StandardButton.Close)
252 253 254
        }

        MenuItem {
255 256
            text:           qsTr("Load KML/SHP...")
            onTriggered:    kmlOrSHPLoadDialog.openForLoad()
257 258 259
        }
    }

260 261 262 263
    Component {
        id: polygonComponent

        MapPolygon {
264 265 266 267 268
            color:          interiorColor
            opacity:        interiorOpacity
            border.color:   borderColor
            border.width:   borderWidth
            path:           mapPolygon.path
269 270 271 272 273 274 275 276 277 278
        }
    }

    Component {
        id: splitHandleComponent

        MapQuickItem {
            id:             mapQuickItem
            anchorPoint.x:  dragHandle.width / 2
            anchorPoint.y:  dragHandle.height / 2
279
            visible:        !_circle
280 281 282 283 284 285 286 287

            property int vertexIndex

            sourceItem: Rectangle {
                id:         dragHandle
                width:      ScreenTools.defaultFontPixelHeight * 1.5
                height:     width
                radius:     width / 2
288 289
                border.color:      "white"
                color:      "transparent"
290
                opacity:    .50
291
                z:          _zorderSplitHandle
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

                QGCLabel {
                    anchors.horizontalCenter:   parent.horizontalCenter
                    anchors.verticalCenter:     parent.verticalCenter
                    text:                       "+"
                }

                QGCMouseArea {
                    fillItem:   parent
                    onClicked:  mapPolygon.splitPolygonSegment(mapQuickItem.vertexIndex)
                }
            }
        }
    }

    Component {
        id: splitHandlesComponent

        Repeater {
            model: mapPolygon.path

            delegate: Item {
                property var _splitHandle
                property var _vertices:     mapPolygon.path

                function _setHandlePosition() {
                    var nextIndex = index + 1
                    if (nextIndex > _vertices.length - 1) {
                        nextIndex = 0
                    }
                    var distance = _vertices[index].distanceTo(_vertices[nextIndex])
                    var azimuth = _vertices[index].azimuthTo(_vertices[nextIndex])
                    _splitHandle.coordinate = _vertices[index].atDistanceAndAzimuth(distance / 2, azimuth)
                }

                Component.onCompleted: {
                    _splitHandle = splitHandleComponent.createObject(mapControl)
                    _splitHandle.vertexIndex = index
                    _setHandlePosition()
                    mapControl.addMapItem(_splitHandle)
                }

                Component.onDestruction: {
                    if (_splitHandle) {
                        _splitHandle.destroy()
                    }
                }
            }
        }
    }

    // Control which is used to drag polygon vertices
    Component {
        id: dragAreaComponent

        MissionItemIndicatorDrag {
348
            id:         dragArea
349
            mapControl: _root.mapControl
350 351
            z:          _zorderDragHandle
            visible:    !_circle
352
            onDragStop: mapPolygon.verifyClockwiseWinding()
353 354 355 356 357 358 359 360 361

            property int polygonVertex

            property bool _creationComplete: false

            Component.onCompleted: _creationComplete = true

            onItemCoordinateChanged: {
                if (_creationComplete) {
362
                    // During component creation some bad coordinate values got through which screws up draw
363 364 365 366
                    mapPolygon.adjustVertex(polygonVertex, itemCoordinate)
                }
            }

367
            onClicked: menu.popupVertex(polygonVertex)
368 369 370
        }
    }

371 372 373 374
    Component {
        id: centerDragHandle
        MapQuickItem {
            id:             mapQuickItem
375 376
            anchorPoint.x:  dragHandle.width  * 0.5
            anchorPoint.y:  dragHandle.height * 0.5
377 378
            z:              _zorderDragHandle
            sourceItem: Rectangle {
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
                id:             dragHandle
                width:          ScreenTools.defaultFontPixelHeight * 1.5
                height:         width
                radius:         width * 0.5
                color:          Qt.rgba(1,1,1,0.8)
                border.color:   Qt.rgba(0,0,0,0.25)
                border.width:   1
                QGCColoredImage {
                    width:      parent.width
                    height:     width
                    color:      Qt.rgba(0,0,0,1)
                    mipmap:     true
                    fillMode:   Image.PreserveAspectFit
                    source:     "/qmlimages/MapCenter.svg"
                    sourceSize.height:  height
                    anchors.centerIn:   parent
395 396 397 398 399
                }
            }
        }
    }

400 401 402 403 404
    Component {
        id: dragHandleComponent

        MapQuickItem {
            id:             mapQuickItem
405
            anchorPoint.x:  dragHandle.width  / 2
406
            anchorPoint.y:  dragHandle.height / 2
407
            z:              _zorderDragHandle
408 409 410
            visible:        !_circle

            property int polygonVertex
411 412

            sourceItem: Rectangle {
413 414 415 416 417 418 419
                id:             dragHandle
                width:          ScreenTools.defaultFontPixelHeight * 1.5
                height:         width
                radius:         width * 0.5
                color:          Qt.rgba(1,1,1,0.8)
                border.color:   Qt.rgba(0,0,0,0.25)
                border.width:   1
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
            }
        }
    }

    // Add all polygon vertex drag handles to the map
    Component {
        id: dragHandlesComponent

        Repeater {
            model: mapPolygon.pathModel

            delegate: Item {
                property var _visuals: [ ]

                Component.onCompleted: {
                    var dragHandle = dragHandleComponent.createObject(mapControl)
                    dragHandle.coordinate = Qt.binding(function() { return object.coordinate })
437
                    dragHandle.polygonVertex = Qt.binding(function() { return index })
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
                    mapControl.addMapItem(dragHandle)
                    var dragArea = dragAreaComponent.createObject(mapControl, { "itemIndicator": dragHandle, "itemCoordinate": object.coordinate })
                    dragArea.polygonVertex = Qt.binding(function() { return index })
                    _visuals.push(dragHandle)
                    _visuals.push(dragArea)
                }

                Component.onDestruction: {
                    for (var i=0; i<_visuals.length; i++) {
                        _visuals[i].destroy()
                    }
                    _visuals = [ ]
                }
            }
        }
    }

455
    Component {
456
        id: editCenterPositionDialog
457 458 459

        EditPositionDialog {
            coordinate: mapPolygon.center
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
            onCoordinateChanged: {
                // Prevent spamming signals on vertex changes by setting centerDrag = true when changing center position.
                // This also fixes a bug where Qt gets confused by all the signalling and draws a bad visual.
                mapPolygon.centerDrag = true
                mapPolygon.center = coordinate
                mapPolygon.centerDrag = false
            }
        }
    }

    Component {
        id: editVertexPositionDialog

        EditPositionDialog {
            coordinate:             mapPolygon.vertexCoordinate(menu._editingVertexIndex)
475 476 477 478
            onCoordinateChanged: {
                mapPolygon.adjustVertex(menu._editingVertexIndex, coordinate)
                mapPolygon.verifyClockwiseWinding()
            }
479 480 481
        }
    }

482 483 484 485
    Component {
        id: centerDragAreaComponent

        MissionItemIndicatorDrag {
486
            mapControl:                 _root.mapControl
Don Gagne's avatar
Don Gagne committed
487
            z:                          _zorderCenterHandle
DonLakeFlyer's avatar
DonLakeFlyer committed
488 489 490
            onItemCoordinateChanged:    mapPolygon.center = itemCoordinate
            onDragStart:                mapPolygon.centerDrag = true
            onDragStop:                 mapPolygon.centerDrag = false
491

492
            onClicked: menu.popupCenter()
493 494

            function setRadiusFromDialog() {
Don Gagne's avatar
Don Gagne committed
495 496
                var radius = QGroundControl.appSettingsDistanceUnitsToMeters(radiusField.text)
                setCircleRadius(mapPolygon.center, radius)
497
                _editCircleRadius = false
498 499 500 501 502 503 504 505 506
            }

            Rectangle {
                anchors.margins:    _margin
                anchors.left:       parent.right
                width:              radiusColumn.width + (_margin *2)
                height:             radiusColumn.height + (_margin *2)
                color:              qgcPal.window
                border.color:       qgcPal.text
507
                visible:            _editCircleRadius
508 509 510 511 512 513 514 515 516 517 518 519

                Column {
                    id:                 radiusColumn
                    anchors.margins:    _margin
                    anchors.left:       parent.left
                    anchors.top:        parent.top
                    spacing:            _margin

                    QGCLabel { text: qsTr("Radius:") }

                    QGCTextField {
                        id:                 radiusField
Don Gagne's avatar
Don Gagne committed
520 521 522
                        showUnits:          true
                        unitsLabel:         QGroundControl.appSettingsDistanceUnitsString
                        text:               QGroundControl.metersToAppSettingsDistanceUnits(_circleRadius).toFixed(2)
523
                        onEditingFinished:  setRadiusFromDialog()
DonLakeFlyer's avatar
DonLakeFlyer committed
524
                        inputMethodHints:   Qt.ImhFormattedNumbersOnly
525 526 527 528 529 530 531 532 533 534 535 536 537 538
                    }
                }

                QGCLabel {
                    anchors.right:  radiusColumn.right
                    anchors.top:    radiusColumn.top
                    text:           "X"

                    QGCMouseArea {
                        fillItem:   parent
                        onClicked:  setRadiusFromDialog()
                    }
                }
            }
539 540 541 542 543 544 545 546 547 548 549
        }
    }

    Component {
        id: centerDragHandleComponent

        Item {
            property var dragHandle
            property var dragArea

            Component.onCompleted: {
550
                dragHandle = centerDragHandle.createObject(mapControl)
551 552 553 554 555 556 557 558 559 560 561 562 563
                dragHandle.coordinate = Qt.binding(function() { return mapPolygon.center })
                mapControl.addMapItem(dragHandle)
                dragArea = centerDragAreaComponent.createObject(mapControl, { "itemIndicator": dragHandle, "itemCoordinate": mapPolygon.center })
            }

            Component.onDestruction: {
                dragHandle.destroy()
                dragArea.destroy()
            }
        }
    }
}