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>
20#include <QtDBus/QDBusConnectionInterface>
21#include <QtDBus/QDBusInterface>
22#include <QtDBus/QDBusMetaType>
23#include <QtDBus/QDBusServiceWatcher>
25#include <QtGui/QAction>
26#include <QtGui/QKeyEvent>
27#include <QtGui/QShortcut>
29#include <QtCore/QStringListModel>
30#include <QtCore/QMetaProperty>
31#include <QtCore/QSettings>
33#include <private/qdbusutil_p.h>
35using namespace Qt::StringLiterals;
40 inline QDBusViewModel(
const QString &service,
const QDBusConnection &connection)
46 if (role == Qt::FontRole && itemType(index) == InterfaceItem) {
51 return QDBusModel::data(index, role);
64 return QStringListModel::flags(index) & ~Qt::ItemIsEditable;
68QDBusViewer::QDBusViewer(
const QDBusConnection &connection, QWidget *parent)
69 : QWidget(parent), c(connection), objectPathRegExp(
"\\[ObjectPath: (.*)\\]"_L1)
71 serviceFilterLine =
new QLineEdit(
this);
72 serviceFilterLine->setPlaceholderText(tr(
"Search..."));
75 servicesModel =
new ServicesModel(
this);
77 servicesProxyModel =
new ServicesProxyModel(
this);
78 servicesProxyModel->setSourceModel(servicesModel);
79 servicesProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
81 servicesView =
new QTableView(
this);
82 servicesView->installEventFilter(
this);
83 servicesView->setModel(servicesProxyModel);
85 servicesView->verticalHeader()->hide();
86 servicesView->horizontalHeader()->setStretchLastSection(
true);
87 servicesView->setShowGrid(
false);
89 servicesView->setSortingEnabled(
true);
90 servicesView->sortByColumn(0, Qt::AscendingOrder);
92 connect(serviceFilterLine, &QLineEdit::textChanged, servicesProxyModel, &QSortFilterProxyModel::setFilterFixedString);
93 connect(serviceFilterLine, &QLineEdit::returnPressed,
this, &QDBusViewer::serviceFilterReturnPressed);
96 tree->setContextMenuPolicy(Qt::CustomContextMenu);
98 connect(tree, &QAbstractItemView::activated,
this, &QDBusViewer::activate);
100 refreshAction =
new QAction(tr(
"&Refresh"), tree);
101 refreshAction->setData(42);
102 refreshAction->setShortcut(QKeySequence::Refresh);
103 connect(refreshAction, &QAction::triggered,
this, &QDBusViewer::refreshChildren);
105 QShortcut *refreshShortcut =
new QShortcut(QKeySequence::Refresh, tree);
106 connect(refreshShortcut, &QShortcut::activated,
this, &QDBusViewer::refreshChildren);
108 QVBoxLayout *layout =
new QVBoxLayout(
this);
109 topSplitter =
new QSplitter(Qt::Vertical,
this);
110 layout->addWidget(topSplitter);
113 connect(log, &QTextBrowser::anchorClicked,
this, &QDBusViewer::anchorClicked);
115 splitter =
new QSplitter(topSplitter);
116 splitter->addWidget(servicesView);
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);
126 topSplitter->addWidget(splitter);
127 topSplitter->addWidget(log);
129 connect(servicesView->selectionModel(), &QItemSelectionModel::currentChanged,
this, &QDBusViewer::serviceChanged);
130 connect(tree, &QWidget::customContextMenuRequested,
this, &QDBusViewer::showContextMenu);
132 QMetaObject::invokeMethod(
this, &QDBusViewer::refresh, Qt::QueuedConnection);
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."));
141 logError(tr(
"Cannot connect to D-Bus: %1").arg(c.lastError().message()));
144 objectPathRegExp.setPatternOptions(QRegularExpression::InvertedGreedinessOption);
149 return u"topSplitterState"_s;
154 return u"splitterState"_s;
159 settings->setValue(topSplitterStateKey(), topSplitter->saveState());
160 settings->setValue(splitterStateKey(), splitter->saveState());
165 topSplitter->restoreState(settings->value(topSplitterStateKey()).toByteArray());
166 splitter->restoreState(settings->value(splitterStateKey()).toByteArray());
171 log->append(msg +
'\n'_L1);
176 serviceFilterLine->setFocus();
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) {
196 log->append(tr(
"<font color=\"red\">Error: </font>%1<br>").arg(msg.toHtmlEscaped()));
201 servicesModel->removeRows(0, servicesModel->rowCount());
203 if (c.isConnected()) {
204 const QStringList serviceNames = c.interface()->registeredServiceNames();
205 servicesModel->setStringList(serviceNames);
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);
223 switch (model->itemType(item)) {
224 case QDBusModel::SignalItem:
225 connectionRequested(sig);
227 case QDBusModel::MethodItem:
230 case QDBusModel::PropertyItem:
238void QDBusViewer::getProperty(
const BusSignature &sig)
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)));
248void QDBusViewer::setProperty(
const BusSignature &sig)
250 QDBusInterface iface(sig.mService, sig.mPath, sig.mInterface, c);
251 QMetaProperty prop = iface.metaObject()->property(iface.metaObject()->indexOfProperty(sig.mName.toLatin1()));
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);
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"));
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)));
280 for (
const auto &type : method.parameterTypes())
281 sig.append(QString::fromLatin1(QDBusMetaType::typeToSignature(QMetaType::fromName(type))));
285void QDBusViewer::callMethod(
const BusSignature &sig)
287 QDBusInterface iface(sig.mService, sig.mPath, sig.mInterface, c);
288 const QMetaObject *mo = iface.metaObject();
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);
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));
306 QList<QVariant> args;
308 const QList<QByteArray> paramTypes = method.parameterTypes();
309 const QList<QByteArray> paramNames = method.parameterNames();
311 for (
int i = 0; i < paramTypes.size(); ++i) {
312 const QByteArray paramType = paramTypes.at(i);
313 if (paramType.endsWith(
'&'))
316 const int type = QMetaType::fromName(paramType).id();
317 dialog.addProperty(QString::fromLatin1(paramNames.value(i)), type);
321 if (!types.isEmpty()) {
322 dialog.setInfo(tr(
"Please enter parameters for the method \"%1\"").arg(sig.mName));
324 if (dialog.exec() != QDialog::Accepted)
327 args = dialog.values();
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);
342 if (types.at(i) == qMetaTypeId<QDBusVariant>())
343 args[i] = QVariant::fromValue(QDBusVariant(args.at(i)));
346 QDBusMessage message = QDBusMessage::createMethodCall(sig.mService, sig.mPath, sig.mInterface,
348 message.setArguments(args);
349 c.callWithCallback(message,
this, SLOT(dumpMessage(QDBusMessage)), SLOT(dumpError(QDBusError)));
352void QDBusViewer::showContextMenu(
const QPoint &point)
354 QModelIndex item = tree->indexAt(point);
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);
368 menu.addAction(refreshAction);
370 switch (model->itemType(item)) {
371 case QDBusModel::SignalItem: {
372 QAction *action =
new QAction(tr(
"&Connect"), &menu);
374 menu.addAction(action);
376 case QDBusModel::MethodItem: {
377 QAction *action =
new QAction(tr(
"&Call"), &menu);
379 menu.addAction(action);
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);
397 QAction *selectedAction = menu.exec(tree->viewport()->mapToGlobal(point));
401 switch (selectedAction->data().toInt()) {
403 connectionRequested(sig);
417void QDBusViewer::connectionRequested(
const BusSignature &sig)
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));
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));
429void QDBusViewer::dumpMessage(
const QDBusMessage &message)
431 QList<QVariant> args = message.arguments();
434 switch (message.type()) {
435 case QDBusMessage::SignalMessage:
436 messageType = tr(
"signal");
438 case QDBusMessage::ErrorMessage:
439 messageType = tr(
"error message");
441 case QDBusMessage::ReplyMessage:
442 messageType = tr(
"reply");
445 messageType = tr(
"message");
449 QString out = tr(
"Received %1 from %2").arg(messageType).arg(message.service());
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());
458 if (args.isEmpty()) {
459 out += tr(
" (no arguments)");
461 QStringList argStrings;
462 for (
const QVariant &arg : std::as_const(args)) {
463 QString str = QDBusUtil::argumentToString(arg).toHtmlEscaped();
465 str.replace(objectPathRegExp, tr(
"[ObjectPath: <a href=\"qdbus://bus\\1\">\\1</a>]"));
467 str.replace(
"\n"_L1,
"<br/>"_L1);
468 argStrings.append(str);
470 out += tr(
" Arguments: %1").arg(argStrings.join(tr(
", ")));
476void QDBusViewer::dumpError(
const QDBusError &error)
478 logError(error.message());
481void QDBusViewer::serviceChanged(
const QModelIndex &index)
483 delete tree->model();
485 currentService.clear();
486 if (!index.isValid())
488 currentService = index.data().toString();
491 tree->setModel(model);
492 connect(model, &QDBusModel::busError,
this, &QDBusViewer::logError);
495void QDBusViewer::serviceRegistered(
const QString &service)
497 if (service == c.baseService())
500 servicesModel->insertRows(0, 1);
501 servicesModel->setData(servicesModel->index(0, 0), service);
506 QModelIndexList hits = servicesModel->match(servicesModel->index(0, 0), Qt::DisplayRole, name);
508 return QModelIndex();
513void QDBusViewer::serviceOwnerChanged(
const QString &name,
const QString &oldOwner,
514 const QString &newOwner)
516 QModelIndex hit = findItem(servicesModel, name);
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);
530 if (servicesProxyModel->rowCount() <= 0)
533 servicesView->selectRow(0);
534 servicesView->setFocus();
539 QDBusModel *model = qobject_cast<QDBusModel *>(tree->model());
542 model->refresh(tree->currentIndex());
547 if (url.scheme() !=
"qdbus"_L1)
552 log->setSource(QUrl());
554 QDBusModel *model = qobject_cast<QDBusModel *>(tree->model());
558 QModelIndex idx = model->findObject(QDBusObjectPath(url.path()));
563 tree->setCurrentIndex(idx);
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)