File indexing completed on 2024-06-23 04:42:34
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 <QVector> 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; 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 ShortcutRole, 0036 }; 0037 0038 /** 0039 * Resets the model 0040 * 0041 * If you are using last Used actions functionality, make sure 0042 * to set the last used actions before calling this function 0043 */ 0044 void refresh(const QVector<ActionGroup> &actionGroups); 0045 0046 int rowCount(const QModelIndex &parent = QModelIndex()) const override 0047 { 0048 if (parent.isValid()) { 0049 return 0; 0050 } 0051 return m_rows.size(); 0052 } 0053 0054 int columnCount(const QModelIndex &parent = QModelIndex()) const override 0055 { 0056 Q_UNUSED(parent); 0057 return 2; 0058 } 0059 0060 /** 0061 * reimplemented function to update score that is calculated by KFuzzyMatcher 0062 */ 0063 bool setData(const QModelIndex &index, const QVariant &value, int role) override 0064 { 0065 if (!index.isValid()) 0066 return false; 0067 if (role == Role::Score) { 0068 auto row = index.row(); 0069 m_rows[row].score = value.toInt(); 0070 } 0071 return QAbstractTableModel::setData(index, value, role); 0072 } 0073 0074 QVariant data(const QModelIndex &index, int role) const override; 0075 0076 /** 0077 * action with name @p name was triggered, store it in m_lastTriggered 0078 */ 0079 void actionTriggered(const QString &name); 0080 0081 /** 0082 * last used actions 0083 * max = 6; 0084 */ 0085 QStringList lastUsedActions() const; 0086 0087 /** 0088 * incoming lastUsedActions 0089 * 0090 * should be set before calling refresh() 0091 */ 0092 void setLastUsedActions(const QStringList &actionNames); 0093 0094 QHash<int, QByteArray> roleNames() const override; 0095 0096 private: 0097 QVector<Item> m_rows; 0098 0099 /** 0100 * Last triggered actions by user 0101 * 0102 * Ordered descending i.e., least recently invoked 0103 * action is at the end 0104 */ 0105 QStringList m_lastTriggered; 0106 };