summaryrefslogtreecommitdiffstats
path: root/src/serviceframework/ipc/qservicemetaobject_dbus.cpp
blob: 3028e89c1dfda9b078965fc77d372ae442e9e5c7 (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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSystems 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$
**
****************************************************************************/

#include "qservicemetaobject_dbus_p.h"
#include <private/qmetaobjectbuilder_p.h>
#include "qsignalintercepter_p.h"
#include <QDebug>

#include <stdlib.h>

QT_BEGIN_NAMESPACE

class ServiceMetaSignalIntercepter : public QSignalIntercepter
{

public:
    ServiceMetaSignalIntercepter(QObject* sender, const QByteArray& signal, QServiceMetaObjectDBus* parent)
        : QSignalIntercepter(sender, signal, parent), serviceDBus(parent)
    {

    }

    void setMetaIndex(int index)
    {
        metaIndex = index;
    }

protected:
    void activated( const QList<QVariant>& args )
    {
        serviceDBus->activateMetaSignal(metaIndex, args);
    }
private:
    QServiceMetaObjectDBus* serviceDBus;
    int metaIndex;
};


class QServiceMetaObjectDBusPrivate
{
public:
    QObject *service;
    const QMetaObject *serviceMeta;
    const QMetaObject *dbusMeta;
};

QServiceMetaObjectDBus::QServiceMetaObjectDBus(QObject* service, bool signalsObject)
    : QDBusAbstractAdaptor(service)
{
    // Register our DBus custom type object
    qRegisterMetaType<QServiceUserTypeDBus>();
    qDBusRegisterMetaType<QServiceUserTypeDBus>();

    // Generate our DBus meta object
    d = new QServiceMetaObjectDBusPrivate();
    d->service = service;
    d->serviceMeta = service->metaObject();
    d->dbusMeta = dbusMetaObject(signalsObject);

    // Relay signals from the service to the constructed DBus meta object
    connectMetaSignals(signalsObject);
}

QServiceMetaObjectDBus::~QServiceMetaObjectDBus()
{
    if (d->dbusMeta)
        free(const_cast<QMetaObject*>(d->dbusMeta));

    delete d;
}

/*!
    Relays all signals from the service object to the converted DBus service adaptor so
    that when a service signal is emitted the DBus object will emit the counterpart signal
*/
void QServiceMetaObjectDBus::connectMetaSignals(bool signalsObject) {
    if (!signalsObject) {
        // Automatically relay signals from service object to adaptor
        setAutoRelaySignals(true);

        // Connect signals with custom arguments
        int methodCount = d->serviceMeta->methodCount();
        for (int i = 0; i < methodCount; i++) {
            QMetaMethod mm = d->serviceMeta->method(i);


            if (mm.methodType() == QMetaMethod::Signal) {
                QByteArray sig(mm.methodSignature());
                bool customType = false;
                const QList<QByteArray> pTypes = mm.parameterTypes();
                const int pTypesCount = pTypes.count();

                // Ignore all QObject calls
                const QMetaObject *mo = QObject::metaObject();
                int qobjectIndex = mo->indexOfMethod(sig);
                if (qobjectIndex >= 0)
                    continue;

                // Detects custom types as passed arguments
                for (int arg = 0; arg < pTypesCount; arg++) {
                    const QByteArray& type = pTypes[arg];
                    int variantType = QMetaType::type(type);
                    if (variantType >= QMetaType::User || variantType == QMetaType::QVariant) {
                        sig.replace(QByteArray(type), QByteArray("QDBusVariant"));
                        customType = true;
                    }
                }

                // Connects the service signal to the corresponding DBus service signal
                if (customType) {
                    QByteArray signal = mm.methodSignature();
                    ServiceMetaSignalIntercepter *intercept =
                        new ServiceMetaSignalIntercepter(d->service, "2"+signal, this);
                    intercept->setMetaIndex(i);
                }
            }
        }
    }
}

/*!
    Relays the activation to the DBus object signal with the given id and arguments list when the
    intercepter for signals with custom arguments has been activated. This bypasses the metacall
    which usually does the relaying for signals with standard arguments since no pre-connection
    conversions are required.
*/
void QServiceMetaObjectDBus::activateMetaSignal(int id, const QVariantList& args)
{
    QMetaMethod method = d->serviceMeta->method(id);

    // Converts the argument list to values supported by the QtDBus type system
    QVariantList convertedList = args;
    QByteArray sig(method.methodSignature());
    QList<QByteArray> params = method.parameterTypes();

    for (int i = 0; i < params.size(); i++) {
        QVariant dbusVariant = args[i];

        // Convert custom types
        const QByteArray& type = params[i];
        int variantType = QMetaType::type(type);
        if (variantType >= QMetaType::User || variantType == QMetaType::QVariant) {
            if (variantType != QMetaType::QVariant) {
                // Wrap custom types in a QDBusVariant of the type name and
                // a buffer of its variant-wrapped data
                QByteArray buffer;
                QDataStream stream(&buffer, QIODevice::ReadWrite | QIODevice::Append);
                stream << args[i];

                QServiceUserTypeDBus customType;
                customType.typeName = type;
                customType.variantBuffer = buffer;

                QDBusVariant replacement(QVariant::fromValue(customType));
                convertedList.replace(i, QVariant::fromValue(replacement));
            }

            sig.replace(QByteArray(type), QByteArray("QDBusVariant"));
        }
    }

    // Activate the DBus object signal call
    const int numArgs = convertedList.size();
    QVarLengthArray<void *, 32> a( numArgs+1 );
    a[0] = 0;

    const QList<QByteArray> pTypes = method.parameterTypes();
    for ( int arg = 0; arg < numArgs; ++arg ) {
        if (pTypes.at(arg) == "QVariant")
            a[arg+1] = (void *)&( convertedList[arg] );
        else
            a[arg+1] = (void *)( convertedList[arg].data() );
    }

    int dbusIndex = d->dbusMeta->indexOfSignal(sig);
    QMetaObject::activate(this, dbusIndex, a.data());
}


/*!
    Build a metaobject that represents the service object as a valid service that
    satisfies the QtDBus type system.
*/
const QMetaObject* QServiceMetaObjectDBus::dbusMetaObject(bool signalsObject) const
{
    // Create a meta-object to represent all the contents of our service on DBus
    QMetaObjectBuilder builder;

    builder.setClassName(d->serviceMeta->className());
    builder.setSuperClass(d->serviceMeta->superClass()); // needed?

    const QMetaObject* mo = d->serviceMeta;
    while (mo && strcmp(mo->className(), "QObject")) {
        // Add our methods, signals and slots
        for (int i = mo->methodOffset(); i < mo->methodCount(); i++) {
            QMetaMethod mm = mo->method(i);

            if (signalsObject && mm.methodType() != QMetaMethod::Signal)
                continue;

            // Convert QVariant and custom return types to QDBusVariants
            QByteArray ret(mm.typeName());
            const QByteArray& type = mm.typeName();
            int variantType = QMetaType::type(type);
            if (variantType >= QMetaType::User || variantType == QMetaType::QVariant) {
                ret = QByteArray("QDBusVariant");
            }

            // Convert QVariant and custom argument types to QDBusVariants
            QByteArray sig(mm.methodSignature());
            const QList<QByteArray> pTypes = mm.parameterTypes();
            const int pTypesCount = pTypes.count();
            for (int i=0; i < pTypesCount; i++) {
                const QByteArray& type = pTypes[i];
                int variantType = QMetaType::type(type);
                if (variantType >= QMetaType::User || variantType == QMetaType::QVariant) {
                    sig.replace(QByteArray(type), QByteArray("QDBusVariant"));
                }
            }

            // Add a MetaMethod with converted signature to our builder
            QMetaMethodBuilder method;
            switch (mm.methodType()) {
                case QMetaMethod::Method:
                    method = builder.addMethod(sig);
                    break;
                case QMetaMethod::Slot:
                    method = builder.addSlot(sig);
                    break;
                case QMetaMethod::Signal:
                    method = builder.addSignal(sig);
                    break;
                default:
                    break;
            }

            // Make sure our built MetaMethod is identical, excluding conversion
            method.setReturnType(ret);
            method.setParameterNames(mm.parameterNames());
            method.setTag(mm.tag());
            method.setAccess(mm.access());
            method.setAttributes(mm.attributes());
        }

        if (signalsObject)
            return builder.toMetaObject();

        // Add our property accessor methods
        // NOTE: required because read/reset properties over DBus require adaptors
        //       otherwise a metacall won't be invoked as QMetaObject::ReadProperty
        //       or QMetaObject::ResetProperty
        QMetaMethodBuilder readProp;
        readProp = builder.addMethod(QByteArray("propertyRead(QString)"));
        readProp.setReturnType(QByteArray("QDBusVariant"));
        QList<QByteArray> params;
        params << QByteArray("name");
        readProp.setParameterNames(params);

        QMetaMethodBuilder resetProp;
        resetProp = builder.addMethod(QByteArray("propertyReset(QString)"));
        QList<QByteArray> paramsReset;
        paramsReset << QByteArray("name");
        resetProp.setParameterNames(paramsReset);


        // Add our properties/enums
        int propCount = d->serviceMeta->propertyCount();
        for (int i=0; i<propCount; i++) {
            QMetaProperty mp = d->serviceMeta->property(i);

            QMetaPropertyBuilder property = builder.addProperty(mp.name(), mp.typeName());
            property.setReadable(mp.isReadable());
            property.setWritable(mp.isWritable());
            property.setResettable(mp.isResettable());
            property.setDesignable(mp.isDesignable());
            property.setScriptable(mp.isScriptable());
            property.setStored(mp.isStored());
            property.setEditable(mp.isEditable());
            property.setUser(mp.isUser());
            property.setStdCppSet(mp.hasStdCppSet());
            property.setEnumOrFlag(mp.isEnumType());
        }

        // Needs Enumerators support when QtDBus supports

        mo = mo->superClass();
    }

    // return our constructed dbus metaobject
    return builder.toMetaObject();
}

/*!
    Provide custom Q_OBJECT implementation of the metaObject
*/
const QMetaObject* QServiceMetaObjectDBus::metaObject() const
{
    // Provide our construected DBus service metaobject
    return d->dbusMeta;
}

/*!
    Overrides metacall which relays the DBus service call to the actual service
    meta object. Positive return will indicate that the metacall was unsuccessful
*/
int QServiceMetaObjectDBus::qt_metacall(QMetaObject::Call c, int id, void **a)
{
    int dbusIndex = id;

    // Relay the meta-object call to the service object
    if (c == QMetaObject::InvokeMetaMethod) {
        // METHOD CALL
        QMetaMethod method = d->dbusMeta->method(id);

        const bool isSignal = (method.methodType() == QMetaMethod::Signal);

        ///////////////////// CHECK SPECIAL PROPERTY ///////////////////////
        // This is required because property READ/RESET doesn't function
        // as desired over DBus without the use of adaptors. Temporary
        // methods propertyRead and propertyReset are added to the published
        // meta object and relay the correct property call
        QString methodName(QLatin1String(method.methodSignature().constData()));
        methodName.truncate(methodName.indexOf(QLatin1String("(")));

        if (methodName == QLatin1String("propertyRead")) {
            QString propertyName = *reinterpret_cast<QString*>(a[1]);
            int index = d->dbusMeta->indexOfProperty(propertyName.toLatin1().constData());
            id = qt_metacall(QMetaObject::ReadProperty, index, a);
            return id;

        } else if (methodName == QLatin1String("propertyReset")) {
            QString propertyName = *reinterpret_cast<QString*>(a[1]);
            int index = d->dbusMeta->indexOfProperty(propertyName.toLatin1().constData());
            id = qt_metacall(QMetaObject::ResetProperty, index, a);
            return id;
        }
        ////////////////////////////////////////////////////////////////////

        // Find the corresponding signature to our service object
        QByteArray sig(method.methodSignature());
        int count = methodName.size() + 1;
        const QList<QByteArray> xTypes = method.parameterTypes();
        const int xTypesCount = xTypes.count();
        for (int i=0; i < xTypesCount; i++) {
            const QByteArray& t = xTypes[i];
            int variantType = QMetaType::type(t);

            // Check for QVariants or custom types, represented as QDBusVariants
            if (t == "QDBusVariant") {
                // Convert QDBusVariant to QVariant
                QVariant convert = QVariant(variantType, a[i+1]);
                QDBusVariant dbusVariant = qvariant_cast<QDBusVariant>(convert);
                QVariant variant = dbusVariant.variant();

                // Is a custom argument if castable to QDBusArgument
                bool hasCustomType = variant.canConvert<QDBusArgument>();
                QByteArray replacement("QVariant");

                // Custom types will have QDBusArgument streaming operators for
                // the QServiceUserTypeDBus object. Extract the real type name
                // and buffered QVariant from this
                if (hasCustomType) {
                    QDBusArgument demarshall = variant.value<QDBusArgument>();
                    QServiceUserTypeDBus userType = qdbus_cast<QServiceUserTypeDBus>(demarshall);
                    *reinterpret_cast<QVariant*>(a[i+1]) = userType.variantBuffer;

                    replacement = userType.typeName;
                }

                // Replace "QDBusVariant" with "QVariant" or custom type name
                sig.replace(count, 12, replacement);
                count += replacement.size();

            } else {
                // Supported type so skip this paramater
                count += t.size();
            }

            // Skips the comma if not last parameter
            if (i < xTypesCount)
                count += 1;
        }

        // Find the corresponding method metaindex to our service object
        id = d->serviceMeta->indexOfMethod(sig);
        QMetaMethod mm = d->serviceMeta->method(id);

        const QList<QByteArray> pTypes = mm.parameterTypes();
        const int pTypesCount = pTypes.count();

        const char* typeNames[] = {0,0,0,0,0,0,0,0,0,0};
        const void* params[] = {0,0,0,0,0,0,0,0,0,0};
        bool hasCustomType = false;

        // Process arguments
        for (int i=0; i < pTypesCount; i++) {
            const QByteArray& t = pTypes[i];
            int variantType = QMetaType::type(t);

            if (variantType >= QMetaType::User) {
                // Custom argument
                QVariant convert = QVariant(QVariant::ByteArray, a[i+1]);
                QByteArray buffer = convert.toByteArray();
                QDataStream stream(&buffer, QIODevice::ReadWrite);

                // Load our buffered variant-wrapped custom type
                QVariant *customType = new QVariant(variantType, (const void*)0);
                QMetaType::load(stream, QMetaType::QVariant, customType);

                typeNames[i] = customType->typeName();
                params[i] = customType->constData();
                hasCustomType = true;
            } else {
                typeNames[i] = t.constData();
                params[i] = a[i+1];
            }
        }

        // Check if this is a signal emit and activate
        if (isSignal) {
            QMetaObject::activate(this, dbusIndex, a);
            return id;
        }

        // Check for custom return types and make the metacall
        const QByteArray& type = mm.typeName();
        int retType = QMetaType::type(type);
        if (retType >= QMetaType::User) {
            // Invoke the object method directly for custom return types
            bool result = false;
            QVariant returnValue = QVariant(retType, (const void*)0);
            QGenericReturnArgument ret(type, returnValue.data());
            result = mm.invoke(d->service, ret,
                    QGenericArgument(typeNames[0], params[0]),
                    QGenericArgument(typeNames[1], params[1]),
                    QGenericArgument(typeNames[2], params[2]),
                    QGenericArgument(typeNames[3], params[3]),
                    QGenericArgument(typeNames[4], params[4]),
                    QGenericArgument(typeNames[5], params[5]),
                    QGenericArgument(typeNames[6], params[6]),
                    QGenericArgument(typeNames[7], params[7]),
                    QGenericArgument(typeNames[8], params[8]),
                    QGenericArgument(typeNames[9], params[9]));

            if (result) {
                // Wrap custom return type in a QDBusVariant of the type
                // and a buffer of its variant-wrapped data
                QByteArray buffer;
                QDataStream stream(&buffer, QIODevice::WriteOnly | QIODevice::Append);
                stream << returnValue;

                QServiceUserTypeDBus customType;
                customType.typeName = type;
                customType.variantBuffer = buffer;

                QDBusVariant replacement(QVariant::fromValue(customType));
                *reinterpret_cast<QDBusVariant*>(a[0]) = replacement;

                // Return negative id to say metacall was handled externally
                return -1;
            }

        } else {
            // Void or standard return types
            if (hasCustomType == true) {
                // Invoke the object method directly for custom arguments
                bool result = false;
                result = mm.invoke(d->service,
                         QGenericArgument(typeNames[0], params[0]),
                         QGenericArgument(typeNames[1], params[1]),
                         QGenericArgument(typeNames[2], params[2]),
                         QGenericArgument(typeNames[3], params[3]),
                         QGenericArgument(typeNames[4], params[4]),
                         QGenericArgument(typeNames[5], params[5]),
                         QGenericArgument(typeNames[6], params[6]),
                         QGenericArgument(typeNames[7], params[7]),
                         QGenericArgument(typeNames[8], params[8]),
                         QGenericArgument(typeNames[9], params[9]));
                if (result) {
                    // Return negative id to say metacall was handled externally
                    return -1;
                }
            } else {
                // Relay standard metacall to service object
                id = d->service->qt_metacall(c, id, a);
            }
        }

    } else {
        // PROPERTY CALL

        // Find the corresponding property metaindex of our service object
        QMetaProperty property = d->dbusMeta->property(id);
        QByteArray name(property.name());
        id = d->serviceMeta->indexOfProperty(name);

        if (c == QMetaObject::ReadProperty) {
            // Convert to DBusVariant
            QMetaProperty mp = d->serviceMeta->property(id);
            QVariant value = mp.read(d->service);
            QDBusVariant replacement(value);
            *reinterpret_cast<QDBusVariant*>(a[0]) = replacement;

            // Return negative id to say metacall was handled externally
            return -1;
        }

        // Metacall our service object property
        id = d->service->qt_metacall(c, id, a);
    }

    return id;
}

void *QServiceMetaObjectDBus::qt_metacast(const char* className)
{
    if (!className) return 0;
    //this object should not be castable to anything but QObject
    return QObject::qt_metacast(className);
}

QDBusArgument &operator<<(QDBusArgument &argument, const QServiceUserTypeDBus &myType)
{
    argument.beginStructure();
    argument << myType.typeName << myType.variantBuffer;
    argument.endStructure();
    return argument;
}

const QDBusArgument &operator>>(const QDBusArgument &argument, QServiceUserTypeDBus &myType)
{
    argument.beginStructure();
    argument >> myType.typeName >> myType.variantBuffer;
    argument.endStructure();
    return argument;
}

QT_END_NAMESPACE