File indexing completed on 2024-06-23 04:42:35

0001 // SPDX-FileCopyrightText: 2021 Waqar Ahmed <waqar.17a@gmail.com>
0002 // SPDX-FileCopyrightText: 2022 Carl Schwan <carl@carlschwan.eu>
0003 // SPDX-License-Identifier: LGPL-2.0-or-later
0004 
0005 #include "commandbarfiltermodel.h"
0006 #include "actionsmodel.h"
0007 #include <KFuzzyMatcher>
0008 #include <QAction>
0009 
0010 CommandBarFilterModel::CommandBarFilterModel(QObject *parent)
0011     : QSortFilterProxyModel(parent)
0012 {
0013 }
0014 
0015 QString CommandBarFilterModel::filterString() const
0016 {
0017     return m_pattern;
0018 }
0019 
0020 void CommandBarFilterModel::setFilterString(const QString &string)
0021 {
0022     if (m_pattern == string) {
0023         return;
0024     }
0025     // MUST reset the model here, we want to repopulate
0026     // invalidateFilter() will not work here
0027     beginResetModel();
0028     m_pattern = string;
0029     endResetModel();
0030     Q_EMIT filterStringChanged();
0031 }
0032 
0033 bool CommandBarFilterModel::lessThan(const QModelIndex &sourceLeft, const QModelIndex &sourceRight) const
0034 {
0035     const int l = sourceLeft.data(KalCommandBarModel::Score).toInt();
0036     const int r = sourceRight.data(KalCommandBarModel::Score).toInt();
0037     return l < r;
0038 }
0039 
0040 bool CommandBarFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
0041 {
0042     if (m_pattern.isEmpty()) {
0043         return true;
0044     }
0045 
0046     const QModelIndex idx = sourceModel()->index(sourceRow, 0, sourceParent);
0047     if (!(qvariant_cast<QAction *>(idx.data(Qt::UserRole))->isEnabled())) {
0048         return false;
0049     }
0050 
0051     const QString actionName = idx.data(Qt::DisplayRole).toString();
0052     KFuzzyMatcher::Result res = KFuzzyMatcher::match(m_pattern, actionName);
0053     sourceModel()->setData(idx, res.score, KalCommandBarModel::Score);
0054     return res.matched;
0055 }