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
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2009-05-07
 * Description : Context menu for GPS list view.
 *
 * SPDX-FileCopyrightText: 2010-2025 by Gilles Caulier <caulier dot gilles at gmail dot com>
 * SPDX-FileCopyrightText: 2009-2014 by Michael G. Hansen <mike at mghansen dot de>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "gpsitemlistcontextmenu.h"

// Qt includes:

#include <QEvent>
#include <QContextMenuEvent>
#include <QClipboard>
#include <QApplication>
#include <QDomDocument>
#include <QPointer>
#include <QAction>
#include <QMenu>
#include <QMessageBox>
#include <QMimeData>

// KDE includes

#include <klocalizedstring.h>

// Local includes

#include "digikam_debug.h"
#include "gpsundocommand.h"
#include "gpscommon.h"
#include "gpsitemcontainer.h"
#include "lookupfactory.h"
#include "gpsbookmarkowner.h"

namespace Digikam
{

class Q_DECL_HIDDEN GPSItemListContextMenu::Private
{
public:

    Private() = default;

public:

    bool                     enabled                        = true;

    QAction*                 actionBookmark                 = nullptr;
    GPSBookmarkOwner*        bookmarkOwner                  = nullptr;

    QAction*                 actionCopy                     = nullptr;
    QAction*                 actionPaste                    = nullptr;
    QAction*                 actionPasteSwap                = nullptr;
    QAction*                 actionRemoveCoordinates        = nullptr;
    QAction*                 actionRemoveAltitude           = nullptr;
    QAction*                 actionRemoveUncertainty        = nullptr;
    QAction*                 actionRemoveSpeed              = nullptr;
    QAction*                 actionLookupMissingAltitudes   = nullptr;

    GPSItemList*             imagesList                     = nullptr;

    /// Altitude lookup
    QPointer<LookupAltitude> altitudeLookup;
    GPSUndoCommand*          altitudeUndoCommand            = nullptr;
    int                      altitudeRequestedCount         = 0;
    int                      altitudeReceivedCount          = 0;
};

GPSItemListContextMenu::GPSItemListContextMenu(GPSItemList* const imagesList,
                                               GPSBookmarkOwner* const bookmarkOwner)
    : QObject(imagesList),
      d      (new Private)
{
    d->imagesList                   = imagesList;

    d->actionCopy                   = new QAction(i18n("Copy coordinates"),                this);
    d->actionCopy->setIcon(QIcon::fromTheme(QLatin1String("edit-copy")));
    d->actionPaste                  = new QAction(i18n("Paste coordinates"),               this);
    d->actionPaste->setIcon(QIcon::fromTheme(QLatin1String("edit-paste")));
    d->actionPasteSwap              = new QAction(i18n("Paste coordinates swapped"),       this);
    d->actionPasteSwap->setIcon(QIcon::fromTheme(QLatin1String("edit-paste")));
    d->actionRemoveCoordinates      = new QAction(i18n("Remove coordinates"),              this);
    d->actionRemoveAltitude         = new QAction(i18n("Remove altitude"),                 this);
    d->actionRemoveUncertainty      = new QAction(i18n("Remove uncertainty"),              this);
    d->actionRemoveSpeed            = new QAction(i18n("Remove speed"),                    this);
    d->actionLookupMissingAltitudes = new QAction(i18n("Look up missing altitude values"), this);

    connect(d->actionCopy, SIGNAL(triggered()),
            this, SLOT(copyActionTriggered()));

    connect(d->actionPaste, SIGNAL(triggered()),
            this, SLOT(pasteActionTriggered()));

    connect(d->actionPasteSwap, SIGNAL(triggered()),
            this, SLOT(pasteSwapActionTriggered()));

    connect(d->actionRemoveCoordinates, SIGNAL(triggered()),
            this, SLOT(slotRemoveCoordinates()));

    connect(d->actionRemoveAltitude, SIGNAL(triggered()),
            this, SLOT(slotRemoveAltitude()));

    connect(d->actionRemoveUncertainty, SIGNAL(triggered()),
            this, SLOT(slotRemoveUncertainty()));

    connect(d->actionRemoveSpeed, SIGNAL(triggered()),
            this, SLOT(slotRemoveSpeed()));

    connect(d->actionLookupMissingAltitudes, SIGNAL(triggered()),
            this, SLOT(slotLookupMissingAltitudes()));

    if (bookmarkOwner)
    {
        d->bookmarkOwner   = bookmarkOwner;
        d->actionBookmark  = new QAction(i18n("Bookmarks"), this);
        d->actionBookmark->setMenu(d->bookmarkOwner->getMenu());

        connect(d->bookmarkOwner, SIGNAL(positionSelected(GPSDataContainer)),
                this, SLOT(slotBookmarkSelected(GPSDataContainer)));
    }

    d->imagesList->installEventFilter(this);
}

GPSItemListContextMenu::~GPSItemListContextMenu()
{
    delete d->altitudeUndoCommand;
    delete d;
}

bool GPSItemListContextMenu::eventFilter(QObject* watched, QEvent* event)
{
    // We are only interested in context-menu events.

    if ((event->type() == QEvent::ContextMenu) && d->enabled)
    {
        // Enable or disable the actions.

        GPSItemModel* const imageModel            = d->imagesList->getModel();<--- Variable 'imageModel' can be declared as pointer to const
        QItemSelectionModel* const selectionModel = d->imagesList->getSelectionModel();
        const QList<QModelIndex> selectedIndices  = selectionModel->selectedRows();
        const int nSelected                       = selectedIndices.size();

        // "copy" are only available for one selected image with geo data.

        bool copyAvailable                        = (nSelected == 1);
        bool removeAltitudeAvailable              = false;
        bool removeCoordinatesAvailable           = false;
        bool removeUncertaintyAvailable           = false;
        bool removeSpeedAvailable                 = false;
        bool lookupMissingAltitudesAvailable      = false;

        for (int i = 0 ; i < nSelected ; ++i)
        {
            GPSItemContainer* const gpsItem = imageModel->itemFromIndex(selectedIndices.at(i));<--- Variable 'gpsItem' can be declared as pointer to const

            if (gpsItem)
            {
                const GPSDataContainer gpsData   = gpsItem->gpsData();
                const bool itemHasCoordinates    = gpsData.getCoordinates().hasCoordinates();
                copyAvailable                   &= itemHasCoordinates;
                removeCoordinatesAvailable      |= itemHasCoordinates;
                removeAltitudeAvailable         |= gpsData.getCoordinates().hasAltitude();
                removeUncertaintyAvailable      |= (int)gpsData.hasNSatellites() | (int)gpsData.hasDop() | (int)gpsData.hasFixType();
                removeSpeedAvailable            |= gpsData.hasSpeed();
                lookupMissingAltitudesAvailable |= itemHasCoordinates && !gpsData.getCoordinates().hasAltitude();
            }
        }

        d->actionCopy->setEnabled(copyAvailable);
        d->actionRemoveAltitude->setEnabled(removeAltitudeAvailable);
        d->actionRemoveCoordinates->setEnabled(removeCoordinatesAvailable);
        d->actionRemoveUncertainty->setEnabled(removeUncertaintyAvailable);
        d->actionRemoveSpeed->setEnabled(removeSpeedAvailable);
        d->actionLookupMissingAltitudes->setEnabled(lookupMissingAltitudesAvailable);

        if (d->bookmarkOwner)
        {
            d->bookmarkOwner->changeAddBookmark(copyAvailable);
            GPSDataContainer position;
            QUrl             itemUrl;
            getCurrentItemPositionAndUrl(&position, &itemUrl);
            const QString itemFileName = itemUrl.fileName();
            d->bookmarkOwner->setPositionAndTitle(position.getCoordinates(), itemFileName);
        }

        // "paste" is only available if there is geo data in the clipboard
        // and at least one photo is selected.

        bool pasteAvailable     = (nSelected >= 1);
        bool pasteSwapAvailable = true;

        if (pasteAvailable)
        {
            QClipboard* const clipboard = QApplication::clipboard();
            const QMimeData* mimedata   = clipboard->mimeData();
            bool hasXmlFormat           = mimedata->hasFormat(QLatin1String("application/gpx+xml"));
            pasteAvailable              = hasXmlFormat || mimedata->hasText();
            pasteSwapAvailable          = !hasXmlFormat && mimedata->hasText();
        }

        d->actionPaste->setEnabled(pasteAvailable);
        d->actionPasteSwap->setEnabled(pasteSwapAvailable);

        // Construct the context-menu.

        QMenu* const menu = new QMenu(d->imagesList);
        menu->addAction(d->actionCopy);
        menu->addAction(d->actionPaste);
        menu->addAction(d->actionPasteSwap);
        menu->addSeparator();
        menu->addAction(d->actionRemoveCoordinates);
        menu->addAction(d->actionRemoveAltitude);
        menu->addAction(d->actionRemoveUncertainty);
        menu->addAction(d->actionRemoveSpeed);
        menu->addAction(d->actionLookupMissingAltitudes);

        if (d->actionBookmark)
        {
            menu->addSeparator();
            menu->addAction(d->actionBookmark);
            d->actionBookmark->setEnabled(nSelected >= 1);
        }

        QContextMenuEvent* const e = static_cast<QContextMenuEvent*>(event);
        menu->exec(e->globalPos());

        delete menu;

        return true;
    }
    else
    {
        return QObject::eventFilter(watched, event);
    }
}

bool GPSItemListContextMenu::getCurrentItemPositionAndUrl(GPSDataContainer* const gpsInfo,
                                                          QUrl* const itemUrl)
{
    // NOTE: currentIndex does not seem to work any more since we use KLinkItemSelectionModel.

    GPSItemModel* const imageModel           = d->imagesList->getModel();<--- Variable 'imageModel' can be declared as pointer to const
    QItemSelectionModel* const selectionModel = d->imagesList->getSelectionModel();
    const QList<QModelIndex> selectedIndices  = selectionModel->selectedRows();

    if (selectedIndices.count() != 1)
    {
        return false;
    }

    const QModelIndex currentIndex = selectedIndices.first();

    if (!currentIndex.isValid())
    {
        return false;
    }

    GPSItemContainer* const gpsItem = imageModel->itemFromIndex(currentIndex);<--- Variable 'gpsItem' can be declared as pointer to const

    if (gpsItem)
    {
        if (gpsInfo)
        {
            *gpsInfo = gpsItem->gpsData();
        }

        if (itemUrl)
        {
            *itemUrl = gpsItem->url();
        }

        return true;
    }

    return false;
}

void GPSItemListContextMenu::copyActionTriggered()
{
    GPSDataContainer gpsInfo;
    QUrl itemUrl;

    if (!getCurrentItemPositionAndUrl(&gpsInfo, &itemUrl))
    {
        return;
    }

    coordinatesToClipboard(gpsInfo.getCoordinates(), itemUrl, QString());
}

void GPSItemListContextMenu::pasteSwapActionTriggered()
{
    pasteActionTriggered(true);
}

void GPSItemListContextMenu::pasteActionTriggered(bool swap)
{
    // Extract the coordinates from the clipboard.

    QClipboard* const clipboard = QApplication::clipboard();
    const QMimeData* mimedata   = clipboard->mimeData();

    GPSDataContainer gpsData;
    bool foundData              = false;

    if (mimedata->hasFormat(QLatin1String("application/gpx+xml")))
    {
        const QByteArray data = mimedata->data(QLatin1String("application/gpx+xml"));
        bool xmlOkay          = true;
        bool foundDoubleData  = false;

        // Code adapted from gpsdataparser.cpp.

        QDomDocument gpxDoc(QLatin1String("gpx"));

        if (!gpxDoc.setContent(data))
        {
            xmlOkay = false;
        }

        if (xmlOkay)
        {
            const QDomElement gpxDocElem = gpxDoc.documentElement();

            if (gpxDocElem.tagName() != QLatin1String("gpx"))
            {
                xmlOkay = false;
            }

            if (xmlOkay)
            {
                for (QDomNode nWpt = gpxDocElem.firstChild() ; !nWpt.isNull() ; nWpt = nWpt.nextSibling())
                {
                    const QDomElement wptElem = nWpt.toElement();

                    if (wptElem.isNull())
                    {
                        continue;
                    }

                    if (wptElem.tagName() != QLatin1String("wpt"))
                    {
                        continue;
                    }

                    double ptAltitude  = 0.0;
                    double ptLatitude  = 0.0;
                    double ptLongitude = 0.0;
                    bool haveAltitude  = false;

                    // Get GPS position. If not available continue to next point.

                    const QString lat  = wptElem.attribute(QLatin1String("lat"));
                    const QString lon  = wptElem.attribute(QLatin1String("lon"));

                    if (lat.isEmpty() || lon.isEmpty())
                    {
                        continue;
                    }

                    ptLatitude         = lat.toDouble();
                    ptLongitude        = lon.toDouble();

                    if (foundData)
                    {
                        foundDoubleData = true;
                        break;
                    }

                    // Get metadata of way point (altitude and time stamp).

                    for (QDomNode nWptMeta = wptElem.firstChild() ; !nWptMeta.isNull() ; nWptMeta = nWptMeta.nextSibling())
                    {
                        const QDomElement wptMetaElem = nWptMeta.toElement();

                        if (wptMetaElem.isNull())
                        {
                            continue;
                        }

                        if (wptMetaElem.tagName() == QLatin1String("ele"))
                        {
                            // Get GPS point altitude. If not available continue to next point.

                            QString ele = wptMetaElem.text();

                            if (!ele.isEmpty())
                            {
                                ptAltitude = ele.toDouble(&haveAltitude);
                                break;
                            }
                        }
                    }

                    foundData = true;
                    GeoCoordinates coordinates(ptLatitude, ptLongitude);

                    if (haveAltitude)
                    {
                        coordinates.setAlt(ptAltitude);
                    }

                    gpsData.setCoordinates(coordinates);
                }
            }
        }

        if (foundDoubleData)
        {
            QMessageBox::information(d->imagesList,
                                     i18nc("@title:window", "Geolocation Editor"),
                                     i18n("Found more than one point on the clipboard - can only assign one point at a time."));
        }
    }

    if (!foundData && mimedata->hasText())
    {
        const QString textdata         = mimedata->text();
        bool foundGeoUrl               = false;
        GeoCoordinates testCoordinates = GeoCoordinates::fromGeoUrl(textdata, &foundGeoUrl);

        if (foundGeoUrl)
        {
            gpsData.setCoordinates(testCoordinates);
            foundData = true;
        }
        else
        {
            /// @todo this is legacy code from before we used geo-url.

            QLocale locale;
            QString cordText = textdata.trimmed();
            QStringList separators({QLatin1String(","),
                                    QLatin1String("/"),
                                    QLatin1String(":"),
                                    QLatin1String(";"),
                                    QLatin1String(" ")});
            int firstPoint   =  cordText.indexOf(QLatin1Char('.'));

            if ((firstPoint == -1) || (firstPoint > 4))
            {
                locale = QLocale(QLocale::French);

                if (cordText.count(QLatin1Char(',')) > 1)
                {
                    separators.removeOne(QLatin1String(","));
                }
            }
            else
            {
                locale = QLocale(QLocale::C);
            }

            QStringList parts;
            bool foundParts = false;

            while (!separators.isEmpty())
            {
                parts = cordText.split(separators.takeFirst(), Qt::SkipEmptyParts);

                if ((parts.size() == 3) || (parts.size() == 2))
                {
                    foundParts = true;
                    break;
                }
            }

            if (foundParts)
            {
                double ptLongitude = 0.0;
                double ptAltitude  = 0.0;
                bool haveAltitude  = false;
                bool okay          = true;
                double ptLatitude  = locale.toDouble(parts[0], &okay);

                if (okay)
                {
                    ptLongitude = locale.toDouble(parts[1], &okay);
                }

                if (okay && (parts.size() == 3))
                {
                    ptAltitude   = locale.toDouble(parts[2], &okay);
                    haveAltitude = okay;
                }

                foundData = okay;

                if (okay)
                {
                    if (swap)
                    {
                        std::swap(ptLatitude, ptLongitude);
                    }

                    GeoCoordinates coordinates(ptLatitude, ptLongitude);

                    if (haveAltitude)
                    {
                        coordinates.setAlt(ptAltitude);
                    }

                    gpsData.setCoordinates(coordinates);
                }
            }
        }
    }

    if (!foundData)
    {
        QMessageBox::information(d->imagesList,
                                 i18nc("@title:window", "Geolocation Editor"),
                                 i18n("Could not find any coordinates on the clipboard."));
        return;
    }

    setGPSDataForSelectedItems(gpsData, i18n("Coordinates pasted"));
}

void GPSItemListContextMenu::setGPSDataForSelectedItems(const GPSDataContainer& gpsData,
                                                        const QString& undoDescription)
{
    GPSItemModel* const imageModel            = d->imagesList->getModel();
    QItemSelectionModel* const selectionModel = d->imagesList->getSelectionModel();
    const QList<QModelIndex> selectedIndices  = selectionModel->selectedRows();
    const int nSelected                       = selectedIndices.size();
    GPSUndoCommand* const undoCommand         = new GPSUndoCommand();

    for (int i = 0 ; i < nSelected ; ++i)
    {
        const QModelIndex itemIndex     = selectedIndices.at(i);
        GPSItemContainer* const gpsItem = imageModel->itemFromIndex(itemIndex);

        GPSUndoCommand::UndoInfo undoInfo(itemIndex);
        undoInfo.readOldDataFromItem(gpsItem);

        gpsItem->setGPSData(gpsData);
        undoInfo.readNewDataFromItem(gpsItem);

        undoCommand->addUndoInfo(undoInfo);
    }

    undoCommand->setText(undoDescription);

    Q_EMIT signalUndoCommand(undoCommand);
}

void GPSItemListContextMenu::slotBookmarkSelected(const GPSDataContainer& position)
{
    setGPSDataForSelectedItems(position, i18n("Bookmark selected"));
}

bool GPSItemListContextMenu::getCurrentPosition(GPSDataContainer* position, void* mydata)
{
    if (!position || !mydata)
    {
        return false;
    }

    GPSItemListContextMenu* const me = reinterpret_cast<GPSItemListContextMenu*>(mydata);

    return me->getCurrentItemPositionAndUrl(position, nullptr);
}

void GPSItemListContextMenu::removeInformationFromSelectedImages(const GPSDataContainer::HasFlags flagsToClear, const QString& undoDescription)
{
    // Enable or disable the actions.

    GPSItemModel* const imageModel            = d->imagesList->getModel();
    QItemSelectionModel* const selectionModel = d->imagesList->getSelectionModel();
    const QList<QModelIndex> selectedIndices  = selectionModel->selectedRows();
    const int nSelected                       = selectedIndices.size();
    GPSUndoCommand* const undoCommand         = new GPSUndoCommand();

    for (int i = 0 ; i < nSelected ; ++i)
    {
        const QModelIndex itemIndex     = selectedIndices.at(i);
        GPSItemContainer* const gpsItem = imageModel->itemFromIndex(itemIndex);

        GPSUndoCommand::UndoInfo undoInfo(itemIndex);
        undoInfo.readOldDataFromItem(gpsItem);

        GPSDataContainer newGPSData     = gpsItem->gpsData();
        bool didSomething               = false;

        if (flagsToClear.testFlag(GPSDataContainer::HasCoordinates))
        {
            if (newGPSData.hasCoordinates())
            {
                didSomething = true;
                newGPSData.clear();
            }
        }

        if (flagsToClear.testFlag(GPSDataContainer::HasAltitude))
        {
            if (newGPSData.hasAltitude())
            {
                didSomething = true;
                newGPSData.clearAltitude();
            }
        }

        if (flagsToClear.testFlag(GPSDataContainer::HasNSatellites))
        {
            if (newGPSData.hasNSatellites())
            {
                didSomething = true;
                newGPSData.clearNSatellites();
            }
        }

        if (flagsToClear.testFlag(GPSDataContainer::HasDop))
        {
            if (newGPSData.hasDop())
            {
                didSomething = true;
                newGPSData.clearDop();
            }
        }

        if (flagsToClear.testFlag(GPSDataContainer::HasFixType))
        {
            if (newGPSData.hasFixType())
            {
                didSomething = true;
                newGPSData.clearFixType();
            }
        }

        if (flagsToClear.testFlag(GPSDataContainer::HasSpeed))
        {
            if (newGPSData.hasSpeed())
            {
                didSomething = true;
                newGPSData.clearSpeed();
            }
        }

        if (didSomething)
        {
            gpsItem->setGPSData(newGPSData);
            undoInfo.readNewDataFromItem(gpsItem);
            undoCommand->addUndoInfo(undoInfo);
        }
    }

    if (undoCommand->affectedItemCount() > 0)
    {
        undoCommand->setText(undoDescription);

        Q_EMIT signalUndoCommand(undoCommand);
    }
    else
    {
        delete undoCommand;
    }
}

void GPSItemListContextMenu::slotRemoveCoordinates()
{
    removeInformationFromSelectedImages(GPSDataContainer::HasCoordinates, i18n("Remove coordinates information"));
}

void GPSItemListContextMenu::slotRemoveAltitude()
{
    removeInformationFromSelectedImages(GPSDataContainer::HasAltitude, i18n("Remove altitude information"));
}

void GPSItemListContextMenu::slotRemoveUncertainty()
{
    removeInformationFromSelectedImages(GPSDataContainer::HasNSatellites|GPSDataContainer::HasDop|GPSDataContainer::HasFixType,
                                        i18n("Remove uncertainty information"));
}

void GPSItemListContextMenu::setEnabled(const bool state)
{
    d->enabled = state;
}

void GPSItemListContextMenu::slotRemoveSpeed()
{
    removeInformationFromSelectedImages(GPSDataContainer::HasSpeed, i18n("Remove speed"));
}

void GPSItemListContextMenu::slotLookupMissingAltitudes()
{
    GPSItemModel* const imageModel            = d->imagesList->getModel();<--- Variable 'imageModel' can be declared as pointer to const
    QItemSelectionModel* const selectionModel = d->imagesList->getSelectionModel();
    const QList<QModelIndex> selectedIndices  = selectionModel->selectedRows();
/*
    const int nSelected                       = selectedIndices.size();
*/
    // Find the indices which have coordinates but no altitude.

    LookupAltitude::Request::List altitudeQueries;

    for (const QModelIndex& currentIndex : std::as_const(selectedIndices))
    {
        GPSItemContainer* const gpsItem = imageModel->itemFromIndex(currentIndex);<--- Variable 'gpsItem' can be declared as pointer to const

        if (!gpsItem)
        {
            continue;
        }

        const GPSDataContainer gpsData   = gpsItem->gpsData();
        const GeoCoordinates coordinates = gpsData.getCoordinates();

        if ((!coordinates.hasCoordinates()) || coordinates.hasAltitude())
        {
            continue;
        }

        // The item has coordinates but no altitude, create a query.

        LookupAltitude::Request myLookup;
        myLookup.coordinates = coordinates;
        myLookup.data        = QVariant::fromValue(QPersistentModelIndex(currentIndex));

        altitudeQueries << myLookup;
    }

    if (altitudeQueries.isEmpty())
    {
        return;
    }

    d->altitudeLookup = LookupFactory::getAltitudeLookup(QLatin1String("geonames"), this);

    connect(d->altitudeLookup, SIGNAL(signalRequestsReady(QList<int>)),
            this, SLOT(slotAltitudeLookupReady(QList<int>)));

    connect(d->altitudeLookup, SIGNAL(signalDone()),
            this, SLOT(slotAltitudeLookupDone()));

    Q_EMIT signalSetUIEnabled(false, this, QString::fromUtf8(SLOT(slotAltitudeLookupCancel())));

    Q_EMIT signalProgressSetup(altitudeQueries.count(), i18n("Looking up altitudes"));

    d->altitudeUndoCommand    = new GPSUndoCommand();
    d->altitudeRequestedCount = altitudeQueries.count();
    d->altitudeReceivedCount  = 0;
    d->altitudeLookup->addRequests(altitudeQueries);
    d->altitudeLookup->startLookup();
}

void GPSItemListContextMenu::slotAltitudeLookupReady(const QList<int>& readyRequests)
{
    GPSItemModel* const imageModel = d->imagesList->getModel();

    for (const int requestIndex : std::as_const(readyRequests))
    {
        const LookupAltitude::Request myLookup  = d->altitudeLookup->getRequest(requestIndex);
        const QPersistentModelIndex markerIndex = myLookup.data.value<QPersistentModelIndex>();

        if (!markerIndex.isValid())
        {
            continue;
        }

        GPSItemContainer* const gpsItem         = imageModel->itemFromIndex(markerIndex);

        if (!gpsItem)
        {
            continue;
        }

        GPSUndoCommand::UndoInfo undoInfo(markerIndex);
        undoInfo.readOldDataFromItem(gpsItem);

        GPSDataContainer gpsData                = gpsItem->gpsData();
        gpsData.setCoordinates(myLookup.coordinates);
        gpsItem->setGPSData(gpsData);
        undoInfo.readNewDataFromItem(gpsItem);

        d->altitudeUndoCommand->addUndoInfo(undoInfo);
        d->altitudeReceivedCount++;
    }

    Q_EMIT signalProgressChanged(d->altitudeReceivedCount);
}

void GPSItemListContextMenu::slotAltitudeLookupDone()
{
    LookupAltitude::StatusAltitude requestStatus = d->altitudeLookup->getStatus();

    if (requestStatus == LookupAltitude::StatusError)
    {
        const QString errorMessage = i18n("Altitude lookup failed:\n%1", d->altitudeLookup->errorMessage());
        QMessageBox::information(d->imagesList, i18nc("@title:window", "Geolocation Editor"), errorMessage);
    }

    if (d->altitudeReceivedCount > 0)
    {
        // At least some queries returned a result, save the undo command.

        d->altitudeUndoCommand->setText(i18n("Altitude looked up"));

        Q_EMIT signalUndoCommand(d->altitudeUndoCommand);
    }
    else
    {
        delete d->altitudeUndoCommand;
    }

    d->altitudeUndoCommand = nullptr;
    d->altitudeLookup->deleteLater();

    Q_EMIT signalSetUIEnabled(true);
}

void GPSItemListContextMenu::slotAltitudeLookupCancel()
{
    if (d->altitudeLookup)
    {
        d->altitudeLookup->cancel();
    }
}

} // namespace Digikam

#include "moc_gpsitemlistcontextmenu.cpp"