File indexing completed on 2024-05-12 17:24:10

0001 // SPDX-FileCopyrightText: 2023 Carl Schwan <carl@carlschwan.eu>
0002 // SPDX-License-Identifier: LGPL-2.0-or-later
0003 
0004 #include "plantimagemodel.h"
0005 
0006 #include <QDebug>
0007 #include <QDir>
0008 
0009 PlantImageModel::PlantImageModel(QObject *parent)
0010     : QAbstractListModel(parent)
0011 {
0012     QDir assets(":/assets/");
0013     m_urls = assets.entryList();
0014 }
0015 
0016 int PlantImageModel::rowCount(const QModelIndex &parent) const
0017 {
0018     Q_UNUSED(parent);
0019     return m_urls.count() + (m_customImage.isEmpty() ? 0 : 1);
0020 }
0021 
0022 QHash<int, QByteArray> PlantImageModel::roleNames() const
0023 {
0024     return {
0025         { UrlRole, "url" },
0026     };
0027 }
0028 
0029 QString PlantImageModel::customImage() const
0030 {
0031     return m_customImage;
0032 }
0033 
0034 void PlantImageModel::setCustomImage(const QString &customImage)
0035 {
0036     if (m_customImage == customImage || customImage.startsWith(QStringLiteral("qrc"))) {
0037         return;
0038     }
0039 
0040     if (customImage.isEmpty()) {
0041         beginRemoveRows({}, 0, 0);
0042         m_customImage = customImage;
0043         endRemoveRows();
0044     } else {
0045         beginInsertRows({}, 0, 0);
0046         m_customImage = customImage;
0047         endInsertRows();
0048     }
0049 
0050     Q_EMIT customImageChanged();
0051 }
0052 
0053 int PlantImageModel::urlToIndex(const QString &url) const
0054 {
0055     if (url.isEmpty()) {
0056         return -1;
0057     }
0058     if (url == m_customImage) {
0059         return 0;
0060     }
0061     const auto it = std::find_if(m_urls.cbegin(), m_urls.cend(), [&url](const QString &_url) {
0062         return _url == url;
0063 
0064     });
0065     if (it == m_urls.cend()) {
0066         return -1;
0067     }
0068     return it - m_urls.cbegin() + (m_customImage.isEmpty() ? 0 : 1);
0069 }
0070 
0071 QVariant PlantImageModel::data(const QModelIndex& index, int role) const
0072 {
0073     Q_ASSERT(checkIndex(index, QAbstractItemModel::CheckIndexOption::IndexIsValid));
0074 
0075     const int row = m_customImage.isEmpty() ? index.row() : index.row() - 1;
0076 
0077     switch (role){
0078     case UrlRole:
0079          return row == -1 ? m_customImage : "qrc:/assets/" + m_urls.at(row);
0080     };
0081 
0082     Q_UNREACHABLE();
0083 }