summaryrefslogtreecommitdiff
path: root/src/webchannel/qmetaobjectpublisher_p.h
blob: 2d255112350df4f543ac211bf8167c03c9e1e4c7 (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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/****************************************************************************
**
** Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff <milian.wolff@kdab.com>
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtWebChannel module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#ifndef QMETAOBJECTPUBLISHER_P_H
#define QMETAOBJECTPUBLISHER_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "variantargument_p.h"
#include "signalhandler_p.h"

#include <QStringList>
#include <QMetaObject>
#include <QBasicTimer>
#include <QPointer>
#include <QProperty>
#include <QJsonObject>
#include <QQueue>

#include <unordered_map>

#include "qwebchannelglobal.h"

QT_BEGIN_NAMESPACE

// NOTE: keep in sync with corresponding maps in qwebchannel.js and WebChannelTest.qml
enum MessageType {
    TypeInvalid = 0,

    TYPES_FIRST_VALUE = 1,

    TypeSignal = 1,
    TypePropertyUpdate = 2,
    TypeInit = 3,
    TypeIdle = 4,
    TypeDebug = 5,
    TypeInvokeMethod = 6,
    TypeConnectToSignal = 7,
    TypeDisconnectFromSignal = 8,
    TypeSetProperty = 9,
    TypeResponse = 10,

    TYPES_LAST_VALUE = 10
};

class QMetaObjectPublisher;
class QWebChannel;
class QWebChannelAbstractTransport;

struct QWebChannelPropertyChangeNotifier : QPropertyObserver
{
    QWebChannelPropertyChangeNotifier(QMetaObjectPublisher *publisher, const QObject *object, int propertyIndex)
        : QPropertyObserver(&QWebChannelPropertyChangeNotifier::notify),
          publisher(publisher), object(object), propertyIndex(propertyIndex)
    {
    }

    QMetaObjectPublisher *publisher = nullptr;
    const QObject *object = nullptr;
    int propertyIndex = 0;
    static void notify(QPropertyObserver *, QUntypedPropertyData *);
};

class Q_WEBCHANNEL_EXPORT QMetaObjectPublisher : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int propertyUpdateIntervalTime READ propertyUpdateInterval WRITE
                       setPropertyUpdateInterval)
public:
    explicit QMetaObjectPublisher(QWebChannel *webChannel);
    virtual ~QMetaObjectPublisher();

    /**
     * Register @p object under the given @p id.
     *
     * The properties, signals and public methods of the QObject are
     * published to the remote client, where an object with the given identifier
     * is constructed.
     *
     * TODO: This must be called, before clients are initialized.
     */
    void registerObject(const QString &id, QObject *object);

    /**
     * Send the given message to all known transports.
     */
    void broadcastMessage(const QJsonObject &message) const;

    /**
     * Enqueue the given @p message to all known transports.
     */
    void enqueueBroadcastMessage(const QJsonObject &message);

    /**
     * Enqueue the given @p message to @p transport.
     */
    void enqueueMessage(const QJsonObject &message, QWebChannelAbstractTransport *transport);

    /**
     * If client for given @p transport is idle, send queued messaged to @p transport and then mark
     * the client as not idle.
     */
    void sendEnqueuedPropertyUpdates(QWebChannelAbstractTransport *transport);

    /**
     * Serialize the QMetaObject of @p object and return it in JSON form.
     */
    QJsonObject classInfoForObject(const QObject *object, QWebChannelAbstractTransport *transport);

    /**
     * Set the client to idle or busy for a single @p transport, based on the value of @p isIdle.
     */
    void setClientIsIdle(bool isIdle, QWebChannelAbstractTransport *transport);

    /**
     * Check that client is idle for @p transport.
     */
    bool isClientIdle(QWebChannelAbstractTransport *transport);

    /**
     * Initialize clients by sending them the class information of the registered objects.
     *
     * Furthermore, if that was not done already, connect to their property notify signals.
     */
    QJsonObject initializeClient(QWebChannelAbstractTransport *transport);

    /**
     * Go through all properties of the given object and connect to their notify signal.
     *
     * When receiving a notify signal, it will store the information in pendingPropertyUpdates which
     * gets send via a Qt.propertyUpdate message to the server when the grouping timer timeouts.
     */
    void initializePropertyUpdates(QObject *const object, const QJsonObject &objectInfo);

    /**
     * Send the clients the new property values since the last time this function was invoked.
     *
     * This is a grouped batch of all properties for which their notify signal was emitted.
     * The list of signals as well as the arguments they contained, are also transmitted to
     * the remote clients.
     *
     * @sa timer, initializePropertyUpdates
     */
    void sendPendingPropertyUpdates();

    /**
     * Invoke the @p method on @p object with the arguments @p args.
     *
     * The return value of the method invocation is then serialized and a response message
     * is returned.
     */
    QVariant invokeMethod(QObject *const object, const QMetaMethod &method, const QJsonArray &args);

    /**
     * Invoke the method of index @p methodIndex on @p object with the arguments @p args.
     *
     * The return value of the method invocation is then serialized and a response message
     * is returned.
     */
    QVariant invokeMethod(QObject *const object, const int methodIndex, const QJsonArray &args);

    /**
     * Invoke the method of name @p methodName on @p object with the arguments @p args.
     *
     * This method performs overload resolution on @p methodName.
     *
     * The return value of the method invocation is then serialized and a response message
     * is returned.
     */
    QVariant invokeMethod(QObject *const object, const QByteArray &methodName, const QJsonArray &args);

    /**
     * Set the value of property @p propertyIndex on @p object to @p value.
     */
    void setProperty(QObject *object, const int propertyIndex, const QJsonValue &value);

    /**
     * Callback of the signalHandler which forwards the signal invocation to the webchannel clients.
     */
    void signalEmitted(const QObject *object, const int signalIndex, const QVariantList &arguments);

    /**
     * Callback for bindable property value changes which forwards the change to the webchannel clients.
     */
    void propertyValueChanged(const QObject *object, const int propertyIndex);

    /**
     * Called after a property has been updated. Starts the update timer if
     * the client is idle and updates are not blocked.
     */
    void startPropertyUpdateTimer(bool forceRestart = false);

    /**
     * Callback for registered or wrapped objects which erases all data related to @p object.
     *
     * @sa signalEmitted
     */
    void objectDestroyed(const QObject *object);

    QObject *unwrapObject(const QString &objectId) const;
    QVariant unwrapMap(QVariantMap map) const;
    QVariant unwrapList(QVariantList list) const;
    QVariant unwrapVariant(const QVariant &value) const;

    QVariant toVariant(const QJsonValue &value, int targetType) const;

    /**
     * Assigns a score for the conversion from @p value to @p targetType.
     *
     * Scores can be compared to find the best match. The lower the score, the
     * more preferable is the conversion.
     *
     * @sa invokeMethod, methodOverloadBadness
     */
    int conversionScore(const QJsonValue &value, int targetType) const;

    /**
     * Scores @p method against @p args.
     *
     * Scores can be compared to find the best match from a set of overloads.
     * The lower the score, the more preferable is the method.
     *
     * @sa invokeMethod, conversionScore
     */
    int methodOverloadBadness(const QMetaMethod &method, const QJsonArray &args) const;

    /**
     * Remove wrapped objects which last transport relation is with the passed transport object.
     */
    void transportRemoved(QWebChannelAbstractTransport *transport);

    /**
     * Given a QVariant containing a QObject*, wrap the object and register for property updates
     * return the objects class information.
     *
     * All other input types are returned as-is.
     */
    QJsonValue wrapResult(const QVariant &result, QWebChannelAbstractTransport *transport,
                          const QString &parentObjectId = QString());

    /**
     * Convert a list of variant values for consumption by the client.
     *
     * This properly handles QML values and also wraps the result if required.
     */
    QJsonArray wrapList(const QVariantList &list, QWebChannelAbstractTransport *transport,
                          const QString &parentObjectId = QString());

    /**
     * Convert a variant map for consumption by the client.
     *
     * This properly handles QML values and also wraps the result if required.
     */
    QJsonObject wrapMap(const QVariantMap &map, QWebChannelAbstractTransport *transport,
                          const QString &parentObjectId = QString());

    /**
     * Invoke delete later on @p object.
     */
    void deleteWrappedObject(QObject *object) const;

    /**
     * The property update interval in milliseconds.
     *
     * This interval can be changed to a different interval in milliseconds by
     * setting it to a positive value. Property updates are batched and sent out
     * after the interval expires. If set to zero, the updates occurring within a
     * single event loop run are batched and sent out on the next run.
     * If negative, updates will be sent immediately.
     * Default value is 50 milliseconds.
     */
    int propertyUpdateInterval();
    void setPropertyUpdateInterval(int ms);

    /**
     * When updates are blocked, no property updates are transmitted to remote clients.
     */
    void setBlockUpdates(bool block);
    bool blockUpdates() const;

Q_SIGNALS:
    void blockUpdatesChanged(bool block);

public Q_SLOTS:
    /**
     * Handle the @p message and if needed send a response to @p transport.
     */
    void handleMessage(const QJsonObject &message, QWebChannelAbstractTransport *transport);

protected:
    void timerEvent(QTimerEvent *) override;

private:
    void onBlockUpdatesChanged();

    friend class QQmlWebChannelPrivate;
    friend class QWebChannel;
    friend class TestWebChannel;

    QWebChannel *webChannel;
    std::unordered_map<const QThread*, SignalHandler<QMetaObjectPublisher>> signalHandlers;
    SignalHandler<QMetaObjectPublisher> *signalHandlerFor(const QObject *object);

    struct TransportState
    {
        TransportState() : clientIsIdle(false) { }
        // true when the client is idle, false otherwise
        bool clientIsIdle;
        // messages to send
        QQueue<QJsonObject> queuedMessages;
    };
    QHash<QWebChannelAbstractTransport *, TransportState> transportState;

    // true when no property updates should be sent, false otherwise
    Q_OBJECT_BINDABLE_PROPERTY(QMetaObjectPublisher, bool, blockUpdatesStatus);

    QPropertyChangeHandler<std::function<void()>> blockUpdatesHandler;
    // true when at least one client was initialized and thus
    // the property updates have been initialized and the
    // object info map set.
    bool propertyUpdatesInitialized;

    // The update interval in ms when more than zero.
    // Update in next event loop when zero.
    // Update immediately when less than zero.
    Q_OBJECT_BINDABLE_PROPERTY(QMetaObjectPublisher, int, propertyUpdateIntervalTime);

    QPropertyChangeHandler<std::function<void()>> propertyUpdateIntervalHandler;
    // Map of registered objects indexed by their id.
    QHash<QString, QObject *> registeredObjects;

    // Map the registered objects to their id.
    QHash<const QObject *, QString> registeredObjectIds;

    // Groups individually wrapped objects with their class information and the transports that have access to it.
    // Also tags objects that are in the process of being wrapped to prevent infinite recursion.
    struct ObjectInfo
    {
        ObjectInfo(QObject *o = nullptr)
            : object(o), isBeingWrapped(false)
        {}
        QObject *object;
        QList<QWebChannelAbstractTransport *> transports;
        bool isBeingWrapped;
    };

    // Map of objects wrapped from invocation returns
    QHash<QString, ObjectInfo> wrappedObjects;
    // Map of transports to wrapped object ids
    QMultiHash<QWebChannelAbstractTransport*, QString> transportedWrappedObjects;

    // Map of objects to maps of signal indices to a set of all their property indices.
    // The last value is a set as a signal can be the notify signal of multiple properties.
    typedef QHash<int, QSet<int> > SignalToPropertyNameMap;
    QHash<const QObject *, SignalToPropertyNameMap> signalToPropertyMap;

    // Keeps property observers alive for as long as we track an object
    std::unordered_multimap<const QObject*, QWebChannelPropertyChangeNotifier> propertyObservers;

    // Objects that changed their properties and are waiting for idle client.
    typedef QHash<int, QVariantList> SignalToArgumentsMap;

    // A set of plain property index (for bindable properties) and a map of
    // signal index to arguments (for property updates from a notify signal).
    // NOTIFY signals and their arguments are first collected and then mapped to
    // the corresponding property in sendPendingPropertyUpdates()
    struct PropertyUpdate
    {
    public:
        SignalToArgumentsMap signalMap;
        QSet<int> plainProperties;

        /**
         * Given a SignalToPropertyNameMap, returns the set of all property
         * indices of properties that were changed in this PropertyUpdate.
         */
        QSet<int> propertyIndices(const SignalToPropertyNameMap &map) const;
    };

    // map of object to either a property index for plain bindable properties
    // or a to map of signal index to arguments
    typedef QHash<const QObject *, PropertyUpdate> PendingPropertyUpdates;
    PendingPropertyUpdates pendingPropertyUpdates;

    // Aggregate property updates since we get multiple Qt.idle message when we have multiple
    // clients. They all share the same QWebProcess though so we must take special care to
    // prevent message flooding.
    QBasicTimer timer;
};

inline QSet<int> QMetaObjectPublisher::PropertyUpdate::propertyIndices(const SignalToPropertyNameMap &map) const {
    auto indexes = plainProperties;
    for (auto it = signalMap.cbegin(); it != signalMap.cend(); ++it) {
        indexes += map.value(it.key());
    }
    return indexes;
}

QT_END_NAMESPACE

#endif // QMETAOBJECTPUBLISHER_P_H