File indexing completed on 2024-05-12 05:02:07

0001 /*
0002    SPDX-FileCopyrightText: 2021-2024 Laurent Montel <montel@kde.org>
0003 
0004    SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "rolesmodel.h"
0008 #include "roles/roleinfo.h"
0009 #include "ruqola_debug.h"
0010 
0011 #include <KLocalizedString>
0012 RolesModel::RolesModel(QObject *parent)
0013     : QStandardItemModel(parent)
0014 {
0015 }
0016 
0017 RolesModel::~RolesModel() = default;
0018 
0019 void RolesModel::createItem(const QString &displayStr, const QString &identifier)
0020 {
0021     auto item = new QStandardItem(displayStr);
0022     item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
0023     item->setData(identifier, Identifier);
0024     item->setData(Qt::Unchecked, Qt::CheckStateRole);
0025     item->setToolTip(displayStr);
0026     appendRow(item);
0027 }
0028 
0029 void RolesModel::setRoles(const QVector<RoleInfo> &newRoles)
0030 {
0031     auto item = new QStandardItem(i18n("Roles"));
0032     item->setSelectable(false);
0033     appendRow(item);
0034     for (const RoleInfo &info : newRoles) {
0035         createItem(info.name(), info.identifier());
0036     }
0037     fillRoleSelected();
0038 }
0039 
0040 QStringList RolesModel::rolesSelected() const
0041 {
0042     QStringList lst;
0043     const int rowCountNb = rowCount();
0044     // First one is not a message type
0045     for (int i = 0; i < rowCountNb; i++) {
0046         QStandardItem *itemModel = item(i);
0047         if (itemModel) {
0048             if (itemModel->isCheckable() && itemModel->checkState() == Qt::Checked) {
0049                 lst.append(itemModel->data(Identifier).toString());
0050             }
0051         }
0052     }
0053     return lst;
0054 }
0055 
0056 void RolesModel::setRolesSelected(const QStringList &newRolesSelected)
0057 {
0058     mRolesSelected = newRolesSelected;
0059     fillRoleSelected();
0060 }
0061 
0062 void RolesModel::fillRoleSelected()
0063 {
0064     const int rowCountNb = rowCount();
0065     // First one is not a message type
0066     QStringList copyList = mRolesSelected;
0067     for (int i = 0; i < rowCountNb; i++) {
0068         QStandardItem *itemModel = item(i);
0069         if (itemModel) {
0070             for (const QString &s : std::as_const(mRolesSelected)) {
0071                 if (itemModel->data(Identifier).toString() == s) {
0072                     itemModel->setCheckState(Qt::Checked);
0073                     copyList.removeAll(s);
0074                     break;
0075                 }
0076             }
0077         }
0078     }
0079     // Remove empty string otherwise it will signal it.
0080     copyList.removeAll(QLatin1String(""));
0081     if (!copyList.isEmpty()) {
0082         qCWarning(RUQOLA_LOG) << "role is not implemented here " << copyList;
0083     }
0084 }
0085 
0086 #include "moc_rolesmodel.cpp"