Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qdbusviewer.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include "qdbusviewer.h"
5#include "qdbusmodel.h"
8#include "logviewer.h"
9
10#include <QtWidgets/QLineEdit>
11#include <QtWidgets/QVBoxLayout>
12#include <QtWidgets/QSplitter>
13#include <QtWidgets/QInputDialog>
14#include <QtWidgets/QMessageBox>
15#include <QtWidgets/QMenu>
16#include <QtWidgets/QTableWidget>
17#include <QtWidgets/QTreeWidget>
18#include <QtWidgets/QHeaderView>
19
20#include <QtDBus/QDBusConnectionInterface>
21#include <QtDBus/QDBusInterface>
22#include <QtDBus/QDBusMetaType>
23#include <QtDBus/QDBusServiceWatcher>
24
25#include <QtGui/QAction>
26#include <QtGui/QKeyEvent>
27#include <QtGui/QShortcut>
28
29#include <QtCore/QStringListModel>
30#include <QtCore/QMetaProperty>
31#include <QtCore/QSettings>
32
33#include <private/qdbusutil_p.h>
34
35using namespace Qt::StringLiterals;
36
38{
39public:
40 inline QDBusViewModel(const QString &service, const QDBusConnection &connection)
41 : QDBusModel(service, connection)
42 {}
43
44 QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
45 {
46 if (role == Qt::FontRole && itemType(index) == InterfaceItem) {
47 QFont f;
48 f.setItalic(true);
49 return f;
50 }
51 return QDBusModel::data(index, role);
52 }
53};
54
56{
57public:
58 explicit ServicesModel(QObject *parent = nullptr)
60 {}
61
62 Qt::ItemFlags flags(const QModelIndex &index) const override
63 {
64 return QStringListModel::flags(index) & ~Qt::ItemIsEditable;
65 }
66};
67
68QDBusViewer::QDBusViewer(const QDBusConnection &connection, QWidget *parent)
69 : QWidget(parent), c(connection), objectPathRegExp("\\[ObjectPath: (.*)\\]"_L1)
70{
71 serviceFilterLine = new QLineEdit(this);
72 serviceFilterLine->setPlaceholderText(tr("Search..."));
73
74 // Create model for services list
75 servicesModel = new ServicesModel(this);
76 // Wrap service list model in proxy for easy filtering and interactive sorting
77 servicesProxyModel = new ServicesProxyModel(this);
78 servicesProxyModel->setSourceModel(servicesModel);
79 servicesProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
80
81 servicesView = new QTableView(this);
82 servicesView->installEventFilter(this);
83 servicesView->setModel(servicesProxyModel);
84 // Make services grid view behave like a list view with headers
85 servicesView->verticalHeader()->hide();
86 servicesView->horizontalHeader()->setStretchLastSection(true);
87 servicesView->setShowGrid(false);
88 // Sort service list by default
89 servicesView->setSortingEnabled(true);
90 servicesView->sortByColumn(0, Qt::AscendingOrder);
91
92 connect(serviceFilterLine, &QLineEdit::textChanged, servicesProxyModel, &QSortFilterProxyModel::setFilterFixedString);
93 connect(serviceFilterLine, &QLineEdit::returnPressed, this, &QDBusViewer::serviceFilterReturnPressed);
94
95 tree = new QTreeView;
96 tree->setContextMenuPolicy(Qt::CustomContextMenu);
97
98 connect(tree, &QAbstractItemView::activated, this, &QDBusViewer::activate);
99
100 refreshAction = new QAction(tr("&Refresh"), tree);
101 refreshAction->setData(42); // increase the amount of 42 used as magic number by one
102 refreshAction->setShortcut(QKeySequence::Refresh);
103 connect(refreshAction, &QAction::triggered, this, &QDBusViewer::refreshChildren);
104
105 QShortcut *refreshShortcut = new QShortcut(QKeySequence::Refresh, tree);
106 connect(refreshShortcut, &QShortcut::activated, this, &QDBusViewer::refreshChildren);
107
108 QVBoxLayout *layout = new QVBoxLayout(this);
109 topSplitter = new QSplitter(Qt::Vertical, this);
110 layout->addWidget(topSplitter);
111
112 log = new LogViewer;
113 connect(log, &QTextBrowser::anchorClicked, this, &QDBusViewer::anchorClicked);
114
115 splitter = new QSplitter(topSplitter);
116 splitter->addWidget(servicesView);
117
118 QWidget *servicesWidget = new QWidget;
119 QVBoxLayout *servicesLayout = new QVBoxLayout(servicesWidget);
120 servicesLayout->setContentsMargins(QMargins());
121 servicesLayout->addWidget(serviceFilterLine);
122 servicesLayout->addWidget(servicesView);
123 splitter->addWidget(servicesWidget);
124 splitter->addWidget(tree);
125
126 topSplitter->addWidget(splitter);
127 topSplitter->addWidget(log);
128
129 connect(servicesView->selectionModel(), &QItemSelectionModel::currentChanged, this, &QDBusViewer::serviceChanged);
130 connect(tree, &QWidget::customContextMenuRequested, this, &QDBusViewer::showContextMenu);
131
132 QMetaObject::invokeMethod(this, &QDBusViewer::refresh, Qt::QueuedConnection);
133
134 if (c.isConnected()) {
135 QDBusServiceWatcher *watcher =
136 new QDBusServiceWatcher("*", c, QDBusServiceWatcher::WatchForOwnerChange, this);
137 connect(watcher, &QDBusServiceWatcher::serviceOwnerChanged, this,
138 &QDBusViewer::serviceOwnerChanged);
139 logMessage(tr("Connected to D-Bus."));
140 } else {
141 logError(tr("Cannot connect to D-Bus: %1").arg(c.lastError().message()));
142 }
143
144 objectPathRegExp.setPatternOptions(QRegularExpression::InvertedGreedinessOption);
145}
146
148{
149 return u"topSplitterState"_s;
150}
151
153{
154 return u"splitterState"_s;
155}
156
157void QDBusViewer::saveState(QSettings *settings) const
158{
159 settings->setValue(topSplitterStateKey(), topSplitter->saveState());
160 settings->setValue(splitterStateKey(), splitter->saveState());
161}
162
163void QDBusViewer::restoreState(const QSettings *settings)
164{
165 topSplitter->restoreState(settings->value(topSplitterStateKey()).toByteArray());
166 splitter->restoreState(settings->value(splitterStateKey()).toByteArray());
167}
168
169void QDBusViewer::logMessage(const QString &msg)
170{
171 log->append(msg + '\n'_L1);
172}
173
174void QDBusViewer::showEvent(QShowEvent *)
175{
176 serviceFilterLine->setFocus();
177}
178
179bool QDBusViewer::eventFilter(QObject *obj, QEvent *event)
180{
181 if (obj == servicesView) {
182 if (event->type() == QEvent::KeyPress) {
183 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
184 if (keyEvent->modifiers() == Qt::NoModifier) {
185 if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) {
186 tree->setFocus();
187 }
188 }
189 }
190 }
191 return false;
192}
193
194void QDBusViewer::logError(const QString &msg)
195{
196 log->append(tr("<font color=\"red\">Error: </font>%1<br>").arg(msg.toHtmlEscaped()));
197}
198
199void QDBusViewer::refresh()
200{
201 servicesModel->removeRows(0, servicesModel->rowCount());
202
203 if (c.isConnected()) {
204 const QStringList serviceNames = c.interface()->registeredServiceNames();
205 servicesModel->setStringList(serviceNames);
206 }
207}
208
209void QDBusViewer::activate(const QModelIndex &item)
210{
211 if (!item.isValid())
212 return;
213
214 const QDBusModel *model = static_cast<const QDBusModel *>(item.model());
215
216 BusSignature sig;
217 sig.mService = currentService;
218 sig.mPath = model->dBusPath(item);
219 sig.mInterface = model->dBusInterface(item);
220 sig.mName = model->dBusMethodName(item);
221 sig.mTypeSig = model->dBusTypeSignature(item);
222
223 switch (model->itemType(item)) {
224 case QDBusModel::SignalItem:
225 connectionRequested(sig);
226 break;
227 case QDBusModel::MethodItem:
228 callMethod(sig);
229 break;
230 case QDBusModel::PropertyItem:
231 getProperty(sig);
232 break;
233 default:
234 break;
235 }
236}
237
238void QDBusViewer::getProperty(const BusSignature &sig)
239{
240 QDBusMessage message = QDBusMessage::createMethodCall(
241 sig.mService, sig.mPath, "org.freedesktop.DBus.Properties"_L1, "Get"_L1);
242 QList<QVariant> arguments;
243 arguments << sig.mInterface << sig.mName;
244 message.setArguments(arguments);
245 c.callWithCallback(message, this, SLOT(dumpMessage(QDBusMessage)), SLOT(dumpError(QDBusError)));
246}
247
248void QDBusViewer::setProperty(const BusSignature &sig)
249{
250 QDBusInterface iface(sig.mService, sig.mPath, sig.mInterface, c);
251 QMetaProperty prop = iface.metaObject()->property(iface.metaObject()->indexOfProperty(sig.mName.toLatin1()));
252
253 bool ok;
254 QString input = QInputDialog::getText(this, tr("Arguments"),
255 tr("Please enter the value of the property %1 (type %2)").arg(
256 sig.mName, QString::fromLatin1(prop.typeName())),
257 QLineEdit::Normal, QString(), &ok);
258 if (!ok)
259 return;
260
261 QVariant value = input;
262 if (!value.convert(prop.metaType())) {
263 QMessageBox::warning(this, tr("Unable to marshall"),
264 tr("Value conversion failed, unable to set property"));
265 return;
266 }
267
268 QDBusMessage message = QDBusMessage::createMethodCall(
269 sig.mService, sig.mPath, "org.freedesktop.DBus.Properties"_L1, "Set"_L1);
270 QList<QVariant> arguments;
271 arguments << sig.mInterface << sig.mName << QVariant::fromValue(QDBusVariant(value));
272 message.setArguments(arguments);
273 c.callWithCallback(message, this, SLOT(dumpMessage(QDBusMessage)), SLOT(dumpError(QDBusError)));
274}
275
276static QString getDbusSignature(const QMetaMethod& method)
277{
278 // create a D-Bus type signature from QMetaMethod's parameters
279 QString sig;
280 for (const auto &type : method.parameterTypes())
281 sig.append(QString::fromLatin1(QDBusMetaType::typeToSignature(QMetaType::fromName(type))));
282 return sig;
283}
284
285void QDBusViewer::callMethod(const BusSignature &sig)
286{
287 QDBusInterface iface(sig.mService, sig.mPath, sig.mInterface, c);
288 const QMetaObject *mo = iface.metaObject();
289
290 // find the method
291 QMetaMethod method;
292 for (int i = 0; i < mo->methodCount(); ++i) {
293 const QString signature = QString::fromLatin1(mo->method(i).methodSignature());
294 if (signature.startsWith(sig.mName) && signature.at(sig.mName.size()) == '('_L1)
295 if (getDbusSignature(mo->method(i)) == sig.mTypeSig)
296 method = mo->method(i);
297 }
298 if (!method.isValid()) {
299 QMessageBox::warning(this, tr("Unable to find method"),
300 tr("Unable to find method %1 on path %2 in interface %3").arg(
301 sig.mName).arg(sig.mPath).arg(sig.mInterface));
302 return;
303 }
304
305 PropertyDialog dialog;
306 QList<QVariant> args;
307
308 const QList<QByteArray> paramTypes = method.parameterTypes();
309 const QList<QByteArray> paramNames = method.parameterNames();
310 QList<int> types; // remember the low-level D-Bus type
311 for (int i = 0; i < paramTypes.size(); ++i) {
312 const QByteArray paramType = paramTypes.at(i);
313 if (paramType.endsWith('&'))
314 continue; // ignore OUT parameters
315
316 const int type = QMetaType::fromName(paramType).id();
317 dialog.addProperty(QString::fromLatin1(paramNames.value(i)), type);
318 types.append(type);
319 }
320
321 if (!types.isEmpty()) {
322 dialog.setInfo(tr("Please enter parameters for the method \"%1\"").arg(sig.mName));
323
324 if (dialog.exec() != QDialog::Accepted)
325 return;
326
327 args = dialog.values();
328 }
329
330 // Try to convert the values we got as closely as possible to the
331 // dbus signature. This is especially important for those input as strings
332 for (int i = 0; i < args.size(); ++i) {
333 QVariant a = args.at(i);
334 int desttype = types.at(i);
335 if (desttype < int(QMetaType::User) && desttype != qMetaTypeId<QVariantMap>()) {
336 const QMetaType metaType(desttype);
337 if (a.canConvert(metaType))
338 args[i].convert(metaType);
339 }
340 // Special case - convert a value to a QDBusVariant if the
341 // interface wants a variant
342 if (types.at(i) == qMetaTypeId<QDBusVariant>())
343 args[i] = QVariant::fromValue(QDBusVariant(args.at(i)));
344 }
345
346 QDBusMessage message = QDBusMessage::createMethodCall(sig.mService, sig.mPath, sig.mInterface,
347 sig.mName);
348 message.setArguments(args);
349 c.callWithCallback(message, this, SLOT(dumpMessage(QDBusMessage)), SLOT(dumpError(QDBusError)));
350}
351
352void QDBusViewer::showContextMenu(const QPoint &point)
353{
354 QModelIndex item = tree->indexAt(point);
355 if (!item.isValid())
356 return;
357
358 const QDBusModel *model = static_cast<const QDBusModel *>(item.model());
359
360 BusSignature sig;
361 sig.mService = currentService;
362 sig.mPath = model->dBusPath(item);
363 sig.mInterface = model->dBusInterface(item);
364 sig.mName = model->dBusMethodName(item);
365 sig.mTypeSig = model->dBusTypeSignature(item);
366
367 QMenu menu;
368 menu.addAction(refreshAction);
369
370 switch (model->itemType(item)) {
371 case QDBusModel::SignalItem: {
372 QAction *action = new QAction(tr("&Connect"), &menu);
373 action->setData(1);
374 menu.addAction(action);
375 break; }
376 case QDBusModel::MethodItem: {
377 QAction *action = new QAction(tr("&Call"), &menu);
378 action->setData(2);
379 menu.addAction(action);
380 break; }
381 case QDBusModel::PropertyItem: {
382 QDBusInterface iface(sig.mService, sig.mPath, sig.mInterface, c);
383 QMetaProperty prop = iface.metaObject()->property(iface.metaObject()->indexOfProperty(sig.mName.toLatin1()));
384 QAction *actionSet = new QAction(tr("&Set value"), &menu);
385 actionSet->setData(3);
386 actionSet->setEnabled(prop.isWritable());
387 QAction *actionGet = new QAction(tr("&Get value"), &menu);
388 actionGet->setEnabled(prop.isReadable());
389 actionGet->setData(4);
390 menu.addAction(actionSet);
391 menu.addAction(actionGet);
392 break; }
393 default:
394 break;
395 }
396
397 QAction *selectedAction = menu.exec(tree->viewport()->mapToGlobal(point));
398 if (!selectedAction)
399 return;
400
401 switch (selectedAction->data().toInt()) {
402 case 1:
403 connectionRequested(sig);
404 break;
405 case 2:
406 callMethod(sig);
407 break;
408 case 3:
409 setProperty(sig);
410 break;
411 case 4:
412 getProperty(sig);
413 break;
414 }
415}
416
417void QDBusViewer::connectionRequested(const BusSignature &sig)
418{
419 if (c.connect(sig.mService, QString(), sig.mInterface, sig.mName, this,
420 SLOT(dumpMessage(QDBusMessage)))) {
421 logMessage(tr("Connected to service %1, path %2, interface %3, signal %4").arg(
422 sig.mService, sig.mPath, sig.mInterface, sig.mName));
423 } else {
424 logError(tr("Unable to connect to service %1, path %2, interface %3, signal %4").arg(
425 sig.mService, sig.mPath, sig.mInterface, sig.mName));
426 }
427}
428
429void QDBusViewer::dumpMessage(const QDBusMessage &message)
430{
431 QList<QVariant> args = message.arguments();
432
433 QString messageType;
434 switch (message.type()) {
435 case QDBusMessage::SignalMessage:
436 messageType = tr("signal");
437 break;
438 case QDBusMessage::ErrorMessage:
439 messageType = tr("error message");
440 break;
441 case QDBusMessage::ReplyMessage:
442 messageType = tr("reply");
443 break;
444 default:
445 messageType = tr("message");
446 break;
447 }
448
449 QString out = tr("Received %1 from %2").arg(messageType).arg(message.service());
450
451 if (!message.path().isEmpty())
452 out += tr(", path %1").arg(message.path());
453 if (!message.interface().isEmpty())
454 out += tr(", interface <i>%1</i>").arg(message.interface());
455 if (!message.member().isEmpty())
456 out += tr(", member %1").arg(message.member());
457 out += "<br>"_L1;
458 if (args.isEmpty()) {
459 out += tr("&nbsp;&nbsp;(no arguments)");
460 } else {
461 QStringList argStrings;
462 for (const QVariant &arg : std::as_const(args)) {
463 QString str = QDBusUtil::argumentToString(arg).toHtmlEscaped();
464 // turn object paths into clickable links
465 str.replace(objectPathRegExp, tr("[ObjectPath: <a href=\"qdbus://bus\\1\">\\1</a>]"));
466 // convert new lines from command to proper HTML line breaks
467 str.replace("\n"_L1, "<br/>"_L1);
468 argStrings.append(str);
469 }
470 out += tr("&nbsp;&nbsp;Arguments: %1").arg(argStrings.join(tr(", ")));
471 }
472
473 log->append(out);
474}
475
476void QDBusViewer::dumpError(const QDBusError &error)
477{
478 logError(error.message());
479}
480
481void QDBusViewer::serviceChanged(const QModelIndex &index)
482{
483 delete tree->model();
484
485 currentService.clear();
486 if (!index.isValid())
487 return;
488 currentService = index.data().toString();
489
490 QDBusViewModel *model = new QDBusViewModel(currentService, c);
491 tree->setModel(model);
492 connect(model, &QDBusModel::busError, this, &QDBusViewer::logError);
493}
494
495void QDBusViewer::serviceRegistered(const QString &service)
496{
497 if (service == c.baseService())
498 return;
499
500 servicesModel->insertRows(0, 1);
501 servicesModel->setData(servicesModel->index(0, 0), service);
502}
503
504static QModelIndex findItem(QStringListModel *servicesModel, const QString &name)
505{
506 QModelIndexList hits = servicesModel->match(servicesModel->index(0, 0), Qt::DisplayRole, name);
507 if (hits.isEmpty())
508 return QModelIndex();
509
510 return hits.first();
511}
512
513void QDBusViewer::serviceOwnerChanged(const QString &name, const QString &oldOwner,
514 const QString &newOwner)
515{
516 QModelIndex hit = findItem(servicesModel, name);
517
518 if (!hit.isValid() && oldOwner.isEmpty() && !newOwner.isEmpty())
519 serviceRegistered(name);
520 else if (hit.isValid() && !oldOwner.isEmpty() && newOwner.isEmpty())
521 servicesModel->removeRows(hit.row(), 1);
522 else if (hit.isValid() && !oldOwner.isEmpty() && !newOwner.isEmpty()) {
523 servicesModel->removeRows(hit.row(), 1);
524 serviceRegistered(name);
525 }
526}
527
528void QDBusViewer::serviceFilterReturnPressed()
529{
530 if (servicesProxyModel->rowCount() <= 0)
531 return;
532
533 servicesView->selectRow(0);
534 servicesView->setFocus();
535}
536
537void QDBusViewer::refreshChildren()
538{
539 QDBusModel *model = qobject_cast<QDBusModel *>(tree->model());
540 if (!model)
541 return;
542 model->refresh(tree->currentIndex());
543}
544
545void QDBusViewer::anchorClicked(const QUrl &url)
546{
547 if (url.scheme() != "qdbus"_L1)
548 // not ours
549 return;
550
551 // swallow the click without setting a new document
552 log->setSource(QUrl());
553
554 QDBusModel *model = qobject_cast<QDBusModel *>(tree->model());
555 if (!model)
556 return;
557
558 QModelIndex idx = model->findObject(QDBusObjectPath(url.path()));
559 if (!idx.isValid())
560 return;
561
562 tree->scrollTo(idx);
563 tree->setCurrentIndex(idx);
564}
QDBusViewModel(const QString &service, const QDBusConnection &connection)
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
Returns the data stored under the given role for the item referred to by the index.
bool eventFilter(QObject *obj, QEvent *event) override
Filters events if this object has been installed as an event filter for the watched object.
void saveState(QSettings *settings) const
void restoreState(const QSettings *settings)
void showEvent(QShowEvent *) override
This event handler can be reimplemented in a subclass to receive widget show events which are passed ...
ServicesModel(QObject *parent=nullptr)
Qt::ItemFlags flags(const QModelIndex &index) const override
Returns the flags for the item with the given index.
static QString topSplitterStateKey()
static QString getDbusSignature(const QMetaMethod &method)
static QString splitterStateKey()
static QModelIndex findItem(QStringListModel *servicesModel, const QString &name)