imageprovider.cpp (2483B)
1 /* 2 * Copyright (C) 2019 Daniel Vrátil <dvratil@kde.org> 3 * 2021 Willy Goiffon <contact@z3bra.org> 4 * 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <https://www.gnu.org/licenses/>. 17 */ 18 19 20 #include "imageprovider.h" 21 22 #include <QPainter> 23 #include <QColor> 24 #include <QMap> 25 26 #include <sailfishapp.h> 27 28 namespace { 29 30 static const auto schemaMap = QMap<QString, QString>{ 31 {{QStringLiteral("passIcon"), QStringLiteral("icons")}, 32 {QStringLiteral("passImage"), QStringLiteral("images")}} 33 }; 34 35 static QString pathForSchema(const QString &schema) 36 { 37 return schemaMap.value(schema); 38 } 39 40 } 41 42 ImageProvider::ImageProvider(const QString &schema) 43 : QQuickImageProvider(QQuickImageProvider::Pixmap) 44 , mSchema(schema) 45 { 46 Q_ASSERT(schemaMap.contains(schema)); 47 } 48 49 // Based on https://together.jolla.com/question/44325/iconbutton-how-to-use-own-icons-with-highlight/ 50 QPixmap ImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) 51 { 52 const auto parts = id.splitRef(QLatin1Char('?')); 53 54 auto source = findSource(parts.at(0)); 55 if (size) { 56 *size = source.size(); 57 } 58 59 if (parts.size() > 1) { 60 const auto color = parts.at(1).toString(); 61 if (QColor::isValidColor(color)) { 62 QPainter painter(&source); 63 painter.setCompositionMode(QPainter::CompositionMode_SourceIn); 64 painter.fillRect(source.rect(), color); 65 painter.end(); 66 } 67 } 68 69 if (requestedSize.width() > 0 && requestedSize.height() > 0) { 70 return source.scaled(requestedSize, Qt::IgnoreAspectRatio); 71 } else { 72 return source; 73 } 74 } 75 76 QPixmap ImageProvider::findSource(const QStringRef &name) 77 { 78 const QString imgPath = QStringLiteral("qml/") % pathForSchema(mSchema) % QStringLiteral("/") % name; 79 return QPixmap(SailfishApp::pathTo(imgPath).toString(QUrl::RemoveScheme)); 80 }