aboutsummaryrefslogtreecommitdiffstats
path: root/tools/svgtoqml/qsvgloader.cpp
blob: 3d924bbdeb68f404b5ae83a01c11ac934c255906 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include "qsvgloader_p.h"
#include <private/qsvgvisitor_p.h>

#include <QString>
#include <QPainter>
#include <QMatrix4x4>
#include <QQuickItem>

#include <private/qquickshape_p.h>
#include <private/qquicktext_p.h>
#include <private/qquicktranslate_p.h>
#include <private/qquickitem_p.h>

#include <private/qquickimagebase_p_p.h>
#include <private/qquickimage_p.h>

#include <private/qquadpath_p.h>

QT_BEGIN_NAMESPACE

class RaiiStream : public QTextStream
{
public:
    RaiiStream() = default;
    explicit RaiiStream(QTextStream *stream): QTextStream(&output, QIODevice::ReadWrite), m_stream(stream) {}
    ~RaiiStream() {
        flush();
        if (m_stream && !output.isEmpty())
            *m_stream << output << Qt::endl;
    }

    RaiiStream(RaiiStream &other) = delete;
    RaiiStream &operator=(const RaiiStream &other) = delete;
    RaiiStream(RaiiStream &&other) : m_stream(std::exchange(other.m_stream, nullptr)), output(std::move(other.output)) {}
    RaiiStream &operator=(RaiiStream &&other) {
        std::swap(m_stream, other.m_stream);
        std::swap(output, other.output);
        return *this;
    }

private:
    QTextStream *m_stream = nullptr;
    QByteArray output;
};

class SvgLoaderVisitor : public QSvgVisitor
{
public:
    SvgLoaderVisitor();
    ~SvgLoaderVisitor();
    void setShapeTypeName(const QString &name) { m_shapeTypeName = name.toLatin1(); }
    QQuickItem *loadQML(QTextStream *stream, const QSvgTinyDocument *doc, QQuickItem *svgItem);

protected:
    void visitNode(const QSvgNode *) override;

    bool visitStructureNodeStart(const QSvgStructureNode *node) override;
    void visitStructureNodeEnd(const QSvgStructureNode *node) override;
    bool visitDefsNodeStart(const QSvgDefs *node) override;

    void visitTextNode(const QSvgText *node) override;
    void visitPathNode(const QSvgPath *node) override;
    void visitRectNode(const QSvgRect *node) override;
    void visitEllipseNode(const QSvgEllipse *node) override;

    void visitLineNode(const QSvgLine *node) override;
    void visitPolygonNode(const QSvgPolygon *node) override;
    void visitPolylineNode(const QSvgPolyline *node) override;

    void visitImageNode(const QSvgImage *node) override;

private:
    QString indent() { return QString().fill(' ', m_indentLevel * 4);}
    RaiiStream stream() {
        RaiiStream strm(m_stream);
        strm << indent();
        return strm;
    }

    const char *shapeName() const { return m_shapeTypeName.isEmpty() ? "Shape" : m_shapeTypeName.constData(); }

    QString currentFillColor() const;
    const QGradient *currentFillGradient() const;
    QString currentStrokeColor() const;
    float currentStrokeWidth() const;

    void handleBaseNodeSetup(const QSvgNode *node);
    void handleBaseNode(const QSvgNode *node);
    void handleBaseNodeEnd(const QSvgNode *node);
    void handlePathNode(const QSvgNode *node, const QPainterPath &path, Qt::PenCapStyle = Qt::SquareCap);
    void outputShapePath(const QSvgNode *node, const QPainterPath &path, Qt::PenCapStyle capStyle);

    QQuickItem *currentItem() { return m_items.top(); }
    void addCurrentItem(QQuickItem *item, const QSvgNode *node = nullptr) {
        item->setParentItem(currentItem());
        m_items.push(item);
        if (node) {
            if (!node->nodeId().isEmpty())
                item->setObjectName(node->nodeId());
            else
                item->setObjectName(node->typeName());
        }
    }

    int m_indentLevel = 0;
    QTextStream *m_stream = nullptr;
    QPainter m_dummyPainter;
    QImage m_dummyImage;
    QSvgExtraStates m_svgState;
    bool m_inShapeItem = false;
    QQuickShape *m_parentShapeItem = nullptr;
    QByteArray m_shapeTypeName;

    QStack<QQuickItem *> m_items;

    QQuickItem *m_loadedItem = nullptr;
    bool m_generateQML = true;
    bool m_generateItems = false;
};

SvgLoaderVisitor::SvgLoaderVisitor()
{
    m_dummyImage = QImage(1, 1, QImage::Format_RGB32);
    m_dummyPainter.begin(&m_dummyImage);
    QPen noPen(Qt::NoPen);
    noPen.setBrush(Qt::NoBrush);
    m_dummyPainter.setPen(noPen);
    m_dummyPainter.setBrush(Qt::black);
}

SvgLoaderVisitor::~SvgLoaderVisitor()
{
    m_dummyPainter.end();
}

void SvgLoaderVisitor::handlePathNode(const QSvgNode *node, const QPainterPath &path, Qt::PenCapStyle capStyle)
{
    handleBaseNodeSetup(node);

    if (m_inShapeItem) {
        if (!node->style().transform.isDefault())
            qWarning() << "Skipped transform for node" << node->nodeId() << "type" << node->typeName() << "(this is not supposed to happen)";
        outputShapePath(node, path, capStyle);
    } else {
        if (m_generateItems) {
            auto *shapeItem = new QQuickShape;
            shapeItem->setPreferredRendererType(QQuickShape::CurveRenderer);
            shapeItem->setContainsMode(QQuickShape::ContainsMode::FillContains); // TODO: configurable?
            addCurrentItem(shapeItem, node);
            m_parentShapeItem = shapeItem;
        }
        m_inShapeItem = true;
        stream() << shapeName() << " {";
        handleBaseNode(node);
        m_indentLevel++;
        outputShapePath(node, path, capStyle);
        //qDebug() << *node->qpath();
        m_indentLevel--;
        stream() << "}";
        if (m_generateItems)
            m_items.pop();
        m_inShapeItem = false;
        m_parentShapeItem = nullptr;
    }
    handleBaseNodeEnd(node);
}

void SvgLoaderVisitor::visitPathNode(const QSvgPath *node)
{
    stream() << "// PATH visit " << node->nodeId() << " count: " << node->path().elementCount();
    handlePathNode(node, node->path());
}

void SvgLoaderVisitor::visitLineNode(const QSvgLine *node)
{
    // TODO: proper end caps (should be flat by default?)
    QPainterPath p;
    p.moveTo(node->line().p1());
    p.lineTo(node->line().p2());
    handlePathNode(node, p, Qt::FlatCap);
}

static QPainterPath polygonToPath(const QPolygonF &poly, bool closed)
{
    QPainterPath path;
    if (poly.isEmpty())
        return path;
    bool first = true;
    for (const auto &p : poly) {
        if (first)
            path.moveTo(p);
        else
            path.lineTo(p);
        first = false;
    }
    if (closed)
        path.closeSubpath();
    return path;
}

void SvgLoaderVisitor::visitPolygonNode(const QSvgPolygon *node)
{
    stream() << "// POLYGON visit " << node->nodeId() << " count: " << node->polygon().count();
    QPainterPath p = polygonToPath(node->polygon(), true);
    handlePathNode(node, p);
}

void SvgLoaderVisitor::visitPolylineNode(const QSvgPolyline *node)
{
    stream() << "// POLYLINE visit " << node->nodeId() << " count: " << node->polygon().count();
    QPainterPath p = polygonToPath(node->polygon(), false);
    handlePathNode(node, p, Qt::FlatCap);
}

void SvgLoaderVisitor::visitImageNode(const QSvgImage *node)
{
    // TODO: this requires proper asset management.
    stream() << "// IMAGE visit " << node->nodeId() << " type: " << node->typeName() << " " << node->type();

    handleBaseNodeSetup(node);
    const auto &img = node->image();
    QRectF rect = node->rect();

    if (m_generateItems) {
        auto *imageItem = new QQuickImage;
        addCurrentItem(imageItem, node);
        auto *imagePriv = static_cast<QQuickImageBasePrivate*>(QQuickItemPrivate::get(imageItem));
        imagePriv->pix.setImage(img);

        imageItem->setX(rect.x());
        imageItem->setY(rect.y());
        imageItem->setWidth(rect.width());
        imageItem->setHeight(rect.height());
    }

    QString fn = img.hasAlphaChannel() ? QStringLiteral("svg_asset_%1.png").arg(img.cacheKey()) : QStringLiteral("svg_asset_%1.jpg").arg(img.cacheKey());
    if (m_generateQML) {
        // For now we just create a copy of the image in the current directory
        img.save(fn);
        qDebug() << "Saving copy of IMAGE" << fn;
    }
    stream() << "Image {";
    handleBaseNode(node);
    m_indentLevel++;
    stream() << "x: " << rect.x();
    stream() << "y: " << rect.y();
    stream() << "width: " << rect.width();
    stream() << "height: " << rect.height();
    stream() << "source: \"" << fn <<"\"";

    m_indentLevel--;
    stream() << "}";
    handleBaseNodeEnd(node);
    if (m_generateItems)
        m_items.pop();
}

void SvgLoaderVisitor::visitTextNode(const QSvgText *node)
{
    // TODO: font/size
    // TODO: fallback to path for gradient fill
    stream() << "// TEXT visit " << node->nodeId() << " type: " << node->typeName() << " " << node->type();
    QPointF pos = node->position();
    static int counter = 0;

    const bool isTextArea = node->type() == QSvgNode::Textarea;
    QQuickItem *alignItem = nullptr;
    QQuickText *textItem = nullptr;
    if (!isTextArea) {
        stream() << "Item { id: textAlignItem_" << counter << "; x: " << pos.x() << "; y: " << pos.y() << "}";
        if (m_generateItems) {
            alignItem = new QQuickItem(currentItem());
            alignItem->setX(pos.x());
            alignItem->setY(pos.y());
        }
    }
    stream() << "Text {";

    if (m_generateItems) {
        textItem = new QQuickText;
        addCurrentItem(textItem, node);
    }
    handleBaseNodeSetup(node);
    m_indentLevel++;

    if (isTextArea) {
        stream() << "x: " << pos.x();
        stream() << "y: " << pos.y();
        stream() << "width: " << node->size().width();
        stream() << "height: " << node->size().height();
        stream() << "wrapMode: Text.Wrap"; // ### WordWrap? verify with SVG standard
        stream() << "clip: true"; //### Not exactly correct: should clip on the text level, not the pixel level
        if (textItem) {
            textItem->setX(pos.x());
            textItem->setY(pos.y());
            textItem->setWidth(node->size().width());
            textItem->setHeight(node->size().height());
            textItem->setWrapMode(QQuickText::Wrap);
            textItem->setClip(true);
        }
    } else {
        auto *anchors = m_generateItems ? QQuickItemPrivate::get(textItem)->anchors() : nullptr;
        auto *alignPrivate = m_generateItems ? QQuickItemPrivate::get(alignItem) : nullptr;
        if (m_generateItems)
            anchors->setBaseline(alignPrivate->top());
        QString hAlign = QStringLiteral("left");
        stream() << "anchors.baseline: textAlignItem_" << counter << ".top";
        switch (m_svgState.textAnchor) {
        case Qt::AlignHCenter:
            hAlign = "horizontalCenter";
            if (m_generateItems)
                anchors->setHorizontalCenter(alignPrivate->left());
            break;
        case Qt::AlignRight:
            hAlign = "right";
            if (m_generateItems)
                anchors->setRight(alignPrivate->left());
            break;
        default:
            qDebug() << "Unexpected text alignment" << m_svgState.textAnchor;
            Q_FALLTHROUGH();
        case Qt::AlignLeft:
            if (m_generateItems)
                anchors->setLeft(alignPrivate->left());
            break;
        }
        stream() << "anchors." << hAlign << ": textAlignItem_" << counter << ".left";
    }
    counter++;
    QString text;
    for (const auto *tspan : node->tspans()) {
        if (!tspan) {
            text += "<br>";
            continue;
        }

        if (!tspan->style().font.isDefault()) // TODO: switch to rich text when we have more complex spans with fonts?
            qDebug() << "Not implemented Tspan with font:" << tspan->style().font->qfont();
        QString spanColor;
        if (!tspan->style().fill.isDefault()) {
            auto &b = tspan->style().fill->qbrush();
            qDebug() << "tspan FILL:" << b;
            if (b.style() != Qt::NoBrush)
                spanColor = b.color().name();
        }
        bool fontTag = !spanColor.isEmpty();
        if (fontTag)
            text += QStringLiteral("<font color=\"%1\">").arg(spanColor); // TODO: size="1-7" ???
        text += tspan->text().toHtmlEscaped();
        if (fontTag)
            text += QStringLiteral("</font>");
    }
    stream() << "color: \"" << currentFillColor() << "\"";
    stream() << "textFormat: Text.StyledText";

    QFont font = m_dummyPainter.font();

    stream() << "text: \"" << text << "\""; // TODO: how about adding template<T> TestVisitor::streamProperty(const QString &name, const T &value)
    stream() << "font.family: \"" << font.family() << "\"";
    if (font.pixelSize() > 0)
        stream() << "font.pixelSize:" << font.pixelSize();
    else if (font.pointSize() > 0)
        stream() << "font.pixelSize:" << font.pointSizeF();
    if (font.underline())
        stream() << "font.underline: true";
    if (font.weight() != QFont::Normal)
        stream() << "font.weight: " << int(font.weight());

    if (font.pixelSize() <= 0 && font.pointSize() > 0)
        font.setPixelSize(font.pointSize()); // ### TODO: this makes no sense ###

    if (m_generateItems) {
        textItem->setColor(QColor::fromString(currentFillColor()));
        textItem->setTextFormat(QQuickText::StyledText);
        textItem->setText(text);
        textItem->setFont(font);
    }

    m_indentLevel--;
    stream() << "}";
    if (m_generateItems)
        m_items.pop();
    handleBaseNodeEnd(node);
}

//#define EXTRA_DEBUG
#ifdef EXTRA_DEBUG
static int nodeSetupLevel = 0;
#endif

void SvgLoaderVisitor::handleBaseNodeSetup(const QSvgNode *node)
{
#ifdef EXTRA_DEBUG
    qDebug() << QByteArray().fill(' ', m_indentLevel * 2).constData() << "before SETUP" << node << "fill" << currentFillColor()
        << "stroke" << currentStrokeColor() << currentStrokeWidth() << node->nodeId() << " type: " << node->typeName()  << " " << node->type() << "level" << nodeSetupLevel;
#endif
    node->applyStyle(&m_dummyPainter, m_svgState);

#ifdef EXTRA_DEBUG
    nodeSetupLevel++;
    qDebug() << QByteArray().fill(' ', m_indentLevel * 2).constData() << "after SETUP" << node << "fill" << currentFillColor()
             << "stroke" << currentStrokeColor() << currentStrokeWidth() << node->nodeId();
#endif
}

void SvgLoaderVisitor::handleBaseNode(const QSvgNode *node)
{
    m_indentLevel++;
    if (!node->nodeId().isEmpty())
        stream() << "objectName: \"" << node->nodeId() << "\""; // or maybe "objectName: \"svg_node:" << node->nodeId()
    if (!node->style().transform.isDefault()) {
        QTransform tr = node->style().transform->qtransform();
        auto sx = tr.m11();
        auto sy = tr.m22();
        auto x = tr.m31();
        auto y = tr.m32();
        if (tr.type() == QTransform::TxTranslate) {
            stream() << "// Translate " << tr.m31() << ", " << tr.m32();
            stream() << "transform: Translate { " << "x: " << x << "; y: " << y << " }";
        } else if (tr.type() == QTransform::TxScale && !x && !y) {
            stream() << "// Scale " << tr.m11() << ", " << tr.m22();
            stream() << "transform: Scale { xScale: " << sx << "; yScale: " << sy << " }";
        } else {
            stream() << "// Complex xform " << tr.type();
            const QMatrix4x4 m(tr);
            auto xform = new QQuickMatrix4x4;
            xform->setMatrix(m);
            {
                stream() << "transform: [ Matrix4x4 { matrix: Qt.matrix4x4 (";
                m_indentLevel += 3;
                const auto *data = m.data();
                for (int i = 0; i < 4; i++) {
                    stream() << data[i] << ", " << data[i+4] << ", " << data[i+8] << ", " << data[i+12] << ", ";
                }
                stream() << ")  } ]";
                m_indentLevel -= 3;
            }
        }
        if (m_generateItems) {
            auto xformProp = currentItem()->transform();
            if (tr.type() == QTransform::TxTranslate) {
                auto *translate = new QQuickTranslate;
                translate->setX(x);
                translate->setY(y);
                xformProp.append(&xformProp, translate);
            } else if (tr.type() == QTransform::TxScale && !x && !y) {
                auto scale = new QQuickScale;
                scale->setParent(currentItem());
                scale->setXScale(sx);
                scale->setYScale(sy);
                xformProp.append(&xformProp, scale);
            } else {
                const QMatrix4x4 m(tr);
                auto xform = new QQuickMatrix4x4;
                xform->setMatrix(m);
                xformProp.append(&xformProp, xform);
            }
        }
    }
    if (!node->style().opacity.isDefault()) {
        stream() << "opacity: " << node->style().opacity->opacity();
        if (m_generateItems)
            currentItem()->setOpacity(node->style().opacity->opacity());
    }
    m_indentLevel--;
}

void SvgLoaderVisitor::handleBaseNodeEnd(const QSvgNode *node)
{
    node->revertStyle(&m_dummyPainter, m_svgState);
#ifdef EXTRA_DEBUG
    nodeSetupLevel--;
    qDebug() << QByteArray().fill(' ', m_indentLevel * 2).constData() << "AFTER" << node << "fill" << currentFillColor()
             << "stroke" << currentStrokeColor() << currentStrokeWidth() << node->nodeId() << "level" << nodeSetupLevel;
#endif
}

QString SvgLoaderVisitor::currentFillColor() const
{
    if (m_dummyPainter.brush().style() != Qt::NoBrush) {
        QColor c(m_dummyPainter.brush().color());
        c.setAlphaF(m_svgState.fillOpacity);
        //qDebug() << "FILL" << c << m_svgState.fillOpacity << c.name();
        return c.name(QColor::HexArgb);
    } else {
        return QStringLiteral("transparent");
    }
}

const QGradient *SvgLoaderVisitor::currentFillGradient() const
{

    if (m_dummyPainter.brush().style() == Qt::LinearGradientPattern || m_dummyPainter.brush().style() == Qt::RadialGradientPattern || m_dummyPainter.brush().style() == Qt::ConicalGradientPattern )
       return m_dummyPainter.brush().gradient();
    return nullptr;
}

QString SvgLoaderVisitor::currentStrokeColor() const
{
    if (m_dummyPainter.pen().style() != Qt::NoPen)
        return m_dummyPainter.pen().color().name();
    else if (m_dummyPainter.pen().brush().style() == Qt::SolidPattern)
        return m_dummyPainter.pen().brush().color().name();
    return {};
}

float SvgLoaderVisitor::currentStrokeWidth() const
{
    float penWidth = m_dummyPainter.pen().widthF();
    return penWidth ? penWidth : 1;
}

// Find the square that gives the same gradient in QGradient::LogicalMode as
// objModeRect does in QGradient::ObjectMode

// When the object's bounding box is not square, the stripes that are conceptually
// perpendicular to the gradient vector within object bounding box space shall render
// non-perpendicular relative to the gradient vector in user space due to application
// of the non-uniform scaling transformation from bounding box space to user space.
static QRectF mapToQtLogicalMode(const QRectF &objModeRect, const QRectF &boundingRect)
{

    QRect pixelRect(objModeRect.x() * boundingRect.width() + boundingRect.left(),
                    objModeRect.y() * boundingRect.height() + boundingRect.top(),
                    objModeRect.width() * boundingRect.width(),
                    objModeRect.height() * boundingRect.height());

    if (pixelRect.isEmpty()) // pure horizontal/vertical gradient
        return pixelRect;

    double w = boundingRect.width();
    double h = boundingRect.height();
    double objModeSlope = objModeRect.height() / objModeRect.width();
    double a = objModeSlope * w / h;

    // do calculation with origin == pixelRect.topLeft
    double x2 = pixelRect.width();
    double y2 = pixelRect.height();
    double x = (x2 + a * y2) / (1 + a * a);
    double y = y2 - (x - x2)/a;

    return QRectF(pixelRect.topLeft(), QSizeF(x,y));
}

void SvgLoaderVisitor::outputShapePath(const QSvgNode *node, const QPainterPath &path, Qt::PenCapStyle capStyle)
{
    QPointF offset; // ??? do we need this?

    stream() << "ShapePath {";
    m_indentLevel++;
    auto *shapePath = m_generateItems ? new QQuickShapePath : nullptr;
    if (!node->nodeId().isEmpty()) {
        stream() << "objectName: \"svg_path:" << node->nodeId() << "\"";
        if (m_generateItems)
            shapePath->setObjectName(QStringLiteral("svg_path:") + node->nodeId());
    }
    stream() << "// boundingRect: " << path.boundingRect().x() << ", " << path.boundingRect().y() << " " << path.boundingRect().width() << "x" << path.boundingRect().height();
    QString penName = currentStrokeColor();
    if (penName.isEmpty()) {
        stream() << "strokeColor: \"transparent\"";
        if (m_generateItems)
            shapePath->setStrokeColor(Qt::transparent);
    } else {
        stream() << "strokeColor: \"" << penName << "\"";
        stream() << "strokeWidth: " << currentStrokeWidth();
        if (m_generateItems) {
            shapePath->setStrokeColor(QColor::fromString(penName));
            shapePath->setStrokeWidth(currentStrokeWidth());
        }
    }
    if (capStyle == Qt::FlatCap)
        stream() << "capStyle: ShapePath.FlatCap"; //### TODO

    if (m_generateItems)
        shapePath->setCapStyle(QQuickShapePath::CapStyle(capStyle));

    if (auto *grad = currentFillGradient()) {

        auto setStops = [](QQuickShapeGradient *quickGrad, const QGradientStops &stops) {
            auto stopsProp = quickGrad->stops();
            for (auto &stop : stops) {
                auto *stopObj = new QQuickGradientStop(quickGrad);
                stopObj->setPosition(stop.first);
                stopObj->setColor(stop.second);
                stopsProp.append(&stopsProp, stopObj);
            }
        };

        if (grad->type() == QGradient::LinearGradient) {
            auto *linGrad = static_cast<const QLinearGradient *>(grad);
//            qDebug() << "grad" << linGrad->start() << linGrad->finalStop() << "mode" << linGrad->coordinateMode();
//            qDebug() << "path BR" << path.boundingRect();
            QRectF br = path.boundingRect();
            stream() << "fillGradient: LinearGradient {";
            m_indentLevel++;

            QRectF gradRect(linGrad->start(), linGrad->finalStop());
            QRectF logRect = linGrad->coordinateMode() == QGradient::LogicalMode ? gradRect : mapToQtLogicalMode(gradRect, br);

            stream() << "x1: " << logRect.left();
            stream() << "y1: " << logRect.top();
            stream() << "x2: " << logRect.right();
            stream() << "y2: " << logRect.bottom();
            for (auto &stop : linGrad->stops()) {
                stream() << "GradientStop { position: " << stop.first << "; color: \"" << stop.second.name(QColor::HexArgb) << "\" }";
            }
            m_indentLevel--;
            stream() << "}";

            if (m_generateItems) {
                auto *quickGrad = new QQuickShapeLinearGradient(shapePath);

                quickGrad->setX1(logRect.left());
                quickGrad->setY1(logRect.top());
                quickGrad->setX2(logRect.right());
                quickGrad->setY2(logRect.bottom());
                setStops(quickGrad, linGrad->stops());

                shapePath->setFillGradient(quickGrad);
            }
        } else if (grad->type() == QGradient::RadialGradient) {
            auto *radGrad = static_cast<const QRadialGradient*>(grad);
            stream() << "fillGradient: RadialGradient {";
            m_indentLevel++;

            stream() << "centerX: " << radGrad->center().x();
            stream() << "centerY: " << radGrad->center().y();
            stream() << "centerRadius: " << radGrad->radius();
            stream() << "focalX: centerX; focalY: centerY";
            for (auto &stop : radGrad->stops()) {
                stream() << "GradientStop { position: " << stop.first << "; color: \"" << stop.second.name(QColor::HexArgb) << "\" }";
            }
            m_indentLevel--;
            stream() << "}";

            if (m_generateItems) {
                auto *quickGrad = new QQuickShapeRadialGradient(shapePath);
                quickGrad->setCenterX(radGrad->center().x());
                quickGrad->setCenterY(radGrad->center().y());
                quickGrad->setCenterRadius(radGrad->radius());
                quickGrad->setFocalX(radGrad->center().x());
                quickGrad->setFocalY(radGrad->center().y());
                setStops(quickGrad, radGrad->stops());

                shapePath->setFillGradient(quickGrad);
            }
        }
    } else {
        stream() << "fillColor: \"" << currentFillColor() << "\"";
        if (m_generateItems)
            shapePath->setFillColor(QColor::fromString(currentFillColor()));
    }
    stream() << "fillRule: ShapePath.WindingFill";

    QString svgPathString;
    QTextStream strm(&svgPathString);
    for (int i = 0; i < path.elementCount(); ++i) {
        QPainterPath::Element element = path.elementAt(i);
        if (element.isMoveTo()) {
            strm << "M " << (element.x - offset.x()) << " " << (element.y - offset.y()) << " ";
        } else if (element.isLineTo()) {
            strm << "L " << (element.x - offset.x()) << " " << (element.y - offset.y()) << " ";
        } else if (element.isCurveTo()) {
            QPointF c1((element.x - offset.x()), (element.y - offset.y()));
            ++i;
            element = path.elementAt(i);

            QPointF c2((element.x - offset.x()), (element.y - offset.y()));
            ++i;
            element = path.elementAt(i);

            strm<<  "C "
                 <<  (c1.x() - offset.x()) << " "
                 <<  (c1.y() - offset.y()) << " "
                 <<  (c2.x() - offset.x()) << " "
                 <<  (c2.y() - offset.y()) << " "
                <<  (element.x - offset.x()) << " "
                 <<  (element.y - offset.y()) << " ";
        }
    }
    stream() <<   "PathSvg { path: \"" << svgPathString << "\" }";

    if (m_generateItems) {
        auto *pathSvg = new QQuickPathSvg;
        pathSvg->setPath(svgPathString);
        pathSvg->setParent(shapePath);

        auto pathElementProp = shapePath->pathElements();
        pathElementProp.append(&pathElementProp, pathSvg);

        shapePath->setParent(currentItem());
        auto shapeDataProp = m_parentShapeItem->data();
        shapeDataProp.append(&shapeDataProp, shapePath);
    }
    m_indentLevel--;
    stream() << "}";
}

static bool isPathContainer(const QSvgStructureNode *node)
{
    bool foundPath = false;
    for (const auto *child : node->renderers()) {
        switch (child->type()) {
            // nodes that shouldn't go inside Shape{}
        case QSvgNode::Switch:
        case QSvgNode::Doc:
        case QSvgNode::Group:
        case QSvgNode::Animation:
        case QSvgNode::Use:
        case QSvgNode::Video:
            //qDebug() << "NOT path container because" << node->typeName() ;
            return false;

            // nodes that could go inside Shape{}
        case QSvgNode::Defs:
        case QSvgNode::Image:
        case QSvgNode::Textarea:
        case QSvgNode::Text:
        case QSvgNode::Tspan:
            break;

           // nodes that are done as pure ShapePath{}
        case QSvgNode::Rect:
        case QSvgNode::Circle:
        case QSvgNode::Ellipse:
        case QSvgNode::Line:
        case QSvgNode::Path:
        case QSvgNode::Polygon:
        case QSvgNode::Polyline:
            if (!child->style().transform.isDefault()) {
                //qDebug() << "NOT path container because local transform";
                return false;
            }
            foundPath = true;
            break;
        default:
            qDebug() << "Unhandled type in switch" << child->type();
            break;
        }
    }
    //qDebug() << "Container" << node->nodeId() << node->typeName()  << "is" << foundPath;
    return foundPath;
}

namespace {
class ViewBoxItem : public QQuickItem
{
public:
    ViewBoxItem(const QRectF viewBox, QQuickItem *parent = nullptr) : QQuickItem(parent), m_viewBox(viewBox) { setXForm(); }

protected:
    void geometryChange(const QRectF &/*newGeometry*/, const QRectF &/*oldGeometry*/) override
    {
        setXForm();
    }

private:
    void setXForm()
    {
        auto xformProp = transform();
        xformProp.clear(&xformProp);
        bool translate = !qFuzzyIsNull(m_viewBox.x()) || !qFuzzyIsNull(m_viewBox.y());
        if (translate) {
            auto *tr = new QQuickTranslate(this);
            tr->setX(-m_viewBox.x());
            tr->setY(-m_viewBox.y());
            xformProp.append(&xformProp, tr);
        }
        if (!m_viewBox.isEmpty() && width() && height()) {
            auto *scale = new QQuickScale(this);
            qreal sx = width() / m_viewBox.width();
            qreal sy = height() / m_viewBox.height();

            scale->setXScale(sx);
            scale->setYScale(sy);
            xformProp.append(&xformProp, scale);
        }
    }
    QRectF m_viewBox;
};
}

bool SvgLoaderVisitor::visitDefsNodeStart(const QSvgDefs *node)
{
    stream() << "// skipping DEFS \"" << node->nodeId() << "\"";
    return false; // skip to end; TODO: implement defs
}

bool SvgLoaderVisitor::visitStructureNodeStart(const QSvgStructureNode *node)
{
    constexpr bool forceSeparatePaths = false;
    handleBaseNodeSetup(node);
    stream() << "// START " << node->nodeId() << " type: " << node->typeName() << " " << node->type();

    bool isTopLevel = node->type() == QSvgNode::Doc;
    bool hasViewBox = false;
    QRectF viewBox;

    if (isTopLevel) {
        auto *doc = static_cast<const QSvgTinyDocument *>(node);
        viewBox = doc->viewBox();
        hasViewBox = !viewBox.isEmpty();
    }

    if (!forceSeparatePaths && !isTopLevel && isPathContainer(node)) {
        stream() << shapeName() <<" { //combined path container";
        if (m_generateItems) {
            auto *shapeItem = new QQuickShape;
            shapeItem->setPreferredRendererType(QQuickShape::CurveRenderer); // TODO: settable
            m_inShapeItem = true;
            m_parentShapeItem = shapeItem;
            addCurrentItem(shapeItem, node);
        }
    } else {
        stream() << "Item { // structure node";
        if (m_generateItems) {
            auto *item = hasViewBox ? new ViewBoxItem(viewBox) : new QQuickItem;
            addCurrentItem(item, node );
            if (isTopLevel)
                m_loadedItem = item;
        }
    }
    if (hasViewBox) {
        m_indentLevel++;
        stream() << "transform: [";
        m_indentLevel++;
        bool translate = !qFuzzyIsNull(viewBox.x()) || !qFuzzyIsNull(viewBox.y());
        if (translate)
            stream() << "Translate { x: " << -viewBox.x() << "; y: " << -viewBox.y() << " },";
        stream() << "Scale { xScale: width / " << viewBox.width() << "; yScale: height / " << viewBox.height() << " }";
        m_indentLevel--;
        stream() << "]";;
        m_indentLevel--;
    }
    handleBaseNode(node);
    m_indentLevel++;
    return true;
}

void SvgLoaderVisitor::visitStructureNodeEnd(const QSvgStructureNode *node)
{
    m_indentLevel--;
    stream() << "} // END " << node->nodeId() << " type: " << node->typeName() << " " << node->type();
    handleBaseNodeEnd(node);
//    qDebug() << "REVERT" << node->nodeId() << node->type() << (m_dummyPainter.pen().style() != Qt::NoPen) << m_dummyPainter.pen().color().name()
//             << (m_dummyPainter.pen().brush().style() != Qt::NoBrush) << m_dummyPainter.pen().brush().color().name();
    m_inShapeItem = false;
    m_parentShapeItem = nullptr;
    if (m_generateItems)
        m_items.pop();
}

void SvgLoaderVisitor::visitRectNode(const QSvgRect *node)
{
    QRectF rect = node->rect();
    QPointF rads = node->radius();
    // This is using Qt::RelativeSize semantics: percentage of half rect size
    qreal x1 = rect.left();
    qreal x2 = rect.right();
    qreal y1 = rect.top();
    qreal y2 = rect.bottom();

    qreal rx =  rads.x() * rect.width() / 200;
    qreal ry = rads.y() * rect.height() / 200;
    QPainterPath p;

    p.moveTo(x1 + rx, y1);
    p.lineTo(x2 - rx, y1);
    // qDebug() << "Line1" << x2 - rx << y1;
    p.arcTo(x2 - rx * 2, y1, rx * 2, ry * 2, 90, -90); // ARC to x2, y1 + ry
    // qDebug() << "p1" << p;

    p.lineTo(x2, y2 - ry);
    p.arcTo(x2 - rx * 2, y2 - ry * 2, rx * 2, ry * 2, 0, -90); // ARC to x2 - rx, y2

    p.lineTo(x1 + rx, y2);
    p.arcTo(x1, y2 - ry * 2, rx * 2, ry * 2, 270, -90); // ARC to x1, y2 - ry

    p.lineTo(x1, y1 + ry);
    p.arcTo(x1, y1, rx * 2, ry * 2, 180, -90); // ARC to x1 + rx, y1


    stream() << "// Path from rect " << node->nodeId() << " r " << rect.x() << ", " << rect.y()
             << " " << rect.width() << "x" << rect.height() << " R: " << rads.x() << ", " << rads.y();

    handlePathNode(node, p);

    return;

}

void SvgLoaderVisitor::visitEllipseNode(const QSvgEllipse *node)
{
    QRectF rect = node->rect();
    stream() << "// Ellipse" << node->nodeId() << " rect: " << rect.x() << ", " << rect.y()
             << " " << rect.width() << "x" << rect.height();
    QPainterPath p;
    p.addEllipse(rect);

    handlePathNode(node, p);
}

QQuickItem *SvgLoaderVisitor::loadQML(QTextStream *outStream, const QSvgTinyDocument *doc, QQuickItem *parentItem)
{
    Q_ASSERT(outStream);
    m_stream = outStream;
    m_indentLevel = 0;
    stream() << "import QtQuick";
    stream() << "import QtQuick.Shapes" << Qt::endl;

    QRectF viewBox = doc->viewBox();

    m_generateItems = parentItem != nullptr;
    m_items.push(parentItem);

    stream() << "Item {";
    m_indentLevel++;
    stream() << "// viewBox " << viewBox.x() << ", " << viewBox.y()
         << " " << viewBox.width() << "x" << viewBox.height();
    stream() << "// size " << doc->width() << "x" << doc->height();
    double w = doc->width();
    double h = doc->height();
    if (w > 0)
        stream() << "implicitWidth: " << w;
    if (h > 0)
        stream() << "implicitHeight: " << h;

    if (parentItem) {
        m_generateItems = true;
        parentItem->setImplicitWidth(w);
        parentItem->setImplicitHeight(h);
    }
    traverse(doc);
    m_indentLevel--;
    stream() << "}";
    return m_loadedItem;
}

void SvgLoaderVisitor::visitNode(const QSvgNode *node)
{
    handleBaseNodeSetup(node);
    stream() << "//### SVG NODE NOT IMPLEMENTED: " << node->nodeId() << " type: " << node->typeName()  << " " << node->type();
    stream() << "Item {";
    handleBaseNode(node);
    stream() << "}";
    handleBaseNodeEnd(node);
}

QQuickItem *QSvgQmlWriter::loadSVG(const QSvgTinyDocument *doc, const QString &outFileName, const QString &typeName, QQuickItem *parentItem)
{
    SvgLoaderVisitor visitor;
    if (!typeName.isEmpty())
        visitor.setShapeTypeName(typeName);
    QByteArray result;
    QTextStream str(&result);
    auto *loadedItem = visitor.loadQML(&str, doc, parentItem);
    if (!outFileName.isEmpty()) {
        QFile outFile(outFileName);
        outFile.open(QIODevice::WriteOnly);
        outFile.write(result);
        outFile.close();
    }
#if 0
    result.truncate(300);
    qDebug().noquote() << result;
#endif
    return loadedItem;
}

QT_END_NAMESPACE