Debian Codegraph @

src/util/private/xdgiconproxyengine.cpp

raw
1 // SPDX-FileCopyrightText: 2022 - 2023 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4
5 #include "xdgiconproxyengine_p.h"
6
7 #include <QFile>
8 #include <QIconEngine>
9 #include <QThreadStorage>
10 #include <QXmlStreamReader>
11 #include <QDebug>
12 #include <QPainter>
13 #include <QPalette>
14 #include <QGuiApplication>
15
16 #include <cxxabi.h>
17 #include <qmath.h>
18 #if XDG_ICON_VERSION_MAR >= 3
19 #define private public
20 #include <private/xdgiconloader/xdgiconloader_p.h>
21 #undef private
22
23 static inline bool XdgIconFollowColorScheme()
24 {
25 return XdgIconLoader::instance()->followColorScheme();
26 }
27
28 static inline QString rgba(const QColor &c)
29 {
30 // Hex-r-g-b-a
31 return c.name(QColor::HexRgb).append(QString::number(c.alpha(), 16));
32 }
33
34 static inline QPalette palette(QPaintDevice *paintDevice)
35 {
36 QPalette pa;
37
38 if (QObject *obj = dynamic_cast<QObject *>(paintDevice)) {
39 pa = qvariant_cast<QPalette>(obj->property("palette"));
40 } else {
41 pa = qApp->palette();
42 }
43
44 return pa;
45 }
46
47 static inline QPixmap entryPixmap(ScalableEntry *color_entry, const QSize &size, QIcon::Mode mode, QIcon::State state)
48 {
49 if (!color_entry)
50 return QPixmap();
51
52 // init svgIcon with svg absolute path
53 // force to use svg iconengine
54 if (color_entry->svgIcon.isNull())
55 color_entry->svgIcon = QIcon(color_entry->filename);
56
57 if (auto d = color_entry->svgIcon.data_ptr())
58 if (d->engine)
59 return d->engine->pixmap(size, mode, state);
60
61 return color_entry->svgIcon.pixmap(size, mode, state);
62 }
63
64 static const QString STYLE = QStringLiteral(".ColorScheme-Text, .ColorScheme-NeutralText{color:%1;}\
65 \n.ColorScheme-Highlight{color:%2;}");
66
67 namespace DEEPIN_XDG_THEME {
68 static QThreadStorage<PALETTE_MAP> colorScheme; // <type, color>
69 }
70
71 DGUI_BEGIN_NAMESPACE
72 XdgIconProxyEngine::XdgIconProxyEngine(XdgIconLoaderEngine *proxy)
73 : engine(proxy)
74 , lastMode(QIcon::Normal)
75 {
76 }
77
78 XdgIconProxyEngine::~XdgIconProxyEngine()
79 {
80 if (engine)
81 delete engine;
82 }
83
84 quint64 XdgIconProxyEngine::entryCacheKey(const ScalableEntry *color_entry, const QIcon::Mode mode, const QIcon::State state)
85 {
86 return quint64(color_entry) ^ (quint64(mode) << 56) ^ (quint64(state) << 48);
87 }
88
89
90 QPixmap XdgIconProxyEngine::followColorPixmap(ScalableEntry *color_entry, const QSize &size, QIcon::Mode mode, QIcon::State state)
91 {
92 if (mode == QIcon::Selected && mode != lastMode) {
93 // 由非选中状态切换至选中状态,如果颜色值不更新,会按照上一次的状态(非选中时的颜色值)
94 // 从svg图标缓存中寻找异常图标,导致图标异常。
95 for (int each_mode = QIcon::Normal; each_mode <= QIcon::Selected; ++each_mode) {
96 quint64 each_cache_key = entryCacheKey(color_entry, QIcon::Mode(each_mode), state);
97 entryToColorScheme.remove(each_cache_key);
98 }
99 }
100
101 lastMode = mode;
102 quint64 cache_key = entryCacheKey(color_entry, mode, state);
103 const DEEPIN_XDG_THEME::PALETTE_MAP &cache_color_scheme = entryToColorScheme.value(cache_key);
104
105 // 当size为1时表示此svg文件不需要处理ColorScheme标签
106 if (!cache_color_scheme.isEmpty() && cache_color_scheme[DEEPIN_XDG_THEME::Text].size() == 1)
107 return entryPixmap(color_entry, size, mode, state);
108
109 const DEEPIN_XDG_THEME::PALETTE_MAP &color_scheme = DEEPIN_XDG_THEME::colorScheme.localData();
110 QPixmap pm = color_scheme == cache_color_scheme ? entryPixmap(color_entry, size, mode, state) : QPixmap();
111 // Note: not checking the QIcon::isNull(), because in Qt5.10 the isNull() is not reliable
112 // for svg icons desierialized from stream (see https://codereview.qt-project.org/#/c/216086/)
113 if (pm.isNull()) {
114 // The following lines are adapted and updated from KDE's "kiconloader.cpp" ->
115 // KIconLoaderPrivate::processSvg() and KIconLoaderPrivate::createIconImage().
116 // They read the SVG color scheme of SVG icons and give images based on the icon mode.
117 QHash<int, QByteArray> svg_buffers;
118 bool invalidBuffers = true;
119 QFile device {color_entry->filename};
120 if (device.open(QIODevice::ReadOnly)) {
121 // Note: indexes are assembled as in qtsvg (QSvgIconEnginePrivate::hashKey())
122 QPair<int, QString> style_sheet;
123 style_sheet = qMakePair((mode << 4) | state, STYLE.arg(color_scheme[DEEPIN_XDG_THEME::Text], color_scheme[DEEPIN_XDG_THEME::Highlight]));
124 QSharedPointer<QXmlStreamWriter> writer(new QXmlStreamWriter {&svg_buffers[style_sheet.first]});
125
126 QXmlStreamReader xmlReader(&device);
127 while (!xmlReader.atEnd()) {
128 if (xmlReader.readNext() == QXmlStreamReader::StartElement
129 && xmlReader.qualifiedName() == QLatin1String("style")
130 && xmlReader.attributes().value(QLatin1String("id")) == QLatin1String("current-color-scheme")) {
131 invalidBuffers = false;
132
133 writer->writeStartElement(QLatin1String("style"));
134 writer->writeAttributes(xmlReader.attributes());
135 writer->writeCharacters(style_sheet.second);
136 writer->writeEndElement();
137
138 while (xmlReader.tokenType() != QXmlStreamReader::EndElement)
139 xmlReader.readNext();
140 } else if (xmlReader.tokenType() != QXmlStreamReader::Invalid) {
141 writer->writeCurrentToken(xmlReader);
142 }
143 }
144 // duplicate the contents also for opposite state
145 // svg_buffers[(QIcon::Normal<<4)|QIcon::On] = svg_buffers[(QIcon::Normal<<4)|QIcon::Off];
146 // svg_buffers[(QIcon::Selected<<4)|QIcon::On] = svg_buffers[(QIcon::Selected<<4)|QIcon::Off];
147 }
148
149 if (invalidBuffers) {
150 // 此svg图标无ColorScheme标签时不应该再下面的操作,且应该记录下来,避免后续再处理svg文件内容
151 entryToColorScheme[cache_key] = DEEPIN_XDG_THEME::PALETTE_MAP({ {DEEPIN_XDG_THEME::Text, "#"} });
152 return entryPixmap(color_entry, size, mode, state);
153 }
154
155 // use the QSvgIconEngine
156 // - assemble the content as it is done by the operator <<(QDataStream &s, const QIcon &icon)
157 // (the QSvgIconEngine::key() + QSvgIconEngine::write())
158 // - create the QIcon from the content by usage of the QIcon::operator >>(QDataStream &s, const QIcon &icon)
159 // (icon with the (QSvgIconEngine) will be used)
160 QByteArray icon_arr;
161 QDataStream str {&icon_arr, QIODevice::WriteOnly};
162 str.setVersion(QDataStream::Qt_4_4);
163 QHash<int, QString> filenames;
164 filenames[0] = color_entry->filename; // Note: filenames are ignored in the QSvgIconEngine::read()
165 filenames[-1] = color_scheme[DEEPIN_XDG_THEME::Text] + color_scheme[DEEPIN_XDG_THEME::Highlight]; // 在dsvg插件中会为svg图标做缓存,此处是为其添加额外的缓存文件key标识,避免不同color的svg图标会命中同一个缓存文件
166 str << QStringLiteral("svg") << filenames << static_cast<int>(0) /*isCompressed*/ << svg_buffers << static_cast<int>(0) /*hasAddedPimaps*/;
167
168 QDataStream str_read {&icon_arr, QIODevice::ReadOnly};
169 str_read.setVersion(QDataStream::Qt_4_4);
170
171 str_read >> color_entry->svgIcon;
172
173 pm = entryPixmap(color_entry, size, mode, state);
174
175 // load the icon directly from file, if still null
176 if (pm.isNull()) {
177 color_entry->svgIcon = QIcon(color_entry->filename);
178 pm = entryPixmap(color_entry, size, mode, state);
179 }
180
181 entryToColorScheme[cache_key] = color_scheme;
182 }
183
184 return pm;
185 }
186
187 QPixmap XdgIconProxyEngine::pixmapByEntry(QIconLoaderEngineEntry *entry, const QSize &size, QIcon::Mode mode, QIcon::State state)
188 {
189 if (!XdgIconFollowColorScheme()) {
190 DEEPIN_XDG_THEME::colorScheme.setLocalData(DEEPIN_XDG_THEME::PALETTE_MAP());
191
192 return entry->pixmap(size, mode, state);
193 }
194
195 QPixmap pixmap;
196 char *type_name = abi::__cxa_demangle(typeid(*entry).name(), 0, 0, 0);
197
198 if (type_name == QByteArrayLiteral("ScalableFollowsColorEntry")) {
199 if (DEEPIN_XDG_THEME::colorScheme.localData().isEmpty()) {
200 const QPalette &pal = palette(&pixmap);
201 DEEPIN_XDG_THEME::colorScheme.setLocalData(DEEPIN_XDG_THEME::PALETTE_MAP({
202 { DEEPIN_XDG_THEME::Text, mode == QIcon::Selected ? rgba(pal.highlightedText().color()) : rgba(pal.windowText().color()) },
203 { DEEPIN_XDG_THEME::Highlight, rgba(pal.highlight().color()) }
204 }));
205 }
206
207 pixmap = followColorPixmap(static_cast<ScalableEntry *>(entry), size, mode, state);
208 } else {
209 pixmap = entry->pixmap(size, mode, state);
210 }
211
212 free(type_name);
213 DEEPIN_XDG_THEME::colorScheme.setLocalData(DEEPIN_XDG_THEME::PALETTE_MAP());
214
215 return pixmap;
216 }
217
218 void XdgIconProxyEngine::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state)
219 {
220 if (painter->device()->devType() == QInternal::Widget
221 && XdgIconFollowColorScheme()
222 && DEEPIN_XDG_THEME::colorScheme.localData().isEmpty()) {
223 const QPalette &pal = palette(painter->device());
224 DEEPIN_XDG_THEME::colorScheme.setLocalData(DEEPIN_XDG_THEME::PALETTE_MAP({
225 { DEEPIN_XDG_THEME::Text, mode == QIcon::Selected ? rgba(pal.highlightedText().color()) : rgba(pal.windowText().color()) },
226 { DEEPIN_XDG_THEME::Highlight, rgba(pal.highlight().color()) }
227 }));
228 }
229
230 qreal ratio = 1.0;
231 if (qApp->testAttribute(Qt::AA_UseHighDpiPixmaps))
232 ratio = painter->device() ? painter->device()->devicePixelRatioF() : qApp->devicePixelRatio();
233
234 QPixmap pix = pixmap(rect.size() * ratio, mode, state);
235
236 if (pix.isNull())
237 return;
238
239 pix.setDevicePixelRatio(ratio);
240 painter->drawPixmap(rect, pix);
241 }
242
243 QPixmap XdgIconProxyEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state)
244 {
245 engine->ensureLoaded();
246 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
247 QIconLoaderEngineEntry *entry = engine->entryForSize(size);
248 #else
249 QIconLoaderEngineEntry *entry = engine->entryForSize(engine->m_info ,size);
250 #endif
251
252 if (!entry) {
253 DEEPIN_XDG_THEME::colorScheme.setLocalData(DEEPIN_XDG_THEME::PALETTE_MAP());
254
255 return QPixmap();
256 }
257
258 return pixmapByEntry(entry, size, mode, state);
259 }
260
261 void XdgIconProxyEngine::addPixmap(const QPixmap &pixmap, QIcon::Mode mode, QIcon::State state)
262 {
263 return engine->addPixmap(pixmap, mode, state);
264 }
265
266 void XdgIconProxyEngine::addFile(const QString &fileName, const QSize &size, QIcon::Mode mode, QIcon::State state)
267 {
268 return engine->addFile(fileName, size, mode, state);
269 }
270
271 QString XdgIconProxyEngine::key() const
272 {
273 return QLatin1String("XdgIconProxyEngine");
274 }
275
276 QSize XdgIconProxyEngine::actualSize(const QSize &size, QIcon::Mode mode, QIcon::State state)
277 {
278 return engine->actualSize(size, mode, state);
279 }
280
281 QIconEngine *XdgIconProxyEngine::clone() const
282 {
283 return new XdgIconProxyEngine(static_cast<XdgIconLoaderEngine *>(engine->clone()));
284 }
285
286 bool XdgIconProxyEngine::read(QDataStream &in)
287 {
288 return engine->read(in);
289 }
290
291 bool XdgIconProxyEngine::write(QDataStream &out) const
292 {
293 return engine->write(out);
294 }
295
296 void XdgIconProxyEngine::virtual_hook(int id, void *data)
297 {
298 #if QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
299 if (id == QIconEngine::ScaledPixmapHook) {
300 engine->ensureLoaded();
301
302 QIconEngine::ScaledPixmapArgument &arg = *reinterpret_cast<QIconEngine::ScaledPixmapArgument *>(data);
303 // QIcon::pixmap() multiplies size by the device pixel ratio.
304 const int integerScale = qCeil(arg.scale);
305
306 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
307 QIconLoaderEngineEntry *entry = engine->entryForSize(arg.size / integerScale, integerScale);
308 #else
309 QIconLoaderEngineEntry *entry = engine->entryForSize(engine->m_info, arg.size / integerScale, integerScale);
310 #endif
311 // 先禁用缩放,因为此size是已经缩放过的
312 bool useHighDpiPixmap = qGuiApp->testAttribute(Qt::AA_UseHighDpiPixmaps);
313 qGuiApp->setAttribute(Qt::AA_UseHighDpiPixmaps, false);
314 arg.pixmap = entry ? pixmapByEntry(entry, arg.size, arg.mode, arg.state) : QPixmap();
315 qGuiApp->setAttribute(Qt::AA_UseHighDpiPixmaps, useHighDpiPixmap);
316 DEEPIN_XDG_THEME::colorScheme.setLocalData(DEEPIN_XDG_THEME::PALETTE_MAP());
317
318 return;
319 }
320 #endif
321
322 return engine->virtual_hook(id, data);
323 }
324
325 DGUI_END_NAMESPACE
326 #endif