Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qsvgvisitorimpl.cpp
Go to the documentation of this file.
1// Copyright (C) 2024 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
7
8#include <private/qsvgvisitor_p.h>
9
10#include <QString>
11#include <QPainter>
12#include <QTextDocument>
13#include <QTextLayout>
14#include <QMatrix4x4>
15#include <QQuickItem>
16
17#include <private/qquickshape_p.h>
18#include <private/qquicktext_p.h>
19#include <private/qquicktranslate_p.h>
20#include <private/qquickitem_p.h>
21
22#include <private/qquickimagebase_p_p.h>
23#include <private/qquickimage_p.h>
24#include <private/qsgcurveprocessor_p.h>
25
26#include <private/qquadpath_p.h>
27
28#include <QtCore/private/qstringiterator_p.h>
29
30#include "utils_p.h"
31#include <QtCore/qloggingcategory.h>
32#include <QtCore/qscopedvaluerollback.h>
33#include <QtCore/qxmlstream.h>
34
35#include <QtSvg/private/qsvgdocument_p.h>
36#include <QtSvg/private/qsvgstyle_p.h>
37#include <QtSvg/private/qsvgfilter_p.h>
38
40
41Q_STATIC_LOGGING_CATEGORY(lcVectorImageAnimations, "qt.quick.vectorimage.animations")
42
43using namespace Qt::StringLiterals;
44
46{
47public:
48 explicit QSvgStyleResolver(const QSvgDocument *doc)
50 {
51 m_dummyImage = QImage(1, 1, QImage::Format_RGB32);
52 m_dummyPainter.begin(&m_dummyImage);
53 QPen defaultPen(Qt::NoBrush, 1, Qt::SolidLine, Qt::FlatCap, Qt::SvgMiterJoin);
54 defaultPen.setMiterLimit(4);
55 m_dummyPainter.setPen(defaultPen);
56 m_dummyPainter.setBrush(Qt::black);
57 }
58
60 {
61 m_dummyPainter.end();
62 }
63
64 QPainter& painter() { return m_dummyPainter; }
65 QSvgExtraStates& states() { return m_svgState; }
66
68 {
69 if (m_dummyPainter.brush().style() == Qt::NoBrush ||
70 m_dummyPainter.brush().color() == QColorConstants::Transparent) {
71 return QColor(QColorConstants::Transparent);
72 }
73
74 QColor fillColor;
75 fillColor = m_dummyPainter.brush().color();
76 fillColor.setAlphaF(m_svgState.fillOpacity);
77
78 return fillColor;
79 }
80
82 {
83 return m_svgState.fillOpacity;
84 }
85
86 const QGradient *currentStrokeGradient() const
87 {
88 QBrush brush = m_dummyPainter.pen().brush();
89 if (brush.style() == Qt::LinearGradientPattern
90 || brush.style() == Qt::RadialGradientPattern
91 || brush.style() == Qt::ConicalGradientPattern) {
92 return brush.gradient();
93 }
94 return nullptr;
95 }
96
97 const QGradient *currentFillGradient() const
98 {
99 if (m_dummyPainter.brush().style() == Qt::LinearGradientPattern || m_dummyPainter.brush().style() == Qt::RadialGradientPattern || m_dummyPainter.brush().style() == Qt::ConicalGradientPattern )
100 return m_dummyPainter.brush().gradient();
101 return nullptr;
102 }
103
105 {
106 return m_dummyPainter.brush().transform();
107 }
108
110 {
111 if (m_dummyPainter.pen().brush().style() == Qt::NoBrush ||
112 m_dummyPainter.pen().brush().color() == QColorConstants::Transparent) {
113 return QColor(QColorConstants::Transparent);
114 }
115
116 QColor strokeColor;
117 strokeColor = m_dummyPainter.pen().brush().color();
118 strokeColor.setAlphaF(m_svgState.strokeOpacity);
119
120 return strokeColor;
121 }
122
123 static QGradient applyOpacityToGradient(const QGradient &gradient, float opacity)
124 {
125 QGradient grad = gradient;
126 QGradientStops stops;
127 for (auto &stop : grad.stops()) {
128 stop.second.setAlphaF(stop.second.alphaF() * opacity);
129 stops.append(stop);
130 }
131
132 grad.setStops(stops);
133
134 return grad;
135 }
136
137 float currentStrokeWidth() const
138 {
139 float penWidth = m_dummyPainter.pen().widthF();
140 return penWidth ? penWidth : 1;
141 }
142
144 {
145 return m_dummyPainter.pen();
146 }
147
148protected:
152};
153
154namespace {
155inline bool isPathContainer(const QSvgDocument *doc, const QSvgStructureNode *node)
156{
157 bool foundPath = false;
158 for (const auto &child : node->renderers()) {
159 switch (child->type()) {
160 // nodes that shouldn't go inside Shape{}
161 case QSvgNode::Switch:
162 case QSvgNode::Doc:
163 case QSvgNode::Group:
164 case QSvgNode::AnimateColor:
165 case QSvgNode::AnimateTransform:
166 case QSvgNode::Use:
167 case QSvgNode::Video:
168 case QSvgNode::Image:
169 case QSvgNode::Textarea:
170 case QSvgNode::Text:
171 case QSvgNode::Tspan:
172 case QSvgNode::Mask:
173 case QSvgNode::Marker:
174 case QSvgNode::Pattern:
175 //qCDebug(lcQuickVectorGraphics) << "NOT path container because" << node->typeName() ;
176 return false;
177
178 // nodes that could go inside Shape{}
179 case QSvgNode::Defs:
180 case QSvgNode::Symbol:
181 break;
182
183 // nodes that are done as pure ShapePath{}
184 case QSvgNode::Rect:
185 case QSvgNode::Circle:
186 case QSvgNode::Ellipse:
187 case QSvgNode::Line:
188 case QSvgNode::Path:
189 case QSvgNode::Polygon:
190 case QSvgNode::Polyline:
191 {
192 if (child->hasFilter())
193 return false;
194
195 if (child->hasAnyMarker())
196 return false;
197
198 if (!child->style().isDefaultProperty(QSvgStyleProperty::Opacity))
199 return false;
200
201 if (!child->style().isDefaultProperty(QSvgStyleProperty::Transform))
202 return false;
203
204 const auto animations = doc->animator()->animationsForNode(child.get());
205 if (!animations.isEmpty()) {
206 //qCDebug(lcQuickVectorGraphics) << "NOT path container because local transform animation";
207 return false;
208 }
209 foundPath = true;
210 break;
211 }
212 default:
213 qCDebug(lcQuickVectorImage) << "Unhandled type in switch" << child->type();
214 break;
215 }
216 }
217 //qCDebug(lcQuickVectorGraphics) << "Container" << node->nodeId() << node->typeName() << "is" << foundPath;
218 return foundPath;
219}
220
221static QString capStyleName(Qt::PenCapStyle style)
222{
223 QString styleName;
224
225 switch (style) {
226 case Qt::SquareCap:
227 styleName = QStringLiteral("squarecap");
228 break;
229 case Qt::FlatCap:
230 styleName = QStringLiteral("flatcap");
231 break;
232 case Qt::RoundCap:
233 styleName = QStringLiteral("roundcap");
234 break;
235 default:
236 break;
237 }
238
239 return styleName;
240}
241
242static QString joinStyleName(Qt::PenJoinStyle style)
243{
244 QString styleName;
245
246 switch (style) {
247 case Qt::MiterJoin:
248 styleName = QStringLiteral("miterjoin");
249 break;
250 case Qt::BevelJoin:
251 styleName = QStringLiteral("beveljoin");
252 break;
253 case Qt::RoundJoin:
254 styleName = QStringLiteral("roundjoin");
255 break;
256 case Qt::SvgMiterJoin:
257 styleName = QStringLiteral("svgmiterjoin");
258 break;
259 default:
260 break;
261 }
262
263 return styleName;
264}
265
266static QString dashArrayString(QList<qreal> dashArray)
267{
268 if (dashArray.isEmpty())
269 return QString();
270
271 QString dashArrayString;
272 QTextStream stream(&dashArrayString);
273
274 for (int i = 0; i < dashArray.length() - 1; i++) {
275 qreal value = dashArray[i];
276 stream << value << ", ";
277 }
278
279 stream << dashArray.last();
280
281 return dashArrayString;
282}
283};
284
285static QString scrub(const QString &raw)
286{
287 QString res(raw.left(80));
288
289 if (!res.isEmpty()) {
290 constexpr QLatin1StringView legalSymbols("_-.:"); // Only valid SVG id characters
291 qsizetype i = 0;
292 do {
293 if (res.at(i).isLetterOrNumber() || legalSymbols.contains(res.at(i)))
294 i++;
295 else
296 res.remove(i, 1);
297 } while (i < res.size());
298 }
299
300 return res;
301}
302
303QSvgVisitorImpl::QSvgVisitorImpl(const QQuickVectorImageSource &source,
304 QQuickGenerator *generator,
305 bool assumeTrustedSource)
308 , m_assumeTrustedSource(assumeTrustedSource)
309{
310}
311
312QSvgVisitorImpl::~QSvgVisitorImpl() = default;
313
314bool QSvgVisitorImpl::startDefsBlock(const QSvgNode *node)
315{
317 fillCommonNodeInfo(node, info);
318
320
321 // Pattern transforms handled through the fill transform, the transform property is ignored, so
322 // we overwrite it with identity.
323 if (node->type() == QSvgNode::Pattern) {
324 info.transform = QQuickAnimatedProperty(QVariant::fromValue(QTransform{}));
325 info.isDefaultTransform = true;
326 }
327
328 if (!m_generator->generateDefsNode(info))
329 return false;
330
331 return true;
332}
333
334void QSvgVisitorImpl::endDefsBlock(const QSvgNode *node)
335{
337 fillCommonNodeInfo(node, info);
338
340
341 m_generator->generateDefsNode(info);
342}
343
344static inline bool isStructureNode(const QSvgNode *node)
345{
346 switch (node->type()) {
347 case QSvgNode::Switch:
348 case QSvgNode::Doc:
349 case QSvgNode::Defs:
350 case QSvgNode::Group:
351 case QSvgNode::Mask:
352 case QSvgNode::Symbol:
353 case QSvgNode::Filter:
354 case QSvgNode::FeMerge:
355 case QSvgNode::FeMergenode:
356 case QSvgNode::FeColormatrix:
357 case QSvgNode::FeGaussianblur:
358 case QSvgNode::FeOffset:
359 case QSvgNode::FeComposite:
360 case QSvgNode::FeFlood:
361 case QSvgNode::FeBlend:
362 case QSvgNode::Marker:
363 case QSvgNode::Pattern:
364 return true;
365 default:
366 return false;
367 }
368}
369
370static void recurseSvgNodes(const QSvgNode *root, const std::function<void(const QSvgNode *)> &fnc)
371{
372 fnc(root);
373
374 if (isStructureNode(root)) {
375 const QSvgStructureNode *sn = static_cast<const QSvgStructureNode *>(root);
376 for (const auto &child : sn->renderers())
377 recurseSvgNodes(child.get(), fnc);
378 }
379}
380
381void QSvgVisitorImpl::pregenerateReferencedNodes(const QSvgNode *doc)
382{
383 Q_ASSERT(m_doc != nullptr);
384 Q_ASSERT(m_generator != nullptr);
385
386 // Find any node which is referenced from elsewhere and generate a Component definition
387 // for it
388 QSet<QString> referencedIds;
389 auto findReferencedIds = [&referencedIds](const QSvgNode *node) {
390 if (node->hasFilter())
391 referencedIds.insert(node->filterId());
392 if (node->hasMask())
393 referencedIds.insert(node->maskId());
394 if (node->hasMarkerStart())
395 referencedIds.insert(node->markerStartId());
396 if (node->hasMarkerMid())
397 referencedIds.insert(node->markerMidId());
398 if (node->hasMarkerEnd())
399 referencedIds.insert(node->markerEndId());
400 if (node->type() == QSvgNode::Pattern)
401 referencedIds.insert(node->nodeId());
402 };
403 recurseSvgNodes(doc, findReferencedIds);
404
405 m_pregeneratingReferencedNodes = true;
406 for (const QString &referencedId : referencedIds) {
407 const QSvgNode *referencedNode = m_doc->namedNode(referencedId);
408 if (referencedNode == nullptr)
409 continue;
410
411 if (!startDefsBlock(referencedNode))
412 return;
413
414 traverse(referencedNode);
415
416 endDefsBlock(referencedNode);
417 }
418
419 m_pregeneratingReferencedNodes = false;
420}
421
423{
424 if (!m_generator) {
425 qCDebug(lcQuickVectorImage) << "No valid QQuickGenerator is set. Genration will stop";
426 return false;
427 }
428
429 QtSvg::Options options;
430 if (m_assumeTrustedSource)
431 options.setFlag(QtSvg::AssumeTrustedSource);
432
433 const auto doc = m_source.isFile()
434 ? QSvgDocument::load(m_source.fileName(), options)
435 : QSvgDocument::load(m_source.data(), options);
436
437 QScopedValueRollback docResetter(m_doc, doc.get());
438 if (!doc) {
439 qCDebug(lcQuickVectorImage) << "Not a valid Svg source:" << m_source;
440 return false;
441 }
442
443 m_styleResolver = std::make_unique<QSvgStyleResolver>(doc.get());
444 QSvgVisitor::traverse(doc.get());
445
446 return true;
447}
448
449void QSvgVisitorImpl::visitNode(const QSvgNode *node)
450{
451 handleBaseNodeSetup(node);
452
453 NodeInfo info;
454 fillCommonNodeInfo(node, info);
455 fillAnimationInfo(node, info);
456
457 m_generator->generateNode(info);
458
459 handleBaseNodeEnd(node);
460}
461
462void QSvgVisitorImpl::visitImageNode(const QSvgImage *node)
463{
464 // TODO: this requires proper asset management.
465 handleBaseNodeSetup(node);
466
467 ImageNodeInfo info;
468 fillCommonNodeInfo(node, info);
469 fillAnimationInfo(node, info);
470 info.image = node->image();
471 info.rect = node->rect();
472 info.externalFileReference = node->filename();
473
474 m_generator->generateImageNode(info);
475
476 handleBaseNodeEnd(node);
477}
478
479void QSvgVisitorImpl::visitRectNode(const QSvgRect *node)
480{
481 QRectF rect = node->rect();
482 QPointF rads = node->radius();
483 // This is using Qt::RelativeSize semantics: percentage of half rect size
484 qreal x1 = rect.left();
485 qreal x2 = rect.right();
486 qreal y1 = rect.top();
487 qreal y2 = rect.bottom();
488
489 qreal rx = rads.x() * rect.width() / 200;
490 qreal ry = rads.y() * rect.height() / 200;
491 QPainterPath p;
492
493 p.moveTo(x1 + rx, y1);
494 p.lineTo(x2 - rx, y1);
495 // qCDebug(lcQuickVectorGraphics) << "Line1" << x2 - rx << y1;
496 p.arcTo(x2 - rx * 2, y1, rx * 2, ry * 2, 90, -90); // ARC to x2, y1 + ry
497 // qCDebug(lcQuickVectorGraphics) << "p1" << p;
498
499 p.lineTo(x2, y2 - ry);
500 p.arcTo(x2 - rx * 2, y2 - ry * 2, rx * 2, ry * 2, 0, -90); // ARC to x2 - rx, y2
501
502 p.lineTo(x1 + rx, y2);
503 p.arcTo(x1, y2 - ry * 2, rx * 2, ry * 2, 270, -90); // ARC to x1, y2 - ry
504
505 p.lineTo(x1, y1 + ry);
506 p.arcTo(x1, y1, rx * 2, ry * 2, 180, -90); // ARC to x1 + rx, y1
507
508 handlePathNode(node, p);
509}
510
511void QSvgVisitorImpl::visitEllipseNode(const QSvgEllipse *node)
512{
513 QRectF rect = node->rect();
514
515 QPainterPath p;
516 p.addEllipse(rect);
517
518 handlePathNode(node, p);
519}
520
521void QSvgVisitorImpl::visitPathNode(const QSvgPath *node)
522{
523 handlePathNode(node, node->path());
524}
525
526void QSvgVisitorImpl::visitLineNode(const QSvgLine *node)
527{
528 QPainterPath p;
529 p.moveTo(node->line().p1());
530 p.lineTo(node->line().p2());
531 handlePathNode(node, p);
532}
533
534void QSvgVisitorImpl::visitPolygonNode(const QSvgPolygon *node)
535{
536 QPainterPath p = QQuickVectorImageGenerator::Utils::polygonToPath(node->polygon(), true);
537 handlePathNode(node, p);
538}
539
540void QSvgVisitorImpl::visitPolylineNode(const QSvgPolyline *node)
541{
542 QPainterPath p = QQuickVectorImageGenerator::Utils::polygonToPath(node->polygon(), false);
543 handlePathNode(node, p);
544}
545
546QString QSvgVisitorImpl::gradientCssDescription(const QGradient *gradient)
547{
548 QString cssDescription;
549 if (gradient->type() == QGradient::LinearGradient) {
550 const QLinearGradient *linearGradient = static_cast<const QLinearGradient *>(gradient);
551
552 cssDescription += " -qt-foreground: qlineargradient("_L1;
553 cssDescription += "x1:"_L1 + QString::number(linearGradient->start().x()) + u',';
554 cssDescription += "y1:"_L1 + QString::number(linearGradient->start().y()) + u',';
555 cssDescription += "x2:"_L1 + QString::number(linearGradient->finalStop().x()) + u',';
556 cssDescription += "y2:"_L1 + QString::number(linearGradient->finalStop().y()) + u',';
557 } else if (gradient->type() == QGradient::RadialGradient) {
558 const QRadialGradient *radialGradient = static_cast<const QRadialGradient *>(gradient);
559
560 cssDescription += " -qt-foreground: qradialgradient("_L1;
561 cssDescription += "cx:"_L1 + QString::number(radialGradient->center().x()) + u',';
562 cssDescription += "cy:"_L1 + QString::number(radialGradient->center().y()) + u',';
563 cssDescription += "fx:"_L1 + QString::number(radialGradient->focalPoint().x()) + u',';
564 cssDescription += "fy:"_L1 + QString::number(radialGradient->focalPoint().y()) + u',';
565 cssDescription += "radius:"_L1 + QString::number(radialGradient->radius()) + u',';
566 } else {
567 const QConicalGradient *conicalGradient = static_cast<const QConicalGradient *>(gradient);
568
569 cssDescription += " -qt-foreground: qconicalgradient("_L1;
570 cssDescription += "cx:"_L1 + QString::number(conicalGradient->center().x()) + u',';
571 cssDescription += "cy:"_L1 + QString::number(conicalGradient->center().y()) + u',';
572 cssDescription += "angle:"_L1 + QString::number(conicalGradient->angle()) + u',';
573 }
574
575 const QStringList coordinateModes = { "logical"_L1, "stretchtodevice"_L1, "objectbounding"_L1, "object"_L1 };
576 cssDescription += "coordinatemode:"_L1;
577 cssDescription += coordinateModes.at(int(gradient->coordinateMode()));
578 cssDescription += u',';
579
580 const QStringList spreads = { "pad"_L1, "reflect"_L1, "repeat"_L1 };
581 cssDescription += "spread:"_L1;
582 cssDescription += spreads.at(int(gradient->spread()));
583
584 for (const QGradientStop &stop : gradient->stops()) {
585 cssDescription += ",stop:"_L1;
586 cssDescription += QString::number(stop.first);
587 cssDescription += u' ';
588 cssDescription += stop.second.name(QColor::HexArgb);
589 }
590
591 cssDescription += ");"_L1;
592
593 return cssDescription;
594}
595
596QString QSvgVisitorImpl::colorCssDescription(QColor color)
597{
598 QString cssDescription;
599 cssDescription += QStringLiteral("rgba(");
600 cssDescription += QString::number(color.red()) + QStringLiteral(",");
601 cssDescription += QString::number(color.green()) + QStringLiteral(",");
602 cssDescription += QString::number(color.blue()) + QStringLiteral(",");
603 cssDescription += QString::number(color.alphaF()) + QStringLiteral(")");
604
605 return cssDescription;
606}
607
608namespace {
609
610 // Simple class for representing the SVG font as a font engine
611 // We use the Proxy font engine type, which is currently unused and does not map to
612 // any specific font engine
613 // (The QSvgFont object must outlive the engine.)
614 class QSvgFontEngine : public QFontEngine
615 {
616 public:
617 QSvgFontEngine(const QString &family, const QSvgFont *font, qreal size);
618
619 QFontEngine *cloneWithSize(qreal size) const override;
620
621 glyph_t glyphIndex(uint ucs4) const override;
622 int stringToCMap(const QChar *str,
623 int len,
624 QGlyphLayout *glyphs,
625 int *nglyphs,
626 ShaperFlags flags) const override;
627
628 void addGlyphsToPath(glyph_t *glyphs,
629 QFixedPoint *positions,
630 int nGlyphs,
631 QPainterPath *path,
632 QTextItem::RenderFlags flags) override;
633
634 glyph_metrics_t boundingBox(glyph_t glyph) override;
635
636 void recalcAdvances(QGlyphLayout *, ShaperFlags) const override;
637 QFixed ascent() const override;
638 QFixed capHeight() const override;
639 QFixed descent() const override;
640 QFixed leading() const override;
641 qreal maxCharWidth() const override;
642 qreal minLeftBearing() const override;
643 qreal minRightBearing() const override;
644
645 QFixed emSquareSize() const override;
646
647 private:
648 const QSvgFont *m_font;
649 QString m_family;
650 };
651
652 QSvgFontEngine::QSvgFontEngine(const QString &family, const QSvgFont *font, qreal size)
653 : QFontEngine(Proxy)
654 , m_font(font)
655 , m_family(family)
656 {
657 fontDef.pixelSize = size;
658 fontDef.families = QStringList(family);
659 }
660
661 QFixed QSvgFontEngine::emSquareSize() const
662 {
663 return QFixed::fromReal(m_font->m_unitsPerEm);
664 }
665
666 glyph_t QSvgFontEngine::glyphIndex(uint ucs4) const
667 {
668 const ushort c(ucs4);
669 if (ucs4 < USHRT_MAX && m_font->findFirstGlyphFor(QStringView(&c, 1)))
670 return glyph_t(ucs4);
671
672 return 0;
673 }
674
675 int QSvgFontEngine::stringToCMap(const QChar *str,
676 int len,
677 QGlyphLayout *glyphs,
678 int *nglyphs,
679 ShaperFlags flags) const
680 {
681 Q_ASSERT(glyphs->numGlyphs >= *nglyphs);
682 if (*nglyphs < len) {
683 *nglyphs = len;
684 return -1;
685 }
686
687 int ucs4Length = 0;
688 QStringIterator it(str, str + len);
689 while (it.hasNext()) {
690 char32_t ucs4 = it.next();
691 glyph_t index = glyphIndex(ucs4);
692 glyphs->glyphs[ucs4Length++] = index;
693 }
694
695 *nglyphs = ucs4Length;
696 glyphs->numGlyphs = ucs4Length;
697
698 if (!(flags & GlyphIndicesOnly))
699 recalcAdvances(glyphs, flags);
700
701 return *nglyphs;
702 }
703
704 void QSvgFontEngine::addGlyphsToPath(glyph_t *glyphs,
705 QFixedPoint *positions,
706 int nGlyphs,
707 QPainterPath *path,
708 QTextItem::RenderFlags flags)
709 {
710 Q_UNUSED(flags);
711 const qreal scale = fontDef.pixelSize / m_font->m_unitsPerEm;
712 for (int i = 0; i < nGlyphs; ++i) {
713 glyph_t index = glyphs[i];
714 if (index > 0) {
715 QPointF position = positions[i].toPointF();
716 const ushort c(index);
717 const QSvgGlyph *foundGlyph = m_font->findFirstGlyphFor(QStringView(&c, 1));
718
719 if (!foundGlyph)
720 continue;
721
722 QPainterPath glyphPath = foundGlyph->m_path;
723
724 QTransform xform;
725 xform.translate(position.x(), position.y());
726 xform.scale(scale, -scale);
727 glyphPath = xform.map(glyphPath);
728 path->addPath(glyphPath);
729 }
730 }
731 }
732
733 glyph_metrics_t QSvgFontEngine::boundingBox(glyph_t glyph)
734 {
735 glyph_metrics_t ret;
736 ret.x = 0; // left bearing
737 ret.y = -ascent();
738 const qreal scale = fontDef.pixelSize / m_font->m_unitsPerEm;
739 const ushort c(glyph);
740 const QSvgGlyph *svgGlyph = m_font->findFirstGlyphFor(QStringView(&c, 1));
741 ret.width = QFixed::fromReal(svgGlyph ? svgGlyph->m_horizAdvX * scale : 0.);
742 ret.height = ascent() + descent();
743 return ret;
744 }
745
746 QFontEngine *QSvgFontEngine::cloneWithSize(qreal size) const
747 {
748 QSvgFontEngine *otherEngine = new QSvgFontEngine(m_family, m_font, size);
749 return otherEngine;
750 }
751
752 void QSvgFontEngine::recalcAdvances(QGlyphLayout *glyphLayout, ShaperFlags) const
753 {
754 const qreal scale = fontDef.pixelSize / m_font->m_unitsPerEm;
755 for (int i = 0; i < glyphLayout->numGlyphs; i++) {
756 const ushort c(glyphLayout->glyphs[i]);
757 const QSvgGlyph *svgGl = m_font->findFirstGlyphFor(QStringView(&c, 1));
758 glyphLayout->advances[i] = QFixed::fromReal(svgGl ? svgGl->m_horizAdvX * scale : 0.);
759 }
760 }
761
762 QFixed QSvgFontEngine::ascent() const
763 {
764 return QFixed::fromReal(fontDef.pixelSize);
765 }
766
767 QFixed QSvgFontEngine::capHeight() const
768 {
769 return ascent();
770 }
771 QFixed QSvgFontEngine::descent() const
772 {
773 return QFixed{};
774 }
775
776 QFixed QSvgFontEngine::leading() const
777 {
778 return QFixed{};
779 }
780
781 qreal QSvgFontEngine::maxCharWidth() const
782 {
783 const qreal scale = fontDef.pixelSize / m_font->m_unitsPerEm;
784 return m_font->m_horizAdvX * scale;
785 }
786
787 qreal QSvgFontEngine::minLeftBearing() const
788 {
789 return 0.0;
790 }
791
792 qreal QSvgFontEngine::minRightBearing() const
793 {
794 return 0.0;
795 }
796}
797
798static QVariant calculateInterpolatedValue(const QSvgAbstractAnimatedProperty *property, int index, int)
799{
800 if (index == 0)
801 const_cast<QSvgAbstractAnimatedProperty *>(property)->interpolate(1, 0.0);
802 else
803 const_cast<QSvgAbstractAnimatedProperty *>(property)->interpolate(index, 1.0);
804
805 return property->interpolatedValue();
806}
807
808void QSvgVisitorImpl::visitTextNode(const QSvgText *node)
809{
810 handleBaseNodeSetup(node);
811 const bool isTextArea = node->type() == QSvgNode::Textarea;
812
813 QString text;
814 bool needsRichText = false;
815 bool preserveWhiteSpace = node->whitespaceMode() == QSvgText::Preserve;
816 const QGradient *mainGradient = m_styleResolver->currentFillGradient();
817
818
819 auto *fontStyle = static_cast<QSvgFontStyle *>(node->styleProperty(QSvgStyleProperty::Font));
820 QSvgFont *svgFont = nullptr;
821 QString svgFontFamily;
822 if (fontStyle) {
823 Q_ASSERT(m_doc);
824 svgFontFamily = fontStyle->qfont().family();
825 svgFont = m_doc->svgFont(svgFontFamily);
826 }
827
828 QFontEngine *fontEngine = nullptr;
829 if (svgFont != nullptr) {
830 fontEngine = new QSvgFontEngine(svgFontFamily, svgFont, m_styleResolver->painter().font().pointSize());
831 fontEngine->ref.ref();
832 }
833
834
835#if QT_CONFIG(texthtmlparser)
836 bool needsPathNode = mainGradient != nullptr
837 || svgFont != nullptr
838 || m_styleResolver->currentStrokeGradient() != nullptr;
839#endif
840 for (const auto *tspan : node->tspans()) {
841 if (!tspan) {
842 text += QStringLiteral("<br>");
843 continue;
844 }
845
846 // Note: We cannot get the font directly from the style, since this does
847 // not apply the weight, since this is relative and depends on current state.
848 handleBaseNodeSetup(tspan);
849 QFont font = m_styleResolver->painter().font();
850
851 QString styleTagContent;
852
853 if ((font.resolveMask() & QFont::FamilyResolved)
854 || (font.resolveMask() & QFont::FamiliesResolved)) {
855 styleTagContent += QStringLiteral("font-family: %1;").arg(font.family());
856 }
857
858 if (font.resolveMask() & QFont::WeightResolved
859 && font.weight() != QFont::Normal
860 && font.weight() != QFont::Bold) {
861 styleTagContent += QStringLiteral("font-weight: %1;").arg(int(font.weight()));
862 }
863
864 if (font.resolveMask() & QFont::SizeResolved) {
865 // Pixel size stored as point size in SVG parser
866 styleTagContent += QStringLiteral("font-size: %1px;").arg(int(font.pointSizeF()));
867 }
868
869 if (font.resolveMask() & QFont::CapitalizationResolved
870 && font.capitalization() == QFont::SmallCaps) {
871 styleTagContent += QStringLiteral("font-variant: small-caps;");
872 }
873
874 if (m_styleResolver->currentFillGradient() != nullptr
875 && m_styleResolver->currentFillGradient() != mainGradient) {
876 const QGradient grad = m_styleResolver->applyOpacityToGradient(*m_styleResolver->currentFillGradient(), m_styleResolver->currentFillOpacity());
877 styleTagContent += gradientCssDescription(&grad) + u';';
878#if QT_CONFIG(texthtmlparser)
879 needsPathNode = true;
880#endif
881 }
882
883 const QColor currentStrokeColor = m_styleResolver->currentStrokeColor();
884 if (currentStrokeColor.alpha() > 0) {
885 QString strokeColor = colorCssDescription(currentStrokeColor);
886 styleTagContent += QStringLiteral("-qt-stroke-color:%1;").arg(strokeColor);
887 styleTagContent += QStringLiteral("-qt-stroke-width:%1px;").arg(m_styleResolver->currentStrokeWidth());
888 styleTagContent += QStringLiteral("-qt-stroke-dasharray:%1;").arg(dashArrayString(m_styleResolver->currentStroke().dashPattern()));
889 styleTagContent += QStringLiteral("-qt-stroke-dashoffset:%1;").arg(m_styleResolver->currentStroke().dashOffset());
890 styleTagContent += QStringLiteral("-qt-stroke-lineCap:%1;").arg(capStyleName(m_styleResolver->currentStroke().capStyle()));
891 styleTagContent += QStringLiteral("-qt-stroke-lineJoin:%1;").arg(joinStyleName(m_styleResolver->currentStroke().joinStyle()));
892 if (m_styleResolver->currentStroke().joinStyle() == Qt::MiterJoin || m_styleResolver->currentStroke().joinStyle() == Qt::SvgMiterJoin)
893 styleTagContent += QStringLiteral("-qt-stroke-miterlimit:%1;").arg(m_styleResolver->currentStroke().miterLimit());
894#if QT_CONFIG(texthtmlparser)
895 needsPathNode = true;
896#endif
897 }
898
899 if (tspan->whitespaceMode() == QSvgText::Preserve && !preserveWhiteSpace)
900 styleTagContent += QStringLiteral("white-space: pre-wrap;");
901
902 QString content = tspan->text().toHtmlEscaped();
903 content.replace(QLatin1Char('\t'), QLatin1Char(' '));
904 content.replace(QLatin1Char('\n'), QLatin1Char(' '));
905
906 bool fontTag = false;
907 if (!tspan->style().isDefaultProperty(QSvgStyleProperty::Fill)) {
908 auto fill = static_cast<QSvgFillStyle *>(tspan->style().property(QSvgStyleProperty::Fill));
909 auto &b = fill->qbrush();
910 qCDebug(lcQuickVectorImage) << "tspan FILL:" << b;
911 if (b.style() != Qt::NoBrush)
912 {
913 if (qFuzzyCompare(b.color().alphaF() + 1.0, 2.0))
914 {
915 QString spanColor = b.color().name();
916 fontTag = !spanColor.isEmpty();
917 if (fontTag)
918 text += QStringLiteral("<font color=\"%1\">").arg(spanColor);
919 } else {
920 QString spanColor = colorCssDescription(b.color());
921 styleTagContent += QStringLiteral("color:%1").arg(spanColor);
922 }
923 }
924 }
925
926 needsRichText = needsRichText || !styleTagContent.isEmpty();
927 if (!styleTagContent.isEmpty())
928 text += QStringLiteral("<span style=\"%1\">").arg(styleTagContent.toHtmlEscaped());
929
930 if (font.resolveMask() & QFont::WeightResolved && font.bold())
931 text += QStringLiteral("<b>");
932
933 if (font.resolveMask() & QFont::StyleResolved && font.italic())
934 text += QStringLiteral("<i>");
935
936 if (font.resolveMask() & QFont::CapitalizationResolved) {
937 switch (font.capitalization()) {
938 case QFont::AllLowercase:
939 content = content.toLower();
940 break;
941 case QFont::AllUppercase:
942 content = content.toUpper();
943 break;
944 case QFont::Capitalize:
945 // ### We need to iterate over the string and do the title case conversion,
946 // since this is not part of QString.
947 qCWarning(lcQuickVectorImage) << "Title case not implemented for tspan";
948 break;
949 default:
950 break;
951 }
952 }
953 text += content;
954 if (fontTag)
955 text += QStringLiteral("</font>");
956
957 if (font.resolveMask() & QFont::StyleResolved && font.italic())
958 text += QStringLiteral("</i>");
959
960 if (font.resolveMask() & QFont::WeightResolved && font.bold())
961 text += QStringLiteral("</b>");
962
963 if (!styleTagContent.isEmpty())
964 text += QStringLiteral("</span>");
965
966 handleBaseNodeEnd(tspan);
967 }
968
969 if (preserveWhiteSpace && (needsRichText || m_styleResolver->currentFillGradient() != nullptr))
970 text = QStringLiteral("<span style=\"white-space: pre-wrap\">") + text + QStringLiteral("</span>");
971
972 QFont font = m_styleResolver->painter().font();
973 if (font.pixelSize() <= 0 && font.pointSize() > 0)
974 font.setPixelSize(font.pointSize()); // Pixel size stored as point size by SVG parser
975
976 font.setHintingPreference(QFont::PreferNoHinting);
977
978#if QT_CONFIG(texthtmlparser)
979 if (needsPathNode) {
980 QTextDocument document;
981 document.setHtml(text);
982 if (isTextArea && node->size().width() > 0)
983 document.setTextWidth(node->size().width());
984 document.setDefaultFont(font);
985 document.pageCount(); // Force layout
986
987 QTextBlock block = document.firstBlock();
988 while (block.isValid()) {
989 QTextLayout *lout = block.layout();
990
991 if (lout != nullptr) {
992 QRectF boundingRect = lout->boundingRect();
993
994 // If this block has requested the current SVG font, we override it
995 // (note that this limits the text to one svg font, but this is also the case
996 // in the QPainter at the moment, and needs a more centralized solution in Qt Svg
997 // first)
998 QFont blockFont = block.charFormat().font();
999 if (svgFont != nullptr
1000 && blockFont.family() == svgFontFamily) {
1001 QRawFont rawFont;
1002 QRawFontPrivate *rawFontD = QRawFontPrivate::get(rawFont);
1003 rawFontD->setFontEngine(fontEngine->cloneWithSize(blockFont.pixelSize()));
1004
1005 lout->setRawFont(rawFont);
1006 }
1007
1008 auto addPathForFormat = [&](QPainterPath p, QTextCharFormat fmt, int pathIndex) {
1009 PathNodeInfo info;
1010 fillCommonNodeInfo(node, info, QStringLiteral("_path%1").arg(pathIndex));
1011 fillPathAnimationInfo(node, info);
1012 auto fillStyle = static_cast<QSvgFillStyle *>(node->style().property(QSvgStyleProperty::Fill));
1013 if (fillStyle)
1014 info.fillRule = fillStyle->fillRule();
1015
1016 if (fmt.hasProperty(QTextCharFormat::ForegroundBrush)) {
1017 info.fillColor.setDefaultValue(fmt.foreground().color());
1018 if (fmt.foreground().gradient() != nullptr && fmt.foreground().gradient()->type() != QGradient::NoGradient)
1019 info.grad = *fmt.foreground().gradient();
1020 } else {
1021 info.fillColor.setDefaultValue(m_styleResolver->currentFillColor());
1022 }
1023
1024 info.path.setDefaultValue(QVariant::fromValue(p));
1025
1026 const QGradient *strokeGradient = m_styleResolver->currentStrokeGradient();
1027 QPen pen;
1028 if (fmt.hasProperty(QTextCharFormat::TextOutline)) {
1029 pen = fmt.textOutline();
1030 if (strokeGradient == nullptr) {
1031 info.strokeStyle = StrokeStyle::fromPen(pen);
1032 info.strokeStyle.color.setDefaultValue(pen.color());
1033 }
1034 } else {
1035 pen = m_styleResolver->currentStroke();
1036 if (strokeGradient == nullptr) {
1037 info.strokeStyle = StrokeStyle::fromPen(pen);
1038 info.strokeStyle.color.setDefaultValue(m_styleResolver->currentStrokeColor());
1039 }
1040 }
1041
1042 if (info.grad.type() == QGradient::NoGradient && m_styleResolver->currentFillGradient() != nullptr)
1043 info.grad = m_styleResolver->applyOpacityToGradient(*m_styleResolver->currentFillGradient(), m_styleResolver->currentFillOpacity());
1044
1045 info.fillTransform = m_styleResolver->currentFillTransform();
1046
1047 m_generator->generatePath(info, boundingRect);
1048
1049 if (strokeGradient != nullptr) {
1050 PathNodeInfo strokeInfo;
1051 fillCommonNodeInfo(node, strokeInfo, QStringLiteral("_stroke%1").arg(pathIndex));
1052 fillPathAnimationInfo(node, strokeInfo);
1053
1054 strokeInfo.grad = *strokeGradient;
1055
1056 QPainterPathStroker stroker(pen);
1057 strokeInfo.path.setDefaultValue(QVariant::fromValue(stroker.createStroke(p)));
1058 m_generator->generatePath(strokeInfo, boundingRect);
1059 }
1060 };
1061
1062 qreal baselineOffset = -QFontMetricsF(font).ascent();
1063 if (lout->lineCount() > 0 && lout->lineAt(0).isValid())
1064 baselineOffset = -lout->lineAt(0).ascent();
1065
1066 const QPointF baselineTranslation(0.0, baselineOffset);
1067 auto glyphsToPath = [&](QList<QGlyphRun> glyphRuns, qreal width) {
1068 QList<QPainterPath> paths;
1069 for (const QGlyphRun &glyphRun : glyphRuns) {
1070 QRawFont font = glyphRun.rawFont();
1071 QList<quint32> glyphIndexes = glyphRun.glyphIndexes();
1072 QList<QPointF> positions = glyphRun.positions();
1073
1074 for (qsizetype j = 0; j < glyphIndexes.size(); ++j) {
1075 quint32 glyphIndex = glyphIndexes.at(j);
1076 const QPointF &pos = positions.at(j);
1077
1078 QPainterPath p = font.pathForGlyph(glyphIndex);
1079 p.translate(pos + node->position() + baselineTranslation);
1080 if (m_styleResolver->states().textAnchor == Qt::AlignHCenter)
1081 p.translate(QPointF(-0.5 * width, 0));
1082 else if (m_styleResolver->states().textAnchor == Qt::AlignRight)
1083 p.translate(QPointF(-width, 0));
1084 paths.append(p);
1085 }
1086 }
1087
1088 return paths;
1089 };
1090
1091 QList<QTextLayout::FormatRange> formats = block.textFormats();
1092 for (int i = 0; i < formats.size(); ++i) {
1093 QTextLayout::FormatRange range = formats.at(i);
1094
1095 QList<QGlyphRun> glyphRuns = lout->glyphRuns(range.start, range.length);
1096 QList<QPainterPath> paths = glyphsToPath(glyphRuns, lout->minimumWidth());
1097 for (int j = 0; j < paths.size(); ++j) {
1098 const QPainterPath &path = paths.at(j);
1099 addPathForFormat(path, range.format, j);
1100 }
1101 }
1102 }
1103
1104 block = block.next();
1105 }
1106 } else
1107#endif
1108 {
1109 TextNodeInfo info;
1110 fillCommonNodeInfo(node, info);
1111 fillAnimationInfo(node, info);
1112
1113 {
1114 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("fill"));
1115 if (!animations.isEmpty())
1116 applyAnimationsToProperty(animations, &info.fillColor, calculateInterpolatedValue);
1117 }
1118
1119 {
1120 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("fill-opacity"));
1121 if (!animations.isEmpty())
1122 applyAnimationsToProperty(animations, &info.fillOpacity, calculateInterpolatedValue);
1123 }
1124
1125 {
1126 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("stroke"));
1127 if (!animations.isEmpty())
1128 applyAnimationsToProperty(animations, &info.strokeColor, calculateInterpolatedValue);
1129 }
1130
1131 {
1132 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("stroke-opacity"));
1133 if (!animations.isEmpty())
1134 applyAnimationsToProperty(animations, &info.strokeOpacity, calculateInterpolatedValue);
1135 }
1136
1137 info.position = node->position();
1138 info.size = node->size();
1139 info.font = font;
1140 info.text = text;
1141 info.isTextArea = isTextArea;
1142 info.needsRichText = needsRichText;
1143 info.fillColor.setDefaultValue(m_styleResolver->currentFillColor());
1144 info.alignment = m_styleResolver->states().textAnchor;
1145 info.strokeColor.setDefaultValue(m_styleResolver->currentStrokeColor());
1146
1147 m_generator->generateTextNode(info);
1148 }
1149
1150 handleBaseNodeEnd(node);
1151
1152 if (fontEngine != nullptr) {
1153 fontEngine->ref.deref();
1154 Q_ASSERT(fontEngine->ref.loadRelaxed() == 0);
1155 delete fontEngine;
1156 }
1157}
1158
1159void QSvgVisitorImpl::visitUseNode(const QSvgUse *node)
1160{
1161 QSvgNode *link = node->link();
1162 if (!link)
1163 return;
1164 handleBaseNodeSetup(node);
1165 UseNodeInfo info;
1166 fillCommonNodeInfo(node, info);
1167 fillAnimationInfo(node, info);
1169 info.startPos = node->start();
1170 m_generator->generateUseNode(info);
1171 QString oldLinkSuffix = m_linkSuffix;
1172 m_linkSuffix += QStringLiteral("_use") + info.id;
1173 m_useLevel++;
1174 QSvgVisitor::traverse(link);
1175 m_useLevel--;
1176 m_linkSuffix = oldLinkSuffix;
1178 m_generator->generateUseNode(info);
1179 handleBaseNodeEnd(node);
1180}
1181
1182bool QSvgVisitorImpl::visitSwitchNodeStart(const QSvgSwitch *node)
1183{
1184 QSvgNode *link = node->childToRender();
1185 if (!link)
1186 return false;
1187
1188 QString oldLinkSuffix = m_linkSuffix;
1189 m_linkSuffix += QStringLiteral("_switch") + QString::number(quintptr(node), 16);
1190 QSvgVisitor::traverse(link);
1191 m_linkSuffix = oldLinkSuffix;
1192
1193 return false;
1194}
1195
1196void QSvgVisitorImpl::visitSwitchNodeEnd(const QSvgSwitch *node)
1197{
1198 Q_UNUSED(node);
1199}
1200
1201bool QSvgVisitorImpl::visitDefsNodeStart(const QSvgDefs *node)
1202{
1203 Q_UNUSED(node);
1204 return m_pregeneratingReferencedNodes;
1205}
1206
1207void QSvgVisitorImpl::visitDefsNodeEnd(const QSvgDefs *node)
1208{
1209 Q_UNUSED(node);
1210}
1211
1212bool QSvgVisitorImpl::visitPatternNodeStart(const QSvgPattern *node)
1213{
1214 if (m_pregeneratingReferencedNodes) {
1215 handleBaseNodeSetup(node);
1216
1217 PatternNodeInfo info;
1218 fillCommonNodeInfo(node, info);
1219 fillAnimationInfo(node, info);
1220
1221 info.stage = StructureNodeStage::Start;
1222
1223 QSvgRectF r = node->rect();
1224 info.isPatternRectRelativeCoordinates = r.unitX() == QtSvg::UnitTypes::objectBoundingBox;
1225 info.patternRect = r;
1226
1227 if (node->contentUnits() == QtSvg::UnitTypes::objectBoundingBox)
1228 qCWarning(lcQuickVectorImage) << "Only user space content units supported for patterns";
1229
1230 return m_generator->generatePatternNode(info);
1231 } else {
1232 return false;
1233 }
1234}
1235
1236void QSvgVisitorImpl::visitPatternNodeEnd(const QSvgPattern *node)
1237{
1238 Q_ASSERT(m_pregeneratingReferencedNodes);
1239
1240 handleBaseNodeSetup(node);
1241
1242 PatternNodeInfo info;
1243 fillCommonNodeInfo(node, info);
1244 fillAnimationInfo(node, info);
1245
1246 QSvgRectF r = node->rect();
1247 info.isPatternRectRelativeCoordinates = r.unitX() == QtSvg::UnitTypes::objectBoundingBox;
1248 info.patternRect = r;
1249
1250 info.stage = StructureNodeStage::End;
1251
1252 m_generator->generatePatternNode(info);
1253}
1254
1255bool QSvgVisitorImpl::visitSymbolNodeStart(const QSvgSymbol *node)
1256{
1257 if (m_useLevel == 0)
1258 return false;
1259
1260 handleBaseNodeSetup(node);
1261
1262 StructureNodeInfo info;
1263 fillCommonNodeInfo(node, info);
1264 fillAnimationInfo(node, info);
1265
1266 QTransform oldTransform = info.transform.defaultValue().value<QTransform>();
1267 info.clipBox = oldTransform.mapRect(node->clipRect());
1268
1269 QTransform xform = node->aspectRatioTransform();
1270 if (!xform.isIdentity()) {
1271 info.isDefaultTransform = false;
1272 xform = xform * oldTransform;
1273 info.transform.setDefaultValue(QVariant::fromValue(xform));
1274 }
1276
1277 return m_generator->generateStructureNode(info);
1278}
1279
1280void QSvgVisitorImpl::visitSymbolNodeEnd(const QSvgSymbol *node)
1281{
1282 handleBaseNodeSetup(node);
1283
1284 StructureNodeInfo info;
1285 fillCommonNodeInfo(node, info);
1286 fillAnimationInfo(node, info);
1287
1288 info.clipBox = node->clipRect();
1290
1291 m_generator->generateStructureNode(info);
1292}
1293
1294bool QSvgVisitorImpl::visitMaskNodeStart(const QSvgMask *node)
1295{
1296 if (!m_pregeneratingReferencedNodes)
1297 return false;
1298
1299 handleBaseNodeSetup(node);
1300
1301 MaskNodeInfo info;
1302
1303 QSvgRectF r = node->rect();
1304 info.isMaskRectRelativeCoordinates = r.unitX() == QtSvg::UnitTypes::objectBoundingBox;
1305 info.maskRect = r;
1306
1308 node->contentUnits() == QtSvg::UnitTypes::objectBoundingBox;
1309
1310 fillCommonNodeInfo(node, info);
1311
1312 return m_generator->generateMaskNode(info);
1313}
1314
1315void QSvgVisitorImpl::visitMaskNodeEnd(const QSvgMask *node)
1316{
1317 MaskNodeInfo info;
1319
1320 QSvgRectF r = node->rect();
1321 info.isMaskRectRelativeCoordinates = r.unitX() == QtSvg::UnitTypes::objectBoundingBox;
1322 info.maskRect = r;
1324 node->contentUnits() == QtSvg::UnitTypes::objectBoundingBox;
1325 fillCommonNodeInfo(node, info);
1326
1327 m_generator->generateMaskNode(info);
1328
1329 handleBaseNodeEnd(node);
1330}
1331
1332bool QSvgVisitorImpl::visitFilterNodeStart(const QSvgFilterContainer *node)
1333{
1334 Q_UNUSED(node)
1335
1336 if (!m_pregeneratingReferencedNodes)
1337 return false;
1338
1339 if (!m_filterPrimitives.isEmpty()) {
1340 qCWarning(lcQuickVectorImage) << "Filter defined inside a filter";
1341 return false;
1342 }
1343
1344 return true;
1345}
1346
1347void QSvgVisitorImpl::visitFilterNodeEnd(const QSvgFilterContainer *node)
1348{
1349 if (m_filterPrimitives.isEmpty())
1350 return;
1351
1352 handleBaseNodeSetup(node);
1353
1354 FilterNodeInfo info;
1355 fillCommonNodeInfo(node, info);
1356
1357 info.filterRect = node->rect();
1358 if (node->filterUnits() == QtSvg::UnitTypes::objectBoundingBox)
1360
1361 bool generatedAlpha = false;
1362 for (const QSvgFeFilterPrimitive *filterPrimitive : std::as_const(m_filterPrimitives)) {
1363 if (filterPrimitive->requiresSourceAlpha() && !generatedAlpha) {
1364 FilterNodeInfo::FilterStep alphaStep;
1365 alphaStep.filterType = FilterNodeInfo::Type::ColorMatrix;
1366 alphaStep.csFilterParameter = FilterNodeInfo::CoordinateSystem::MatchFilterRect;
1367
1368 // Isolate alpha
1369 qreal values[] = { 0.0, 0.0, 0.0, 0.0, 0.0,
1370 0.0, 0.0, 0.0, 0.0, 0.0,
1371 0.0, 0.0, 0.0, 0.0, 0.0,
1372 0.0, 0.0, 0.0, 1.0, 0.0,
1373 0.0, 0.0, 0.0, 0.0, 0.0 };
1374 QGenericMatrix<5, 5, qreal> matrix(values);
1375 alphaStep.filterParameter = QVariant::fromValue(matrix);
1376 alphaStep.outputName = info.id + QStringLiteral("_source_alpha");
1377 generatedAlpha = true;
1378
1379 info.steps.append(alphaStep);
1380 }
1381
1382 fillFilterPrimitiveInfo(node, filterPrimitive, info);
1383 }
1384
1385 m_generator->generateFilterNode(info);
1386 m_filterPrimitives.clear();
1387}
1388
1389void QSvgVisitorImpl::fillFilterPrimitiveInfo(const QSvgFilterContainer *node,
1390 const QSvgFeFilterPrimitive *filterPrimitive,
1391 FilterNodeInfo &info)
1392{
1394 step.filterPrimitiveRect = filterPrimitive->rect();
1395
1396 step.outputName = info.id + QStringLiteral("_")
1397 + (filterPrimitive->result().isEmpty()
1398 ? QStringLiteral("output_") + QString::number(info.steps.size())
1399 : filterPrimitive->result());
1400
1401 auto findInput = [&info, &filterPrimitive](const QString &input, QString *outName) {
1402 const QString alphaSource = info.id + QStringLiteral("_source_alpha");
1403 if (input == QStringLiteral("SourceGraphic")) {
1405 } else if (input == QStringLiteral("SourceAlpha")) {
1406 *outName = alphaSource;
1408 } else if (info.steps.isEmpty()) {
1410 }
1411
1412 if (!input.isEmpty()) {
1413 *outName = info.id + QStringLiteral("_") + input;
1414 } else {
1415 bool insideMergeNode = filterPrimitive->type() == QSvgNode::FeMergenode;
1416 for (int i = info.steps.size() - 1; i >= 0; --i) {
1417 const auto &prevStep = info.steps.at(i);
1418 if (insideMergeNode && prevStep.filterType == FilterNodeInfo::Type::Merge) {
1419 insideMergeNode = false;
1420 continue;
1421 }
1422
1423 if (!prevStep.outputName.isEmpty() && prevStep.outputName != alphaSource) {
1424 *outName = prevStep.outputName;
1425 break;
1426 }
1427 }
1428 }
1429
1431 };
1432
1433 step.input1 = findInput(filterPrimitive->input(), &step.namedInput1);
1434
1435 if (node->primitiveUnits() == QtSvg::UnitTypes::objectBoundingBox)
1437
1438 // We special-case the default filter primitive rect as is done in Qt Svg.
1439 // The default is to match the filter's rect and this is represented by making
1440 // the types of the filter primitive's rect QtSvg::UnitTypes::unknown. Since
1441 // this is not generally handled in Qt Svg, we also just special case it here.
1442 if (node->primitiveUnits() == QtSvg::UnitTypes::userSpaceOnUse
1443 && filterPrimitive->rect().unitW() == QtSvg::UnitTypes::unknown) {
1445 }
1446
1447 switch (filterPrimitive->type()) {
1448 case QSvgNode::FeMerge:
1450 break;
1451 case QSvgNode::FeMergenode:
1453 break;
1454 case QSvgNode::FeBlend:
1455 {
1456 const QSvgFeBlend *blend = static_cast<const QSvgFeBlend *>(filterPrimitive);
1457 switch (blend->mode()) {
1458 case QSvgFeBlend::Mode::Normal:
1460 break;
1461 case QSvgFeBlend::Mode::Multiply:
1463 break;
1464 case QSvgFeBlend::Mode::Screen:
1466 break;
1467 case QSvgFeBlend::Mode::Darken:
1469 break;
1470 case QSvgFeBlend::Mode::Lighten:
1472 break;
1473 }
1474
1475 step.input2 = findInput(blend->input2(), &step.namedInput2);
1476 break;
1477 }
1478 case QSvgNode::FeComposite:
1479 {
1480 const QSvgFeComposite *composite = static_cast<const QSvgFeComposite *>(filterPrimitive);
1481 switch (composite->compositionOperator()) {
1482 case QSvgFeComposite::Operator::Over:
1484 break;
1485 case QSvgFeComposite::Operator::In:
1487 break;
1488 case QSvgFeComposite::Operator::Out:
1490 break;
1491 case QSvgFeComposite::Operator::Atop:
1493 break;
1494 case QSvgFeComposite::Operator::Xor:
1496 break;
1497 case QSvgFeComposite::Operator::Lighter:
1499 break;
1500 case QSvgFeComposite::Operator::Arithmetic:
1502 break;
1503 };
1504
1505 step.input2 = findInput(composite->input2(), &step.namedInput2);
1506 step.filterParameter = composite->k();
1507 break;
1508 }
1509 case QSvgNode::FeOffset:
1510 {
1511 const QSvgFeOffset *offset = static_cast<const QSvgFeOffset *>(filterPrimitive);
1513 step.filterParameter = QVariant::fromValue(QVector2D(offset->dx(), offset->dy()));
1514 break;
1515
1516 }
1517 case QSvgNode::FeColormatrix:
1518 {
1519 const QSvgFeColorMatrix *colorMatrix =
1520 static_cast<const QSvgFeColorMatrix *>(filterPrimitive);
1522 step.filterParameter = QVariant::fromValue(colorMatrix->matrix());
1523 break;
1524 }
1525
1526 case QSvgNode::FeGaussianblur:
1527 {
1528 const QSvgFeGaussianBlur *gaussianBlur =
1529 static_cast<const QSvgFeGaussianBlur *>(filterPrimitive);
1530
1531 if (gaussianBlur->edgeMode() == QSvgFeGaussianBlur::EdgeMode::Wrap)
1532 info.wrapMode = QSGTexture::Repeat;
1534 if (!qFuzzyCompare(gaussianBlur->stdDeviationX(), gaussianBlur->stdDeviationY()))
1535 qCWarning(lcQuickVectorImage) << "Separate X and Y deviations not supported for gaussian blur";
1536 step.filterParameter = std::max(gaussianBlur->stdDeviationX(),
1537 gaussianBlur->stdDeviationY());
1538 break;
1539 }
1540
1541 case QSvgNode::FeFlood:
1542 {
1543 const QSvgFeFlood *flood =
1544 static_cast<const QSvgFeFlood *>(filterPrimitive);
1545
1547 step.filterParameter = flood->color();
1548 break;
1549 }
1550 default:
1551 // Create a dummy filter node to make sure bindings still work for unsupported filters
1553 break;
1554 }
1555
1556 info.steps.append(step);
1557}
1558
1559bool QSvgVisitorImpl::visitFeFilterPrimitiveNodeStart(const QSvgFeFilterPrimitive *node)
1560{
1561 m_filterPrimitives.append(node);
1562 return true;
1563}
1564
1565void QSvgVisitorImpl::visitFeFilterPrimitiveNodeEnd(const QSvgFeFilterPrimitive *node)
1566{
1567 Q_UNUSED(node);
1568}
1569
1570bool QSvgVisitorImpl::visitStructureNodeStart(const QSvgStructureNode *node)
1571{
1572 Q_ASSERT(m_doc);
1573 constexpr bool forceSeparatePaths = false;
1574 handleBaseNodeSetup(node);
1575
1576 StructureNodeInfo info;
1577
1578 fillCommonNodeInfo(node, info);
1579 fillAnimationInfo(node, info);
1580 info.forceSeparatePaths = forceSeparatePaths;
1581 info.isPathContainer = isPathContainer(m_doc, node);
1582 if (!info.isDefaultOpacity || info.opacity.isAnimated())
1583 info.opacityGroupBounds = node->bounds(m_doc);
1585
1586 return m_generator->generateStructureNode(info);
1587}
1588
1589void QSvgVisitorImpl::visitStructureNodeEnd(const QSvgStructureNode *node)
1590{
1591 Q_ASSERT(m_doc);
1592 handleBaseNodeEnd(node);
1593 // qCDebug(lcQuickVectorGraphics) << "REVERT" << node->nodeId() << node->type() << (m_styleResolver->painter().pen().style() != Qt::NoPen) << m_styleResolver->painter().pen().color().name()
1594 // << (m_styleResolver->painter().pen().brush().style() != Qt::NoBrush) << m_styleResolver->painter().pen().brush().color().name();
1595
1596 StructureNodeInfo info;
1597 fillCommonNodeInfo(node, info);
1598 info.isPathContainer = isPathContainer(m_doc, node);
1600
1601 m_generator->generateStructureNode(info);
1602}
1603
1604QString QSvgVisitorImpl::nextNodeId() const
1605{
1606 return QStringLiteral("_qt_node%1").arg(m_nodeIdCounter++);
1607}
1608
1609bool QSvgVisitorImpl::visitDocumentNodeStart(const QSvgDocument *node)
1610{
1611 handleBaseNodeSetup(node);
1612
1613 StructureNodeInfo info;
1614 fillCommonNodeInfo(node, info);
1615 fillAnimationInfo(node, info);
1616
1617 const QSvgDocument *doc = static_cast<const QSvgDocument *>(node);
1618 info.size = doc->size();
1619 info.viewBox = doc->viewBox();
1620 info.isPathContainer = isPathContainer(doc, node);
1621 info.forceSeparatePaths = false;
1623
1624 if (m_generator->generateRootNode(info)) {
1625 pregenerateReferencedNodes(node);
1626 return true;
1627 } else {
1628 return false;
1629 }
1630}
1631
1632void QSvgVisitorImpl::visitDocumentNodeEnd(const QSvgDocument *node)
1633{
1634 handleBaseNodeEnd(node);
1635 qCDebug(lcQuickVectorImage) << "REVERT" << node->nodeId() << node->type() << (m_styleResolver->painter().pen().style() != Qt::NoPen)
1636 << m_styleResolver->painter().pen().color().name() << (m_styleResolver->painter().pen().brush().style() != Qt::NoBrush)
1637 << m_styleResolver->painter().pen().brush().color().name();
1638
1639 StructureNodeInfo info;
1640 fillCommonNodeInfo(node, info);
1642
1643 m_generator->generateRootNode(info);
1644}
1645
1646QString QSvgVisitorImpl::findOrCreateId(const QString &id)
1647{
1648 QString ret = m_idForNodeId.value(id);
1649 if (ret.isEmpty()) {
1650 ret = nextNodeId();
1651 m_idForNodeId.insert(id, ret);
1652 }
1653 return ret;
1654}
1655
1656QString QSvgVisitorImpl::findOrCreateId(const QSvgNode *node, const QString &nodeId)
1657{
1658 QString key = nodeId;
1659 const QSvgNode *n = m_nodesForKeys.value(key);
1660 if (key.isEmpty() || (n != nullptr && n != node))
1661 key = QString::number(quintptr(node), 16);
1662
1663 m_nodesForKeys.insert(key, node);
1664 return findOrCreateId(key);
1665}
1666
1667void QSvgVisitorImpl::fillCommonNodeInfo(const QSvgNode *node, NodeInfo &info, const QString &idSuffix)
1668{
1669 const QString nodeId = scrub(node->nodeId());
1670 info.id = findOrCreateId(node, nodeId);
1671
1672 // Internal disambiguation when multiple items come from the same node
1673 info.id += idSuffix;
1674
1675 if (!m_linkSuffix.isEmpty())
1676 info.id += m_linkSuffix;
1677
1678 info.nodeId = nodeId;
1679 info.typeName = node->typeName();
1680 info.isDefaultTransform = node->style().isDefaultProperty(QSvgStyleProperty::Transform);
1681
1682 auto transform = static_cast<QSvgTransformStyle *>(node->style().property(QSvgStyleProperty::Transform));
1683 QTransform xf = !info.isDefaultTransform ? transform->qtransform() : QTransform();
1684 info.transform.setDefaultValue(QVariant::fromValue(xf));
1685
1686 auto opacity = static_cast<QSvgOpacityStyle *>(node->style().property(QSvgStyleProperty::Opacity));
1687 info.isDefaultOpacity = node->style().isDefaultProperty(QSvgStyleProperty::Opacity);
1688 info.opacity.setDefaultValue(!info.isDefaultOpacity ? opacity->opacity() : 1.0);
1689 info.isVisible = node->isVisible();
1690 info.isDisplayed = node->displayMode() != QSvgNode::DisplayMode::NoneMode;
1691
1692 if (node->hasFilter()
1693 || node->hasMask()
1694 || node->type() == QSvgNode::Type::Mask
1695 || node->type() == QSvgNode::Type::Pattern) {
1696 QImage dummy(1, 1, QImage::Format_RGB32);
1697 QPainter p(&dummy);
1698 p.setPen(QPen(Qt::NoPen));
1699 QRectF b;
1700 if (m_doc) {
1701 QSvgExtraStates states(m_doc);
1702 b = node->internalBounds(&p, states);
1703 }
1704 info.bounds = b;
1705 }
1706
1707 if (node->hasMask())
1708 info.maskId = findOrCreateId(node->maskId());
1709
1710 if (node->hasFilter())
1711 info.filterId = findOrCreateId(node->filterId());
1712}
1713
1714QList<QSvgVisitorImpl::AnimationPair> QSvgVisitorImpl::collectAnimations(const QSvgNode *node,
1715 const QString &propertyName)
1716{
1717 Q_ASSERT(m_doc);
1718 QList<AnimationPair> ret;
1719 const QList<QSvgAbstractAnimation *> animations = m_doc->animator()->animationsForNode(node);
1720 for (const QSvgAbstractAnimation *animation : animations) {
1721 const QList<QSvgAbstractAnimatedProperty *> properties = animation->properties();
1722 for (const QSvgAbstractAnimatedProperty *property : properties) {
1723 if (property->propertyName() == propertyName)
1724 ret.append(std::make_pair(animation, property));
1725 }
1726 }
1727
1728 return ret;
1729}
1730
1731void QSvgVisitorImpl::applyAnimationsToProperty(const QList<AnimationPair> &animations,
1732 QQuickAnimatedProperty *outProperty,
1733 std::function<QVariant(const QSvgAbstractAnimatedProperty *, int index, int animationIndex)> calculateValue)
1734{
1735 qCDebug(lcVectorImageAnimations) << "Applying animations to property with default value"
1736 << outProperty->defaultValue();
1737 for (auto it = animations.constBegin(); it != animations.constEnd(); ++it) {
1738 qCDebug(lcVectorImageAnimations) << " -> Add animation";
1739 const QSvgAbstractAnimation *animation = it->first;
1740 const QSvgAbstractAnimatedProperty *property = it->second;
1741
1742 const int start = animation->start();
1743 const int repeatCount = animation->iterationCount();
1744 const int duration = animation->duration();
1745
1746 bool freeze = false;
1747 bool replace = true;
1748 if (animation->animationType() == QSvgAbstractAnimation::SMIL) {
1749 const QSvgAnimateNode *animateNode = static_cast<const QSvgAnimateNode *>(animation);
1750 freeze = animateNode->fill() == QSvgAnimateNode::Freeze;
1751 replace = animateNode->additiveType() == QSvgAnimateNode::Replace;
1752 }
1753
1754 qCDebug(lcVectorImageAnimations) << " -> Start:" << start
1755 << ", repeatCount:" << repeatCount
1756 << ", freeze:" << freeze
1757 << ", replace:" << replace;
1758
1759 QList<qreal> propertyKeyFrames = property->keyFrames();
1760 QList<QQuickAnimatedProperty::PropertyAnimation> outAnimations;
1761
1762 // For transform animations, we register the type of the transform in the animation
1763 // (this assumes that each animation is only for a single part of the transform)
1764 if (property->type() == QSvgAbstractAnimatedProperty::Transform) {
1765 const auto *transformProperty = static_cast<const QSvgAnimatedPropertyTransform *>(property);
1766 const auto &components = transformProperty->components();
1767 Q_ASSERT(q20::cmp_greater_equal(components.size(),transformProperty->transformCount()));
1768 for (uint i = 0; i < transformProperty->transformCount(); ++i) {
1769 QQuickAnimatedProperty::PropertyAnimation outAnimation;
1770 outAnimation.repeatCount = repeatCount;
1771 outAnimation.startOffset = start;
1772 if (freeze)
1773 outAnimation.flags |= QQuickAnimatedProperty::PropertyAnimation::FreezeAtEnd;
1774 if (replace)
1775 outAnimation.flags |= QQuickAnimatedProperty::PropertyAnimation::ReplacePreviousAnimations;
1776 switch (components.at(i).type) {
1777 case QSvgAnimatedPropertyTransform::TransformComponent::Translate:
1778 outAnimation.subtype = QTransform::TxTranslate;
1779 break;
1780 case QSvgAnimatedPropertyTransform::TransformComponent::Scale:
1781 outAnimation.subtype = QTransform::TxScale;
1782 break;
1783 case QSvgAnimatedPropertyTransform::TransformComponent::Rotate:
1784 outAnimation.subtype = QTransform::TxRotate;
1785 break;
1786 case QSvgAnimatedPropertyTransform::TransformComponent::Skew:
1787 outAnimation.subtype = QTransform::TxShear;
1788 break;
1789 default:
1790 qCWarning(lcQuickVectorImage()) << "Unhandled transform type:" << components.at(i).type;
1791 break;
1792 }
1793
1794 qDebug(lcVectorImageAnimations) << " -> Property type:"
1795 << property->type()
1796 << " name:"
1797 << property->propertyName()
1798 << " animation subtype:"
1799 << outAnimation.subtype;
1800
1801 outAnimations.append(outAnimation);
1802 }
1803 } else {
1804 QQuickAnimatedProperty::PropertyAnimation outAnimation;
1805 outAnimation.repeatCount = repeatCount;
1806 outAnimation.startOffset = start;
1807 if (freeze)
1808 outAnimation.flags |= QQuickAnimatedProperty::PropertyAnimation::FreezeAtEnd;
1809
1810 qDebug(lcVectorImageAnimations) << " -> Property type:"
1811 << property->type()
1812 << " name:"
1813 << property->propertyName();
1814
1815 outAnimations.append(outAnimation);
1816 }
1817
1818 outProperty->beginAnimationGroup();
1819 const auto animationEasing = easingForAnimation(animation->easing(), animation->animationType());
1820 for (int i = 0; i < outAnimations.size(); ++i) {
1821 QQuickAnimatedProperty::PropertyAnimation outAnimation = outAnimations.at(i);
1822
1823 for (int j = 0; j < propertyKeyFrames.size(); ++j) {
1824 const int time = qRound(propertyKeyFrames.at(j) * duration);
1825
1826 const QVariant value = calculateValue(property, j, i);
1827 outAnimation.frames[time] = value;
1828
1829 const QSvgEasingInterface *easingInterface = j > 0 ? property->easingAt(j - 1) : nullptr;
1830 outAnimation.easingPerFrame[time] = easingInterface != nullptr
1831 ? easingForAnimation(easingInterface, animation->animationType())
1832 : animationEasing;
1833
1834 qCDebug(lcVectorImageAnimations) << " -> Frame " << time << " is " << value;
1835 }
1836
1837 outProperty->addAnimation(outAnimation);
1838 }
1839 }
1840}
1841
1842QBezier QSvgVisitorImpl::easingForAnimation(const QSvgEasingInterface *easingInterface,
1843 QSvgAbstractAnimation::AnimationType type)
1844{
1845 constexpr QPointF startControlPoint(0, 0);
1846 constexpr QPointF endControlPoint(1, 1);
1847 constexpr QPointF easeC1(0.25, 0.1);
1848 constexpr QPointF easeC2(0.25, 1);
1849
1850 QBezier easing = QBezier::fromPoints(startControlPoint, startControlPoint, endControlPoint, endControlPoint);
1851
1852#if QT_CONFIG(cssparser)
1853 if (type == QSvgAbstractAnimation::CSS) {
1854 const QSvgCssEasing *cssEasing = static_cast<const QSvgCssEasing *>(easingInterface);
1855 switch (cssEasing->easingFunction()) {
1856 case QSvgCssValues::EasingFunction::Ease:
1857 case QSvgCssValues::EasingFunction::EaseIn:
1858 case QSvgCssValues::EasingFunction::EaseOut:
1859 case QSvgCssValues::EasingFunction::EaseInOut:
1860 case QSvgCssValues::EasingFunction::CubicBezier:
1861 case QSvgCssValues::EasingFunction::Linear:
1862 {
1863 const QSvgCssCubicBezierEasing *cssCubicEasing = static_cast<const QSvgCssCubicBezierEasing *>(cssEasing);
1864 QPointF c1 = cssCubicEasing->c1();
1865 QPointF c2 = cssCubicEasing->c2();
1866 easing = QBezier::fromPoints(startControlPoint, c1, c2, endControlPoint);
1867 break;
1868 }
1869 case QSvgCssValues::EasingFunction::Steps:
1870 {
1871 qCDebug(lcVectorImageAnimations) << "Step easing is not supported reverting to default.";
1872 easing = QBezier::fromPoints(startControlPoint, easeC1, easeC2, endControlPoint);
1873 break;
1874 }
1875 }
1876 }
1877#endif
1878
1879 return easing;
1880}
1881
1882void QSvgVisitorImpl::fillColorAnimationInfo(const QSvgNode *node, PathNodeInfo &info)
1883{
1884 // Collect all animations affecting fill
1885 {
1886 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("fill"));
1887 if (!animations.isEmpty())
1888 applyAnimationsToProperty(animations, &info.fillColor, calculateInterpolatedValue);
1889 }
1890
1891 {
1892 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("fill-opacity"));
1893 if (!animations.isEmpty())
1894 applyAnimationsToProperty(animations, &info.fillOpacity, calculateInterpolatedValue);
1895 }
1896
1897 {
1898 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("stroke"));
1899 if (!animations.isEmpty())
1900 applyAnimationsToProperty(animations, &info.strokeStyle.color, calculateInterpolatedValue);
1901 }
1902
1903 {
1904 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("stroke-opacity"));
1905 if (!animations.isEmpty())
1906 applyAnimationsToProperty(animations, &info.strokeStyle.opacity, calculateInterpolatedValue);
1907 }
1908}
1909
1910void QSvgVisitorImpl::fillTransformAnimationInfo(const QSvgNode *node, NodeInfo &info)
1911{
1912 qCDebug(lcVectorImageAnimations) << "Applying transform animations to property with default value"
1913 << info.transform.defaultValue();
1914
1915 auto calculateValue = [](const QSvgAbstractAnimatedProperty *property, int index, int animationIndex) {
1916 if (property->type() != QSvgAbstractAnimatedProperty::Transform)
1917 return QVariant{};
1918
1919 const auto *transformProperty = static_cast<const QSvgAnimatedPropertyTransform *>(property);
1920 const auto &components = transformProperty->components();
1921
1922 const int componentIndex = index * transformProperty->transformCount() + animationIndex;
1923
1924 QVariantList parameters;
1925
1926 const QSvgAnimatedPropertyTransform::TransformComponent &component = components.at(componentIndex);
1927 switch (component.type) {
1928 case QSvgAnimatedPropertyTransform::TransformComponent::Translate:
1929 parameters.append(QVariant::fromValue(QPointF(component.values.value(0),
1930 component.values.value(1))));
1931 break;
1932 case QSvgAnimatedPropertyTransform::TransformComponent::Rotate:
1933 parameters.append(QVariant::fromValue(QPointF(component.values.value(1),
1934 component.values.value(2))));
1935 parameters.append(QVariant::fromValue(component.values.value(0)));
1936 break;
1937 case QSvgAnimatedPropertyTransform::TransformComponent::Scale:
1938 parameters.append(QVariant::fromValue(QPointF(component.values.value(0),
1939 component.values.value(1))));
1940 break;
1941 case QSvgAnimatedPropertyTransform::TransformComponent::Skew:
1942 parameters.append(QVariant::fromValue(QPointF(component.values.value(0),
1943 component.values.value(1))));
1944 break;
1945 default:
1946 qCWarning(lcVectorImageAnimations) << "Unhandled transform type:" << component.type;
1947 };
1948
1949 return QVariant::fromValue(parameters);
1950 };
1951
1952
1953 {
1954 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("transform"));
1955 if (!animations.isEmpty())
1956 applyAnimationsToProperty(animations, &info.transform, calculateValue);
1957 }
1958}
1959
1960void QSvgVisitorImpl::fillMotionPathAnimationInfo(const QSvgNode *node, NodeInfo &info)
1961{
1962 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("offset-distance"));
1963 auto offset = static_cast<QSvgOffsetStyle *>(node->style().property(QSvgStyleProperty::Offset));
1964
1965 if (animations.isEmpty())
1966 return;
1967
1968 if (!offset) {
1969 qCWarning(lcQuickVectorImage) << "Motion path animation: No offset path";
1970 return;
1971 }
1972
1973 if (animations.size() > 1) {
1974 qCWarning(lcQuickVectorImage)
1975 << "Not supported: More than one offset path animation on same node";
1976 }
1977
1978 const AnimationPair &animationPair = animations.first();
1979
1980 const QSvgAbstractAnimation *animation = animationPair.first;
1981 const QSvgAbstractAnimatedProperty *property = animationPair.second;
1982
1983 const int start = animation->start();
1984 const int repeatCount = animation->iterationCount();
1985 const int duration = animation->duration();
1986
1987 qCDebug(lcVectorImageAnimations) << "Motion path animation:"
1988 << "start == " << start
1989 << ", repeatCount == " << repeatCount
1990 << "; duration == " << duration;
1991
1992
1993 QQuickAnimatedProperty::PropertyAnimation outAnimation;
1994 outAnimation.repeatCount = repeatCount;
1995 outAnimation.startOffset = start;
1996
1997 QPainterPath originalPath = offset->path();
1998
1999 qreal baseRotation;
2000 bool adaptAngle;
2001 switch (offset->rotateType()) {
2002 case QtSvg::OffsetRotateType::Auto:
2003 adaptAngle = true;
2004 baseRotation = 0.0;
2005 break;
2006 case QtSvg::OffsetRotateType::Angle:
2007 adaptAngle = false;
2008 baseRotation = offset->rotateAngle();
2009 break;
2010 case QtSvg::OffsetRotateType::AutoAngle:
2011 adaptAngle = true;
2012 baseRotation = offset->rotateAngle();
2013 break;
2014 case QtSvg::OffsetRotateType::Reverse:
2015 adaptAngle = true;
2016 baseRotation = 180.0;
2017 break;
2018 case QtSvg::OffsetRotateType::ReverseAngle:
2019 adaptAngle = true;
2020 baseRotation = offset->rotateAngle() + 180.0f;
2021 break;
2022 default:
2023 Q_UNREACHABLE();
2024 }
2025
2026 // Default value holds additional parameters
2027 QVariantList params({ QVariant::fromValue(originalPath), adaptAngle, baseRotation });
2028 info.motionPath.setDefaultValue(params);
2029
2030 const QList<qreal> propertyKeyFrames = property->keyFrames();
2031 outAnimation.frames[0] = qreal(0);
2032 const auto animationEasing = easingForAnimation(animation->easing(), animation->animationType());
2033 for (int j = 0; j < propertyKeyFrames.size(); ++j) {
2034 const int time = qRound(propertyKeyFrames.at(j) * duration);
2035 if (time >= 0) {
2036 qreal t = calculateInterpolatedValue(property, j, 0).toReal();
2037 outAnimation.frames[time] = t;
2038
2039 const QSvgEasingInterface *easingInterface = j > 0 ? property->easingAt(j - 1) : nullptr;
2040 outAnimation.easingPerFrame[time] = easingInterface != nullptr
2041 ? easingForAnimation(easingInterface, animation->animationType())
2042 : animationEasing;
2043
2044 qCDebug(lcVectorImageAnimations) << " -> Frame " << time << " is " << t;
2045 }
2046 }
2047
2048 info.motionPath.addAnimation(outAnimation);
2049}
2050
2051void QSvgVisitorImpl::fillPathAnimationInfo(const QSvgNode *node, PathNodeInfo &info)
2052{
2053 fillColorAnimationInfo(node, info);
2054 fillAnimationInfo(node, info);
2055}
2056
2057void QSvgVisitorImpl::fillAnimationInfo(const QSvgNode *node, NodeInfo &info)
2058{
2059 {
2060 QList<AnimationPair> animations = collectAnimations(node, QStringLiteral("opacity"));
2061 if (!animations.isEmpty())
2062 applyAnimationsToProperty(animations, &info.opacity, calculateInterpolatedValue);
2063 }
2064
2065 fillTransformAnimationInfo(node, info);
2066 fillMotionPathAnimationInfo(node, info);
2067}
2068
2069void QSvgVisitorImpl::handleBaseNodeSetup(const QSvgNode *node)
2070{
2071 qCDebug(lcQuickVectorImage) << "Before SETUP" << node << "fill" << m_styleResolver->currentFillColor()
2072 << "stroke" << m_styleResolver->currentStrokeColor() << m_styleResolver->currentStrokeWidth()
2073 << node->nodeId() << " type: " << node->typeName() << " " << node->type();
2074
2075 node->applyStyle(&m_styleResolver->painter(), m_styleResolver->states());
2076
2077 qCDebug(lcQuickVectorImage) << "After SETUP" << node << "fill" << m_styleResolver->currentFillColor()
2078 << "stroke" << m_styleResolver->currentStrokeColor()
2079 << m_styleResolver->currentStrokeWidth() << node->nodeId();
2080}
2081
2082void QSvgVisitorImpl::handleBaseNode(const QSvgNode *node)
2083{
2084 NodeInfo info;
2085 fillCommonNodeInfo(node, info);
2086
2087 m_generator->generateNodeBase(info);
2088}
2089
2090void QSvgVisitorImpl::handleBaseNodeEnd(const QSvgNode *node)
2091{
2092 node->revertStyle(&m_styleResolver->painter(), m_styleResolver->states());
2093
2094 qCDebug(lcQuickVectorImage) << "After END" << node << "fill" << m_styleResolver->currentFillColor()
2095 << "stroke" << m_styleResolver->currentStrokeColor() << m_styleResolver->currentStrokeWidth()
2096 << node->nodeId();
2097}
2098
2099void QSvgVisitorImpl::handlePathNode(const QSvgNode *node, const QPainterPath &path)
2100{
2101 handleBaseNodeSetup(node);
2102
2103 PathNodeInfo info;
2104 fillCommonNodeInfo(node, info);
2105
2106 if (node->hasMarkerStart())
2107 info.markerStartId = findOrCreateId(node->markerStartId());
2108
2109 if (node->hasMarkerMid())
2110 info.markerMidId = findOrCreateId(node->markerMidId());
2111
2112 if (node->hasMarkerEnd())
2113 info.markerEndId = findOrCreateId(node->markerEndId());
2114
2115 const QGradient *strokeGradient = m_styleResolver->currentStrokeGradient();
2116 auto strokeStyle = static_cast<QSvgStrokeStyle *>(node->style().property(QSvgStyleProperty::Stroke));
2117 bool hasStrokePattern = strokeStyle
2118 && strokeStyle->paintServer()
2119 && strokeStyle->paintServer()->type() == QSvgPaintServer::Type::Pattern;
2120
2121 info.path.setDefaultValue(QVariant::fromValue(path));
2122 info.fillColor.setDefaultValue(m_styleResolver->currentFillColor());
2123 if (strokeGradient != nullptr)
2124 info.strokeGrad = *strokeGradient;
2125
2126 if (!hasStrokePattern) {
2127 info.strokeStyle = StrokeStyle::fromPen(m_styleResolver->currentStroke());
2128 info.strokeStyle.color.setDefaultValue(m_styleResolver->currentStrokeColor());
2129 }
2130 if (m_styleResolver->currentFillGradient() != nullptr)
2131 info.grad = m_styleResolver->applyOpacityToGradient(*m_styleResolver->currentFillGradient(), m_styleResolver->currentFillOpacity());
2132 info.fillTransform = m_styleResolver->currentFillTransform();
2133
2134 auto fillStyle = static_cast<QSvgFillStyle *>(node->style().property(QSvgStyleProperty::Fill));
2135 if (fillStyle) {
2136 info.fillRule = fillStyle->fillRule();
2137
2138 if (fillStyle->paintServer()
2139 && fillStyle->paintServer()->type() == QSvgPaintServer::Type::Pattern) {
2140 QSvgPatternPaint *paintServer = static_cast<QSvgPatternPaint *>(fillStyle->paintServer());
2141 info.patternId = findOrCreateId(paintServer->patternNode()->nodeId());
2142
2143 // The fill transform in the style resolver is a calculated transform which contains
2144 // the inverse of the QPainter's world transform at the given time to negate any other
2145 // transform set. We avoid this by generating the pattern definition in isolation and
2146 // ignore its transform, so we just use the raw pattern transform from the input here.
2147 info.fillTransform = paintServer->patternNode()->transform();
2148 }
2149 }
2150
2151 fillPathAnimationInfo(node, info);
2152
2153 m_generator->generatePath(info);
2154
2155 if (hasStrokePattern) {
2156 PathNodeInfo strokeInfo;
2157 fillCommonNodeInfo(node, strokeInfo, QStringLiteral("_stroke"));
2158
2159 QSvgPatternPaint *paintServer = static_cast<QSvgPatternPaint *>(strokeStyle->paintServer());
2160 strokeInfo.patternId = findOrCreateId(paintServer->patternNode()->nodeId());
2161 strokeInfo.fillTransform = paintServer->patternNode()->transform();
2162
2163 QPainterPathStroker stroker(m_styleResolver->currentStroke());
2164 strokeInfo.path.setDefaultValue(QVariant::fromValue(stroker.createStroke(path)));
2165 m_generator->generatePath(strokeInfo);
2166 }
2167
2168 handleBaseNodeEnd(node);
2169}
2170
2171void QSvgVisitorImpl::fillMarkerInfo(const QSvgMarker *node, MarkerNodeInfo &info)
2172{
2173 QTransform oldTransform = info.transform.defaultValue().value<QTransform>();
2174
2175 info.markerSize = node->rect().size();
2176 info.anchorPoint = node->refP();
2177 info.clipBox = oldTransform.mapRect(node->clipRect());
2178 info.viewBox = node->viewBox();
2179 switch (node->orientation()) {
2180 case QSvgMarker::Orientation::Auto:
2182 break;
2183 case QSvgMarker::Orientation::AutoStartReverse:
2185 break;
2186 case QSvgMarker::Orientation::Value:
2188 break;
2189 }
2190
2191 switch (node->markerUnits()) {
2192 case QSvgMarker::MarkerUnits::UserSpaceOnUse:
2194 break;
2195 case QSvgMarker::MarkerUnits::StrokeWidth:
2197 break;
2198 }
2199
2200 info.angle = node->orientationAngle();
2201
2202 QTransform xform = node->aspectRatioTransform();
2203 if (!xform.isIdentity()) {
2204 info.isDefaultTransform = false;
2205 xform = xform * oldTransform;
2206 info.transform.setDefaultValue(QVariant::fromValue(xform));
2207 }
2208
2209 info.preserveAspectRatio = MarkerNodeInfo::PreserveAspectRatio(node->preserveAspectRatios().toInt());
2210}
2211
2212bool QSvgVisitorImpl::visitMarkerNodeStart(const QSvgMarker *node)
2213{
2214 if (!m_pregeneratingReferencedNodes)
2215 return false;
2216
2217 handleBaseNodeSetup(node);
2218
2219 MarkerNodeInfo info;
2220
2221 fillCommonNodeInfo(node, info);
2222 fillAnimationInfo(node, info);
2223 fillMarkerInfo(node, info);
2224 info.stage = StructureNodeStage::Start;
2225
2226 return m_generator->generateMarkerNode(info);
2227}
2228
2229void QSvgVisitorImpl::visitMarkerNodeEnd(const QSvgMarker *node)
2230{
2231 handleBaseNodeEnd(node);
2232
2233 MarkerNodeInfo info;
2234 fillCommonNodeInfo(node, info);
2235 fillMarkerInfo(node, info);
2236 info.stage = StructureNodeStage::End;
2237
2238 m_generator->generateMarkerNode(info);
2239}
2240
2241QT_END_NAMESPACE
const QGradient * currentFillGradient() const
const QGradient * currentStrokeGradient() const
QColor currentFillColor() const
QSvgExtraStates & states()
static QGradient applyOpacityToGradient(const QGradient &gradient, float opacity)
QTransform currentFillTransform() const
QPen currentStroke() const
qreal currentFillOpacity() const
float currentStrokeWidth() const
QSvgExtraStates m_svgState
QSvgStyleResolver(const QSvgDocument *doc)
QColor currentStrokeColor() const
bool visitFilterNodeStart(const QSvgFilterContainer *node) override
void visitPolygonNode(const QSvgPolygon *node) override
bool visitSwitchNodeStart(const QSvgSwitch *node) override
void visitMaskNodeEnd(const QSvgMask *node) override
void visitEllipseNode(const QSvgEllipse *node) override
void visitPathNode(const QSvgPath *node) override
void visitMarkerNodeEnd(const QSvgMarker *node) override
bool visitDefsNodeStart(const QSvgDefs *node) override
void visitDefsNodeEnd(const QSvgDefs *node) override
bool visitMaskNodeStart(const QSvgMask *node) override
void visitDocumentNodeEnd(const QSvgDocument *node) override
~QSvgVisitorImpl() override
void visitStructureNodeEnd(const QSvgStructureNode *node) override
void visitRectNode(const QSvgRect *node) override
void visitFeFilterPrimitiveNodeEnd(const QSvgFeFilterPrimitive *node) override
void visitLineNode(const QSvgLine *node) override
void visitNode(const QSvgNode *node) override
bool visitMarkerNodeStart(const QSvgMarker *node) override
void visitPolylineNode(const QSvgPolyline *node) override
void visitUseNode(const QSvgUse *node) override
QSvgVisitorImpl(const QQuickVectorImageSource &source, QQuickGenerator *generator, bool assumeTrustedSource)
bool visitSymbolNodeStart(const QSvgSymbol *node) override
void visitPatternNodeEnd(const QSvgPattern *) override
bool visitDocumentNodeStart(const QSvgDocument *node) override
void visitImageNode(const QSvgImage *node) override
void visitFilterNodeEnd(const QSvgFilterContainer *node) override
bool visitPatternNodeStart(const QSvgPattern *) override
void visitTextNode(const QSvgText *node) override
void visitSwitchNodeEnd(const QSvgSwitch *node) override
void visitSymbolNodeEnd(const QSvgSymbol *node) override
bool visitFeFilterPrimitiveNodeStart(const QSvgFeFilterPrimitive *node) override
bool visitStructureNodeStart(const QSvgStructureNode *node) override
Combined button and popup list for selecting options.
static QString scrub(const QString &raw)
static bool isStructureNode(const QSvgNode *node)
static void recurseSvgNodes(const QSvgNode *root, const std::function< void(const QSvgNode *)> &fnc)
static QVariant calculateInterpolatedValue(const QSvgAbstractAnimatedProperty *property, int index, int)