File indexing completed on 2024-12-22 04:27:04

0001 /*
0002     SPDX-FileCopyrightText: 2023 Volker Krause <vkrause@kde.org>
0003     SPDX-License-Identifier: LGPL-2.0-or-later
0004 */
0005 
0006 #include "texturecache_p.h"
0007 #include "logging.h"
0008 
0009 #include <QDebug>
0010 #include <QFile>
0011 #include <QGuiApplication>
0012 #include <QImageReader>
0013 
0014 using namespace KOSMIndoorMap;
0015 
0016 TextureCache::TextureCache() = default;
0017 TextureCache::~TextureCache() = default;
0018 
0019 QImage TextureCache::image(const QString &name) const
0020 {
0021     auto it = std::lower_bound(m_cache.begin(), m_cache.end(), name, [](const auto &lhs, const auto &rhs) { return lhs.name < rhs; });
0022     if (it != m_cache.end() && (*it).name == name) {
0023         return (*it).image;
0024     }
0025 
0026     CacheEntry entry;
0027     entry.name = name;
0028 
0029     const QString fileName = QLatin1String(":/org.kde.kosmindoormap/assets/textures/") + name;
0030     if (name.endsWith(QLatin1String(".svg"))) {
0031         QImageReader imgReader(fileName, "svg");
0032         imgReader.setScaledSize(imgReader.size() * qGuiApp->devicePixelRatio());
0033         entry.image = imgReader.read();
0034         entry.image.setDevicePixelRatio(qGuiApp->devicePixelRatio());
0035     } else {
0036         // TODO high dpi raster image loading
0037         // QImageReader is supposed to do that transparently, but that doesn't seem to work here?
0038         QImageReader imgReader(fileName);
0039         entry.image = imgReader.read();
0040     }
0041 
0042     if (entry.image.isNull()) {
0043         qCWarning(Log) << "failed to load texture:" << name;
0044     } else {
0045         qCDebug(Log) << "loaded texture:" << entry.name << entry.image;
0046     }
0047 
0048     it = m_cache.insert(it, std::move(entry));
0049     return (*it).image;
0050 }