File indexing completed on 2023-12-03 10:55:12
0001 /* 0002 * SPDX-FileCopyrightText: 2023 Kai Uwe Broulik <kde@broulik.de> 0003 * 0004 * SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL 0005 */ 0006 0007 #include "kopenaction_p.h" 0008 0009 #include <KRecentFilesAction> 0010 #include <KStandardAction> 0011 0012 #include <QMenu> 0013 #include <QPointer> 0014 0015 class KOpenActionPrivate 0016 { 0017 public: 0018 KOpenActionPrivate(KOpenAction *q); 0019 0020 void updatePopupMode(); 0021 void onPopupMenuAboutToShow(); 0022 0023 KOpenAction *q; 0024 QPointer<KRecentFilesAction> recentFilesAction; 0025 }; 0026 0027 KOpenActionPrivate::KOpenActionPrivate(KOpenAction *q) 0028 : q(q) 0029 { 0030 } 0031 0032 KOpenAction::~KOpenAction() = default; 0033 0034 void KOpenActionPrivate::updatePopupMode() 0035 { 0036 if (recentFilesAction && recentFilesAction->isEnabled()) { 0037 q->setPopupMode(KToolBarPopupAction::MenuButtonPopup); 0038 } else { 0039 q->setPopupMode(KToolBarPopupAction::NoPopup); 0040 } 0041 } 0042 0043 void KOpenActionPrivate::onPopupMenuAboutToShow() 0044 { 0045 q->popupMenu()->clear(); 0046 0047 if (recentFilesAction) { 0048 // Using the menu explicitly rather than the actions so we also get the "Forget..." entry. 0049 if (auto *recentMenu = recentFilesAction->menu()) { 0050 // Trigger a menu update. 0051 Q_EMIT recentMenu->aboutToShow(); 0052 0053 const auto actions = recentMenu->actions(); 0054 for (QAction *action : actions) { 0055 q->popupMenu()->addAction(action); 0056 } 0057 } 0058 } 0059 } 0060 0061 KOpenAction::KOpenAction(QObject *parent) 0062 : KOpenAction(QIcon(), QString(), parent) 0063 { 0064 } 0065 0066 KOpenAction::KOpenAction(const QIcon &icon, const QString &text, QObject *parent) 0067 : KToolBarPopupAction(icon, text, parent) 0068 , d(new KOpenActionPrivate(this)) 0069 { 0070 setPopupMode(KToolBarPopupAction::NoPopup); 0071 connect(popupMenu(), &QMenu::aboutToShow, this, [this] { 0072 d->onPopupMenuAboutToShow(); 0073 }); 0074 } 0075 0076 QWidget *KOpenAction::createWidget(QWidget *parentWidget) 0077 { 0078 if (!d->recentFilesAction) { 0079 // Find the accompanying file_open_recent action. 0080 QAction *action = nullptr; 0081 0082 if (parent() && parent()->inherits("KActionCollection")) { 0083 const QString openRecentActionId = QString::fromUtf8(KStandardAction::name(KStandardAction::OpenRecent)); 0084 QMetaObject::invokeMethod(parent(), "action", Q_RETURN_ARG(QAction *, action), Q_ARG(QString, openRecentActionId)); 0085 } 0086 0087 d->recentFilesAction = qobject_cast<KRecentFilesAction *>(action); 0088 if (d->recentFilesAction) { 0089 connect(d->recentFilesAction.data(), &QAction::enabledChanged, this, [this] { 0090 d->updatePopupMode(); 0091 }); 0092 } 0093 } 0094 0095 d->updatePopupMode(); 0096 0097 return KToolBarPopupAction::createWidget(parentWidget); 0098 } 0099 0100 #include "moc_kopenaction_p.cpp"