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
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2009-12-01
 * Description : Google-Maps-backend for geolocation interface
 *
 * SPDX-FileCopyrightText: 2010-2025 by Gilles Caulier <caulier dot gilles at gmail dot com>
 * SPDX-FileCopyrightText: 2009-2011 by Michael G. Hansen <mike at mghansen dot de>
 * SPDX-FileCopyrightText: 2014      by Justus Schwartz <justus at gmx dot li>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "backendgooglemaps.h"

// Qt includes

#include <QMenu>
#include <QTimer>
#include <QAction>
#include <QBuffer>
#include <QPointer>
#include <QResizeEvent>
#include <QActionGroup>
#include <QApplication>
#include <QStandardPaths>

// KDE includes

#include <kconfiggroup.h>
#include <klocalizedstring.h>

// Marble includes

#ifdef HAVE_GEOLOCATION

#   include "GeoDataLatLonAltBox.h"

#endif

// Local includes

#include "digikam_config.h"
#include "digikam_debug.h"
#include "mapwidget.h"
#include "abstractmarkertiler.h"
#include "geomodelhelper.h"
#include "htmlwidget_qwebengine.h"

namespace Digikam
{

class Q_DECL_HIDDEN GMInternalWidgetInfo
{
public:

    GMInternalWidgetInfo() = default;

    HTMLWidget* htmlWidget = nullptr;
};

} // namespace Digikam

Q_DECLARE_METATYPE(Digikam::GMInternalWidgetInfo)

namespace Digikam
{

class Q_DECL_HIDDEN BackendGoogleMaps::Private
{
public:

    Private() = default;

public:

    QPointer<HTMLWidget>                      htmlWidget                    = nullptr;
    QPointer<QWidget>                         htmlWidgetWrapper             = nullptr;
    bool                                      isReady                       = false;
    QActionGroup*                             mapTypeActionGroup            = nullptr;
    QActionGroup*                             floatItemsActionGroup         = nullptr;
    QAction*                                  showMapTypeControlAction      = nullptr;
    QAction*                                  showNavigationControlAction   = nullptr;
    QAction*                                  showScaleControlAction        = nullptr;
    QString                                   htmlFileName                  = QLatin1String("backend-googlemaps.html");
    QString                                   cacheMapType                  = QLatin1String("ROADMAP");
    bool                                      cacheShowMapTypeControl       = true;
    bool                                      cacheShowNavigationControl    = true;
    bool                                      cacheShowScaleControl         = true;
    int                                       cacheZoom                     = 8;
    int                                       cacheMaxZoom                  = 0;
    int                                       cacheMinZoom                  = 0;
    GeoCoordinates                            cacheCenter                   = GeoCoordinates(52.0, 6.0);
    QPair<GeoCoordinates, GeoCoordinates>     cacheBounds;
    bool                                      activeState                   = false;
    bool                                      widgetIsDocked                = false;
    QList<TrackManager::TrackChanges>         trackChangeTracker;
};

BackendGoogleMaps::BackendGoogleMaps(const QExplicitlySharedDataPointer<GeoIfaceSharedData>& sharedData,
                                     QObject* const parent)
    : MapBackend(sharedData, parent),
      d         (new Private)
{
    createActions();
}

BackendGoogleMaps::~BackendGoogleMaps()
{
    /// @todo Should we leave our widget in this list and not destroy it?
    ///       Maybe for now this should simply be limited to leaving one
    ///       unused widget in the global cache.

    GeoIfaceGlobalObject* const go = GeoIfaceGlobalObject::instance();
    go->removeMyInternalWidgetFromPool(this);

    if (d->htmlWidgetWrapper)
    {
        delete d->htmlWidgetWrapper;
    }

    delete d;
}

void BackendGoogleMaps::createActions()
{
    // actions for selecting the map type:

    d->mapTypeActionGroup = new QActionGroup(this);
    d->mapTypeActionGroup->setExclusive(true);

    connect(d->mapTypeActionGroup, SIGNAL(triggered(QAction*)),
            this, SLOT(slotMapTypeActionTriggered(QAction*)));

    QStringList mapTypes, mapTypesHumanNames;
    mapTypes
        << QLatin1String("ROADMAP")
        << QLatin1String("SATELLITE")
        << QLatin1String("HYBRID")
        << QLatin1String("TERRAIN");

    mapTypesHumanNames
        << i18n("Roadmap")
        << i18n("Satellite")
        << i18n("Hybrid")
        << i18n("Terrain");

    for (int i = 0 ; i < mapTypes.count() ; ++i)
    {
        QAction* const mapTypeAction = new QAction(d->mapTypeActionGroup);
        mapTypeAction->setData(mapTypes.at(i));
        mapTypeAction->setText(mapTypesHumanNames.at(i));
        mapTypeAction->setCheckable(true);
    }

    // float items:

    d->floatItemsActionGroup = new QActionGroup(this);
    d->floatItemsActionGroup->setExclusive(false);

    connect(d->floatItemsActionGroup, SIGNAL(triggered(QAction*)),
            this, SLOT(slotFloatSettingsTriggered(QAction*)));

    d->showMapTypeControlAction = new QAction(i18n("Show Map Type Control"), d->floatItemsActionGroup);
    d->showMapTypeControlAction->setCheckable(true);
    d->showMapTypeControlAction->setChecked(d->cacheShowMapTypeControl);
    d->showMapTypeControlAction->setData(QLatin1String("showmaptypecontrol"));

    d->showNavigationControlAction = new QAction(i18n("Show Navigation Control"), d->floatItemsActionGroup);
    d->showNavigationControlAction->setCheckable(true);
    d->showNavigationControlAction->setChecked(d->cacheShowNavigationControl);
    d->showNavigationControlAction->setData(QLatin1String("shownavigationcontrol"));

    d->showScaleControlAction = new QAction(i18n("Show Scale Control"), d->floatItemsActionGroup);
    d->showScaleControlAction->setCheckable(true);
    d->showScaleControlAction->setChecked(d->cacheShowScaleControl);
    d->showScaleControlAction->setData(QLatin1String("showscalecontrol"));
}

QString BackendGoogleMaps::backendName() const
{
    return QLatin1String("googlemaps");
}

QString BackendGoogleMaps::backendHumanName() const
{
    return i18n("Google Maps");
}

QWidget* BackendGoogleMaps::mapWidget()
{
    if (!d->htmlWidgetWrapper)
    {
        GeoIfaceGlobalObject* const go = GeoIfaceGlobalObject::instance();

        GeoIfaceInternalWidgetInfo info;
        bool foundReusableWidget       = go->getInternalWidgetFromPool(this, &info);

        if (foundReusableWidget)
        {
            d->htmlWidgetWrapper               = info.widget;
            const GMInternalWidgetInfo intInfo = info.backendData.value<GMInternalWidgetInfo>();
            d->htmlWidget                      = intInfo.htmlWidget;
        }
        else
        {
            // the widget has not been created yet, create it now:

            d->htmlWidgetWrapper = new QWidget();
            d->htmlWidgetWrapper->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
            d->htmlWidget        = new HTMLWidget(d->htmlWidgetWrapper);
            d->htmlWidgetWrapper->resize(400, 400);
        }

        connect(d->htmlWidget, SIGNAL(signalJavaScriptReady()),
                this, SLOT(slotHTMLInitialized()));

        connect(d->htmlWidget, SIGNAL(signalHTMLEvents(QStringList)),
                this, SLOT(slotHTMLEvents(QStringList)));

        connect(d->htmlWidget, SIGNAL(signalMessageEvent(QString)),
                this, SLOT(slotMessageEvent(QString)));

        connect(d->htmlWidget, SIGNAL(selectionHasBeenMade(Digikam::GeoCoordinates::Pair)),
                this, SLOT(slotSelectionHasBeenMade(Digikam::GeoCoordinates::Pair)));

        d->htmlWidget->setSharedGeoIfaceObject(s.data());
        d->htmlWidgetWrapper->installEventFilter(this);

        if (foundReusableWidget)
        {
            slotHTMLInitialized();
        }
        else
        {
            reload();
        }
    }

    return d->htmlWidgetWrapper.data();
}

void BackendGoogleMaps::reload()
{
    if (d->htmlWidget)
    {
        const QUrl htmlUrl = GeoIfaceGlobalObject::instance()->locateDataFile(d->htmlFileName);
        d->htmlWidget->load(htmlUrl);
    }
}

GeoCoordinates BackendGoogleMaps::getCenter() const
{
    return d->cacheCenter;
}

void BackendGoogleMaps::setCenter(const GeoCoordinates& coordinate)
{
    d->cacheCenter = coordinate;

    if (isReady())
    {
        QTimer::singleShot(0, this, SLOT(slotSetCenterTimer()));
    }
}

void BackendGoogleMaps::slotSetCenterTimer()
{
    d->htmlWidget->runScript(QString::fromLatin1("kgeomapSetCenter(%1, %2);")
                                 .arg(d->cacheCenter.latString())
                                 .arg(d->cacheCenter.lonString()));
}

bool BackendGoogleMaps::isReady() const
{
    return d->isReady;
}

void BackendGoogleMaps::slotHTMLInitialized()
{
    d->isReady     = true;
    d->htmlWidget->runScript(QString::fromLatin1("kgeomapWidgetResized(%1, %2)")
                                 .arg(d->htmlWidgetWrapper->width())
                                 .arg(d->htmlWidgetWrapper->height()));

    // TODO: call javascript directly here and update action availability in one shot

    setMapType(d->cacheMapType);
    setShowScaleControl(d->cacheShowScaleControl);
    setShowMapTypeControl(d->cacheShowMapTypeControl);
    setShowNavigationControl(d->cacheShowNavigationControl);

    Q_EMIT signalBackendReadyChanged(backendName());
}

void BackendGoogleMaps::zoomIn()
{
    if (!d->isReady)
    {
        return;
    }

    d->htmlWidget->runScript(QLatin1String("kgeomapZoomIn();"));
}

void BackendGoogleMaps::zoomOut()
{
    if (!d->isReady)
    {
        return;
    }

    d->htmlWidget->runScript(QLatin1String("kgeomapZoomOut();"));
}

QString BackendGoogleMaps::getMapType() const
{
    return d->cacheMapType;
}

void BackendGoogleMaps::setMapType(const QString& newMapType)
{
    d->cacheMapType = newMapType;
    qCDebug(DIGIKAM_GEOIFACE_LOG) << newMapType;

    if (isReady())
    {
        d->htmlWidget->runScript(QString::fromLatin1("kgeomapSetMapType(\"%1\");").arg(newMapType));
        updateZoomMinMaxCache();
        updateActionAvailability();
    }
}

void BackendGoogleMaps::slotMapTypeActionTriggered(QAction* action)
{
    const QString newMapType = action->data().toString();
    setMapType(newMapType);
}

void BackendGoogleMaps::addActionsToConfigurationMenu(QMenu* const configurationMenu)
{
    GEOIFACE_ASSERT(configurationMenu!=nullptr);

    if (!d->isReady)
    {
        return;
    }

    configurationMenu->addSeparator();

    // map type actions:

    const QList<QAction*> mapTypeActions = d->mapTypeActionGroup->actions();

    for (int i = 0 ; i < mapTypeActions.count() ; ++i)
    {
        QAction* const mapTypeAction = mapTypeActions.at(i);
        configurationMenu->addAction(mapTypeAction);
    }

    configurationMenu->addSeparator();

    // float items visibility:

    QMenu* const floatItemsSubMenu = new QMenu(i18n("Float items"), configurationMenu);
    configurationMenu->addMenu(floatItemsSubMenu);

    floatItemsSubMenu->addAction(d->showMapTypeControlAction);
    floatItemsSubMenu->addAction(d->showNavigationControlAction);
    floatItemsSubMenu->addAction(d->showScaleControlAction);

    configurationMenu->addSeparator();

    addCommonOptions(configurationMenu);

    updateActionAvailability();
}

void BackendGoogleMaps::saveSettingsToGroup(KConfigGroup* const group)
{
    GEOIFACE_ASSERT(group != nullptr);

    if (!group)
    {
        return;
    }

    group->writeEntry("GoogleMaps Map Type",                getMapType());
    group->writeEntry("GoogleMaps Show Scale Control",      d->cacheShowScaleControl);
    group->writeEntry("GoogleMaps Show Map Type Control",   d->cacheShowMapTypeControl);
    group->writeEntry("GoogleMaps Show Navigation Control", d->cacheShowNavigationControl);
}

void BackendGoogleMaps::readSettingsFromGroup(const KConfigGroup* const group)
{
    GEOIFACE_ASSERT(group != nullptr);

    if (!group)
    {
        return;
    }

    setMapType(group->readEntry("GoogleMaps Map Type",                              "ROADMAP"));
    setShowScaleControl(group->readEntry("GoogleMaps Show Scale Control",           true));
    setShowMapTypeControl(group->readEntry("GoogleMaps Show Map Type Control",      true));
    setShowNavigationControl(group->readEntry("GoogleMaps Show Navigation Control", true));
}

void BackendGoogleMaps::slotUngroupedModelChanged(const int mindex)
{
    GEOIFACE_ASSERT(isReady());

    if (!isReady())
    {
        return;
    }

    d->htmlWidget->runScript(QString::fromLatin1("kgeomapClearMarkers(%1);").arg(mindex));

    // this can happen when a model was removed and we are simply asked to remove its markers

    if (mindex >= s->ungroupedModels.count())
    {
        return;
    }

    GeoModelHelper* const modelHelper = s->ungroupedModels.at(mindex);

    if (!modelHelper)
    {
        return;
    }

    if (!modelHelper->modelFlags().testFlag(GeoModelHelper::FlagVisible))
    {
        return;
    }

    QAbstractItemModel* const model = modelHelper->model();

    for (int row = 0 ; row < model->rowCount() ; ++row)
    {
        const QModelIndex currentIndex                = model->index(row, 0);
        const GeoModelHelper::PropertyFlags itemFlags = modelHelper->itemFlags(currentIndex);

        // TODO: this is untested! We need to make sure the indices stay correct inside the JavaScript part!

        if (!itemFlags.testFlag(GeoModelHelper::FlagVisible))
        {
            continue;
        }

        GeoCoordinates currentCoordinates;

        if (!modelHelper->itemCoordinates(currentIndex, &currentCoordinates))
        {
            continue;
        }

        // TODO: use the pixmap supplied by the modelHelper

        d->htmlWidget->runScript(QString::fromLatin1("kgeomapAddMarker(%1, %2, %3, %4, %5, %6);")
                                     .arg(mindex)
                                     .arg(row)
                                     .arg(currentCoordinates.latString())
                                     .arg(currentCoordinates.lonString())
                                     .arg(itemFlags.testFlag(GeoModelHelper::FlagMovable) ? QLatin1String("true")
                                                                                          : QLatin1String("false"))
                                     .arg(itemFlags.testFlag(GeoModelHelper::FlagSnaps) ? QLatin1String("true")
                                                                                        : QLatin1String("false"))
                                );

        QPoint     markerCenterPoint;
        QSize      markerSize;
        QPixmap    markerPixmap;
        QUrl       markerUrl;
        const bool markerHasIcon = modelHelper->itemIcon(currentIndex, &markerCenterPoint,
                                                         &markerSize, &markerPixmap, &markerUrl);

        if (markerHasIcon)
        {
            if (!markerUrl.isEmpty())
            {
                setMarkerPixmap(mindex, row, markerCenterPoint, markerSize, markerUrl);
            }
            else
            {
                setMarkerPixmap(mindex, row, markerCenterPoint, markerPixmap);
            }
        }
    }
}
void BackendGoogleMaps::updateMarkers()
{
    // re-transfer all markers to the javascript-part:

    for (int i = 0 ; i < s->ungroupedModels.count() ; ++i)
    {
        slotUngroupedModelChanged(i);
    }
}

void BackendGoogleMaps::slotHTMLEvents(const QStringList& events)
{
    // for some events, we just note that they appeared and then process them later on:

    bool centerProbablyChanged    = false;
    bool mapTypeChanged           = false;
    bool zoomProbablyChanged      = false;
    bool mapBoundsProbablyChanged = false;
    QIntList movedClusters;
    QList<QPersistentModelIndex> movedMarkers;
    QIntList clickedClusters;

    // TODO: verify that the order of the events is still okay
    //       or that the order does not matter

    for (QStringList::const_iterator it = events.constBegin() ; it != events.constEnd() ; ++it)
    {
        const QString eventCode           = it->left(2);
        const QString eventParameter      = it->mid(2);
        const QStringList eventParameters = eventParameter.split(QLatin1Char('/'));

        if      (eventCode == QLatin1String("MT"))
        {
            // map type changed

            mapTypeChanged  = true;
            d->cacheMapType = eventParameter;
        }
        else if (eventCode == QLatin1String("MB"))
        {
            // NOTE: event currently disabled in javascript part
            // map bounds changed

            centerProbablyChanged    = true;
            zoomProbablyChanged      = true;
            mapBoundsProbablyChanged = true;
        }
        else if (eventCode == QLatin1String("ZC"))
        {
            // NOTE: event currently disabled in javascript part
            // zoom changed

            zoomProbablyChanged      = true;
            mapBoundsProbablyChanged = true;
        }
        else if (eventCode == QLatin1String("id"))
        {
            // idle after drastic map changes

            centerProbablyChanged    = true;
            zoomProbablyChanged      = true;
            mapBoundsProbablyChanged = true;
        }
        else if (eventCode == QLatin1String("cm"))
        {
            /// @todo buffer this event type!
            // cluster moved

            bool okay              = false;
            const int clusterIndex = eventParameter.toInt(&okay);

            GEOIFACE_ASSERT(okay);

            if (!okay)
            {
                continue;
            }

            GEOIFACE_ASSERT(clusterIndex >= 0);
            GEOIFACE_ASSERT(clusterIndex < s->clusterList.size());

            if ((clusterIndex < 0) || (clusterIndex > s->clusterList.size()))
            {
                continue;
            }

            // re-read the marker position:

            GeoCoordinates clusterCoordinates;
            const bool isValid = d->htmlWidget->runScript2Coordinates(
                    QString::fromLatin1("kgeomapGetClusterPosition(%1);").arg(clusterIndex),
                    &clusterCoordinates);

            GEOIFACE_ASSERT(isValid);

            if (!isValid)
            {
                continue;
            }

            /// @todo this discards the altitude!
            /// @todo is this really necessary? clusters should be regenerated anyway...

            s->clusterList[clusterIndex].coordinates = clusterCoordinates;

            movedClusters << clusterIndex;
        }
        else if (eventCode == QLatin1String("cs"))
        {
            /// @todo buffer this event type!
            // cluster snapped

            bool okay              = false;
            const int clusterIndex = eventParameters.first().toInt(&okay);

            GEOIFACE_ASSERT(okay);

            if (!okay)
            {
                continue;
            }

            GEOIFACE_ASSERT(clusterIndex >= 0);
            GEOIFACE_ASSERT(clusterIndex < s->clusterList.size());

            if ((clusterIndex < 0) || (clusterIndex > s->clusterList.size()))
            {
                continue;
            }

            // determine to which marker we snapped:

            okay                  = false;
            const int snapModelId = eventParameters.at(1).toInt(&okay);

            GEOIFACE_ASSERT(okay);

            if (!okay)
            {
                continue;
            }

            okay                   = false;
            const int snapMarkerId = eventParameters.at(2).toInt(&okay);

            GEOIFACE_ASSERT(okay);

            if (!okay)
            {
                continue;
            }

            /// @todo Q_EMIT signal here or later?

            GeoModelHelper* const modelHelper  = s->ungroupedModels.at(snapModelId);<--- Variable 'modelHelper' can be declared as pointer to const
            QAbstractItemModel* const model    = modelHelper->model();
            QPair<int, QModelIndex> snapTargetIndex(snapModelId, model->index(snapMarkerId, 0));

            Q_EMIT signalClustersMoved(QIntList() << clusterIndex, snapTargetIndex);
        }
        else if (eventCode == QLatin1String("cc"))
        {
            /// @todo buffer this event type!
            // cluster clicked

            bool okay              = false;
            const int clusterIndex = eventParameter.toInt(&okay);

            GEOIFACE_ASSERT(okay);

            if (!okay)
            {
                continue;
            }

            GEOIFACE_ASSERT(clusterIndex >= 0);
            GEOIFACE_ASSERT(clusterIndex < s->clusterList.size());

            if ((clusterIndex < 0) || (clusterIndex > s->clusterList.size()))
            {
                continue;
            }

            clickedClusters << clusterIndex;
        }
        else if (eventCode == QLatin1String("mm"))
        {
/*
            // TODO: buffer this event type!
            // marker moved

            bool okay           = false;
            const int markerRow = eventParameter.toInt(&okay);
            GEOIFACE_ASSERT(okay);

            if (!okay)
            {
                continue;
            }

            GEOIFACE_ASSERT(markerRow >= 0);
            GEOIFACE_ASSERT(markerRow<s->specialMarkersModel->rowCount());

            if ((markerRow<0)||(markerRow>=s->specialMarkersModel->rowCount()))
            {
                continue;
            }

            // re-read the marker position:

            GeoCoordinates markerCoordinates;
            const bool isValid = d->htmlWidget->runScript2Coordinates(
                    QString::fromLatin1("kgeomapGetMarkerPosition(%1);").arg(markerRow),
                    &markerCoordinates
                );

            GEOIFACE_ASSERT(isValid);

            if (!isValid)
            {
                continue;
            }

            // TODO: this discards the altitude!

            const QModelIndex markerIndex = s->specialMarkersModel->index(markerRow, 0);
            s->specialMarkersModel->setData(markerIndex, QVariant::fromValue(markerCoordinates), s->specialMarkersCoordinatesRole);

            movedMarkers << QPersistentModelIndex(markerIndex);
*/
        }
        else if (eventCode == QLatin1String("do"))
        {
            // debug output:

            qCDebug(DIGIKAM_GEOIFACE_LOG) << QString::fromLatin1("javascript:%1").arg(eventParameter);
        }
    }

    if (!movedClusters.isEmpty())
    {
        qCDebug(DIGIKAM_GEOIFACE_LOG) << movedClusters;

        Q_EMIT signalClustersMoved(movedClusters, QPair<int, QModelIndex>(-1, QModelIndex()));
    }

    // cppcheck-suppress knownConditionTrueFalse
    if (!movedMarkers.isEmpty())
    {
        qCDebug(DIGIKAM_GEOIFACE_LOG) << movedMarkers;
/*
        Q_EMIT signalSpecialMarkersMoved(movedMarkers);
*/
    }

    if (!clickedClusters.isEmpty())
    {
        Q_EMIT signalClustersClicked(clickedClusters);
    }

    // now process the buffered events:

    if (mapTypeChanged)
    {
        updateZoomMinMaxCache();
    }

    if (zoomProbablyChanged && !mapTypeChanged)
    {
        d->cacheZoom = d->htmlWidget->runScript(QLatin1String("kgeomapGetZoom();"), false).toInt();

        Q_EMIT signalZoomChanged(QString::fromLatin1("googlemaps:%1").arg(d->cacheZoom));
    }

    if (centerProbablyChanged && !mapTypeChanged)
    {
        // there is nothing we can do if the coordinates are invalid
/*
        const bool isValid =
*/
        d->htmlWidget->runScript2Coordinates(QLatin1String("kgeomapGetCenter();"), &(d->cacheCenter));
    }

    // update the actions if necessary:

    if (zoomProbablyChanged || mapTypeChanged || centerProbablyChanged)
    {
        updateActionAvailability();
    }

    if (mapBoundsProbablyChanged)
    {
        const QString mapBoundsString = d->htmlWidget->runScript(QLatin1String("kgeomapGetBounds();"), false).toString();
        const bool isValid            = GeoIfaceHelperParseBoundsString(mapBoundsString, &d->cacheBounds);

        if (!isValid)
        {
            qCDebug(DIGIKAM_GEOIFACE_LOG) << "Invalid map bounds";
        }
    }

    if (mapBoundsProbablyChanged || !movedClusters.isEmpty())
    {
        s->worldMapWidget->markClustersAsDirty();
        s->worldMapWidget->updateClusters();
    }
}

void BackendGoogleMaps::updateClusters()
{
    qCDebug(DIGIKAM_GEOIFACE_LOG) << "start updateclusters";

    // re-transfer the clusters to the map:

    GEOIFACE_ASSERT(isReady());

    if (!isReady())
    {
        return;
    }

    // TODO: only update clusters that have actually changed!

    // re-transfer all markers to the javascript-part:

    const bool canMoveItems = !s->showThumbnails      &&
                              s->modificationsAllowed &&
                              s->markerModel->tilerFlags().testFlag(AbstractMarkerTiler::FlagMovable);

    d->htmlWidget->runScript(QLatin1String("kgeomapClearClusters();"));
    d->htmlWidget->runScript(QString::fromLatin1("kgeomapSetIsInEditMode(%1);")
                                 .arg(s->showThumbnails ? QLatin1String("false")
                                                        : QLatin1String("true"))
                            );

    for (int currentIndex = 0 ; currentIndex < s->clusterList.size() ; ++currentIndex)
    {
        const GeoIfaceCluster& currentCluster = s->clusterList.at(currentIndex);

        d->htmlWidget->runScript(QString::fromLatin1("kgeomapAddCluster(%1, %2, %3, %4, %5, %6);")
                                     .arg(currentIndex)
                                     .arg(currentCluster.coordinates.latString())
                                     .arg(currentCluster.coordinates.lonString())
                                     .arg(canMoveItems ? QLatin1String("true")
                                                       : QLatin1String("false"))
                                     .arg(currentCluster.markerCount)
                                     .arg(currentCluster.markerSelectedCount)
                                );

        // TODO: for now, only set generated pixmaps when not in edit mode
        // this can be changed once we figure out how to appropriately handle
        // the selection state changes when a marker is dragged

        if (s->showThumbnails)
        {
            QPoint clusterCenterPoint;

            // TODO: who calculates the override values?

            const QPixmap clusterPixmap = s->worldMapWidget->getDecoratedPixmapForCluster(currentIndex, nullptr, nullptr, &clusterCenterPoint);

            setClusterPixmap(currentIndex, clusterCenterPoint, clusterPixmap);
        }
    }

    qCDebug(DIGIKAM_GEOIFACE_LOG) << "end updateclusters";
}

bool BackendGoogleMaps::screenCoordinates(const GeoCoordinates& coordinates, QPoint* const point)
{
    if (!d->isReady)
    {
        return false;
    }

    const QString pointStringResult = d->htmlWidget->runScript(
                QString::fromLatin1("kgeomapLatLngToPixel(%1, %2);")
                    .arg(coordinates.latString())
                    .arg(coordinates.lonString()),
                false).toString();

    const bool isValid              = GeoIfaceHelperParseXYStringToPoint(pointStringResult, point);

    // TODO: apparently, even points outside the visible area are returned as valid
    // check whether they are actually visible

    return isValid;
}

bool BackendGoogleMaps::geoCoordinates(const QPoint& point, GeoCoordinates* const coordinates) const
{
    if (!d->isReady)
    {
        return false;
    }

    const bool isValid = d->htmlWidget->runScript2Coordinates(
        QString::fromLatin1("kgeomapPixelToLatLng(%1, %2);")
            .arg(point.x())
            .arg(point.y()),
            coordinates);

    return isValid;
}

QSize BackendGoogleMaps::mapSize() const
{
    GEOIFACE_ASSERT(d->htmlWidgetWrapper != nullptr);

    return d->htmlWidgetWrapper->size();
}

void BackendGoogleMaps::slotFloatSettingsTriggered(QAction* action)
{
    const QString actionIdString = action->data().toString();
    const bool actionState       = action->isChecked();

    if      (actionIdString == QLatin1String("showmaptypecontrol"))
    {
        setShowMapTypeControl(actionState);
    }
    else if (actionIdString == QLatin1String("shownavigationcontrol"))
    {
        setShowNavigationControl(actionState);
    }
    else if (actionIdString == QLatin1String("showscalecontrol"))
    {
        setShowScaleControl(actionState);
    }
}

void BackendGoogleMaps::setShowScaleControl(const bool state)
{
    d->cacheShowScaleControl = state;

    if (d->showScaleControlAction)
    {
        d->showScaleControlAction->setChecked(state);
    }

    if (!isReady())
    {
        return;
    }

    d->htmlWidget->runScript(QString::fromLatin1("kgeomapSetShowScaleControl(%1);")
                                 .arg(state ? QLatin1String("true")
                                            : QLatin1String("false"))
                            );
}

void BackendGoogleMaps::setShowNavigationControl(const bool state)
{
    d->cacheShowNavigationControl = state;

    if (d->showNavigationControlAction)
    {
        d->showNavigationControlAction->setChecked(state);
    }

    if (!isReady())
    {
        return;
    }

    d->htmlWidget->runScript(
                             QString::fromLatin1("kgeomapSetShowNavigationControl(%1);")
                                 .arg(state ? QLatin1String("true")
                                            : QLatin1String("false"))
                            );
}

void BackendGoogleMaps::setShowMapTypeControl(const bool state)
{
    d->cacheShowMapTypeControl = state;

    if (d->showMapTypeControlAction)
    {
        d->showMapTypeControlAction->setChecked(state);
    }

    if (!isReady())
    {
        return;
    }

    d->htmlWidget->runScript(
                             QString::fromLatin1("kgeomapSetShowMapTypeControl(%1);")
                                 .arg(state ? QLatin1String("true")
                                            : QLatin1String("false"))
                            );
}

void BackendGoogleMaps::slotClustersNeedUpdating()
{
    s->worldMapWidget->updateClusters();
}

void BackendGoogleMaps::setZoom(const QString& newZoom)
{
    const QString myZoomString = s->worldMapWidget->convertZoomToBackendZoom(newZoom, QLatin1String("googlemaps"));
    GEOIFACE_ASSERT(myZoomString.startsWith(QLatin1String("googlemaps:")));

    const int myZoom           = myZoomString.mid(QString::fromLatin1("googlemaps:").length()).toInt();
    d->cacheZoom               = myZoom;

    if (isReady())
    {
        d->htmlWidget->runScript(QString::fromLatin1("kgeomapSetZoom(%1);").arg(d->cacheZoom));
    }
}

QString BackendGoogleMaps::getZoom() const
{
    return QString::fromLatin1("googlemaps:%1").arg(d->cacheZoom);
}

int BackendGoogleMaps::getMarkerModelLevel()
{
    GEOIFACE_ASSERT(isReady());

    if (!isReady())
    {
        return 0;
    }

    // get the current zoom level:

    const int currentZoom = d->cacheZoom;

    int tileLevel = 0;

    if      (currentZoom ==  0) { tileLevel = 1; }
    else if (currentZoom ==  1) { tileLevel = 1; }
    else if (currentZoom ==  2) { tileLevel = 1; }
    else if (currentZoom ==  3) { tileLevel = 2; }
    else if (currentZoom ==  4) { tileLevel = 2; }
    else if (currentZoom ==  5) { tileLevel = 3; }
    else if (currentZoom ==  6) { tileLevel = 3; }
    else if (currentZoom ==  7) { tileLevel = 3; }
    else if (currentZoom ==  8) { tileLevel = 4; }
    else if (currentZoom ==  9) { tileLevel = 4; }
    else if (currentZoom == 10) { tileLevel = 4; }
    else if (currentZoom == 11) { tileLevel = 4; }
    else if (currentZoom == 12) { tileLevel = 4; }
    else if (currentZoom == 13) { tileLevel = 4; }
    else if (currentZoom == 14) { tileLevel = 5; }
    else if (currentZoom == 15) { tileLevel = 5; }
    else if (currentZoom == 16) { tileLevel = 6; }
    else if (currentZoom == 17) { tileLevel = 7; }
    else if (currentZoom == 18) { tileLevel = 7; }
    else if (currentZoom == 19) { tileLevel = 8; }
    else if (currentZoom == 20) { tileLevel = 9; }
    else if (currentZoom == 21) { tileLevel = 9; }
    else if (currentZoom == 22) { tileLevel = 9; }
    else
    {
        tileLevel = TileIndex::MaxLevel - 1;
    }

    GEOIFACE_ASSERT(tileLevel <= TileIndex::MaxLevel-1);

    return tileLevel;
}

GeoCoordinates::PairList BackendGoogleMaps::getNormalizedBounds()
{
    return GeoIfaceHelperNormalizeBounds(d->cacheBounds);
}

/*
void BackendGoogleMaps::updateDragDropMarker(const QPoint& pos, const GeoIfaceDragData* const dragData)
{
    if (!isReady())
    {
        return;
    }

    if (!dragData)
    {
        d->htmlWidget->runScript("kgeomapRemoveDragMarker();");
    }
    else
    {
        d->htmlWidget->runScript(QLatin1String("kgeomapSetDragMarker(%1, %2, %3, %4);")
                .arg(pos.x())
                .arg(pos.y())
                .arg(dragData->itemCount)
                .arg(dragData->itemCount)
            );
    }

    // TODO: hide dragged markers on the map
}

void BackendGoogleMaps::updateDragDropMarkerPosition(const QPoint& pos)
{
    // TODO: buffer this!

    if (!isReady())
    {
        return;
    }

    d->htmlWidget->runScript(QLatin1String("kgeomapMoveDragMarker(%1, %2);")
            .arg(pos.x())
            .arg(pos.y())
        );
}
*/

void BackendGoogleMaps::updateActionAvailability()
{
    if (!d->activeState || !isReady())
    {
        return;
    }

    const QString currentMapType         = getMapType();
    const QList<QAction*> mapTypeActions = d->mapTypeActionGroup->actions();

    for (int i = 0 ; i < mapTypeActions.size() ; ++i)
    {
        mapTypeActions.at(i)->setChecked(mapTypeActions.at(i)->data().toString()==currentMapType);
    }

    s->worldMapWidget->getControlAction(QLatin1String("zoomin"))->setEnabled(true/*d->cacheZoom<d->cacheMaxZoom*/);
    s->worldMapWidget->getControlAction(QLatin1String("zoomout"))->setEnabled(true/*d->cacheZoom>d->cacheMinZoom*/);
}

void BackendGoogleMaps::updateZoomMinMaxCache()
{
    // TODO: these functions seem to cause problems, the map is not fully updated after a few calls
/*
    d->cacheMaxZoom = d->htmlWidget->runScript("kgeomapGetMaxZoom();", false).toInt();
    d->cacheMinZoom = d->htmlWidget->runScript("kgeomapGetMinZoom();", false).toInt();
*/
}

void BackendGoogleMaps::slotThumbnailAvailableForIndex(const QVariant& index, const QPixmap& pixmap)
{
    qCDebug(DIGIKAM_GEOIFACE_LOG) << index<<pixmap.size();

    if (pixmap.isNull() || !s->showThumbnails)
    {
        return;
    }

    // TODO: properly reject pixmaps with the wrong size

    const int expectedThumbnailSize = s->worldMapWidget->getUndecoratedThumbnailSize();

    if ((pixmap.size().height() > expectedThumbnailSize) || (pixmap.size().width() > expectedThumbnailSize))
    {
        return;
    }

    // find the cluster which is represented by this index:

    for (int i = 0 ; i < s->clusterList.count() ; ++i)
    {
        // TODO: use the right sortkey
        // TODO: let the representativeChooser handle the index comparison

        const QVariant representativeMarker = s->worldMapWidget->getClusterRepresentativeMarker(i, s->sortKey);

        if (s->markerModel->indicesEqual(index, representativeMarker))
        {
            QPoint clusterCenterPoint;

            // TODO: who calculates the override values?

            const QPixmap clusterPixmap = s->worldMapWidget->getDecoratedPixmapForCluster(i, nullptr, nullptr, &clusterCenterPoint);

            setClusterPixmap(i, clusterCenterPoint, clusterPixmap);

            break;
        }
    }
}

void BackendGoogleMaps::setClusterPixmap(const int clusterId, const QPoint& centerPoint, const QPixmap& clusterPixmap)
{
    // decorate the pixmap:

    const QPixmap styledPixmap = clusterPixmap;

    QByteArray bytes;
    QBuffer buffer(&bytes);
    buffer.open(QIODevice::WriteOnly);
    clusterPixmap.save(&buffer, "PNG");
    buffer.close();

    // www.faqs.org/rfcs/rfc2397.html

    const QString imageData = QString::fromLatin1("data:image/png;base64,%1").arg(QString::fromLatin1(bytes.toBase64()));
    d->htmlWidget->runScript(
                             QString::fromLatin1("kgeomapSetClusterPixmap(%1,%5,%6,%2,%3,'%4');")
                                 .arg(clusterId)
                                 .arg(centerPoint.x())
                                 .arg(centerPoint.y())
                                 .arg(imageData)
                                 .arg(clusterPixmap.width())
                                 .arg(clusterPixmap.height())
                            );
}

void BackendGoogleMaps::setMarkerPixmap(const int modelId, const int markerId,
                                        const QPoint& centerPoint, const QPixmap& markerPixmap)
{
    QByteArray bytes;
    QBuffer buffer(&bytes);
    buffer.open(QIODevice::WriteOnly);
    markerPixmap.save(&buffer, "PNG");
    buffer.close();

    // www.faqs.org/rfcs/rfc2397.html

    const QString imageData = QString::fromLatin1("data:image/png;base64,%1").arg(QString::fromLatin1(bytes.toBase64()));
    d->htmlWidget->runScript(
                             QString::fromLatin1("kgeomapSetMarkerPixmap(%7,%1,%5,%6,%2,%3,'%4');")
                                 .arg(markerId)
                                 .arg(centerPoint.x())
                                 .arg(centerPoint.y())
                                 .arg(imageData)
                                 .arg(markerPixmap.width())
                                 .arg(markerPixmap.height())
                                 .arg(modelId)
                            );
}

void BackendGoogleMaps::setMarkerPixmap(const int modelId, const int markerId,
                                        const QPoint& centerPoint, const QSize& iconSize,
                                        const QUrl& iconUrl)
{
    /// @todo Sort the parameters

    d->htmlWidget->runScript(
                             QString::fromLatin1("kgeomapSetMarkerPixmap(%7,%1,%5,%6,%2,%3,'%4');")
                                 .arg(markerId)
                                 .arg(centerPoint.x())
                                 .arg(centerPoint.y())
                                 .arg(iconUrl.url()) /// @todo Escape characters like apostrophe
                                 .arg(iconSize.width())
                                 .arg(iconSize.height())
                                 .arg(modelId)
                            );
}

bool BackendGoogleMaps::eventFilter(QObject* object, QEvent* event)
{
    if (object == d->htmlWidgetWrapper)
    {
        if (event->type() == QEvent::Resize)
        {
            QResizeEvent* const resizeEvent = dynamic_cast<QResizeEvent*>(event);<--- Variable 'resizeEvent' can be declared as pointer to const

            if (resizeEvent)
            {
                // TODO: the map div does not adjust its height properly if height=100%,
                //       therefore we adjust it manually here

                if (d->isReady)
                {
                    d->htmlWidget->runScript(
                                             QString::fromLatin1("kgeomapWidgetResized(%1, %2)")
                                                 .arg(d->htmlWidgetWrapper->width())
                                                 .arg(d->htmlWidgetWrapper->height())
                                            );
                }
            }
        }
    }

    return false;
}

void BackendGoogleMaps::regionSelectionChanged()
{
    if (!d->htmlWidget)
    {
        return;
    }

    if (s->hasRegionSelection())
    {
        d->htmlWidget->setSelectionRectangle(s->selectionRectangle);
    }
    else
    {
        d->htmlWidget->removeSelectionRectangle();
    }
}

void BackendGoogleMaps::mouseModeChanged()
{
    if (!d->htmlWidget)
    {
        return;
    }

    /// @todo Does htmlwidget read this value from s->currentMouseMode on its own?

    d->htmlWidget->mouseModeChanged(s->currentMouseMode);
}

void BackendGoogleMaps::slotSelectionHasBeenMade(const Digikam::GeoCoordinates::Pair& searchCoordinates)
{
    Q_EMIT signalSelectionHasBeenMade(searchCoordinates);
}

void BackendGoogleMaps::setActive(const bool state)
{
    const bool oldState = d->activeState;
    d->activeState      = state;

    if (oldState != state)
    {
        if (!state && d->htmlWidgetWrapper)
        {
            // we should share our widget in the list of widgets in the global object

            GeoIfaceInternalWidgetInfo info;
            info.deleteFunction = deleteInfoFunction;
            info.widget         = d->htmlWidgetWrapper.data();
            info.currentOwner   = this;
            info.backendName    = backendName();
            info.state          = d->widgetIsDocked ? GeoIfaceInternalWidgetInfo::InternalWidgetStillDocked
                                                    : GeoIfaceInternalWidgetInfo::InternalWidgetUndocked;

            GMInternalWidgetInfo intInfo;
            intInfo.htmlWidget  = d->htmlWidget.data();
            info.backendData.setValue(intInfo);

            GeoIfaceGlobalObject* const go = GeoIfaceGlobalObject::instance();
            go->addMyInternalWidgetToPool(info);
        }

        if (state && d->htmlWidgetWrapper)
        {
            // we should remove our widget from the list of widgets in the global object

            GeoIfaceGlobalObject* const go = GeoIfaceGlobalObject::instance();
            go->removeMyInternalWidgetFromPool(this);

            /// @todo re-cluster, update markers?

            setMapType(d->cacheMapType);
            setShowScaleControl(d->cacheShowScaleControl);
            setShowMapTypeControl(d->cacheShowMapTypeControl);
            setShowNavigationControl(d->cacheShowNavigationControl);

            setCenter(d->cacheCenter);
            d->htmlWidget->runScript(QString::fromLatin1("kgeomapSetZoom(%1);").arg(d->cacheZoom));

            /// @todo update tracks more gently

            slotTracksChanged(d->trackChangeTracker);
            d->trackChangeTracker.clear();
        }
    }
}

void BackendGoogleMaps::releaseWidget(GeoIfaceInternalWidgetInfo* const info)
{
    // clear all tracks

    d->htmlWidget->runScript(QString::fromLatin1("kgeomapClearTracks();"));

    disconnect(d->htmlWidget, SIGNAL(signalJavaScriptReady()),
               this, SLOT(slotHTMLInitialized()));

    disconnect(d->htmlWidget, SIGNAL(signalHTMLEvents(QStringList)),
               this, SLOT(slotHTMLEvents(QStringList)));

    disconnect(d->htmlWidget, SIGNAL(selectionHasBeenMade(Digikam::GeoCoordinates::Pair)),
               this, SLOT(slotSelectionHasBeenMade(Digikam::GeoCoordinates::Pair)));

    d->htmlWidget->setSharedGeoIfaceObject(nullptr);
    d->htmlWidgetWrapper->removeEventFilter(this);

    d->htmlWidget        = nullptr;
    d->htmlWidgetWrapper = nullptr;
    info->currentOwner   = nullptr;
    info->state          = GeoIfaceInternalWidgetInfo::InternalWidgetReleased;
    d->isReady           = false;

    Q_EMIT signalBackendReadyChanged(backendName());
}

void BackendGoogleMaps::mapWidgetDocked(const bool state)
{
    if (d->widgetIsDocked != state)
    {
        GeoIfaceGlobalObject* const go = GeoIfaceGlobalObject::instance();
        go->updatePooledWidgetState(d->htmlWidgetWrapper, state ? GeoIfaceInternalWidgetInfo::InternalWidgetStillDocked
                                                                : GeoIfaceInternalWidgetInfo::InternalWidgetUndocked);
    }

    d->widgetIsDocked = state;
}

void BackendGoogleMaps::deleteInfoFunction(GeoIfaceInternalWidgetInfo* const info)
{
    if (info->currentOwner)
    {
        qobject_cast<MapBackend*>(info->currentOwner.data())->releaseWidget(info);
    }

    const GMInternalWidgetInfo intInfo = info->backendData.value<GMInternalWidgetInfo>();

    delete intInfo.htmlWidget;
    delete info->widget.data();
}

void BackendGoogleMaps::storeTrackChanges(const TrackManager::TrackChanges trackChanges)
{
    for (int i = 0 ; i < d->trackChangeTracker.count() ; ++i)
    {
        if (d->trackChangeTracker.at(i).first == trackChanges.first)
        {
            d->trackChangeTracker[i].second = TrackManager::ChangeFlag(d->trackChangeTracker.at(i).second | trackChanges.second);

            return;
        }
    }

    d->trackChangeTracker << trackChanges;
}

void BackendGoogleMaps::slotTrackManagerChanged()
{
    /// @todo disconnect old track manager
    /// @todo mark all tracks as dirty

    if (s->trackManager)
    {
        connect(s->trackManager, SIGNAL(signalTracksChanged(QList<TrackManager::TrackChanges>)),
                this, SLOT(slotTracksChanged(QList<TrackManager::TrackChanges>)));

        connect(s->trackManager, SIGNAL(signalVisibilityChanged(bool)),
                this, SLOT(slotTrackVisibilityChanged(bool)));

        // store all tracks which are already in the manager as changed

        const TrackManager::Track::List trackList = s->trackManager->getTrackList();

        for (const TrackManager::Track& t : std::as_const(trackList))
        {
            storeTrackChanges(TrackManager::TrackChanges(t.id, TrackManager::ChangeAdd));
        }
    }
}

void BackendGoogleMaps::slotTracksChanged(const QList<TrackManager::TrackChanges>& trackChanges)
{
    bool needToTrackChanges = !d->activeState;

    if (s->trackManager)
    {
        needToTrackChanges |= !s->trackManager->getVisibility();
    }

    if (needToTrackChanges)
    {
        for (const TrackManager::TrackChanges& tc : std::as_const(trackChanges))
        {
            storeTrackChanges(tc);
        }

        return;
    }

    /// @todo We have to re-read the tracks after being inactive.
    /// @todo Tracks have to be cleared in JavaScript every time the
    ///       htmlwidget is passed to another mapwidget.
    /// @todo Clearing all tracks and re-adding them takes too long. We
    ///       have to see which track changed, and whether coordinates or only properties changed.

    if (!s->trackManager)
    {
        // no track manager, clear all tracks

        const QVariant successClear = d->htmlWidget->runScript(QString::fromLatin1("kgeomapClearTracks();"), false);

        return;
    }

    for (const TrackManager::TrackChanges& tc : std::as_const(trackChanges))
    {
        if (tc.second & TrackManager::ChangeRemoved)
        {
            d->htmlWidget->runScript(QString::fromLatin1("kgeomapRemoveTrack(%1);").arg(tc.first));
        }
        else
        {
            /// @todo For now, remove the track and re-add it.

            d->htmlWidget->runScript(QString::fromLatin1("kgeomapRemoveTrack(%1);").arg(tc.first));

            const TrackManager::Track track = s->trackManager->getTrackById(tc.first);

            if (track.points.count() < 2)
            {
                continue;
            }

            const QString createTrackScript = QString::fromLatin1("kgeomapCreateTrack(%1,'%2');")
                                              .arg(track.id)
                                              .arg(track.color.name()); // QColor::name() returns #ff00ff
            d->htmlWidget->runScript(createTrackScript);

            QDateTime t1                    = QDateTime::currentDateTime();
            const int numPointsToPassAtOnce = 1000;

            for (int coordIdx = 0 ; coordIdx < track.points.count() ; coordIdx += numPointsToPassAtOnce)
            {
                /// @todo Even by passing only a few points each time, we can
                ///       block the UI for a long time. Instead, it may be better
                ///       to call addPointsToTrack via the eventloop repeatedly
                ///       to allow processing of other events.

                addPointsToTrack(track.id, track.points, coordIdx, numPointsToPassAtOnce);
            }

            QDateTime t2 = QDateTime::currentDateTime();
            qCDebug(DIGIKAM_GEOIFACE_LOG) << track.url.fileName() << t1.msecsTo(t2);
        }
    }
}

void BackendGoogleMaps::addPointsToTrack(const quint64 trackId, TrackManager::TrackPoint::List const& track, const int firstPoint, const int nPoints)
{
    QString json;
    QTextStream jsonBuilder(&json);
    jsonBuilder << '[';
    int lastPoint = track.count()-1;

    if (nPoints > 0)
    {
        lastPoint = qMin(firstPoint + nPoints - 1, track.count()-1);
    }

    for (int coordIdx = firstPoint ; coordIdx <= lastPoint ; ++coordIdx)
    {
        GeoCoordinates const& coordinates = track.at(coordIdx).coordinates;

        if (coordIdx > firstPoint)
        {
            jsonBuilder << ',';
        }

        /// @todo This looks like a lot of text to parse. Is there a more compact way?

        jsonBuilder << "{\"lat\":" << coordinates.latString() << ","
                    << "\"lon\":"  << coordinates.lonString() << "}";
    }

    jsonBuilder << ']';
    const QString addTrackScript = QString::fromLatin1("kgeomapAddToTrack(%1,'%2');").arg(trackId).arg(json);
    d->htmlWidget->runScript(addTrackScript);
}

void BackendGoogleMaps::slotTrackVisibilityChanged(const bool newState)
{
    /// @todo Now we remove all tracks and re-add them on visibility change.
    ///       This is very slow.

    if      (newState)
    {
        // store all tracks which are already in the manager as changed

        const TrackManager::Track::List trackList = s->trackManager->getTrackList();
        QList<TrackManager::TrackChanges> trackChanges;

        for (const TrackManager::Track& t : std::as_const(trackList))
        {
            trackChanges << TrackManager::TrackChanges(t.id, TrackManager::ChangeAdd);
        }

        slotTracksChanged(trackChanges);
    }
    else if (d->htmlWidget)
    {
        const QVariant successClear = d->htmlWidget->runScript(QString::fromLatin1("kgeomapClearTracks();"), false);
    }
}

void BackendGoogleMaps::slotMessageEvent(const QString& /*message*/)
{
/*
    qCDebug(DIGIKAM_GEOIFACE_LOG) << "Javascript Message:" << message;
*/
}

#ifdef HAVE_GEOLOCATION

void BackendGoogleMaps::centerOn(const Marble::GeoDataLatLonBox& latLonBox, const bool useSaneZoomLevel)
{
    /// @todo Buffer this call if there is no widget or if inactive!

    if (!d->htmlWidget)
    {
        return;
    }

    const qreal boxWest  = latLonBox.west(Marble::GeoDataCoordinates::Degree);
    const qreal boxNorth = latLonBox.north(Marble::GeoDataCoordinates::Degree);
    const qreal boxEast  = latLonBox.east(Marble::GeoDataCoordinates::Degree);
    const qreal boxSouth = latLonBox.south(Marble::GeoDataCoordinates::Degree);

    d->htmlWidget->centerOn(boxWest, boxNorth, boxEast, boxSouth, useSaneZoomLevel);
    qCDebug(DIGIKAM_GEOIFACE_LOG) << getZoom();
}

#endif

} // namespace Digikam

#include "moc_backendgooglemaps.cpp"