SILICON
Loading...
Searching...
No Matches
icons.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2025. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "icons.hpp"
19#include "theme.hpp"
20#include "themedSvgItem.hpp"
21
22#include <algorithm>
23#include <cmath>
24#include <utility>
25
26#include <QCache>
27#include <QDebug>
28#include <QFile>
29#include <QIconEngine>
30#include <QPainter>
31#include <QPixmapCache>
32#include <QPointer>
33#include <QSvgRenderer>
34#include <QThread>
35#include <QXmlStreamReader>
36#include <QXmlStreamWriter>
37#include <QtMath>
38
39namespace SILICON::ui {
40namespace {
41 void setAttribute(QXmlStreamAttributes& attributes, const QString& name,
42 const QString& value)
43 {
44 for (auto& attribute : attributes) {
45 if (attribute.qualifiedName() == name) {
46 attribute = QXmlStreamAttribute(name, value);
47 return;
48 }
49 }
50 attributes.append(name, value);
51 }
52
53 bool resolveAnnotations(QXmlStreamAttributes& attributes)
54 {
55 for (const QString& property : {QStringLiteral("fill"), QStringLiteral("stroke")}) {
56 const QString annotation = "data-silicon-" + property;
57 if (!attributes.hasAttribute(annotation))
58 continue;
59 const auto token = theme::tokenFromName(attributes.value(annotation));
60 if (!token) {
61 qWarning() << "Unknown SVG theme token:" << attributes.value(annotation);
62 return false;
63 }
64 const auto color = ThemeEngine::getColor(*token).name();
65 // Inline styles take precedence in SVG. Keep both representations coherent,
66 // replacing all repeated declarations of an annotated property as well.
67 setAttribute(attributes, property, color);
68 auto declarations = attributes.value("style").toString().split(';');
69 bool changed = false;
70 for (auto& declaration : declarations) {
71 const auto colon = declaration.indexOf(':');
72 if (colon >= 0
73 && declaration.left(colon).trimmed().compare(property, Qt::CaseInsensitive)
74 == 0) {
75 declaration = declaration.left(colon + 1) + color;
76 changed = true;
77 }
78 }
79 if (changed)
80 setAttribute(attributes, "style", declarations.join(';'));
81 }
82 return true;
83 }
84
85 QString iconPath(const QString& name)
86 {
87 static const QHash<QString, QString> aliases{{"silicon", "silicon-icon"},
88 {"mouse-pointer", "mouse-pointer-2"},
89 {"pan", "move"},
90 {"chart", "file-chart-line"},
91 {"check", "circle-check"},
92 {"xmark-circle", "circle-alert"},
93 {"explosion", "zap"},
94 {"import", "file-input"},
95 {"export", "file-output"},
96 {"open", "folder-open"},
97 {"paste", "clipboard-paste"},
98 {"plug-error", "circle-alert"},
99 {"plus", "circle-plus"},
100 {"minus", "circle-minus"},
101 {"print", "printer"},
102 {"undo", "undo-2"},
103 {"redo", "redo-2"},
104 {"rotate", "rotate-cw"},
105 {"cut", "scissors"},
106 {"delete", "trash"},
107 {"xmark", "x"},
108 {"build", "hammer"},
109 {"diagram", "layout-template"},
110 {"rearrange", "layout-freeform"}};
111 return QStringLiteral(":/icons/%1.svg").arg(aliases.value(name, name));
112 }
113
114 // QApplication owns the cache; items retain shared renderers after eviction.
115 class SvgCache : public QObject {
116 public:
117 using QObject::QObject;
118 QCache<QString, std::shared_ptr<QSvgRenderer>> renderers{256};
119 };
120
121 class SvgIconEngine : public QIconEngine {
122 public:
123 SvgIconEngine(QString path, bool themed, QColor color = {})
124 : path(std::move(path)), themed(themed), color(std::move(color))
125 {
126 }
127
128 SvgIconEngine* clone() const override { return new SvgIconEngine(*this); }
129 QString key() const override { return QStringLiteral("silicon-svg"); }
130 bool isNull() override { return !svg::renderer(path); }
131
132 void paint(QPainter* painter, const QRect& rect, QIcon::Mode mode,
133 QIcon::State) override
134 {
135 if (!painter || rect.isEmpty())
136 return;
137 // deviceTransform includes DPR, rotation, shear and world/view scaling.
138 // The largest singular value gives sufficient resolution even under shear.
139 const auto transform = painter->deviceTransform();
140 const qreal trace =
141 transform.m11() * transform.m11() + transform.m12() * transform.m12()
142 + transform.m21() * transform.m21() + transform.m22() * transform.m22();
143 const qreal determinant =
144 transform.m11() * transform.m22() - transform.m12() * transform.m21();
145 const qreal scale = std::sqrt(
146 (trace
147 + std::sqrt(std::max(qreal(0), trace * trace - 4 * determinant * determinant)))
148 / 2);
149 const auto pm = raster(rect.size(), std::max(scale, qreal(0.01)), mode);
150 painter->drawPixmap(QRectF(rect), pm, QRectF(pm.rect()));
151 }
152
153 QPixmap pixmap(const QSize& size, QIcon::Mode mode, QIcon::State) override
154 {
155 return raster(size, 1.0, mode);
156 }
157
158 QPixmap scaledPixmap(const QSize& size, QIcon::Mode mode, QIcon::State,
159 qreal scale) override
160 {
161#if QT_VERSION < QT_VERSION_CHECK(6, 8, 0)
162 // QIcon passed physical dimensions before Qt 6.8.
163 return raster(QSizeF(size) / scale, scale, mode);
164#else
165 return raster(size, scale, mode);
166#endif
167 }
168
169 private:
170 QString path;
171 bool themed;
172 QColor color;
173
174 QColor colorForMode(QIcon::Mode mode) const
175 {
176 if (mode == QIcon::Disabled)
178 if (color.isValid())
179 return color;
180 return themed ? ThemeEngine::getColor(theme::ColorToken::Ink) : QColor();
181 }
182
183 QPixmap raster(QSizeF logicalSize, qreal dpr, QIcon::Mode mode)
184 {
185 if (logicalSize.isEmpty() || !std::isfinite(dpr) || dpr <= 0)
186 return {};
187 const QSize pixels(qCeil(logicalSize.width() * dpr),
188 qCeil(logicalSize.height() * dpr));
189 if (pixels.isEmpty())
190 return {};
191 const QColor effectiveColor = colorForMode(mode);
192 // Length-prefix identity so even paths containing separators cannot collide.
193 // Round-trip precision keeps fractional device pixel ratios distinct.
194 const QString cacheKey =
195 QStringLiteral("silicon-svg:%1:%2:%3x%4:%5:%6:%7")
196 .arg(path.size())
197 .arg(path)
198 .arg(pixels.width())
199 .arg(pixels.height())
200 .arg(QString::number(dpr, 'g', 17))
201 .arg(effectiveColor.isValid() ? effectiveColor.name(QColor::HexArgb)
202 : "multicolor")
203 .arg(int(ThemeEngine::mode()));
204 QPixmap pm;
205 if (QPixmapCache::find(cacheKey, &pm))
206 return pm;
207 const auto renderer = svg::renderer(path);
208 if (!renderer)
209 return {};
210 pm = QPixmap(pixels);
211 pm.fill(Qt::transparent);
212 {
213 QPainter painter(&pm);
214 renderer->render(&painter, QRectF(QPointF(), QSizeF(pixels)));
215 if (effectiveColor.isValid()) {
216 painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
217 painter.fillRect(pm.rect(), effectiveColor);
218 }
219 }
220 pm.setDevicePixelRatio(dpr);
221 // Qt bounds and evicts raster entries; both immutable themes can reuse their
222 // entries.
223 QPixmapCache::insert(cacheKey, pm);
224 return pm;
225 }
226 };
227
228} // namespace
229
230QByteArray svg::preprocess(const QByteArray& svg)
231{
232 QXmlStreamReader reader(svg);
233 QByteArray result;
234 QXmlStreamWriter writer(&result);
235 while (!reader.atEnd()) {
236 reader.readNext();
237 if (reader.isStartElement()) {
238 auto attributes = reader.attributes();
239 if (!resolveAnnotations(attributes))
240 return {};
241 writer.writeStartElement(reader.qualifiedName().toString());
242 for (const auto& declaration : reader.namespaceDeclarations()) {
243 if (declaration.prefix().isEmpty())
244 writer.writeDefaultNamespace(declaration.namespaceUri().toString());
245 else
246 writer.writeNamespace(declaration.namespaceUri().toString(),
247 declaration.prefix().toString());
248 }
249 writer.writeAttributes(attributes);
250 } else if (!reader.hasError()) {
251 writer.writeCurrentToken(reader);
252 }
253 }
254 if (reader.hasError()) {
255 qWarning() << "Cannot preprocess SVG:" << reader.errorString();
256 return {};
257 }
258 return result;
259}
260
261std::shared_ptr<QSvgRenderer> svg::renderer(const QString& path)
262{
263 Q_ASSERT(qApp && QThread::currentThread() == qApp->thread());
264 static QPointer<SvgCache> cache;
265 if (!cache)
266 cache = new SvgCache(qApp);
267 // Preprocessing bakes in palette colors, so each theme needs its own renderer.
268 const QString key = QString::number(int(ThemeEngine::mode())) + ':' + path;
269 if (const auto* cached = cache->renderers.object(key))
270 return *cached;
271 QFile file(path);
272 if (!file.open(QFile::ReadOnly)) {
273 qWarning() << "Cannot read SVG:" << path << file.errorString();
274 return {};
275 }
276 const auto source = preprocess(file.readAll());
277 if (source.isEmpty())
278 return {};
279 auto result = std::make_shared<QSvgRenderer>();
280 result->setAspectRatioMode(Qt::KeepAspectRatio);
281 if (!result->load(source)) {
282 qWarning() << "Cannot load SVG:" << path;
283 return {};
284 }
285 cache->renderers.insert(key, new std::shared_ptr<QSvgRenderer>(result));
286 return result;
287}
288
289Icon::Icon(const QString& commonName)
290 : QIcon(new SvgIconEngine(iconPath(commonName), commonName != "silicon"))
291{
292}
293
294Icon::Icon(const QString& commonName, const QColor& color)
295 : QIcon(new SvgIconEngine(iconPath(commonName), color.isValid(), color))
296{
297}
298
299class ThemedSvgItem::RendererLease : public QObject {
300public:
301 using QObject::QObject;
302 std::shared_ptr<QSvgRenderer> renderer;
303};
304
305ThemedSvgItem::ThemedSvgItem(QString path, QGraphicsItem* parent)
306 : QGraphicsSvgItem(parent),
307 path(std::move(path)),
309{
310 refreshTheme();
312 [this] { refreshTheme(); });
313}
314
316{
317 auto renderer = svg::renderer(path);
318 if (!renderer)
319 renderer = std::make_shared<QSvgRenderer>();
320 // The item borrows the pointer. Replace it before releasing the previous lease.
321 setSharedRenderer(renderer.get());
322 rendererLease->renderer = std::move(renderer);
323 update();
324}
325
327
328} // namespace SILICON::ui
Icon(const QString &commonName)
Definition icons.cpp:289
static theme::Mode mode()
Definition theme.hpp:91
static const QColor & getColor(theme::ColorToken token)
Definition theme.hpp:92
static ThemeEngine & instance()
Definition theme.cpp:147
std::shared_ptr< QSvgRenderer > renderer
Definition icons.cpp:302
ThemedSvgItem(QString path, QGraphicsItem *parent=nullptr)
Definition icons.cpp:305
std::shared_ptr< QSvgRenderer > renderer(const QString &path)
Definition icons.cpp:261
QByteArray preprocess(const QByteArray &source)
Definition icons.cpp:230
std::optional< ColorToken > tokenFromName(QStringView name)
Definition theme.cpp:70