on xenial help sign in
protect the GlobalShortcut pointer with QPointer

cleanup the list of shortcuts on destruction

commit94be13178c440f5b8ebb9c5bfd750834b3475a19 authorLukáš Tinkl <lukas.tinkl@canonical.com> dateTue 25 Aug 2015, 12:05 (11 years ago) parent6657af0
2 files changed+34−11
plugins/GlobalShortcut/globalshortcutregistry.cpp+30−10 plugins/GlobalShortcut/globalshortcutregistry.h+4−1
plugins/GlobalShortcut/globalshortcutregistry.cpp+30−10
@@ -40,12 +40,31 @@ bool GlobalShortcutRegistry::hasShortcut(const QVariant &seq) const
4040
4141void GlobalShortcutRegistry::addShortcut(const QVariant &seq, GlobalShortcut *sc)
4242{
43− if (!m_shortcuts.keys().contains(seq)) { // create a new entry
44− m_shortcuts.insert(seq, {sc});
45− } else { // append to an existing one
46− auto shortcuts = m_shortcuts[seq];
47− shortcuts.append(sc);
48− m_shortcuts.insert(seq, shortcuts);
43+ if (sc) {
44+ if (!m_shortcuts.keys().contains(seq)) { // create a new entry
45+ m_shortcuts.insert(seq, {sc});
46+ } else { // append to an existing one
47+ auto shortcuts = m_shortcuts[seq];
48+ shortcuts.append(sc);
49+ m_shortcuts.insert(seq, shortcuts);
50+ }
51+
52+ connect(sc, &GlobalShortcut::destroyed, this, &GlobalShortcutRegistry::removeShortcut);
53+ }
54+}
55+
56+void GlobalShortcutRegistry::removeShortcut(QObject *obj)
57+{
58+ QMutableMapIterator<QVariant, QVector<QPointer<GlobalShortcut>>> it(m_shortcuts);
59+ while (it.hasNext()) {
60+ it.next();
61+ GlobalShortcut * scObj = static_cast<GlobalShortcut *>(obj);
62+ if (scObj && it.value().contains(scObj)) {
63+ it.value().removeAll(scObj);
64+ if (it.value().isEmpty()) {
65+ it.remove();
66+ }
67+ }
4968 }
5069}
5170
@@ -56,14 +75,15 @@ bool GlobalShortcutRegistry::eventFilter(QObject *obj, QEvent *event)
5675
5776 if (event->type() == QEvent::KeyPress) {
5877 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
59−
6078 QKeySequence seq = QKeySequence(keyEvent->key() + keyEvent->modifiers());
6179 if (m_shortcuts.keys().contains(seq)) {
6280 const auto shortcuts = m_shortcuts.value(seq);
63− Q_FOREACH(auto shortcut, shortcuts) {
64− qApp->sendEvent(shortcut, keyEvent);
81+ Q_FOREACH(const auto &shortcut, shortcuts) {
82+ if (shortcut) {
83+ qApp->sendEvent(shortcut, keyEvent);
84+ event->accept();
85+ }
6586 }
66− event->accept();
6787 }
6888
6989 return event->isAccepted();
plugins/GlobalShortcut/globalshortcutregistry.h+4−1
@@ -24,7 +24,7 @@
2424
2525#include "globalshortcut.h"
2626
27−typedef QMap<QVariant, QVector<GlobalShortcut *>> GlobalShortcutList;
27+typedef QMap<QVariant, QVector<QPointer<GlobalShortcut>>> GlobalShortcutList;
2828
2929/**
3030 * @brief The GlobalShortcutRegistry class
@@ -59,6 +59,9 @@ public:
5959protected:
6060 bool eventFilter(QObject *obj, QEvent *event) override;
6161
62+private Q_SLOTS:
63+ void removeShortcut(QObject *obj);
64+
6265private:
6366 GlobalShortcutList m_shortcuts;
6467 QPointer<QWindow> m_filteredWindow = nullptr;