Debian Codegraph @

src/util/private/dbuiltiniconengine.cpp

raw
1 // SPDX-FileCopyrightText: 2022 - 2023 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4 #include "dbuiltiniconengine_p.h"
5
6 #include <DGuiApplicationHelper>
7
8 #include <QPainter>
9 #include <QPixmap>
10 #include <QPixmapCache>
11 #include <QImageReader>
12 #include <QDir>
13 #include <qmath.h>
14 #include <private/qiconloader_p.h>
15 #include <private/qguiapplication_p.h>
16 #include <QDebug>
17
18 #define BUILTIN_ICON_PATH ":/icons/deepin/builtin"
19
20 DGUI_BEGIN_NAMESPACE
21
22 static qreal devicePixelRatio(QPainter *painter)
23 {
24 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
25 if (qApp->testAttribute(Qt::AA_UseHighDpiPixmaps))
26 return (painter && painter->device()) ? painter->device()->devicePixelRatioF() : qApp->devicePixelRatio();
27 return 1.0;
28 #else
29 return (painter && painter->device()) ? painter->device()->devicePixelRatioF() : qApp->devicePixelRatio();
30 #endif
31 }
32
33 class Q_DECL_HIDDEN ImageEntry : public QIconLoaderEngineEntry
34 {
35 public:
36 enum Type {
37 TextType, // 完全跟随画笔前景色变化
38 ActionType, // 只在非normal状态下跟随画笔前景色
39 IconType // 任务状态都不跟随画笔颜色
40 };
41
42 ImageEntry(Type t)
43 : type(t)
44 {
45
46 }
47
48 QString pmcKey(const QSize &size, QIcon::Mode mode, QIcon::State state)
49 {
50 return QLatin1String("$qt_icon_")
51 + filename + QLatin1String("_")
52 + QString::number((((((qint64(size.width()) << 11) | size.height()) << 11) | mode) << 4) | state, 16);
53 }
54
55 void genIconTypeIcon(QPixmap &pm, QIcon::Mode mode)
56 {
57 if (type == IconType && qobject_cast<QGuiApplication *>(QCoreApplication::instance())) {
58 const QPixmap generated = QGuiApplicationPrivate::instance()->applyQIconStyleHelper(mode, pm);
59 if (!generated.isNull())
60 pm = generated;
61 }
62 }
63
64 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
65 QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state, qreal scale) override {
66 #else
67 QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) override {
68 #endif
69 Q_UNUSED(state)
70
71 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
72 const QSize pixmapSize = size * scale;
73 #else
74 const QSize pixmapSize(size);
75 #endif
76 QPixmap pm;
77 QString pmckey(pmcKey(pixmapSize, mode, state));
78 if (QPixmapCache::find(pmckey, &pm)) {
79 genIconTypeIcon(pm, mode);
80 return pm;
81 }
82
83 // png 会读取前8个 bit 对比,需要关闭重新打开,否则同一个 icon 不同 state/mode 会再次读取时报错导致 pixmap 为空。
84 // 所以此处只对 DirImageEntry(isdir==true) 进行判断不再重新调用 setFileName
85 if (Q_UNLIKELY(!reader.device()) || !QFileInfo(filename).isDir()) {
86 reader.setFileName(filename);
87 }
88
89 if (dir.type == QIconDirInfo::Scalable)
90 reader.setScaledSize(pixmapSize);
91
92 pm = QPixmap::fromImageReader(&reader);
93 if (!pm.isNull())
94 QPixmapCache::insert(pmckey, pm);
95
96 genIconTypeIcon(pm, mode);
97 return pm;
98 }
99
100 Type type;
101 QImageReader reader;
102 };
103
104 class Q_DECL_HIDDEN DirImageEntry : public ImageEntry
105 {
106 public:
107 using ImageEntry::ImageEntry;
108
109 static QString getIconFile(const QString &key, const QDir &dir, const QString &suffix)
110 {
111 if (dir.exists(key + "." + suffix)) {
112 return dir.filePath(key + "." + suffix);
113 }
114
115 int _index = key.indexOf('_');
116
117 if (_index > 0) {
118 const QString &mode = key.left(_index);
119
120 if (dir.exists(mode + "." + suffix)) {
121 return dir.filePath(mode + "." + suffix);
122 }
123
124 const QString &state = key.mid(_index);
125
126 if (dir.exists("normal" + state + "." + suffix)) {
127 return dir.filePath("normal" + state + "." + suffix);
128 }
129 }
130
131 return dir.filePath("normal." + suffix);
132 }
133
134 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
135 QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state, qreal scale) override {
136 #else
137 QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) override {
138 #endif
139 if (iconFileMap.isEmpty()) {
140 const QString &suffix = QFileInfo(filename).suffix();
141 QDir dir(filename);
142
143 iconFileMap[QIcon::Disabled << 8 | QIcon::On] = getIconFile("disabled_on", dir, suffix);
144 iconFileMap[QIcon::Disabled << 8 | QIcon::Off] = getIconFile("disabled_off", dir, suffix);
145 iconFileMap[QIcon::Active << 8 | QIcon::On] = getIconFile("active_on", dir, suffix);
146 iconFileMap[QIcon::Active << 8 | QIcon::Off] = getIconFile("active_off", dir, suffix);
147 iconFileMap[QIcon::Selected << 8 | QIcon::On] = getIconFile("selected_on", dir, suffix);
148 iconFileMap[QIcon::Selected << 8 | QIcon::Off] = getIconFile("selected_off", dir, suffix);
149 iconFileMap[QIcon::Normal << 8 | QIcon::On] = getIconFile("normal_on", dir, suffix);
150 iconFileMap[QIcon::Normal << 8 | QIcon::Off] = getIconFile("normal_off", dir, suffix);
151 }
152
153 reader.setFileName(iconFileMap.value(mode << 8 | state));
154
155 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
156 return ImageEntry::pixmap(size, mode, state, scale);
157 #else
158 return ImageEntry::pixmap(size, mode, state);
159 #endif
160 }
161
162 QMap<qint16, QString> iconFileMap;
163 };
164
165 DBuiltinIconEngine::DBuiltinIconEngine(const QString &iconName)
166 : m_iconName(iconName)
167 , m_initialized(false)
168 // 当主题名称中包含'/'时, '/'前面的部分即为指定的图标类型, 此时不需要再
169 // 跟随系统中的主题类型改变
170 , m_followSystemTheme(iconName.indexOf('/') < 0)
171 {
172 // 初始化图标类型
173 m_key = iconName.startsWith("dark/") ? DGuiApplicationHelper::DarkType
174 : DGuiApplicationHelper::LightType;
175 }
176
177 DBuiltinIconEngine::DBuiltinIconEngine(const DBuiltinIconEngine &other)
178 : QIconEngine(other)
179 , m_iconName(other.m_iconName)
180 , m_key(other.m_key)
181 , m_initialized(other.m_initialized)
182 , m_followSystemTheme(other.m_initialized)
183 {
184
185 }
186
187 DBuiltinIconEngine::~DBuiltinIconEngine()
188 {
189 #if QT_VERSION <= QT_VERSION_CHECK(6, 2, 4)
190 if (hasIcon())
191 qDeleteAll(m_info.entries);
192 #endif
193 }
194
195 QSize DBuiltinIconEngine::actualSize(const QSize &size, QIcon::Mode mode,
196 QIcon::State state)
197 {
198 Q_UNUSED(mode);
199 Q_UNUSED(state);
200
201 ensureLoaded();
202
203 QIconLoaderEngineEntry *entry = QIconLoaderEngine::entryForSize(m_info, size);
204 if (entry) {
205 const QIconDirInfo &dir = entry->dir;
206 if (dir.type == QIconDirInfo::Scalable) {
207 return size;
208 } else {
209 int result = qMin<int>(dir.size, qMin(size.width(), size.height()));
210 return QSize(result, result);
211 }
212 }
213 return QSize(0, 0);
214 }
215
216 QPixmap DBuiltinIconEngine::pixmap(const QSize &size, QIcon::Mode mode,
217 QIcon::State state)
218 {
219 ensureLoaded();
220
221 QIconLoaderEngineEntry *entry = QIconLoaderEngine::entryForSize(m_info, size);
222 if (entry)
223 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
224 return entry->pixmap(size, mode, state, devicePixelRatio(nullptr));
225 #else
226 return entry->pixmap(size, mode, state);
227 #endif
228
229 return QPixmap();
230 }
231
232 void DBuiltinIconEngine::paint(QPainter *painter, const QRect &rect,
233 QIcon::Mode mode, QIcon::State state)
234 {
235 ensureLoaded();
236
237 const qreal scale = devicePixelRatio(painter);
238 QSize pixmapSize = rect.size() * scale;
239
240 QIconLoaderEngineEntry *entry = QIconLoaderEngine::entryForSize(m_info, pixmapSize);
241 if (!entry)
242 return;
243
244 // 如果有 background 则绘制背景图先
245 QString bgFileName = entry->filename + QStringLiteral(".background");
246
247 if (QFile::exists(bgFileName)) {
248 QIcon(bgFileName).paint(painter, rect, Qt::AlignCenter, mode, state);
249 }
250
251 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
252 QPixmap pm = entry->pixmap(pixmapSize, mode, state, 1.0);
253 #else
254 QPixmap pm = entry->pixmap(pixmapSize, mode, state);
255 #endif
256 ImageEntry::Type type = static_cast<ImageEntry *>(entry)->type;
257 if (type == ImageEntry::TextType || (type == ImageEntry::ActionType && mode != QIcon::Normal)) {
258 QPainter pa(&pm);
259 pa.setCompositionMode(QPainter::CompositionMode_SourceIn);
260 pa.fillRect(pm.rect(), painter->pen().brush());
261 }
262
263 pm.setDevicePixelRatio(scale);
264 painter->drawPixmap(rect, pm);
265 }
266
267 QString DBuiltinIconEngine::key() const
268 {
269 return QLatin1String("DBuiltinIconEngine");
270 }
271
272 QIconEngine *DBuiltinIconEngine::clone() const
273 {
274 return new DBuiltinIconEngine(*this);
275 }
276
277
278 bool DBuiltinIconEngine::read(QDataStream &in)
279 {
280 // QDataStream不支持位数据, 此处先将内容转为正常类型
281 uint key = m_key;
282 bool followSystemTheme = m_followSystemTheme;
283 in >> m_iconName >> key >> followSystemTheme;
284 m_key = key;
285 m_followSystemTheme = followSystemTheme;
286 return true;
287 }
288
289
290 bool DBuiltinIconEngine::write(QDataStream &out) const
291 {
292 out << m_iconName << m_key << m_followSystemTheme;
293 return true;
294 }
295
296 QString DBuiltinIconEngine::iconName()
297 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
298 const
299 #endif
300 {
301 return m_iconName;
302 }
303
304 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
305 QList<QSize> DBuiltinIconEngine::availableSizes(QIcon::Mode mode, QIcon::State state)
306 {
307 ensureLoaded();
308
309 QList<QSize> sizes;
310 const int N = m_info.entries.size();
311 sizes.reserve(N);
312
313 // Gets all sizes from the DirectoryInfo entries
314 for (int i = 0; i < N; ++i) {
315 const auto& entry = m_info.entries.at(i);
316 int size = entry->dir.size;
317 sizes.append(QSize(size, size));
318 }
319
320 return sizes;
321 }
322 #endif
323
324 QThemeIconInfo DBuiltinIconEngine::loadIcon(const QString &iconName, uint key)
325 {
326 QThemeIconInfo info;
327 info.iconName = iconName;
328
329 QString theme_name = (key == DGuiApplicationHelper::DarkType ? "dark" : "light");
330 QStringList iconDirList {
331 QString("%1/%2/texts").arg(BUILTIN_ICON_PATH, theme_name),
332 QString("%1/%2/actions").arg(BUILTIN_ICON_PATH, theme_name),
333 QString("%1/%2/icons").arg(BUILTIN_ICON_PATH, theme_name),
334 QString("%1/texts").arg(BUILTIN_ICON_PATH),
335 QString("%1/actions").arg(BUILTIN_ICON_PATH),
336 QString("%1/icons").arg(BUILTIN_ICON_PATH)
337 };
338
339 QDir dir;
340 dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
341
342 for (int i = 0; i < iconDirList.count(); ++i) {
343 dir.setPath(iconDirList.at(i));
344
345 if (!dir.exists()) {
346 continue;
347 }
348
349 ImageEntry::Type type = static_cast<ImageEntry::Type>(i % 3);
350
351 for (const QFileInfo &icon_file_info : dir.entryInfoList()) {
352 const QString &file_name = icon_file_info.fileName();
353
354 // do not load background file
355 if (!file_name.startsWith(iconName) || file_name.endsWith(QStringLiteral(".background")))
356 continue;
357
358 // 先找到px所在位置
359 int size_str_pos = iconName.length() + 1;
360 int px_str_pos = file_name.indexOf("px.", size_str_pos + 1);
361
362 if (px_str_pos < 0)
363 continue;
364
365 bool ok = false;
366 int size = file_name.mid(size_str_pos, px_str_pos - size_str_pos).toInt(&ok);
367
368 if (Q_UNLIKELY(!ok || size <= 0)) {
369 continue;
370 }
371
372 ImageEntry *entry = icon_file_info.isDir() ? new DirImageEntry(type) : new ImageEntry(type);
373 entry->filename = icon_file_info.absoluteFilePath();
374 entry->dir.path = icon_file_info.absolutePath();
375 entry->dir.size = size;
376 entry->dir.type = icon_file_info.suffix().startsWith("svg") ? QIconDirInfo::Scalable : QIconDirInfo::Fixed;
377 #if QT_VERSION <= QT_VERSION_CHECK(6, 2, 4)
378 info.entries.append(entry);
379 #else
380 info.entries.push_back(std::unique_ptr<QIconLoaderEngineEntry>(entry));
381 #endif
382 }
383
384 // 已经找到图标时不再继续
385 if (info.entries.size() > 0) {
386 break;
387 }
388 }
389
390 return info;
391 }
392
393 bool DBuiltinIconEngine::hasIcon() const
394 {
395 return m_info.entries.size() > 0;
396 }
397
398 void DBuiltinIconEngine::virtual_hook(int id, void *data)
399 {
400 ensureLoaded();
401
402 switch (id) {
403 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
404 case QIconEngine::AvailableSizesHook:
405 {
406 QIconEngine::AvailableSizesArgument &arg
407 = *reinterpret_cast<QIconEngine::AvailableSizesArgument*>(data);
408 const int N = m_info.entries.size();
409 QList<QSize> sizes;
410 sizes.reserve(N);
411
412 // Gets all sizes from the DirectoryInfo entries
413 for (int i = 0; i < N; ++i) {
414 const QIconLoaderEngineEntry *entry = m_info.entries.at(i);
415 int size = entry->dir.size;
416 sizes.append(QSize(size, size));
417 }
418 arg.sizes.swap(sizes); // commit
419 }
420 break;
421 case QIconEngine::IconNameHook:
422 {
423 QString &name = *reinterpret_cast<QString*>(data);
424 name = m_info.iconName;
425 }
426 break;
427 #endif
428 case QIconEngine::IsNullHook:
429 {
430 *reinterpret_cast<bool*>(data) = !hasIcon();
431 }
432 break;
433 case QIconEngine::ScaledPixmapHook:
434 {
435 QIconEngine::ScaledPixmapArgument &arg = *reinterpret_cast<QIconEngine::ScaledPixmapArgument*>(data);
436 // QIcon::pixmap() multiplies size by the device pixel ratio.
437 const int integerScale = qCeil(arg.scale);
438 QIconLoaderEngineEntry *entry = QIconLoaderEngine::entryForSize(m_info, arg.size / integerScale, integerScale);
439 #if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
440 arg.pixmap = entry ? entry->pixmap(arg.size, arg.mode, arg.state, arg.scale) : QPixmap();
441 #else
442 arg.pixmap = entry ? entry->pixmap(arg.size, arg.mode, arg.state) : QPixmap();
443 #endif
444 }
445 break;
446 default:
447 QIconEngine::virtual_hook(id, data);
448 }
449 }
450
451 void DBuiltinIconEngine::ensureLoaded()
452 {
453 if (Q_LIKELY(m_followSystemTheme) && Q_UNLIKELY(DGuiApplicationHelper::instance()->themeType() != m_key)) {
454 m_initialized = false;
455 // 记录当前使用的主题类型
456 m_key = DGuiApplicationHelper::instance()->themeType();
457 }
458
459 if (Q_LIKELY(m_initialized)) {
460 return;
461 }
462 // 标记为已初始化
463 m_initialized = true;
464
465 #if QT_VERSION <= QT_VERSION_CHECK(6, 2, 4)
466 qDeleteAll(m_info.entries);
467 #endif
468 m_info.entries.clear();
469 m_info.iconName.clear();
470
471 Q_ASSERT(m_info.entries.size() == 0);
472 m_info = loadIcon(m_iconName, m_key);
473 }
474
475 DGUI_END_NAMESPACE