┌   ┐
54
└   ┘

summaryrefslogtreecommitdiff
path: root/src/disabledactionnotifier.cpp
blob: 0b83a9664e93ab37d04dfcdb48990c12268587ae (plain)
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
/*
 * SPDX-FileCopyrightText: 2024 Jin Liu <[email protected]>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "disabledactionnotifier.h"

DisabledActionNotifier::DisabledActionNotifier(QObject *parent)
    : QObject(parent)
{
}

void DisabledActionNotifier::setDisabledReason(QAction *action, QStringView reason)
{
    if (action->isEnabled()) {
        return;
    }

    if (m_shortcuts.contains(action)) {
        clearDisabledReason(action);
    }

    QShortcut *shortcut = new QShortcut(action->shortcut(), parent());
    m_shortcuts.insert(action, shortcut);

    connect(
        action,
        &QAction::enabledChanged,
        this,
        [this, action](bool enabled) {
            if (enabled && m_shortcuts.contains(action)) {
                m_shortcuts.take(action)->deleteLater();
            }
        },
        Qt::SingleShotConnection);

    // Don't capture QStringView, as it may reference a temporary QString
    QString reasonString = reason.toString();
    connect(shortcut, &QShortcut::activated, this, [this, action, reasonString]() {
        Q_EMIT disabledActionTriggered(action, reasonString);
    });
}

void DisabledActionNotifier::clearDisabledReason(QAction *action)
{
    if (action->isEnabled()) {
        return;
    }

    action->disconnect(this);
    if (m_shortcuts.contains(action)) {
        m_shortcuts.take(action)->deleteLater();
    }
}

#include "moc_disabledactionnotifier.cpp"