Debian Codegraph @

core/tests/geolocation/geoiface/demo/mainwindow.cpp

raw symbols SCIP
1 /* ============================================================
2 *
3 * This file is a part of digiKam project
4 * https://www.digikam.org
5 *
6 * Date : 2009-12-01
7 * Description : main-window of the demo application
8 *
9 * SPDX-FileCopyrightText: 2009-2010 by Michael G. Hansen <mike at mghansen dot de>
10 * SPDX-FileCopyrightText: 2014 by Justus Schwartz <justus at gmx dot li>
11 *
12 * SPDX-License-Identifier: GPL-2.0-or-later
13 *
14 * ============================================================ */
15
16 #include "mainwindow.h"
17
18 // Qt includes
19
20 #include <QAction>
21 #include <QStandardItemModel>
22 #include <QCloseEvent>
23 #include <QComboBox>
24 #include <QFuture>
25 #include <QFutureWatcher>
26 #include <QHBoxLayout>
27 #include <QLabel>
28 #include <QPushButton>
29 #include <QSplitter>
30 #include <QTimer>
31 #include <QTreeWidget>
32 #include <QVBoxLayout>
33 #include <QtConcurrentMap>
34 #include <QCommandLineParser>
35 #include <QMenuBar>
36 #include <QStatusBar>
37 #include <QPointer>
38 #include <QScopedPointer>
39 #include <QProgressBar>
40
41 // KDE includes
42
43 #include <kconfig.h>
44 #include <kconfiggroup.h>
45
46 // Local includes
47
48 #include "digikam_debug.h"
49 #include "dmetadata.h"
50 #include "lookupaltitude.h"
51 #include "lookupfactory.h"
52 #include "mapwidget.h"
53 #include "itemmarkertiler.h"
54 #include "geoifacecommon.h"
55 #include "mydragdrophandler.h"
56 #include "mytreewidget.h"
57 #include "myimageitem.h"
58 #include "dfiledialog.h"
59 #include "actionthreadbase.h"
60
61 using namespace Digikam;
62
63 MarkerModelHelper::MarkerModelHelper(QAbstractItemModel* const itemModel,
64 QItemSelectionModel* const itemSelectionModel)
65 : GeoModelHelper (itemModel),
66 m_itemModel (itemModel),
67 m_itemSelectionModel(itemSelectionModel)
68 {
69 connect(itemModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
70 this, SIGNAL(signalModelChangedDrastically()));
71 }
72
73 MarkerModelHelper::~MarkerModelHelper()
74 {
75 }
76
77 QAbstractItemModel* MarkerModelHelper::model() const
78 {
79 return m_itemModel;
80 }
81
82 QItemSelectionModel* MarkerModelHelper::selectionModel() const
83 {
84 return m_itemSelectionModel;
85 }
86
87 bool MarkerModelHelper::itemCoordinates(const QModelIndex& index,
88 GeoCoordinates* const coordinates) const
89 {
90 if (!index.data(RoleCoordinates).canConvert<GeoCoordinates>())
91 {
92 return false;
93 }
94
95 if (coordinates)
96 {
97 *coordinates = index.data(RoleCoordinates).value<GeoCoordinates>();
98 }
99
100 return true;
101 }
102
103 void MarkerModelHelper::onIndicesMoved(const QList<QPersistentModelIndex>& movedIndices,
104 const GeoCoordinates& targetCoordinates,
105 const QPersistentModelIndex& targetSnapIndex)
106 {
107 Q_UNUSED(targetSnapIndex);
108
109 for (int i = 0; i < movedIndices.count(); ++i)
110 {
111 m_itemModel->setData(movedIndices.at(i),
112 QVariant::fromValue(targetCoordinates), RoleCoordinates);
113 }
114
115 Q_EMIT signalMarkersMoved(movedIndices);
116 }
117
118 // ----------------------------------------------------------------------
119
120 class Q_DECL_HIDDEN MyImageData
121 {
122 public:
123
124 GeoCoordinates coordinates;
125 QUrl url;
126 };
127
128 // ----------------------------------------------------------------------
129
130 MyTrackModelHelper::MyTrackModelHelper(QAbstractItemModel* const imageItemsModel)
131 : QObject (imageItemsModel),
132 m_itemModel(imageItemsModel)
133 {
134 connect(imageItemsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
135 this, SLOT(slotTrackModelChanged()));
136
137 connect(imageItemsModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
138 this, SLOT(slotTrackModelChanged()));
139
140 connect(imageItemsModel, SIGNAL(modelReset()),
141 this, SLOT(slotTrackModelChanged()));
142 }
143
144 void MyTrackModelHelper::slotTrackModelChanged()
145 {
146 m_tracks.clear();
147
148 TrackManager::Track track;
149
150 for (int row = 0; row < m_itemModel->rowCount(); ++row)
151 {
152 const QModelIndex currentIndex = m_itemModel->index(row, 0);
153
154 if (!currentIndex.data(RoleCoordinates).canConvert<GeoCoordinates>())
155 {
156 continue;
157 }
158
159 const GeoCoordinates markerCoordinates = currentIndex.data(RoleCoordinates).value<GeoCoordinates>();
160 TrackManager::TrackPoint trackPoint;
161 trackPoint.coordinates = markerCoordinates;
162 track.points << trackPoint;
163 }
164
165 m_tracks << track;
166
167 Q_EMIT signalModelChanged();
168 }
169
170 TrackManager::Track::List MyTrackModelHelper::getTracks() const
171 {
172 return m_tracks;
173 }
174
175 // ----------------------------------------------------------------------
176
177 MyImageData s_loadImageData(const QUrl& urlToLoad)
178 {
179 ActionThreadBase::setCurrentThreadName(QLatin1String(__FUNCTION__)); // To customize thread name
180
181 MyImageData imageData;
182 imageData.url = urlToLoad;
183
184 // TODO: error handling!
185
186 QScopedPointer<DMetadata> meta(new DMetadata);
187 meta->load(urlToLoad.toLocalFile());
188 double lat = 0.0, lon = 0.0, alt = 0.0;
189
190 if (meta->getGPSInfo(alt, lat, lon))
191 {
192 imageData.coordinates.setLatLon(lat, lon);
193 imageData.coordinates.setAlt(alt);
194 }
195
196 return imageData;
197 }
198
199 // ----------------------------------------------------------------------
200
201 class Q_DECL_HIDDEN MainWindow::Private
202 {
203 public:
204
205 explicit Private()
206 : splitter (nullptr),
207 mapWidget (nullptr),
208 lookupAltitudeList (),
209 treeWidget (nullptr),
210 progressBar (nullptr),
211 imageLoadingRunningFutures (),
212 imageLoadingFutureWatchers (),
213 imageLoadingTotalCount (0),
214 imageLoadingCurrentCount (0),
215 imageLoadingBuncher (),
216 imageLoadingBunchTimer (nullptr),
217 cmdLineArgs (nullptr),
218 lastImageOpenDir (),
219 displayMarkersModel (nullptr),
220 selectionModel (nullptr),
221 markerModelHelper (nullptr),
222 trackModelHelper (nullptr)
223 {
224 }
225
226 public:
227
228 QSplitter* splitter;
229 MapWidget* mapWidget;
230 QList<LookupAltitude*> lookupAltitudeList;
231 MyTreeWidget* treeWidget;
232 QPointer<QProgressBar> progressBar;
233 QList<QFuture<MyImageData> > imageLoadingRunningFutures;
234 QList<QFutureWatcher<MyImageData>*> imageLoadingFutureWatchers;
235 int imageLoadingTotalCount;
236 int imageLoadingCurrentCount;
237 QList<MyImageData> imageLoadingBuncher;
238 QTimer* imageLoadingBunchTimer;
239 QCommandLineParser* cmdLineArgs;
240 QUrl lastImageOpenDir;
241
242 QAbstractItemModel* displayMarkersModel;
243 QItemSelectionModel* selectionModel;
244 MarkerModelHelper* markerModelHelper;
245 MyTrackModelHelper* trackModelHelper;
246 };
247
248 MainWindow::MainWindow(QCommandLineParser* const cmdLineArgs, QWidget* const parent)
249 : QMainWindow(parent),
250 d (new Private)
251 {
252 // initialize Exiv2 before doing any multitasking
253
254 MetaEngine::initializeExiv2();
255
256 d->treeWidget = new MyTreeWidget(this);
257 d->treeWidget->setColumnCount(2);
258 d->treeWidget->setHeaderLabels(QStringList() << QLatin1String("Filename") << QLatin1String("Coordinates"));
259 d->treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
260
261 d->displayMarkersModel = d->treeWidget->model();
262 d->selectionModel = d->treeWidget->selectionModel();
263 d->markerModelHelper = new MarkerModelHelper(d->displayMarkersModel, d->selectionModel);
264 d->trackModelHelper = new MyTrackModelHelper(d->treeWidget->model());
265 ItemMarkerTiler* const mm = new ItemMarkerTiler(d->markerModelHelper, this);
266
267 resize(512, 512);
268 setWindowTitle(QLatin1String("Geolocation Interface Demo"));
269 setWindowIcon(QIcon::fromTheme(QLatin1String("globe")));
270 setObjectName(QLatin1String("DemoGeoLocationInterface" ));
271
272 d->cmdLineArgs = cmdLineArgs;
273
274 d->imageLoadingBunchTimer = new QTimer(this);
275 d->imageLoadingBunchTimer->setSingleShot(false);
276
277 connect(d->imageLoadingBunchTimer, SIGNAL(timeout()),
278 this, SLOT(slotImageLoadingBunchReady()));
279
280 // create a status bar:
281
282 statusBar();
283 createMenus();
284
285 d->splitter = new QSplitter(Qt::Vertical, this);
286 setCentralWidget(d->splitter);
287
288 d->mapWidget = new MapWidget(d->splitter);
289 d->mapWidget->setGroupedModel(mm);
290 d->mapWidget->setActive(true);
291 d->mapWidget->setDragDropHandler(new MyDragDropHandler(d->displayMarkersModel, d->mapWidget));
292 d->mapWidget->setVisibleMouseModes(MouseModePan|MouseModeZoomIntoGroup|MouseModeSelectThumbnail);
293 d->mapWidget->setAvailableMouseModes(MouseModePan|MouseModeZoomIntoGroup|MouseModeSelectThumbnail);
294 // d->mapWidget->setTrackModel(d->trackModelHelper);
295
296 connect(d->markerModelHelper, SIGNAL(signalMarkersMoved(QList<QPersistentModelIndex>)),
297 this, SLOT(slotMarkersMoved(QList<QPersistentModelIndex>)));
298
299 // d->mapWidget->resize(d->mapWidget->width(), 200);
300 d->splitter->addWidget(d->mapWidget);
301 d->splitter->setCollapsible(0, false);
302 d->splitter->setSizes(QList<int>()<<200);
303 d->splitter->setStretchFactor(0, 10);
304
305 QWidget* const dummyWidget = new QWidget(this);
306 QVBoxLayout* const vbox = new QVBoxLayout(dummyWidget);
307
308 vbox->addWidget(d->mapWidget->getControlWidget());
309 vbox->addWidget(d->treeWidget);
310
311 d->progressBar = new QProgressBar();
312 d->progressBar->setFormat(QLatin1String("Loading images -"));
313
314 d->splitter->addWidget(dummyWidget);
315
316 readSettings();
317
318 GeoCoordinates::List markerList;
319
320 // ice cafe
321 markerList<<GeoCoordinates::fromGeoUrl(QLatin1String("geo:51.0913031421,6.88878178596,44" ));
322
323 // bar
324 markerList<<GeoCoordinates::fromGeoUrl(QLatin1String("geo:51.06711205,6.90020261667,43" ));
325
326 // Marienburg castle
327 markerList<<GeoCoordinates::fromGeoUrl(QLatin1String("geo:51.087647318,6.88282728201,44" ));
328
329 // head of monster
330 markerList<<GeoCoordinates::fromGeoUrl(QLatin1String("geo:51.0889433167,6.88000331667,39.6" ));
331
332 // Langenfeld
333 markerList<<GeoCoordinates::fromGeoUrl(QLatin1String("geo:51.1100157609,6.94911003113,51" ));
334
335 // Sagrada Familia in Spain
336 markerList<<GeoCoordinates::fromGeoUrl(QLatin1String("geo:41.4036480511,2.1743756533,46" ));
337
338 if (cmdLineArgs->isSet(QLatin1String("demopoints_single")) ||
339 cmdLineArgs->isSet(QLatin1String("demopoints_group")))
340 {
341 for (int i = 0 ; i < markerList.count() ; ++i)
342 {
343 QTreeWidgetItem* const treeItem = new QTreeWidgetItem();
344 treeItem->setText(0, QString::fromLatin1("item %1").arg(i));
345 treeItem->setText(1, markerList.at(i).geoUrl());
346
347 d->treeWidget->addTopLevelItem(treeItem);
348 }
349 }
350 }
351
352 MainWindow::~MainWindow()
353 {
354 if (d->progressBar)
355 {
356 delete d->progressBar;
357 }
358
359 delete d;
360 }
361
362 void MainWindow::readSettings()
363 {
364 KConfig config( QLatin1String("wmw-demo-1" ));
365
366 const KConfigGroup groupWidgetConfig = config.group(QLatin1String("WidgetConfig"));
367 d->mapWidget->readSettingsFromGroup(&groupWidgetConfig);
368
369 KConfigGroup groupMainWindowConfig = config.group(QLatin1String("MainWindowConfig"));
370 d->lastImageOpenDir = groupMainWindowConfig.readEntry("Last Image Open Directory", QUrl());
371
372 if (groupMainWindowConfig.hasKey("SplitterState"))
373 {
374 const QByteArray splitterState = QByteArray::fromBase64(groupMainWindowConfig.readEntry(QLatin1String("SplitterState"), QByteArray()));
375
376 if (!splitterState.isEmpty())
377 {
378 d->splitter->restoreState(splitterState);
379 }
380 }
381 }
382
383 void MainWindow::saveSettings()
384 {
385 KConfig config( QLatin1String("wmw-demo-1" ));
386
387 KConfigGroup groupWidgetConfig = config.group(QLatin1String("WidgetConfig"));
388 d->mapWidget->saveSettingsToGroup(&groupWidgetConfig);
389
390 KConfigGroup groupMainWindowConfig = config.group(QLatin1String("MainWindowConfig"));
391 groupMainWindowConfig.writeEntry("Last Image Open Directory", d->lastImageOpenDir.toLocalFile());
392 groupMainWindowConfig.writeEntry(QLatin1String("SplitterState"), d->splitter->saveState().toBase64());
393 }
394
395 void MainWindow::closeEvent(QCloseEvent* e)
396 {
397 if (!e)
398 {
399 return;
400 }
401
402 saveSettings();
403 e->accept();
404 }
405
406
407 void MainWindow::slotFutureResultsReadyAt(int startIndex, int endIndex)
408 {
409 // //qCDebug(DIGIKAM_TESTS_LOG)<<"future"<<startIndex<<endIndex;
410
411 // determine the sender:
412 const QFutureWatcher<MyImageData>* const futureSender = reinterpret_cast<QFutureWatcher<MyImageData>*>(sender());
413
414 GEOIFACE_ASSERT(futureSender != nullptr);
415
416 if (futureSender == nullptr)
417 {
418 return;
419 }
420
421 int futureIndex = -1;
422
423 for (int i = 0; i < d->imageLoadingFutureWatchers.size(); ++i)
424 {
425 if (d->imageLoadingFutureWatchers.at(i) == futureSender)
426 {
427 futureIndex = i;
428 break;
429 }
430 }
431
432 GEOIFACE_ASSERT(futureIndex >= 0);
433
434 if (futureIndex < 0)
435 {
436 // TODO: error!
437 return;
438 }
439
440 for (int index = startIndex; index < endIndex; ++index)
441 {
442 MyImageData newData = d->imageLoadingRunningFutures.at(futureIndex).resultAt(index);
443 // //qCDebug(DIGIKAM_TESTS_LOG)<<"future"<<newData.url<<newData.coordinates.geoUrl();
444
445 d->imageLoadingBuncher << newData;
446 }
447
448 d->imageLoadingCurrentCount+= endIndex-startIndex;
449
450 if (d->imageLoadingCurrentCount < d->imageLoadingTotalCount)
451 {
452 d->progressBar->setValue(d->imageLoadingCurrentCount);
453 }
454 else
455 {
456 statusBar()->removeWidget(d->progressBar);
457 statusBar()->showMessage(QLatin1String("%1 image(s) have been loaded.", d->imageLoadingTotalCount), 3000);
458 d->imageLoadingCurrentCount = 0;
459 d->imageLoadingTotalCount = 0;
460
461 // remove the QFutures:
462 qDeleteAll(d->imageLoadingFutureWatchers);
463 d->imageLoadingFutureWatchers.clear();
464 d->imageLoadingRunningFutures.clear();
465
466 d->imageLoadingBunchTimer->stop();
467
468 // force display of all images:
469 QTimer::singleShot(0, this, SLOT(slotImageLoadingBunchReady()));;
470 }
471 }
472
473 void MainWindow::slotScheduleImagesForLoading(const QList<QUrl>& imagesToSchedule)
474 {
475 if (imagesToSchedule.isEmpty())
476 {
477 return;
478 }
479
480 if (d->imageLoadingTotalCount == 0)
481 {
482 statusBar()->addWidget(d->progressBar);
483 d->imageLoadingBunchTimer->start(100);
484 }
485
486 d->imageLoadingTotalCount+=imagesToSchedule.count();
487 d->progressBar->setRange(0, d->imageLoadingTotalCount);
488 d->progressBar->setValue(d->imageLoadingCurrentCount);
489 QFutureWatcher<MyImageData>* const watcher = new QFutureWatcher<MyImageData>(this);
490
491 connect(watcher, SIGNAL(resultsReadyAt(int,int)),
492 this, SLOT(slotFutureResultsReadyAt(int,int)));
493
494 QFuture<MyImageData> future = QtConcurrent::mapped(imagesToSchedule, s_loadImageData);
495 watcher->setFuture(future);
496
497 d->imageLoadingRunningFutures << future;
498 d->imageLoadingFutureWatchers << watcher;
499 }
500
501 void MainWindow::slotImageLoadingBunchReady()
502 {
503 qCDebug(DIGIKAM_TESTS_LOG) << "slotImageLoadingBunchReady";
504
505 for (int i = 0; i < d->imageLoadingBuncher.count(); ++i)
506 {
507 const MyImageData& currentInfo = d->imageLoadingBuncher.at(i);
508
509 // add the item to the tree widget:
510 QTreeWidgetItem* const treeItem = new MyImageItem(currentInfo.url, currentInfo.coordinates);
511 d->treeWidget->addTopLevelItem(treeItem);
512 }
513
514 d->imageLoadingBuncher.clear();
515
516 if (d->imageLoadingTotalCount == 0)
517 {
518 // remove the QFutures:
519 qDeleteAll(d->imageLoadingFutureWatchers);
520 d->imageLoadingFutureWatchers.clear();
521 d->imageLoadingRunningFutures.clear();
522 }
523 }
524
525 void MainWindow::slotMarkersMoved(const QList<QPersistentModelIndex>& markerIndices)
526 {
527 // prepare altitude lookups
528 LookupAltitude::Request::List altitudeQueries;
529
530 for (int i = 0; i < markerIndices.count(); ++i)
531 {
532 const QPersistentModelIndex currentIndex = markerIndices.at(i);
533 const GeoCoordinates newCoordinates = currentIndex.data(RoleCoordinates).value<GeoCoordinates>();
534
535 LookupAltitude::Request myLookup;
536 myLookup.coordinates = newCoordinates;
537 myLookup.data = QVariant::fromValue(QPersistentModelIndex(currentIndex));
538 altitudeQueries << myLookup;
539 }
540
541 if (!altitudeQueries.isEmpty())
542 {
543 LookupAltitude* const myAltitudeLookup = LookupFactory::getAltitudeLookup(QLatin1String("geonames"), this);
544
545 connect(myAltitudeLookup, SIGNAL(signalRequestsReady(QList<int>)),
546 this, SLOT(slotAltitudeRequestsReady(QList<int>)));
547
548 connect(myAltitudeLookup, SIGNAL(signalDone()),
549 this, SLOT(slotAltitudeLookupDone()));
550
551 myAltitudeLookup->addRequests(altitudeQueries);
552
553 d->lookupAltitudeList << myAltitudeLookup;
554
555 /// @todo Check the return value?
556 myAltitudeLookup->startLookup();
557 qCDebug(DIGIKAM_TESTS_LOG) << "Starting lookup for " << altitudeQueries.count() << " items!";
558 }
559 }
560
561 void MainWindow::slotAltitudeRequestsReady(const QList<int>& readyRequests)
562 {
563 qCDebug(DIGIKAM_TESTS_LOG) << readyRequests.count() << " items ready!";
564
565 const LookupAltitude* const myAltitudeLookup = qobject_cast<LookupAltitude*>(sender());
566
567 if (!myAltitudeLookup)
568 {
569 return;
570 }
571
572 for (int i = 0; i < readyRequests.count(); ++i)
573 {
574 const LookupAltitude::Request& myLookup = myAltitudeLookup->getRequest(readyRequests.at(i));
575 const QPersistentModelIndex markerIndex = myLookup.data.value<QPersistentModelIndex>();
576
577 if (!markerIndex.isValid())
578 {
579 continue;
580 }
581
582 /// @todo Why does the index return a const model???
583 const QAbstractItemModel* const itemModel = markerIndex.model();
584 const_cast<QAbstractItemModel*>(itemModel)->setData(markerIndex, QVariant::fromValue(myLookup.coordinates), RoleCoordinates);
585 }
586 }
587
588 void MainWindow::slotAltitudeLookupDone()
589 {
590 LookupAltitude* const myAltitudeLookup = qobject_cast<LookupAltitude*>(sender());
591
592 if (!myAltitudeLookup)
593 {
594 return;
595 }
596
597 d->lookupAltitudeList.removeOne(myAltitudeLookup);
598 myAltitudeLookup->deleteLater();
599 }
600
601 void MainWindow::slotAddImages()
602 {
603 const QList<QUrl> fileNames = DFileDialog::getOpenFileUrls(this, QLatin1String("Add image files"), d->lastImageOpenDir, QLatin1String("Images (*.jpg *.jpeg *.png *.tif *.tiff)"));
604
605 if (fileNames.isEmpty())
606 {
607 return;
608 }
609
610 d->lastImageOpenDir = fileNames.first().resolved(QUrl(QLatin1String("../")));
611
612 slotScheduleImagesForLoading(fileNames);
613 }
614
615 void MainWindow::createMenus()
616 {
617 QMenu* const fileMenu = menuBar()->addMenu(QLatin1String("File"));
618 QAction* const addFilesAction = new QAction(QLatin1String("Add images..."), fileMenu);
619 fileMenu->addAction(addFilesAction);
620
621 connect(addFilesAction, SIGNAL(triggered()),
622 this, SLOT(slotAddImages()));
623 }
624
625 GeoModelHelper::PropertyFlags MarkerModelHelper::modelFlags() const
626 {
627 return FlagMovable;
628 }
629
630 #include "moc_mainwindow.cpp"