summaryrefslogtreecommitdiffstats
path: root/src/bm/plotter.cpp
blob: cbfca535c58c9a32a76d8babcdda80e6235d6300 (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
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the BM project on Qt Labs.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 or 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#include "plotter.h"
#include "bmmisc.h"
#include <QGraphicsScene>
#include <QGraphicsSimpleTextItem>
#include <QPainter>
#include <QDebug>

// ### Note: There is a potential for refactoring in order to avoid code duplication
// in this file.


// Template method.
QImage Plotter::createImage(QString *error) const
{
    const QRectF sceneRect_ = sceneRect();

    QGraphicsScene scene_far(sceneRect_); // Background scene (rendered first)
    QGraphicsScene scene_mid_aa(sceneRect_); // Middle scene (antialiased)
    QGraphicsScene scene_near(sceneRect_); // Foreground scene (rendered last)

    if (!drawScenes(&scene_far, &scene_mid_aa, &scene_near, error))
        return QImage();

    Q_ASSERT(scene_far.sceneRect() == scene_mid_aa.sceneRect());
    Q_ASSERT(scene_far.sceneRect() == scene_near.sceneRect());

    QImage image(scene_far.width(), scene_far.height(), QImage::Format_ARGB32);
    {
        QPainter painter(&image);
        scene_far.render(&painter);
    }
    {
        QPainter painter(&image);
        painter.setRenderHint(QPainter::Antialiasing);
        scene_mid_aa.render(&painter);
    }
    {
        QPainter painter(&image);
        scene_near.render(&painter);
    }

    return image;
}

ResultHistoryPlotter::ResultHistoryPlotter(
    const QList<int> &timestamps, const QList<qreal> &values, const int resultId, const int basePos)
    : timestamps(timestamps), values(values), resultId(resultId), basePos(basePos)
    , width(1100), height(450)
{
}

QRectF ResultHistoryPlotter::sceneRect() const
{
    return QRectF(0, 0, width, height);
}

// ### 2 B DOCUMENTED!
// ### 2 B DONE: Maybe factor out parts that this function has in common with
//     other *::drawScenes() implementations
bool ResultHistoryPlotter::drawScenes(
    QGraphicsScene *scene_far, QGraphicsScene *scene_mid_aa, QGraphicsScene *scene_near,
    QString *error) const
{
    if (timestamps.isEmpty()) {
        if (error)
            *error = "no data to plot (no values)";
        return false;
    }
    Q_ASSERT(timestamps.size() == values.size());
    for (int i = 1; i < timestamps.size(); ++i) {
        Q_ASSERT(timestamps.at(i - 1) <= timestamps.at(i));
    }
    Q_ASSERT(basePos < timestamps.size());

    const qreal pad_left = 150;
    const qreal pad_right = 150;
    const qreal pad_top = 50;
    const qreal pad_bottom = 50;
    const qreal xmin = pad_left;
    const qreal xmax = width - pad_right;
    const qreal xdefault = 0.5 * (xmin + xmax);
    const qreal ymin = pad_top;
    const qreal ymax = height - pad_bottom;
    const qreal ydefault = 0.5 * (ymin + ymax);

    qreal loTimestamp = timestamps.first();
    qreal hiTimestamp = timestamps.last();

    qreal xfact = xdefault;
    if (loTimestamp < hiTimestamp) {
        const qreal tfact = 1.0 / (hiTimestamp - loTimestamp);
        xfact = tfact * (xmax - xmin);
    }

    qreal vmin = -1;
    qreal vmax = -1;
    vmin = vmax = values.first();
    for (int i = 1; i < values.size(); ++i) {
        vmin = qMin(vmin, values.at(i));
        vmax = qMax(vmax, values.at(i));
    }

    const qreal vfact = 1 / (vmax - vmin); // zero division handled elsewhere
    const qreal yfact = vfact * (ymax - ymin);

    // Compute scene coordinates of history curve ...
    QList<qreal> x;
    QList<qreal> y;
    for (int i = 0; i < values.size(); ++i) {
        const qreal t = timestamps.at(i);
        const qreal v = values.at(i);
        x.append(((timestamps.size() > 1) || (loTimestamp < hiTimestamp))
                 ? (xmin + (t - loTimestamp) * xfact)
                 : xdefault);
        y.append(BMMisc::v2y(v, ymax, vmin, yfact, ydefault));
    }

    // Draw background ...
    scene_far->setBackgroundBrush(QBrush(Qt::white));

    // Draw axis indicators ...
    const qreal indicatorSize = 5;
    const QColor indicatorColor(119, 119, 255, 255);
    // ... x-axis (all values) ...
    {
        QPainterPath path;
        for (int i = 0; i < x.size(); ++i) {
            path.moveTo(x.at(i), ymax);
            path.lineTo(x.at(i), ymax + indicatorSize);
        }
        scene_far->addPath(path, QPen(indicatorColor));
    }
    // ... y-axises (min and max value only) ...
    {
        QPainterPath path;
        path.moveTo(xmin, ymin);
        path.lineTo(xmin - indicatorSize, ymin);
        path.moveTo(xmin, ymax);
        path.lineTo(xmin - indicatorSize, ymax);
        path.moveTo(xmax, ymin);
        path.lineTo(xmax + indicatorSize, ymin);
        path.moveTo(xmax, ymax);
        path.lineTo(xmax + indicatorSize, ymax);
        scene_far->addPath(path, QPen(indicatorColor));
    }

    // Draw border rectangle  ...
    scene_far->addRect(xmin, ymin, xmax - xmin, ymax - ymin, QPen(QColor(220, 220, 220, 255)));

    if (basePos >= 0) {
        // Draw line indicating the base position ...
        QColor color(0, 0, 255);
        color.setAlpha(100);
        scene_far->addLine(xmin, y.at(basePos), xmax, y.at(basePos), QPen(color, 2));
    }

    const qreal dpSize = 4;

    // Draw history curve between data points ...
    {
        QPainterPath path(QPointF(x.first(), y.first()));
        for (int i = 0; i < x.size(); ++i)
            path.lineTo(x.at(i), y.at(i));
        scene_mid_aa->addPath(path, QPen(QColor(128, 128, 128, 255)));
    }

    // Draw data points (except the one representing the base position if any) ...
    {
        QPainterPath path;
        path.setFillRule(Qt::WindingFill);
        const qreal dpSize_2 = 0.5 * dpSize;
        for (int i = 0; i < x.size(); ++i)
            if ((basePos < 0) || (i != basePos))
                path.addRect(x.at(i) - dpSize_2, y.at(i) - dpSize_2, dpSize, dpSize);

        const QColor color(0, 0, 0, 255);
        scene_near->addPath(path, QPen(color), QBrush(color));
    }

    if (basePos >= 0) {
        // Draw the data point representing the base position ...
        QPainterPath path;
        path.addRect(x.at(basePos) - dpSize / 2, y.at(basePos) - dpSize / 2, dpSize, dpSize);
        const QColor color(0, 0, 0, 255);
        scene_near->addPath(path, QPen(color), QBrush(Qt::yellow)); // ### 4 NOW
    }


    // Draw labels ...
    const qreal labelPad = 10;
    const qreal captionPad = 4;
    qreal captionHeight;

    // ... left y axis ...
    {
        const QString yCaption = "value"; // ### 4 NOW (could e.g. be metric name)
        QFont font;
        font.setPointSize(14);
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText(yCaption, font);
        const qreal x_ = xmin - text->boundingRect().height() - captionPad;
        const qreal y_ = (ymin + ymax) / 2 + text->boundingRect().width() / 2;
        text->setTransform(QTransform().translate(x_, y_).rotate(-90));
        captionHeight = text->boundingRect().height();
    }
    {
        QGraphicsSimpleTextItem *text =
            scene_near->addSimpleText(QString().setNum(vmin));
        text->setPos(
            xmin - captionPad - captionHeight - labelPad - text->boundingRect().width(),
            ymax - text->boundingRect().height() / 2);
    }
    {
        QGraphicsSimpleTextItem *text =
            scene_near->addSimpleText(QString().setNum(vmax));
        text->setPos(
            xmin - captionPad - captionHeight - labelPad - text->boundingRect().width(),
            ymin - text->boundingRect().height() / 2);
    }

    if (basePos >= 0) {
        QGraphicsSimpleTextItem *text =
            scene_near->addSimpleText(QString().setNum(values.at(basePos)));
        text->setPos(
            xmin - captionPad - captionHeight - labelPad - text->boundingRect().width(),
            y.at(basePos) - text->boundingRect().height() / 2);

        // Avoid overlap
        if (!scene_near->collidingItems(text).isEmpty()) {
            scene_near->removeItem(text);
            delete text;
        }
    }

    const bool showNormDiff = true; // ### 4 NOW

    if ((basePos >= 0) && showNormDiff) {
        // ... right y axis ...
        {
            QFont font;
            font.setPointSize(14);
            QGraphicsSimpleTextItem *text =
                scene_near->addSimpleText("norm. diff. between baseline value and value", font);
            const qreal x_ = xmax + captionPad;
            const qreal y_ = (ymin + ymax) / 2 + text->boundingRect().width() / 2;
            text->setTransform(QTransform().translate(x_, y_).rotate(-90));
            captionHeight = text->boundingRect().height();
        }
        {
            QGraphicsSimpleTextItem *text =
                scene_near->addSimpleText(
                    QString().setNum(
                        BMMisc::normalizedDifference(values.at(basePos), vmin), 'f', 4));
            text->setPos(
                xmax + captionPad + captionHeight + labelPad,
                ymax - text->boundingRect().height() / 2);
        }
        {
            QGraphicsSimpleTextItem *text =
                scene_near->addSimpleText(
                    QString().setNum(
                        BMMisc::normalizedDifference(values.at(basePos), vmax), 'f', 4));
            text->setPos(
                xmax + captionPad + captionHeight + labelPad,
                ymin - text->boundingRect().height() / 2);
        }
        {
            QGraphicsSimpleTextItem *text =
                scene_near->addSimpleText(QString().setNum(0.0, 'f', 4));
            text->setPos(
                xmax + captionPad + captionHeight + labelPad,
                y.last() - text->boundingRect().height() / 2);

            // Avoid overlap
            if (!scene_near->collidingItems(text).isEmpty()) {
                scene_near->removeItem(text);
                delete text;
            }
        }
    }

    // ... top x axis ...
    {
        QFont font;
        font.setPointSize(16);
        const QString title = QString("Result history containing baseline result %1").arg(resultId);
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText(title, font);
        const qreal x_ = (xmin + xmax) / 2 - text->boundingRect().width() / 2;
        const qreal y_ = ymin - labelPad - text->boundingRect().height();
        text->translate(x_, y_);
    }

    // ... bottom x axis ...
    QDateTime dateTime;
    dateTime.setTime_t(loTimestamp);
    const QString xLabel_lo = dateTime.toString();
    dateTime.setTime_t(hiTimestamp);
    const QString xLabel_hi = dateTime.toString();
    {
        QFont font;
        font.setPointSize(14);
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText("time", font);
        const qreal x_ = (xmin + xmax) / 2 - text->boundingRect().width() / 2;
        const qreal y_ = ymax + labelPad;
        text->translate(x_, y_);
    }
    {
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText(xLabel_lo);
        text->setPos(
            xmin - text->boundingRect().width() / 2,
            ymax + labelPad);
    }
    {
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText(xLabel_hi);
        text->setPos(
            xmax - text->boundingRect().width() / 2,
            ymax + labelPad);
    }

    return true;
}


IndexPlotter::IndexPlotter(
    const QList<int> &timestamps, const QList<qreal> &values, const QList<int> &contributions,
    const int baseTimestamp, const bool showBaseValue, const qreal baseValue)
    : timestamps(timestamps), values(values), contributions(contributions)
    , baseTimestamp(baseTimestamp), showBaseValue(showBaseValue), baseValue(baseValue)
{
    width = 1100;
    height = 450;
}

QRectF IndexPlotter::sceneRect() const
{
    return QRectF(0, 0, width, height);
}

// ### 2 B DOCUMENTED!
// ### 2 B DONE: Maybe factor out parts that this function has in common with
//     other *::drawScenes() implementations
bool IndexPlotter::drawScenes(
    QGraphicsScene *scene_far, QGraphicsScene *scene_mid_aa, QGraphicsScene *scene_near,
    QString *error) const
{
    // --- BEGIN main graph ---

    if (timestamps.isEmpty()) {
        if (error)
            *error = "no data to plot (no values)";
        return false;
    }
    Q_ASSERT(timestamps.size() == values.size());
    Q_ASSERT(timestamps.size() == contributions.size());
    for (int i = 1; i < timestamps.size(); ++i) {
        Q_ASSERT(timestamps.at(i - 1) <= timestamps.at(i));
    }

    const qreal pad_left = 150;
    const qreal pad_right = 150;
    const qreal pad_top = 50;
    const qreal pad_bottom = 50;

    const qreal xmin = pad_left;
    const qreal xmax = width - pad_right;
    const qreal xdefault = 0.5 * (xmin + xmax);
    const qreal ymin = pad_top;
    const qreal ymax = height - pad_bottom;
    const qreal ydefault = 0.5 * (ymin + ymax);

    qreal loTimestamp = timestamps.first();
    qreal hiTimestamp = timestamps.last();

    qreal xfact = xdefault;
    if (loTimestamp < hiTimestamp) {
        const qreal tfact = 1.0 / (hiTimestamp - loTimestamp);
        xfact = tfact * (xmax - xmin);
    }

    QList<bool> missing;
    for (int i = 0; i < contributions.size(); ++i)
        missing.append(contributions.at(i) == 0);

    qreal vmin = -1;
    qreal vmax = -1;
    const int firstNonMissing = missing.indexOf(false);
    if (firstNonMissing >= 0) {
        vmin = vmax = values.at(firstNonMissing);
        for (int i = firstNonMissing + 1; i < values.size(); ++i) {
            if (!missing.at(i)) {
                vmin = qMin(vmin, values.at(i));
                vmax = qMax(vmax, values.at(i));
            }
        }
    }

    const qreal vfact = 1 / (vmax - vmin); // zero division handled elsewhere
    const qreal yfact = vfact * (ymax - ymin);

    // Compute scene coordinates of history curve ...
    QList<qreal> x;
    QList<qreal> y;
    for (int i = 0; i < values.size(); ++i) {
        const qreal t = timestamps.at(i);
        const qreal v = values.at(i);
        x.append(((timestamps.size() > 1) || (loTimestamp < hiTimestamp))
                 ? (xmin + (t - loTimestamp) * xfact)
                 : xdefault);
        y.append(BMMisc::v2y(v, ymax, vmin, yfact, ydefault));
    }

    // Draw background ...
    scene_far->setBackgroundBrush(QBrush(Qt::white));

    // Draw axis indicators ...
    const qreal indicatorSize = 5;
    const QColor indicatorColor(119, 119, 255, 255);
    // ... x-axis (all values) ...
    {
        QPainterPath path;
        for (int i = 0; i < x.size(); ++i) {
            path.moveTo(x.at(i), ymax);
            path.lineTo(x.at(i), ymax + indicatorSize);
        }
        scene_far->addPath(path, QPen(indicatorColor));
    }
    // ... y-axises (min and max value only) ...
    {
        QPainterPath path;
        path.moveTo(xmin, ymin);
        path.lineTo(xmin - indicatorSize, ymin);
        path.moveTo(xmin, ymax);
        path.lineTo(xmin - indicatorSize, ymax);
        path.moveTo(xmax, ymin);
        path.lineTo(xmax + indicatorSize, ymin);
        path.moveTo(xmax, ymax);
        path.lineTo(xmax + indicatorSize, ymax);
        scene_far->addPath(path, QPen(indicatorColor));
    }

    // Draw border rectangle  ...
    scene_far->addRect(xmin, ymin, xmax - xmin, ymax - ymin, QPen(QColor(220, 220, 220, 255)));

    if (showBaseValue) {
        // Draw line indicating the base value ...
        QColor color(0, 0, 255);
        color.setAlpha(100);
        const qreal y_base = BMMisc::v2y(baseValue, ymax, vmin, yfact, ydefault);
        scene_far->addLine(xmin, y_base, xmax, y_base, QPen(color, 1));
    }

    if ((baseTimestamp >= timestamps.first()) && (baseTimestamp <= timestamps.last())) {
        // Draw line indicating the base timestamp ...
        QColor color(0, 0, 255);
        color.setAlpha(100);
        const qreal btx = xmin + (baseTimestamp - loTimestamp) * xfact;
        scene_far->addLine(btx, ymin, btx, ymax, QPen(color, 1));
    }

    const qreal dpSize = 3;

    // Draw history curve between data points that are not missing ...
    if (missing.count(false) > 1)
    {
        int pos = missing.indexOf(false, 0);
        QPainterPath path(QPointF(x.at(pos), y.at(pos)));
        while (true) {
            pos = missing.indexOf(false, pos + 1);
            if (pos == -1)
                break;
            path.lineTo(x.at(pos), y.at(pos));
        }
        scene_mid_aa->addPath(path, QPen(QColor(128, 128, 128, 255)));
    }

    // Draw data points (except the one representing the base value if any) ...
    {
        QPainterPath path;
        path.setFillRule(Qt::WindingFill);
        QPainterPath missingPath;
        const qreal ymid = 0.5 * (ymin + ymax);
        const qreal dpSize_2 = 0.5 * dpSize;
        for (int i = 0; i < x.size(); ++i)
            if (missing.at(i)) {
                missingPath.moveTo(x.at(i) - dpSize_2, ymid - dpSize_2);
                missingPath.lineTo(x.at(i) + dpSize_2, ymid + dpSize_2);
                missingPath.moveTo(x.at(i) - dpSize_2, ymid + dpSize_2);
                missingPath.lineTo(x.at(i) + dpSize_2, ymid - dpSize_2);
            } else {
                path.addRect(x.at(i) - dpSize_2, y.at(i) - dpSize_2, dpSize, dpSize);
            }

        const QColor color(0, 0, 0, 255);
        scene_near->addPath(path, QPen(color), QBrush(color));
        const QColor missingColor(255, 0, 0, 255);
        scene_near->addPath(missingPath, QPen(missingColor, 1), QBrush(missingColor));
    }

    // Draw labels ...
    const qreal labelPad = 10;
    const qreal captionPad = 4;
    qreal captionHeight;

    // ... left y axis ...
    {
        const QString yCaption = "value"; // ### 4 NOW
        QFont font;
        font.setPointSize(14);
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText(yCaption, font);
        const qreal x_ = xmin - text->boundingRect().height() - captionPad;
        const qreal y_ = (ymin + ymax) / 2 + text->boundingRect().width() / 2;
        text->setTransform(QTransform().translate(x_, y_).rotate(-90));
        captionHeight = text->boundingRect().height();
    }
    {
        QGraphicsSimpleTextItem *text =
            scene_near->addSimpleText(QString().setNum(vmin));
        text->setPos(
            xmin - captionPad - captionHeight - labelPad - text->boundingRect().width(),
            ymax - text->boundingRect().height() / 2);
    }
    {
        QGraphicsSimpleTextItem *text =
            scene_near->addSimpleText(QString().setNum(vmax));
        text->setPos(
            xmin - captionPad - captionHeight - labelPad - text->boundingRect().width(),
            ymin - text->boundingRect().height() / 2);
    }

    if (showBaseValue && ((baseValue >= vmin) && (baseValue <= vmax))) {
        QGraphicsSimpleTextItem *text =
            scene_near->addSimpleText(QString().setNum(baseValue));
        const qreal y_base = BMMisc::v2y(baseValue, ymax, vmin, yfact, ydefault);
        text->setPos(
            xmin - captionPad - captionHeight - labelPad - text->boundingRect().width(),
            y_base - text->boundingRect().height() / 2);

        // Avoid overlap
        if (!scene_near->collidingItems(text).isEmpty()) {
            scene_near->removeItem(text);
            delete text;
        }
    }

    // ... top x axis ...
    {
        QFont font;
        font.setPointSize(16);
        const QString title = QString("Qt Performance Index (<description>)");
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText(title, font);
        const qreal x_ = (xmin + xmax) / 2 - text->boundingRect().width() / 2;
        const qreal y_ = ymin - labelPad - text->boundingRect().height();
        text->translate(x_, y_);
    }

    // ... bottom x axis ...
    QDateTime dateTime;
    dateTime.setTime_t(loTimestamp);
    const QString xLabel_lo = dateTime.toString();
    dateTime.setTime_t(hiTimestamp);
    const QString xLabel_hi = dateTime.toString();
    {
        QFont font;
        font.setPointSize(14);
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText("time", font);
        const qreal x_ = (xmin + xmax) / 2 - text->boundingRect().width() / 2;
        const qreal y_ = ymax + labelPad;
        text->translate(x_, y_);
    }
    {
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText(xLabel_lo);
        text->setPos(
            xmin - text->boundingRect().width() / 2,
            ymax + labelPad);
    }
    {
        QGraphicsSimpleTextItem *text = scene_near->addSimpleText(xLabel_hi);
        text->setPos(
            xmax - text->boundingRect().width() / 2,
            ymax + labelPad);
    }


    return true;
}


HistoriesPlotter::HistoriesPlotter(const QList<ResultHistoryInfo *> &rhInfos)
    : rhInfos(rhInfos)
    , width(1200)
    , rhHeight(qMin(150, qMax(100, 800 / rhInfos.size())))
    , pad_top(50)
    , pad_bottom(50)
    , height(pad_top + pad_bottom + rhInfos.size() * rhHeight)
{
}

QRectF HistoriesPlotter::sceneRect() const
{
    return QRectF(0, 0, width, height);
}

struct MetricInfo {
    qreal vmin;
    qreal vmax;
    MetricInfo(const qreal vmin, const qreal vmax)
        : vmin(vmin), vmax(vmax) {}
};

// ### 2 B DOCUMENTED!
// ### 2 B DONE: Maybe factor out parts that this function has in common with
//     other *::drawScenes() implementations
bool HistoriesPlotter::drawScenes(
    QGraphicsScene *scene_far, QGraphicsScene *scene_mid_aa, QGraphicsScene *scene_near,
    QString *error) const
{
    if (rhInfos.isEmpty()) {
        if (error)
            *error = "no result histories to plot";
        return false;
    }

    const qreal pad_left = 150;
    const qreal pad_right = 300;
    const qreal pad_rh = 10;
    const qreal xmin = pad_left;
    const qreal xmax = width - pad_right;
    const qreal xdefault = 0.5 * (xmin + xmax);

    // Find global timestamp range ...
    qreal loTimestamp = -1;
    qreal hiTimestamp = -1;
    for (int i = 0; i < rhInfos.size(); ++i) {
        const ResultHistoryInfo *rhInfo = rhInfos.at(i);
        if (i == 0) {
            loTimestamp = rhInfo->timestamp(0);
            hiTimestamp = rhInfo->timestamp(rhInfo->size() - 1);
        } else {
            loTimestamp = qMin(loTimestamp, rhInfo->timestamp(0));
            hiTimestamp = qMax(hiTimestamp, rhInfo->timestamp(rhInfo->size() - 1));
        }
    }

    // Find global per-metric value ranges ...
    QMap<QString, MetricInfo *> metricInfos;
    for (int i = 0; i < rhInfos.size(); ++i) {
        const ResultHistoryInfo *rhInfo = rhInfos.at(i);
        const QString metric = rhInfo->metric();
        if (!metricInfos.contains(metric)) {
            const qreal firstValue = rhInfo->value(0);
            metricInfos.insert(metric, new MetricInfo(firstValue, firstValue));
        }
        MetricInfo *metricInfo = metricInfos.value(metric);
        for (int j = 0; j < rhInfo->size(); ++j) {
            const qreal value = rhInfo->value(j);
            metricInfo->vmin = qMin(metricInfo->vmin, value);
            metricInfo->vmax = qMax(metricInfo->vmax, value);
        }
    }

    qreal xfact = xdefault;
    if (loTimestamp < hiTimestamp) {
        const qreal tfact = 1.0 / (hiTimestamp - loTimestamp);
        xfact = tfact * (xmax - xmin);
    }

    const int nDispTimestamps = 5;
    const int dispTimestampStep = (hiTimestamp - loTimestamp) / (nDispTimestamps - 1);
    QList<qreal> dispTimestamps = QList<qreal>() << loTimestamp << hiTimestamp;
    for (int i = 1; i < nDispTimestamps - 1; ++i)
        dispTimestamps.insert(i, loTimestamp + i * dispTimestampStep);

    QFont font;
    const qreal labelPad = 10;

    // Plot the result histories below each other ...
    for (int rh = 0; rh < rhInfos.size(); ++rh) {

        ResultHistoryInfo *rhInfo = rhInfos.at(rh);

        const qreal ymin = pad_top + rh * rhHeight + pad_rh;
        const qreal ymax = pad_top + (rh + 1) * rhHeight - pad_rh;
        const qreal ydefault = 0.5 * (ymin + ymax);
        MetricInfo *metricInfo = metricInfos.value(rhInfo->metric());
        const qreal vmin = metricInfo->vmin;
        const qreal vmax = metricInfo->vmax;
        const qreal vfact = 1 / (vmax - vmin); // zero division handled elsewhere:
        const qreal yfact = vfact * (ymax - ymin);

        // Compute scene coordinates of history curve ...
        QList<qreal> x;
        QList<qreal> y;
        qDebug() << "";
        for (int i = 0; i < rhInfo->size(); ++i) {
            const qreal t = rhInfo->timestamp(i);
            const qreal v = rhInfo->value(i);
            x.append(((rhInfo->size() > 1) || (loTimestamp < hiTimestamp))
                     ? (xmin + (t - loTimestamp) * xfact)
                     : xdefault);
            y.append(BMMisc::v2y(v, ymax, vmin, yfact, ydefault));
        }

        // Draw background ...
        scene_far->setBackgroundBrush(QBrush(Qt::white));

        // Draw axis indicators ...
        const qreal indicatorSize = 5;
        const QColor indicatorColor(119, 119, 255, 255);
        // ... x-axis (all values) ...
        {
            QPainterPath path;
            for (int i = 0; i < x.size(); ++i) {
                path.moveTo(x.at(i), ymax);
                path.lineTo(x.at(i), ymax + indicatorSize);
            }
            scene_far->addPath(path, QPen(indicatorColor));
        }
        // ... y-axises (min and max value only) ...
        {
            QPainterPath path;
            path.moveTo(xmin, ymin);
            path.lineTo(xmin - indicatorSize, ymin);
            path.moveTo(xmin, ymax);
            path.lineTo(xmin - indicatorSize, ymax);
            path.moveTo(xmax, ymin);
            path.lineTo(xmax + indicatorSize, ymin);
            path.moveTo(xmax, ymax);
            path.lineTo(xmax + indicatorSize, ymax);
            scene_far->addPath(path, QPen(indicatorColor));
        }

        // Draw background rectangle  ...
        {
            QGraphicsItem *bgRect = scene_far->addRect(
                xmin, ymin, xmax - xmin, ymax - ymin, QPen(Qt::NoPen),
                QBrush(QColor(245, 245, 245, 255)));
            bgRect->setZValue(-2);
        }

        // Draw border rectangle  ...
        {
            QGraphicsItem *bgRect = scene_far->addRect(
                xmin, ymin, xmax - xmin, ymax - ymin, QPen(QColor(200, 200, 200, 255)));
            bgRect->setZValue(-1);
        }

        const qreal dpSize = 4;

        // Draw history curve between data points ...
        {
            QPainterPath path(QPointF(x.first(), y.first()));
            for (int i = 0; i < x.size(); ++i)
                path.lineTo(x.at(i), y.at(i));
            scene_mid_aa->addPath(path, QPen(QColor(100, 100, 100, 255)));
        }

        // Draw data points ...
        {
            QPainterPath path;
            path.setFillRule(Qt::WindingFill);
            const qreal dpSize_2 = 0.5 * dpSize;
            for (int i = 0; i < x.size(); ++i)
                path.addRect(x.at(i) - dpSize_2, y.at(i) - dpSize_2, dpSize, dpSize);

            const QColor color(50, 50, 50, 255);
            scene_near->addPath(path, QPen(color), QBrush(color));
        }

        font.setPointSize(12);

        // Draw labels on left y axis ...
        {
            QGraphicsSimpleTextItem *text = scene_near->addSimpleText(QString().setNum(vmin), font);
            text->setPos(
                xmin - labelPad - text->boundingRect().width(),
                ymax - text->boundingRect().height() / 2);
        }
        {
            QGraphicsSimpleTextItem *text = scene_near->addSimpleText(QString().setNum(vmax), font);
            text->setPos(
                xmin - labelPad - text->boundingRect().width(),
                ymin - text->boundingRect().height() / 2);
        }

        // Draw labels on right y axis ...

        qreal textYPos = ymin;
        const qreal labelPad_rh_ver = 3;
        font.setPointSize(10);
        font.setFamily("mono");

        // ... metric ...
        {
            QGraphicsSimpleTextItem *text =
                scene_near->addSimpleText(
                    QString("M: %1").arg(rhInfo->metric()), font);
            text->setPos(xmax + labelPad, textYPos);
            textYPos += text->boundingRect().height() + labelPad_rh_ver;

            QColor color(255, 255, 200, 255);
            QGraphicsItem *bgRect = scene_near->addRect(
                text->boundingRect(), QPen(color), QBrush(color));
            bgRect->setPos(text->pos());
            bgRect->setZValue(-1);
        }

        // ... platform ...
        {
            QGraphicsSimpleTextItem *text =
                scene_near->addSimpleText(
                    QString("P: %1").arg(rhInfo->platform()), font);
            text->setPos(xmax + labelPad, textYPos);
            textYPos += text->boundingRect().height() + labelPad_rh_ver;

            QColor color(200, 255, 255, 255);
            QGraphicsItem *bgRect = scene_near->addRect(
                text->boundingRect(), QPen(color), QBrush(color));
            bgRect->setPos(text->pos());
            bgRect->setZValue(-1);
        }

        // ... host ...
        {
            QGraphicsSimpleTextItem *text =
                scene_near->addSimpleText(
                    QString("H: %1").arg(rhInfo->host()), font);
            text->setPos(xmax + labelPad, textYPos);
            textYPos += text->boundingRect().height() + labelPad_rh_ver;

            QColor color(230, 210, 255, 255);
            QGraphicsItem *bgRect = scene_near->addRect(
                text->boundingRect(), QPen(color), QBrush(color));
            bgRect->setPos(text->pos());
            bgRect->setZValue(-1);
        }

        // ... git repo/branch ...
        {
            QGraphicsSimpleTextItem *text =
                scene_near->addSimpleText(
                    QString("B: %1 %2").arg(rhInfo->gitRepo()).arg(rhInfo->gitBranch()), font);
            text->setPos(xmax + labelPad, textYPos);
            textYPos += text->boundingRect().height() + labelPad_rh_ver;

            QColor color(255, 230, 210, 255);
            QGraphicsItem *bgRect = scene_near->addRect(
                text->boundingRect(), QPen(color), QBrush(color));
            bgRect->setPos(text->pos());
            bgRect->setZValue(-1);
        }

        // Draw vertical lines indicating display timestamps ...
        for (int i = 0; i < dispTimestamps.size(); ++i) {
            const qreal xpos = xmin + (dispTimestamps.at(i) - loTimestamp) * xfact;
            scene_far->addLine(xpos, ymin, xpos, ymax, QPen(QColor(200, 200, 200), 1));
        }
    }

    // Draw global labels ...

    // ... timestamps ...

    const qreal ymin = pad_top;
    const qreal ymax = height - pad_bottom;

    for (int i = 0; i < dispTimestamps.size(); ++i) {

        const qreal timestamp = dispTimestamps.at(i);

        const QString xLabel = BMMisc::compactDateString(timestamp);
        font.setPointSize(12);

        const qreal xpos = xmin + (timestamp - loTimestamp) * xfact;

        // ... top x axis label ...
        {
            QGraphicsSimpleTextItem *text = scene_near->addSimpleText(xLabel, font);
            text->setPos(
                xpos - text->boundingRect().width() / 2,
                ymin - (text->boundingRect().height() + labelPad));
        }

        // ... bottom x axis label ...
        {
            QGraphicsSimpleTextItem *text = scene_near->addSimpleText(xLabel, font);
            text->setPos(
                xpos - text->boundingRect().width() / 2,
                ymax + labelPad);
        }
    }

    return true;
}