File indexing completed on 2025-02-23 05:09:22
0001 /* 0002 SPDX-FileCopyrightText: 2021 Derek Christ <christ.derek@gmail.com> 0003 0004 SPDX-License-Identifier: GPL-2.0-or-later 0005 */ 0006 0007 #include "removeaction.h" 0008 0009 #include <QGuiApplication> 0010 #include <QKeyEvent> 0011 0012 RemoveAction::RemoveAction(KActionCollection *collection, QObject *parent) 0013 : QAction(parent) 0014 , m_collection(collection) 0015 { 0016 connect(this, &RemoveAction::triggered, this, [this]() { 0017 if (m_action) { 0018 m_action->trigger(); 0019 } 0020 }); 0021 } 0022 0023 void RemoveAction::update(ShiftState shiftState) 0024 { 0025 if (!m_collection) { 0026 m_action = nullptr; 0027 return; 0028 } 0029 0030 if (shiftState == ShiftState::Unknown) { 0031 shiftState = QGuiApplication::keyboardModifiers() & Qt::ShiftModifier ? ShiftState::Pressed : ShiftState::Released; 0032 } 0033 0034 switch (shiftState) { 0035 case ShiftState::Pressed: { 0036 m_action = m_collection->action(QStringLiteral("del")); 0037 0038 if (m_action) { 0039 // Make sure we show Shift+Del in the context menu. 0040 auto deleteShortcuts = m_action->shortcuts(); 0041 deleteShortcuts.removeAll(Qt::SHIFT | Qt::Key_Delete); 0042 deleteShortcuts.prepend(Qt::SHIFT | Qt::Key_Delete); 0043 m_collection->setDefaultShortcuts(this, deleteShortcuts); 0044 } 0045 break; 0046 } 0047 case ShiftState::Released: { 0048 m_action = m_collection->action(QStringLiteral("trash")); 0049 0050 if (m_action) { 0051 // Make sure we show Del in the context menu. 0052 auto trashShortcuts = m_action->shortcuts(); 0053 trashShortcuts.removeAll(QKeySequence::Delete); 0054 trashShortcuts.prepend(QKeySequence::Delete); 0055 m_collection->setDefaultShortcuts(this, trashShortcuts); 0056 } 0057 break; 0058 } 0059 case ShiftState::Unknown: 0060 Q_UNREACHABLE(); 0061 break; 0062 } 0063 0064 if (m_action) { 0065 setText(m_action->text()); 0066 setIcon(m_action->icon()); 0067 setEnabled(m_action->isEnabled()); 0068 } 0069 } 0070 0071 const QAction *RemoveAction::proxyAction() const 0072 { 0073 return m_action; 0074 } 0075 0076 bool RemoveAction::eventFilter(QObject *watched, QEvent *event) 0077 { 0078 Q_UNUSED(watched) 0079 0080 // Catching Shift modifier usage on open context menus to swap the 0081 // Trash/Delete actions. 0082 if (event->type() == QEvent::KeyPress) { 0083 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); 0084 0085 if (keyEvent->key() == Qt::Key_Shift) { 0086 update(RemoveAction::ShiftState::Pressed); 0087 } 0088 } else if (event->type() == QEvent::KeyRelease) { 0089 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); 0090 0091 if (keyEvent->key() == Qt::Key_Shift) { 0092 update(RemoveAction::ShiftState::Released); 0093 } 0094 } 0095 0096 return false; 0097 }