forked from notepadqq/notepadqq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvgiconengine.cpp
76 lines (63 loc) · 2.65 KB
/
svgiconengine.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "include/svgiconengine.h"
#include <QFile>
#include <QPainter>
#include <QGraphicsColorizeEffect>
#include <QApplication>
#include <QPalette>
#include <QRegularExpression>
SVGIconEngine::SVGIconEngine(const std::string &iconBuffer) {
auto data = QByteArray::fromStdString(iconBuffer);
m_darkIcon = replaceSvgMainFillColor(QString(data), QColor(65,65,65)).toUtf8();
m_lightIcon = replaceSvgMainFillColor(QString(data), QColor(205,205,205)).toUtf8();
}
SVGIconEngine* SVGIconEngine::fromFile(const QString &fileName) {
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
return new SVGIconEngine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"></svg>");
}
return new SVGIconEngine(file.readAll().toStdString());
}
void SVGIconEngine::paint(QPainter *painter, const QRect &rect,
QIcon::Mode mode, QIcon::State) {
auto bgColor = QApplication::palette().color(QPalette::Window);
bool darkUI = bgColor.lightnessF() < 0.5;
QSvgRenderer renderer(darkUI ? m_lightIcon : m_darkIcon);
renderer.render(painter, rect);
}
QIconEngine *SVGIconEngine::clone() const {
return new SVGIconEngine(*this);
}
QPixmap SVGIconEngine::pixmap(const QSize &size, QIcon::Mode mode,
QIcon::State state) {
// This function is necessary to create an EMPTY pixmap. It's called always
// before paint()
QImage img(size, QImage::Format_ARGB32);
img.fill(qRgba(0, 0, 0, 0));
QPixmap pix = QPixmap::fromImage(img, Qt::NoFormatConversion);
{
QPainter painter(&pix);
QRect r(QPoint(0.0, 0.0), size);
this->paint(&painter, r, mode, state);
}
return pix;
}
QString SVGIconEngine::replaceSvgMainFillColor(const QString& svg, const QColor& color) const
{
static const QRegularExpression reFillTag(R"PRE(<svg(.|\n|\r)*?fill="([^"]*?)">)PRE");
static const QRegularExpression reNoFillTag(R"PRE(<svg(.|\n|\r)*?>)PRE");
// Try replacing the color within the already existing "fill" attribute, if it exists
auto match = reFillTag.match(svg);
if (match.hasMatch()) {
auto a = match.capturedStart(1); // start of the attribute value
auto b = match.capturedEnd(1); // end of the attribute value
QString new_svg = svg.mid(0, a) + color.name(QColor::HexRgb) + svg.mid(b);
return new_svg;
}
match = reNoFillTag.match(svg);
if (match.hasMatch()) {
auto b = match.capturedEnd(0) - 1; // end of the opening <svg> tag
QString new_svg = svg.mid(0, b) + " fill=\"" + color.name(QColor::HexRgb) + "\"" + svg.mid(b);
return new_svg;
}
return svg;
}