aboutsummaryrefslogtreecommitdiffstats
path: root/src/quick/platform/android/qandroidquickviewembedding.cpp
blob: 262dd9179c0ecfda5dd8a66fd95013281005219b (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
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
// Copyright (C) 2023 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 <QtQuick/private/qandroidquickviewembedding_p.h>
#include <QtQuick/private/qandroidtypes_p.h>
#include <QtQuick/private/qandroidtypeconverter_p.h>
#include <QtQuick/private/qandroidviewsignalmanager_p.h>
#include <QtQuick/private/qandroiditemmodelproxy_p.h>
#include <QtQuick/private/qandroidmodelindexproxy_p.h>

#include <QtCore/qcoreapplication.h>
#include <QtCore/qjnienvironment.h>
#include <QtCore/qjniobject.h>
#include <QtCore/qjniarray.h>
#include <QtCore/qjnitypes.h>
#include <QtQml/qqmlengine.h>
#include <QtQuick/qquickitem.h>

QT_BEGIN_NAMESPACE

Q_DECLARE_JNI_CLASS(QtDelegate, "org/qtproject/qt/android/QtEmbeddedContextDelegate");
Q_DECLARE_JNI_CLASS(QtQuickView, "org/qtproject/qt/android/QtQuickView");
Q_DECLARE_JNI_CLASS(QtWindow, "org/qtproject/qt/android/QtWindow");
Q_DECLARE_JNI_CLASS(View, "android/view/View");

namespace QtAndroidQuickViewEmbedding
{
    constexpr const char *uninitializedViewMessage = "because QtQuickView is not loaded or ready yet.";

    void createQuickView(JNIEnv *, jobject nativeWindow, jstring qmlUri, jint width, jint height,
                         jlong parentWindowReference, jlong viewReference,
                         const QJniArray<jstring> &qmlImportPaths)
    {
        static_assert (sizeof(jlong) >= sizeof(void*),
                      "Insufficient size of Java type to hold the c++ pointer");
        const QUrl qmlUrl(QJniObject(qmlUri).toString());

        const QStringList importPaths = qmlImportPaths.toContainer();
        QMetaObject::invokeMethod(qApp, [qtViewObject = QJniObject(nativeWindow),
                                        parentWindowReference,
                                        viewReference,
                                        width,
                                        height,
                                        qmlUrl,
                                        importPaths] {
            // If the view does not exists (viewReference==0) we should create and set it up.
            // Else we only reset the source of the view.
            QAndroidQuickView *view = reinterpret_cast<QAndroidQuickView *>(viewReference);
            if (!view) {
                QWindow *parentWindow = reinterpret_cast<QWindow *>(parentWindowReference);
                view = new QAndroidQuickView(parentWindow);
                QObject::connect(view, &QAndroidQuickView::statusChanged, view,
                                 [qtViewObject](QAndroidQuickView::Status status) {
                                     qtViewObject.callMethod<void>("handleStatusChange", status);
                                 });
                view->setResizeMode(QAndroidQuickView::SizeRootObjectToView);
                view->setColor(QColor(Qt::transparent));
                view->setWidth(width);
                view->setHeight(height);
                QQmlEngine *engine = view->engine();
                for (const QString &path : importPaths)
                    engine->addImportPath(path);

                const QtJniTypes::QtWindow window = reinterpret_cast<jobject>(view->winId());
                qtViewObject.callMethod<void>("addQtWindow",
                                              window,
                                              reinterpret_cast<jlong>(view),
                                              parentWindowReference);
            }
            view->setSource(qmlUrl);
        });
    }

    std::pair<QAndroidQuickView *, QQuickItem *> getViewAndRootObject(jlong windowReference)
    {
        QAndroidQuickView *view = reinterpret_cast<QAndroidQuickView *>(windowReference);
        QQuickItem *rootObject = Q_LIKELY(view) ? view->rootObject() : nullptr;
        return std::make_pair(view, rootObject);
    }

    void setRootObjectProperty(JNIEnv *env, jobject object, jlong windowReference,
                               jstring propertyName, jobject value)
    {
        Q_UNUSED(env);
        Q_UNUSED(object);

        auto [_, rootObject] = getViewAndRootObject(windowReference);
        if (!rootObject) {
            qWarning("Cannot set property %s %s", qPrintable(QJniObject(propertyName).toString()),
                     uninitializedViewMessage);
            return;
        }

        const QString property = QJniObject(propertyName).toString();
        const QMetaObject *rootMetaObject = rootObject->metaObject();
        int propertyIndex = rootMetaObject->indexOfProperty(qPrintable(property));
        if (propertyIndex < 0) {
            qWarning("Property %s does not exist in the root QML object.", qPrintable(property));
            return;
        }

        QMetaProperty metaProperty = rootMetaObject->property(propertyIndex);
        const QJniObject propertyValue(value);
        const QVariant variantToWrite = QAndroidTypeConverter::toQVariant(propertyValue);

        if (!variantToWrite.isValid()) {
            qWarning("Setting the property type of %s is not supported.",
                     qPrintable(propertyValue.className()));
        } else {
            metaProperty.write(rootObject, variantToWrite);
        }
    }

    jobject getRootObjectProperty(JNIEnv *env, jobject object, jlong windowReference,
                                  jstring propertyName)
    {
        Q_UNUSED(object);
        Q_ASSERT(env);

        const QString property = QJniObject(propertyName).toString();
        auto [_, rootObject] = getViewAndRootObject(windowReference);
        if (!rootObject) {
            qWarning("Cannot get property %s %s", qPrintable(property), uninitializedViewMessage);
            return nullptr;
        }

        const QMetaObject *rootMetaObject = rootObject->metaObject();
        int propertyIndex = rootMetaObject->indexOfProperty(property.toUtf8().constData());
        if (propertyIndex < 0) {
            qWarning("Cannot get property %s as it does not exist in the root QML object.",
                     qPrintable(property));
            return nullptr;
        }

        QMetaProperty metaProperty = rootMetaObject->property(propertyIndex);
        const QVariant propertyValue = metaProperty.read(rootObject);
        jobject jObject = QAndroidTypeConverter::toJavaObject(propertyValue, env);
        if (!jObject) {
            qWarning("Property %s cannot be converted to a supported Java data type.",
                     qPrintable(property));
        }
        return jObject;
    }

    int addRootObjectSignalListener(JNIEnv *env, jobject, jlong windowReference, jstring signalName,
                                   jclass argType, jobject listener)
    {
        Q_ASSERT(env);
        static QHash<QByteArray, int> javaToQMetaType = {
            { "java/lang/Void", QMetaType::Type::Void },
            { "java/lang/String", QMetaType::Type::QString },
            { "java/lang/Integer", QMetaType::Type::Int },
            { "java/lang/Double", QMetaType::Type::Double },
            { "java/lang/Float", QMetaType::Type::Float },
            { "java/lang/Boolean", QMetaType::Type::Bool }
        };

        auto [view, rootObject] = getViewAndRootObject(windowReference);
        if (!rootObject) {
            qWarning("Cannot connect to signal %s %s",
                     qPrintable(QJniObject(signalName).toString()), uninitializedViewMessage);
            return -1;
        }

        QAndroidViewSignalManager *signalManager = view->signalManager();
        const QByteArray javaArgClass = QJniObject(argType).className();
        const char *qArgName =
                QMetaType(javaToQMetaType.value(javaArgClass, QMetaType::Type::UnknownType)).name();
        const QString signalMethodName = QJniObject(signalName).toString();

        const QMetaObject *metaObject = rootObject->metaObject();
        int signalIndex = -1;
        int propertyIndex = -1;

        QByteArray signalSignature = QMetaObject::normalizedSignature(qPrintable(
                QStringLiteral("%1(%2)").arg(signalMethodName).arg(QLatin1StringView(qArgName))));
        signalIndex = metaObject->indexOfSignal(signalSignature.constData());

        // Try to check if the signal is a parameterless notifier of a property
        // or a property name itself.
        if (signalIndex == -1) {
            signalSignature = QMetaObject::normalizedSignature(
                    qPrintable(QStringLiteral("%1()").arg(signalMethodName)));
            for (int i = 0; i < metaObject->propertyCount(); ++i) {
                QMetaProperty metaProperty = metaObject->property(i);
                QMetaMethod notifyMethod = metaProperty.notifySignal();

                if (signalSignature == notifyMethod.methodSignature()) {
                    signalIndex = metaObject->property(i).notifySignalIndex();
                    propertyIndex = i;
                    break;
                } else if (signalMethodName == QLatin1StringView(metaProperty.name())) {
                    signalIndex = metaObject->property(i).notifySignalIndex();
                    signalSignature = notifyMethod.methodSignature();
                    propertyIndex = i;
                    break;
                }
            }
        }

        if (signalIndex == -1)
            return -1;

        const QMetaObject *helperMetaObject = signalManager->metaObject();
        QByteArray helperSignalSignature = signalSignature;
        helperSignalSignature.replace(0, signalSignature.indexOf('('), "forwardSignal");
        int helperSlotIndex = helperMetaObject->indexOfSlot(helperSignalSignature.constData());
        if (helperSlotIndex == -1)
            return -1;

        // Return the id if the signal is already connected to the same listener.
        QJniObject listenerJniObject(listener);
        if (signalManager->connectionInfoMap.contains(signalSignature)) {
            auto connectionInfos = signalManager->connectionInfoMap.values(signalSignature);
            auto isSameListener =
                    [listenerJniObject](
                            const QAndroidViewSignalManager::ConnectionInfo &connectionInfo) {
                        return connectionInfo.listener == listenerJniObject;
                    };
            auto iterator = std::find_if(connectionInfos.constBegin(),
                                         connectionInfos.constEnd(),
                                         isSameListener);
            if (iterator != connectionInfos.end()) {
                qWarning("Signal listener with the ID of %i is already connected to %s signal.",
                         iterator->id,
                         signalSignature.constData());
                return iterator->id;
            }
        }

        QMetaMethod signalMethod = metaObject->method(signalIndex);
        QMetaMethod signalForwarderMethod = helperMetaObject->method(helperSlotIndex);
        signalManager->connectionHandleCounter++;

        QMetaObject::Connection connection;
        if (signalManager->connectionInfoMap.contains(signalSignature)) {
            const int existingId = signalManager->connectionInfoMap.value(signalSignature).id;
            connection = signalManager->connections[existingId];
        } else {
            connection = QObject::connect(rootObject,
                                          signalMethod,
                                          signalManager,
                                          signalForwarderMethod);
        }

        QAndroidViewSignalManager::ConnectionInfo connectionInfo;
        connectionInfo.listener = listenerJniObject;
        connectionInfo.javaArgType = javaArgClass;
        connectionInfo.propertyIndex = propertyIndex;
        connectionInfo.signalSignature = signalSignature;
        connectionInfo.id = signalManager->connectionHandleCounter;

        signalManager->connectionInfoMap.insert(signalSignature, connectionInfo);
        signalManager->connections.insert(connectionInfo.id, connection);

        return connectionInfo.id;
    }

    bool removeRootObjectSignalListener(JNIEnv *, jobject, jlong windowReference,
                                       jint signalListenerId)
    {
        auto [view, rootObject] = getViewAndRootObject(windowReference);
        if (!rootObject) {
            qWarning("Cannot disconnect the signal connection with id: %i %s", signalListenerId,
                     uninitializedViewMessage);
            return false;
        }

        QAndroidViewSignalManager *signalManager = view->signalManager();
        if (!signalManager->connections.contains(signalListenerId))
            return false;

        QByteArray signalSignature;
        for (auto listenerInfoIter = signalManager->connectionInfoMap.begin();
             listenerInfoIter != signalManager->connectionInfoMap.end();) {
            if (listenerInfoIter->id == signalListenerId) {
                signalSignature = listenerInfoIter->signalSignature;
                signalManager->connectionInfoMap.erase(listenerInfoIter);
                break;
            } else {
                ++listenerInfoIter;
            }
        }

        // disconnect if its the last listener associated with the signal signatures
        if (!signalManager->connectionInfoMap.contains(signalSignature))
            rootObject->disconnect(signalManager->connections.value(signalListenerId));

        signalManager->connections.remove(signalListenerId);
        return true;
    }

    bool registerNatives(QJniEnvironment& env) {
        return env.registerNativeMethods(QtJniTypes::Traits<QtJniTypes::QtQuickView>::className(),
                                         {Q_JNI_NATIVE_SCOPED_METHOD(createQuickView,
                                                                     QtAndroidQuickViewEmbedding),
                                          Q_JNI_NATIVE_SCOPED_METHOD(setRootObjectProperty,
                                                                     QtAndroidQuickViewEmbedding),
                                          Q_JNI_NATIVE_SCOPED_METHOD(getRootObjectProperty,
                                                                     QtAndroidQuickViewEmbedding),
                                          Q_JNI_NATIVE_SCOPED_METHOD(addRootObjectSignalListener,
                                                                     QtAndroidQuickViewEmbedding),
                                          Q_JNI_NATIVE_SCOPED_METHOD(removeRootObjectSignalListener,
                                                                     QtAndroidQuickViewEmbedding)});
    }
}

Q_DECL_EXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
    Q_UNUSED(vm)
    Q_UNUSED(reserved)

    static bool initialized = false;
    if (initialized)
        return JNI_VERSION_1_6;
    initialized = true;

    QJniEnvironment env;
    if (!env.isValid())
        return JNI_ERR;
    if (!QtAndroidQuickViewEmbedding::registerNatives(env))
        return JNI_ERR;
    if (!QAndroidItemModelProxy::registerAbstractNatives(env))
        return JNI_ERR;
    if (!QAndroidItemModelProxy::registerProxyNatives(env))
        return JNI_ERR;
    if (!QAndroidModelIndexProxy::registerNatives(env))
        return JNI_ERR;
    return JNI_VERSION_1_6;
}

QT_END_NAMESPACE