summaryrefslogtreecommitdiffstats
path: root/src/graphs2d/qsgrenderer/pointrenderer.cpp
blob: 54bdd4a7552d1ceaa03673c93b6c202d4eae6833 (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
// Copyright (C) 2023 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#ifdef USE_LINEGRAPH
#include <QtGraphs/qlineseries.h>
#endif
#ifdef USE_SCATTERGRAPH
#include <QtGraphs/qscatterseries.h>
#endif
#ifdef USE_SPLINEGRAPH
#include <QtGraphs/qsplineseries.h>
#endif
#include <QtQuick/private/qquickdraghandler_p.h>
#include <QtQuick/private/qquicktaphandler_p.h>
#include <private/axisrenderer_p.h>
#include <private/pointrenderer_p.h>
#include <private/qabstractseries_p.h>
#include <private/qgraphsview_p.h>
#include <private/qxyseries_p.h>

QT_BEGIN_NAMESPACE

static const char *TAG_POINT_COLOR = "pointColor";
static const char *TAG_POINT_BORDER_COLOR = "pointBorderColor";
static const char *TAG_POINT_BORDER_WIDTH = "pointBorderWidth";
static const char *TAG_POINT_SELECTED_COLOR = "pointSelectedColor";
static const char *TAG_POINT_SELECTED = "pointSelected";
static const char *TAG_POINT_VALUE_X = "pointValueX";
static const char *TAG_POINT_VALUE_Y = "pointValueY";
static const char *TAG_POINT_INDEX = "pointIndex";

PointRenderer::PointRenderer(QGraphsView *graph, bool clipPlotArea)
    : QQuickItem(graph)
    , m_graph(graph)
{
    setFlag(QQuickItem::ItemHasContents);
    setClip(clipPlotArea);

    m_shape.setParentItem(this);
    m_shape.setPreferredRendererType(QQuickShape::CurveRenderer);

    const QString qmlData = QLatin1StringView(R"QML(
        import QtQuick;

        Rectangle {
            property bool pointSelected
            property color pointColor
            property color pointBorderColor
            property color pointSelectedColor
            property real pointBorderWidth
            color: pointSelected ? pointSelectedColor : pointColor
            border.color: pointBorderColor
            border.width: pointBorderWidth
            width: %1
            height: %1
        }
    )QML").arg(QString::number((int) defaultSize()));
    m_tempMarker = new QQmlComponent(qmlEngine(m_graph), this);
    m_tempMarker->setData(qmlData.toUtf8(), QUrl());

    m_tapHandler = new QQuickTapHandler(this);
    connect(m_tapHandler, &QQuickTapHandler::singleTapped,
            this, &PointRenderer::onSingleTapped);
    connect(m_tapHandler, &QQuickTapHandler::doubleTapped,
            this, &PointRenderer::onDoubleTapped);
    connect(m_tapHandler, &QQuickTapHandler::pressedChanged,
            this, &PointRenderer::onPressedChanged);
}

PointRenderer::~PointRenderer()
{
    qDeleteAll(m_groups);
}

void PointRenderer::resetShapePathCount()
{
    m_currentShapePathIndex = 0;
}

qreal PointRenderer::defaultSize(QXYSeries *series)
{
    qreal size = 16.0;
    if (series != nullptr) {
#ifdef USE_LINEGRAPH
        if (auto line = qobject_cast<QLineSeries *>(series))
            size = qMax(size, line->width());
#endif
#if defined(USE_LINEGRAPH) && defined(USE_SPLINEGRAPH)
        else
#endif
#ifdef USE_SPLINEGRAPH
            if (auto spline = qobject_cast<QSplineSeries *>(series))
            size = qMax(size, spline->width());
#endif
    }
    return size;
}

void PointRenderer::calculateRenderCoordinates(AxisRenderer *axisRenderer,
                                               QAbstractSeries *series,
                                               qreal origX,
                                               qreal origY,
                                               qreal *renderX,
                                               qreal *renderY)
{
    auto &axisX = axisRenderer->getAxisX(series);
    auto &axisY = axisRenderer->getAxisY(series);

    auto flipX = axisX.maxValue < axisX.minValue ? -1 : 1;
    auto flipY = axisY.maxValue < axisY.minValue ? -1 : 1;

    *renderX = m_areaWidth * flipX * origX * m_maxHorizontal - m_horizontalOffset;
    *renderY = m_areaHeight - m_areaHeight * flipY * origY * m_maxVertical
               + m_verticalOffset;
}

void PointRenderer::reverseRenderCoordinates(AxisRenderer *axisRenderer,
                                             QAbstractSeries *series,
                                             qreal renderX,
                                             qreal renderY,
                                             qreal *origX,
                                             qreal *origY)
{
    auto &axisX = axisRenderer->getAxisX(series);
    auto &axisY = axisRenderer->getAxisY(series);

    auto flipX = axisX.maxValue < axisX.minValue ? -1 : 1;
    auto flipY = axisY.maxValue < axisY.minValue ? -1 : 1;

    *origX = (renderX + m_horizontalOffset) / (m_areaWidth * flipX * m_maxHorizontal);
    *origY = (renderY - m_areaHeight - m_verticalOffset)
             / (-1 * m_areaHeight * flipY * m_maxVertical);
}

PointRenderer::SeriesStyle PointRenderer::getSeriesStyle(PointGroup *group)
{
    auto theme = m_graph->theme();

    const auto &seriesColors = theme->seriesColors();
    const auto &borderColors = theme->borderColors();

    qsizetype index = group->colorIndex % seriesColors.size();
    QColor color = group->series->color().alpha() != 0 ? group->series->color() : seriesColors.at(index);

    QColor selectedColor = group->series->selectedColor().alpha() != 0
                               ? group->series->selectedColor()
                               : m_graph->theme()->singleHighlightColor();

    index = group->colorIndex % borderColors.size();
    QColor borderColor = borderColors.at(index);
    qreal borderWidth = theme->borderWidth();

    return {
        color,
        selectedColor,
        borderColor,
        borderWidth
    };
}

void PointRenderer::updatePointDelegate(
    QXYSeries *series, PointGroup *group, qsizetype pointIndex, qreal x, qreal y)
{
    const auto style = getSeriesStyle(group);

    auto marker = group->markers[pointIndex];
    auto &rect = group->rects[pointIndex];

    if (marker->property(TAG_POINT_SELECTED).isValid())
        marker->setProperty(TAG_POINT_SELECTED, series->isPointSelected(pointIndex));
    if (marker->property(TAG_POINT_COLOR).isValid())
        marker->setProperty(TAG_POINT_COLOR, style.color);
    if (marker->property(TAG_POINT_BORDER_COLOR).isValid())
        marker->setProperty(TAG_POINT_BORDER_COLOR, style.borderColor);
    if (marker->property(TAG_POINT_BORDER_WIDTH).isValid())
        marker->setProperty(TAG_POINT_BORDER_WIDTH, style.borderWidth);
    if (marker->property(TAG_POINT_SELECTED_COLOR).isValid())
        marker->setProperty(TAG_POINT_SELECTED_COLOR, style.selectedColor);
    const auto point = series->points().at(pointIndex);
    if (marker->property(TAG_POINT_VALUE_X).isValid())
        marker->setProperty(TAG_POINT_VALUE_X, point.x());
    if (marker->property(TAG_POINT_VALUE_Y).isValid())
        marker->setProperty(TAG_POINT_VALUE_Y, point.y());
    if (marker->property(TAG_POINT_INDEX).isValid())
        marker->setProperty(TAG_POINT_INDEX, pointIndex);

    marker->setX(x - marker->width() / 2.0);
    marker->setY(y - marker->height() / 2.0);
    marker->setVisible(true);

    rect = QRectF(x - marker->width() / 2.0,
                  y - marker->height() / 2.0,
                  marker->width(),
                  marker->height());
}

void PointRenderer::hidePointDelegates(QXYSeries *series)
{
    auto *group = m_groups.value(series);
    if (group->currentMarker) {
        for (int i = 0; i < group->markers.size(); ++i) {
            auto *marker = group->markers[i];
            marker->setVisible(false);
        }
    }
    group->rects.clear();
}

void PointRenderer::updateLegendData(QXYSeries *series, QLegendData &legendData)
{
    QList<QLegendData> legendDataList = {legendData};
    series->d_func()->setLegendData(legendDataList);
}

void PointRenderer::onSingleTapped(QEventPoint eventPoint, Qt::MouseButton button)
{
    Q_UNUSED(button)

    for (auto &&group : m_groups) {
        if (!group->series->isVisible())
            continue;

        if (!group->series->isSelectable() && !group->series->isDraggable())
            continue;

        int index = 0;
        for (auto &&rect : group->rects) {
            if (rect.contains(eventPoint.position())) {
                emit group->series->clicked(group->series->at(index).toPoint());
                return;
            }
            index++;
        }
    }
}

void PointRenderer::onDoubleTapped(QEventPoint eventPoint, Qt::MouseButton button)
{
    Q_UNUSED(button)

    for (auto &&group : m_groups) {
        if (!group->series->isVisible())
            continue;

        if (!group->series->isSelectable() && !group->series->isDraggable())
            continue;

        int index = 0;
        for (auto &&rect : group->rects) {
            if (rect.contains(eventPoint.position())) {
                emit group->series->doubleClicked(group->series->at(index).toPoint());
                return;
            }
            index++;
        }
    }
}

void PointRenderer::onPressedChanged()
{
    if (m_tapHandler->isPressed()) {
        for (auto &&group : m_groups) {
            if (!group->series->isVisible())
                continue;

            if (!group->series->isSelectable() && !group->series->isDraggable())
                continue;

            int index = 0;
            for (auto &&rect : group->rects) {
                if (rect.contains(m_tapHandler->point().position())) {
                    m_pressedGroup = group;
                    m_pressedPointIndex = index;
                    emit group->series->pressed(m_pressedGroup->series->at(index).toPoint());
                }
                index++;
            }
        }
    } else {
        if (m_pressedGroup
            && m_pressedGroup->series->isSelectable()
            && m_pressedGroup->series->isVisible()) {
            if (m_pressedGroup->rects[m_pressedPointIndex].contains(
                    m_tapHandler->point().position())) {
                if (m_pressedGroup->series->isPointSelected(m_pressedPointIndex))
                    m_pressedGroup->series->deselectPoint(m_pressedPointIndex);
                else
                    m_pressedGroup->series->selectPoint(m_pressedPointIndex);
                m_previousDelta = QPoint(0, 0);
                emit m_pressedGroup->series->released(
                    m_pressedGroup->series->at(m_pressedPointIndex).toPoint());
            }
        }
    }
}

#ifdef USE_SCATTERGRAPH
void PointRenderer::updateScatterSeries(QScatterSeries *series, QLegendData &legendData)
{
    auto group = m_groups.value(series);
    const auto style = getSeriesStyle(group);

    if (series->isVisible()) {
        auto &&points = series->points();
        group->rects.resize(points.size());
        for (int i = 0; i < points.size(); ++i) {
            qreal x, y;
            calculateRenderCoordinates(m_graph->m_axisRenderer,
                                       series,
                                       points[i].x(),
                                       points[i].y(),
                                       &x,
                                       &y);
            y *= series->valuesMultiplier();
            if (group->currentMarker) {
                updatePointDelegate(series, group, i, x, y);
            } else {
                auto &rect = group->rects[i];
                qreal size = defaultSize(series);
                rect = QRectF(x - size / 2.0, y - size / 2.0, size, size);
            }
        }
    } else {
        hidePointDelegates(series);
    }

    legendData = { style.color, style.borderColor, series->name() };
}
#endif

#ifdef USE_LINEGRAPH
void PointRenderer::updateLineSeries(QLineSeries *series, QLegendData &legendData)
{
    auto group = m_groups.value(series);
    const auto style = getSeriesStyle(group);

    group->shapePath->setStrokeColor(style.color);
    group->shapePath->setStrokeWidth(series->width());
    group->shapePath->setFillColor(QColorConstants::Transparent);

    Qt::PenCapStyle capStyle = series->capStyle();
    if (capStyle == Qt::PenCapStyle::SquareCap)
        group->shapePath->setCapStyle(QQuickShapePath::CapStyle::SquareCap);
    else if (capStyle == Qt::PenCapStyle::FlatCap)
        group->shapePath->setCapStyle(QQuickShapePath::CapStyle::FlatCap);
    else if (capStyle == Qt::PenCapStyle::RoundCap)
        group->shapePath->setCapStyle(QQuickShapePath::CapStyle::RoundCap);

    auto &painterPath = group->painterPath;
    painterPath.clear();

    if (series->isVisible()) {
        auto &&points = series->points();
        group->rects.resize(points.size());
        for (int i = 0; i < points.size(); ++i) {
            qreal x, y;
            calculateRenderCoordinates(m_graph->m_axisRenderer,
                                       series,
                                       points[i].x(),
                                       points[i].y(),
                                       &x,
                                       &y);
            y *= series->valuesMultiplier();
            if (i == 0)
                painterPath.moveTo(x, y);
            else
                painterPath.lineTo(x, y);

            if (group->currentMarker) {
                updatePointDelegate(series, group, i, x, y);
            } else {
                auto &rect = group->rects[i];
                qreal size = defaultSize(series);
                rect = QRectF(x - size / 2.0, y - size / 2.0, size, size);
            }
        }
    } else {
        hidePointDelegates(series);
    }
    group->shapePath->setPath(painterPath);
    legendData = { style.color, style.borderColor, series->name() };
}
#endif

#ifdef USE_SPLINEGRAPH
void PointRenderer::updateSplineSeries(QSplineSeries *series, QLegendData &legendData)
{
    auto group = m_groups.value(series);
    const auto style = getSeriesStyle(group);

    group->shapePath->setStrokeColor(style.color);
    group->shapePath->setStrokeWidth(series->width());
    group->shapePath->setFillColor(QColorConstants::Transparent);

    Qt::PenCapStyle capStyle = series->capStyle();
    if (capStyle == Qt::PenCapStyle::SquareCap)
        group->shapePath->setCapStyle(QQuickShapePath::CapStyle::SquareCap);
    else if (capStyle == Qt::PenCapStyle::FlatCap)
        group->shapePath->setCapStyle(QQuickShapePath::CapStyle::FlatCap);
    else if (capStyle == Qt::PenCapStyle::RoundCap)
        group->shapePath->setCapStyle(QQuickShapePath::CapStyle::RoundCap);

    auto &painterPath = group->painterPath;
    painterPath.clear();

    if (series->isVisible()) {
        auto &&points = series->points();
        group->rects.resize(points.size());
        auto fittedPoints = series->getControlPoints();

        for (int i = 0, j = 0; i < points.size(); ++i, ++j) {
            qreal x, y;
            calculateRenderCoordinates(m_graph->m_axisRenderer,
                                       series,
                                       points[i].x(),
                                       points[i].y(),
                                       &x,
                                       &y);

            qreal valuesMultiplier = series->valuesMultiplier();
            y *= valuesMultiplier;
            if (i == 0) {
                painterPath.moveTo(x, y);
            } else {
                qreal x1, y1, x2, y2;
                calculateRenderCoordinates(m_graph->m_axisRenderer,
                                           series,
                                           fittedPoints[j - 1].x(),
                                           fittedPoints[j - 1].y(),
                                           &x1,
                                           &y1);
                calculateRenderCoordinates(m_graph->m_axisRenderer,
                                           series,
                                           fittedPoints[j].x(),
                                           fittedPoints[j].y(),
                                           &x2,
                                           &y2);

                y1 *= valuesMultiplier;
                y2 *= valuesMultiplier;
                painterPath.cubicTo(x1, y1, x2, y2, x, y);
                ++j;
            }

            if (group->currentMarker) {
                updatePointDelegate(series, group, i, x, y);
            } else {
                auto &rect = group->rects[i];
                qreal size = defaultSize(series);
                rect = QRectF(x - size / 2.0, y - size / 2.0, size, size);
            }
        }
    } else {
        hidePointDelegates(series);
    }

    group->shapePath->setPath(painterPath);
    legendData = { style.color, style.borderColor, series->name() };
}
#endif

void PointRenderer::handlePolish(QXYSeries *series)
{
    auto theme = m_graph->theme();
    if (!theme) {
        qCCritical(lcCritical2D, "Theme not found");
        return;
    }

    if (!m_graph->m_axisRenderer) {
        qCCritical(lcCritical2D, "Axis renderer not found.");
        return;
    }

    if (series->points().isEmpty()) {
        auto group = m_groups.value(series);

        if (group) {
            if (group->shapePath) {
                auto &painterPath = group->painterPath;
                painterPath.clear();
                group->shapePath->setPath(painterPath);
            }

            for (auto m : group->markers)
                m->deleteLater();

            group->markers.clear();
        }

        return;
    }

    if (width() <= 0 || height() <= 0)
        return;

    m_areaWidth = width();
    m_areaHeight = height();

    auto &axisX = m_graph->m_axisRenderer->getAxisX(series);
    auto &axisY = m_graph->m_axisRenderer->getAxisY(series);

    m_maxVertical = axisY.valueRange > 0 ? 1.0 / axisY.valueRange : 100.0;
    m_maxHorizontal = axisX.valueRange > 0 ? 1.0 / axisX.valueRange : 100.0;

    auto vmin = axisY.minValue > axisY.maxValue ? std::abs(axisY.minValue) : axisY.minValue;
    m_verticalOffset = (vmin / axisY.valueRange) * m_areaHeight;

    auto hmin = axisX.minValue > axisX.maxValue ? std::abs(axisX.minValue) : axisX.minValue;
    m_horizontalOffset = (hmin / axisX.valueRange) * m_areaWidth;

    if (!m_groups.contains(series)) {
        PointGroup *group = new PointGroup();
        group->series = series;
        m_groups.insert(series, group);

        if (series->type() != QAbstractSeries::SeriesType::Scatter) {
            group->shapePath = new QQuickShapePath(&m_shape);
            group->shapePath->setAsynchronous(true);
            auto data = m_shape.data();
            data.append(&data, group->shapePath);
        }
    }

    auto group = m_groups.value(series);

    if (series->type() != QAbstractSeries::SeriesType::Scatter) {
        auto data = m_shape.data();
        group->shapePath = qobject_cast<QQuickShapePath *>(data.at(&data, m_currentShapePathIndex));

        m_currentShapePathIndex++;
    }

    qsizetype pointCount = series->points().size();

    if ((series->type() == QAbstractSeries::SeriesType::Scatter) && !series->pointDelegate())
        group->currentMarker = m_tempMarker;
    else if (series->pointDelegate())
        group->currentMarker = series->pointDelegate();

    if (group->currentMarker != group->previousMarker) {
        for (auto &&marker : group->markers)
            marker->deleteLater();
        group->markers.clear();
    }
    group->previousMarker = group->currentMarker;

    if (group->currentMarker) {
        qsizetype markerCount = group->markers.size();
        if (markerCount < pointCount) {
            for (qsizetype i = markerCount; i < pointCount; ++i) {
                QQuickItem *item = qobject_cast<QQuickItem *>(
                    group->currentMarker->create(group->currentMarker->creationContext()));
                item->setParent(this);
                item->setParentItem(this);
                QQuickDragHandler *handler = new QQuickDragHandler(item);
                handler->setEnabled(series->isDraggable());
                connect(series, &QXYSeries::draggableChanged, this, [handler, series]() {
                    handler->setEnabled(series->isDraggable());
                });
                group->markers << item;
                group->dragHandlers << handler;

                connect(handler, &QQuickDragHandler::translationChanged, this, [&]() {
                    if (m_pressedGroup) {
                        float w = width();
                        float h = height();
                        double maxVertical
                            = axisY.valueRange > 0
                                  ? 1.0 / axisY.valueRange
                                  : 100.0;
                        double maxHorizontal
                            = axisX.valueRange > 0
                                  ? 1.0 / axisX.valueRange
                                  : 100.0;

                        QPoint currentDelta =
                            m_pressedGroup->dragHandlers.at(m_pressedPointIndex)
                                ->activeTranslation().toPoint();
                        QPoint delta = currentDelta - m_previousDelta;
                        m_previousDelta = currentDelta;

                        qreal deltaX = delta.x() / w / maxHorizontal;
                        qreal deltaY = -delta.y() / h / maxVertical;

                        QPointF point = m_pressedGroup->series->at(m_pressedPointIndex)
                                        + QPointF(deltaX, deltaY);
                        m_pressedGroup->series->replace(m_pressedPointIndex, point);
                    }
                });
                connect(handler, &QQuickDragHandler::grabChanged, this,
                        [&](QPointingDevice::GrabTransition transition, QEventPoint point) {
                            Q_UNUSED(point)

                            if (transition == QPointingDevice::UngrabExclusive ||
                                transition == QPointingDevice::UngrabPassive) {
                                m_previousDelta = QPoint(0, 0);
                            }
                        });
            }
        } else if (markerCount > pointCount) {
            for (qsizetype i = pointCount; i < markerCount; ++i)
                group->markers[i]->deleteLater();
            group->markers.resize(pointCount);
        }
    } else if (group->markers.size() > 0) {
        for (auto &&marker : group->markers)
            marker->deleteLater();
        group->markers.clear();
    }

    for (auto &&marker : group->markers)
        marker->setZ(group->series->drawOrder());

    if (group->colorIndex < 0) {
        group->colorIndex = m_graph->graphSeriesCount();
        m_graph->setGraphSeriesCount(group->colorIndex + 1);
    }

    QLegendData legendData;
#ifdef USE_SCATTERGRAPH
    if (auto scatter = qobject_cast<QScatterSeries *>(series))
        updateScatterSeries(scatter, legendData);
#endif
#if defined(USE_SCATTERGRAPH) && defined(USE_LINEGRAPH)
    else
#endif
#ifdef USE_LINEGRAPH
        if (auto line = qobject_cast<QLineSeries *>(series))
        updateLineSeries(line, legendData);
#endif
#if defined(USE_LINEGRAPH) && defined(USE_SPLINEGRAPH)
    else
#endif
#ifdef USE_SPLINEGRAPH
        if (auto spline = qobject_cast<QSplineSeries *>(series))
        updateSplineSeries(spline, legendData);
#endif

    updateLegendData(series, legendData);
}

void PointRenderer::afterPolish(QList<QAbstractSeries *> &cleanupSeries)
{
    for (auto series : cleanupSeries) {
        auto xySeries = qobject_cast<QXYSeries *>(series);
        if (xySeries && m_groups.contains(xySeries)) {
            auto group = m_groups.value(xySeries);

            for (auto marker : group->markers)
                marker->deleteLater();

            if (group->shapePath) {
                auto painterPath = group->painterPath;
                painterPath.clear();
                group->shapePath->setPath(painterPath);
            }

            delete group;
            m_groups.remove(xySeries);
        }
    }
}

void PointRenderer::updateSeries(QXYSeries *series)
{
    Q_UNUSED(series);
}

void PointRenderer::afterUpdate(QList<QAbstractSeries *> &cleanupSeries)
{
    Q_UNUSED(cleanupSeries);
}

bool PointRenderer::handleHoverMove(QHoverEvent *event)
{
    bool handled = false;
    const QPointF &position = event->position();

    for (auto &&group : m_groups) {
        if (!group->series->isHoverable() || !group->series->isVisible())
            continue;

        auto axisRenderer = group->series->graph()->m_axisRenderer;
        auto &axisX = axisRenderer->getAxisX(group->series);
        auto &axisY = axisRenderer->getAxisY(group->series);

        bool isHNegative = axisX.maxValue < axisX.minValue;
        bool isVNegative = axisY.maxValue < axisY.minValue;

        if (group->series->type() == QAbstractSeries::SeriesType::Scatter) {
            const QString &name = group->series->name();

            bool hovering = false;

            int index = 0;
            for (auto &&rect : group->rects) {
                if (rect.contains(position.toPoint())) {
                    if (!group->hover) {
                        group->hover = true;
                        emit group->series->hoverEnter(name, position, group->series->at(index));
                    }
                    emit group->series->hover(name, position, group->series->at(index));
                    hovering = true;
                }
                index++;
            }

            if (!hovering && group->hover) {
                group->hover = false;
                emit group->series->hoverExit(name, position);
            }
        } else {
            const qreal x0 = event->position().x();
            const qreal y0 = event->position().y();

            const qreal hoverSize = defaultSize(group->series) / 2.0;
            const QString &name = group->series->name();
            auto &&points = group->series->points();
            // True when line, false when spline
            const bool isLine = group->series->type() == QAbstractSeries::SeriesType::Line;
            if (points.size() >= 2) {
                bool hovering = false;
                auto subpath = group->painterPath.toSubpathPolygons();

                if (group->painterPath.elementCount() != points.size())
                    m_graph->ensurePolished();

                for (int i = 0; i < points.size() - 1; i++) {
                    qreal x1, y1, x2, y2;
                    if (i == 0) {
                        auto element1 = group->painterPath.elementAt(0);
                        auto element2 = group->painterPath.elementAt(isLine ? 1 : 3);
                        x1 = isHNegative ? element2.x : element1.x;
                        y1 = element1.y;
                        x2 = isHNegative ? element1.x : element2.x;
                        y2 = element2.y;
                    } else {
                        bool n = isVNegative | isHNegative;
                        // Each Spline (cubicTo) has 3 elements where third one is the x & y.
                        // So content of elements are:
                        // With Spline:
                        // [0] : MoveToElement
                        // [1] : 1. CurveToElement (c1x, c1y)
                        // [2] : 1. CurveToDataElement (c2x, c2y)
                        // [3] : 1. CurveToDataElement (x, y)
                        // [4] : 2. CurveToElement (c1x, c1y)
                        // ...
                        // With Line:
                        // [0] : MoveToElement
                        // [1] : 1. LineToElement (x, y)
                        // [2] : 2. LineToElement (x, y)
                        // ...
                        int element1Index = n ? (i + 1) : i;
                        int element2Index = n ? i : (i + 1);
                        element1Index = isLine ? element1Index : element1Index * 3;
                        element2Index = isLine ? element2Index : element2Index * 3;
                        auto element1 = group->painterPath.elementAt(element1Index);
                        auto element2 = group->painterPath.elementAt(element2Index);
                        x1 = element1.x;
                        y1 = element1.y;
                        x2 = element2.x;
                        y2 = element2.y;
                    }

                    if (isLine) {
                        qreal denominator = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
                        qreal hoverDistance = qAbs((x2 - x1) * (y1 - y0) - (x1 - x0) * (y2 - y1))
                                              / qSqrt(denominator);

                        if (hoverDistance < hoverSize) {
                            qreal alpha = 0;
                            qreal extrapolation = 0;
                            if (x2 - x1 >= y2 - y1) {
                                if (x2 - x1 != 0) {
                                    alpha = ((x2 - x1) - (x0 - x1)) / qAbs(x2 - x1);
                                    extrapolation = hoverSize / qAbs(x2 - x1);
                                }
                            } else {
                                if (y2 - y1 != 0) {
                                    alpha = ((y2 - y1) - (y0 - y1)) / qAbs(y2 - y1);
                                    extrapolation = hoverSize / qAbs(y2 - y1);
                                }
                            }

                            if (alpha >= -extrapolation && alpha <= 1.0 + extrapolation) {
                                bool n = isVNegative | isHNegative;

                                const QPointF &point1 = points[n ? i + 1 : i];
                                const QPointF &point2 = points[n ? i : i + 1];

                                QPointF point = (point2 * (1.0 - alpha)) + (point1 * alpha);

                                if (!group->hover) {
                                    group->hover = true;
                                    group->series->setHovered(true);
                                    emit group->series->hoverEnter(name, position, point);
                                }

                                emit group->series->hover(name, position, point);
                                hovering = true;
                                handled = true;
                            }
                        }
                    } else { // Spline
                        auto segments = subpath[0];

                        for (auto it = segments.begin(); it != segments.end(); ++it) {
                            if (std::next(it, 1) == segments.end())
                                break;

                            auto it2 = std::next(it, 1);

                            qreal denominator = (it2->x() - it->x()) * (it2->x() - it->x())
                                                + (it2->y() - it->y()) * (it2->y() - it->y());
                            qreal hoverDistance = qAbs((it2->x() - it->x()) * (it->y() - y0)
                                                       - (it->x() - x0) * (it2->y() - it->y()))
                                                  / qSqrt(denominator);

                            if (hoverDistance < hoverSize) {
                                qreal alpha = 0;
                                qreal extrapolation = 0;
                                if (it2->x() - it->x() >= it2->y() - it->y()) {
                                    if (it2->x() - it->x() != 0) {
                                        alpha = ((it2->x() - it->x()) - (x0 - it->x()))
                                                / qAbs(it2->x() - it->x());
                                        extrapolation = hoverSize / qAbs(it2->x() - it->x());
                                    }
                                } else {
                                    if (it2->y() - it->y() != 0) {
                                        alpha = ((it2->y() - it->y()) - (y0 - it->y()))
                                                / qAbs(it2->y() - it->y());
                                        extrapolation = hoverSize / qAbs(it2->y() - it->y());
                                    }
                                }

                                if (alpha >= -extrapolation && alpha <= 1.0 + extrapolation) {
                                    qreal cx1, cy1, cx2, cy2;

                                    reverseRenderCoordinates(axisRenderer,
                                                             group->series,
                                                             it->x(),
                                                             it->y(),
                                                             &cx1,
                                                             &cy1);
                                    reverseRenderCoordinates(axisRenderer,
                                                             group->series,
                                                             it2->x(),
                                                             it2->y(),
                                                             &cx2,
                                                             &cy2);

                                    const QPointF &point1 = {cx1, cy1};
                                    const QPointF &point2 = {cx2, cy2};

                                    QPointF point = (point2 * (1.0 - alpha)) + (point1 * alpha);

                                    if (!group->hover) {
                                        group->hover = true;
                                        emit group->series->hoverEnter(name, position, point);
                                    }

                                    emit group->series->hover(name, position, point);
                                    hovering = true;
                                    handled = true;
                                }
                            }
                        }
                    }
                }

                if (!hovering && group->hover) {
                    group->hover = false;
                    group->series->setHovered(false);
                    emit group->series->hoverExit(name, position);
                    handled = true;
                }
            }
        }
    }
    return handled;
}


QPointF PointRenderer::reverseRenderCoordinates(QAbstractSeries *series, qreal x, qreal y)
{
    m_areaWidth = width();
    m_areaHeight = height();

    auto &axisX = m_graph->m_axisRenderer->getAxisX(series);
    auto &axisY = m_graph->m_axisRenderer->getAxisY(series);

    m_maxVertical = axisY.valueRange > 0 ? 1.0 / axisY.valueRange : 100.0;
    m_maxHorizontal = axisX.valueRange > 0 ? 1.0 / axisX.valueRange : 100.0;

    auto vmin = axisY.minValue > axisY.maxValue ? std::abs(axisY.minValue) : axisY.minValue;
    m_verticalOffset = (vmin / axisY.valueRange) * m_areaHeight;

    auto hmin = axisX.minValue > axisX.maxValue ? std::abs(axisX.minValue) : axisX.minValue;
    m_horizontalOffset = (hmin / axisX.valueRange) * m_areaWidth;

    qreal x0;
    qreal y0;

    reverseRenderCoordinates(m_graph->m_axisRenderer, series, x, y, &x0, &y0);

    return QPointF(x0, y0);
}

QT_END_NAMESPACE