| 1 | /* |
| 2 | SPDX-FileCopyrightText: 2019 Dan Leinir Turthra Jensen <admin@leinir.dk> |
| 3 | |
| 4 | SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL |
| 5 | */ |
| 6 | |
| 7 | #include "categoriesmodel.h" |
| 8 | |
| 9 | #include "provider.h" |
| 10 | |
| 11 | #include <KLocalizedString> |
| 12 | |
| 13 | CategoriesModel::CategoriesModel(KNSCore::EngineBase *parent) |
| 14 | : QAbstractListModel(parent) |
| 15 | , m_engine(parent) |
| 16 | { |
| 17 | connect(sender: m_engine, signal: &KNSCore::EngineBase::signalCategoriesMetadataLoded, context: this, slot: [this]() { |
| 18 | beginResetModel(); |
| 19 | endResetModel(); |
| 20 | }); |
| 21 | } |
| 22 | |
| 23 | CategoriesModel::~CategoriesModel() = default; |
| 24 | |
| 25 | QHash<int, QByteArray> CategoriesModel::roleNames() const |
| 26 | { |
| 27 | static const QHash<int, QByteArray> roles{{NameRole, "name" }, {IdRole, "id" }, {DisplayNameRole, "displayName" }}; |
| 28 | return roles; |
| 29 | } |
| 30 | |
| 31 | int CategoriesModel::rowCount(const QModelIndex &parent) const |
| 32 | { |
| 33 | if (parent.isValid()) { |
| 34 | return 0; |
| 35 | } |
| 36 | return m_engine->categoriesMetadata().count() + 1; |
| 37 | } |
| 38 | |
| 39 | QVariant CategoriesModel::data(const QModelIndex &index, int role) const |
| 40 | { |
| 41 | if (!index.isValid()) { |
| 42 | return QVariant(); |
| 43 | } |
| 44 | const QList<KNSCore::Provider::CategoryMetadata> categoriesMetadata = m_engine->categoriesMetadata(); |
| 45 | if (index.row() == 0) { |
| 46 | switch (role) { |
| 47 | case NameRole: |
| 48 | return QString(); |
| 49 | case IdRole: |
| 50 | return 0; |
| 51 | case DisplayNameRole: |
| 52 | return i18nc("The first entry in the category selection list (also the default value)" , "All Categories" ); |
| 53 | default: |
| 54 | return QStringLiteral("Unknown role" ); |
| 55 | } |
| 56 | } else if (index.row() <= categoriesMetadata.count()) { |
| 57 | const KNSCore::Provider::CategoryMetadata category = categoriesMetadata[index.row() - 1]; |
| 58 | switch (role) { |
| 59 | case NameRole: |
| 60 | return category.name; |
| 61 | case IdRole: |
| 62 | return category.id; |
| 63 | case DisplayNameRole: |
| 64 | return category.displayName; |
| 65 | default: |
| 66 | return QStringLiteral("Unknown role" ); |
| 67 | } |
| 68 | } |
| 69 | return QVariant(); |
| 70 | } |
| 71 | |
| 72 | QString CategoriesModel::idToDisplayName(const QString &id) const // TODO KF6 unused? |
| 73 | { |
| 74 | QString dispName = i18nc("The string passed back in the case the requested category is not known" , "Unknown Category" ); |
| 75 | const auto metaData = m_engine->categoriesMetadata(); |
| 76 | for (const KNSCore::Provider::CategoryMetadata &cat : metaData) { |
| 77 | if (cat.id == id) { |
| 78 | dispName = cat.displayName; |
| 79 | break; |
| 80 | } |
| 81 | } |
| 82 | return dispName; |
| 83 | } |
| 84 | |
| 85 | #include "moc_categoriesmodel.cpp" |
| 86 | |