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
|
/* This file is part of the dbusmenu-qt library
SPDX-FileCopyrightText: 2009 Canonical
SPDX-FileContributor: Aurelien Gateau <aurelien.gateau@canonical.com>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#include "dbusmenuimporter.h"
#include "debug.h"
// Qt
#include <QActionGroup>
#include <QCoreApplication>
#include <QDBusConnection>
#include <QDBusInterface>
#include <QDBusReply>
#include <QDBusVariant>
#include <QDebug>
#include <QFont>
#include <QMenu>
#include <QPointer>
#include <QSet>
#include <QTime>
#include <QTimer>
#include <QToolButton>
#include <QWidgetAction>
// Local
#include "dbusmenushortcut_p.h"
#include "dbusmenutypes_p.h"
#include "utils_p.h"
// Generated
#include "dbusmenu_interface.h"
// #define BENCHMARK
#ifdef BENCHMARK
static QTime sChrono;
#endif
#define DMRETURN_IF_FAIL(cond) \
if (!(cond)) { \
qCWarning(DBUSMENUQT) << "Condition failed: " #cond; \
return; \
}
static const char *DBUSMENU_PROPERTY_ID = "_dbusmenu_id";
static const char *DBUSMENU_PROPERTY_ICON_NAME = "_dbusmenu_icon_name";
static const char *DBUSMENU_PROPERTY_ICON_DATA_HASH = "_dbusmenu_icon_data_hash";
static QAction *createKdeTitle(QAction *action, QWidget *parent)
{
QToolButton *titleWidget = new QToolButton(nullptr);
QFont font = titleWidget->font();
font.setBold(true);
titleWidget->setFont(font);
titleWidget->setIcon(action->icon());
titleWidget->setText(action->text());
titleWidget->setDown(true);
titleWidget->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
QWidgetAction *titleAction = new QWidgetAction(parent);
titleAction->setDefaultWidget(titleWidget);
return titleAction;
}
class DBusMenuImporterPrivate
{
public:
DBusMenuImporter *q;
DBusMenuInterface *m_interface;
QMenu *m_menu;
using ActionForId = QMap<int, QAction *>;
ActionForId m_actionForId;
QTimer *m_pendingLayoutUpdateTimer;
QSet<int> m_idsRefreshedByAboutToShow;
QSet<int> m_pendingLayoutUpdates;
QDBusPendingCallWatcher *refresh(int id)
{
auto call = m_interface->GetLayout(id, 1, QStringList());
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(call, q);
watcher->setProperty(DBUSMENU_PROPERTY_ID, id);
QObject::connect(watcher, &QDBusPendingCallWatcher::finished, q, &DBusMenuImporter::slotGetLayoutFinished);
return watcher;
}
QMenu *createMenu(QWidget *parent)
{
QMenu *menu = q->createMenu(parent);
return menu;
}
/**
* Init all the immutable action properties here
* TODO: Document immutable properties?
*
* Note: we remove properties we handle from the map (using QMap::take()
* instead of QMap::value()) to avoid warnings about these properties in
* updateAction()
*/
QAction *createAction(int id, const QVariantMap &_map, QWidget *parent)
{
QVariantMap map = _map;
QAction *action = new QAction(parent);
action->setProperty(DBUSMENU_PROPERTY_ID, id);
QString type = map.take(QStringLiteral("type")).toString();
if (type == QLatin1String("separator")) {
action->setSeparator(true);
}
if (map.take(QStringLiteral("children-display")).toString() == QLatin1String("submenu")) {
QMenu *menu = createMenu(parent);
action->setMenu(menu);
}
QString toggleType = map.take(QStringLiteral("toggle-type")).toString();
if (!toggleType.isEmpty()) {
action->setCheckable(true);
if (toggleType == QLatin1String("radio")) {
QActionGroup *group = new QActionGroup(action);
group->addAction(action);
}
}
bool isKdeTitle = map.take(QStringLiteral("x-kde-title")).toBool();
updateAction(action, map, map.keys());
if (isKdeTitle) {
action = createKdeTitle(action, parent);
}
return action;
}
/**
* Update mutable properties of an action. A property may be listed in
* requestedProperties but not in map, this means we should use the default value
* for this property.
*
* @param action the action to update
* @param map holds the property values
* @param requestedProperties which properties has been requested
*/
void updateAction(QAction *action, const QVariantMap &map, const QStringList &requestedProperties)
{
for (const QString &key : requestedProperties) {
updateActionProperty(action, key, map.value(key));
}
}
void updateActionProperty(QAction *action, const QString &key, const QVariant &value)
{
if (key == QLatin1String("label")) {
updateActionLabel(action, value);
} else if (key == QLatin1String("enabled")) {
updateActionEnabled(action, value);
} else if (key == QLatin1String("toggle-state")) {
updateActionChecked(action, value);
} else if (key == QLatin1String("icon-name")) {
updateActionIconByName(action, value);
} else if (key == QLatin1String("icon-data")) {
updateActionIconByData(action, value);
} else if (key == QLatin1String("visible")) {
updateActionVisible(action, value);
} else if (key == QLatin1String("shortcut")) {
updateActionShortcut(action, value);
} else {
qDebug(DBUSMENUQT) << "Unhandled property update" << key;
}
}
void updateActionLabel(QAction *action, const QVariant &value)
{
QString text = swapMnemonicChar(value.toString(), '_', '&');
action->setText(text);
}
void updateActionEnabled(QAction *action, const QVariant &value)
{
action->setEnabled(value.isValid() ? value.toBool() : true);
}
void updateActionChecked(QAction *action, const QVariant &value)
{
if (action->isCheckable() && value.isValid()) {
action->setChecked(value.toInt() == 1);
}
}
void updateActionIconByName(QAction *action, const QVariant &value)
{
const QString iconName = value.toString();
const QString previous = action->property(DBUSMENU_PROPERTY_ICON_NAME).toString();
if (previous == iconName) {
return;
}
action->setProperty(DBUSMENU_PROPERTY_ICON_NAME, iconName);
if (iconName.isEmpty()) {
action->setIcon(QIcon());
return;
}
action->setIcon(q->iconForName(iconName));
}
void updateActionIconByData(QAction *action, const QVariant &value)
{
const QByteArray data = value.toByteArray();
uint dataHash = qHash(data);
uint previousDataHash = action->property(DBUSMENU_PROPERTY_ICON_DATA_HASH).toUInt();
if (previousDataHash == dataHash) {
return;
}
action->setProperty(DBUSMENU_PROPERTY_ICON_DATA_HASH, dataHash);
QPixmap pix;
if (!pix.loadFromData(data)) {
qDebug(DBUSMENUQT) << "Failed to decode icon-data property for action" << action->text();
action->setIcon(QIcon());
return;
}
action->setIcon(QIcon(pix));
}
void updateActionVisible(QAction *action, const QVariant &value)
{
action->setVisible(value.isValid() ? value.toBool() : true);
}
void updateActionShortcut(QAction *action, const QVariant &value)
{
QDBusArgument arg = value.value<QDBusArgument>();
DBusMenuShortcut dmShortcut;
arg >> dmShortcut;
QKeySequence keySequence = dmShortcut.toKeySequence();
action->setShortcut(keySequence);
}
QMenu *menuForId(int id) const
{
if (id == 0) {
return q->menu();
}
QAction *action = m_actionForId.value(id);
if (!action) {
return nullptr;
}
return action->menu();
}
void slotItemsPropertiesUpdated(const DBusMenuItemList &updatedList, const DBusMenuItemKeysList &removedList);
void sendEvent(int id, const QString &eventId)
{
m_interface->Event(id, eventId, QDBusVariant(QString()), 0u);
}
};
DBusMenuImporter::DBusMenuImporter(const QString &service, const QString &path, QObject *parent)
: QObject(parent)
, d(new DBusMenuImporterPrivate)
{
DBusMenuTypes_register();
d->q = this;
d->m_interface = new DBusMenuInterface(service, path, QDBusConnection::sessionBus(), this);
d->m_menu = nullptr;
d->m_pendingLayoutUpdateTimer = new QTimer(this);
d->m_pendingLayoutUpdateTimer->setSingleShot(true);
connect(d->m_pendingLayoutUpdateTimer, &QTimer::timeout, this, &DBusMenuImporter::processPendingLayoutUpdates);
connect(d->m_interface, &DBusMenuInterface::LayoutUpdated, this, &DBusMenuImporter::slotLayoutUpdated);
connect(d->m_interface, &DBusMenuInterface::ItemActivationRequested, this, &DBusMenuImporter::slotItemActivationRequested);
connect(d->m_interface,
&DBusMenuInterface::ItemsPropertiesUpdated,
this,
[this](const DBusMenuItemList &updatedList, const DBusMenuItemKeysList &removedList) {
d->slotItemsPropertiesUpdated(updatedList, removedList);
});
d->refresh(0);
}
DBusMenuImporter::~DBusMenuImporter()
{
// Do not use "delete d->m_menu": even if we are being deleted we should
// leave enough time for the menu to finish what it was doing, for example
// if it was being displayed.
d->m_menu->deleteLater();
delete d;
}
void DBusMenuImporter::slotLayoutUpdated(uint revision, int parentId)
{
Q_UNUSED(revision)
if (d->m_idsRefreshedByAboutToShow.remove(parentId)) {
return;
}
d->m_pendingLayoutUpdates << parentId;
if (!d->m_pendingLayoutUpdateTimer->isActive()) {
d->m_pendingLayoutUpdateTimer->start();
}
}
void DBusMenuImporter::processPendingLayoutUpdates()
{
const QSet<int> ids = d->m_pendingLayoutUpdates;
d->m_pendingLayoutUpdates.clear();
for (int id : ids) {
d->refresh(id);
}
}
QMenu *DBusMenuImporter::menu() const
{
if (!d->m_menu) {
d->m_menu = d->createMenu(nullptr);
}
return d->m_menu;
}
void DBusMenuImporterPrivate::slotItemsPropertiesUpdated(const DBusMenuItemList &updatedList, const DBusMenuItemKeysList &removedList)
{
for (const DBusMenuItem &item : updatedList) {
QAction *action = m_actionForId.value(item.id);
if (!action) {
// We don't know this action. It probably is in a menu we haven't fetched yet.
continue;
}
QVariantMap::ConstIterator it = item.properties.constBegin(), end = item.properties.constEnd();
for (; it != end; ++it) {
updateActionProperty(action, it.key(), it.value());
}
}
for (const DBusMenuItemKeys &item : removedList) {
QAction *action = m_actionForId.value(item.id);
if (!action) {
// We don't know this action. It probably is in a menu we haven't fetched yet.
continue;
}
const auto properties{item.properties};
for (const QString &key : properties) {
updateActionProperty(action, key, QVariant());
}
}
}
QAction *DBusMenuImporter::actionForId(int id) const
{
return d->m_actionForId.value(id);
}
void DBusMenuImporter::slotItemActivationRequested(int id, uint /*timestamp*/)
{
QAction *action = d->m_actionForId.value(id);
DMRETURN_IF_FAIL(action);
actionActivationRequested(action);
}
void DBusMenuImporter::slotGetLayoutFinished(QDBusPendingCallWatcher *watcher)
{
int parentId = watcher->property(DBUSMENU_PROPERTY_ID).toInt();
watcher->deleteLater();
QMenu *menu = d->menuForId(parentId);
QDBusPendingReply<uint, DBusMenuLayoutItem> reply = *watcher;
if (!reply.isValid()) {
qDebug(DBUSMENUQT) << reply.error().message();
if (menu) {
Q_EMIT menuUpdated(menu);
}
return;
}
#ifdef BENCHMARK
DMDEBUG << "- items received:" << sChrono.elapsed() << "ms";
#endif
DBusMenuLayoutItem rootItem = reply.argumentAt<1>();
if (!menu) {
qDebug(DBUSMENUQT) << "No menu for id" << parentId;
return;
}
// remove outdated actions
QSet<int> newDBusMenuItemIds;
newDBusMenuItemIds.reserve(rootItem.children.count());
for (const DBusMenuLayoutItem &item : qAsConst(rootItem.children)) {
newDBusMenuItemIds << item.id;
}
for (QAction *action : menu->actions()) {
int id = action->property(DBUSMENU_PROPERTY_ID).toInt();
if (!newDBusMenuItemIds.contains(id)) {
// Not calling removeAction() as QMenu will immediately close when it becomes empty,
// which can happen when an application completely reloads this menu.
// When the action is deleted deferred, it is removed from the menu.
action->deleteLater();
if (action->menu()) {
action->menu()->deleteLater();
}
d->m_actionForId.remove(id);
}
}
// insert or update new actions into our menu
for (const DBusMenuLayoutItem &dbusMenuItem : qAsConst(rootItem.children)) {
DBusMenuImporterPrivate::ActionForId::Iterator it = d->m_actionForId.find(dbusMenuItem.id);
QAction *action = nullptr;
if (it == d->m_actionForId.end()) {
int id = dbusMenuItem.id;
action = d->createAction(id, dbusMenuItem.properties, menu);
d->m_actionForId.insert(id, action);
connect(action, &QObject::destroyed, this, [this, id]() {
d->m_actionForId.remove(id);
});
connect(action, &QAction::triggered, this, [id, this]() {
sendClickedEvent(id);
});
if (QMenu *menuAction = action->menu()) {
connect(menuAction, &QMenu::aboutToShow, this, &DBusMenuImporter::slotMenuAboutToShow, Qt::UniqueConnection);
}
connect(menu, &QMenu::aboutToHide, this, &DBusMenuImporter::slotMenuAboutToHide, Qt::UniqueConnection);
menu->addAction(action);
} else {
action = *it;
QStringList filteredKeys = dbusMenuItem.properties.keys();
filteredKeys.removeOne(QStringLiteral("type"));
filteredKeys.removeOne(QStringLiteral("toggle-type"));
filteredKeys.removeOne(QStringLiteral("children-display"));
d->updateAction(*it, dbusMenuItem.properties, filteredKeys);
// Move the action to the tail so we can keep the order same as the dbus request.
menu->removeAction(action);
menu->addAction(action);
}
}
Q_EMIT menuUpdated(menu);
}
void DBusMenuImporter::sendClickedEvent(int id)
{
d->sendEvent(id, QStringLiteral("clicked"));
}
void DBusMenuImporter::updateMenu()
{
updateMenu(DBusMenuImporter::menu());
}
void DBusMenuImporter::updateMenu(QMenu *menu)
{
Q_ASSERT(menu);
QAction *action = menu->menuAction();
Q_ASSERT(action);
int id = action->property(DBUSMENU_PROPERTY_ID).toInt();
auto call = d->m_interface->AboutToShow(id);
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(call, this);
watcher->setProperty(DBUSMENU_PROPERTY_ID, id);
connect(watcher, &QDBusPendingCallWatcher::finished, this, &DBusMenuImporter::slotAboutToShowDBusCallFinished);
// Firefox deliberately ignores "aboutToShow" whereas Qt ignores" opened", so we'll just send both all the time...
d->sendEvent(id, QStringLiteral("opened"));
}
void DBusMenuImporter::slotAboutToShowDBusCallFinished(QDBusPendingCallWatcher *watcher)
{
int id = watcher->property(DBUSMENU_PROPERTY_ID).toInt();
watcher->deleteLater();
QMenu *menu = d->menuForId(id);
if (!menu) {
return;
}
QDBusPendingReply<bool> reply = *watcher;
if (reply.isError()) {
qDebug(DBUSMENUQT) << "Call to AboutToShow() failed:" << reply.error().message();
Q_EMIT menuUpdated(menu);
return;
}
// Note, this isn't used by Qt's QPT - but we get a LayoutChanged emitted before
// this returns, which equates to the same thing
bool needRefresh = reply.argumentAt<0>();
if (needRefresh || menu->actions().isEmpty()) {
d->m_idsRefreshedByAboutToShow << id;
d->refresh(id);
} else if (menu) {
Q_EMIT menuUpdated(menu);
}
}
void DBusMenuImporter::slotMenuAboutToHide()
{
QMenu *menu = qobject_cast<QMenu *>(sender());
Q_ASSERT(menu);
QAction *action = menu->menuAction();
Q_ASSERT(action);
int id = action->property(DBUSMENU_PROPERTY_ID).toInt();
d->sendEvent(id, QStringLiteral("closed"));
}
void DBusMenuImporter::slotMenuAboutToShow()
{
QMenu *menu = qobject_cast<QMenu *>(sender());
Q_ASSERT(menu);
updateMenu(menu);
}
QMenu *DBusMenuImporter::createMenu(QWidget *parent)
{
return new QMenu(parent);
}
QIcon DBusMenuImporter::iconForName(const QString &name)
{
return QIcon::fromTheme(name);
}
#include "moc_dbusmenuimporter.cpp"
|