applicationcontroller.cpp 14.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
    Copyright (C) 2018 Volker Krause <vkrause@kde.org>

    This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This program is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU General Public License
15
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
16 17 18
*/

#include "applicationcontroller.h"
19 20 21
#include "logging.h"
#include "pkpassmanager.h"
#include "reservationmanager.h"
22 23

#include <KItinerary/JsonLdDocument>
24
#include <KItinerary/LocationUtil>
25 26
#include <KItinerary/Place>

27
#include <QClipboard>
Volker Krause's avatar
Volker Krause committed
28
#include <QDebug>
29
#include <QDesktopServices>
30
#include <QFile>
31
#include <QGuiApplication>
32
#include <QJsonArray>
33
#include <QMimeData>
34 35 36
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
37 38 39
#include <QUrl>
#include <QUrlQuery>

40 41 42
#ifdef Q_OS_ANDROID
#include <QtAndroid>
#include <QAndroidJniObject>
43 44 45
#else
#include <QGeoPositionInfo>
#include <QGeoPositionInfoSource>
46 47
#endif

48 49
#include <memory>

50 51
using namespace KItinerary;

52
#ifdef Q_OS_ANDROID
53 54 55

#define PERMISSION_CALENDAR QStringLiteral("android.permission.READ_CALENDAR")

56 57 58 59 60 61
static void importReservation(JNIEnv *env, jobject that, jstring data)
{
    Q_UNUSED(that);
    ApplicationController::instance()->importData(env->GetStringUTFChars(data, 0));
}

Nicolas Fella's avatar
Nicolas Fella committed
62 63 64 65 66 67 68
static void importFromIntent(JNIEnv *env, jobject that, jobject data)
{
    Q_UNUSED(that);
    Q_UNUSED(env)
    ApplicationController::instance()->importFromIntent(data);
}

69
static const JNINativeMethod methods[] = {
Nicolas Fella's avatar
Nicolas Fella committed
70 71
    {"importReservation", "(Ljava/lang/String;)V", (void*)importReservation},
    {"importFromIntent", "(Landroid/content/Intent;)V", (void*)importFromIntent}
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
};

Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void*)
{
    static bool initialized = false;
    if (initialized)
        return JNI_VERSION_1_6;
    initialized = true;

    JNIEnv *env = nullptr;
    if (vm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) {
        qCWarning(Log) << "Failed to get JNI environment.";
        return -1;
    }
    jclass cls = env->FindClass("org/kde/itinerary/Activity");
    if (env->RegisterNatives(cls, methods, sizeof(methods) / sizeof(JNINativeMethod)) < 0) {
        qCWarning(Log) << "Failed to register native functions.";
        return -1;
    }

    return JNI_VERSION_1_4;
}
#endif

ApplicationController* ApplicationController::s_instance = nullptr;

98 99
ApplicationController::ApplicationController(QObject* parent)
    : QObject(parent)
100 101 102
#ifdef Q_OS_ANDROID
    , m_activityResultReceiver(this)
#endif
103
{
104
    s_instance = this;
105 106

    connect(QGuiApplication::clipboard(), &QClipboard::dataChanged, this, &ApplicationController::clipboardContentChanged);
107 108 109 110 111
}

ApplicationController::~ApplicationController()
{
    s_instance = nullptr;
112 113
}

114 115 116 117
ApplicationController* ApplicationController::instance()
{
    return s_instance;
}
118

119 120 121 122 123 124 125 126 127 128
void ApplicationController::setReservationManager(ReservationManager* resMgr)
{
    m_resMgr = resMgr;
}

void ApplicationController::setPkPassManager(PkPassManager* pkPassMgr)
{
    m_pkPassMgr = pkPassMgr;
}

129 130 131 132 133 134 135
void ApplicationController::showOnMap(const QVariant &place)
{
    if (place.isNull()) {
        return;
    }

    const auto geo = JsonLdDocument::readProperty(place, "geo").value<GeoCoordinates>();
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    const auto addr = JsonLdDocument::readProperty(place, "address").value<PostalAddress>();

#ifdef Q_OS_ANDROID
    QString intentUri;
    if (geo.isValid()) {
        intentUri = QLatin1String("geo:") + QString::number(geo.latitude())
            + QLatin1Char(',') + QString::number(geo.longitude());
    } else if (!addr.isEmpty()) {
        intentUri = QLatin1String("geo:0,0?q=") + addr.streetAddress() + QLatin1String(", ")
            + addr.postalCode() + QLatin1Char(' ')
            + addr.addressLocality() + QLatin1String(", ")
            + addr.addressCountry();
    } else {
        return;
    }

    const auto activity = QtAndroid::androidActivity();
    if (activity.isValid()) {
154
        activity.callMethod<void>("launchViewIntentFromUri", "(Ljava/lang/String;)V", QAndroidJniObject::fromString(intentUri).object());
155 156 157
    }

#else
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
    if (geo.isValid()) {
        // zoom out further from airports, they are larger and you usually want to go further away from them
        const auto zoom = place.userType() == qMetaTypeId<Airport>() ? 12 : 17;
        QUrl url;
        url.setScheme(QStringLiteral("https"));
        url.setHost(QStringLiteral("www.openstreetmap.org"));
        url.setPath(QStringLiteral("/"));
        const QString fragment = QLatin1String("map=") + QString::number(zoom)
                                    + QLatin1Char('/') + QString::number(geo.latitude())
                                    + QLatin1Char('/') + QString::number(geo.longitude());
        url.setFragment(fragment);
        QDesktopServices::openUrl(url);
        return;
    }

    if (!addr.isEmpty()) {
        QUrl url;
        url.setScheme(QStringLiteral("https"));
        url.setHost(QStringLiteral("www.openstreetmap.org"));
        url.setPath(QStringLiteral("/search"));
        const QString queryString = addr.streetAddress() + QLatin1String(", ")
                                    + addr.postalCode() + QLatin1Char(' ')
                                    + addr.addressLocality() + QLatin1String(", ")
                                    + addr.addressCountry();
        QUrlQuery query;
        query.addQueryItem(QStringLiteral("query"), queryString);
        url.setQuery(query);
        QDesktopServices::openUrl(url);
    }
187
#endif
188
}
Volker Krause's avatar
Volker Krause committed
189

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
bool ApplicationController::canNavigateTo(const QVariant& place)
{
    if (place.isNull()) {
        return false;
    }

    if (JsonLdDocument::readProperty(place, "geo").value<GeoCoordinates>().isValid()) {
        return true;
    }

#ifdef Q_OS_ANDROID
    return !JsonLdDocument::readProperty(place, "address").value<PostalAddress>().isEmpty();
#else
    return false;
#endif
}

Volker Krause's avatar
Volker Krause committed
207 208
void ApplicationController::navigateTo(const QVariant& place)
{
209
    if (place.isNull()) {
Volker Krause's avatar
Volker Krause committed
210 211 212
        return;
    }

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
#ifdef Q_OS_ANDROID
    const auto geo = JsonLdDocument::readProperty(place, "geo").value<GeoCoordinates>();
    const auto addr = JsonLdDocument::readProperty(place, "address").value<PostalAddress>();

    QString intentUri;
    if (geo.isValid()) {
        intentUri = QLatin1String("google.navigation:q=") + QString::number(geo.latitude())
            + QLatin1Char(',') + QString::number(geo.longitude());
    } else if (!addr.isEmpty()) {
        intentUri = QLatin1String("google.navigation:q=") + addr.streetAddress() + QLatin1String(", ")
            + addr.postalCode() + QLatin1Char(' ')
            + addr.addressLocality() + QLatin1String(", ")
            + addr.addressCountry();
    } else {
        return;
    }

    const auto activity = QtAndroid::androidActivity();
    if (activity.isValid()) {
        activity.callMethod<void>("launchViewIntentFromUri", "(Ljava/lang/String;)V", QAndroidJniObject::fromString(intentUri).object());
    }

#else
236 237 238
    if (m_pendingNavigation) {
        return;
    }
Volker Krause's avatar
Volker Krause committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

    if (!m_positionSource) {
        m_positionSource = QGeoPositionInfoSource::createDefaultSource(this);
        if (!m_positionSource) {
            qWarning() << "no geo position info source available";
            return;
        }
    }

    if (m_positionSource->lastKnownPosition().isValid()) {
        navigateTo(m_positionSource->lastKnownPosition(), place);
    } else {
        m_pendingNavigation = connect(m_positionSource, &QGeoPositionInfoSource::positionUpdated,
                                      this, [this, place](const QGeoPositionInfo &pos) {
            navigateTo(pos, place);
        });
        m_positionSource->requestUpdate();
    }
257
#endif
Volker Krause's avatar
Volker Krause committed
258 259
}

260
#ifndef Q_OS_ANDROID
Volker Krause's avatar
Volker Krause committed
261 262
void ApplicationController::navigateTo(const QGeoPositionInfo &from, const QVariant &to)
{
263
    qDebug() << from.coordinate() << from.isValid();
Volker Krause's avatar
Volker Krause committed
264 265 266 267 268
    disconnect(m_pendingNavigation);
    if (!from.isValid()) {
        return;
    }

269
    const auto geo = LocationUtil::geo(to);
Volker Krause's avatar
Volker Krause committed
270 271 272 273 274
    if (geo.isValid()) {
        QUrl url;
        url.setScheme(QStringLiteral("https"));
        url.setHost(QStringLiteral("www.openstreetmap.org"));
        url.setPath(QStringLiteral("/directions"));
Volker Krause's avatar
Volker Krause committed
275 276 277 278 279
        QUrlQuery query;
        query.addQueryItem(QLatin1String("route"),
            QString::number(from.coordinate().latitude()) + QLatin1Char(',') + QString::number(from.coordinate().longitude())
            + QLatin1Char(';') + QString::number(geo.latitude()) + QLatin1Char(',') + QString::number(geo.longitude()));
        url.setQuery(query);
Volker Krause's avatar
Volker Krause committed
280 281 282 283
        QDesktopServices::openUrl(url);
        return;
    }
}
284
#endif
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
void ApplicationController::navigateTo(const QVariant& from, const QVariant& to)
{
#ifdef Q_OS_ANDROID
    // TODO Android can't do this by default, but we can do osmand API calls directly
    Q_UNUSED(from);
    navigateTo(to);
#else
    const auto fromGeo = LocationUtil::geo(from);
    if (!fromGeo.isValid()) {
        navigateTo(to);
        return;
    }

    const auto toGeo = LocationUtil::geo(to);
    if (!toGeo.isValid()) {
        return;
    }

    QUrl url;
    url.setScheme(QStringLiteral("https"));
    url.setHost(QStringLiteral("www.openstreetmap.org"));
    url.setPath(QStringLiteral("/directions"));
    QUrlQuery query;
    query.addQueryItem(QLatin1String("route"),
        QString::number(fromGeo.latitude()) + QLatin1Char(',') + QString::number(fromGeo.longitude())
        + QLatin1Char(';') + QString::number(toGeo.latitude()) + QLatin1Char(',') + QString::number(toGeo.longitude()));
    url.setQuery(query);
    QDesktopServices::openUrl(url);
#endif
}

317
#ifdef Q_OS_ANDROID
318 319 320 321 322 323 324 325 326 327 328
void ApplicationController::importFromIntent(const QAndroidJniObject &intent)
{
    if (!intent.isValid()) {
        return;
    }

    const auto uri = intent.callObjectMethod("getData", "()Landroid/net/Uri;");
    if (!uri.isValid()) {
        return;
    }

329 330
    const auto uriStr = uri.callObjectMethod("toString", "()Ljava/lang/String;");
    importFromUrl(QUrl(uriStr.toString()));
331 332 333 334 335 336 337 338 339
}

void ApplicationController::ActivityResultReceiver::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &intent)
{
    qCDebug(Log) << receiverRequestCode << resultCode;
    m_controller->importFromIntent(intent);
}
#endif

Volker Krause's avatar
Volker Krause committed
340
void ApplicationController::showImportFileDialog()
341 342 343 344 345 346 347 348 349 350
{
#ifdef Q_OS_ANDROID
    const auto ACTION_OPEN_DOCUMENT = QAndroidJniObject::getStaticObjectField<jstring>("android/content/Intent", "ACTION_OPEN_DOCUMENT");
    QAndroidJniObject intent("android/content/Intent", "(Ljava/lang/String;)V", ACTION_OPEN_DOCUMENT.object());
    const auto CATEGORY_OPENABLE = QAndroidJniObject::getStaticObjectField<jstring>("android/content/Intent", "CATEGORY_OPENABLE");
    intent.callObjectMethod("addCategory", "(Ljava/lang/String;)Landroid/content/Intent;", CATEGORY_OPENABLE.object());
    intent.callObjectMethod("setType", "(Ljava/lang/String;)Landroid/content/Intent;", QAndroidJniObject::fromString(QStringLiteral("*/*")).object());
    QtAndroid::startActivity(intent, 0, &m_activityResultReceiver);
#endif
}
351

352 353 354 355
void ApplicationController::importFromClipboard()
{
    if (QGuiApplication::clipboard()->mimeData()->hasUrls()) {
        const auto urls = QGuiApplication::clipboard()->mimeData()->urls();
Volker Krause's avatar
Volker Krause committed
356
        for (const auto &url : urls)
357
            importFromUrl(url);
358
        return;
359 360 361
    }

    if (QGuiApplication::clipboard()->mimeData()->hasText()) {
362 363
        const auto content = QGuiApplication::clipboard()->mimeData()->data(QLatin1String("text/plain"));
        importData(content);
364 365 366
    }
}

367 368 369
void ApplicationController::importFromUrl(const QUrl &url)
{
    qCDebug(Log) << url;
370 371
    if (url.isLocalFile() || url.scheme() == QLatin1String("content")) {
        importLocalFile(url);
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
        return;
    }

    if (url.scheme().startsWith(QLatin1String("http"))) {
        if (!m_nam ) {
            m_nam = new QNetworkAccessManager(this);
        }
        auto reqUrl(url);
        reqUrl.setScheme(QLatin1String("https"));
        QNetworkRequest req(reqUrl);
        req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
        auto reply = m_nam->get(req);
        connect(reply, &QNetworkReply::finished, this, [this, reply]() {
            if (reply->error() != QNetworkReply::NoError) {
                qCDebug(Log) << reply->url() << reply->errorString();
                return;
            }
            importData(reply->readAll());
        });
        return;
    }

    qCDebug(Log) << "Unhandled URL type:" << url;
}

397
void ApplicationController::importLocalFile(const QUrl &url)
398
{
399
    qCDebug(Log) << url;
400
    if (url.isEmpty()) {
401
        return;
402
    }
403

404
    QFile f(url.isLocalFile() ? url.toLocalFile() : url.toString());
405
    if (!f.open(QFile::ReadOnly)) {
406
        qCWarning(Log) << "Failed to open" << f.fileName() << f.errorString();
407 408
        return;
    }
409 410 411 412
    if (f.size() > 4000000) {
        qCWarning(Log) << "File too large, ignoring" << f.fileName() << f.size();
        return;
    }
413

414 415
    const auto head = f.peek(4);
    if (url.fileName().endsWith(QLatin1String(".pkpass"), Qt::CaseInsensitive) || strncmp(head.constData(), "PK\x03\x04", 4) == 0) {
416 417 418
        m_pkPassMgr->importPass(url);
    } else {
        m_resMgr->importReservation(f.readAll(), f.fileName());
419 420
    }
}
421

422 423
void ApplicationController::importData(const QByteArray &data)
{
424
    qCDebug(Log);
425
    if (data.size() < 4) {
426
        return;
427 428 429 430 431 432
    }
    if (strncmp(data.constData(), "PK\x03\x04", 4) == 0) {
        m_pkPassMgr->importPassFromData(data);
    } else {
        m_resMgr->importReservation(data);
    }
433 434
}

435 436 437
void ApplicationController::checkCalendar()
{
#ifdef Q_OS_ANDROID
438 439 440 441 442 443 444 445 446 447 448 449

    if (QtAndroid::checkPermission(PERMISSION_CALENDAR) == QtAndroid::PermissionResult::Granted) {
        const auto activity = QtAndroid::androidActivity();
        if (activity.isValid()) {
            activity.callMethod<void>("checkCalendar");
        }
    } else {
        QtAndroid::requestPermissions({PERMISSION_CALENDAR}, [this] (const QtAndroid::PermissionResultMap &result){
            if (result[PERMISSION_CALENDAR] == QtAndroid::PermissionResult::Granted) {
                checkCalendar();
            }
        });
450 451 452
    }
#endif
}
453 454 455

bool ApplicationController::hasClipboardContent() const
{
456
    return QGuiApplication::clipboard()->mimeData()->hasText() || QGuiApplication::clipboard()->mimeData()->hasUrls();
457
}