Debian Codegraph @

src/util/ddciicon.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 "ddciicon.h"
6 #include "dguiapplicationhelper.h"
7 #include "dicontheme.h"
8
9 #include <DObjectPrivate>
10 #include <DDciFile>
11 #include <DPlatformTheme>
12 #include <DSGApplication>
13 #include <private/qguiapplication_p.h>
14
15 #include <QPainter>
16 #include <QBuffer>
17 #include <QImageReader>
18 #include <QtMath>
19 #include <QDir>
20
21 DCORE_USE_NAMESPACE
22 DGUI_BEGIN_NAMESPACE
23
24 #define MODE_NORMAL "normal"
25 #define MODE_DISABLED "disabled"
26 #define MODE_HOVER "hover"
27 #define MODE_PRESSED "pressed"
28
29 #define THEME_LIGHT "light"
30 #define THEME_DARK "dark"
31 #define ALPHA8STRING "alpha8"
32
33 struct DDciIconEntry {
34 struct ScalableLayer {
35 int imagePixelRatio = 0;
36 struct Layer {
37 int prior = 0;
38 DDciIconPalette::PaletteRole role = DDciIconPalette::NoPalette;
39 QByteArray format;
40 QByteArray data;
41 bool isAlpha8Format = false;
42
43 qint8 hue = 0;
44 qint8 saturation = 0;
45 qint8 lightness = 0;
46 qint8 red = 0;
47 qint8 green = 0;
48 qint8 blue = 0;
49 qint8 alpha = 0;
50 qint16 padding = 0;
51 };
52 QVector<Layer> layers;
53 };
54
55
56 int iconSize = 0;
57 qint16 maxPaddings = 0;
58 DDciIcon::Mode mode = DDciIcon::Normal;
59 DDciIcon::Theme theme = DDciIcon::Light;
60 QVector<ScalableLayer> scalableLayers;
61 inline bool isNull() const { return scalableLayers.isEmpty(); }
62 };
63
64 struct EntryNode {
65 int iconSize = 0;
66 qint16 maxPaddings = 0;
67 QVector<DDciIconEntry *> entries;
68 };
69 using EntryNodeList = QVector<EntryNode>;
70
71 class EntryPropertyParser
72 {
73 public:
74 static void registerSteps();
75 static void doParse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties);
76 private:
77 static struct Step {
78 virtual ~Step() {}
79 Step *nextStep = nullptr;
80 virtual QVector<QStringView> parse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties) = 0;
81 } *root;
82
83 struct PriorStep : public Step {
84 QVector<QStringView> parse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties) override;
85 };
86
87 struct FormatAndAlpha8Step : public Step {
88 QVector<QStringView> parse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties) override;
89 };
90
91 struct PaddingStep : public Step {
92 QVector<QStringView> parse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties) override;
93 };
94
95 struct PaletteStep : public Step {
96 QVector<QStringView> parse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties) override;
97 };
98 };
99
100 EntryPropertyParser::Step *EntryPropertyParser::root = nullptr;
101
102 void EntryPropertyParser::registerSteps()
103 {
104 static PriorStep priorSt;
105 static FormatAndAlpha8Step formatSt;
106 static PaddingStep paddingSt;
107 static PaletteStep paletteSt;
108
109 priorSt.nextStep = &formatSt;
110 formatSt.nextStep = &paddingSt;
111 paddingSt.nextStep = &paletteSt;
112 paletteSt.nextStep = nullptr;
113 root = &priorSt;
114 }
115
116 void EntryPropertyParser::doParse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties)
117 {
118 Q_ASSERT(layer);
119 if (!root)
120 registerSteps();
121 EntryPropertyParser::Step *step = root;
122 QVector<QStringView> ps = properties;
123 while (step) {
124 // If the input information flow is empty, it means that the next steps do not need to be continued
125 if (ps.isEmpty())
126 break;
127 ps = step->parse(layer, ps);
128 step = step->nextStep;
129 }
130 }
131
132 QVector<QStringView> EntryPropertyParser::PriorStep::parse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties)
133 {
134 bool ok = false;
135 QVector<QStringView> ps = properties;
136 layer->prior = ps.takeFirst().toString().toInt(&ok);
137 if (!ok)
138 return {}; // error priority.
139 return ps;
140 }
141
142 QVector<QStringView> EntryPropertyParser::FormatAndAlpha8Step::parse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties)
143 {
144 QVector<QStringView> ps = properties;
145 const QString alpha8OrFormat = ps.takeLast().toString();
146 if (alpha8OrFormat.compare(ALPHA8STRING, Qt::CaseInsensitive) == 0) {
147 // Alpha8 format
148 layer->isAlpha8Format = true;
149 layer->format = ps.takeLast().toLatin1();
150 } else {
151 // normal format
152 layer->format = alpha8OrFormat.toLatin1();
153 }
154
155 return ps;
156 }
157
158 QVector<QStringView> EntryPropertyParser::PaddingStep::parse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties)
159 {
160 QVector<QStringView> ps = properties;
161 // Take the padding property
162 auto it = std::find_if(ps.cbegin(), ps.cend(), [](const QStringView &p) {
163 return p.endsWith(QLatin1Char('p'));
164 });
165
166 if (it != ps.cend()) {
167 layer->padding = it->left(it->length() - 1).toString().toShort();
168 ps.removeOne(*it);
169 }
170
171 return ps;
172 }
173
174 QVector<QStringView> EntryPropertyParser::PaletteStep::parse(DDciIconEntry::ScalableLayer::Layer *layer, const QVector<QStringView> &properties)
175 {
176 QVector<QStringView> ps = properties;
177 QStringView palettes = ps.takeFirst();
178 // `role_hue_saturation_lightness_red_green_blue_alpha` or `role`
179 if (palettes.toString().contains(QLatin1Char('_'))) {
180 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
181 // QVector is an alias for QList in Qt6
182 const QVector<QStringView> paletteProps = palettes.split(QLatin1Char('_'));
183 #elif QT_VERSION >= QT_VERSION_CHECK(5, 15, 2)
184 // QStringView::split() has been added in 5.12.2.
185 const QVector<QStringView> paletteProps = QVector<QStringView>::fromList(palettes.split(QLatin1Char('_')));
186 #else
187 QStringList strList = palettes.toString().split(QLatin1Char('_'));
188 QList<QStringView> viewList;
189 for (auto str : strList) {
190 viewList.append(QStringView(str));
191 }
192 const QVector<QStringView> paletteProps = QVector<QStringView>::fromList(viewList);
193 #endif
194 if (paletteProps.length() != 8)
195 return ps;
196
197 int role = paletteProps.at(0).toString().toInt();
198 if (role < DDciIconPalette::NoPalette || role > DDciIconPalette::PaletteCount)
199 role = DDciIconPalette::NoPalette;
200
201 layer->role = DDciIconPalette::PaletteRole(role);
202 layer->hue = static_cast<qint8>(paletteProps.at(1).toString().toShort());
203 layer->saturation = static_cast<qint8>(paletteProps.at(2).toString().toShort());
204 layer->lightness = static_cast<qint8>(paletteProps.at(3).toString().toShort());
205 layer->red = static_cast<qint8>(paletteProps.at(4).toString().toShort());
206 layer->green = static_cast<qint8>(paletteProps.at(5).toString().toShort());
207 layer->blue = static_cast<qint8>(paletteProps.at(6).toString().toShort());
208 layer->alpha = static_cast<qint8>(paletteProps.at(7).toString().toShort());
209 } else {
210 // only palette
211 int role = palettes.toString().toInt();
212 if (role < DDciIconPalette::NoPalette || role > DDciIconPalette::PaletteCount)
213 role = DDciIconPalette::NoPalette;
214 layer->role = DDciIconPalette::PaletteRole(role);
215 }
216
217 return ps;
218 }
219
220 void alpha8ImageDeleter(void *image) {
221 delete static_cast<QImage *>(image);
222 }
223
224 static QImage readImageData(QImageReader &reader, qreal pixmapScale, bool isAlpha8Format)
225 {
226 QImage image;
227
228 if (reader.canRead()) {
229 bool scaled = false;
230 int imageSize = qMax(reader.size().width(), reader.size().height());
231 int scaledSize = qRound(pixmapScale * imageSize);
232 if (!isAlpha8Format && reader.supportsOption(QImageIOHandler::ScaledSize)) {
233 reader.setScaledSize(reader.size().scaled(scaledSize, scaledSize, Qt::KeepAspectRatio));
234 scaled = true;
235 }
236
237 QImage *imagePtr = &image;
238 if (isAlpha8Format)
239 imagePtr = new QImage();
240 reader.read(imagePtr);
241 if (isAlpha8Format) {
242 QImage tt(imagePtr->bits(), imagePtr->width(), imagePtr->width(), imagePtr->bytesPerLine(),
243 QImage::Format_Alpha8, alpha8ImageDeleter, static_cast<void *>(imagePtr));
244 return tt.scaled(scaledSize, scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
245 }
246
247 if (!scaled)
248 image = image.scaled(scaledSize, scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
249 } else {
250 qWarning() << reader.errorString() << reader.format();
251 }
252
253 return image;
254 }
255
256 class DDciIconImagePrivate
257 {
258 public:
259 DDciIconImagePrivate(const DDciIconImagePrivate &other)
260 : imageSize(other.imageSize)
261 , devicePixelRatio(other.devicePixelRatio)
262 , imageScale(other.imageScale)
263 , layers(other.layers)
264 {
265
266 }
267 DDciIconImagePrivate(qreal imageSize, qreal devicePixelRatio, qreal imageScale,
268 const DDciIconEntry::ScalableLayer &sLayer)
269 : imageSize(imageSize)
270 , devicePixelRatio(devicePixelRatio)
271 , imageScale(imageScale)
272 , layers(sLayer.layers)
273 {
274 }
275
276 void init();
277
278 inline bool loaded() const {
279 return layers.size() == readers.size();
280 }
281
282 inline void ensureLoad() {
283 if (loaded())
284 return;
285 init();
286 }
287
288 const qreal imageSize;
289 const qreal devicePixelRatio;
290 const qreal imageScale;
291
292 const QVector<DDciIconEntry::ScalableLayer::Layer> layers;
293
294 struct ReaderData {
295 ReaderData() {}
296 ~ReaderData() {}
297 ReaderData(const ReaderData &other)
298 : index(other.index)
299 , buffer(nullptr)
300 , reader(nullptr)
301 , pastImageDelay(other.pastImageDelay)
302 , currentImage(other.currentImage)
303 , currentImageIsValid(other.currentImageIsValid)
304 , m_currentImageEndTime(other.m_currentImageEndTime)
305 {}
306 ReaderData(ReaderData &&other) {
307 index = std::move(other.index);
308 buffer.swap(other.buffer);
309 reader.swap(other.reader);
310 pastImageDelay = std::move(other.pastImageDelay);
311 currentImage.swap(other.currentImage);
312 currentImageIsValid = std::move(other.currentImageIsValid);
313 m_currentImageEndTime = std::move(other.m_currentImageEndTime);
314 }
315
316 qsizetype index = 0;
317 std::unique_ptr<QBuffer> buffer;
318 std::unique_ptr<QImageReader> reader;
319 int pastImageDelay = 0;
320 QImage currentImage;
321 bool currentImageIsValid = false;
322 int m_currentImageEndTime = 0;
323
324 inline void initCurrentImage(const DDciIconImagePrivate *d) {
325 if (currentImageIsValid)
326 return;
327 // Ensure can get a valid QImageReader::nextImageDelay(), Because
328 // using QImageReader::nextImageDelay() needs call QImageReader::read() before.
329 currentImage = readImageData(*reader, d->imageScale, d->layers.at(index).isAlpha8Format);
330 currentImageIsValid = true;
331 m_currentImageEndTime = pastImageDelay + reader->nextImageDelay();
332 }
333 inline bool jumpToNextImage(DDciIconImagePrivate *d) {
334 Q_ASSERT(reader->supportsAnimation());
335 pastImageDelay += reader->nextImageDelay();
336 ++d->pastImageCount;
337 if (!reader->canRead())
338 return false;
339 currentImage = QImage();
340 currentImageIsValid = false;
341 initCurrentImage(d);
342 return true;
343 }
344 inline int currentImageEndTime() const {
345 Q_ASSERT(currentImageIsValid);
346 return m_currentImageEndTime;
347 }
348 inline bool currentImageIsEnd(const DDciIconImagePrivate *d) const {
349 return d->currentPastImageDelay > 0 && d->currentPastImageDelay >= currentImageEndTime();
350 }
351 };
352
353 QVector<ReaderData *> readers;
354 bool supportsAnimation = false;
355 int totalMaxImageCount = 0;
356 int maxLoopCount = -2;
357
358 ReaderData *readAnimationNextData();
359
360 ReaderData *animation = nullptr;
361 int currentImageNumber = 0;
362 int pastImageCount = 0;
363 int currentPastImageDelay = 0;
364 };
365
366 class DDciIconPrivate : public QSharedData
367 {
368 public:
369 DDciIconPrivate()
370 : dciFile(nullptr)
371 {
372 }
373
374 DDciIconPrivate(const DDciIconPrivate &other)
375 : QSharedData(other)
376 , dciFile(other.dciFile)
377 {
378 }
379
380 ~DDciIconPrivate();
381
382 DDciIconEntry *loadIcon(const QString &parentDir, const QString &imageDir);
383 void loadIconList();
384 void ensureLoaded();
385
386 DDciIconEntry *tryMatchIcon(int iconSize, DDciIcon::Theme theme, DDciIcon::Mode mode, DDciIcon::IconMatchedFlags flags = DDciIcon::None) const;
387 static void paint(QPainter *painter, const QRectF &rect, Qt::Alignment alignment,
388 const QVector<DDciIconEntry::ScalableLayer::Layer> &layers,
389 QVector<DDciIconImagePrivate::ReaderData *> *layerReaders,
390 const DDciIconPalette &palette, qreal pixmapScale);
391 static void paint(QPainter *painter, const QRect &rect, qreal devicePixelRatio, Qt::Alignment alignment,
392 const DDciIconEntry *entry, const DDciIconPalette &palette, qreal pixmapScale);
393 inline static bool hasPalette(const QVector<DDciIconEntry::ScalableLayer::Layer> &layers) {
394 return std::any_of(layers.cbegin(), layers.cend(),
395 [](const DDciIconEntry::ScalableLayer::Layer &layer) {
396 return layer.role != DDciIconPalette::NoPalette;
397 });
398 }
399 bool hasPalette(DDciIconMatchResult result) const;
400 static inline bool entryIsValid(const DDciIconEntry *entry) {
401 return entry && !entry->isNull();
402 }
403
404 QSharedPointer<const DDciFile> dciFile;
405 EntryNodeList icons;
406 };
407
408 // In Qt 6, registration of comparators, and QDebug and QDataStream streaming operators is
409 // done automatically. Consequently, \c QMetaType::registerEqualsComparator(),
410 // \c QMetaType::registerComparators(), \c qRegisterMetaTypeStreamOperators() and
411 // \c QMetaType::registerDebugStreamOperator() do no longer exist. Calls to those methods
412 // have to be removed when porting to Qt 6.
413 #if !defined(QT_NO_DATASTREAM) && (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
414 __attribute__((constructor))
415 static void registerMetaType()
416 {
417 qRegisterMetaTypeStreamOperators<DDciIcon>("DDciIcon");
418 }
419 #endif
420
421 static inline bool toMode(const QStringView &name, DDciIcon::Mode *mode) {
422 if (name == QLatin1String(MODE_NORMAL)) {
423 *mode = DDciIcon::Normal;
424 return true;
425 }
426
427 if (name == QLatin1String(MODE_DISABLED)) {
428 *mode = DDciIcon::Disabled;
429 return true;
430 }
431
432 if (name == QLatin1String(MODE_HOVER)) {
433 *mode = DDciIcon::Hover;
434 return true;
435 }
436
437 if (name == QLatin1String(MODE_PRESSED)) {
438 *mode = DDciIcon::Pressed;
439 return true;
440 }
441
442 return false;
443 }
444
445 static inline bool toTheme(const QStringView &name, DDciIcon::Theme *theme) {
446 if (name == QLatin1String(THEME_LIGHT)) {
447 *theme = DDciIcon::Light;
448 return true;
449 }
450
451 if (name == QLatin1String(THEME_DARK)) {
452 *theme = DDciIcon::Dark;
453 return true;
454 }
455
456 return false;
457 }
458
459 // DCI 内部目录使用 '/' 作为路径分隔符
460 static inline QString joinPath(const QString &s1, const QString &s2) {
461 return s1 + QLatin1Char('/') + s2;
462 }
463
464 static QImage readImageData(const QByteArray &data, const QByteArray &format, qreal pixmapScale, bool isAlpha8Format)
465 {
466 if (data.isEmpty())
467 return QImage();
468
469 QBuffer rawDataBuffer;
470 rawDataBuffer.setData(data);
471 rawDataBuffer.open(QBuffer::ReadOnly);
472
473 QImageReader reader(&rawDataBuffer);
474 if (!format.isEmpty())
475 reader.setFormat(format);
476
477 return readImageData(reader, pixmapScale, isAlpha8Format);
478 }
479
480 static int findIconsByLowerBoundSize(const EntryNodeList &list, const int size, bool regardPaddingsAsSize)
481 {
482 const auto compFun1 = [] (const EntryNode &n1, const EntryNode &n2) {
483 return n1.iconSize < n2.iconSize;
484 };
485 const auto compFun2 = [] (const EntryNode &n1, const EntryNode &n2) {
486 return n1.iconSize + n1.maxPaddings < n2.iconSize + n2.maxPaddings;
487 };
488 EntryNode target;
489 target.iconSize = size;
490 target.maxPaddings = 0;
491 auto neighbor = std::lower_bound(list.cbegin(), list.cend(), target,
492 regardPaddingsAsSize ? compFun2 : compFun1);
493
494 if (neighbor != list.cend())
495 return static_cast<int>(neighbor - list.constBegin());
496 return -1;
497 }
498
499 static QRectF alignedRect(Qt::LayoutDirection direction, Qt::Alignment alignment, const QSizeF &size, const QRectF &rect)
500 {
501 alignment = QGuiApplicationPrivate::visualAlignment(direction, alignment);
502 qreal x = rect.x();
503 qreal y = rect.y();
504 qreal w = size.width();
505 qreal h = size.height();
506 if ((alignment & Qt::AlignVCenter) == Qt::AlignVCenter)
507 y += rect.size().height()/2 - h/2;
508 else if ((alignment & Qt::AlignBottom) == Qt::AlignBottom)
509 y += rect.size().height() - h;
510 if ((alignment & Qt::AlignRight) == Qt::AlignRight)
511 x += rect.size().width() - w;
512 else if ((alignment & Qt::AlignHCenter) == Qt::AlignHCenter)
513 x += rect.size().width()/2 - w/2;
514
515 return QRectF(x, y, w, h);
516 }
517
518 DDciIconPrivate::~DDciIconPrivate()
519 {
520 for (auto icon : icons)
521 qDeleteAll(icon.entries);
522 }
523
524 // Note that QStringView is a non-owning, read-only view of a QString
525 // so we need to make sure that the original QString object stays alive
526 // for as long as we're using the QStringView.
527 static inline QVector<QStringView> fromQStringList(const QStringList &list)
528 {
529 QVector<QStringView> views;
530 views.reserve(list.size());
531 std::copy(list.begin(), list.end(), std::back_inserter(views));
532
533 return views;
534 }
535
536 DDciIconEntry *DDciIconPrivate::loadIcon(const QString &parentDir, const QString &imageDir)
537 {
538 // Mode-Theme
539 auto props = imageDir.split(QLatin1Char('.'));
540 const QVector<QStringView> &iconProps = fromQStringList(props);
541 if (iconProps.count() != 2) // Error file name.
542 return nullptr;
543
544 DDciIcon::Mode mode;
545 DDciIcon::Theme theme;
546 if (!toMode(iconProps[0], &mode))
547 return nullptr;
548 if (!toTheme(iconProps[1], &theme))
549 return nullptr;
550
551 DDciIconEntry *icon = new DDciIconEntry();
552 icon->mode = mode;
553 icon->theme = theme;
554 const QString &stateDir = joinPath(parentDir, imageDir);
555 for (const QString &scaleString : dciFile->list(stateDir, true)) {
556 bool ok = false;
557 int scale = scaleString.toInt(&ok);
558 // No restrictions on icons with scale ratio greater than 3.
559 if (!ok)
560 continue;
561 DDciIconEntry::ScalableLayer scaleIcon;
562 scaleIcon.imagePixelRatio = scale;
563 const QString &path = joinPath(stateDir, scaleString);
564 for (const QString &layerPath : dciFile->list(path, true)) {
565 props = layerPath.split(QLatin1Char('.'));
566 const QVector<QStringView> &layerProps = fromQStringList(props);
567 DDciIconEntry::ScalableLayer::Layer layer;
568 EntryPropertyParser::doParse(&layer, layerProps);
569 layer.data = dciFile->dataRef(joinPath(path, layerPath));
570 // The sequence number starts with 1, convert it into index.
571 scaleIcon.layers.insert(layer.prior - 1, layer);
572 icon->maxPaddings = qMax(icon->maxPaddings, layer.padding);
573 }
574 icon->scalableLayers.append(scaleIcon);
575 }
576
577 return icon;
578 }
579
580 void DDciIconPrivate::loadIconList()
581 {
582 const QStringList &listOfSize = dciFile->list(QLatin1String("/"), true);
583 for (const QString &dir : listOfSize) {
584 bool ok = false;
585 int size = dir.toInt(&ok);
586 if (!ok)
587 continue;
588
589 EntryNode node;
590 node.iconSize = size;
591 node.maxPaddings = 0;
592 const QString &dirPath = joinPath(QLatin1String(), dir);
593 for (const QString &imageDir : dciFile->list(dirPath, true)) {
594 auto icon = loadIcon(dirPath, imageDir);
595 if (!icon || icon->isNull())
596 continue;
597 icon->iconSize = size;
598 node.entries << icon;
599 node.maxPaddings = qMax(node.maxPaddings, icon->maxPaddings);
600 }
601 if (node.entries.isEmpty())
602 continue;
603 icons << std::move(node);
604 }
605 }
606
607 void DDciIconPrivate::ensureLoaded()
608 {
609 // TODO: Modified to resemble the addFile function in QIcon.
610 if (!dciFile->isValid())
611 return;
612 loadIconList();
613 }
614
615 DDciIconEntry *DDciIconPrivate::tryMatchIcon(int iconSize, DDciIcon::Theme theme, DDciIcon::Mode mode, DDciIcon::IconMatchedFlags flags) const
616 {
617 if (icons.isEmpty())
618 return nullptr;
619
620 auto neighborIndex = findIconsByLowerBoundSize(icons, iconSize, flags & DDciIcon::RegardPaddingsAsSize);
621 if (neighborIndex < 0) {
622 neighborIndex = static_cast<int>(icons.size() - 1);
623 }
624
625 const auto &listOfSize = icons.at(neighborIndex);
626
627 QVector<qint8> iconWeight;
628 iconWeight.resize(listOfSize.entries.size());
629 for (int i = 0; i < listOfSize.entries.size(); ++i) {
630 qint8 weight = 0;
631 const DDciIconEntry *icon = listOfSize.entries.at(i);
632
633 if (icon->mode == mode) {
634 weight += 2;
635 } else if (flags.testFlag(DDciIcon::DontFallbackMode)
636 || icon->mode != DDciIcon::Normal) {
637 weight = -1;
638 continue;
639 }
640 if (icon->theme == theme) {
641 weight += 1;
642 } else {
643 weight = -1;
644 continue;
645 }
646
647 iconWeight[i] = weight;
648 }
649
650 const auto targetIcon = std::max_element(iconWeight.constBegin(), iconWeight.constEnd());
651 if (targetIcon != iconWeight.constEnd() && *targetIcon > 0)
652 return listOfSize.entries.at(targetIcon - iconWeight.constBegin());
653 return nullptr;
654 }
655
656 static const DDciIconEntry::ScalableLayer &findScalableLayer(const DDciIconEntry *entry, qreal devicePixelRatio)
657 {
658 const DDciIconEntry::ScalableLayer *maxLayer = nullptr;
659 const int imagePixelRatio = qCeil(devicePixelRatio);
660
661 for (const auto &i : qAsConst(entry->scalableLayers)) {
662 if (!maxLayer || i.imagePixelRatio > maxLayer->imagePixelRatio)
663 maxLayer = &i;
664 if (i.imagePixelRatio > imagePixelRatio)
665 return i;
666 }
667
668 Q_ASSERT(maxLayer);
669 return *maxLayer;
670 }
671
672 void DDciIconPrivate::paint(QPainter *painter, const QRectF &rect, Qt::Alignment alignment,
673 const QVector<DDciIconEntry::ScalableLayer::Layer> &layers,
674 QVector<DDciIconImagePrivate::ReaderData *> *layerReaders,
675 const DDciIconPalette &palette, qreal pixmapScale)
676 {
677 const bool useImageReader = layerReaders && !layerReaders->isEmpty();
678 Q_ASSERT(!useImageReader || layerReaders->size() == layers.size());
679 for (auto layerIter = layers.begin(); layerIter != layers.end(); ++layerIter) {
680 QImage layer;
681 if (useImageReader) {
682 const qsizetype index = layerIter - layers.begin();
683 auto &reader = layerReaders->operator [](index);
684 if (reader->currentImageIsValid) {
685 layer = reader->currentImage;
686 } else {
687 layer = readImageData(*reader->reader, pixmapScale, layerIter->isAlpha8Format);
688 reader->currentImage = layer;
689 reader->currentImageIsValid = true;
690 }
691 } else {
692 if (layerIter->data.isEmpty())
693 continue;
694 layer = readImageData(layerIter->data, layerIter->format, pixmapScale, layerIter->isAlpha8Format);
695 }
696
697 if (layer.isNull())
698 continue;
699 QColor fillColor;
700 switch (layerIter->role) {
701 case DDciIconPalette::Foreground:
702 fillColor = palette.foreground();
703 break;
704 case DDciIconPalette::Background:
705 fillColor = palette.background();
706 break;
707 case DDciIconPalette::HighlightForeground:
708 fillColor = palette.highlightForeground();
709 break;
710 case DDciIconPalette::Highlight:
711 fillColor = palette.highlight();
712 break;
713 default:
714 break;
715 }
716
717 // ###(Chen Bin) Can't compose image when this image's format is Format_Alpha8.
718 if (layer.format() == QImage::Format_Alpha8)
719 layer = layer.convertToFormat(QImage::Format_ARGB32_Premultiplied);
720
721 if (fillColor.isValid()) {
722 QPainter render(&layer);
723 fillColor = DGuiApplicationHelper::adjustColor(fillColor, layerIter->hue, layerIter->saturation,
724 layerIter->lightness, layerIter->red, layerIter->green,
725 layerIter->blue, layerIter->alpha);
726 render.setCompositionMode(QPainter::CompositionMode_SourceIn);
727 render.fillRect(layer.rect(), fillColor);
728 }
729
730 QRectF targetRect =alignedRect(painter->layoutDirection(), alignment, layer.size(), rect);
731 if (rect.width() < targetRect.width())
732 targetRect = rect;
733
734 painter->drawImage(targetRect, layer);
735 }
736 }
737
738 void DDciIconPrivate::paint(QPainter *painter, const QRect &rect, qreal devicePixelRatio, Qt::Alignment alignment,
739 const DDciIconEntry *entry, const DDciIconPalette &palette, qreal pixmapScale)
740 {
741 qreal pixelRatio = devicePixelRatio;
742 bool useHighDpiPixmaps =
743 #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
744 true;
745 #else
746 qApp->testAttribute(Qt::AA_UseHighDpiPixmaps);
747 #endif
748 if (pixelRatio <= 0 && painter->device() && useHighDpiPixmaps)
749 pixelRatio = painter->device()->devicePixelRatio();
750 if (pixelRatio <= 0)
751 pixelRatio = 1.0;
752
753 auto scalableLayer = findScalableLayer(entry, devicePixelRatio);
754 paint(painter, rect, alignment, scalableLayer.layers, nullptr, palette, pixelRatio * pixmapScale / scalableLayer.imagePixelRatio);
755 }
756
757 bool DDciIconPrivate::hasPalette(DDciIconMatchResult result) const
758 {
759 auto entry = static_cast<const DDciIconEntry *>(result);
760 if (!entryIsValid(entry))
761 return false;
762 if (entry->scalableLayers.isEmpty())
763 return false;
764 auto scaledLayer = entry->scalableLayers.first();
765 return hasPalette(scaledLayer.layers);
766 }
767
768 DDciIcon::DDciIcon()
769 : d(new DDciIconPrivate())
770 {
771
772 }
773
774 DDciIcon::DDciIcon(const DDciFile *dciFile)
775 : DDciIcon()
776 {
777 d->dciFile.reset(dciFile);
778 d->ensureLoaded();
779 }
780
781 DDciIcon::DDciIcon(const QString &fileName)
782 : DDciIcon()
783 {
784 d->dciFile.reset(new DDciFile(fileName));
785 d->ensureLoaded();
786 }
787
788 DDciIcon::DDciIcon(const QByteArray &data)
789 : DDciIcon()
790 {
791 d->dciFile.reset(new DDciFile(data));
792 d->ensureLoaded();
793 }
794
795 DDciIcon::DDciIcon(const DDciIcon &other)
796 : d(other.d)
797 { }
798
799 DDciIcon &DDciIcon::operator=(const DDciIcon &other) noexcept
800 {
801 d = other.d;
802 return *this;
803 }
804
805 DDciIcon::~DDciIcon() {}
806
807 DDciIcon::DDciIcon(DDciIcon &&other) noexcept
808 : d(other.d)
809 { other.d = nullptr; }
810
811 DDciIcon &DDciIcon::operator=(DDciIcon &&other) noexcept
812 { swap(other); return *this; }
813
814 bool DDciIcon::isNull() const
815 {
816 return d->icons.isEmpty();
817 }
818
819 DDciIconMatchResult DDciIcon::matchIcon(int size, Theme theme, Mode mode, IconMatchedFlags flags) const
820 {
821 return d->tryMatchIcon(size, theme, mode, flags);
822 }
823
824 int DDciIcon::actualSize(DDciIconMatchResult result) const
825 {
826 auto entry = static_cast<const DDciIconEntry *>(result);
827 if (!d->entryIsValid(entry))
828 return -1;
829 return entry->iconSize;
830 }
831
832 int DDciIcon::actualSize(int size, DDciIcon::Theme theme, DDciIcon::Mode mode) const
833 {
834 auto entry = d->tryMatchIcon(size, theme, mode);
835 return actualSize(entry);
836 }
837
838 QList<int> DDciIcon::availableSizes(DDciIcon::Theme theme, DDciIcon::Mode mode) const
839 {
840 if (d->icons.isEmpty())
841 return {};
842 QList<int> sizes;
843 std::for_each(d->icons.begin(), d->icons.end(), [theme, mode, &sizes](const EntryNode &node) {
844 auto it = std::find_if(node.entries.begin(), node.entries.end(), [theme, mode](const DDciIconEntry *entry) {
845 if (entry->mode == mode && entry->theme == theme)
846 return true;
847 return false;
848 });
849 if (it != node.entries.end())
850 sizes.append((*it)->iconSize);
851 });
852 return sizes;
853 }
854
855 bool DDciIcon::isSupportedAttribute(DDciIconMatchResult result, IconAttribute attr) const
856 {
857 switch (attr) {
858 case HasPalette:
859 return d->hasPalette(result);
860 default:
861 break;
862 }
863
864 return false;
865 }
866
867 bool DDciIcon::isSupportedAttribute(const DDciIconImage &image, IconAttribute attr)
868 {
869 if (image.isNull())
870 return false;
871
872 switch (attr) {
873 case HasPalette:
874 return DDciIconPrivate::hasPalette(image.d->layers);
875 default:
876 break;
877 }
878
879 return false;
880 }
881
882 QPixmap DDciIcon::pixmap(qreal devicePixelRatio, int iconSize, DDciIcon::Theme theme, DDciIcon::Mode mode, const DDciIconPalette &palette) const
883 {
884 auto entry = d->tryMatchIcon(iconSize, theme, mode);
885 return pixmap(devicePixelRatio, iconSize, entry, palette);
886 }
887
888 QPixmap DDciIcon::pixmap(qreal devicePixelRatio, int iconSize, DDciIconMatchResult result, const DDciIconPalette &palette) const
889 {
890 auto image = this->image(result, iconSize, devicePixelRatio);
891 if (image.isNull())
892 return QPixmap();
893 return QPixmap::fromImage(image.toImage(palette));
894 }
895
896 void DDciIcon::paint(QPainter *painter, const QRect &rect, qreal devicePixelRatio, DDciIcon::Theme theme, DDciIcon::Mode mode,
897 Qt::Alignment alignment, const DDciIconPalette &palette) const
898 {
899 int canvarsSize = qMax(rect.width(), rect.height());
900 auto entry = d->tryMatchIcon(canvarsSize, theme, mode, RegardPaddingsAsSize);
901 return paint(painter, rect, devicePixelRatio, entry, alignment, palette);
902 }
903
904 void DDciIcon::paint(QPainter *painter, const QRect &rect, qreal devicePixelRatio, DDciIconMatchResult result, Qt::Alignment alignment, const DDciIconPalette &palette) const
905 {
906 auto entry = static_cast<const DDciIconEntry *>(result);
907 if (!d->entryIsValid(entry))
908 return;
909 qreal canvarsSize = qMax(rect.width(), rect.height());
910 const qreal pixmapScale = canvarsSize / (entry->iconSize + entry->maxPaddings * 2);
911 d->paint(painter, rect, devicePixelRatio, alignment, entry, palette, pixmapScale);
912 }
913
914 DDciIconImage DDciIcon::image(DDciIconMatchResult result, int size, qreal devicePixelRatio) const
915 {
916 auto entry = static_cast<DDciIconEntry*>(result);
917 if (!d->entryIsValid(entry))
918 return DDciIconImage();
919
920 auto scalableLayer = findScalableLayer(entry, devicePixelRatio);
921 int iconSize = size;
922 if (iconSize <= 0)
923 iconSize = entry->iconSize;
924 Q_ASSERT_X((iconSize > 0), "DDciIcon::generatePixmap", "You must specify the icon size.");
925 const qreal pixmapScale = qreal(iconSize) / entry->iconSize;
926 const qreal imageSize = (entry->maxPaddings * 2 + entry->iconSize) * pixmapScale;
927 const qreal imageScale = pixmapScale * devicePixelRatio / scalableLayer.imagePixelRatio;
928
929 auto image = QSharedPointer<DDciIconImagePrivate>(new DDciIconImagePrivate(imageSize, devicePixelRatio, imageScale, scalableLayer));
930
931 return DDciIconImage(image);
932 }
933
934 DDciIcon DDciIcon::fromTheme(const QString &name)
935 {
936 if (QDir::isAbsolutePath(name))
937 return DDciIcon(name);
938
939 DDciIcon icon;
940
941 QString iconName = name;
942 // FIX uengine appname is empty, will cause qt_assert
943 if (!QCoreApplication::applicationName().isEmpty() && !DSGApplication::id().isEmpty()) {
944 // allow the icon theme to override the icon for a given application
945 iconName.prepend(DSGApplication::id() + "/");
946 }
947
948 QString iconPath;
949 QString iconThemeName =DGuiApplicationHelper::instance()->applicationTheme()->iconThemeName();
950 if (auto cached = DIconTheme::cached()) {
951 iconPath = cached->findDciIconFile(iconName, iconThemeName);
952 } else {
953 iconPath = DIconTheme::findDciIconFile(iconName, iconThemeName);
954 }
955
956 if (!iconPath.isEmpty())
957 icon = DDciIcon(iconPath);
958
959 return icon;
960 }
961
962 DDciIcon DDciIcon::fromTheme(const QString &name, const DDciIcon &fallback)
963 {
964 DDciIcon icon = fromTheme(name);
965
966 if (icon.isNull() || icon.availableSizes(Light).isEmpty() || icon.availableSizes(Dark).isEmpty())
967 return fallback;
968
969 return icon;
970 }
971
972 #ifndef QT_NO_DATASTREAM
973 QDataStream &operator<<(QDataStream &s, const DDciIcon &icon)
974 {
975 if (icon.isNull())
976 return s << QByteArray();
977 auto dciFile = icon.d->dciFile;
978 const QByteArray &data = dciFile->toData();
979 s << data;
980 return s;
981 }
982
983 QDataStream &operator>>(QDataStream &s, DDciIcon &icon)
984 {
985 QByteArray data;
986 s >> data;
987 icon = DDciIcon(data);
988 return s;
989 }
990
991 DDciIconImage::DDciIconImage(const DDciIconImage &other)
992 : d(other.d)
993 {
994
995 }
996
997 DDciIconImage &DDciIconImage::operator=(const DDciIconImage &other) noexcept
998 {
999 d = other.d;
1000 return *this;
1001 }
1002
1003 DDciIconImage::~DDciIconImage()
1004 {
1005 reset();
1006 }
1007
1008 DDciIconImage::DDciIconImage(DDciIconImage &&other) noexcept
1009 : d(other.d)
1010 {
1011
1012 }
1013
1014 DDciIconImage &DDciIconImage::operator=(DDciIconImage &&other) noexcept
1015 {
1016 swap(other);
1017 return *this;
1018 }
1019
1020 void DDciIconImage::reset()
1021 {
1022 if (!d)
1023 return;
1024
1025 qDeleteAll(d->readers);
1026 d->readers.clear();
1027 d->supportsAnimation = false;
1028 d->totalMaxImageCount = 0;
1029 d->maxLoopCount = -2;
1030 d->animation = nullptr;
1031 d->currentImageNumber = 0;
1032 d->pastImageCount = 0;
1033 d->currentPastImageDelay = 0;
1034 }
1035
1036 QImage DDciIconImage::toImage(const DDciIconPalette &palette) const
1037 {
1038 const int imageSize = qRound(d->imageSize * d->devicePixelRatio);
1039 QImage image(imageSize, imageSize, QImage::Format_ARGB32_Premultiplied);
1040 image.fill(Qt::transparent);
1041 QPainter painter(&image);
1042 painter.setRenderHint(QPainter::SmoothPixmapTransform);
1043 paint(&painter, image.rect(), Qt::AlignCenter, palette);
1044
1045 image.setDevicePixelRatio(d->devicePixelRatio);
1046 return image;
1047 }
1048
1049 void DDciIconImage::paint(QPainter *painter, const QRectF &rect, Qt::Alignment alignment, const DDciIconPalette &palette) const
1050 {
1051 DDciIconPrivate::paint(painter, rect, alignment, d->layers, &d->readers, palette, d->imageScale);
1052 }
1053
1054 bool DDciIconImage::hasPalette() const
1055 {
1056 return DDciIcon::isSupportedAttribute(*this, DDciIcon::HasPalette);
1057 }
1058
1059 bool DDciIconImage::supportsAnimation() const
1060 {
1061 if (!d)
1062 return false;
1063 d->ensureLoad();
1064 return d->supportsAnimation;
1065 }
1066
1067 bool DDciIconImage::atBegin() const
1068 {
1069 return d && d->pastImageCount == 0;
1070 }
1071
1072 bool DDciIconImage::atEnd() const
1073 {
1074 return d && d->supportsAnimation && d->pastImageCount >= d->totalMaxImageCount - 1;
1075 }
1076
1077 bool DDciIconImage::jumpToNextImage()
1078 {
1079 d->ensureLoad();
1080 if (!d->animation)
1081 return false;
1082
1083 // Jump to next frame for current animation image
1084 d->animation->jumpToNextImage(d.get());
1085 d->currentPastImageDelay = d->animation->pastImageDelay;
1086 d->animation = d->readAnimationNextData();
1087
1088 if (d->animation) {
1089 ++d->currentImageNumber;
1090
1091 // Clear old images if icon animation is not last frame
1092 for (auto &reader : d->readers) {
1093 if (reader->currentImageIsEnd(d.get()))
1094 reader->currentImage = QImage();
1095 }
1096 }
1097
1098 return d->animation;
1099 }
1100
1101 int DDciIconImage::loopCount() const
1102 {
1103 if (!d)
1104 return 0;
1105 d->ensureLoad();
1106 return d->maxLoopCount;
1107 }
1108
1109 int DDciIconImage::maxImageCount() const
1110 {
1111 if (!d)
1112 return 0;
1113
1114 d->ensureLoad();
1115 if (!d->supportsAnimation)
1116 return 0;
1117
1118 return d->totalMaxImageCount;
1119 }
1120
1121 int DDciIconImage::currentImageDuration() const
1122 {
1123 if (!d)
1124 return -1;
1125 d->ensureLoad();
1126 if (!d->animation)
1127 return -1;
1128 return d->animation->pastImageDelay + d->animation->reader->nextImageDelay()
1129 - d->currentPastImageDelay;
1130 }
1131
1132 int DDciIconImage::currentImageNumber() const
1133 {
1134 return d ? d->currentImageNumber : -1;
1135 }
1136
1137 void DDciIconImagePrivate::init()
1138 {
1139 readers.reserve(layers.size());
1140 for (const auto &layer : qAsConst(layers)) {
1141 ReaderData *data = new ReaderData;
1142 Q_ASSERT(data);
1143 auto buffer = new QBuffer();
1144 data->buffer.reset(buffer);
1145 auto reader = new QImageReader();
1146 data->reader.reset(reader);
1147 readers.append(data);
1148 data->index = readers.size() - 1;
1149
1150 buffer->setData(layer.data);
1151 buffer->open(QIODevice::ReadOnly);
1152 Q_ASSERT(buffer->isOpen());
1153 reader->setDevice(buffer);
1154 reader->setFormat(layer.format);
1155
1156 if (reader->supportsAnimation()) {
1157 supportsAnimation = true;
1158 totalMaxImageCount += reader->imageCount();
1159 maxLoopCount = qMax(maxLoopCount, reader->loopCount());
1160 }
1161 }
1162
1163 if (supportsAnimation)
1164 animation = readAnimationNextData();
1165 }
1166
1167 DDciIconImagePrivate::ReaderData *DDciIconImagePrivate::readAnimationNextData()
1168 {
1169 const ReaderData *next = nullptr;
1170
1171 for (auto &reader : readers) {
1172 if (!reader->reader->supportsAnimation())
1173 continue;
1174 // Ensure can get a valid QImageReader::nextImageDelay(), Because
1175 // using QImageReader::nextImageDelay() needs call QImageReader::read() before.
1176 reader->initCurrentImage(this);
1177 if (reader->currentImageIsEnd(this) && !reader->jumpToNextImage(this))
1178 continue;
1179 if (!next || reader->currentImageEndTime() < next->currentImageEndTime())
1180 next = reader;
1181 }
1182 return const_cast<ReaderData*>(next);
1183 }
1184
1185 #endif
1186
1187 DGUI_END_NAMESPACE