]> git.sesse.net Git - nageru/blob - nageru/correlation_meter.cpp
Fix a dangling reference (found by GCC 14).
[nageru] / nageru / correlation_meter.cpp
1 #include "correlation_meter.h"
2
3 #include <math.h>
4 #include <algorithm>
5 #include <mutex>
6
7 #include <QBrush>
8 #include <QColor>
9 #include <QPaintDevice>
10 #include <QPainter>
11 #include <QPixmap>
12 #include <QRect>
13 #include <QWidget>
14
15 class QPaintEvent;
16 class QResizeEvent;
17
18 using namespace std;
19
20 CorrelationMeter::CorrelationMeter(QWidget *parent)
21         : QWidget(parent)
22 {
23 }
24
25 void CorrelationMeter::resizeEvent(QResizeEvent *event)
26 {
27         on_pixmap = QPixmap(width(), height());
28         QPainter on_painter(&on_pixmap);
29         QLinearGradient on(0, 0, width(), 0);
30         on.setColorAt(0.0f, QColor(255, 0, 0));
31         on.setColorAt(0.5f, QColor(255, 255, 0));
32         on.setColorAt(0.8f, QColor(0, 255, 0));
33         on.setColorAt(0.95f, QColor(255, 255, 0));
34         on_painter.fillRect(0, 0, width(), height(), Qt::black);
35         on_painter.fillRect(1, 1, width() - 2, height() - 2, on);
36
37         off_pixmap = QPixmap(width(), height());
38         QPainter off_painter(&off_pixmap);
39         QLinearGradient off(0, 0, width(), 0);
40         off.setColorAt(0.0f, QColor(127, 0, 0));
41         off.setColorAt(0.5f, QColor(127, 127, 0));
42         off.setColorAt(0.8f, QColor(0, 127, 0));
43         off.setColorAt(0.95f, QColor(127, 127, 0));
44         off_painter.fillRect(0, 0, width(), height(), Qt::black);
45         off_painter.fillRect(1, 1, width() - 2, height() - 2, off);
46 }
47
48 void CorrelationMeter::paintEvent(QPaintEvent *event)
49 {
50         QPainter painter(this);
51
52         float correlation;
53         {
54                 lock_guard<mutex> lock(correlation_mutex);
55                 correlation = this->correlation;
56         }
57
58         // Just in case.
59         correlation = std::min(std::max(correlation, -1.0f), 1.0f);
60
61         int pos = 3 + lrintf(0.5f * (correlation + 1.0f) * (width() - 6));
62         QRect off_rect(0, 0, width(), height());
63         QRect on_rect(pos - 2, 0, 5, height());
64
65         painter.drawPixmap(off_rect, off_pixmap, off_rect);
66         painter.drawPixmap(on_rect, on_pixmap, on_rect);
67 }