summaryrefslogtreecommitdiff
path: root/src/location/declarativemaps/qquickgeomapgesturearea.cpp
blob: fc2debc3a7b56d8e1be39a1cdea7344e55f19966 (plain)
1
2
3
4
5
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
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
447
448
449
450
451
452
453
454
455
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
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
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
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
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qquickgeomapgesturearea_p.h"
#include "qquickgeocoordinateanimation_p.h"
#include "qdeclarativegeomap_p.h"
#include "error_messages_p.h"

#include <QtGui/QGuiApplication>
#include <QtGui/qevent.h>
#if QT_CONFIG(wheelevent)
#include <QtGui/QWheelEvent>
#endif
#include <QtGui/QStyleHints>
#include <QtQml/qqmlinfo.h>
#include <QtQuick/QQuickWindow>
#include <QPropertyAnimation>
#include <QDebug>
#include "math.h"
#include <cmath>
#include "qgeomap_p.h"
#include "qdoublevector2d_p.h"
#include "qlocationutils_p.h"
#include <QtGui/QMatrix4x4>


#define QML_MAP_FLICK_DEFAULTMAXVELOCITY 2500
#define QML_MAP_FLICK_MINIMUMDECELERATION 500
#define QML_MAP_FLICK_DEFAULTDECELERATION 2500
#define QML_MAP_FLICK_MAXIMUMDECELERATION 10000

#define QML_MAP_FLICK_VELOCITY_SAMPLE_PERIOD 38
// FlickThreshold determines how far the "mouse" must have moved
// before we perform a flick.
static const int FlickThreshold = 20;
// Really slow flicks can be annoying.
static const qreal MinimumFlickVelocity = 75.0;
// Tolerance for detecting two finger sliding start
static const qreal MaximumParallelPosition = 40.0; // in degrees
// Tolerance for detecting parallel sliding
static const qreal MaximumParallelSlidingAngle = 4.0; // in degrees
// Tolerance for starting rotation
static const qreal MinimumRotationStartingAngle = 15.0; // in degrees
// Tolerance for starting pinch
static const qreal MinimumPinchDelta = 40; // in pixels
// Tolerance for starting tilt when sliding vertical
static const qreal MinimumPanToTiltDelta = 80; // in pixels;

static qreal distanceBetweenTouchPoints(const QPointF &p1, const QPointF &p2)
{
    return QLineF(p1, p2).length();
}

static qreal angleFromPoints(const QPointF &p1, const QPointF &p2)
{
    return QLineF(p1, p2).angle();
}

// Keeps it in +- 180
static qreal touchAngle(const QPointF &p1, const QPointF &p2)
{
    qreal angle = angleFromPoints(p1, p2);
    if (angle > 180)
        angle -= 360;
    return angle;
}

// Deals with angles crossing the +-180 edge, assumes that the delta can't be > 180
static qreal angleDelta(const qreal angle1, const qreal angle2)
{
    qreal delta = angle1 - angle2;
    if (delta > 180.0) // detect crossing angle1 positive, angle2 negative, rotation counterclockwise, difference negative
        delta = angle1 - angle2 - 360.0;
    else if (delta < -180.0) // detect crossing angle1 negative, angle2 positive, rotation clockwise, difference positive
        delta = angle1 - angle2 + 360.0;

    return delta;
}

static bool pointDragged(const QPointF &pOld, const QPointF &pNew)
{
    static const int startDragDistance = qApp->styleHints()->startDragDistance();
    return ( qAbs(pNew.x() - pOld.x()) > startDragDistance
             || qAbs(pNew.y() - pOld.y()) > startDragDistance);
}

static qreal vectorSize(const QPointF &vector)
{
    return std::sqrt(vector.x() * vector.x() + vector.y() * vector.y());
}

// This linearizes the angles around 0, and keep it linear around 180, allowing to differentiate
// touch angles that are supposed to be parallel (0 or 180 depending on what finger goes first)
static qreal touchAngleTilting(const QPointF &p1, const QPointF &p2)
{
    qreal angle = angleFromPoints(p1, p2);
    if (angle > 270)
        angle -= 360;
    return angle;
}

static bool movingParallelVertical(const QPointF &p1old, const QPointF &p1new, const QPointF &p2old, const QPointF &p2new)
{
    if (!pointDragged(p1old, p1new) || !pointDragged(p2old, p2new))
        return false;

    QPointF v1 = p1new - p1old;
    QPointF v2 = p2new - p2old;
    qreal v1v2size = vectorSize(v1 + v2);

    if (v1v2size < vectorSize(v1) || v1v2size < vectorSize(v2)) // going in opposite directions
        return false;

    const qreal newAngle = touchAngleTilting(p1new, p2new);
    const qreal oldAngle = touchAngleTilting(p1old, p2old);
    const qreal angleDiff = angleDelta(newAngle, oldAngle);

    if (qAbs(angleDiff) > MaximumParallelSlidingAngle)
        return false;

    return true;
}

QT_BEGIN_NAMESPACE


/*!
    \qmltype MapPinchEvent
    \instantiates QGeoMapPinchEvent
    \inqmlmodule QtLocation

    \brief MapPinchEvent type provides basic information about pinch event.

    MapPinchEvent type provides basic information about pinch event. They are
    present in handlers of MapPinch (for example pinchStarted/pinchUpdated). Events are only
    guaranteed to be valid for the duration of the handler.

    Except for the \l accepted property, all properties are read-only.

    \section2 Example Usage

    The following example enables the pinch gesture on a map and reacts to the
    finished event.

    \code
    Map {
        id: map
        gesture.enabled: true
        gesture.onPinchFinished:{
            var coordinate1 = map.toCoordinate(gesture.point1)
            var coordinate2 = map.toCoordinate(gesture.point2)
            console.log("Pinch started at:")
            console.log("        Points (" + gesture.point1.x + ", " + gesture.point1.y + ") - (" + gesture.point2.x + ", " + gesture.point2.y + ")")
            console.log("   Coordinates (" + coordinate1.latitude + ", " + coordinate1.longitude + ") - (" + coordinate2.latitude + ", " + coordinate2.longitude + ")")
        }
    }
    \endcode

    \ingroup qml-QtLocation5-maps
    \since Qt Location 5.0
*/

/*!
    \qmlproperty QPoint QtLocation::MapPinchEvent::center

    This read-only property holds the current center point.
*/

/*!
    \qmlproperty real QtLocation::MapPinchEvent::angle

    This read-only property holds the current angle between the two points in
    the range -180 to 180. Positive values for the angles mean counter-clockwise
    while negative values mean the clockwise direction. Zero degrees is at the
    3 o'clock position.
*/

/*!
    \qmlproperty QPoint QtLocation::MapPinchEvent::point1
    \qmlproperty QPoint QtLocation::MapPinchEvent::point2

    These read-only properties hold the actual touch points generating the pinch.
    The points are not in any particular order.
*/

/*!
    \qmlproperty int QtLocation::MapPinchEvent::pointCount

    This read-only property holds the number of points currently touched.
    The MapPinch will not react until two touch points have initiated a gesture,
    but will remain active until all touch points have been released.
*/

/*!
    \qmlproperty bool QtLocation::MapPinchEvent::accepted

    Setting this property to false in the \c MapPinch::onPinchStarted handler
    will result in no further pinch events being generated, and the gesture
    ignored.
*/

/*!
    \qmltype MapGestureArea
    \instantiates QQuickGeoMapGestureArea

    \inqmlmodule QtLocation

    \brief The MapGestureArea type provides Map gesture interaction.

    MapGestureArea objects are used as part of a Map, to provide for panning,
    flicking and pinch-to-zoom gesture used on touch displays, as well as two finger rotation
    and two finger parallel vertical sliding to tilt the map.
    On platforms supporting \l QWheelEvent, using the scroll wheel alone, or in combination with
    key modifiers Shift or Control will also zoom, rotate or tilt the map, respectively.

    A MapGestureArea is automatically created with a new Map and available with
    the \l{Map::gesture}{gesture} property. This is the only way
    to create a MapGestureArea, and once created this way cannot be destroyed
    without its parent Map.

    The two most commonly used properties of the MapGestureArea are the \l enabled
    and \l acceptedGestures properties. Both of these must be set before a
    MapGestureArea will have any effect upon interaction with the Map.
    The \l flickDeceleration property controls how quickly the map pan slows after contact
    is released while panning the map.

    \section2 Performance

    The MapGestureArea, when enabled, must process all incoming touch events in
    order to track the shape and size of the "pinch". The overhead added on
    touch events can be considered constant time.

    \section2 Example Usage

    The following example enables the pinch and pan gestures on the map, but not flicking. So the
    map scrolling will halt immediately on releasing the mouse button / touch.

    \code
    Map {
        gesture.enabled: true
        gesture.acceptedGestures: MapGestureArea.PinchGesture | MapGestureArea.PanGesture
    }
    \endcode

    \ingroup qml-QtLocation5-maps
    \since Qt Location 5.0
*/

/*!
    \qmlproperty bool QtLocation::MapGestureArea::enabled

    This property holds whether the gestures are enabled.
*/

/*!
    \qmlproperty bool QtLocation::MapGestureArea::pinchActive

    This read-only property holds whether the pinch gesture is active.
*/

/*!
    \qmlproperty bool QtLocation::MapGestureArea::panActive

    This read-only property holds whether the pan gesture is active.

    \note Change notifications for this property were introduced in Qt 5.5.
*/

/*!
    \qmlproperty bool QtLocation::MapGestureArea::rotationActive

    This read-only property holds whether the two-finger rotation gesture is active.

    \since Qt Location 5.9
*/

/*!
    \qmlproperty bool QtLocation::MapGestureArea::tiltActive

    This read-only property holds whether the two-finger tilt gesture is active.

    \since Qt Location 5.9
*/

/*!
    \qmlproperty real QtLocation::MapGestureArea::maximumZoomLevelChange

    This property holds the maximum zoom level change per pinch, essentially
    meant to be used for setting the zoom sensitivity.

    It is an indicative measure calculated from the dimensions of the
    map area, roughly corresponding how much zoom level could change with
    maximum pinch zoom. Default value is 4.0, maximum value is 10.0
*/

/*!
    \qmlproperty real MapGestureArea::flickDeceleration

    This property holds the rate at which a flick will decelerate.

    The default value is 2500.
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::pinchStarted(PinchEvent event)

    This signal is emitted when a pinch gesture is started.

    The corresponding handler is \c onPinchStarted.

    \sa pinchUpdated, pinchFinished
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::pinchUpdated(PinchEvent event)

    This signal is emitted as the user's fingers move across the map,
    after the \l pinchStarted signal is emitted.

    The corresponding handler is \c onPinchUpdated.

    \sa pinchStarted, pinchFinished
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::pinchFinished(PinchEvent event)

    This signal is emitted at the end of a pinch gesture.

    The corresponding handler is \c onPinchFinished.

    \sa pinchStarted, pinchUpdated
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::panStarted()

    This signal is emitted when the map begins to move due to user
    interaction. Typically this means that the user is dragging a finger -
    or a mouse with one of more mouse buttons pressed - on the map.

    The corresponding handler is \c onPanStarted.
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::panFinished()

    This signal is emitted when the map stops moving due to user
    interaction.  If a flick was generated, this signal is
    emitted before flick starts. If a flick was not
    generated, this signal is emitted when the
    user stops dragging - that is a mouse or touch release.

    The corresponding handler is \c onPanFinished.

*/

/*!
    \qmlsignal QtLocation::MapGestureArea::flickStarted()

    This signal is emitted when the map is flicked.  A flick
    starts from the point where the mouse or touch was released,
    while still in motion.

    The corresponding handler is \c onFlichStarted.
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::flickFinished()

    This signal is emitted when the map stops moving due to a flick.

    The corresponding handler is \c onFlickFinished.
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::rotationStarted(PinchEvent event)

    This signal is emitted when a two-finger rotation gesture is started.

    The corresponding handler is \c onRotationStarted.

    \sa rotationUpdated, rotationFinished

    \since Qt Location 5.9
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::rotationUpdated(PinchEvent event)

    This signal is emitted as the user's fingers move across the map,
    after the \l rotationStarted signal is emitted.

    The corresponding handler is \c onRotationUpdated.

    \sa rotationStarted, rotationFinished

    \since Qt Location 5.9
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::rotationFinished(PinchEvent event)

    This signal is emitted at the end of a two-finger rotation gesture.

    The corresponding handler is \c onRotationFinished.

    \sa rotationStarted, rotationUpdated

    \since Qt Location 5.9
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::tiltStarted(PinchEvent event)

    This signal is emitted when a two-finger tilt gesture is started.

    The corresponding handler is \c onTiltStarted.

    \sa tiltUpdated, tiltFinished

    \since Qt Location 5.9
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::tiltUpdated(PinchEvent event)

    This signal is emitted as the user's fingers move across the map,
    after the \l tiltStarted signal is emitted.

    The corresponding handler is \c onTiltUpdated.

    \sa tiltStarted, tiltFinished

    \since Qt Location 5.9
*/

/*!
    \qmlsignal QtLocation::MapGestureArea::tiltFinished(PinchEvent event)

    This signal is emitted at the end of a two-finger tilt gesture.

    The corresponding handler is \c onTiltFinished.

    \sa tiltStarted, tiltUpdated

    \since Qt Location 5.9
*/

QQuickGeoMapGestureArea::QQuickGeoMapGestureArea(QDeclarativeGeoMap *map)
    : QQuickItem(map),
      m_map(0),
      m_declarativeMap(map),
      m_enabled(true),
      m_acceptedGestures(PinchGesture | PanGesture | FlickGesture | RotationGesture | TiltGesture),
      m_preventStealing(false)
{
    m_touchPointState = touchPoints0;
    m_pinchState = pinchInactive;
    m_flickState = flickInactive;
    m_rotationState = rotationInactive;
    m_tiltState = tiltInactive;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::setMap(QGeoMap *map)
{
    if (m_map || !map)
        return;

    m_map = map;
    m_flick.m_animation = new QQuickGeoCoordinateAnimation(this);
    m_flick.m_animation->setTargetObject(m_declarativeMap);
    m_flick.m_animation->setProperty(QStringLiteral("center"));
    m_flick.m_animation->setEasing(QEasingCurve(QEasingCurve::OutQuad));
    connect(m_flick.m_animation, &QQuickAbstractAnimation::stopped, this, &QQuickGeoMapGestureArea::handleFlickAnimationStopped);
}

/*!
    \qmlproperty bool QtQuick::MapGestureArea::preventStealing
    This property holds whether the mouse events may be stolen from this
    MapGestureArea.

    If a Map is placed within an item that filters child mouse
    and touch events, such as Flickable, the mouse and touch events
    may be stolen from the MapGestureArea if a gesture is recognized
    by the parent item, e.g. a flick gesture.  If preventStealing is
    set to true, no item will steal the mouse and touch events.

    Note that setting preventStealing to true once an item has started
    stealing events will have no effect until the next press event.

    By default this property is false.
*/

bool QQuickGeoMapGestureArea::preventStealing() const
{
    return m_preventStealing;
}

void QQuickGeoMapGestureArea::setPreventStealing(bool prevent)
{
    if (prevent != m_preventStealing) {
        m_preventStealing = prevent;
        m_declarativeMap->setKeepMouseGrab(m_preventStealing && m_enabled);
        m_declarativeMap->setKeepTouchGrab(m_preventStealing && m_enabled);
        emit preventStealingChanged();
    }
}

QQuickGeoMapGestureArea::~QQuickGeoMapGestureArea()
{
}

/*!
    \qmlproperty enumeration QtLocation::MapGestureArea::acceptedGestures

    This property holds the gestures that will be active. By default
    the zoom, pan and flick gestures are enabled.

    \list
    \li MapGestureArea.NoGesture - Don't support any additional gestures (value: 0x0000).
    \li MapGestureArea.PinchGesture - Support the map pinch gesture (value: 0x0001).
    \li MapGestureArea.PanGesture  - Support the map pan gesture (value: 0x0002).
    \li MapGestureArea.FlickGesture  - Support the map flick gesture (value: 0x0004).
    \li MapGestureArea.RotationGesture  - Support the map rotation gesture (value: 0x0008).
    \li MapGestureArea.TiltGesture  - Support the map tilt gesture (value: 0x0010).
    \endlist
*/

QQuickGeoMapGestureArea::AcceptedGestures QQuickGeoMapGestureArea::acceptedGestures() const
{
    return m_acceptedGestures;
}


void QQuickGeoMapGestureArea::setAcceptedGestures(AcceptedGestures acceptedGestures)
{
    if (acceptedGestures == m_acceptedGestures)
        return;
    m_acceptedGestures = acceptedGestures;

    if (enabled()) {
        setPanEnabled(acceptedGestures & PanGesture);
        setFlickEnabled(acceptedGestures & FlickGesture);
        setPinchEnabled(acceptedGestures & PinchGesture);
        setRotationEnabled(acceptedGestures & RotationGesture);
        setTiltEnabled(acceptedGestures & TiltGesture);
    }

    emit acceptedGesturesChanged();
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::isPinchActive() const
{
    return m_pinchState == pinchActive;
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::isRotationActive() const
{
    return m_rotationState == rotationActive;
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::isTiltActive() const
{
    return m_tiltState == tiltActive;
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::isPanActive() const
{
    return m_flickState == panActive || m_flickState == flickActive;
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::enabled() const
{
    return m_enabled;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::setEnabled(bool enabled)
{
    if (enabled == m_enabled)
        return;
    m_enabled = enabled;

    if (enabled) {
        setPanEnabled(m_acceptedGestures & PanGesture);
        setFlickEnabled(m_acceptedGestures & FlickGesture);
        setPinchEnabled(m_acceptedGestures & PinchGesture);
        setRotationEnabled(m_acceptedGestures & RotationGesture);
        setTiltEnabled(m_acceptedGestures & TiltGesture);
    } else {
        setPanEnabled(false);
        setFlickEnabled(false);
        setPinchEnabled(false);
        setRotationEnabled(false);
        setTiltEnabled(false);
    }

    emit enabledChanged();
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::pinchEnabled() const
{
    return m_pinch.m_pinchEnabled;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::setPinchEnabled(bool enabled)
{
    m_pinch.m_pinchEnabled = enabled;
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::rotationEnabled() const
{
    return m_pinch.m_rotationEnabled;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::setRotationEnabled(bool enabled)
{
    m_pinch.m_rotationEnabled = enabled;
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::tiltEnabled() const
{
    return m_pinch.m_tiltEnabled;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::setTiltEnabled(bool enabled)
{
    m_pinch.m_tiltEnabled = enabled;
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::panEnabled() const
{
    return m_flick.m_panEnabled;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::setPanEnabled(bool enabled)
{
    if (enabled == m_flick.m_panEnabled)
        return;
    m_flick.m_panEnabled = enabled;

    // unlike the pinch, the pan existing functionality is to stop immediately
    if (!enabled) {
        stopPan();
        m_flickState = flickInactive;
    }
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::flickEnabled() const
{
    return m_flick.m_flickEnabled;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::setFlickEnabled(bool enabled)
{
    if (enabled == m_flick.m_flickEnabled)
        return;
    m_flick.m_flickEnabled = enabled;
    // unlike the pinch, the flick existing functionality is to stop immediately
    if (!enabled) {
        bool stateActive = (m_flickState != flickInactive);
        stopFlick();
        if (stateActive) {
            if (m_flick.m_panEnabled)
                m_flickState = panActive;
            else
                m_flickState = flickInactive;
        }
    }
}

/*!
    \internal
    Used internally to set the minimum zoom level of the gesture area.
    The caller is responsible to only send values that are valid
    for the map plugin. Negative values are ignored.
 */
void QQuickGeoMapGestureArea::setMinimumZoomLevel(qreal min)
{
    // TODO: remove m_zoom.m_minimum and m_maximum and use m_declarativeMap directly instead.
    if (min >= 0)
        m_pinch.m_zoom.m_minimum = min;
}

/*!
   \internal
 */
qreal QQuickGeoMapGestureArea::minimumZoomLevel() const
{
    return m_pinch.m_zoom.m_minimum;
}

/*!
    \internal
    Used internally to set the maximum zoom level of the gesture area.
    The caller is responsible to only send values that are valid
    for the map plugin. Negative values are ignored.
 */
void QQuickGeoMapGestureArea::setMaximumZoomLevel(qreal max)
{
    if (max >= 0)
        m_pinch.m_zoom.m_maximum = max;
}

/*!
   \internal
 */
qreal QQuickGeoMapGestureArea::maximumZoomLevel() const
{
    return m_pinch.m_zoom.m_maximum;
}

/*!
    \internal
*/
qreal QQuickGeoMapGestureArea::maximumZoomLevelChange() const
{
    return m_pinch.m_zoom.maximumChange;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::setMaximumZoomLevelChange(qreal maxChange)
{
    if (maxChange == m_pinch.m_zoom.maximumChange || maxChange < 0.1 || maxChange > 10.0)
        return;
    m_pinch.m_zoom.maximumChange = maxChange;
    emit maximumZoomLevelChangeChanged();
}

/*!
    \internal
*/
qreal QQuickGeoMapGestureArea::flickDeceleration() const
{
    return m_flick.m_deceleration;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::setFlickDeceleration(qreal deceleration)
{
    if (deceleration < QML_MAP_FLICK_MINIMUMDECELERATION)
        deceleration = QML_MAP_FLICK_MINIMUMDECELERATION;
    else if (deceleration > QML_MAP_FLICK_MAXIMUMDECELERATION)
        deceleration = QML_MAP_FLICK_MAXIMUMDECELERATION;
    if (deceleration == m_flick.m_deceleration)
        return;
    m_flick.m_deceleration = deceleration;
    emit flickDecelerationChanged();
}

/*!
    \internal
*/
QTouchEvent::TouchPoint* createTouchPointFromMouseEvent(QMouseEvent *event, Qt::TouchPointState state)
{
    // this is only partially filled. But since it is only partially used it works
    // more robust would be to store a list of QPointFs rather than TouchPoints
    QTouchEvent::TouchPoint* newPoint = new QTouchEvent::TouchPoint();
    newPoint->setPos(event->localPos());
    newPoint->setScenePos(event->windowPos());
    newPoint->setScreenPos(event->screenPos());
    newPoint->setState(state);
    newPoint->setId(0);
    return newPoint;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::handleMousePressEvent(QMouseEvent *event)
{
    m_mousePoint.reset(createTouchPointFromMouseEvent(event, Qt::TouchPointPressed));
    if (m_touchPoints.isEmpty()) update();
    event->accept();
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::handleMouseMoveEvent(QMouseEvent *event)
{
    m_mousePoint.reset(createTouchPointFromMouseEvent(event, Qt::TouchPointMoved));
    if (m_touchPoints.isEmpty()) update();
    event->accept();
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::handleMouseReleaseEvent(QMouseEvent *event)
{
    if (!m_mousePoint.isNull()) {
        //this looks super ugly , however is required in case we do not get synthesized MouseReleaseEvent
        //and we reset the point already in handleTouchUngrabEvent
        m_mousePoint.reset(createTouchPointFromMouseEvent(event, Qt::TouchPointReleased));
        if (m_touchPoints.isEmpty()) update();
    }
    event->accept();
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::handleMouseUngrabEvent()
{

    if (m_touchPoints.isEmpty() && !m_mousePoint.isNull()) {
        m_mousePoint.reset();
        update();
    } else {
        m_mousePoint.reset();
    }
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::handleTouchUngrabEvent()
{
        m_touchPoints.clear();
        //this is needed since in some cases mouse release is not delivered
        //(second touch point breaks mouse synthesized events)
        m_mousePoint.reset();
        update();
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::handleTouchEvent(QTouchEvent *event)
{
    m_touchPoints.clear();
    m_mousePoint.reset();

    for (int i = 0; i < event->touchPoints().count(); ++i) {
        auto point = event->touchPoints().at(i);
        if (point.state() != Qt::TouchPointReleased)
            m_touchPoints << point;
    }
    if (event->touchPoints().count() >= 2)
        event->accept();
    else
        event->ignore();
    update();
}

#if QT_CONFIG(wheelevent)
void QQuickGeoMapGestureArea::handleWheelEvent(QWheelEvent *event)
{
    if (!m_map)
        return;

    const QGeoCoordinate &wheelGeoPos = m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(event->posF()), false);
    const QPointF &preZoomPoint = event->posF();

    // Not using AltModifier as, for some reason, it causes angleDelta to be 0
    if (event->modifiers() & Qt::ShiftModifier && rotationEnabled()) {
        // First set bearing
        const double bearingDelta = event->angleDelta().y() * qreal(0.05);
        m_declarativeMap->setBearing(m_declarativeMap->bearing() + bearingDelta);
        // then reanchor
        m_declarativeMap->setCenter(m_map->geoProjection().anchorCoordinateToPoint(wheelGeoPos, preZoomPoint));
    } else if (event->modifiers() & Qt::ControlModifier && tiltEnabled()) {
        const double tiltDelta = event->angleDelta().y() * qreal(0.05);
        m_declarativeMap->setTilt(m_declarativeMap->tilt() + tiltDelta);
    } else if (pinchEnabled()) {
        const double zoomLevelDelta = event->angleDelta().y() * qreal(0.001);
        // Gesture area should always honor maxZL, but Map might not.
        m_declarativeMap->setZoomLevel(qMin<qreal>(m_declarativeMap->zoomLevel() + zoomLevelDelta, maximumZoomLevel()),
                                       false);
        const QPointF &postZoomPoint = m_map->geoProjection().coordinateToItemPosition(wheelGeoPos, false).toPointF();

        if (preZoomPoint != postZoomPoint) // need to re-anchor the wheel geoPos to the event position
              m_declarativeMap->setCenter(m_map->geoProjection().anchorCoordinateToPoint(wheelGeoPos, preZoomPoint));
    }
    event->accept();
}
#endif

/*!
    \internal
*/
void QQuickGeoMapGestureArea::clearTouchData()
{
    m_flickVector = QVector2D();
    m_touchPointsCentroid.setX(0);
    m_touchPointsCentroid.setY(0);
    m_touchCenterCoord.setLongitude(0);
    m_touchCenterCoord.setLatitude(0);
    m_startCoord.setLongitude(0);
    m_startCoord.setLatitude(0);
}


/*!
    \internal
*/
void QQuickGeoMapGestureArea::updateFlickParameters(const QPointF &pos)
{
    // Take velocity samples every sufficient period of time, used later to determine the flick
    // duration and speed (when mouse is released).
    qreal elapsed = qreal(m_lastPosTime.elapsed());

    if (elapsed >= QML_MAP_FLICK_VELOCITY_SAMPLE_PERIOD) {
        elapsed /= 1000.;
        qreal vel  = distanceBetweenTouchPoints(pos, m_lastPos) / elapsed;
        m_flickVector = (QVector2D(pos) - QVector2D(m_lastPos)).normalized();
        m_flickVector *= qBound<qreal>(-m_flick.m_maxVelocity, vel, m_flick.m_maxVelocity);

        m_lastPos = pos;
        m_lastPosTime.restart();
    }
}

void QQuickGeoMapGestureArea::setTouchPointState(const QQuickGeoMapGestureArea::TouchPointState state)
{
    m_touchPointState = state;
}

void QQuickGeoMapGestureArea::setFlickState(const QQuickGeoMapGestureArea::FlickState state)
{
    m_flickState = state;
}

void QQuickGeoMapGestureArea::setTiltState(const QQuickGeoMapGestureArea::TiltState state)
{
    m_tiltState = state;
}

void QQuickGeoMapGestureArea::setRotationState(const QQuickGeoMapGestureArea::RotationState state)
{
    m_rotationState = state;
}

void QQuickGeoMapGestureArea::setPinchState(const QQuickGeoMapGestureArea::PinchState state)
{
    m_pinchState = state;
}

/*!
    \internal
*/

bool QQuickGeoMapGestureArea::isActive() const
{
    return isPanActive() || isPinchActive() || isRotationActive() || isTiltActive();
}

/*!
    \internal
*/
// simplify the gestures by using a state-machine format (easy to move to a future state machine)
void QQuickGeoMapGestureArea::update()
{
    if (!m_map)
        return;
    // First state machine is for the number of touch points

    //combine touch with mouse event
    m_allPoints.clear();
    m_allPoints << m_touchPoints;
    if (m_allPoints.isEmpty() && !m_mousePoint.isNull())
        m_allPoints << *m_mousePoint.data();

    touchPointStateMachine();

    // Parallel state machine for tilt. Tilt goes first as it blocks anything else, when started.
    // But tilting can also only start if nothing else is active.
    if (isTiltActive() || m_pinch.m_tiltEnabled)
        tiltStateMachine();

    // Parallel state machine for pinch
    if (isPinchActive() || m_pinch.m_pinchEnabled)
        pinchStateMachine();

    // Parallel state machine for rotation.
    if (isRotationActive() || m_pinch.m_rotationEnabled)
        rotationStateMachine();

    // Parallel state machine for pan (since you can pan at the same time as pinching)
    // The stopPan function ensures that pan stops immediately when disabled,
    // but the isPanActive() below allows pan continue its current gesture if you disable
    // the whole gesture.
    // Pan goes last because it does reanchoring in updatePan()  which makes the map
    // properly rotate around the touch point centroid.
    if (isPanActive() || m_flick.m_flickEnabled || m_flick.m_panEnabled)
        panStateMachine();
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::touchPointStateMachine()
{
    // Transitions:
    switch (m_touchPointState) {
    case touchPoints0:
        if (m_allPoints.count() == 1) {
            clearTouchData();
            startOneTouchPoint();
            setTouchPointState(touchPoints1);
        } else if (m_allPoints.count() >= 2) {
            clearTouchData();
            startTwoTouchPoints();
            setTouchPointState(touchPoints2);
        }
        break;
    case touchPoints1:
        if (m_allPoints.count() == 0) {
            setTouchPointState(touchPoints0);
        } else if (m_allPoints.count() == 2) {
            m_touchCenterCoord = m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(m_touchPointsCentroid), false);
            startTwoTouchPoints();
            setTouchPointState(touchPoints2);
        }
        break;
    case touchPoints2:
        if (m_allPoints.count() == 0) {
            setTouchPointState(touchPoints0);
        } else if (m_allPoints.count() == 1) {
            m_touchCenterCoord = m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(m_touchPointsCentroid), false);
            startOneTouchPoint();
            setTouchPointState(touchPoints1);
        }
        break;
    };

    // Update
    switch (m_touchPointState) {
    case touchPoints0:
        break; // do nothing if no touch points down
    case touchPoints1:
        updateOneTouchPoint();
        break;
    case touchPoints2:
        updateTwoTouchPoints();
        break;
    }
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::startOneTouchPoint()
{
    m_sceneStartPoint1 = mapFromScene(m_allPoints.at(0).scenePos());
    m_lastPos = m_sceneStartPoint1;
    m_lastPosTime.start();
    QGeoCoordinate startCoord = m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(m_sceneStartPoint1), false);
    // ensures a smooth transition for panning
    m_startCoord.setLongitude(m_startCoord.longitude() + startCoord.longitude() -
                             m_touchCenterCoord.longitude());
    m_startCoord.setLatitude(m_startCoord.latitude() + startCoord.latitude() -
                            m_touchCenterCoord.latitude());
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::updateOneTouchPoint()
{
    m_touchPointsCentroid = mapFromScene(m_allPoints.at(0).scenePos());
    updateFlickParameters(m_touchPointsCentroid);
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::startTwoTouchPoints()
{
    m_sceneStartPoint1 = mapFromScene(m_allPoints.at(0).scenePos());
    m_sceneStartPoint2 = mapFromScene(m_allPoints.at(1).scenePos());
    QPointF startPos = (m_sceneStartPoint1 + m_sceneStartPoint2) * 0.5;
    m_lastPos = startPos;
    m_lastPosTime.start();
    QGeoCoordinate startCoord = m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(startPos), false);
    m_startCoord.setLongitude(m_startCoord.longitude() + startCoord.longitude() -
                             m_touchCenterCoord.longitude());
    m_startCoord.setLatitude(m_startCoord.latitude() + startCoord.latitude() -
                            m_touchCenterCoord.latitude());
    m_twoTouchAngleStart = touchAngle(m_sceneStartPoint1, m_sceneStartPoint2); // Initial angle used for calculating rotation
    m_distanceBetweenTouchPointsStart = distanceBetweenTouchPoints(m_sceneStartPoint1, m_sceneStartPoint2);
    m_twoTouchPointsCentroidStart = (m_sceneStartPoint1 + m_sceneStartPoint2) / 2;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::updateTwoTouchPoints()
{
    QPointF p1 = mapFromScene(m_allPoints.at(0).scenePos());
    QPointF p2 = mapFromScene(m_allPoints.at(1).scenePos());
    m_distanceBetweenTouchPoints = distanceBetweenTouchPoints(p1, p2);
    m_touchPointsCentroid = (p1 + p2) / 2;
    updateFlickParameters(m_touchPointsCentroid);

    m_twoTouchAngle = touchAngle(p1, p2);
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::tiltStateMachine()
{
    TiltState lastState = m_tiltState;
    // Transitions:
    switch (m_tiltState) {
    case tiltInactive:
        if (m_allPoints.count() >= 2) {
            if (!isRotationActive() && !isPinchActive() && canStartTilt()) { // only gesture that can be overridden: pan/flick
                m_declarativeMap->setKeepMouseGrab(true);
                m_declarativeMap->setKeepTouchGrab(true);
                startTilt();
                setTiltState(tiltActive);
            } else {
                setTiltState(tiltInactiveTwoPoints);
            }
        }
        break;
    case tiltInactiveTwoPoints:
        if (m_allPoints.count() <= 1) {
            setTiltState(tiltInactive);
        } else {
            if (!isRotationActive() && !isPinchActive() && canStartTilt()) { // only gesture that can be overridden: pan/flick
                m_declarativeMap->setKeepMouseGrab(true);
                m_declarativeMap->setKeepTouchGrab(true);
                startTilt();
                setTiltState(tiltActive);
            }
        }
        break;
    case tiltActive:
        if (m_allPoints.count() <= 1) {
            setTiltState(tiltInactive);
            m_declarativeMap->setKeepMouseGrab(m_preventStealing);
            m_declarativeMap->setKeepTouchGrab(m_preventStealing);
            endTilt();
        }
        break;
    }
    // This line implements an exclusive state machine, where the transitions and updates don't
    // happen on the same frame
    if (m_tiltState != lastState) {
        emit tiltActiveChanged();
        return;
    }

    // Update
    switch (m_tiltState) {
    case tiltInactive:
    case tiltInactiveTwoPoints:
        break; // do nothing
    case tiltActive:
        updateTilt();
        break;
    }
}

bool validateTouchAngleForTilting(const qreal angle)
{
    return ((qAbs(angle) - 180.0) < MaximumParallelPosition) || (qAbs(angle) < MaximumParallelPosition);
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::canStartTilt()
{
    if (m_allPoints.count() >= 2) {
        QPointF p1 = mapFromScene(m_allPoints.at(0).scenePos());
        QPointF p2 = mapFromScene(m_allPoints.at(1).scenePos());
        if (validateTouchAngleForTilting(m_twoTouchAngle)
                && movingParallelVertical(m_sceneStartPoint1, p1, m_sceneStartPoint2, p2)
                && qAbs(m_twoTouchPointsCentroidStart.y() - m_touchPointsCentroid.y()) > MinimumPanToTiltDelta) {
            m_pinch.m_event.setCenter(mapFromScene(m_touchPointsCentroid));
            m_pinch.m_event.setAngle(m_twoTouchAngle);
            m_pinch.m_event.setPoint1(p1);
            m_pinch.m_event.setPoint2(p2);
            m_pinch.m_event.setPointCount(m_allPoints.count());
            m_pinch.m_event.setAccepted(true);
            emit tiltStarted(&m_pinch.m_event);
            return true;
        }
    }
    return false;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::startTilt()
{
    if (isPanActive()) {
        stopPan();
        setFlickState(flickInactive);
    }

    m_pinch.m_tilt.m_startTouchCentroid = m_touchPointsCentroid;
    m_pinch.m_tilt.m_startTilt = m_declarativeMap->tilt();
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::updateTilt()
{
    // Calculate the new tilt
    qreal verticalDisplacement = (m_touchPointsCentroid - m_pinch.m_tilt.m_startTouchCentroid).y();

    // Approach: 10pixel = 1 degree.
    qreal tilt =  verticalDisplacement / 10.0;
    qreal newTilt = m_pinch.m_tilt.m_startTilt - tilt;
    m_declarativeMap->setTilt(newTilt);

    m_pinch.m_event.setCenter(mapFromScene(m_touchPointsCentroid));
    m_pinch.m_event.setAngle(m_twoTouchAngle);
    m_pinch.m_lastPoint1 = mapFromScene(m_allPoints.at(0).scenePos());
    m_pinch.m_lastPoint2 = mapFromScene(m_allPoints.at(1).scenePos());
    m_pinch.m_event.setPoint1(m_pinch.m_lastPoint1);
    m_pinch.m_event.setPoint2(m_pinch.m_lastPoint2);
    m_pinch.m_event.setPointCount(m_allPoints.count());
    m_pinch.m_event.setAccepted(true);

    emit tiltUpdated(&m_pinch.m_event);
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::endTilt()
{
    QPointF p1 = mapFromScene(m_pinch.m_lastPoint1);
    QPointF p2 = mapFromScene(m_pinch.m_lastPoint2);
    m_pinch.m_event.setCenter((p1 + p2) / 2);
    m_pinch.m_event.setAngle(m_pinch.m_lastAngle);
    m_pinch.m_event.setPoint1(p1);
    m_pinch.m_event.setPoint2(p2);
    m_pinch.m_event.setAccepted(true);
    m_pinch.m_event.setPointCount(0);
    emit tiltFinished(&m_pinch.m_event);
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::rotationStateMachine()
{
    RotationState lastState = m_rotationState;
    // Transitions:
    switch (m_rotationState) {
    case rotationInactive:
        if (m_allPoints.count() >= 2) {
            if (!isTiltActive() && canStartRotation()) {
                m_declarativeMap->setKeepMouseGrab(true);
                m_declarativeMap->setKeepTouchGrab(true);
                startRotation();
                setRotationState(rotationActive);
            } else {
                setRotationState(rotationInactiveTwoPoints);
            }
        }
        break;
    case rotationInactiveTwoPoints:
        if (m_allPoints.count() <= 1) {
            setRotationState(rotationInactive);
        } else {
            if (!isTiltActive() && canStartRotation()) {
                m_declarativeMap->setKeepMouseGrab(true);
                m_declarativeMap->setKeepTouchGrab(true);
                startRotation();
                setRotationState(rotationActive);
            }
        }
        break;
    case rotationActive:
        if (m_allPoints.count() <= 1) {
            setRotationState(rotationInactive);
            m_declarativeMap->setKeepMouseGrab(m_preventStealing);
            m_declarativeMap->setKeepTouchGrab(m_preventStealing);
            endRotation();
        }
        break;
    }
    // This line implements an exclusive state machine, where the transitions and updates don't
    // happen on the same frame
    if (m_rotationState != lastState) {
        emit rotationActiveChanged();
        return;
    }

    // Update
    switch (m_rotationState) {
    case rotationInactive:
    case rotationInactiveTwoPoints:
        break; // do nothing
    case rotationActive:
        updateRotation();
        break;
    }
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::canStartRotation()
{
    if (m_allPoints.count() >= 2) {
        QPointF p1 = mapFromScene(m_allPoints.at(0).scenePos());
        QPointF p2 = mapFromScene(m_allPoints.at(1).scenePos());
        if (pointDragged(m_sceneStartPoint1, p1) || pointDragged(m_sceneStartPoint2, p2)) {
            qreal delta = angleDelta(m_twoTouchAngleStart, m_twoTouchAngle);
            if (qAbs(delta) < MinimumRotationStartingAngle) {
                return false;
            }
            m_pinch.m_event.setCenter(mapFromScene(m_touchPointsCentroid));
            m_pinch.m_event.setAngle(m_twoTouchAngle);
            m_pinch.m_event.setPoint1(p1);
            m_pinch.m_event.setPoint2(p2);
            m_pinch.m_event.setPointCount(m_allPoints.count());
            m_pinch.m_event.setAccepted(true);
            emit rotationStarted(&m_pinch.m_event);
            return m_pinch.m_event.accepted();
        }
    }
    return false;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::startRotation()
{
    m_pinch.m_rotation.m_startBearing = m_declarativeMap->bearing();
    m_pinch.m_rotation.m_previousTouchAngle = m_twoTouchAngle;
    m_pinch.m_rotation.m_totalAngle = 0.0;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::updateRotation()
{
    // Calculate the new bearing
    qreal angle = angleDelta(m_pinch.m_rotation.m_previousTouchAngle, m_twoTouchAngle);
    if (qAbs(angle) < 0.2) // avoiding too many updates
        return;

    m_pinch.m_rotation.m_previousTouchAngle = m_twoTouchAngle;
    m_pinch.m_rotation.m_totalAngle += angle;
    qreal newBearing = m_pinch.m_rotation.m_startBearing - m_pinch.m_rotation.m_totalAngle;
    m_declarativeMap->setBearing(newBearing);

    m_pinch.m_event.setCenter(mapFromScene(m_touchPointsCentroid));
    m_pinch.m_event.setAngle(m_twoTouchAngle);
    m_pinch.m_lastPoint1 = mapFromScene(m_allPoints.at(0).scenePos());
    m_pinch.m_lastPoint2 = mapFromScene(m_allPoints.at(1).scenePos());
    m_pinch.m_event.setPoint1(m_pinch.m_lastPoint1);
    m_pinch.m_event.setPoint2(m_pinch.m_lastPoint2);
    m_pinch.m_event.setPointCount(m_allPoints.count());
    m_pinch.m_event.setAccepted(true);

    emit rotationUpdated(&m_pinch.m_event);
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::endRotation()
{
    QPointF p1 = mapFromScene(m_pinch.m_lastPoint1);
    QPointF p2 = mapFromScene(m_pinch.m_lastPoint2);
    m_pinch.m_event.setCenter((p1 + p2) / 2);
    m_pinch.m_event.setAngle(m_pinch.m_lastAngle);
    m_pinch.m_event.setPoint1(p1);
    m_pinch.m_event.setPoint2(p2);
    m_pinch.m_event.setAccepted(true);
    m_pinch.m_event.setPointCount(0);
    emit rotationFinished(&m_pinch.m_event);
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::pinchStateMachine()
{
    PinchState lastState = m_pinchState;
    // Transitions:
    switch (m_pinchState) {
    case pinchInactive:
        if (m_allPoints.count() >= 2) {
            if (!isTiltActive() && canStartPinch()) {
                m_declarativeMap->setKeepMouseGrab(true);
                m_declarativeMap->setKeepTouchGrab(true);
                startPinch();
                setPinchState(pinchActive);
            } else {
                setPinchState(pinchInactiveTwoPoints);
            }
        }
        break;
    case pinchInactiveTwoPoints:
        if (m_allPoints.count() <= 1) {
            setPinchState(pinchInactive);
        } else {
            if (!isTiltActive() && canStartPinch()) {
                m_declarativeMap->setKeepMouseGrab(true);
                m_declarativeMap->setKeepTouchGrab(true);
                startPinch();
                setPinchState(pinchActive);
            }
        }
        break;
    case pinchActive:
        if (m_allPoints.count() <= 1) { // Once started, pinch goes off only when finger(s) are release
            setPinchState(pinchInactive);
            m_declarativeMap->setKeepMouseGrab(m_preventStealing);
            m_declarativeMap->setKeepTouchGrab(m_preventStealing);
            endPinch();
        }
        break;
    }
    // This line implements an exclusive state machine, where the transitions and updates don't
    // happen on the same frame
    if (m_pinchState != lastState) {
        emit pinchActiveChanged();
        return;
    }

    // Update
    switch (m_pinchState) {
    case pinchInactive:
    case pinchInactiveTwoPoints:
        break; // do nothing
    case pinchActive:
        updatePinch();
        break;
    }
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::canStartPinch()
{
    if (m_allPoints.count() >= 2) {
        QPointF p1 = mapFromScene(m_allPoints.at(0).scenePos());
        QPointF p2 = mapFromScene(m_allPoints.at(1).scenePos());
        if (qAbs(m_distanceBetweenTouchPoints - m_distanceBetweenTouchPointsStart) > MinimumPinchDelta) {
            m_pinch.m_event.setCenter(mapFromScene(m_touchPointsCentroid));
            m_pinch.m_event.setAngle(m_twoTouchAngle);
            m_pinch.m_event.setPoint1(p1);
            m_pinch.m_event.setPoint2(p2);
            m_pinch.m_event.setPointCount(m_allPoints.count());
            m_pinch.m_event.setAccepted(true);
            emit pinchStarted(&m_pinch.m_event);
            return m_pinch.m_event.accepted();
        }
    }
    return false;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::startPinch()
{
    m_pinch.m_startDist = m_distanceBetweenTouchPoints;
    m_pinch.m_zoom.m_previous = m_declarativeMap->zoomLevel();
    m_pinch.m_lastAngle = m_twoTouchAngle;

    m_pinch.m_lastPoint1 = mapFromScene(m_allPoints.at(0).scenePos());
    m_pinch.m_lastPoint2 = mapFromScene(m_allPoints.at(1).scenePos());

    m_pinch.m_zoom.m_start = m_declarativeMap->zoomLevel();
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::updatePinch()
{
    // Calculate the new zoom level if we have distance ( >= 2 touchpoints), otherwise stick with old.
    qreal newZoomLevel = m_pinch.m_zoom.m_previous;
    if (m_distanceBetweenTouchPoints) {
        newZoomLevel =
                // How much further/closer the current touchpoints are (in pixels) compared to pinch start
                ((m_distanceBetweenTouchPoints - m_pinch.m_startDist)  *
                 //  How much one pixel corresponds in units of zoomlevel (and multiply by above delta)
                 (m_pinch.m_zoom.maximumChange / ((width() + height()) / 2))) +
                // Add to starting zoom level. Sign of (dist-pinchstartdist) takes care of zoom in / out
                m_pinch.m_zoom.m_start;
    }

    m_pinch.m_event.setCenter(mapFromScene(m_touchPointsCentroid));
    m_pinch.m_event.setAngle(m_twoTouchAngle);

    m_pinch.m_lastPoint1 = mapFromScene(m_allPoints.at(0).scenePos());
    m_pinch.m_lastPoint2 = mapFromScene(m_allPoints.at(1).scenePos());
    m_pinch.m_event.setPoint1(m_pinch.m_lastPoint1);
    m_pinch.m_event.setPoint2(m_pinch.m_lastPoint2);
    m_pinch.m_event.setPointCount(m_allPoints.count());
    m_pinch.m_event.setAccepted(true);

    m_pinch.m_lastAngle = m_twoTouchAngle;
    emit pinchUpdated(&m_pinch.m_event);

    if (m_acceptedGestures & PinchGesture) {
        // Take maximum and minimumzoomlevel into account
        qreal perPinchMinimumZoomLevel = qMax(m_pinch.m_zoom.m_start - m_pinch.m_zoom.maximumChange, m_pinch.m_zoom.m_minimum);
        qreal perPinchMaximumZoomLevel = qMin(m_pinch.m_zoom.m_start + m_pinch.m_zoom.maximumChange, m_pinch.m_zoom.m_maximum);
        newZoomLevel = qMin(qMax(perPinchMinimumZoomLevel, newZoomLevel), perPinchMaximumZoomLevel);
        m_declarativeMap->setZoomLevel(qMin<qreal>(newZoomLevel, maximumZoomLevel()), false);
        m_pinch.m_zoom.m_previous = newZoomLevel;
    }
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::endPinch()
{
    QPointF p1 = mapFromScene(m_pinch.m_lastPoint1);
    QPointF p2 = mapFromScene(m_pinch.m_lastPoint2);
    m_pinch.m_event.setCenter((p1 + p2) / 2);
    m_pinch.m_event.setAngle(m_pinch.m_lastAngle);
    m_pinch.m_event.setPoint1(p1);
    m_pinch.m_event.setPoint2(p2);
    m_pinch.m_event.setAccepted(true);
    m_pinch.m_event.setPointCount(0);
    emit pinchFinished(&m_pinch.m_event);
    m_pinch.m_startDist = 0;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::panStateMachine()
{
    FlickState lastState = m_flickState;

    // Transitions
    switch (m_flickState) {
    case flickInactive:
        if (!isTiltActive() && canStartPan()) {
            // Update startCoord_ to ensure smooth start for panning when going over startDragDistance
            QGeoCoordinate newStartCoord = m_map->geoProjection().itemPositionToCoordinate(QDoubleVector2D(m_touchPointsCentroid), false);
            m_startCoord.setLongitude(newStartCoord.longitude());
            m_startCoord.setLatitude(newStartCoord.latitude());
            m_declarativeMap->setKeepMouseGrab(true);
            setFlickState(panActive);
        }
        break;
    case panActive:
        if (m_allPoints.count() == 0) {
            if (!tryStartFlick())
            {
                setFlickState(flickInactive);
                // mark as inactive for use by camera
                if (m_pinchState == pinchInactive && m_rotationState == rotationInactive && m_tiltState == tiltInactive) {
                    m_declarativeMap->setKeepMouseGrab(m_preventStealing);
                    m_map->prefetchData();
                }
                emit panFinished();
            } else {
                setFlickState(flickActive);
                emit panFinished();
                emit flickStarted();
            }
        }
        break;
    case flickActive:
        if (m_allPoints.count() > 0) { // re touched before movement ended
            stopFlick();
            m_declarativeMap->setKeepMouseGrab(true);
            setFlickState(panActive);
        }
        break;
    }

    if (m_flickState != lastState)
        emit panActiveChanged();

    // Update
    switch (m_flickState) {
    case flickInactive: // do nothing
        break;
    case panActive:
        updatePan();
        // this ensures 'panStarted' occurs after the pan has actually started
        if (lastState != panActive)
            emit panStarted();
        break;
    case flickActive:
        break;
    }
}
/*!
    \internal
*/
bool QQuickGeoMapGestureArea::canStartPan()
{
    if (m_allPoints.count() == 0 || (m_acceptedGestures & PanGesture) == 0)
        return false;

    // Check if thresholds for normal panning are met.
    // (normal panning vs flicking: flicking will start from mouse release event).
    const int startDragDistance = qApp->styleHints()->startDragDistance() * 2;
    QPointF p1 = mapFromScene(m_allPoints.at(0).scenePos());
    int dyFromPress = int(p1.y() - m_sceneStartPoint1.y());
    int dxFromPress = int(p1.x() - m_sceneStartPoint1.x());
    if ((qAbs(dyFromPress) >= startDragDistance || qAbs(dxFromPress) >= startDragDistance))
        return true;
    return false;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::updatePan()
{
    QGeoCoordinate animationStartCoordinate = m_map->geoProjection().anchorCoordinateToPoint(m_startCoord, m_touchPointsCentroid);
    m_declarativeMap->setCenter(animationStartCoordinate);
}

/*!
    \internal
*/
bool QQuickGeoMapGestureArea::tryStartFlick()
{
    if ((m_acceptedGestures & FlickGesture) == 0)
        return false;
    // if we drag then pause before release we should not cause a flick.
    qreal flickSpeed = 0.0;
    if (m_lastPosTime.elapsed() < QML_MAP_FLICK_VELOCITY_SAMPLE_PERIOD)
        flickSpeed = m_flickVector.length();

    int flickTime = 0;
    int flickPixels = 0;
    QVector2D flickVector;

    if (qAbs(flickSpeed) > MinimumFlickVelocity
            && distanceBetweenTouchPoints(m_touchPointsCentroid, m_sceneStartPoint1) > FlickThreshold) {
        qreal acceleration = m_flick.m_deceleration;
        if ((flickSpeed > 0.0f) == (m_flick.m_deceleration > 0.0f))
            acceleration = acceleration * -1.0f;
        flickTime = static_cast<int>(-1000 * flickSpeed / acceleration);
        flickPixels = (flickTime * flickSpeed) / 2000.0;
        flickVector = m_flickVector.normalized() * flickPixels;
    }

    if (flickTime > 0) {
        startFlick(flickVector.x(), flickVector.y(), flickTime);
        return true;
    }
    return false;
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::startFlick(int dx, int dy, int timeMs)
{
    if (!m_flick.m_animation)
        return;
    if (timeMs < 0)
        return;

    QGeoCoordinate animationStartCoordinate = m_declarativeMap->center();

    if (m_flick.m_animation->isRunning())
        m_flick.m_animation->stop();
    QGeoCoordinate animationEndCoordinate = m_declarativeMap->center();
    m_flick.m_animation->setDuration(timeMs);

    QPointF delta(dx, dy);
    QMatrix4x4 matBearing;
    matBearing.rotate(m_map->cameraData().bearing(), 0, 0, 1);
    delta = matBearing * delta;

    double zoom = pow(2.0, m_declarativeMap->zoomLevel());
    double longitude = animationStartCoordinate.longitude() - (delta.x() / zoom);
    double latitude = animationStartCoordinate.latitude() + (delta.y() / zoom);

    if (delta.x() > 0)
        m_flick.m_animation->setDirection(QQuickGeoCoordinateAnimation::East);
    else
        m_flick.m_animation->setDirection(QQuickGeoCoordinateAnimation::West);

    //keep animation in correct bounds
    animationEndCoordinate.setLongitude(QLocationUtils::wrapLong(longitude));
    animationEndCoordinate.setLatitude(QLocationUtils::clipLat(latitude, QLocationUtils::mercatorMaxLatitude()));

    m_flick.m_animation->setFrom(animationStartCoordinate);
    m_flick.m_animation->setTo(animationEndCoordinate);
    m_flick.m_animation->start();
}

void QQuickGeoMapGestureArea::stopPan()
{
    if (m_flickState == flickActive) {
        stopFlick();
    } else if (m_flickState == panActive) {
        m_flickVector = QVector2D();
        setFlickState(flickInactive);
        m_declarativeMap->setKeepMouseGrab(m_preventStealing);
        emit panFinished();
        emit panActiveChanged();
        m_map->prefetchData();
    }
}

/*!
    \internal
*/
void QQuickGeoMapGestureArea::stopFlick()
{
    if (!m_flick.m_animation)
        return;
    m_flickVector = QVector2D();
    if (m_flick.m_animation->isRunning())
        m_flick.m_animation->stop();
    else
        handleFlickAnimationStopped();
}

void QQuickGeoMapGestureArea::handleFlickAnimationStopped()
{
    m_declarativeMap->setKeepMouseGrab(m_preventStealing);
    if (m_flickState == flickActive) {
        setFlickState(flickInactive);
        emit flickFinished();
        emit panActiveChanged();
        m_map->prefetchData();
    }
}

QT_END_NAMESPACE