1/*
2 SPDX-FileCopyrightText: 2021 Volker Krause <vkrause@kde.org>
3 SPDX-License-Identifier: LGPL-2.0-or-later
4*/
5
6#include "kgeourihandler_p.h"
7
8#include <QUrl>
9#include <QUrlQuery>
10
11void KGeoUriHandler::setCoordinateTemplate(const QString &coordTmpl)
12{
13 m_coordTmpl = coordTmpl;
14}
15
16void KGeoUriHandler::setQueryTemplate(const QString &queryTmpl)
17{
18 m_queryTmpl = queryTmpl;
19}
20
21void KGeoUriHandler::setFallbackUrl(const QString &fallbackUrl)
22{
23 m_fallbackUrl = fallbackUrl;
24}
25
26static bool isValidCoordinate(double c, double limit)
27{
28 return c != 0.0 && c >= -limit && c <= limit;
29}
30
31QString KGeoUriHandler::handleUri(const QUrl &geoUri)
32{
33 const auto pathElems = geoUri.path().split(sep: QLatin1Char(';'));
34 const auto coordElems = pathElems.isEmpty() ? QStringList() : pathElems.at(i: 0).split(sep: QLatin1Char(','));
35
36 const auto lat = coordElems.size() < 2 ? 0.0 : coordElems.at(i: 0).toDouble();
37 const auto lon = coordElems.size() < 2 ? 0.0 : coordElems.at(i: 1).toDouble();
38
39 const auto geoQuery = QUrlQuery(geoUri.query());
40 const auto query = geoQuery.queryItemValue(QStringLiteral("q"));
41
42 bool zoomValid = false;
43 int zoom = geoQuery.queryItemValue(QStringLiteral("z")).toInt(ok: &zoomValid);
44 if (!zoomValid || zoom < 0 || zoom > 21) {
45 zoom = 18;
46 }
47
48 // unsupported coordinate reference system
49 if (!pathElems.isEmpty() && std::any_of(first: pathElems.begin() + 1, last: pathElems.end(), pred: [](const auto &elem) {
50 return elem.startsWith(QLatin1String("crs="), Qt::CaseInsensitive) && !elem.endsWith(QLatin1String("=wgs84"), Qt::CaseInsensitive);
51 })) {
52 return m_fallbackUrl;
53 }
54
55 QString tmpl;
56 if (!query.isEmpty()) {
57 tmpl = m_queryTmpl;
58 } else if (isValidCoordinate(c: lat, limit: 90.0) && isValidCoordinate(c: lon, limit: 180.0)) {
59 tmpl = m_coordTmpl;
60 } else {
61 return m_fallbackUrl;
62 }
63
64 tmpl.replace(before: QLatin1String("<LAT>"), after: QString::number(lat));
65 tmpl.replace(before: QLatin1String("<LON>"), after: QString::number(lon));
66 tmpl.replace(before: QLatin1String("<Q>"), after: query);
67 tmpl.replace(before: QLatin1String("<Z>"), after: QString::number(zoom));
68 return tmpl;
69}
70

source code of kguiaddons/src/geo-scheme-handler/kgeourihandler.cpp