File indexing completed on 2025-02-16 04:56:40
0001 // SPDX-FileCopyrightText: 2021 Waqar Ahmed <waqar.17a@gmail.com> 0002 // SPDX-License-Identifier: LGPL-2.0-or-later 0003 0004 #pragma once 0005 0006 #include <QAbstractTableModel> 0007 #include <QList> 0008 0009 class QAction; 0010 0011 class KalCommandBarModel final : public QAbstractTableModel 0012 { 0013 Q_OBJECT 0014 public: 0015 struct Item { 0016 QString groupName; 0017 QAction *action = nullptr; 0018 int score = 0; 0019 }; 0020 0021 /** 0022 * Represents a list of action that belong to the same group. 0023 * For example: 0024 * - All actions under the menu "File" or "Tool" 0025 */ 0026 struct ActionGroup { 0027 QString name; 0028 QList<QAction *> actions; 0029 }; 0030 0031 explicit KalCommandBarModel(QObject *parent = nullptr); 0032 0033 enum Role { 0034 Score = Qt::UserRole + 1, 0035 DisplayNameRole, 0036 ShortcutRole, 0037 }; 0038 0039 /** 0040 * Resets the model 0041 * 0042 * If you are using last Used actions functionality, make sure 0043 * to set the last used actions before calling this function 0044 */ 0045 void refresh(const QList<ActionGroup> &actionGroups); 0046 0047 int rowCount(const QModelIndex &parent = QModelIndex()) const override 0048 { 0049 if (parent.isValid()) { 0050 return 0; 0051 } 0052 return m_rows.size(); 0053 } 0054 0055 int columnCount(const QModelIndex &parent = QModelIndex()) const override 0056 { 0057 Q_UNUSED(parent); 0058 return 2; 0059 } 0060 0061 /** 0062 * reimplemented function to update score that is calculated by KFuzzyMatcher 0063 */ 0064 bool setData(const QModelIndex &index, const QVariant &value, int role) override 0065 { 0066 if (!index.isValid()) 0067 return false; 0068 if (role == Role::Score) { 0069 auto row = index.row(); 0070 m_rows[row].score = value.toInt(); 0071 } 0072 return QAbstractTableModel::setData(index, value, role); 0073 } 0074 0075 QVariant data(const QModelIndex &index, int role) const override; 0076 0077 /** 0078 * action with name @p name was triggered, store it in m_lastTriggered 0079 */ 0080 void actionTriggered(const QString &name); 0081 0082 /** 0083 * last used actions 0084 * max = 6; 0085 */ 0086 QStringList lastUsedActions() const; 0087 0088 /** 0089 * incoming lastUsedActions 0090 * 0091 * should be set before calling refresh() 0092 */ 0093 void setLastUsedActions(const QStringList &actionNames); 0094 0095 QHash<int, QByteArray> roleNames() const override; 0096 0097 private: 0098 QList<Item> m_rows; 0099 0100 /** 0101 * Last triggered actions by user 0102 * 0103 * Ordered descending i.e., least recently invoked 0104 * action is at the end 0105 */ 0106 QStringList m_lastTriggered; 0107 };