/
declarativedbusinterface.cpp
1194 lines (983 loc) · 36.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/****************************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Andrew den Exter <andrew.den.exter@jollamobile.com>
** All rights reserved.
**
** You may use this file under the terms of the GNU Lesser General
** Public License version 2.1 as published by the Free Software Foundation
** and appearing in the file license.lgpl included in the packaging
** of this file.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file license.lgpl included in the packaging
** of this file.
17
**
18
19
20
21
** This library 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
** Lesser General Public License for more details.
22
**
23
24
25
****************************************************************************************/
#include "declarativedbusinterface.h"
26
#include "dbus.h"
27
28
#include <QMetaMethod>
29
30
#include <QDBusMessage>
#include <QDBusConnection>
31
#include <QDBusConnectionInterface>
32
33
#include <QDBusObjectPath>
#include <QDBusSignature>
34
#include <QDBusUnixFileDescriptor>
35
36
#include <QDBusPendingCallWatcher>
#include <QDBusPendingReply>
37
38
39
40
#include <qqmlinfo.h>
#include <QJSEngine>
#include <QJSValue>
#include <QJSValueIterator>
41
42
#include <QFile>
#include <QUrl>
43
#include <QXmlStreamReader>
44
45
46
/*!
\qmltype DBusInterface
47
\inqmlmodule Nemo.DBus
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
\brief Provides access to a service on D-Bus
The DBusInterface object can be used to call methods of objects on the system and session bus,
as well as receive signals (see \l signalsEnabled) and read properties of those objects.
DBusInterface is intended to provide access to simple objects exposed over D-Bus. Property
values and method arguments are automatically converted between QML/JS and D-Bus. There is
limited control over this process. For more complex use cases it is recommended to use C++ and
the Qt DBus module.
\section2 Handling D-Bus Signals
If \l signalsEnabled is set to \c true, signals of the destination object will be connected to
functions on the object that have the same name.
Imagine a D-Bus object in service \c {org.example.service} at path \c {/org/example/service} and
interface \c {org.example.intf} with two signals, \c {UpdateAll} and \c {UpdateOne}. You can
handle these signals this way:
\code
DBusInterface {
service: 'org.example.service'
path: '/org/example/service'
iface: 'org.example.intf'
signalsEnabled: true
function updateAll() {
// Will be called when the "UpdateAll" signal is received
}
function updateOne(a, b) {
// Will be called when the "UpdateOne" signal is received
}
}
\endcode
\note In D-Bus, signal names usually start with an uppercase letter, but in QML, function names
on objects must start with lowercase letters. The plugin connects uppercase signal names
to functions where the first letter is lowercase (the D-Bus signal \c {UpdateOne} is
handled by the QML/JavaScript function \c {updateOne}).
\section2 Calling D-Bus Methods
Remote D-Bus methods can be called using either \l call() or \l typedCall(). \l call() provides
a simplier calling API, only supporting basic data types and discards any value return by the
method. \l typedCall() supports more data types and has callbacks for call completion and error.
Imagine a D-Bus object in service \c {org.example.service} at path \c {/org/example/service} and
interface \c {org.example.intf} with two methods:
\list
\li \c RegisterObject with a single \e {object path} parameter and returning a \c bool
\li \c Update with no parameters
\endlist
You can call these two methods this way:
\code
DBusInterface {
service: 'org.example.service'
path: '/org/example/service'
iface: 'org.example.intf'
// Local function to call remote method RegisterObject
function registerObject(object) {
typedCall('RegisterObject',
{ 'type': 'o', 'value': '/example/object/path' },
function(result) { console.log('call completed with:', result) },
117
function(error, message) { console.log('call failed', error, 'message:', message) })
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
}
// Location function to call remote method Update
function update() {
call('Update', undefined)
}
}
\endcode
*/
/*!
\qmlsignal DBusInterface::propertiesChanged()
This signal is emitted when properties of the D-Bus object have changed (only if the D-Bus
object does emit signals when properties change). Right now, this does not tell which properties
have changed and to which values.
\since version 2.0.8
*/
138
139
140
141
namespace {
const QLatin1String PropertyInterface("org.freedesktop.DBus.Properties");
}
142
DeclarativeDBusInterface::DeclarativeDBusInterface(QObject *parent)
143
: QObject(parent)
144
145
, m_watchServiceStatus(false)
, m_status(Unknown)
146
147
148
149
150
151
152
153
, m_bus(DeclarativeDBus::SessionBus)
, m_componentCompleted(false)
, m_signalsEnabled(false)
, m_signalsConnected(false)
, m_propertiesEnabled(false)
, m_propertiesConnected(false)
, m_introspected(false)
, m_providesPropertyInterface(false)
154
, m_serviceWatcher(nullptr)
155
156
157
158
159
{
}
DeclarativeDBusInterface::~DeclarativeDBusInterface()
{
160
161
foreach (QDBusPendingCallWatcher *watcher, m_pendingCalls.keys())
delete watcher;
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
bool DeclarativeDBusInterface::watchServiceStatus() const
{
return m_watchServiceStatus;
}
void DeclarativeDBusInterface::setWatchServiceStatus(bool watchServiceStatus)
{
if (m_watchServiceStatus != watchServiceStatus) {
m_watchServiceStatus = watchServiceStatus;
updateServiceWatcher();
emit watchServiceStatusChanged();
connectSignalHandler();
connectPropertyHandler();
}
}
DeclarativeDBusInterface::Status DeclarativeDBusInterface::status() const
{
return m_status;
}
187
188
189
190
191
/*!
\qmlproperty string DBusInterface::service
This property holds the service name of the service to connect to.
*/
192
QString DeclarativeDBusInterface::service() const
193
{
194
return m_service;
195
196
}
197
void DeclarativeDBusInterface::setService(const QString &service)
198
{
199
if (m_service != service) {
200
invalidateIntrospection();
201
202
m_service = service;
203
204
updateServiceWatcher();
205
emit serviceChanged();
206
207
connectSignalHandler();
208
connectPropertyHandler();
209
210
211
}
}
212
213
214
215
216
/*!
\qmlproperty string DBusInterface::path
This property holds the object path of the object to access.
*/
217
218
219
220
221
222
223
224
QString DeclarativeDBusInterface::path() const
{
return m_path;
}
void DeclarativeDBusInterface::setPath(const QString &path)
{
if (m_path != path) {
225
invalidateIntrospection();
226
227
228
m_path = path;
emit pathChanged();
229
230
connectSignalHandler();
231
connectPropertyHandler();
232
233
234
}
}
235
236
237
238
239
/*!
\qmlproperty string DBusInterface::iface
This property holds the interface.
*/
240
241
242
243
244
245
246
247
QString DeclarativeDBusInterface::interface() const
{
return m_interface;
}
void DeclarativeDBusInterface::setInterface(const QString &interface)
{
if (m_interface != interface) {
248
invalidateIntrospection();
249
250
251
m_interface = interface;
emit interfaceChanged();
252
253
connectSignalHandler();
254
connectPropertyHandler();
255
256
257
}
}
258
259
260
261
262
263
264
265
266
267
/*!
\qmlproperty enum DBusInterface::bus
This property holds whether to use the session or system D-Bus.
\list
\li DBus.SessionBus - The D-Bus session bus
\li DBus.SystemBus - The D-Bus system bus
\endlist
*/
268
DeclarativeDBus::BusType DeclarativeDBusInterface::bus() const
269
{
270
return m_bus;
271
272
}
273
void DeclarativeDBusInterface::setBus(DeclarativeDBus::BusType bus)
274
{
275
if (m_bus != bus) {
276
invalidateIntrospection();
277
278
m_bus = bus;
279
updateServiceWatcher();
280
emit busChanged();
281
282
connectSignalHandler();
283
connectPropertyHandler();
284
285
286
}
}
287
288
289
290
291
292
/*!
\qmlproperty bool DBusInterface::signalsEnabled
This property holds whether this object listens signal emissions on the remote D-Bus object. See
\l {Handling D-Bus Signals}.
*/
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
bool DeclarativeDBusInterface::signalsEnabled() const
{
return m_signalsEnabled;
}
void DeclarativeDBusInterface::setSignalsEnabled(bool enabled)
{
if (m_signalsEnabled != enabled) {
if (!enabled)
disconnectSignalHandler();
m_signalsEnabled = enabled;
emit signalsEnabledChanged();
connectSignalHandler();
308
309
310
}
}
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
bool DeclarativeDBusInterface::propertiesEnabled() const
{
return m_propertiesEnabled;
}
void DeclarativeDBusInterface::setPropertiesEnabled(bool enabled)
{
if (m_propertiesEnabled != enabled) {
if (!m_signalsEnabled)
disconnectPropertyHandler();
m_propertiesEnabled = enabled;
emit propertiesEnabledChanged();
queryPropertyValues(); // connectPropertyHandler will call this as well. This just cover the case where connectPropertyHandler was previously called and m_propertiesEnabled was false.
connectPropertyHandler();
}
}
330
QVariantList DeclarativeDBusInterface::argumentsFromScriptValue(const QJSValue &arguments)
331
332
333
334
{
QVariantList dbusArguments;
if (arguments.isArray()) {
335
336
337
QJSValueIterator it(arguments);
while (it.hasNext()) {
it.next();
338
339
340
// Arrays carry the size as last value
if (!it.hasNext())
continue;
341
342
dbusArguments.append(it.value().toVariant());
}
343
} else if (!arguments.isUndefined()) {
344
dbusArguments.append(arguments.toVariant());
345
346
}
347
348
349
return dbusArguments;
}
350
/*!
351
\qmlmethod void DBusInterface::call(string method, variant arguments, variant callback, variant errorCallback)
352
353
354
355
Call a D-Bus method with the name \a method on the object with \a arguments as either a single
value or an array. For a function with no arguments, pass in \c undefined.
356
357
358
359
360
When the function returns, call \a callback with a single argument that is the return value. The
\a callback argument is optional, if set to \c undefined (the default), the return value will be
discarded. If the function fails \a errorCallback is called if it is not set to \c undefined
(the default).
361
362
363
364
365
\note This function supports passing basic data types and will fail if the signature of the
remote method does not match the signature determined from the type of \a arguments. The
\l typedCall() function can be used to explicity specify the type of each element of
\a arguments.
*/
366
367
368
369
370
void DeclarativeDBusInterface::call(
const QString &method,
const QJSValue &arguments,
const QJSValue &callback,
const QJSValue &errorCallback)
371
372
373
{
QVariantList dbusArguments = argumentsFromScriptValue(arguments);
374
QDBusMessage message = QDBusMessage::createMethodCall(
375
m_service,
376
377
378
379
m_path,
m_interface,
method);
message.setArguments(dbusArguments);
380
381
dispatch(message, callback, errorCallback);
382
383
}
384
385
386
template<typename T> static QList<T> toQList(const QVariantList &lst)
{
QList<T> arr;
387
foreach (const QVariant &var, lst) {
388
389
390
391
392
arr << qvariant_cast<T>(var);
}
return arr;
}
393
394
static QStringList toQStringList(const QVariantList &lst)
{
395
QStringList arr;
396
foreach (const QVariant &var, lst) {
397
398
399
arr << qvariant_cast<QString>(var);
}
return arr;
400
}
401
402
403
static QByteArray toQByteArray(const QVariantList &lst)
{
404
QByteArray arr;
405
foreach (const QVariant &var, lst) {
406
407
408
409
uchar tmp = static_cast<uchar>(var.toUInt());
arr.append(static_cast<char>(tmp));
}
return arr;
410
}
411
412
413
414
415
416
static bool flattenVariantList(QVariant &var, const QVariantList &lst,
int typeChar)
{
bool res = true;
417
switch (typeChar) {
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
case 'b': // BOOLEAN
var = QVariant::fromValue(toQList<bool>(lst));
break;
case 'y': // BYTE
var = QVariant::fromValue(toQByteArray(lst));
break;
case 'q': // UINT16
var = QVariant::fromValue(toQList<quint16>(lst));
break;
case 'u': // UINT32
var = QVariant::fromValue(toQList<quint32>(lst));
break;
case 't': // UINT64
var = QVariant::fromValue(toQList<quint64>(lst));
break;
case 'n': // INT16
var = QVariant::fromValue(toQList<qint16>(lst));
break;
case 'i': // INT32
var = QVariant::fromValue(toQList<qint32>(lst));
break;
case 'x': // INT64
var = QVariant::fromValue(toQList<qint64>(lst));
break;
case 'd': // DOUBLE
var = QVariant::fromValue(toQList<double>(lst));
break;
case 's': // STRING
var = QVariant::fromValue(toQStringList(lst));
break;
default:
res = false;
break;
}
return res;
}
455
456
static bool flattenVariantArrayForceType(QVariant &var, int typeChar)
457
{
458
459
460
461
462
463
464
465
466
return flattenVariantList(var, var.toList(), typeChar);
}
static void flattenVariantArrayGuessType(QVariant &var)
{
/* If the value can't be converted to a variant list
* or if the resulting list would be empty: use the
* value without modification */
QVariantList arr = var.toList();
467
if (arr.empty())
468
469
470
471
472
return;
/* If all items in the list do not share the same type:
* use as is -> each value will be wrapped in variant
* container */
473
474
475
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
int t = arr[0].typeId();
#else
476
int t = arr[0].type();
477
#endif
478
int n = arr.size();
479
for (int i = 1; i < n; ++i) {
480
481
482
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
if (arr[i].typeId() != t)
#else
483
if (arr[i].type() != t)
484
#endif
485
486
487
return;
}
488
489
490
491
492
493
494
495
496
497
498
499
500
switch (t) {
case QVariant::String:
flattenVariantList(var, arr, 's');
break;
case QVariant::Bool:
flattenVariantList(var, arr, 'b');
break;
case QVariant::Int:
flattenVariantList(var, arr, 'i');
break;
case QVariant::Double:
flattenVariantList(var, arr, 'd');
break;
501
502
503
504
default:
/* Unhandled types are encoded as variant:array:variant:val
* instead of variant:array:val what we actually want.
*/
505
506
507
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
qWarning("unhandled array type: %d (%s)", t, QMetaType(t).name());
#else
508
qWarning("unhandled array type: %d (%s)", t, QVariant::typeToName(t));
509
#endif
510
break;
511
512
513
}
}
514
515
bool
DeclarativeDBusInterface::marshallDBusArgument(QDBusMessage &msg, const QJSValue &arg)
516
{
517
QJSValue type = arg.property(QLatin1String("type"));
518
519
520
if (!type.isString()) {
qWarning() << "DeclarativeDBusInterface::typedCall - Invalid type";
521
522
qmlInfo(this) << "DeclarativeDBusInterface::typedCall - Invalid type";
return false;
523
524
}
525
526
QJSValue value = arg.property(QLatin1String("value"));
527
if (value.isNull() || value.isUndefined()) {
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
575
576
577
578
579
580
581
582
583
584
585
586
587
qWarning() << "DeclarativeDBusInterface::typedCall - Invalid argument";
qmlInfo(this) << "DeclarativeDBusInterface::typedCall - Invalid argument";
return false;
}
QString t = type.toString();
if (t.length() == 1) {
switch (t.at(0).toLatin1()) {
case 'y': // BYTE
msg << QVariant::fromValue(static_cast<quint8>(value.toUInt()));
return true;
case 'q': // UINT16
msg << QVariant::fromValue(static_cast<quint16>(value.toUInt()));
return true;
case 'u': // UINT32
msg << QVariant::fromValue(static_cast<quint32>(value.toUInt()));
return true;
case 't': // UINT64
msg << QVariant::fromValue(static_cast<quint64>(value.toVariant().toULongLong()));
return true;
case 'n': // INT16
msg << QVariant::fromValue(static_cast<qint16>(value.toInt()));
return true;
case 'i': // INT32
msg << QVariant::fromValue(static_cast<qint32>(value.toInt()));
return true;
case 'x': // INT64
msg << QVariant::fromValue(static_cast<qint64>(value.toVariant().toLongLong()));
return true;
case 'b': // BOOLEAN
msg << value.toBool();
return true;
case 'd': // DOUBLE
msg << value.toNumber();
return true;
case 's': // STRING
msg << value.toString();
return true;
case 'o': // OBJECT_PATH
msg << QVariant::fromValue(QDBusObjectPath(value.toString()));
return true;
case 'g': // SIGNATURE
msg << QVariant::fromValue(QDBusSignature(value.toString()));
return true;
case 'h': // UNIX_FD
msg << QVariant::fromValue(QDBusUnixFileDescriptor(value.toInt()));
return true;
588
589
590
591
592
case 'v': { // VARIANT
QVariant var = value.toVariant();
flattenVariantArrayGuessType(var);
msg << QVariant::fromValue(QDBusVariant(var));
}
593
594
595
596
597
598
599
600
601
return true;
default:
break;
}
} else if (t.length() == 2 && (t.at(0).toLatin1() == 'a')) {
// The result must be an array of typed data
if (!value.isArray()) {
qWarning() << "Invalid value for type specifier:" << t << "v:" << value.toVariant();
602
qmlInfo(this) << "Invalid value for type specifier: " << t << " v: " << value.toVariant();
603
604
605
606
607
608
return false;
}
QVariant vec = value.toVariant();
int type = t.at(1).toLatin1();
609
if (flattenVariantArrayForceType(vec, type)) {
610
611
msg << vec;
return true;
612
}
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
} else if (t == "a{sv}") {
if (!value.isObject()) {
qWarning() << "Invalid value for type specifier:" << t << "v:" << value.toVariant();
qmlInfo(this) << "Invalid value for type specifier: " << t << " v: " << value.toVariant();
return false;
}
QVariantMap variantMap;
QJSValueIterator it(value);
while (it.hasNext()) {
it.next();
QVariant var = it.value().toVariant();
flattenVariantArrayGuessType(var);
variantMap.insert(it.name(), var);
}
msg << variantMap;
return true;
630
631
}
632
qWarning() << "DeclarativeDBusInterface::typedCall - Invalid type specifier:" << t;
633
qmlInfo(this) << "DeclarativeDBusInterface::typedCall - Invalid type specifier: " << t;
634
return false;
635
636
}
637
638
639
640
641
642
QDBusMessage
DeclarativeDBusInterface::constructMessage(const QString &service,
const QString &path,
const QString &interface,
const QString &method,
const QJSValue &arguments)
643
{
644
QDBusMessage message = QDBusMessage::createMethodCall(service, path, interface, method);
645
646
if (arguments.isArray()) {
647
quint32 len = arguments.property(QLatin1String("length")).toUInt();
648
for (quint32 i = 0; i < len; ++i) {
649
if (!marshallDBusArgument(message, arguments.property(i)))
650
return QDBusMessage();
651
652
653
}
} else if (!arguments.isUndefined()) {
// arguments is a singular typed value
654
if (!marshallDBusArgument(message, arguments))
655
return QDBusMessage();
656
}
657
658
659
return message;
}
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
void DeclarativeDBusInterface::updateServiceWatcher()
{
delete m_serviceWatcher;
m_serviceWatcher = nullptr;
if (!m_service.isEmpty() && m_watchServiceStatus) {
QDBusConnection conn = DeclarativeDBus::connection(m_bus);
m_serviceWatcher = new QDBusServiceWatcher(m_service, conn,
QDBusServiceWatcher::WatchForRegistration |
QDBusServiceWatcher::WatchForUnregistration, this);
connect(m_serviceWatcher, &QDBusServiceWatcher::serviceRegistered,
this, &DeclarativeDBusInterface::serviceRegistered);
connect(m_serviceWatcher, &QDBusServiceWatcher::serviceUnregistered,
this, &DeclarativeDBusInterface::serviceUnregistered);
if (conn.interface()->isServiceRegistered(m_service)) {
QMetaObject::invokeMethod(this, "serviceRegistered", Qt::QueuedConnection);
}
}
}
bool DeclarativeDBusInterface::serviceAvailable() const
{
// If we're not interrested about watching service status, treat service as available.
return !m_watchServiceStatus || m_status == Available;
}
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
/*!
\qmlmethod bool DBusInterface::typedCall(string method, variant arguments, variant callback, variant errorCallback)
Call a D-Bus method with the name \a method on the object with \a arguments. Each parameter is
described by an object:
\code
{
'type': 'o'
'value': '/org/example'
}
\endcode
Where \c type is the D-Bus type that \c value should be marshalled as. \a arguments can be
either a single object describing the parameter or an array of objects.
When the function returns, call \a callback with a single argument that is the return value. The
\a callback argument is optional, if set to \c undefined (the default), the return value will be
discarded. If the function fails \a errorCallback is called if it is not set to \c undefined
(the default).
*/
708
709
bool DeclarativeDBusInterface::typedCall(const QString &method, const QJSValue &arguments,
const QJSValue &callback,
710
const QJSValue &errorCallback)
711
{
712
QDBusMessage message = constructMessage(m_service, m_path, m_interface, method, arguments);
713
if (message.type() == QDBusMessage::InvalidMessage) {
714
qmlInfo(this) << "Invalid message, cannot call method: " << method;
715
return false;
716
}
717
718
719
720
721
722
723
return dispatch(message, callback, errorCallback);
}
bool DeclarativeDBusInterface::dispatch(
const QDBusMessage &message, const QJSValue &callback, const QJSValue &errorCallback)
{
724
QDBusConnection conn = DeclarativeDBus::connection(m_bus);
725
726
727
728
729
730
if (callback.isUndefined()) {
// Call without waiting for return value (callback is undefined)
if (!conn.send(message)) {
qmlInfo(this) << conn.lastError();
}
731
return true;
732
}
733
734
// If we have a non-undefined callback, it must be callable
735
736
if (!callback.isCallable()) {
qmlInfo(this) << "Callback argument is not a function";
737
return false;
738
739
}
740
741
if (!errorCallback.isUndefined() && !errorCallback.isCallable()) {
qmlInfo(this) << "Error callback argument is not a function or undefined";
742
return false;
743
744
}
745
746
747
748
QDBusPendingCall pendingCall = conn.asyncCall(message);
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pendingCall);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
this, SLOT(pendingCallFinished(QDBusPendingCallWatcher*)));
749
m_pendingCalls.insert(watcher, qMakePair(callback, errorCallback));
750
return true;
751
752
}
753
754
755
756
757
/*!
\qmlproperty variant DBusInteface::getProperty(string name)
Returns the the D-Bus property named \a name from the object.
*/
758
759
760
QVariant DeclarativeDBusInterface::getProperty(const QString &name)
{
QDBusMessage message =
761
762
763
QDBusMessage::createMethodCall(m_service, m_path,
PropertyInterface,
QLatin1String("Get"));
764
765
766
767
768
769
770
QVariantList args;
args.append(m_interface);
args.append(name);
message.setArguments(args);
771
QDBusConnection conn = DeclarativeDBus::connection(m_bus);
772
773
774
775
776
777
778
QDBusMessage reply = conn.call(message);
if (reply.type() == QDBusMessage::ErrorMessage)
return QVariant();
if (reply.arguments().isEmpty())
return QVariant();
779
return NemoDBus::demarshallDBusArgument(reply.arguments().first());
780
781
}
782
783
784
785
786
787
788
/*!
\qmlmethod void DBusInterface::setProperty(string name, variant value)
Sets the D-Bus property named \a name on the object to \a value.
\since version 2.0.0
*/
789
void DeclarativeDBusInterface::setProperty(const QString &name, const QVariant &newValue)
790
791
{
QDBusMessage message = QDBusMessage::createMethodCall(m_service, m_path,
792
793
PropertyInterface,
QLatin1String("Set"));
794
795
796
797
798
QVariant value = newValue;
if (value.userType() == qMetaTypeId<QJSValue>())
value = value.value<QJSValue>().toVariant();
799
800
801
802
QVariantList args;
args.append(m_interface);
args.append(name);
803
args.append(QVariant::fromValue(QDBusVariant(value)));
804
message.setArguments(args);
805
806
807
808
809
810
QDBusConnection conn = DeclarativeDBus::connection(m_bus);
if (!conn.send(message))
qmlInfo(this) << conn.lastError();
}
811
812
813
814
815
816
817
818
void DeclarativeDBusInterface::classBegin()
{
}
void DeclarativeDBusInterface::componentComplete()
{
m_componentCompleted = true;
connectSignalHandler();
819
connectPropertyHandler();
820
821
}
822
823
void DeclarativeDBusInterface::pendingCallFinished(QDBusPendingCallWatcher *watcher)
{
824
QPair<QJSValue, QJSValue> callbacks = m_pendingCalls.take(watcher);
825
826
827
828
829
830
watcher->deleteLater();
QDBusPendingReply<> reply = *watcher;
if (reply.isError()) {
831
832
QJSValue errorCallback = callbacks.second;
if (errorCallback.isCallable()) {
833
834
835
QDBusError error = reply.error();
QJSValueList args = { QJSValue(error.name()), QJSValue(error.message()) };
QJSValue result = errorCallback.call(args);
836
837
838
if (result.isError()) {
qmlInfo(this) << "Error executing error handling callback";
}
839
840
} else {
qmlInfo(this) << reply.error();
841
}
842
843
844
845
return;
}
846
847
848
849
QJSValue callback = callbacks.first;
if (!callback.isCallable())
return;
850
851
852
853
854
855
QJSEngine *engine = qjsEngine(this);
if (!engine) {
qmlInfo(this) << "Error getting QJSEngine";
return;
}
856
857
QDBusMessage message = reply.reply();
858
QJSValueList callbackArguments;
859
860
861
QVariantList arguments = message.arguments();
foreach (QVariant argument, arguments) {
862
callbackArguments << engine->toScriptValue<QVariant>(NemoDBus::demarshallDBusArgument(argument));
863
864
}
865
866
867
868
QJSValue result = callback.call(callbackArguments);
if (result.isError()) {
qmlInfo(this) << "Error executing callback";
}
869
}
870
871
872
873
void DeclarativeDBusInterface::signalHandler(const QDBusMessage &message)
{
QVariantList arguments = message.arguments();
874
QVariantList normalized;
875
876
877
878
QGenericArgument args[10];
for (int i = 0; i < qMin(arguments.length(), 10); ++i) {
879
const QVariant &tmp = arguments.at(i);
880
normalized.append(NemoDBus::demarshallDBusArgument(tmp));
881
882
883
884
}
for (int i = 0; i < normalized.count(); ++i) {
const QVariant &arg = normalized.at(i);
885
886
887
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
args[i] = QGenericArgument(QMetaType(arg.metaType()).name(), arg.data());
#else
888
args[i] = Q_ARG(QVariant, arg);
889
#endif
890
891
892
893
894
895
}
QMetaMethod method = m_signals.value(message.member());
if (!method.isValid())
return;
896
897
method.invoke(this, args[0], args[1], args[2], args[3], args[4],
args[5], args[6], args[7], args[8], args[9]);
898
899
}
900
static int indexOfMangledName(const QString &name, const QStringList &candidates)
901
{
902
903
904
905
int index = candidates.indexOf(name);
if (index >= 0) {
return index;
} else if (name.length() > 2
906
907
&& name.startsWith(QStringLiteral("rc"))
&& name.at(2).isUpper()) {
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
// API version 1.0 name mangling:
// Connect QML signals with the prefix 'rc' followed by an upper-case
// letter to DBus signals of the same name minus the prefix.
return candidates.indexOf(name.mid(2));
} else if (name.length() >= 2) {
// API version 2.0 name mangling:
// "methodName" -> "MethodName" (if a corresponding signal exists)
return candidates.indexOf(name.at(0).toUpper() + name.mid(1));
} else {
return -1;
}
}
void DeclarativeDBusInterface::introspectionDataReceived(const QString &introspectionData)
{
invalidateIntrospection();
m_introspected = true;
926
QStringList dbusSignals;
927
QStringList dbusProperties;
928
929
930
931
932
933
934
935
936
QXmlStreamReader xml(introspectionData);
while (!xml.atEnd()) {
if (!xml.readNextStartElement())
continue;
if (xml.name() == QLatin1String("node"))
continue;
937
938
939
bool skip = false;
if (xml.name() != QLatin1String("interface")) {
skip = true;
940
941
942
943
944
} else {
if (xml.attributes().value(QLatin1String("name")) == PropertyInterface) {
m_providesPropertyInterface = true;
}
skip = xml.attributes().value(QLatin1String("name")) != m_interface;
945
946
947
}
if (skip) {
948
949
950
951
952
953
954
955
956
957
xml.skipCurrentElement();
continue;
}
while (!xml.atEnd()) {
if (!xml.readNextStartElement())
break;
if (xml.name() == QLatin1String("signal"))
dbusSignals.append(xml.attributes().value(QLatin1String("name")).toString());
958
959
if (xml.name() == QLatin1String("property"))
dbusProperties.append(xml.attributes().value(QStringLiteral("name")).toString());
960
961
xml.skipCurrentElement();
962
963
964
}
}
965
if (dbusSignals.isEmpty() && dbusProperties.isEmpty() && !m_propertiesEnabled)
966
967
return;
968
969
// Skip over signals defined in DeclarativeDBusInterface and its parent classes
// so only signals defined in qml are connected to.
970
const QMetaObject *const meta = metaObject();
971
972
for (int i = staticMetaObject.methodCount(); i < meta->methodCount(); ++i) {
QMetaMethod method = meta->method(i);
973
974
975
976
const int index = indexOfMangledName(method.name(), dbusSignals);
if (index < 0)
continue;
977
978
979
980
981
982
983
984
m_signals.insert(dbusSignals.at(index), method);
dbusSignals.removeAt(index);
if (dbusSignals.isEmpty())
break;
}
985
986
987
988
989
990
for (int i = staticMetaObject.propertyCount(); i < meta->propertyCount(); ++i) {
QMetaProperty property = meta->property(i);
const int index = indexOfMangledName(property.name(), dbusProperties);
if (index < 0)
991
992
continue;
993
m_properties.insert(dbusProperties.at(index), property);
994
995
dbusProperties.removeAt(index);
996
997
if (dbusProperties.isEmpty())
998
999
break;
}
1000