summaryrefslogtreecommitdiffstats
path: root/src/plugins/platforms/android/qandroidplatformservices.cpp
blob: dea73d800ea9424e8eda7cd64b615c2b955efcf7 (plain)
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
// Copyright (C) 2012 BogDan Vatra <bogdan@kde.org>
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qandroidplatformservices.h"

#if QT_CONFIG(desktopservices)
#include <QDebug>
#include <QDesktopServices>
#include <QFile>
#include <QMimeDatabase>
#include <QtCore/QJniObject>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qscopedvaluerollback.h>
#endif

QT_BEGIN_NAMESPACE

using namespace QtJniTypes;
using namespace Qt::StringLiterals;

#if QT_CONFIG(desktopservices)
static constexpr auto s_defaultScheme = "file"_L1;
static constexpr auto s_defaultProvider = "qtprovider"_L1;
#endif

QAndroidPlatformServices::QAndroidPlatformServices()
{
#if QT_CONFIG(desktopservices)
    m_actionView = QJniObject::getStaticObjectField("android/content/Intent", "ACTION_VIEW",
                                                    "Ljava/lang/String;")
                           .toString();

    QtAndroidPrivate::registerNewIntentListener(this);

    // Qt applications without Activity contexts cannot retrieve intents from the Activity.
    if (QNativeInterface::QAndroidApplication::isActivityContext()) {
        QMetaObject::invokeMethod(
                this,
                [this] {
                    QJniObject context = QJniObject(QtAndroidPrivate::context());
                    QJniObject intent =
                            context.callObjectMethod("getIntent", "()Landroid/content/Intent;");
                    handleNewIntent(nullptr, intent.object());
                },
                Qt::QueuedConnection);
    }
#endif // QT_CONFIG(desktopservices)
}

QByteArray QAndroidPlatformServices::desktopEnvironment() const
{
    return QByteArray("Android");
}

Q_DECLARE_JNI_CLASS(FileProvider, "androidx/core/content/FileProvider");
Q_DECLARE_JNI_CLASS(PackageManager, "android/content/pm/PackageManager");
Q_DECLARE_JNI_CLASS(PackageInfo, "android/content/pm/PackageInfo");
Q_DECLARE_JNI_CLASS(ProviderInfo, "android/content/pm/ProviderInfo");

#if QT_CONFIG(desktopservices)
bool QAndroidPlatformServices::openUrl(const QUrl &theUrl)
{
    QUrl url(theUrl);

    // avoid recursing back into self
    if (url == m_handlingUrl)
        return false;

    // a real URL including the scheme is needed, else the Intent can not be started
    if (url.scheme().isEmpty())
        url.setScheme(s_defaultScheme);

    const int sdkVersion = QNativeInterface::QAndroidApplication::sdkVersion();
    if (url.scheme() != s_defaultScheme || sdkVersion < 24 )
        return openURL(url);
    return openUrlWithFileProvider(url);
}

QString QAndroidPlatformServices::getMimeOfUrl(const QUrl &url) const
{
    QString mime;
    if (url.scheme() == s_defaultScheme)
        mime = QMimeDatabase().mimeTypeForUrl(url).name();
    return mime;
}

bool QAndroidPlatformServices::openURL(const QUrl &url) const
{
    return  openURL(url.toString());
}

bool QAndroidPlatformServices::openURL(const QString &url) const
{
    return  QJniObject::callStaticMethod<jboolean>(
            QtAndroid::applicationClass(), "openURL",
            QNativeInterface::QAndroidApplication::context(),
            url,
            getMimeOfUrl(url));
}

bool QAndroidPlatformServices::openUrlWithFileProvider(const QUrl &url)
{
    const QJniObject context = QNativeInterface::QAndroidApplication::context();
    auto authorities = getFileProviderAuthorities(context);
    if (authorities.isEmpty())
        return false;
    return openUrlWithAuthority(url, getAdequateFileproviderAuthority(authorities));
}


QString QAndroidPlatformServices::getAdequateFileproviderAuthority(const QStringList &authorities) const
{
    if (authorities.size() == 1)
        return authorities[0];

    QString nonQtAuthority;
    for (const auto &authority : authorities) {
        if (!authority.endsWith(s_defaultProvider, Qt::CaseSensitive)) {
            nonQtAuthority = authority;
            break;
        }
    }
    return nonQtAuthority;
}

bool QAndroidPlatformServices::openUrlWithAuthority(const QUrl &url, const QString &authority)
{
    const auto urlPath = QJniObject::fromString(url.path());
    const auto urlFile = QJniObject(Traits<File>::className(),
                                    urlPath.object<jstring>());
    const auto fileProviderUri = QJniObject::callStaticMethod<Uri>(
            Traits<FileProvider>::className(), "getUriForFile",
            QNativeInterface::QAndroidApplication::context(), authority,
            urlFile.object<File>());
    if (fileProviderUri.isValid())
        return openURL(fileProviderUri.toString());
    return false;
}

QStringList QAndroidPlatformServices::getFileProviderAuthorities(const QJniObject &context) const
{
    QStringList authorityList;

    const auto packageManager = context.callMethod<PackageManager>("getPackageManager");
    const auto packageName = context.callMethod<QString>("getPackageName");
    const auto packageInfo = packageManager.callMethod<PackageInfo>("getPackageInfo",
                                                                    packageName,
                                                                    8 /* PackageManager.GET_PROVIDERS */);
    const auto providersArray = packageInfo.getField<ProviderInfo[]>("providers");

    if (providersArray.isValid()) {
        const auto className = Traits<FileProvider>::className();
        for (const auto &fileProvider : providersArray) {
            auto providerName = fileProvider.getField<QString>("name");
            if (providerName.replace(".", "/").contains(className.data())) {
                const auto authority = fileProvider.getField<QString>("authority");
                if (!authority.isEmpty())
                    authorityList << authority;
            }
        }
    }
    if (authorityList.isEmpty())
        qWarning() << "No file provider found in the AndroidManifest.xml.";

    return authorityList;
}

bool QAndroidPlatformServices::openDocument(const QUrl &url)
{
    return openUrl(url);
}

bool QAndroidPlatformServices::handleNewIntent(JNIEnv *env, jobject intent)
{
    Q_UNUSED(env);

    const QJniObject jniIntent(intent);

    const QString action = jniIntent.callObjectMethod<jstring>("getAction").toString();
    if (action != m_actionView)
        return false;

    const QString url = jniIntent.callObjectMethod<jstring>("getDataString").toString();
    QScopedValueRollback<QUrl> rollback(m_handlingUrl, url);
    return QDesktopServices::openUrl(url);
}
#endif // QT_CONFIG(desktopservices)

QT_END_NAMESPACE