31#include <QPixmapCache>
33#include <QSvgRenderer>
35#include <QXmlStreamReader>
36#include <QXmlStreamWriter>
41 void setAttribute(QXmlStreamAttributes& attributes,
const QString& name,
44 for (
auto& attribute : attributes) {
45 if (attribute.qualifiedName() == name) {
46 attribute = QXmlStreamAttribute(name, value);
50 attributes.append(name, value);
53 bool resolveAnnotations(QXmlStreamAttributes& attributes)
55 for (
const QString& property : {QStringLiteral(
"fill"), QStringLiteral(
"stroke")}) {
56 const QString annotation =
"data-silicon-" + property;
57 if (!attributes.hasAttribute(annotation))
61 qWarning() <<
"Unknown SVG theme token:" << attributes.value(annotation);
67 setAttribute(attributes, property, color);
68 auto declarations = attributes.value(
"style").toString().split(
';');
70 for (
auto& declaration : declarations) {
71 const auto colon = declaration.indexOf(
':');
73 && declaration.left(colon).trimmed().compare(property, Qt::CaseInsensitive)
75 declaration = declaration.left(colon + 1) + color;
80 setAttribute(attributes,
"style", declarations.join(
';'));
85 QString iconPath(
const QString& name)
87 static const QHash<QString, QString> aliases{{
"silicon",
"silicon-icon"},
88 {
"mouse-pointer",
"mouse-pointer-2"},
90 {
"chart",
"file-chart-line"},
91 {
"check",
"circle-check"},
92 {
"xmark-circle",
"circle-alert"},
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"},
104 {
"rotate",
"rotate-cw"},
109 {
"diagram",
"layout-template"},
110 {
"rearrange",
"layout-freeform"}};
111 return QStringLiteral(
":/icons/%1.svg").arg(aliases.value(name, name));
115 class SvgCache :
public QObject {
117 using QObject::QObject;
118 QCache<QString, std::shared_ptr<QSvgRenderer>> renderers{256};
121 class SvgIconEngine :
public QIconEngine {
123 SvgIconEngine(QString path,
bool themed, QColor color = {})
124 : path(std::move(path)), themed(themed), color(std::move(color))
128 SvgIconEngine* clone()
const override {
return new SvgIconEngine(*
this); }
129 QString key()
const override {
return QStringLiteral(
"silicon-svg"); }
132 void paint(QPainter* painter,
const QRect& rect, QIcon::Mode mode,
133 QIcon::State)
override
135 if (!painter || rect.isEmpty())
139 const auto transform = painter->deviceTransform();
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(
147 + std::sqrt(std::max(qreal(0), trace * trace - 4 * determinant * determinant)))
149 const auto pm = raster(rect.size(), std::max(scale, qreal(0.01)), mode);
150 painter->drawPixmap(QRectF(rect), pm, QRectF(pm.rect()));
153 QPixmap pixmap(
const QSize& size, QIcon::Mode mode, QIcon::State)
override
155 return raster(size, 1.0, mode);
158 QPixmap scaledPixmap(
const QSize& size, QIcon::Mode mode, QIcon::State,
159 qreal scale)
override
161#if QT_VERSION < QT_VERSION_CHECK(6, 8, 0)
163 return raster(QSizeF(size) / scale, scale, mode);
165 return raster(size, scale, mode);
174 QColor colorForMode(QIcon::Mode mode)
const
176 if (mode == QIcon::Disabled)
183 QPixmap raster(QSizeF logicalSize, qreal dpr, QIcon::Mode mode)
185 if (logicalSize.isEmpty() || !std::isfinite(dpr) || dpr <= 0)
187 const QSize pixels(qCeil(logicalSize.width() * dpr),
188 qCeil(logicalSize.height() * dpr));
189 if (pixels.isEmpty())
191 const QColor effectiveColor = colorForMode(mode);
194 const QString cacheKey =
195 QStringLiteral(
"silicon-svg:%1:%2:%3x%4:%5:%6:%7")
199 .arg(pixels.height())
200 .arg(QString::number(dpr,
'g', 17))
201 .arg(effectiveColor.isValid() ? effectiveColor.name(QColor::HexArgb)
205 if (QPixmapCache::find(cacheKey, &pm))
210 pm = QPixmap(pixels);
211 pm.fill(Qt::transparent);
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);
220 pm.setDevicePixelRatio(dpr);
223 QPixmapCache::insert(cacheKey, pm);
232 QXmlStreamReader reader(
svg);
234 QXmlStreamWriter writer(&result);
235 while (!reader.atEnd()) {
237 if (reader.isStartElement()) {
238 auto attributes = reader.attributes();
239 if (!resolveAnnotations(attributes))
241 writer.writeStartElement(reader.qualifiedName().toString());
242 for (
const auto& declaration : reader.namespaceDeclarations()) {
243 if (declaration.prefix().isEmpty())
244 writer.writeDefaultNamespace(declaration.namespaceUri().toString());
246 writer.writeNamespace(declaration.namespaceUri().toString(),
247 declaration.prefix().toString());
249 writer.writeAttributes(attributes);
250 }
else if (!reader.hasError()) {
251 writer.writeCurrentToken(reader);
254 if (reader.hasError()) {
255 qWarning() <<
"Cannot preprocess SVG:" << reader.errorString();
263 Q_ASSERT(qApp && QThread::currentThread() == qApp->thread());
264 static QPointer<SvgCache> cache;
266 cache =
new SvgCache(qApp);
269 if (
const auto* cached = cache->renderers.object(key))
272 if (!file.open(QFile::ReadOnly)) {
273 qWarning() <<
"Cannot read SVG:" << path << file.errorString();
276 const auto source =
preprocess(file.readAll());
277 if (source.isEmpty())
279 auto result = std::make_shared<QSvgRenderer>();
280 result->setAspectRatioMode(Qt::KeepAspectRatio);
281 if (!result->load(source)) {
282 qWarning() <<
"Cannot load SVG:" << path;
285 cache->renderers.insert(key,
new std::shared_ptr<QSvgRenderer>(result));
290 : QIcon(new SvgIconEngine(iconPath(commonName), commonName !=
"silicon"))
295 : QIcon(new SvgIconEngine(iconPath(commonName), color.isValid(), color))
301 using QObject::QObject;
306 : QGraphicsSvgItem(parent),
319 renderer = std::make_shared<QSvgRenderer>();
321 setSharedRenderer(renderer.get());
Icon(const QString &commonName)
static theme::Mode mode()
static const QColor & getColor(theme::ColorToken token)
static ThemeEngine & instance()
std::shared_ptr< QSvgRenderer > renderer
RendererLease * rendererLease
ThemedSvgItem(QString path, QGraphicsItem *parent=nullptr)
~ThemedSvgItem() override
std::shared_ptr< QSvgRenderer > renderer(const QString &path)
QByteArray preprocess(const QByteArray &source)
std::optional< ColorToken > tokenFromName(QStringView name)