8#include <private/qsgcurveprocessor_p.h>
9#include <private/qquickshape_p.h>
10#include <private/qquadpath_p.h>
11#include <private/qquickitem_p.h>
12#include <private/qquickimagebase_p_p.h>
13#include <private/qquicktext_p.h>
14#include <private/qquicktranslate_p.h>
15#include <private/qquickimage_p.h>
17#include <QtCore/qloggingcategory.h>
18#include <QtCore/qdir.h>
19#include <QtCore/qstandardpaths.h>
23using namespace Qt::StringLiterals;
28 s.replace(QLatin1Char(
'\\'), QLatin1String(
"\\\\"));
29 s.replace(QLatin1Char(
'"'), QLatin1String(
"\\\""));
34QQuickAnimatedProperty::PropertyAnimation QQuickAnimatedProperty::PropertyAnimation::simplified()
const
36 QQuickAnimatedProperty::PropertyAnimation res = *
this;
37 int consecutiveEquals = 0;
38 int prevTimePoint = -1;
40 for (
const auto &[timePoint, value] : frames.asKeyValueRange()) {
41 if (value != prevValue) {
42 consecutiveEquals = 1;
44 }
else if (consecutiveEquals < 2) {
48 res.frames.remove(prevTimePoint);
49 res.easingPerFrame.remove(prevTimePoint);
51 prevTimePoint = timePoint;
57QQuickQmlGenerator::QQuickQmlGenerator(
const QString fileName, QQuickVectorImageGenerator::GeneratorFlags flags,
const QString &outFileName)
58 : QQuickGenerator(fileName, flags)
59 , outputFileName(outFileName)
61 m_result.open(QIODevice::ReadWrite);
62 m_oldIndentLevels.push(0);
64 if (outFileName.isEmpty()) {
65 setRetainFilePaths(
true);
66 setAssetFileDirectory(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
67 setAssetFilePrefix(QStringLiteral(
"_qt_vectorimage_"));
68 setUrlPrefix(QStringLiteral(
"file:"));
72QQuickQmlGenerator::~QQuickQmlGenerator()
76bool QQuickQmlGenerator::save()
78 if (Q_UNLIKELY(errorState()))
82 if (!outputFileName.isEmpty()) {
83 QFileInfo fileInfo(outputFileName);
84 QDir dir(fileInfo.absolutePath());
85 if (!dir.exists() && !dir.mkpath(QStringLiteral(
"."))) {
86 qCWarning(lcQuickVectorImage) <<
"Failed to create path" << dir.absolutePath();
89 QFile outFile(outputFileName);
90 if (outFile.open(QIODevice::WriteOnly)) {
91 outFile.write(m_result.data());
94 qCWarning(lcQuickVectorImage) <<
"Failed to write to file" << outFile.fileName();
100 if (lcQuickVectorImage().isDebugEnabled())
101 qCDebug(lcQuickVectorImage).noquote() << m_result.data().left(300);
106void QQuickQmlGenerator::setShapeTypeName(
const QString &name)
108 m_shapeTypeName = name.toLatin1();
111QString QQuickQmlGenerator::shapeTypeName()
const
113 return QString::fromLatin1(m_shapeTypeName);
116void QQuickQmlGenerator::setCommentString(
const QString commentString)
118 m_commentString = commentString;
121QString QQuickQmlGenerator::commentString()
const
123 return m_commentString;
126QString QQuickQmlGenerator::generateNodeBase(
const NodeInfo &info,
const QString &idSuffix)
128 static qint64 maxNodes = qEnvironmentVariableIntegerValue(
"QT_QUICKVECTORIMAGE_MAX_NODES").value_or(10000);
129 if (Q_UNLIKELY(!checkSanityLimit(++m_nodeCounter, maxNodes,
"nodes"_L1)))
132 if (!info.nodeId.isEmpty())
133 stream() <<
"objectName: \"" << info.nodeId <<
"\"";
135 if (!info.id.isEmpty())
136 stream() <<
"id: " << info.id << idSuffix;
138 if (!info.bounds.isNull() || !info.boundsReferenceId.isEmpty()) {
139 stream() <<
"property var originalBounds: ";
140 if (!info.bounds.isNull()) {
141 stream(SameLine) <<
"Qt.rect(" << info.bounds.x() <<
", " << info.bounds.y() <<
", "
142 << info.bounds.width() <<
", " << info.bounds.height() <<
")";
144 stream(SameLine) << info.boundsReferenceId <<
".originalBounds";
146 stream() <<
"width: originalBounds.width";
147 stream() <<
"height: originalBounds.height";
150 stream() <<
"transformOrigin: Item.TopLeft";
152 if (info.filterId.isEmpty() && info.maskId.isEmpty()) {
153 if (!info.isDefaultOpacity)
154 stream() <<
"opacity: " << info.opacity.defaultValue().toReal();
155 generateItemAnimations(info.id, info);
161void QQuickQmlGenerator::generateNodeEnd(
const NodeInfo &info)
163 if (Q_UNLIKELY(errorState()))
167 generateShaderUse(info);
170void QQuickQmlGenerator::generateItemAnimations(
const QString &idString,
const NodeInfo &info)
172 const bool hasTransform = info.transform.isAnimated()
173 || !info.maskId.isEmpty()
174 || !info.filterId.isEmpty()
175 || !info.isDefaultTransform
176 || !info.transformReferenceId.isEmpty()
177 || info.motionPath.isAnimated();
180 stream() <<
"transform: TransformGroup {";
183 bool hasNonConstantTransform =
false;
184 int earliestOverrideGroup = -1;
186 if (!idString.isEmpty()) {
187 stream() <<
"id: " << idString <<
"_transform_base_group";
189 if (!info.maskId.isEmpty() || !info.filterId.isEmpty())
190 stream() <<
"Translate { x: " << idString <<
".sourceX; y: " << idString <<
".sourceY }";
192 if (info.transform.isAnimated()) {
193 for (
int groupIndex = 0; groupIndex < info.transform.animationGroupCount(); ++groupIndex) {
194 stream() <<
"TransformGroup {";
197 if (!idString.isEmpty())
198 stream() <<
"id: " << idString <<
"_transform_group_" << groupIndex;
200 int animationStart = info.transform.animationGroup(groupIndex);
201 int nextAnimationStart = groupIndex + 1 < info.transform.animationGroupCount()
202 ? info.transform.animationGroup(groupIndex + 1)
203 : info.transform.animationCount();
205 const QQuickAnimatedProperty::PropertyAnimation &firstAnimation = info.transform.animation(animationStart);
206 const bool replace = firstAnimation.flags & QQuickAnimatedProperty::PropertyAnimation::ReplacePreviousAnimations;
207 if (replace && earliestOverrideGroup < 0)
208 earliestOverrideGroup = groupIndex;
210 for (
int i = nextAnimationStart - 1; i >= animationStart; --i) {
211 const QQuickAnimatedProperty::PropertyAnimation &animation = info.transform.animation(i);
212 if (animation.frames.isEmpty())
215 const QVariantList ¶meters = animation.frames.first().value<QVariantList>();
216 switch (animation.subtype) {
217 case QTransform::TxTranslate:
218 if (animation.isConstant()) {
219 const QPointF translation = parameters.value(0).value<QPointF>();
220 if (!translation.isNull())
221 stream() <<
"Translate { x: " << translation.x() <<
"; y: " << translation.y() <<
" }";
223 hasNonConstantTransform =
true;
224 stream() <<
"Translate { id: " << idString <<
"_transform_" << groupIndex <<
"_" << i <<
" }";
227 case QTransform::TxScale:
228 if (animation.isConstant()) {
229 const QPointF scale = parameters.value(0).value<QPointF>();
230 if (scale != QPointF(1, 1))
231 stream() <<
"Scale { xScale: " << scale.x() <<
"; yScale: " << scale.y() <<
" }";
233 hasNonConstantTransform =
true;
234 stream() <<
"Scale { id: " << idString <<
"_transform_" << groupIndex <<
"_" << i <<
"}";
237 case QTransform::TxRotate:
238 if (animation.isConstant()) {
239 const QPointF center = parameters.value(0).value<QPointF>();
240 const qreal angle = parameters.value(1).toReal();
241 if (!qFuzzyIsNull(angle))
242 stream() <<
"Rotation { angle: " << angle <<
"; origin.x: " << center.x() <<
"; origin.y: " << center.y() <<
" }";
244 hasNonConstantTransform =
true;
245 stream() <<
"Rotation { id: " << idString <<
"_transform_" << groupIndex <<
"_" << i <<
" }";
248 case QTransform::TxShear:
249 if (animation.isConstant()) {
250 const QPointF skew = parameters.value(0).value<QPointF>();
252 stream() <<
"Shear { xAngle: " << skew.x() <<
"; yAngle: " << skew.y() <<
" }";
254 hasNonConstantTransform =
true;
255 stream() <<
"Shear { id: " << idString <<
"_transform_" << groupIndex <<
"_" << i <<
" }";
268 if (info.motionPath.isAnimated()) {
269 QVariantList defaultProps = info.motionPath.defaultValue().value<QVariantList>();
270 const bool adaptAngle = defaultProps.value(1).toBool();
271 const qreal baseRotation = defaultProps.value(2).toReal();
272 QString interpolatorId = idString + QStringLiteral(
"_motion_interpolator");
273 if (adaptAngle || !qFuzzyIsNull(baseRotation)) {
274 stream() <<
"Rotation {";
278 stream() <<
"angle: " << interpolatorId <<
".angle";
279 if (!qFuzzyIsNull(baseRotation))
280 stream(SameLine) <<
" + " << baseRotation;
282 stream() <<
"angle: " << baseRotation;
289 stream() <<
"Translate {";
292 stream() <<
"x: " << interpolatorId <<
".x";
293 stream() <<
"y: " << interpolatorId <<
".y";
300 if (!info.isDefaultTransform) {
301 QTransform xf = info.transform.defaultValue().value<QTransform>();
302 if (xf.type() <= QTransform::TxTranslate) {
303 stream() <<
"Translate { x: " << xf.dx() <<
"; y: " << xf.dy() <<
"}";
305 stream() <<
"Matrix4x4 { matrix: ";
306 generateTransform(xf);
307 stream(SameLine) <<
"}";
311 if (!info.transformReferenceId.isEmpty())
312 stream() <<
"Matrix4x4 { matrix: " << info.transformReferenceId <<
".transformMatrix }";
317 if (hasNonConstantTransform) {
318 generateAnimateTransform(idString, info);
319 }
else if (info.transform.isAnimated() && earliestOverrideGroup >= 0) {
322 stream() <<
"Component.onCompleted: {";
325 stream() << idString <<
"_transform_base_group.activateOverride("
326 << idString <<
"_transform_group_" << earliestOverrideGroup <<
")";
333 generateAnimateMotionPath(idString, info.motionPath);
335 generatePropertyAnimation(info.opacity, idString, QStringLiteral(
"opacity"));
338void QQuickQmlGenerator::generateShaderUse(
const NodeInfo &info)
340 const bool hasMask = !info.maskId.isEmpty();
341 const bool hasFilters = !info.filterId.isEmpty();
342 if (!hasMask && !hasFilters)
345 const QString effectId = hasFilters
346 ? info.filterId + QStringLiteral(
"_") + info.id + QStringLiteral(
"_effect")
349 QString animatedItemId;
351 stream() <<
"ShaderEffectSource {";
354 const QString seId = info.id + QStringLiteral(
"_se");
355 stream() <<
"id: " << seId;
357 stream() <<
"ItemSpy {";
359 stream() <<
"id: " << info.id <<
"_itemspy";
360 stream() <<
"anchors.fill: parent";
364 stream() <<
"hideSource: true";
365 stream() <<
"wrapMode: " << info.filterId <<
"_filterParameters.wrapMode";
366 stream() <<
"sourceItem: " << info.id;
367 stream() <<
"sourceRect: " << info.filterId
368 <<
"_filterParameters.adaptToFilterRect("
369 << info.id <<
".originalBounds.x, "
370 << info.id <<
".originalBounds.y, "
371 << info.id <<
".originalBounds.width, "
372 << info.id <<
".originalBounds.height)";
373 stream() <<
"textureSize: " << info.id <<
"_itemspy.requiredTextureSize";
374 stream() <<
"width: sourceRect.width";
375 stream() <<
"height: sourceRect.height";
376 stream() <<
"visible: false";
381 stream() <<
"Loader {";
384 animatedItemId = effectId;
385 stream() <<
"id: " << effectId;
387 stream() <<
"property var filterSourceItem: " << seId;
388 stream() <<
"sourceComponent: " << info.filterId <<
"_container";
389 stream() <<
"property real sourceX: " << info.id <<
".originalBounds.x";
390 stream() <<
"property real sourceY: " << info.id <<
".originalBounds.y";
391 stream() <<
"width: " << info.id <<
".originalBounds.width";
392 stream() <<
"height: " << info.id <<
".originalBounds.height";
402 stream() <<
"ShaderEffectSource {";
405 const QString maskId = info.maskId + QStringLiteral(
"_") + info.id + QStringLiteral(
"_mask");
406 stream() <<
"id: " << maskId;
407 stream() <<
"sourceItem: " << info.maskId;
408 stream() <<
"visible: false";
409 stream() <<
"hideSource: true";
411 if (m_contentRelativeMasks.contains(info.maskId)) {
412 stream() <<
"Binding { target: " << info.maskId
413 <<
"; property: \"contentX\"; value: " << info.id <<
".originalBounds.x }";
414 stream() <<
"Binding { target: " << info.maskId
415 <<
"; property: \"contentY\"; value: " << info.id <<
".originalBounds.y }";
416 stream() <<
"Binding { target: " << info.maskId
417 <<
"; property: \"contentWidth\"; value: " << info.id
418 <<
".originalBounds.width }";
419 stream() <<
"Binding { target: " << info.maskId
420 <<
"; property: \"contentHeight\"; value: " << info.id
421 <<
".originalBounds.height }";
424 stream() <<
"ItemSpy {";
426 stream() <<
"id: " << maskId <<
"_itemspy";
427 stream() <<
"anchors.fill: parent";
430 stream() <<
"textureSize: " << maskId <<
"_itemspy.requiredTextureSize";
432 stream() <<
"sourceRect: " << info.maskId <<
".maskRect("
433 << info.id <<
".originalBounds.x,"
434 << info.id <<
".originalBounds.y,"
435 << info.id <<
".originalBounds.width,"
436 << info.id <<
".originalBounds.height)";
438 stream() <<
"width: sourceRect.width";
439 stream() <<
"height: sourceRect.height";
445 stream() <<
"ShaderEffectSource {";
448 const QString seId = info.id + QStringLiteral(
"_masked_se");
449 stream() <<
"id: " << seId;
451 stream() <<
"ItemSpy {";
453 stream() <<
"id: " << info.id <<
"_masked_se_itemspy";
454 stream() <<
"anchors.fill: parent";
458 stream() <<
"hideSource: true";
460 stream() <<
"sourceItem: " << effectId;
462 stream() <<
"sourceItem: " << info.id;
463 stream() <<
"textureSize: " << info.id <<
"_masked_se_itemspy.requiredTextureSize";
465 stream() <<
"sourceRect: " << info.maskId <<
".maskRect("
466 << info.id <<
".originalBounds.x,"
467 << info.id <<
".originalBounds.y,"
468 << info.id <<
".originalBounds.width,"
469 << info.id <<
".originalBounds.height)";
471 stream() <<
"sourceRect: " << info.maskId <<
".maskRect(0, 0,"
472 << info.id <<
".originalBounds.width,"
473 << info.id <<
".originalBounds.height)";
475 stream() <<
"width: sourceRect.width";
476 stream() <<
"height: sourceRect.height";
477 stream() <<
"smooth: false";
478 stream() <<
"visible: false";
483 stream() <<
"ShaderEffect {";
486 const QString maskShaderId = maskId + QStringLiteral(
"_se");
487 animatedItemId = maskShaderId;
489 stream() <<
"id:" << maskShaderId;
491 stream() <<
"property real sourceX: " << maskId <<
".sourceRect.x";
492 stream() <<
"property real sourceY: " << maskId <<
".sourceRect.y";
493 stream() <<
"width: " << maskId <<
".sourceRect.width";
494 stream() <<
"height: " << maskId <<
".sourceRect.height";
496 stream() <<
"fragmentShader: \"qrc:/qt-project.org/quickvectorimage/helpers/shaders_ng/genericmask.frag.qsb\"";
497 stream() <<
"property var source: " << seId;
498 stream() <<
"property var maskSource: " << maskId;
499 stream() <<
"property bool isAlpha: " << (info.isMaskAlpha ?
"true" :
"false");
500 stream() <<
"property bool isInverted: " << (info.isMaskInverted ?
"true" :
"false");
503 if (!info.isDefaultOpacity)
504 stream() <<
"opacity: " << info.opacity.defaultValue().toReal();
506 generateItemAnimations(animatedItemId, info);
512bool QQuickQmlGenerator::generateDefsNode(
const StructureNodeInfo &info)
514 if (Q_UNLIKELY(errorState()))
517 if (info.stage == StructureNodeStage::Start) {
518 m_oldIndentLevels.push(m_indentLevel);
520 stream() <<
"Component {";
523 stream() <<
"id: " << info.id <<
"_container";
525 stream() <<
"Item {";
528 generateTimelineFields(info);
529 if (!info.transformReferenceChildId.isEmpty()) {
530 stream() <<
"property alias transformMatrix: "
531 << info.transformReferenceChildId <<
".transformMatrix";
534 generateNodeBase(info, QStringLiteral(
"_defs"));
536 generateNodeEnd(info);
541 stream() << m_defsSuffix;
542 m_defsSuffix.clear();
544 m_indentLevel = m_oldIndentLevels.pop();
550void QQuickQmlGenerator::generateImageNode(
const ImageNodeInfo &info)
552 if (Q_UNLIKELY(errorState() || !isNodeVisible(info)))
555 const QFileInfo outputFileInfo(outputFileName);
556 const QDir outputDir(outputFileInfo.absolutePath());
560 if (!m_retainFilePaths || info.externalFileReference.isEmpty()) {
561 filePath = m_assetFileDirectory;
562 if (filePath.isEmpty())
563 filePath = outputDir.absolutePath();
565 if (!filePath.isEmpty() && !filePath.endsWith(u'/'))
568 QDir fileDir(filePath);
569 if (!fileDir.exists()) {
570 if (!fileDir.mkpath(QStringLiteral(
".")))
571 qCWarning(lcQuickVectorImage) <<
"Failed to create image resource directory:" << filePath;
574 filePath += QStringLiteral(
"%1%2.png").arg(m_assetFilePrefix.isEmpty()
575 ? QStringLiteral(
"svg_asset_")
577 .arg(info.image.cacheKey());
579 if (!info.image.save(filePath))
580 qCWarning(lcQuickVectorImage) <<
"Unabled to save image resource" << filePath;
581 qCDebug(lcQuickVectorImage) <<
"Saving copy of IMAGE" << filePath;
583 filePath = info.externalFileReference;
586 const QFileInfo assetFileInfo(filePath);
588 stream() <<
"Image {";
591 generateNodeBase(info);
592 stream() <<
"x: " << info.rect.x();
593 stream() <<
"y: " << info.rect.y();
594 stream() <<
"width: " << info.rect.width();
595 stream() <<
"height: " << info.rect.height();
596 stream() <<
"source: \"" << m_urlPrefix << outputDir.relativeFilePath(assetFileInfo.absoluteFilePath()) <<
"\"";
597 generateNodeEnd(info);
600void QQuickQmlGenerator::generateMarkers(
const PathNodeInfo &info)
602 const QPainterPath path = info.path.defaultValue().value<QPainterPath>();
603 for (
int i = 0; i < path.elementCount(); ++i) {
604 const QPainterPath::Element element = path.elementAt(i);
609 auto getMeanAngle = [](QPointF p0, QPointF p1, QPointF p2) -> qreal {
610 QPointF t1 = p1 - p0;
611 QPointF t2 = p2 - p1;
612 qreal hyp1 = hypot(t1.x(), t1.y());
617 qreal hyp2 = hypot(t2.x(), t2.y());
622 QPointF tangent = t1 + t2;
623 return -atan2(tangent.y(), tangent.x()) / M_PI * 180.;
627 markerId = info.markerStartId;
628 angle = path.angleAtPercent(0.0);
629 }
else if (i == path.elementCount() - 1) {
630 markerId = info.markerEndId;
631 angle = path.angleAtPercent(1.0);
632 }
else if (path.elementAt(i + 1).type != QPainterPath::CurveToDataElement) {
633 markerId = info.markerMidId;
635 const QPainterPath::Element prevElement = path.elementAt(i - 1);
636 const QPainterPath::Element nextElement = path.elementAt(i + 1);
638 QPointF p1(prevElement.x, prevElement.y);
639 QPointF p2(element.x, element.y);
640 QPointF p3(nextElement.x, nextElement.y);
642 angle = getMeanAngle(p1, p2, p3);
645 if (!markerId.isEmpty()) {
646 stream() <<
"Loader {";
650 stream() <<
"sourceComponent: " << markerId <<
"_container";
651 stream() <<
"property real strokeWidth: " << info.strokeStyle.width.defaultValue().toReal();
652 stream() <<
"transform: [";
655 stream() <<
"Scale { "
656 <<
"xScale: " << markerId <<
"_markerParameters.startReversed ? -1 : 1; "
657 <<
"yScale: " << markerId <<
"_markerParameters.startReversed ? -1 : 1 },";
659 stream() <<
"Rotation { angle: " << markerId <<
"_markerParameters.autoAngle(" << -angle <<
") },";
660 stream() <<
"Translate { x: " << element.x <<
"; y: " << element.y <<
"}";
671void QQuickQmlGenerator::generatePath(
const PathNodeInfo &info,
const QRectF &overrideBoundingRect)
673 if (Q_UNLIKELY(errorState() || !isNodeVisible(info)))
676 if (m_inShapeItemLevel > 0) {
677 if (!info.isDefaultTransform)
678 qWarning() <<
"Skipped transform for node" << info.nodeId <<
"type" << info.typeName <<
"(this is not supposed to happen)";
679 optimizePaths(info, overrideBoundingRect);
681 m_inShapeItemLevel++;
682 stream() << shapeName() <<
" {";
685 generateNodeBase(info);
687 if (m_flags.testFlag(QQuickVectorImageGenerator::GeneratorFlag::CurveRenderer))
688 stream() <<
"preferredRendererType: Shape.CurveRenderer";
689 if (m_flags.testFlag(QQuickVectorImageGenerator::GeneratorFlag::AsyncShapes))
690 stream() <<
"asynchronous: true";
691 optimizePaths(info, overrideBoundingRect);
694 if (!info.markerStartId.isEmpty()
695 || !info.markerMidId.isEmpty()
696 || !info.markerEndId.isEmpty()) {
697 generateMarkers(info);
700 generateNodeEnd(info);
701 m_inShapeItemLevel--;
705void QQuickQmlGenerator::generateGradient(
const QGradient *grad,
706 const QString &propertyName,
707 const QRectF &coordinateConversion)
709 const QSizeF &scale = coordinateConversion.size();
710 const QPointF &translation = coordinateConversion.topLeft();
712 if (grad->type() == QGradient::LinearGradient) {
713 auto *linGrad =
static_cast<
const QLinearGradient *>(grad);
714 stream() << propertyName <<
": LinearGradient {";
717 QRectF gradRect(linGrad->start(), linGrad->finalStop());
719 stream() <<
"x1: " << (gradRect.left() * scale.width()) + translation.x();
720 stream() <<
"y1: " << (gradRect.top() * scale.height()) + translation.y();
721 stream() <<
"x2: " << (gradRect.right() * scale.width()) + translation.x();
722 stream() <<
"y2: " << (gradRect.bottom() * scale.height()) + translation.y();
723 for (
auto &stop : linGrad->stops())
724 stream() <<
"GradientStop { position: " << QString::number(stop.first,
'g', 7)
725 <<
"; color: \"" << stop.second.name(QColor::HexArgb) <<
"\" }";
726 }
else if (grad->type() == QGradient::RadialGradient) {
727 auto *radGrad =
static_cast<
const QRadialGradient*>(grad);
728 stream() << propertyName <<
": RadialGradient {";
731 stream() <<
"centerX: " << (radGrad->center().x() * scale.width()) + translation.x();
732 stream() <<
"centerY: " << (radGrad->center().y() * scale.height()) + translation.y();
733 stream() <<
"centerRadius: " << (radGrad->radius() * scale.width());
734 stream() <<
"focalX:" << (radGrad->focalPoint().x() * scale.width()) + translation.x();
735 stream() <<
"focalY:" << (radGrad->focalPoint().y() * scale.height()) + translation.y();
736 for (
auto &stop : radGrad->stops())
737 stream() <<
"GradientStop { position: " << QString::number(stop.first,
'g', 7)
738 <<
"; color: \"" << stop.second.name(QColor::HexArgb) <<
"\" }";
741 stream() <<
"spread: ShapeGradient.";
742 switch (grad->spread()) {
743 case QGradient::PadSpread:
744 stream(SameLine) <<
"PadSpread";
746 case QGradient::ReflectSpread:
747 stream(SameLine) <<
"ReflectSpread";
749 case QGradient::RepeatSpread:
750 stream(SameLine) <<
"RepeatSpread";
758void QQuickQmlGenerator::generateAnimationBindings()
761 if (Q_UNLIKELY(!isRuntimeGenerator()))
762 prefix = QStringLiteral(
".animations");
764 stream() <<
"loops: " << m_topLevelIdString << prefix <<
".loops";
765 stream() <<
"paused: " << m_topLevelIdString << prefix <<
".paused";
766 stream() <<
"running: true";
769 stream() <<
"onLoopsChanged: { if (running) { restart() } }";
772void QQuickQmlGenerator::generateEasing(
const QQuickAnimatedProperty::PropertyAnimation &animation,
773 int time,
int streamFlags)
775 if (animation.easingPerFrame.contains(time)) {
776 QBezier bezier = animation.easingPerFrame.value(time);
777 QPointF c1 = bezier.pt2();
778 QPointF c2 = bezier.pt3();
780 bool isLinear = (c1 == c1.transposed() && c2 == c2.transposed());
782 int nextIdx = m_easings.size();
783 QString &id = m_easings[{c1.x(), c1.y(), c2.x(), c2.y()}];
785 id = QString(QLatin1String(
"easing_%1")).arg(nextIdx, 2, 10, QLatin1Char(
'0'));
786 if (streamFlags & SameLine)
787 stream(streamFlags) <<
"; ";
788 stream(streamFlags) <<
"easing: " << m_topLevelIdString <<
"." << id;
795 static qreal multiplier = qreal(qEnvironmentVariable(
"QT_QUICKVECTORIMAGE_TIME_DILATION", QStringLiteral(
"1.0"))
797 return std::round(multiplier * time);
800void QQuickQmlGenerator::generatePropertyAnimation(
const QQuickAnimatedProperty &property,
801 const QString &targetName,
802 const QString &propertyName,
803 AnimationType animationType)
805 if (!property.isAnimated())
808 if (usingTimelineAnimation())
809 return generatePropertyTimeline(property, targetName, propertyName, animationType);
811 QString mainAnimationId = targetName
812 + QStringLiteral(
"_")
814 + QStringLiteral(
"_animation");
815 mainAnimationId.replace(QLatin1Char(
'.'), QLatin1Char(
'_'));
818 if (Q_UNLIKELY(!isRuntimeGenerator()))
819 prefix = QStringLiteral(
".animations");
821 stream() <<
"Connections { target: " << m_topLevelIdString << prefix <<
"; function onRestart() {" << mainAnimationId <<
".restart() } }";
823 stream() <<
"ParallelAnimation {";
826 stream() <<
"id: " << mainAnimationId;
828 generateAnimationBindings();
830 for (
int i = 0; i < property.animationCount(); ++i) {
831 const QQuickAnimatedProperty::PropertyAnimation &animation = property.animation(i);
833 stream() <<
"SequentialAnimation {";
836 const int startOffset = processAnimationTime(animation.startOffset);
838 stream() <<
"PauseAnimation { duration: " << startOffset <<
" }";
840 stream() <<
"SequentialAnimation {";
843 const int repeatCount = animation.repeatCount;
845 stream() <<
"loops: Animation.Infinite";
847 stream() <<
"loops: " << repeatCount;
849 int previousTime = 0;
850 QVariant previousValue;
851 for (
auto it = animation.frames.constBegin(); it != animation.frames.constEnd(); ++it) {
852 const int time = it.key();
853 const int frameTime = processAnimationTime(time - previousTime);
854 const QVariant &value = it.value();
856 if (previousValue.isValid() && previousValue == value) {
858 stream() <<
"PauseAnimation { duration: " << frameTime <<
" }";
859 }
else if (animationType == AnimationType::Auto && value.typeId() == QMetaType::Bool) {
862 stream() <<
"PauseAnimation { duration: " << frameTime <<
" }";
863 stream() <<
"ScriptAction {";
866 stream() <<
"script:" << targetName <<
"." << propertyName <<
" = " << value.toString();
871 generateAnimatedPropertySetter(targetName,
881 previousValue = value;
884 if (!(animation.flags & QQuickAnimatedProperty::PropertyAnimation::FreezeAtEnd)) {
885 stream() <<
"ScriptAction {";
887 stream() <<
"script: ";
889 switch (animationType) {
890 case AnimationType::Auto:
891 stream(SameLine) << targetName <<
"." << propertyName <<
" = ";
893 case AnimationType::ColorOpacity:
894 stream(SameLine) << targetName <<
"." << propertyName <<
".a = ";
898 QVariant value = property.defaultValue();
899 if (value.typeId() == QMetaType::QColor)
900 stream(SameLine) <<
"\"" << value.toString() <<
"\"";
902 stream(SameLine) << value.toReal();
919void QQuickQmlGenerator::generateTimelinePropertySetter(
920 const QString &targetName,
921 const QString &propertyName,
922 const QQuickAnimatedProperty::PropertyAnimation &animation,
923 std::function<QVariant(
const QVariant &)>
const& extractValue,
926 if (animation.repeatCount != 1 || animation.startOffset
927 || animation.flags != QQuickAnimatedProperty::PropertyAnimation::FreezeAtEnd) {
928 qCWarning(lcQuickVectorImage) <<
"Animation feature not implemented in timeline mode, for"
929 << targetName << propertyName;
932 stream() <<
"KeyframeGroup {";
934 stream() <<
"target: " << targetName;
935 stream() <<
"property: \"" << propertyName <<
"\"";
937 for (
const auto &[frame, rawValue] : animation.frames.asKeyValueRange()) {
939 if (rawValue.typeId() == QMetaType::QVariantList)
940 value = extractValue(rawValue.toList().value(valueIndex));
942 value = extractValue(rawValue);
944 stream() <<
"Keyframe { frame: " << frame <<
"; value: ";
945 if (value.typeId() == QMetaType::QVector3D) {
946 const QVector3D &v = value.value<QVector3D>();
947 stream(SameLine) <<
"Qt.vector3d(" << v.x() <<
", " << v.y() <<
", " << v.z() <<
")";
948 }
else if (value.typeId() == QMetaType::QColor) {
949 stream(SameLine) <<
"\"" << value.toString() <<
"\"";
951 stream(SameLine) << value.toReal();
953 generateEasing(animation, frame, SameLine);
954 stream(SameLine) <<
" }";
961void QQuickQmlGenerator::generatePropertyTimeline(
const QQuickAnimatedProperty &property,
962 const QString &targetName,
963 const QString &propertyName,
964 AnimationType animationType)
966 if (animationType == QQuickQmlGenerator::AnimationType::ColorOpacity) {
967 qCWarning(lcQuickVectorImage) <<
"ColorOpacity animation not available in timeline mode";
971 if (property.animationGroupCount() > 1 || property.animationCount() > 1) {
972 qCWarning(lcQuickVectorImage) <<
"Property feature not implemented in timeline mode, for"
973 << targetName << propertyName;
976 stream() <<
"Timeline {";
978 stream() <<
"currentFrame: " << property.timelineReferenceId() <<
".frameCounter";
979 stream() <<
"enabled: true";
981 auto extractor = [](
const QVariant &value) {
return value; };
982 generateTimelinePropertySetter(targetName, propertyName, property.animation(0), extractor);
988void QQuickQmlGenerator::generateTransform(
const QTransform &xf)
991 stream(SameLine) <<
"PlanarTransform.fromAffineMatrix("
992 << xf.m11() <<
", " << xf.m12() <<
", "
993 << xf.m21() <<
", " << xf.m22() <<
", "
994 << xf.dx() <<
", " << xf.dy() <<
")";
997 stream(SameLine) <<
"Qt.matrix4x4(";
999 const auto *data = m.data();
1000 for (
int i = 0; i < 4; i++) {
1001 stream() << data[i] <<
", " << data[i+4] <<
", " << data[i+8] <<
", " << data[i+12];
1003 stream(SameLine) <<
", ";
1005 stream(SameLine) <<
")";
1010void QQuickQmlGenerator::outputShapePath(
const PathNodeInfo &info,
const QPainterPath *painterPath,
const QQuadPath *quadPath, QQuickVectorImageGenerator::PathSelector pathSelector,
const QRectF &boundingRect)
1012 Q_UNUSED(pathSelector)
1013 Q_ASSERT(painterPath || quadPath);
1015 if (Q_UNLIKELY(errorState()))
1018 const bool invalidGradientBounds = info.strokeGrad.coordinateMode() == QGradient::ObjectMode
1019 && (qFuzzyIsNull(boundingRect.width()) ||
1020 qFuzzyIsNull(boundingRect.height()));
1022 const QColor strokeColor = info.strokeStyle.color.defaultValue().value<QColor>();
1023 const bool noPen = (strokeColor == QColorConstants::Transparent || !strokeColor.isValid())
1024 && !info.strokeStyle.color.isAnimated()
1025 && !info.strokeStyle.opacity.isAnimated()
1026 && (info.strokeGrad.type() == QGradient::NoGradient
1027 || invalidGradientBounds);
1028 if (pathSelector == QQuickVectorImageGenerator::StrokePath && noPen)
1031 const QColor fillColor = info.fillColor.defaultValue().value<QColor>();
1032 const bool noFill = info.grad.type() == QGradient::NoGradient
1033 && fillColor == QColorConstants::Transparent
1034 && !info.fillColor.isAnimated()
1035 && !info.fillOpacity.isAnimated();
1036 if (pathSelector == QQuickVectorImageGenerator::FillPath && noFill)
1039 if (noPen && noFill)
1041 auto fillRule = QQuickShapePath::FillRule(painterPath ? painterPath->fillRule() : quadPath->fillRule());
1042 stream() <<
"ShapePath {";
1045 QString shapePathId = info.id;
1046 if (pathSelector & QQuickVectorImageGenerator::FillPath)
1047 shapePathId += QStringLiteral(
"_fill");
1048 if (pathSelector & QQuickVectorImageGenerator::StrokePath)
1049 shapePathId += QStringLiteral(
"_stroke");
1051 stream() <<
"id: " << shapePathId;
1053 if (!info.nodeId.isEmpty()) {
1054 switch (pathSelector) {
1055 case QQuickVectorImageGenerator::FillPath:
1056 stream() <<
"objectName: \"svg_fill_path:" << info.nodeId <<
"\"";
1058 case QQuickVectorImageGenerator::StrokePath:
1059 stream() <<
"objectName: \"svg_stroke_path:" << info.nodeId <<
"\"";
1061 case QQuickVectorImageGenerator::FillAndStroke:
1062 stream() <<
"objectName: \"svg_path:" << info.nodeId <<
"\"";
1067 if (noPen || !(pathSelector & QQuickVectorImageGenerator::StrokePath)) {
1068 stream() <<
"strokeColor: \"transparent\"";
1070 if (info.strokeGrad.type() != QGradient::NoGradient && !invalidGradientBounds) {
1071 QRectF coordinateSys = info.strokeGrad.coordinateMode() == QGradient::ObjectMode
1073 : QRectF(0.0, 0.0, 1.0, 1.0);
1074 generateGradient(&info.strokeGrad, QStringLiteral(
"strokeGradient"), coordinateSys);
1075 }
else if (info.strokeStyle.opacity.isAnimated()) {
1076 stream() <<
"property color strokeBase: \"" << strokeColor.name(QColor::HexArgb) <<
"\"";
1077 stream() <<
"property real strokeOpacity: " << info.strokeStyle.opacity.defaultValue().toReal();
1078 stream() <<
"strokeColor: Qt.rgba(strokeBase.r, strokeBase.g, strokeBase.b, strokeOpacity)";
1080 stream() <<
"strokeColor: \"" << strokeColor.name(QColor::HexArgb) <<
"\"";
1082 stream() <<
"strokeWidth: " << info.strokeStyle.width.defaultValue().toReal();
1083 stream() <<
"capStyle: " << QQuickVectorImageGenerator::Utils::strokeCapStyleString(info.strokeStyle.lineCapStyle);
1084 stream() <<
"joinStyle: " << QQuickVectorImageGenerator::Utils::strokeJoinStyleString(info.strokeStyle.lineJoinStyle);
1085 stream() <<
"miterLimit: " << info.strokeStyle.miterLimit;
1086 if (info.strokeStyle.cosmetic)
1087 stream() <<
"cosmeticStroke: true";
1088 if (info.strokeStyle.dashArray.length() != 0) {
1089 stream() <<
"strokeStyle: " <<
"ShapePath.DashLine";
1090 stream() <<
"dashPattern: " << QQuickVectorImageGenerator::Utils::listString(info.strokeStyle.dashArray);
1091 stream() <<
"dashOffset: " << info.strokeStyle.dashOffset.defaultValue().toReal();
1095 QTransform fillTransform = info.fillTransform;
1096 if (!(pathSelector & QQuickVectorImageGenerator::FillPath)) {
1097 stream() <<
"fillColor: \"transparent\"";
1098 }
else if (info.grad.type() != QGradient::NoGradient) {
1099 generateGradient(&info.grad, QStringLiteral(
"fillGradient"));
1102 if (info.grad.coordinateMode() == QGradient::ObjectMode) {
1103 QTransform objectToUserSpace;
1104 objectToUserSpace.translate(boundingRect.x(), boundingRect.y());
1105 objectToUserSpace.scale(boundingRect.width(), boundingRect.height());
1106 fillTransform *= objectToUserSpace;
1109 if (info.fillOpacity.isAnimated()) {
1110 stream() <<
"property color fillBase: \"" << fillColor.name(QColor::HexArgb) <<
"\"";
1111 stream() <<
"property real fillOpacity:" << info.fillOpacity.defaultValue().toReal();
1112 stream() <<
"fillColor: Qt.rgba(fillBase.r, fillBase.g, fillBase.b, fillOpacity)";
1114 stream() <<
"fillColor: \"" << fillColor.name(QColor::HexArgb) <<
"\"";
1118 if (!info.patternId.isEmpty()) {
1119 stream() <<
"fillItem: ShaderEffectSource {";
1122 stream() <<
"parent: " << info.id;
1123 stream() <<
"sourceItem: " << info.patternId;
1124 stream() <<
"hideSource: true";
1125 stream() <<
"visible: false";
1126 stream() <<
"width: " << info.patternId <<
".width";
1127 stream() <<
"height: " << info.patternId <<
".height";
1128 stream() <<
"wrapMode: ShaderEffectSource.Repeat";
1129 stream() <<
"textureSize: Qt.size(width * __qt_toplevel_scale_itemspy.requiredTextureSize.width, "
1130 <<
"height * __qt_toplevel_scale_itemspy.requiredTextureSize.height)";;
1131 stream() <<
"sourceRect: " << info.patternId <<
".sourceRect("
1132 << info.id <<
".width, "
1133 << info.id <<
".height)";
1140 stream() <<
"function calculateFillTransform(xScale, yScale) {";
1143 stream() <<
"var m = ";
1144 generateTransform(fillTransform);
1146 stream() <<
"m.translate(" << info.patternId <<
".sourceOffset("
1147 << info.id <<
".width, "
1148 << info.id <<
".height))";
1150 stream() <<
"m.scale(1.0 / xScale, 1.0 / yScale, 1.0)";
1151 stream() <<
"return m";
1156 stream() <<
"fillTransform: calculateFillTransform(__qt_toplevel_scale_itemspy.requiredTextureSize.width, "
1157 <<
"__qt_toplevel_scale_itemspy.requiredTextureSize.height)";
1159 }
else if (!fillTransform.isIdentity()) {
1160 const QTransform &xf = fillTransform;
1161 stream() <<
"fillTransform: ";
1162 if (info.fillTransform.type() == QTransform::TxTranslate)
1163 stream(SameLine) <<
"PlanarTransform.fromTranslate(" << xf.dx() <<
", " << xf.dy() <<
")";
1164 else if (info.fillTransform.type() == QTransform::TxScale && !xf.dx() && !xf.dy())
1165 stream(SameLine) <<
"PlanarTransform.fromScale(" << xf.m11() <<
", " << xf.m22() <<
")";
1167 generateTransform(xf);
1170 if (info.trim.enabled) {
1171 stream() <<
"trim.start: " << info.trim.start.defaultValue().toReal();
1172 stream() <<
"trim.end: " << info.trim.end.defaultValue().toReal();
1173 stream() <<
"trim.offset: " << info.trim.offset.defaultValue().toReal();
1177 if (fillRule == QQuickShapePath::WindingFill)
1178 stream() <<
"fillRule: ShapePath.WindingFill";
1180 stream() <<
"fillRule: ShapePath.OddEvenFill";
1184 hintStr = QQuickVectorImageGenerator::Utils::pathHintString(*quadPath);
1185 if (!hintStr.isEmpty())
1186 stream() << hintStr;
1188 QQuickAnimatedProperty pathFactor(QVariant::fromValue(0));
1189 pathFactor.setTimelineReferenceId(info.path.timelineReferenceId());
1190 QString pathId = shapePathId +
"_ip"_L1;
1191 if (!info.path.isAnimated() || (info.path.animation(0).startOffset == 0 && info.path.animation(0).isConstant())) {
1192 QString svgPathString = painterPath ? QQuickVectorImageGenerator::Utils::toSvgString(*painterPath) : QQuickVectorImageGenerator::Utils::toSvgString(*quadPath);
1193 stream() <<
"PathSvg { path: \"" << svgPathString <<
"\" }";
1195 stream() <<
"PathInterpolated {";
1197 stream() <<
"id: " << pathId;
1198 stream() <<
"svgPaths: [";
1200 QQuickAnimatedProperty::PropertyAnimation pathFactorAnim = info.path.animation(0);
1201 auto &frames = pathFactorAnim.frames;
1204 for (
auto it = frames.begin(); it != frames.end(); ++it) {
1205 QString svg = QQuickVectorImageGenerator::Utils::toSvgString(it->value<QPainterPath>());
1206 if (svg != lastSvg) {
1208 stream(SameLine) <<
",";
1209 stream() <<
"\"" << svg <<
"\"";
1213 *it = QVariant::fromValue(pathIdx);
1215 pathFactor.addAnimation(pathFactorAnim);
1225 if (pathFactor.isAnimated())
1226 generatePropertyAnimation(pathFactor, pathId,
"factor"_L1);
1228 if (info.trim.enabled) {
1229 generatePropertyAnimation(info.trim.start, shapePathId + QStringLiteral(
".trim"), QStringLiteral(
"start"));
1230 generatePropertyAnimation(info.trim.end, shapePathId + QStringLiteral(
".trim"), QStringLiteral(
"end"));
1231 generatePropertyAnimation(info.trim.offset, shapePathId + QStringLiteral(
".trim"), QStringLiteral(
"offset"));
1234 if (info.strokeStyle.opacity.isAnimated()) {
1235 generatePropertyAnimation(info.strokeStyle.color, shapePathId, QStringLiteral(
"strokeBase"));
1236 generatePropertyAnimation(info.strokeStyle.opacity, shapePathId, QStringLiteral(
"strokeOpacity"));
1238 generatePropertyAnimation(info.strokeStyle.color, shapePathId, QStringLiteral(
"strokeColor"));
1240 if (info.strokeStyle.width.isAnimated())
1241 generatePropertyAnimation(info.strokeStyle.width, shapePathId, QStringLiteral(
"strokeWidth"));
1242 if (info.strokeStyle.dashOffset.isAnimated())
1243 generatePropertyAnimation(info.strokeStyle.dashOffset, shapePathId, QStringLiteral(
"dashOffset"));
1245 if (info.fillOpacity.isAnimated()) {
1246 generatePropertyAnimation(info.fillColor, shapePathId, QStringLiteral(
"fillBase"));
1247 generatePropertyAnimation(info.fillOpacity, shapePathId, QStringLiteral(
"fillOpacity"));
1249 generatePropertyAnimation(info.fillColor, shapePathId, QStringLiteral(
"fillColor"));
1253void QQuickQmlGenerator::generateNode(
const NodeInfo &info)
1255 if (Q_UNLIKELY(errorState() || !isNodeVisible(info)))
1258 stream() <<
"// Missing Implementation for SVG Node: " << info.typeName;
1259 stream() <<
"// Adding an empty Item and skipping";
1260 stream() <<
"Item {";
1262 generateNodeBase(info);
1263 generateNodeEnd(info);
1266void QQuickQmlGenerator::generateTextNode(
const TextNodeInfo &info)
1268 if (Q_UNLIKELY(errorState() || !isNodeVisible(info)))
1271 stream() <<
"Item {";
1273 generateNodeBase(info);
1275 if (!info.isTextArea)
1276 stream() <<
"Item { id: textAlignItem_" << m_textNodeCounter <<
"; x: " << info.position.x() <<
"; y: " << info.position.y() <<
"}";
1278 stream() <<
"Text {";
1282 const QString textItemId = QStringLiteral(
"_qt_textItem_%1").arg(m_textNodeCounter);
1283 stream() <<
"id: " << textItemId;
1285 generatePropertyAnimation(info.fillColor, textItemId, QStringLiteral(
"color"));
1286 generatePropertyAnimation(info.fillOpacity, textItemId, QStringLiteral(
"color"), AnimationType::ColorOpacity);
1287 generatePropertyAnimation(info.strokeColor, textItemId, QStringLiteral(
"styleColor"));
1288 generatePropertyAnimation(info.strokeOpacity, textItemId, QStringLiteral(
"styleColor"), AnimationType::ColorOpacity);
1290 if (info.isTextArea) {
1291 stream() <<
"x: " << info.position.x();
1292 stream() <<
"y: " << info.position.y();
1293 if (info.size.width() > 0)
1294 stream() <<
"width: " << info.size.width();
1295 if (info.size.height() > 0)
1296 stream() <<
"height: " << info.size.height();
1297 stream() <<
"wrapMode: Text.Wrap";
1298 stream() <<
"clip: true";
1300 QString hAlign = QStringLiteral(
"left");
1301 stream() <<
"anchors.baseline: textAlignItem_" << m_textNodeCounter <<
".top";
1302 switch (info.alignment) {
1303 case Qt::AlignHCenter:
1304 hAlign = QStringLiteral(
"horizontalCenter");
1306 case Qt::AlignRight:
1307 hAlign = QStringLiteral(
"right");
1310 qCDebug(lcQuickVectorImage) <<
"Unexpected text alignment" << info.alignment;
1315 stream() <<
"anchors." << hAlign <<
": textAlignItem_" << m_textNodeCounter <<
".left";
1317 m_textNodeCounter++;
1319 stream() <<
"color: \"" << info.fillColor.defaultValue().value<QColor>().name(QColor::HexArgb) <<
"\"";
1320 stream() <<
"textFormat:" << (info.needsRichText ?
"Text.RichText" :
"Text.StyledText");
1322 stream() <<
"text: \"" << sanitizeString(info.text) <<
"\"";
1323 stream() <<
"font.family: \"" << sanitizeString(info.font.family()) <<
"\"";
1324 if (info.font.pixelSize() > 0)
1325 stream() <<
"font.pixelSize:" << info.font.pixelSize();
1326 else if (info.font.pointSize() > 0)
1327 stream() <<
"font.pixelSize:" << info.font.pointSizeF();
1328 if (info.font.underline())
1329 stream() <<
"font.underline: true";
1330 if (info.font.weight() != QFont::Normal)
1331 stream() <<
"font.weight: " <<
int(info.font.weight());
1332 if (info.font.italic())
1333 stream() <<
"font.italic: true";
1334 switch (info.font.hintingPreference()) {
1335 case QFont::PreferFullHinting:
1336 stream() <<
"font.hintingPreference: Font.PreferFullHinting";
1338 case QFont::PreferVerticalHinting:
1339 stream() <<
"font.hintingPreference: Font.PreferVerticalHinting";
1341 case QFont::PreferNoHinting:
1342 stream() <<
"font.hintingPreference: Font.PreferNoHinting";
1344 case QFont::PreferDefaultHinting:
1345 stream() <<
"font.hintingPreference: Font.PreferDefaultHinting";
1349 const QColor strokeColor = info.strokeColor.defaultValue().value<QColor>();
1350 if (strokeColor != QColorConstants::Transparent || info.strokeColor.isAnimated()) {
1351 stream() <<
"styleColor: \"" << strokeColor.name(QColor::HexArgb) <<
"\"";
1352 stream() <<
"style: Text.Outline";
1358 generateNodeEnd(info);
1361void QQuickQmlGenerator::generateUseNode(
const UseNodeInfo &info)
1363 if (Q_UNLIKELY(errorState() || !isNodeVisible(info)))
1366 if (info.stage == StructureNodeStage::Start) {
1367 stream() <<
"Item {";
1369 generateNodeBase(info);
1371 generateNodeEnd(info);
1375void QQuickQmlGenerator::generatePathContainer(
const StructureNodeInfo &info)
1378 stream() << shapeName() <<
" {";
1380 if (m_flags.testFlag(QQuickVectorImageGenerator::GeneratorFlag::CurveRenderer))
1381 stream() <<
"preferredRendererType: Shape.CurveRenderer";
1382 if (m_flags.testFlag(QQuickVectorImageGenerator::GeneratorFlag::AsyncShapes))
1383 stream() <<
"asynchronous: true";
1386 m_inShapeItemLevel++;
1389void QQuickQmlGenerator::generateAnimateMotionPath(
const QString &targetName,
1390 const QQuickAnimatedProperty &property)
1392 if (!property.isAnimated())
1395 QPainterPath path = property.defaultValue().value<QVariantList>().value(0).value<QPainterPath>();
1396 const QString mainAnimationId = targetName + QStringLiteral(
"_motion_interpolator");
1397 stream() <<
"PathInterpolator {";
1399 stream() <<
"id: " << mainAnimationId;
1400 const QString svgPathString = QQuickVectorImageGenerator::Utils::toSvgString(path);
1401 stream() <<
"path: Path { PathSvg { path: \"" << svgPathString <<
"\" } }";
1405 generatePropertyAnimation(property, mainAnimationId, QStringLiteral(
"progress"));
1408void QQuickQmlGenerator::generateAnimatedPropertySetter(
const QString &targetName,
1409 const QString &propertyName,
1410 const QVariant &value,
1411 const QQuickAnimatedProperty::PropertyAnimation &animation,
1414 AnimationType animationType)
1416 if (frameTime > 0) {
1417 switch (animationType) {
1418 case AnimationType::Auto:
1419 if (value.typeId() == QMetaType::QColor)
1420 stream() <<
"ColorAnimation {";
1422 stream() <<
"PropertyAnimation {";
1424 case AnimationType::ColorOpacity:
1425 stream() <<
"ColorOpacityAnimation {";
1430 stream() <<
"duration: " << frameTime;
1431 stream() <<
"target: " << targetName;
1432 stream() <<
"property: \"" << propertyName <<
"\"";
1434 if (value.typeId() == QMetaType::QVector3D) {
1435 const QVector3D &v = value.value<QVector3D>();
1436 stream(SameLine) <<
"Qt.vector3d(" << v.x() <<
", " << v.y() <<
", " << v.z() <<
")";
1437 }
else if (value.typeId() == QMetaType::QColor) {
1438 stream(SameLine) <<
"\"" << value.toString() <<
"\"";
1440 stream(SameLine) << value.toReal();
1442 generateEasing(animation, time);
1446 stream() <<
"ScriptAction {";
1448 stream() <<
"script:" << targetName <<
"." << propertyName;
1449 if (animationType == AnimationType::ColorOpacity)
1450 stream(SameLine) <<
".a";
1452 stream(SameLine) <<
" = ";
1453 if (value.typeId() == QMetaType::QVector3D) {
1454 const QVector3D &v = value.value<QVector3D>();
1455 stream(SameLine) <<
"Qt.vector3d(" << v.x() <<
", " << v.y() <<
", " << v.z() <<
")";
1456 }
else if (value.typeId() == QMetaType::QColor) {
1457 stream(SameLine) <<
"\"" << value.toString() <<
"\"";
1459 stream(SameLine) << value.toReal();
1466void QQuickQmlGenerator::generateAnimateTransform(
const QString &targetName,
const NodeInfo &info)
1468 if (!info.transform.isAnimated())
1471 if (usingTimelineAnimation())
1472 return generateTransformTimeline(targetName, info);
1474 const QString mainAnimationId = targetName
1475 + QStringLiteral(
"_transform_animation");
1478 if (Q_UNLIKELY(!isRuntimeGenerator()))
1479 prefix = QStringLiteral(
".animations");
1480 stream() <<
"Connections { target: " << m_topLevelIdString << prefix <<
"; function onRestart() {" << mainAnimationId <<
".restart() } }";
1482 stream() <<
"ParallelAnimation {";
1485 stream() <<
"id:" << mainAnimationId;
1487 generateAnimationBindings();
1488 for (
int groupIndex = 0; groupIndex < info.transform.animationGroupCount(); ++groupIndex) {
1489 int animationStart = info.transform.animationGroup(groupIndex);
1490 int nextAnimationStart = groupIndex + 1 < info.transform.animationGroupCount()
1491 ? info.transform.animationGroup(groupIndex + 1)
1492 : info.transform.animationCount();
1495 const QQuickAnimatedProperty::PropertyAnimation &firstAnimation = info.transform.animation(animationStart);
1496 const bool freeze = firstAnimation.flags & QQuickAnimatedProperty::PropertyAnimation::FreezeAtEnd;
1497 const bool replace = firstAnimation.flags & QQuickAnimatedProperty::PropertyAnimation::ReplacePreviousAnimations;
1499 stream() <<
"SequentialAnimation {";
1502 const int startOffset = processAnimationTime(firstAnimation.startOffset);
1503 if (startOffset > 0)
1504 stream() <<
"PauseAnimation { duration: " << startOffset <<
" }";
1506 const int repeatCount = firstAnimation.repeatCount;
1507 if (repeatCount < 0)
1508 stream() <<
"loops: Animation.Infinite";
1510 stream() <<
"loops: " << repeatCount;
1513 stream() <<
"ScriptAction {";
1516 stream() <<
"script: " << targetName <<
"_transform_base_group"
1517 <<
".activateOverride(" << targetName <<
"_transform_group_" << groupIndex <<
")";
1523 stream() <<
"ParallelAnimation {";
1526 for (
int i = animationStart; i < nextAnimationStart; ++i) {
1527 const QQuickAnimatedProperty::PropertyAnimation &animation = info.transform.animation(i);
1528 if (animation.isConstant())
1530 bool hasRotationCenter =
false;
1531 if (animation.subtype == QTransform::TxRotate) {
1532 for (
auto it = animation.frames.constBegin(); it != animation.frames.constEnd(); ++it) {
1533 const QPointF center = it->value<QVariantList>().value(0).value<QPointF>();
1534 if (!center.isNull()) {
1535 hasRotationCenter =
true;
1541 stream() <<
"SequentialAnimation {";
1544 int previousTime = 0;
1545 QVariantList previousParameters;
1546 for (
auto it = animation.frames.constBegin(); it != animation.frames.constEnd(); ++it) {
1547 const int time = it.key();
1548 const int frameTime = processAnimationTime(time - previousTime);
1549 const QVariantList ¶meters = it.value().value<QVariantList>();
1550 if (parameters.isEmpty())
1553 if (parameters == previousParameters) {
1555 stream() <<
"PauseAnimation { duration: " << frameTime <<
" }";
1557 stream() <<
"ParallelAnimation {";
1560 const QString propertyTargetName = targetName
1561 + QStringLiteral(
"_transform_")
1562 + QString::number(groupIndex)
1563 + QStringLiteral(
"_")
1564 + QString::number(i);
1566 switch (animation.subtype) {
1567 case QTransform::TxTranslate:
1569 const QPointF translation = parameters.first().value<QPointF>();
1571 generateAnimatedPropertySetter(propertyTargetName,
1572 QStringLiteral(
"x"),
1577 generateAnimatedPropertySetter(propertyTargetName,
1578 QStringLiteral(
"y"),
1585 case QTransform::TxScale:
1587 const QPointF scale = parameters.first().value<QPointF>();
1588 generateAnimatedPropertySetter(propertyTargetName,
1589 QStringLiteral(
"xScale"),
1594 generateAnimatedPropertySetter(propertyTargetName,
1595 QStringLiteral(
"yScale"),
1602 case QTransform::TxRotate:
1604 Q_ASSERT(parameters.size() == 2);
1605 const qreal angle = parameters.value(1).toReal();
1606 if (hasRotationCenter) {
1607 const QPointF center = parameters.value(0).value<QPointF>();
1608 generateAnimatedPropertySetter(propertyTargetName,
1609 QStringLiteral(
"origin"),
1610 QVector3D(center.x(), center.y(), 0.0),
1615 generateAnimatedPropertySetter(propertyTargetName,
1616 QStringLiteral(
"angle"),
1623 case QTransform::TxShear:
1625 const QPointF skew = parameters.first().value<QPointF>();
1627 generateAnimatedPropertySetter(propertyTargetName,
1628 QStringLiteral(
"xAngle"),
1634 generateAnimatedPropertySetter(propertyTargetName,
1635 QStringLiteral(
"yAngle"),
1650 previousTime = time;
1651 previousParameters = parameters;
1663 if (firstAnimation.repeatCount >= 0) {
1664 stream() <<
"ScriptAction {";
1667 stream() <<
"script: {";
1671 stream() << targetName <<
"_transform_base_group.deactivate("
1672 << targetName <<
"_transform_group_" << groupIndex <<
")";
1673 }
else if (!replace) {
1674 stream() << targetName <<
"_transform_base_group.deactivateOverride("
1675 << targetName <<
"_transform_group_" << groupIndex <<
")";
1693void QQuickQmlGenerator::generateTransformTimeline(
const QString &targetName,
const NodeInfo &info)
1695 stream() <<
"Timeline {";
1697 stream() <<
"currentFrame: " << info.transform.timelineReferenceId() <<
".frameCounter";
1698 stream() <<
"enabled: true";
1700 const int groupIndex = 0;
1701 for (
int i = 0; i < info.transform.animationCount(); ++i) {
1702 const QQuickAnimatedProperty::PropertyAnimation &animation = info.transform.animation(i);
1703 if (animation.isConstant())
1705 if (info.transform.animationGroupCount() > 1
1706 || animation.repeatCount != 1 || animation.startOffset
1707 || animation.flags != QQuickAnimatedProperty::PropertyAnimation::FreezeAtEnd) {
1708 qCWarning(lcQuickVectorImage) <<
"Feature not implemented in timeline xf animation mode, for"
1709 << targetName <<
"subtype" << animation.subtype;
1712 bool hasRotationCenter =
false;
1713 if (animation.subtype == QTransform::TxRotate) {
1714 for (
auto it = animation.frames.constBegin(); it != animation.frames.constEnd(); ++it) {
1715 const QPointF center = it->value<QVariantList>().value(0).value<QPointF>();
1716 if (!center.isNull()) {
1717 hasRotationCenter =
true;
1723 auto pointFxExtractor = [](
const QVariant &value) {
return value.toPointF().x(); };
1724 auto pointFyExtractor = [](
const QVariant &value) {
return value.toPointF().y(); };
1725 auto realExtractor = [](
const QVariant &value) {
return value.toReal(); };
1726 auto pointFtoVector3dExtractor = [](
const QVariant &v) {
return QVector3D(v.toPointF()); };
1728 const QString propertyTargetName = targetName
1729 + QStringLiteral(
"_transform_")
1730 + QString::number(groupIndex)
1731 + QStringLiteral(
"_")
1732 + QString::number(i);
1734 switch (animation.subtype) {
1735 case QTransform::TxTranslate:
1736 generateTimelinePropertySetter(propertyTargetName,
"x"_L1, animation, pointFxExtractor);
1737 generateTimelinePropertySetter(propertyTargetName,
"y"_L1, animation, pointFyExtractor);
1739 case QTransform::TxScale:
1740 generateTimelinePropertySetter(propertyTargetName,
"xScale"_L1, animation, pointFxExtractor);
1741 generateTimelinePropertySetter(propertyTargetName,
"yScale"_L1, animation, pointFyExtractor);
1743 case QTransform::TxRotate:
1744 if (hasRotationCenter)
1745 generateTimelinePropertySetter(propertyTargetName,
"origin"_L1, animation, pointFtoVector3dExtractor);
1746 generateTimelinePropertySetter(propertyTargetName,
"angle"_L1, animation, realExtractor, 1);
1748 case QTransform::TxShear:
1749 generateTimelinePropertySetter(propertyTargetName,
"xAngle"_L1, animation, pointFxExtractor);
1750 generateTimelinePropertySetter(propertyTargetName,
"yAngle"_L1, animation, pointFyExtractor);
1759bool QQuickQmlGenerator::generateStructureNode(
const StructureNodeInfo &info)
1761 if (Q_UNLIKELY(errorState() || !isNodeVisible(info)))
1764 const bool isPathContainer = !info.forceSeparatePaths && info.isPathContainer;
1765 if (info.stage == StructureNodeStage::Start) {
1766 if (!info.clipBox.isEmpty()) {
1767 stream() <<
"Item { // Clip";
1770 stream() <<
"width: " << info.clipBox.width();
1771 stream() <<
"height: " << info.clipBox.height();
1772 stream() <<
"clip: true";
1775 if (isPathContainer) {
1776 generatePathContainer(info);
1777 }
else if (!info.customItemType.isEmpty()) {
1778 stream() << info.customItemType <<
" {";
1780 stream() <<
"Item { // Structure node";
1784 generateTimelineFields(info);
1786 if (!info.viewBox.isEmpty()) {
1787 stream() <<
"transform: [";
1789 bool translate = !qFuzzyIsNull(info.viewBox.x()) || !qFuzzyIsNull(info.viewBox.y());
1791 stream() <<
"Translate { x: " << -info.viewBox.x() <<
"; y: " << -info.viewBox.y() <<
" },";
1792 stream() <<
"Scale { xScale: width / " << info.viewBox.width() <<
"; yScale: height / " << info.viewBox.height() <<
" }";
1797 generateNodeBase(info);
1799 generateNodeEnd(info);
1800 if (isPathContainer)
1801 m_inShapeItemLevel--;
1803 if (!info.clipBox.isEmpty()) {
1812bool QQuickQmlGenerator::generateMaskNode(
const MaskNodeInfo &info)
1814 if (Q_UNLIKELY(errorState()))
1818 if (info.stage == StructureNodeStage::Start) {
1819 if (info.isMaskContentRelativeCoordinates) {
1820 m_contentRelativeMasks.insert(info.id);
1821 stream() <<
"Item {";
1823 stream() <<
"transform: Matrix4x4 {";
1825 stream() <<
"matrix: Qt.matrix4x4(";
1827 stream() << info.id <<
".contentWidth, 0, 0, " << info.id <<
".contentX,";
1828 stream() <<
"0, " << info.id <<
".contentHeight, 0, " << info.id <<
".contentY,";
1829 stream() <<
"0, 0, 1, 0,";
1830 stream() <<
"0, 0, 0, 1)";
1838 if (info.stage == StructureNodeStage::End) {
1839 if (info.isMaskContentRelativeCoordinates) {
1845 startDefsSuffixBlock();
1846 stream() <<
"Loader {";
1849 stream() <<
"id: " << info.id;
1850 stream() <<
"visible: false";
1851 stream() <<
"sourceComponent: " << info.id <<
"_container";
1852 stream() <<
"width: item !== null ? item.originalBounds.width : 0";
1853 stream() <<
"height: item !== null ? item.originalBounds.height : 0";
1855 if (info.boundsReferenceId.isEmpty()) {
1856 stream() <<
"property real maskX: " << info.maskRect.left();
1857 stream() <<
"property real maskY: " << info.maskRect.top();
1858 stream() <<
"property real maskWidth: " << info.maskRect.width();
1859 stream() <<
"property real maskHeight: " << info.maskRect.height();
1862 if (info.isMaskContentRelativeCoordinates) {
1863 stream() <<
"property real contentX: 0";
1864 stream() <<
"property real contentY: 0";
1865 stream() <<
"property real contentWidth: 1";
1866 stream() <<
"property real contentHeight: 1";
1869 stream() <<
"function maskRect(otherX, otherY, otherWidth, otherHeight) {";
1872 stream() <<
"return ";
1873 if (!info.boundsReferenceId.isEmpty()) {
1874 stream(SameLine) << info.boundsReferenceId <<
".originalBounds";
1875 }
else if (info.isMaskRectRelativeCoordinates) {
1878 << info.id <<
".maskX * otherWidth + otherX,"
1879 << info.id <<
".maskY * otherHeight + otherY,"
1880 << info.id <<
".maskWidth * otherWidth,"
1881 << info.id <<
".maskHeight * otherHeight)";
1885 << info.id <<
".maskX, "
1886 << info.id <<
".maskY, "
1887 << info.id <<
".maskWidth, "
1888 << info.id <<
".maskHeight)";
1897 endDefsSuffixBlock();
1903void QQuickQmlGenerator::generateFilterNode(
const FilterNodeInfo &info)
1905 if (Q_UNLIKELY(errorState()))
1908 stream() <<
"Item {";
1911 generateNodeBase(info);
1913 stream() <<
"property real originalWidth: filterSourceItem.sourceItem.originalBounds.width";
1914 stream() <<
"property real originalHeight: filterSourceItem.sourceItem.originalBounds.height";
1915 stream() <<
"property rect filterRect: " << info.id <<
"_filterParameters"
1916 <<
".adaptToFilterRect(0, 0, originalWidth, originalHeight)";
1918 for (qsizetype i = 0; i < info.steps.size();)
1919 i = generateFilterStep(info, i);
1922 startDefsSuffixBlock();
1923 stream() <<
"QtObject {";
1926 stream() <<
"id: " << info.id <<
"_filterParameters";
1927 stream() <<
"property int wrapMode: ";
1928 if (info.wrapMode == QSGTexture::Repeat)
1929 stream(SameLine) <<
"ShaderEffectSource.Repeat";
1931 stream(SameLine) <<
"ShaderEffectSource.ClampToEdge";
1933 stream() <<
"property rect filterRect: Qt.rect("
1934 << info.filterRect.x() <<
", "
1935 << info.filterRect.y() <<
", "
1936 << info.filterRect.width() <<
", "
1937 << info.filterRect.height() <<
")";
1939 stream() <<
"function adaptToFilterRect(sx, sy, sw, sh) {";
1942 if (info.csFilterRect == FilterNodeInfo::CoordinateSystem::Absolute) {
1943 stream() <<
"return Qt.rect(filterRect.x, filterRect.y, filterRect.width, filterRect.height)";
1945 stream() <<
"return Qt.rect(sx + sw * filterRect.x, sy + sh * filterRect.y, sw * filterRect.width, sh * filterRect.height)";
1953 endDefsSuffixBlock();
1955 generateNodeEnd(info);
1958qsizetype QQuickQmlGenerator::generateFilterStep(
const FilterNodeInfo &info,
1959 qsizetype stepIndex)
1961 const FilterNodeInfo::FilterStep &step = info.steps.at(stepIndex);
1962 const QString primitiveId = info.id + QStringLiteral(
"_primitive") + QString::number(stepIndex);
1966 QString inputId = step.input1 != FilterNodeInfo::FilterInput::SourceColor
1968 : QStringLiteral(
"filterSourceItem");
1970 bool isComposite =
false;
1971 switch (step.filterType) {
1972 case FilterNodeInfo::Type::Merge:
1974 const int maxNodeCount = 8;
1977 QList<std::pair<FilterNodeInfo::FilterInput, QString> > inputs;
1978 for (; stepIndex < info.steps.size(); ++stepIndex) {
1979 const FilterNodeInfo::FilterStep &nodeStep = info.steps.at(stepIndex);
1980 if (nodeStep.filterType != FilterNodeInfo::Type::MergeNode)
1983 inputs.emplace_back(nodeStep.input1, nodeStep.namedInput1);
1986 if (inputs.size() > maxNodeCount) {
1987 qCWarning(lcQuickVectorImage) <<
"Maximum of" << maxNodeCount
1988 <<
"nodes exceeded in merge effect.";
1991 if (inputs.isEmpty()) {
1992 qCWarning(lcQuickVectorImage) <<
"Merge effect requires at least one node.";
1996 stream() <<
"ShaderEffect {";
1999 stream() <<
"id: " << primitiveId;
2000 stream() <<
"visible: false";
2002 stream() <<
"fragmentShader: \"qrc:/qt-project.org/quickvectorimage/helpers/shaders_ng/femerge.frag.qsb\"";
2003 stream() <<
"width: source1.width";
2004 stream() <<
"height: source1.height";
2005 stream() <<
"property int sourceCount: " << std::min(qsizetype(8), inputs.size());
2007 for (
int i = 0; i < maxNodeCount; ++i) {
2008 auto input = i < inputs.size()
2010 : std::pair(FilterNodeInfo::FilterInput::None, u"null"_s);
2012 QString inputId = input.first != FilterNodeInfo::FilterInput::SourceColor
2014 : QStringLiteral(
"filterSourceItem");
2016 stream() <<
"property var source" << (i + 1) <<
": " << inputId;
2024 case FilterNodeInfo::Type::CompositeOver:
2025 case FilterNodeInfo::Type::CompositeOut:
2026 case FilterNodeInfo::Type::CompositeIn:
2027 case FilterNodeInfo::Type::CompositeXor:
2028 case FilterNodeInfo::Type::CompositeAtop:
2029 case FilterNodeInfo::Type::CompositeArithmetic:
2030 case FilterNodeInfo::Type::CompositeLighter:
2034 case FilterNodeInfo::Type::BlendNormal:
2035 case FilterNodeInfo::Type::BlendMultiply:
2036 case FilterNodeInfo::Type::BlendScreen:
2037 case FilterNodeInfo::Type::BlendDarken:
2038 case FilterNodeInfo::Type::BlendLighten:
2040 stream() <<
"ShaderEffect {";
2043 QString input2Id = step.input2 != FilterNodeInfo::FilterInput::SourceColor
2045 : QStringLiteral(
"filterSourceItem");
2047 stream() <<
"id: " << primitiveId;
2048 stream() <<
"visible: false";
2051 switch (step.filterType) {
2052 case FilterNodeInfo::Type::CompositeOver:
2053 shader = QStringLiteral(
"fecompositeover");
2055 case FilterNodeInfo::Type::CompositeOut:
2056 shader = QStringLiteral(
"fecompositeout");
2058 case FilterNodeInfo::Type::CompositeIn:
2059 shader = QStringLiteral(
"fecompositein");
2061 case FilterNodeInfo::Type::CompositeXor:
2062 shader = QStringLiteral(
"fecompositexor");
2064 case FilterNodeInfo::Type::CompositeAtop:
2065 shader = QStringLiteral(
"fecompositeatop");
2067 case FilterNodeInfo::Type::CompositeArithmetic:
2068 shader = QStringLiteral(
"fecompositearithmetic");
2070 case FilterNodeInfo::Type::CompositeLighter:
2071 shader = QStringLiteral(
"fecompositelighter");
2073 case FilterNodeInfo::Type::BlendNormal:
2074 shader = QStringLiteral(
"feblendnormal");
2076 case FilterNodeInfo::Type::BlendMultiply:
2077 shader = QStringLiteral(
"feblendmultiply");
2079 case FilterNodeInfo::Type::BlendScreen:
2080 shader = QStringLiteral(
"feblendscreen");
2082 case FilterNodeInfo::Type::BlendDarken:
2083 shader = QStringLiteral(
"feblenddarken");
2085 case FilterNodeInfo::Type::BlendLighten:
2086 shader = QStringLiteral(
"feblendlighten");
2092 stream() <<
"fragmentShader: \"qrc:/qt-project.org/quickvectorimage/helpers/shaders_ng/"
2093 << shader <<
".frag.qsb\"";
2094 stream() <<
"property var source: " << inputId;
2095 stream() <<
"property var source2: " << input2Id;
2096 stream() <<
"width: source.width";
2097 stream() <<
"height: source.height";
2100 QVector4D k = step.filterParameter.value<QVector4D>();
2101 stream() <<
"property var k: Qt.vector4d("
2114 case FilterNodeInfo::Type::Flood:
2116 stream() <<
"Rectangle {";
2119 stream() <<
"id: " << primitiveId;
2120 stream() <<
"visible: false";
2122 stream() <<
"width: " << inputId <<
".width";
2123 stream() <<
"height: " << inputId <<
".height";
2125 QColor floodColor = step.filterParameter.value<QColor>();
2126 stream() <<
"color: \"" << floodColor.name(QColor::HexArgb) <<
"\"";
2133 case FilterNodeInfo::Type::ColorMatrix:
2135 stream() <<
"ShaderEffect {";
2138 stream() <<
"id: " << primitiveId;
2139 stream() <<
"visible: false";
2141 stream() <<
"fragmentShader: \"qrc:/qt-project.org/quickvectorimage/helpers/shaders_ng/fecolormatrix.frag.qsb\"";
2142 stream() <<
"property var source: " << inputId;
2143 stream() <<
"width: source.width";
2144 stream() <<
"height: source.height";
2146 QGenericMatrix<5, 5, qreal> matrix = step.filterParameter.value<QGenericMatrix<5, 5, qreal> >();
2147 for (
int row = 0; row < 4; ++row) {
2150 for (
int col = 0; col < 5; ++col)
2151 stream() <<
"property real m_" << row <<
"_" << col <<
": " << matrix(col, row);
2160 case FilterNodeInfo::Type::Offset:
2162 stream() <<
"ShaderEffectSource {";
2165 stream() <<
"id: " << primitiveId;
2166 stream() <<
"visible: false";
2167 stream() <<
"sourceItem: " << inputId;
2168 stream() <<
"width: sourceItem.width + offset.x";
2169 stream() <<
"height: sourceItem.height + offset.y";
2171 QVector2D offset = step.filterParameter.value<QVector2D>();
2172 stream() <<
"property vector2d offset: Qt.vector2d(";
2173 if (step.csFilterParameter == FilterNodeInfo::CoordinateSystem::Absolute)
2174 stream(SameLine) << offset.x() <<
" / width, " << offset.y() <<
" / height)";
2176 stream(SameLine) << offset.x() <<
", " << offset.y() <<
")";
2178 stream() <<
"sourceRect: Qt.rect(-offset.x, -offset.y, width, height)";
2180 stream() <<
"ItemSpy {";
2182 stream() <<
"id: " << primitiveId <<
"_offset_itemspy";
2183 stream() <<
"anchors.fill: parent";
2187 stream() <<
"textureSize: " << primitiveId <<
"_offset_itemspy.requiredTextureSize";
2196 case FilterNodeInfo::Type::GaussianBlur:
2199 stream() <<
"MultiEffect {";
2202 stream() <<
"id: " << primitiveId;
2203 stream() <<
"visible: false";
2205 stream() <<
"source: " << inputId;
2206 stream() <<
"blurEnabled: true";
2207 stream() <<
"width: source.width";
2208 stream() <<
"height: source.height";
2210 const qreal maxDeviation(12.0);
2211 const qreal deviation = step.filterParameter.toReal();
2212 if (step.csFilterParameter == FilterNodeInfo::CoordinateSystem::Relative)
2213 stream() <<
"blur: Math.min(1.0, " << deviation <<
" * filterSourceItem.width / " << maxDeviation <<
")";
2215 stream() <<
"blur: " << std::min(qreal(1.0), deviation / maxDeviation);
2216 stream() <<
"blurMax: 64";
2224 qCWarning(lcQuickVectorImage) <<
"Unhandled filter type: " <<
int(step.filterType);
2226 stream() <<
"Item { id: " << primitiveId <<
" }";
2231 stream() <<
"ShaderEffectSource {";
2234 stream() <<
"id: " << step.outputName;
2235 if (stepIndex < info.steps.size())
2236 stream() <<
"visible: false";
2238 qreal x1, x2, y1, y2;
2239 step.filterPrimitiveRect.getCoords(&x1, &y1, &x2, &y2);
2240 if (step.csFilterParameter == FilterNodeInfo::CoordinateSystem::Absolute) {
2241 stream() <<
"property real fpx1: " << x1;
2242 stream() <<
"property real fpy1: " << y1;
2243 stream() <<
"property real fpx2: " << x2;
2244 stream() <<
"property real fpy2: " << y2;
2245 }
else if (step.csFilterParameter == FilterNodeInfo::CoordinateSystem::Relative) {
2249 stream() <<
"property real fpx1: " << x1 <<
" * filterSourceItem.sourceItem.originalBounds.width";
2250 stream() <<
"property real fpy1: " << y1 <<
" * filterSourceItem.sourceItem.originalBounds.height";
2251 stream() <<
"property real fpx2: " << x2 <<
" * filterSourceItem.sourceItem.originalBounds.width";
2252 stream() <<
"property real fpy2: " << y2 <<
" * filterSourceItem.sourceItem.originalBounds.height";
2254 stream() <<
"property real fpx1: parent.filterRect.x";
2255 stream() <<
"property real fpy1: parent.filterRect.y";
2256 stream() <<
"property real fpx2: parent.filterRect.x + parent.filterRect.width";
2257 stream() <<
"property real fpy2: parent.filterRect.y + parent.filterRect.height";
2260 stream() <<
"sourceItem: " << primitiveId;
2261 stream() <<
"sourceRect: Qt.rect(fpx1 - parent.filterRect.x, fpy1 - parent.filterRect.y, width, height)";
2263 stream() <<
"x: fpx1";
2264 stream() <<
"y: fpy1";
2265 stream() <<
"width: " <<
"fpx2 - fpx1";
2266 stream() <<
"height: " <<
"fpy2 - fpy1";
2268 stream() <<
"ItemSpy {";
2270 stream() <<
"id: " << primitiveId <<
"_itemspy";
2271 stream() <<
"anchors.fill: parent";
2275 stream() <<
"textureSize: " << primitiveId <<
"_itemspy.requiredTextureSize";
2283void QQuickQmlGenerator::generateTimelineFields(
const StructureNodeInfo &info)
2285 if (usingTimelineAnimation() && info.timelineInfo) {
2286 QString frameCounterRef = info.timelineInfo->frameCounterReference
2287 + QStringLiteral(
".frameCounter");
2289 if (info.timelineInfo->generateVisibility) {
2290 stream() <<
"visible: " << frameCounterRef <<
" >= " << info.timelineInfo->startFrame
2291 <<
" && " << frameCounterRef <<
" < " << info.timelineInfo->endFrame;
2294 if (info.timelineInfo->generateFrameCounter) {
2295 stream() <<
"property real frameCounter: ";
2296 if (info.timelineInfo->frameCounterMapper.isAnimated()) {
2298 stream(SameLine) <<
"0";
2299 generatePropertyTimeline(info.timelineInfo->frameCounterMapper, info.id,
"frameCounter"_L1);
2301 const auto offset = info.timelineInfo->frameCounterOffset;
2302 const auto multiplier = info.timelineInfo->frameCounterMultiplier;
2303 const bool needsParens = (offset && multiplier);
2305 stream(SameLine) <<
"(";
2306 stream(SameLine) << frameCounterRef;
2308 stream(SameLine) << (offset > 0 ?
" + " :
" - ") << qAbs(offset);
2310 stream(SameLine) <<
")";
2312 stream(SameLine) <<
" * " << multiplier;
2318bool QQuickQmlGenerator::generatePatternNode(
const PatternNodeInfo &info)
2320 if (info.stage == StructureNodeStage::Start) {
2323 startDefsSuffixBlock();
2324 stream() <<
"Loader {";
2327 stream() <<
"id: " << info.id;
2328 stream() <<
"sourceComponent: " << info.id <<
"_container";
2329 stream() <<
"width: item !== null ? item.originalBounds.width : 0";
2330 stream() <<
"height: item !== null ? item.originalBounds.height : 0";
2331 stream() <<
"visible: false";
2332 stream() <<
"function sourceRect(targetWidth, targetHeight) {";
2335 stream() <<
"return Qt.rect(0, 0, ";
2336 if (!info.isPatternRectRelativeCoordinates) {
2337 stream(SameLine) << info.patternRect.width() <<
", "
2338 << info.patternRect.height();
2340 stream(SameLine) << info.patternRect.width() <<
" * targetWidth, "
2341 << info.patternRect.height() <<
" * targetHeight";
2343 stream(SameLine) <<
")";
2347 stream() <<
"function sourceOffset(targetWidth, targetHeight) {";
2350 stream() <<
"return Qt.vector3d(";
2351 if (!info.isPatternRectRelativeCoordinates) {
2352 stream(SameLine) << info.patternRect.x() <<
", "
2353 << info.patternRect.y() <<
", ";
2355 stream(SameLine) << info.patternRect.x() <<
" * targetWidth, "
2356 << info.patternRect.y() <<
" * targetHeight, ";
2358 stream(SameLine) <<
"0.0)";
2366 endDefsSuffixBlock();
2372void QQuickQmlGenerator::generateDefsInstantiationNode(
const StructureNodeInfo &info)
2374 if (Q_UNLIKELY(errorState()))
2377 if (info.stage == StructureNodeStage::Start) {
2378 stream() <<
"Loader {";
2381 stream() <<
"sourceComponent: " << info.defsId <<
"_container";
2382 generateNodeBase(info);
2383 generateTimelineFields(info);
2390bool QQuickQmlGenerator::generateMarkerNode(
const MarkerNodeInfo &info)
2392 if (info.stage == StructureNodeStage::Start) {
2393 startDefsSuffixBlock();
2394 stream() <<
"QtObject {";
2397 stream() <<
"id: " << info.id <<
"_markerParameters";
2399 stream() <<
"property bool startReversed: ";
2400 if (info.orientation == MarkerNodeInfo::Orientation::AutoStartReverse)
2401 stream(SameLine) <<
"true";
2403 stream(SameLine) <<
"false";
2405 stream() <<
"function autoAngle(adaptedAngle) {";
2407 if (info.orientation == MarkerNodeInfo::Orientation::Value)
2408 stream() <<
"return " << info.angle;
2410 stream() <<
"return adaptedAngle";
2416 endDefsSuffixBlock();
2418 if (!info.clipBox.isEmpty()) {
2419 stream() <<
"Item {";
2422 stream() <<
"x: " << info.clipBox.x();
2423 if (info.markerUnits == MarkerNodeInfo::MarkerUnits::StrokeWidth)
2424 stream(SameLine) <<
" * strokeWidth";
2425 stream() <<
"y: " << info.clipBox.y();
2426 if (info.markerUnits == MarkerNodeInfo::MarkerUnits::StrokeWidth)
2427 stream(SameLine) <<
" * strokeWidth";
2428 stream() <<
"width: " << info.clipBox.width();
2429 if (info.markerUnits == MarkerNodeInfo::MarkerUnits::StrokeWidth)
2430 stream(SameLine) <<
" * strokeWidth";
2431 stream() <<
"height: " << info.clipBox.height();
2432 if (info.markerUnits == MarkerNodeInfo::MarkerUnits::StrokeWidth)
2433 stream(SameLine) <<
" * strokeWidth";
2434 stream() <<
"clip: true";
2437 stream() <<
"Item {";
2440 if (!info.clipBox.isEmpty()) {
2441 stream() <<
"x: " << -info.clipBox.x();
2442 if (info.markerUnits == MarkerNodeInfo::MarkerUnits::StrokeWidth)
2443 stream(SameLine) <<
" * strokeWidth";
2444 stream() <<
"y: " << -info.clipBox.y();
2445 if (info.markerUnits == MarkerNodeInfo::MarkerUnits::StrokeWidth)
2446 stream(SameLine) <<
" * strokeWidth";
2449 stream() <<
"id: " << info.id;
2451 stream() <<
"property real markerWidth: " << info.markerSize.width();
2452 if (info.markerUnits == MarkerNodeInfo::MarkerUnits::StrokeWidth)
2453 stream(SameLine) <<
" * strokeWidth";
2455 stream() <<
"property real markerHeight: " << info.markerSize.height();
2456 if (info.markerUnits == MarkerNodeInfo::MarkerUnits::StrokeWidth)
2457 stream(SameLine) <<
" * strokeWidth";
2459 stream() <<
"function calculateMarkerScale(w, h) {";
2462 stream() <<
"var scaleX = 1.0";
2463 stream() <<
"var scaleY = 1.0";
2464 stream() <<
"var offsetX = 0.0";
2465 stream() <<
"var offsetY = 0.0";
2466 if (info.viewBox.width() > 0)
2467 stream() <<
"if (w > 0) scaleX = w / " << info.viewBox.width();
2468 if (info.viewBox.height() > 0)
2469 stream() <<
"if (h > 0) scaleY = h / " << info.viewBox.height();
2471 if (info.preserveAspectRatio & MarkerNodeInfo::xyMask) {
2472 stream() <<
"if (scaleX != scaleY) {";
2475 if (info.preserveAspectRatio & MarkerNodeInfo::meet)
2476 stream() <<
"scaleX = scaleY = Math.min(scaleX, scaleY)";
2478 stream() <<
"scaleX = scaleY = Math.max(scaleX, scaleY)";
2480 QString overflowX = QStringLiteral(
"scaleX * %1 - w").arg(info.viewBox.width());
2481 QString overflowY = QStringLiteral(
"scaleY * %1 - h").arg(info.viewBox.height());
2483 const quint8 xRatio = info.preserveAspectRatio & MarkerNodeInfo::xMask;
2484 if (xRatio == MarkerNodeInfo::xMid)
2485 stream() <<
"offsetX -= " << overflowX <<
" / 2";
2486 else if (xRatio == MarkerNodeInfo::xMax)
2487 stream() <<
"offsetX -= " << overflowX;
2489 const quint8 yRatio = info.preserveAspectRatio & MarkerNodeInfo::yMask;
2490 if (yRatio == MarkerNodeInfo::yMid)
2491 stream() <<
"offsetY -= " << overflowY <<
" / 2";
2492 else if (yRatio == MarkerNodeInfo::yMax)
2493 stream() <<
"offsetY -= " << overflowY;
2499 stream() <<
"return Qt.vector4d("
2500 <<
"offsetX - " << info.anchorPoint.x() <<
" * scaleX, "
2501 <<
"offsetY - " << info.anchorPoint.y() <<
" * scaleY, "
2508 stream() <<
"property vector4d markerScale: calculateMarkerScale(markerWidth, markerHeight)";
2510 stream() <<
"transform: [";
2513 stream() <<
"Scale { xScale: " << info.id <<
".markerScale.z; yScale: " << info.id <<
".markerScale.w },";
2514 stream() <<
"Translate { x: " << info.id <<
".markerScale.x; y: " << info.id <<
".markerScale.y }";
2520 generateNodeEnd(info);
2522 if (!info.clipBox.isEmpty()) {
2531bool QQuickQmlGenerator::generateRootNode(
const StructureNodeInfo &info)
2533 if (Q_UNLIKELY(errorState()))
2536 const QStringList comments = m_commentString.split(u'\n');
2538 if (!isNodeVisible(info)) {
2541 if (comments.isEmpty()) {
2542 stream() <<
"// Generated from SVG";
2544 for (
const auto &comment : comments)
2545 stream() <<
"// " << comment;
2548 stream() <<
"import QtQuick";
2549 stream() <<
"import QtQuick.Shapes" << Qt::endl;
2550 stream() <<
"Item {";
2553 double w = info.size.width();
2554 double h = info.size.height();
2556 stream() <<
"implicitWidth: " << w;
2558 stream() <<
"implicitHeight: " << h;
2566 if (info.stage == StructureNodeStage::Start) {
2569 if (comments.isEmpty())
2570 stream() <<
"// Generated from SVG";
2572 for (
const auto &comment : comments)
2573 stream() <<
"// " << comment;
2575 stream() <<
"import QtQuick";
2576 stream() <<
"import QtQuick.VectorImage";
2577 stream() <<
"import QtQuick.VectorImage.Helpers";
2578 stream() <<
"import QtQuick.Shapes";
2579 stream() <<
"import QtQuick.Effects";
2580 if (usingTimelineAnimation())
2581 stream() <<
"import QtQuick.Timeline";
2583 for (
const auto &import : std::as_const(m_extraImports))
2584 stream() <<
"import " << import;
2586 stream() << Qt::endl <<
"Item {";
2589 double w = info.size.width();
2590 double h = info.size.height();
2592 stream() <<
"implicitWidth: " << w;
2594 stream() <<
"implicitHeight: " << h;
2596 if (Q_UNLIKELY(!isRuntimeGenerator())) {
2597 stream() <<
"component AnimationsInfo : QtObject";
2602 stream() <<
"property bool paused: false";
2603 stream() <<
"property int loops: 1";
2604 stream() <<
"signal restart()";
2606 if (Q_UNLIKELY(!isRuntimeGenerator())) {
2609 stream() <<
"property AnimationsInfo animations : AnimationsInfo {}";
2612 stream() <<
"Item {";
2614 stream() <<
"width: 1";
2615 stream() <<
"height: 1";
2617 stream() <<
"ItemSpy { id: __qt_toplevel_scale_itemspy; anchors.fill: parent }";
2622 if (!info.viewBox.isEmpty()) {
2623 stream() <<
"transform: [";
2625 bool translate = !qFuzzyIsNull(info.viewBox.x()) || !qFuzzyIsNull(info.viewBox.y());
2627 stream() <<
"Translate { x: " << -info.viewBox.x() <<
"; y: " << -info.viewBox.y() <<
" },";
2628 stream() <<
"Scale { xScale: width / " << info.viewBox.width() <<
"; yScale: height / " << info.viewBox.height() <<
" }";
2633 if (!info.forceSeparatePaths && info.isPathContainer) {
2634 m_topLevelIdString = QStringLiteral(
"__qt_toplevel");
2635 stream() <<
"id: " << m_topLevelIdString;
2637 generatePathContainer(info);
2640 generateNodeBase(info);
2642 m_topLevelIdString = generateNodeBase(info);
2643 if (m_topLevelIdString.isEmpty())
2644 qCWarning(lcQuickVectorImage) <<
"No ID specified for top level item";
2647 if (usingTimelineAnimation() && info.timelineInfo) {
2648 stream() <<
"property real startFrame: " << info.timelineInfo->startFrame;
2649 stream() <<
"property real endFrame: " << info.timelineInfo->endFrame;
2650 stream() <<
"property real frameRate: " << info.timelineInfo->frameRate;
2651 stream() <<
"property real frameCounter: " << info.timelineInfo->startFrame;
2652 if (!info.timelineInfo->markers.isEmpty()) {
2653 QStringList markerEntries;
2654 markerEntries.reserve(info.timelineInfo->markers.size());
2655 for (
const LottieMarkerInfo &marker : info.timelineInfo->markers) {
2656 markerEntries << u'"' + sanitizeString(marker.name) + u"\": ["
2657 + QString::number(marker.frame) + u", "
2658 + QString::number(marker.duration) + u']';
2660 stream() <<
"property var markers: ({" << markerEntries.join(
", "_L1) <<
"})";
2662 stream() <<
"NumberAnimation on frameCounter {";
2664 stream() <<
"objectName: \"_qt_frameCounterAnimation\"";
2665 stream() <<
"from: " << m_topLevelIdString <<
".startFrame";
2666 stream() <<
"to: " << m_topLevelIdString <<
".endFrame";
2667 stream() <<
"duration: " << processAnimationTime(1000) <<
" * Math.abs(to - from) / "
2668 <<
"Math.max(" << m_topLevelIdString <<
".frameRate, 1)";
2669 generateAnimationBindings();
2672 stream() <<
"visible: frameCounter >= " << info.timelineInfo->startFrame
2673 <<
" && frameCounter < " << info.timelineInfo->endFrame;
2676 if (m_inShapeItemLevel > 0) {
2677 m_inShapeItemLevel--;
2682 for (
const auto [coords, id] : m_easings.asKeyValueRange()) {
2683 stream() <<
"readonly property easingCurve " << id <<
": ({ type: Easing.BezierSpline, bezierCurve: [ ";
2684 for (
auto coord : coords)
2685 stream(SameLine) << coord <<
", ";
2686 stream(SameLine) <<
"1, 1 ] })";
2689 generateNodeEnd(info);
2696void QQuickQmlGenerator::startDefsSuffixBlock()
2698 int tmp = m_oldIndentLevels.top();
2699 m_oldIndentLevels.push(m_indentLevel);
2700 m_indentLevel = tmp;
2701 m_stream.setString(&m_defsSuffix);
2704void QQuickQmlGenerator::endDefsSuffixBlock()
2706 m_indentLevel = m_oldIndentLevels.pop();
2707 m_stream.setDevice(&m_result);
2710QStringView QQuickQmlGenerator::indent()
2712 int indentWidth = m_indentLevel * 4;
2713 if (indentWidth > m_indentString.size())
2714 m_indentString.fill(QLatin1Char(
' '), indentWidth * 2);
2715 return QStringView(m_indentString).first(indentWidth);
2718QTextStream &QQuickQmlGenerator::stream(
int flags)
2720 if (m_stream.device() ==
nullptr && m_stream.string() ==
nullptr)
2721 m_stream.setDevice(&m_result);
2722 else if (!(flags & StreamFlags::SameLine))
2723 m_stream << Qt::endl << indent();
2725 static qint64 maxBufferSize = qEnvironmentVariableIntegerValue(
"QT_QUICKVECTORIMAGE_MAX_BUFFER").value_or(64 << 20);
2726 if (m_stream.device()) {
2727 if (Q_UNLIKELY(!checkSanityLimit(m_stream.device()->size(), maxBufferSize,
"buffer size"_L1)))
2728 m_stream.device()->reset();
2730 if (Q_UNLIKELY(!checkSanityLimit(m_stream.string()->size(), maxBufferSize,
"buffer string size"_L1)))
2731 m_stream.string()->clear();
2737const char *QQuickQmlGenerator::shapeName()
const
2739 return m_shapeTypeName.isEmpty() ?
"Shape" : m_shapeTypeName.constData();
Combined button and popup list for selecting options.
static QString sanitizeString(const QString &input)
static int processAnimationTime(int time)