Debian Codegraph @

src/util/ddbusextendedabstractinterface.cpp

raw
1 // SPDX-FileCopyrightText: 2015 Jolla Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4
5 #include "ddbusextendedpendingcallwatcher_p.h"
6
7 #include <DDBusExtendedAbstractInterface>
8
9 #include <QtDBus/QDBusMessage>
10 #include <QtDBus/QDBusMetaType>
11 #include <QtDBus/QDBusPendingCall>
12 #include <QtDBus/QDBusPendingCallWatcher>
13 #include <QtDBus/QDBusPendingReply>
14
15 #include <QtCore/QDebug>
16 #include <QtCore/QMetaProperty>
17
18 DCORE_BEGIN_NAMESPACE
19
20 Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, dBusInterface, ("org.freedesktop.DBus"))
21 Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, dBusPropertiesInterface, ("org.freedesktop.DBus.Properties"))
22 Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, dBusPropertiesChangedSignal, ("PropertiesChanged"))
23 Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, propertyChangedSignature, ("propertyChanged(QString,QVariant)"))
24 Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, propertyInvalidatedSignature, ("propertyInvalidated(QString)"))
25
26 DDBusExtendedAbstractInterface::DDBusExtendedAbstractInterface(
27 const QString &service, const QString &path, const char *interface, const QDBusConnection &connection, QObject *parent)
28 : QDBusAbstractInterface(service, path, interface, connection, parent)
29 , m_sync(true)
30 , m_useCache(false)
31 , m_getAllPendingCallWatcher(0)
32 , m_propertiesChangedConnected(false)
33 {
34 const_cast<QDBusConnection &>(connection)
35 .connect(QString("org.freedesktop.DBus"),
36 QString("/org/freedesktop/DBus"),
37 QString("org.freedesktop.DBus"),
38 QString("NameOwnerChanged"),
39 this,
40 SLOT(onDBusNameOwnerChanged(QString, QString, QString)));
41 }
42
43 DDBusExtendedAbstractInterface::~DDBusExtendedAbstractInterface() {}
44
45 void DDBusExtendedAbstractInterface::setSync(bool sync)
46 {
47 setSync(sync, true);
48 }
49
50 /*
51 * @~english
52 * @note After sync is set to false, it will always return a empty value
53 * if you call the property's get function directly. So you can only get it
54 * through the changed signal when you get an property, and it's also a good
55 * idea to save a cache yourself.
56 */
57 void DDBusExtendedAbstractInterface::setSync(bool sync, bool autoStart)
58 {
59 m_sync = sync;
60
61 // init all properties
62 if (autoStart && !m_sync && !isValid())
63 startServiceProcess();
64 }
65
66 void DDBusExtendedAbstractInterface::getAllProperties()
67 {
68 m_lastExtendedError = QDBusError();
69
70 if (!isValid()) {
71 QString errorMessage = QStringLiteral("This Extended DBus interface is not valid yet.");
72 m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
73 qDebug() << Q_FUNC_INFO << errorMessage;
74 return;
75 }
76
77 if (!m_sync && m_getAllPendingCallWatcher) {
78 // Call already in place, not repeating ...
79 return;
80 }
81
82 QDBusMessage msg = QDBusMessage::createMethodCall(service(), path(), *dBusPropertiesInterface(), QStringLiteral("GetAll"));
83 msg << interface();
84
85 if (m_sync) {
86 QDBusMessage reply = connection().call(msg);
87
88 if (reply.type() != QDBusMessage::ReplyMessage) {
89 m_lastExtendedError = QDBusError(reply);
90 qWarning() << Q_FUNC_INFO << m_lastExtendedError.message();
91 return;
92 }
93
94 if (reply.signature() != QLatin1String("a{sv}")) {
95 QString errorMessage = QStringLiteral("Invalid signature \"%1\" in return from call to %2")
96 .arg(reply.signature(), QString(*dBusPropertiesInterface()));
97 qWarning() << Q_FUNC_INFO << errorMessage;
98 m_lastExtendedError = QDBusError(QDBusError::InvalidSignature, errorMessage);
99 return;
100 }
101
102 QVariantMap value = reply.arguments().at(0).toMap();
103 onPropertiesChanged(interface(), value, QStringList());
104 } else {
105 QDBusPendingReply<QVariantMap> async = connection().asyncCall(msg);
106 m_getAllPendingCallWatcher = new QDBusPendingCallWatcher(async, this);
107
108 connect(m_getAllPendingCallWatcher,
109 SIGNAL(finished(QDBusPendingCallWatcher *)),
110 this,
111 SLOT(onAsyncGetAllPropertiesFinished(QDBusPendingCallWatcher *)));
112 return;
113 }
114 }
115
116 void DDBusExtendedAbstractInterface::connectNotify(const QMetaMethod &signal)
117 {
118 if (signal.methodType() == QMetaMethod::Signal && (signal.methodSignature() == *propertyChangedSignature() ||
119 signal.methodSignature() == *propertyInvalidatedSignature())) {
120 if (!m_propertiesChangedConnected) {
121 QStringList argumentMatch;
122 argumentMatch << interface();
123 connection().connect(service(),
124 path(),
125 *dBusPropertiesInterface(),
126 *dBusPropertiesChangedSignal(),
127 argumentMatch,
128 QString(),
129 this,
130 SLOT(onPropertiesChanged(QString, QVariantMap, QStringList)));
131
132 m_propertiesChangedConnected = true;
133 return;
134 }
135 } else {
136 QDBusAbstractInterface::connectNotify(signal);
137 }
138 }
139
140 void DDBusExtendedAbstractInterface::disconnectNotify(const QMetaMethod &signal)
141 {
142 if (signal.methodType() == QMetaMethod::Signal && (signal.methodSignature() == *propertyChangedSignature() ||
143 signal.methodSignature() == *propertyInvalidatedSignature())) {
144 if (m_propertiesChangedConnected && 0 == receivers(propertyChangedSignature()->constData()) &&
145 0 == receivers(propertyInvalidatedSignature()->constData())) {
146 QStringList argumentMatch;
147 argumentMatch << interface();
148 connection().disconnect(service(),
149 path(),
150 *dBusPropertiesInterface(),
151 *dBusPropertiesChangedSignal(),
152 argumentMatch,
153 QString(),
154 this,
155 SLOT(onPropertiesChanged(QString, QVariantMap, QStringList)));
156
157 m_propertiesChangedConnected = false;
158 return;
159 }
160 } else {
161 QDBusAbstractInterface::disconnectNotify(signal);
162 }
163 }
164
165 QVariant DDBusExtendedAbstractInterface::internalPropGet(const char *propname, void *propertyPtr)
166 {
167 m_lastExtendedError = QDBusError();
168
169 if (m_useCache) {
170 int propertyIndex = metaObject()->indexOfProperty(propname);
171 QMetaProperty metaProperty = metaObject()->property(propertyIndex);
172 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
173 return QVariant{metaProperty.metaType(), propertyPtr};
174 #else
175 return QVariant(metaProperty.userType(), propertyPtr);
176 #endif
177 }
178
179 if (m_sync) {
180 QVariant ret = property(propname);
181
182 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
183 ret.metaType().construct(propertyPtr, ret.constData());
184 #else
185 QMetaType::construct(ret.userType(), propertyPtr, ret.constData());
186
187 #endif
188 return ret;
189 } else {
190 if (!isValid()) {
191 QString errorMessage = QStringLiteral("This Extended DBus interface is not valid yet.");
192 m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
193 qDebug() << Q_FUNC_INFO << errorMessage;
194 return QVariant();
195 }
196
197 int propertyIndex = metaObject()->indexOfProperty(propname);
198
199 if (-1 == propertyIndex) {
200 QString errorMessage = QStringLiteral("Got unknown property \"%1\" to read").arg(QString::fromLatin1(propname));
201 m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
202 qWarning() << Q_FUNC_INFO << errorMessage;
203 return QVariant();
204 }
205
206 QMetaProperty metaProperty = metaObject()->property(propertyIndex);
207
208 if (!metaProperty.isReadable()) {
209 QString errorMessage = QStringLiteral("Property \"%1\" is NOT readable").arg(QString::fromLatin1(propname));
210 m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
211 qWarning() << Q_FUNC_INFO << errorMessage;
212 return QVariant();
213 }
214
215 // is this metatype registered?
216 const char *expectedSignature = "";
217 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
218 if (metaProperty.typeId() != QMetaType::QVariant) {
219 expectedSignature = QDBusMetaType::typeToSignature(metaProperty.metaType());
220 #else
221 if (int(metaProperty.type()) != QMetaType::QVariant) {
222 expectedSignature = QDBusMetaType::typeToSignature(metaProperty.userType());
223 #endif
224 if (0 == expectedSignature) {
225 QString errorMessage = QStringLiteral("Type %1 must be registered with Qt D-Bus "
226 "before it can be used to read property "
227 "%2.%3")
228 .arg(metaProperty.typeName(), interface(), propname);
229 m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
230 qWarning() << Q_FUNC_INFO << errorMessage;
231 return QVariant();
232 }
233 }
234
235 asyncProperty(propname);
236 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
237 return QVariant{metaProperty.metaType(), propertyPtr};
238 #else
239 return QVariant(metaProperty.userType(), propertyPtr);
240 #endif
241 }
242 }
243
244 void DDBusExtendedAbstractInterface::internalPropSet(const char *propname, const QVariant &value, void *propertyPtr)
245 {
246 m_lastExtendedError = QDBusError();
247
248 if (m_sync) {
249 setProperty(propname, value);
250 } else {
251 if (!isValid()) {
252 QString errorMessage = QStringLiteral("This interface is not yet valid");
253 m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
254 qDebug() << Q_FUNC_INFO << errorMessage;
255 return;
256 }
257
258 int propertyIndex = metaObject()->indexOfProperty(propname);
259
260 if (-1 == propertyIndex) {
261 QString errorMessage = QStringLiteral("Got unknown property \"%1\" to write").arg(QString::fromLatin1(propname));
262 m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
263 qWarning() << Q_FUNC_INFO << errorMessage;
264 return;
265 }
266
267 QMetaProperty metaProperty = metaObject()->property(propertyIndex);
268
269 if (!metaProperty.isWritable()) {
270 QString errorMessage = QStringLiteral("Property \"%1\" is NOT writable").arg(QString::fromLatin1(propname));
271 m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
272 qWarning() << Q_FUNC_INFO << errorMessage;
273 return;
274 }
275
276 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
277 QVariant variant = QVariant{metaProperty.metaType(), propertyPtr};
278 #else
279 QVariant variant = QVariant(metaProperty.type(), propertyPtr);
280 #endif
281 variant = value;
282
283 asyncSetProperty(propname, variant);
284 }
285 }
286
287 QVariant DDBusExtendedAbstractInterface::asyncProperty(const QString &propertyName)
288 {
289 QDBusMessage msg = QDBusMessage::createMethodCall(service(), path(), *dBusPropertiesInterface(), QStringLiteral("Get"));
290 msg << interface() << propertyName;
291 QDBusPendingReply<QVariant> async = connection().asyncCall(msg);
292 DDBusExtendedPendingCallWatcher *watcher = new DDBusExtendedPendingCallWatcher(async, propertyName, QVariant(), this);
293
294 connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher *)), this, SLOT(onAsyncPropertyFinished(QDBusPendingCallWatcher *)));
295
296 return QVariant();
297 }
298
299 void DDBusExtendedAbstractInterface::asyncSetProperty(const QString &propertyName, const QVariant &value)
300 {
301 QDBusMessage msg = QDBusMessage::createMethodCall(service(), path(), *dBusPropertiesInterface(), QStringLiteral("Set"));
302
303 msg << interface() << propertyName << QVariant::fromValue(QDBusVariant(value));
304 QDBusPendingReply<> async = connection().asyncCall(msg);
305 DDBusExtendedPendingCallWatcher *watcher = new DDBusExtendedPendingCallWatcher(async, propertyName, value, this);
306
307 connect(
308 watcher, SIGNAL(finished(QDBusPendingCallWatcher *)), this, SLOT(onAsyncSetPropertyFinished(QDBusPendingCallWatcher *)));
309 }
310
311 void DDBusExtendedAbstractInterface::startServiceProcess()
312 {
313 const QString &servName = service();
314
315 if (isValid()) {
316 qWarning() << "Service" << servName << "is already started.";
317 return;
318 }
319
320 QDBusMessage msg =
321 QDBusMessage::createMethodCall("org.freedesktop.DBus", "/", *dBusInterface(), QStringLiteral("StartServiceByName"));
322 msg << servName << quint32(0);
323 QDBusPendingReply<quint32> async = connection().asyncCall(msg);
324 QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(async, this);
325
326 connect(watcher, &QDBusPendingCallWatcher::finished, this, &DDBusExtendedAbstractInterface::onStartServiceProcessFinished);
327 }
328
329 void DDBusExtendedAbstractInterface::onStartServiceProcessFinished(QDBusPendingCallWatcher *w)
330 {
331 if (w->isError()) {
332 m_lastExtendedError = w->error();
333 } else {
334 m_lastExtendedError = QDBusError();
335 }
336
337 QDBusPendingReply<quint32> reply = *w;
338
339 Q_EMIT serviceStartFinished(reply.value());
340
341 w->deleteLater();
342 }
343
344 void DDBusExtendedAbstractInterface::onAsyncPropertyFinished(QDBusPendingCallWatcher *w)
345 {
346 DDBusExtendedPendingCallWatcher *watcher = qobject_cast<DDBusExtendedPendingCallWatcher *>(w);
347 Q_ASSERT(watcher);
348
349 QDBusPendingReply<QVariant> reply = *watcher;
350
351 if (reply.isError()) {
352 m_lastExtendedError = reply.error();
353 } else {
354 int propertyIndex = metaObject()->indexOfProperty(watcher->asyncProperty().toLatin1().constData());
355 QVariant value = demarshall(interface(), metaObject()->property(propertyIndex), reply.value(), &m_lastExtendedError);
356
357 if (m_lastExtendedError.isValid()) {
358 Q_EMIT propertyInvalidated(watcher->asyncProperty());
359 } else {
360 Q_EMIT propertyChanged(watcher->asyncProperty(), value);
361 }
362 }
363
364 Q_EMIT asyncPropertyFinished(watcher->asyncProperty());
365 watcher->deleteLater();
366 }
367
368 void DDBusExtendedAbstractInterface::onAsyncSetPropertyFinished(QDBusPendingCallWatcher *w)
369 {
370 DDBusExtendedPendingCallWatcher *watcher = qobject_cast<DDBusExtendedPendingCallWatcher *>(w);
371 Q_ASSERT(watcher);
372
373 QDBusPendingReply<> reply = *watcher;
374
375 if (reply.isError()) {
376 m_lastExtendedError = reply.error();
377 } else {
378 m_lastExtendedError = QDBusError();
379 }
380
381 Q_EMIT asyncSetPropertyFinished(watcher->asyncProperty());
382
383 // Resetting the property to its previous value after sending the
384 // finished signal
385 if (!reply.isError()) {
386 m_lastExtendedError = QDBusError();
387 Q_EMIT propertyChanged(watcher->asyncProperty(), watcher->previousValue());
388 }
389
390 watcher->deleteLater();
391 }
392
393 void DDBusExtendedAbstractInterface::onAsyncGetAllPropertiesFinished(QDBusPendingCallWatcher *watcher)
394 {
395 m_getAllPendingCallWatcher = 0;
396
397 QDBusPendingReply<QVariantMap> reply = *watcher;
398
399 if (reply.isError()) {
400 m_lastExtendedError = reply.error();
401 } else {
402 m_lastExtendedError = QDBusError();
403 }
404
405 Q_EMIT asyncGetAllPropertiesFinished();
406
407 if (!reply.isError()) {
408 onPropertiesChanged(interface(), reply.value(), QStringList());
409 }
410
411 watcher->deleteLater();
412 }
413
414 void DDBusExtendedAbstractInterface::onPropertiesChanged(const QString &interfaceName,
415 const QVariantMap &changedProperties,
416 const QStringList &invalidatedProperties)
417 {
418 if (interfaceName == interface()) {
419 QVariantMap::const_iterator i = changedProperties.constBegin();
420 while (i != changedProperties.constEnd()) {
421 int propertyIndex = metaObject()->indexOfProperty(i.key().toLatin1().constData());
422
423 if (-1 == propertyIndex) {
424 qDebug() << Q_FUNC_INFO << "Got unknown changed property" << i.key();
425 } else {
426 QVariant value = demarshall(interface(), metaObject()->property(propertyIndex), i.value(), &m_lastExtendedError);
427
428 if (m_lastExtendedError.isValid()) {
429 Q_EMIT propertyInvalidated(i.key());
430 } else {
431 Q_EMIT propertyChanged(i.key(), value);
432 }
433 }
434
435 ++i;
436 }
437
438 QStringList::const_iterator j = invalidatedProperties.constBegin();
439 while (j != invalidatedProperties.constEnd()) {
440 if (-1 == metaObject()->indexOfProperty(j->toLatin1().constData())) {
441 qDebug() << Q_FUNC_INFO << "Got unknown invalidated property" << *j;
442 } else {
443 m_lastExtendedError = QDBusError();
444 Q_EMIT propertyInvalidated(*j);
445 }
446
447 ++j;
448 }
449 }
450 }
451
452 void DDBusExtendedAbstractInterface::onDBusNameOwnerChanged(const QString &name, const QString &oldOwner, const QString &newOwner)
453 {
454 if (name == service() && oldOwner.isEmpty()) {
455 m_dbusOwner = newOwner;
456 Q_EMIT serviceValidChanged(true);
457 } else if (name == m_dbusOwner && newOwner.isEmpty()) {
458 m_dbusOwner.clear();
459 Q_EMIT serviceValidChanged(false);
460 }
461 }
462
463 QVariant DDBusExtendedAbstractInterface::demarshall(const QString &interface,
464 const QMetaProperty &metaProperty,
465 const QVariant &value,
466 QDBusError *error)
467 {
468 Q_ASSERT(metaProperty.isValid());
469 Q_ASSERT(error != 0);
470
471 if (value.userType() == metaProperty.userType()) {
472 // No need demarshalling. Passing back straight away ...
473 *error = QDBusError();
474 return value;
475 }
476
477 QString errorMessage;
478 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
479 QVariant result = QVariant{metaProperty.metaType()};
480 const char *expectedSignature = QDBusMetaType::typeToSignature(metaProperty.metaType());
481
482 #else
483 QVariant result = QVariant(metaProperty.userType(), (void *)0);
484 const char *expectedSignature = QDBusMetaType::typeToSignature(metaProperty.userType());
485 #endif
486 if (value.userType() == qMetaTypeId<QDBusArgument>()) {
487 // demarshalling a DBus argument ...
488 QDBusArgument dbusArg = value.value<QDBusArgument>();
489
490 if (expectedSignature == dbusArg.currentSignature().toLatin1()) {
491 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
492 QDBusMetaType::demarshall(dbusArg, metaProperty.metaType(), result.data());
493 #else
494 QDBusMetaType::demarshall(dbusArg, metaProperty.userType(), result.data());
495 #endif
496 if (!result.isValid()) {
497 errorMessage = QStringLiteral("Unexpected failure demarshalling "
498 "upon PropertiesChanged signal arrival "
499 "for property `%3.%4' (expected type `%5' (%6))")
500 .arg(interface,
501 QString::fromLatin1(metaProperty.name()),
502 QString::fromLatin1(metaProperty.typeName()),
503 expectedSignature);
504 }
505 } else {
506 errorMessage = QStringLiteral("Unexpected `user type' (%2) "
507 "upon PropertiesChanged signal arrival "
508 "for property `%3.%4' (expected type `%5' (%6))")
509 .arg(dbusArg.currentSignature(),
510 interface,
511 QString::fromLatin1(metaProperty.name()),
512 QString::fromLatin1(metaProperty.typeName()),
513 QString::fromLatin1(expectedSignature));
514 }
515 } else {
516 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
517 const char *actualSignature = QDBusMetaType::typeToSignature(value.metaType());
518 #else
519 const char *actualSignature = QDBusMetaType::typeToSignature(value.userType());
520 #endif
521
522 errorMessage = QStringLiteral("Unexpected `%1' (%2) "
523 "upon PropertiesChanged signal arrival "
524 "for property `%3.%4' (expected type `%5' (%6))")
525 .arg(QString::fromLatin1(value.typeName()),
526 QString::fromLatin1(actualSignature),
527 interface,
528 QString::fromLatin1(metaProperty.name()),
529 QString::fromLatin1(metaProperty.typeName()),
530 QString::fromLatin1(expectedSignature));
531 }
532
533 if (errorMessage.isEmpty()) {
534 *error = QDBusError();
535 } else {
536 *error = QDBusMessage::createError(QDBusError::InvalidSignature, errorMessage);
537 qDebug() << Q_FUNC_INFO << errorMessage;
538 }
539
540 return result;
541 }
542 DCORE_END_NAMESPACE