]> sigrok.org Git - pulseview.git/blame - pv/views/trace/analogsignal.cpp
Convert threshold display setting to a multi-value choice
[pulseview.git] / pv / views / trace / analogsignal.cpp
CommitLineData
aba1dd16
JH
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
efdec55a 17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
aba1dd16
JH
18 */
19
20#include <extdef.h>
21
3b68d03d
JH
22#include <cassert>
23#include <cmath>
8a2fafcc
JH
24#include <cstdlib>
25#include <limits>
a8fd2759 26#include <vector>
aba1dd16 27
37b9fed4 28#include <QApplication>
73e377fe 29#include <QCheckBox>
368a37c2 30#include <QComboBox>
4cffac16 31#include <QFormLayout>
368a37c2
SA
32#include <QGridLayout>
33#include <QLabel>
03cc651d 34#include <QString>
37b9fed4 35
2acdb232 36#include "analogsignal.hpp"
1573bf16
SA
37#include "logicsignal.hpp"
38#include "view.hpp"
39
2acdb232 40#include "pv/data/analog.hpp"
f3d66e52 41#include "pv/data/analogsegment.hpp"
a8fd2759
SA
42#include "pv/data/logic.hpp"
43#include "pv/data/logicsegment.hpp"
bf0edd2b 44#include "pv/data/signalbase.hpp"
8de1e1b2 45#include "pv/globalsettings.hpp"
aba1dd16 46
fe3a1c21 47#include <libsigrokcxx/libsigrokcxx.hpp>
e8d00928 48
2601ce96 49using std::bind;
6f925ba9
UH
50using std::deque;
51using std::div;
52using std::div_t;
819f4c25 53using std::max;
a5d93c27 54using std::make_pair;
819f4c25 55using std::min;
6f925ba9
UH
56using std::numeric_limits;
57using std::pair;
2601ce96 58using std::placeholders::_1;
f9abf97e 59using std::shared_ptr;
a8fd2759 60using std::vector;
aba1dd16 61
2b6e7a72
SA
62using pv::data::SignalBase;
63
aba1dd16 64namespace pv {
f4e57597 65namespace views {
1573bf16 66namespace trace {
aba1dd16 67
568b90d4
JH
68const QColor AnalogSignal::SignalColours[4] = {
69 QColor(0xC4, 0xA0, 0x00), // Yellow
70 QColor(0x87, 0x20, 0x7A), // Magenta
71 QColor(0x20, 0x4A, 0x87), // Blue
72 QColor(0x4E, 0x9A, 0x06) // Green
73};
74
561ba3ae 75const QPen AnalogSignal::AxisPen(QColor(0, 0, 0, 30 * 256 / 100), 2);
c063290a
UH
76const QColor AnalogSignal::GridMajorColor = QColor(0, 0, 0, 40 * 256 / 100);
77const QColor AnalogSignal::GridMinorColor = QColor(0, 0, 0, 20 * 256 / 100);
37b9fed4 78
8de1e1b2
UH
79const QColor AnalogSignal::SamplingPointColour(0x77, 0x77, 0x77);
80
4433246b 81const QColor AnalogSignal::ThresholdColor = QColor(0, 0, 0, 30 * 256 / 100);
1d150cd6 82const QColor AnalogSignal::ThresholdColorLo = QColor(255, 0, 0, 8 * 256 / 100);
78bf7ce5 83const QColor AnalogSignal::ThresholdColorNe = QColor(0, 0, 0, 10 * 256 / 100);
1d150cd6 84const QColor AnalogSignal::ThresholdColorHi = QColor(0, 255, 0, 8 * 256 / 100);
4433246b 85
fdfd5b3e
SA
86const int64_t AnalogSignal::TracePaintBlockSize = 1024 * 1024; // 4 MiB (due to float)
87const float AnalogSignal::EnvelopeThreshold = 64.0f;
7c68ddae 88
4cffac16 89const int AnalogSignal::MaximumVDivs = 10;
368a37c2
SA
90const int AnalogSignal::MinScaleIndex = -6;
91const int AnalogSignal::MaxScaleIndex = 7;
4cffac16 92
03cc651d
SA
93const int AnalogSignal::InfoTextMarginRight = 20;
94const int AnalogSignal::InfoTextMarginBottom = 5;
95
b86aa8f4 96AnalogSignal::AnalogSignal(
2b81ae46 97 pv::Session &session,
cbd2a2de 98 shared_ptr<data::SignalBase> base) :
73a25a6e 99 Signal(session, base),
834a4f1b 100 scale_index_(4), // 20 per div
37b9fed4 101 scale_index_drag_offset_(0),
459db2c5
SA
102 pos_vdivs_(1),
103 neg_vdivs_(1),
73e377fe 104 resolution_(0),
a970015f 105 display_type_(DisplayBoth),
1f1d55ce 106 autoranging_(true)
aba1dd16 107{
561ba3ae
SA
108 axis_pen_ = AxisPen;
109
85715407
SA
110 pv::data::Analog* analog_data =
111 dynamic_cast<pv::data::Analog*>(data().get());
112
c6d9cf65
SA
113 connect(analog_data, SIGNAL(min_max_changed(float, float)),
114 this, SLOT(on_min_max_changed(float, float)));
85715407 115
90ee1ed9
SA
116 GlobalSettings::register_change_handler(GlobalSettings::Key_View_ConversionThresholdDispMode,
117 bind(&AnalogSignal::on_settingViewConversionThresholdDispMode_changed, this, _1));
2601ce96 118
cbb50547 119 GlobalSettings gs;
90ee1ed9
SA
120 conversion_threshold_disp_mode_ =
121 gs.value(GlobalSettings::Key_View_ConversionThresholdDispMode).toInt();
2601ce96 122
cbb50547
SA
123 div_height_ = gs.value(GlobalSettings::Key_View_DefaultDivHeight).toInt();
124
73a25a6e 125 base_->set_colour(SignalColours[base_->index() % countof(SignalColours)]);
834a4f1b 126 update_scale();
aba1dd16
JH
127}
128
3009b5b3
JH
129shared_ptr<pv::data::SignalData> AnalogSignal::data() const
130{
cbd2a2de 131 return base_->analog_data();
9a0cd293
JH
132}
133
3a21afa6
SA
134void AnalogSignal::save_settings(QSettings &settings) const
135{
459db2c5
SA
136 settings.setValue("pos_vdivs", pos_vdivs_);
137 settings.setValue("neg_vdivs", neg_vdivs_);
3a21afa6 138 settings.setValue("scale_index", scale_index_);
a970015f 139 settings.setValue("display_type", display_type_);
73e377fe 140 settings.setValue("autoranging", autoranging_);
cbb50547 141 settings.setValue("div_height", div_height_);
3a21afa6
SA
142}
143
144void AnalogSignal::restore_settings(QSettings &settings)
145{
459db2c5
SA
146 if (settings.contains("pos_vdivs"))
147 pos_vdivs_ = settings.value("pos_vdivs").toInt();
148
149 if (settings.contains("neg_vdivs"))
150 neg_vdivs_ = settings.value("neg_vdivs").toInt();
3a21afa6
SA
151
152 if (settings.contains("scale_index")) {
153 scale_index_ = settings.value("scale_index").toInt();
154 update_scale();
155 }
73e377fe 156
a970015f
SA
157 if (settings.contains("display_type"))
158 display_type_ = (DisplayType)(settings.value("display_type").toInt());
159
73e377fe
SA
160 if (settings.contains("autoranging"))
161 autoranging_ = settings.value("autoranging").toBool();
cbb50547
SA
162
163 if (settings.contains("div_height")) {
164 const int old_height = div_height_;
165 div_height_ = settings.value("div_height").toInt();
166
167 if ((div_height_ != old_height) && owner_) {
168 // Call order is important, otherwise the lazy event handler won't work
169 owner_->extents_changed(false, true);
170 owner_->row_item_appearance_changed(false, true);
171 }
172 }
3a21afa6
SA
173}
174
6f925ba9 175pair<int, int> AnalogSignal::v_extents() const
a5d93c27 176{
459db2c5
SA
177 const int ph = pos_vdivs_ * div_height_;
178 const int nh = neg_vdivs_ * div_height_;
179 return make_pair(-ph, nh);
a5d93c27
JH
180}
181
214470fc
JH
182int AnalogSignal::scale_handle_offset() const
183{
459db2c5 184 const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
37b9fed4 185
c063290a 186 return ((scale_index_drag_offset_ - scale_index_) * h / 4) - h / 2;
214470fc
JH
187}
188
189void AnalogSignal::scale_handle_dragged(int offset)
190{
459db2c5 191 const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
37b9fed4 192
c063290a 193 scale_index_ = scale_index_drag_offset_ - (offset + h / 2) / (h / 4);
834a4f1b
SA
194
195 update_scale();
8a2fafcc
JH
196}
197
198void AnalogSignal::scale_handle_drag_release()
199{
200 scale_index_drag_offset_ = scale_index_;
834a4f1b 201 update_scale();
214470fc
JH
202}
203
60938e04 204void AnalogSignal::paint_back(QPainter &p, ViewItemPaintParams &pp)
fe08b6e8 205{
1d150cd6
SA
206 if (!base_->enabled())
207 return;
208
90ee1ed9
SA
209 bool paint_thr_bg =
210 conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Background;
211
1d150cd6
SA
212 const vector<double> thresholds = base_->get_conversion_thresholds();
213
214 // Only display thresholds if we have some and we show analog samples
90ee1ed9 215 if ((thresholds.size() > 0) && paint_thr_bg &&
1d150cd6
SA
216 ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth))) {
217
218 const int visual_y = get_visual_y();
219 const pair<int, int> extents = v_extents();
220 const int top = visual_y + extents.first;
221 const int btm = visual_y + extents.second;
222
223 // Draw high/neutral/low areas
224 if (thresholds.size() == 2) {
225 const double thr_lo = visual_y - thresholds[0] * scale_;
226 const double thr_hi = visual_y - thresholds[1] * scale_;
227
228 p.fillRect(QRectF(pp.left(), top, pp.width(), thr_hi - top),
229 QBrush(ThresholdColorHi));
230 p.fillRect(QRectF(pp.left(), thr_hi, pp.width(), thr_lo - thr_hi),
231 QBrush(ThresholdColorNe));
232 p.fillRect(QRectF(pp.left(), thr_lo, pp.width(), btm - thr_lo),
233 QBrush(ThresholdColorLo));
234 } else {
235 const double thr = visual_y - thresholds[0] * scale_;
236
237 p.fillRect(QRectF(pp.left(), top, pp.width(), thr - top),
238 QBrush(ThresholdColorHi));
239 p.fillRect(QRectF(pp.left(), thr, pp.width(), btm - thr),
240 QBrush(ThresholdColorLo));
241 }
242
243 paint_axis(p, pp, get_visual_y());
244 } else {
99af6802 245 Trace::paint_back(p, pp);
97904bf7 246 paint_axis(p, pp, get_visual_y());
99af6802 247 }
fe08b6e8
JH
248}
249
60938e04 250void AnalogSignal::paint_mid(QPainter &p, ViewItemPaintParams &pp)
aba1dd16 251{
cbd2a2de 252 assert(base_->analog_data());
8dbbc7f0 253 assert(owner_);
a8acb46e 254
be9e7b4b 255 const int y = get_visual_y();
01fd3263 256
73a25a6e 257 if (!base_->enabled())
cec48d16
JH
258 return;
259
a8fd2759
SA
260 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
261 paint_grid(p, y, pp.left(), pp.right());
262
263 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
264 base_->analog_data()->analog_segments();
265 if (segments.empty())
266 return;
267
268 const shared_ptr<pv::data::AnalogSegment> &segment =
269 segments.front();
270
271 const double pixels_offset = pp.pixels_offset();
272 const double samplerate = max(1.0, segment->samplerate());
273 const pv::util::Timestamp& start_time = segment->start_time();
274 const int64_t last_sample = segment->get_sample_count() - 1;
275 const double samples_per_pixel = samplerate * pp.scale();
276 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
277 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
278
279 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
280 (int64_t)0), last_sample);
281 const int64_t end_sample = min(max((ceil(end) + 1).convert_to<int64_t>(),
282 (int64_t)0), last_sample);
283
284 if (samples_per_pixel < EnvelopeThreshold)
285 paint_trace(p, segment, y, pp.left(),
286 start_sample, end_sample,
287 pixels_offset, samples_per_pixel);
288 else
289 paint_envelope(p, segment, y, pp.left(),
290 start_sample, end_sample,
291 pixels_offset, samples_per_pixel);
292 }
a8acb46e 293
1d150cd6
SA
294 if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
295 paint_logic_mid(p, pp);
7c68ddae
JH
296}
297
60938e04 298void AnalogSignal::paint_fore(QPainter &p, ViewItemPaintParams &pp)
03cc651d
SA
299{
300 if (!enabled())
301 return;
302
b8c4a95b
SA
303 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
304 const int y = get_visual_y();
03cc651d 305
b8c4a95b
SA
306 // Show the info section on the right side of the trace
307 const QString infotext = QString("%1 V/div").arg(resolution_);
03cc651d 308
b8c4a95b
SA
309 p.setPen(base_->colour());
310 p.setFont(QApplication::font());
03cc651d 311
b8c4a95b
SA
312 const QRectF bounding_rect = QRectF(pp.left(),
313 y + v_extents().first,
314 pp.width() - InfoTextMarginRight,
315 v_extents().second - v_extents().first - InfoTextMarginBottom);
03cc651d 316
b8c4a95b
SA
317 p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
318 }
03cc651d
SA
319}
320
37b9fed4
SA
321void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
322{
46a0cadc
SA
323 p.setRenderHint(QPainter::Antialiasing, false);
324
8ad61f40
UH
325 GlobalSettings settings;
326 const bool show_analog_minor_grid =
327 settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
328
459db2c5
SA
329 if (pos_vdivs_ > 0) {
330 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
331 for (int i = 1; i <= pos_vdivs_; i++) {
332 const float dy = i * div_height_;
333 p.drawLine(QLineF(left, y - dy, right, y - dy));
334 }
8ad61f40 335 }
459db2c5 336
8ad61f40 337 if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
459db2c5
SA
338 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
339 for (int i = 0; i < pos_vdivs_; i++) {
340 const float dy = i * div_height_;
341 const float dy25 = dy + (0.25 * div_height_);
342 const float dy50 = dy + (0.50 * div_height_);
343 const float dy75 = dy + (0.75 * div_height_);
344 p.drawLine(QLineF(left, y - dy25, right, y - dy25));
345 p.drawLine(QLineF(left, y - dy50, right, y - dy50));
346 p.drawLine(QLineF(left, y - dy75, right, y - dy75));
347 }
37b9fed4
SA
348 }
349
459db2c5
SA
350 if (neg_vdivs_ > 0) {
351 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
352 for (int i = 1; i <= neg_vdivs_; i++) {
353 const float dy = i * div_height_;
354 p.drawLine(QLineF(left, y + dy, right, y + dy));
355 }
8ad61f40 356 }
459db2c5 357
8ad61f40 358 if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
459db2c5
SA
359 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
360 for (int i = 0; i < neg_vdivs_; i++) {
361 const float dy = i * div_height_;
362 const float dy25 = dy + (0.25 * div_height_);
363 const float dy50 = dy + (0.50 * div_height_);
364 const float dy75 = dy + (0.75 * div_height_);
365 p.drawLine(QLineF(left, y + dy25, right, y + dy25));
366 p.drawLine(QLineF(left, y + dy50, right, y + dy50));
367 p.drawLine(QLineF(left, y + dy75, right, y + dy75));
368 }
37b9fed4 369 }
46a0cadc
SA
370
371 p.setRenderHint(QPainter::Antialiasing, true);
37b9fed4
SA
372}
373
7c68ddae 374void AnalogSignal::paint_trace(QPainter &p,
f3d66e52 375 const shared_ptr<pv::data::AnalogSegment> &segment,
7c68ddae
JH
376 int y, int left, const int64_t start, const int64_t end,
377 const double pixels_offset, const double samples_per_pixel)
378{
fdfd5b3e
SA
379 if (end <= start)
380 return;
381
382 // Calculate and paint the sampling points if enabled and useful
383 GlobalSettings settings;
384 const bool show_sampling_points =
385 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() &&
386 (samples_per_pixel < 0.25);
387
73a25a6e 388 p.setPen(base_->colour());
7c68ddae 389
76ce6c7a
UH
390 const int64_t points_count = end - start;
391
392 QPointF *points = new QPointF[points_count];
a8acb46e
JH
393 QPointF *point = points;
394
fdfd5b3e
SA
395 QRectF *sampling_points = nullptr;
396 if (show_sampling_points)
397 sampling_points = new QRectF[points_count];
8de1e1b2
UH
398 QRectF *sampling_point = sampling_points;
399
fdfd5b3e
SA
400 int64_t sample_count = min(points_count, TracePaintBlockSize);
401 int64_t block_sample = 0;
b82243f7
SA
402 float *sample_block = new float[TracePaintBlockSize];
403 segment->get_samples(start, start + sample_count, sample_block);
26a883ed 404
8de1e1b2 405 const int w = 2;
fdfd5b3e
SA
406 for (int64_t sample = start; sample != end; sample++, block_sample++) {
407
408 if (block_sample == TracePaintBlockSize) {
409 block_sample = 0;
fdfd5b3e 410 sample_count = min(points_count - sample, TracePaintBlockSize);
b82243f7 411 segment->get_samples(sample, sample + sample_count, sample_block);
fdfd5b3e
SA
412 }
413
a8acb46e 414 const float x = (sample / samples_per_pixel -
2658961b 415 pixels_offset) + left;
26a883ed 416
fdfd5b3e 417 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
8de1e1b2 418
fdfd5b3e
SA
419 if (show_sampling_points)
420 *sampling_point++ =
421 QRectF(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
a8acb46e 422 }
fdfd5b3e 423 delete[] sample_block;
a8acb46e 424
76ce6c7a 425 p.drawPolyline(points, points_count);
a8acb46e 426
fdfd5b3e 427 if (show_sampling_points) {
8de1e1b2
UH
428 p.setPen(SamplingPointColour);
429 p.drawRects(sampling_points, points_count);
fdfd5b3e 430 delete[] sampling_points;
8de1e1b2
UH
431 }
432
a8acb46e 433 delete[] points;
aba1dd16
JH
434}
435
7c68ddae 436void AnalogSignal::paint_envelope(QPainter &p,
f3d66e52 437 const shared_ptr<pv::data::AnalogSegment> &segment,
7c68ddae
JH
438 int y, int left, const int64_t start, const int64_t end,
439 const double pixels_offset, const double samples_per_pixel)
440{
f3d66e52 441 using pv::data::AnalogSegment;
7c68ddae 442
f3d66e52
JH
443 AnalogSegment::EnvelopeSection e;
444 segment->get_envelope_section(e, start, end, samples_per_pixel);
7c68ddae
JH
445
446 if (e.length < 2)
447 return;
448
819f4c25 449 p.setPen(QPen(Qt::NoPen));
73a25a6e 450 p.setBrush(base_->colour());
7c68ddae
JH
451
452 QRectF *const rects = new QRectF[e.length];
453 QRectF *rect = rects;
454
c063290a 455 for (uint64_t sample = 0; sample < e.length - 1; sample++) {
7c68ddae
JH
456 const float x = ((e.scale * sample + e.start) /
457 samples_per_pixel - pixels_offset) + left;
f3d66e52 458 const AnalogSegment::EnvelopeSample *const s =
7c68ddae
JH
459 e.samples + sample;
460
461 // We overlap this sample with the next so that vertical
462 // gaps do not appear during steep rising or falling edges
c063290a
UH
463 const float b = y - max(s->max, (s + 1)->min) * scale_;
464 const float t = y - min(s->min, (s + 1)->max) * scale_;
7c68ddae
JH
465
466 float h = b - t;
f3290553 467 if (h >= 0.0f && h <= 1.0f)
7c68ddae 468 h = 1.0f;
f3290553 469 if (h <= 0.0f && h >= -1.0f)
7c68ddae
JH
470 h = -1.0f;
471
472 *rect++ = QRectF(x, t, 1.0f, h);
473 }
474
475 p.drawRects(rects, e.length);
476
477 delete[] rects;
478 delete[] e.samples;
479}
480
60938e04 481void AnalogSignal::paint_logic_mid(QPainter &p, ViewItemPaintParams &pp)
a8fd2759
SA
482{
483 QLineF *line;
484
485 vector< pair<int64_t, bool> > edges;
486
487 assert(base_);
488
489 const int y = get_visual_y();
490
6c0df7c4 491 if (!base_->enabled() || !base_->logic_data())
a8fd2759
SA
492 return;
493
494 const int signal_margin =
495 QFontMetrics(QApplication::font()).height() / 2;
496
497 const int ph = min(pos_vdivs_, 1) * div_height_;
498 const int nh = min(neg_vdivs_, 1) * div_height_;
499 const float high_offset = y - ph + signal_margin + 0.5f;
500 const float low_offset = y + nh - signal_margin - 0.5f;
501
502 const deque< shared_ptr<pv::data::LogicSegment> > &segments =
503 base_->logic_data()->logic_segments();
6c0df7c4 504
a8fd2759
SA
505 if (segments.empty())
506 return;
507
508 const shared_ptr<pv::data::LogicSegment> &segment =
509 segments.front();
510
511 double samplerate = segment->samplerate();
512
513 // Show sample rate as 1Hz when it is unknown
514 if (samplerate == 0.0)
515 samplerate = 1.0;
516
517 const double pixels_offset = pp.pixels_offset();
518 const pv::util::Timestamp& start_time = segment->start_time();
519 const int64_t last_sample = segment->get_sample_count() - 1;
520 const double samples_per_pixel = samplerate * pp.scale();
124be547 521 const double pixels_per_sample = 1 / samples_per_pixel;
a8fd2759
SA
522 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
523 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
524
525 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
526 (int64_t)0), last_sample);
527 const uint64_t end_sample = min(max(ceil(end).convert_to<int64_t>(),
528 (int64_t)0), last_sample);
529
530 segment->get_subsampled_edges(edges, start_sample, end_sample,
531 samples_per_pixel / LogicSignal::Oversampling, 0);
532 assert(edges.size() >= 2);
533
124be547
SA
534 // Check whether we need to paint the sampling points
535 GlobalSettings settings;
536 const bool show_sampling_points =
537 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() &&
538 (samples_per_pixel < 0.25);
539
540 vector<QRectF> sampling_points;
541 float sampling_point_x = 0.0f;
542 int64_t sampling_point_sample = start_sample;
543 const int w = 2;
544
545 if (show_sampling_points) {
546 sampling_points.reserve(end_sample - start_sample + 1);
547 sampling_point_x = (edges.cbegin()->first / samples_per_pixel - pixels_offset) + pp.left();
548 }
549
a8fd2759
SA
550 // Paint the edges
551 const unsigned int edge_count = edges.size() - 2;
552 QLineF *const edge_lines = new QLineF[edge_count];
553 line = edge_lines;
554
555 for (auto i = edges.cbegin() + 1; i != edges.cend() - 1; i++) {
556 const float x = ((*i).first / samples_per_pixel -
557 pixels_offset) + pp.left();
558 *line++ = QLineF(x, high_offset, x, low_offset);
124be547
SA
559
560 if (show_sampling_points)
561 while (sampling_point_sample < (*i).first) {
562 const float y = (*i).second ? low_offset : high_offset;
563 sampling_points.emplace_back(
564 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
565 sampling_point_sample++;
566 sampling_point_x += pixels_per_sample;
567 };
a8fd2759
SA
568 }
569
124be547
SA
570 // Calculate the sample points from the last edge to the end of the trace
571 if (show_sampling_points)
572 while ((uint64_t)sampling_point_sample <= end_sample) {
573 // Signal changed after the last edge, so the level is inverted
574 const float y = (edges.cend() - 1)->second ? high_offset : low_offset;
575 sampling_points.emplace_back(
576 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
577 sampling_point_sample++;
578 sampling_point_x += pixels_per_sample;
579 };
580
a8fd2759
SA
581 p.setPen(LogicSignal::EdgeColour);
582 p.drawLines(edge_lines, edge_count);
583 delete[] edge_lines;
584
585 // Paint the caps
586 const unsigned int max_cap_line_count = edges.size();
587 QLineF *const cap_lines = new QLineF[max_cap_line_count];
588
589 p.setPen(LogicSignal::HighColour);
590 paint_logic_caps(p, cap_lines, edges, true, samples_per_pixel,
591 pixels_offset, pp.left(), high_offset);
592 p.setPen(LogicSignal::LowColour);
593 paint_logic_caps(p, cap_lines, edges, false, samples_per_pixel,
594 pixels_offset, pp.left(), low_offset);
595
596 delete[] cap_lines;
597
a8fd2759 598 // Paint the sampling points
124be547
SA
599 if (show_sampling_points) {
600 p.setPen(SamplingPointColour);
601 p.drawRects(sampling_points.data(), sampling_points.size());
a8fd2759 602 }
a8fd2759
SA
603}
604
605void AnalogSignal::paint_logic_caps(QPainter &p, QLineF *const lines,
606 vector< pair<int64_t, bool> > &edges, bool level,
607 double samples_per_pixel, double pixels_offset, float x_offset,
608 float y_offset)
609{
610 QLineF *line = lines;
611
612 for (auto i = edges.begin(); i != (edges.end() - 1); i++)
613 if ((*i).second == level) {
614 *line++ = QLineF(
615 ((*i).first / samples_per_pixel -
616 pixels_offset) + x_offset, y_offset,
617 ((*(i+1)).first / samples_per_pixel -
618 pixels_offset) + x_offset, y_offset);
619 }
620
621 p.drawLines(lines, line - lines);
622}
623
368a37c2 624float AnalogSignal::get_resolution(int scale_index)
8a2fafcc
JH
625{
626 const float seq[] = {1.0f, 2.0f, 5.0f};
834a4f1b 627
6f925ba9
UH
628 const int offset = numeric_limits<int>::max() / (2 * countof(seq));
629 const div_t d = div((int)(scale_index + countof(seq) * offset),
8a2fafcc 630 countof(seq));
834a4f1b 631
368a37c2
SA
632 return powf(10.0f, d.quot - offset) * seq[d.rem];
633}
634
635void AnalogSignal::update_scale()
636{
637 resolution_ = get_resolution(scale_index_);
834a4f1b 638 scale_ = div_height_ / resolution_;
8a2fafcc
JH
639}
640
52c900ac
SA
641void AnalogSignal::update_conversion_widgets()
642{
2b6e7a72 643 SignalBase::ConversionType conv_type = base_->get_conversion_type();
52c900ac
SA
644
645 // Enable or disable widgets depending on conversion state
2b6e7a72
SA
646 conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
647 display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
52c900ac
SA
648
649 conv_threshold_cb_->clear();
650
651 vector < pair<QString, int> > presets = base_->get_conversion_presets();
652
653 // Prevent the combo box from firing the "edit text changed" signal
654 // as that would involuntarily select the first entry
655 conv_threshold_cb_->blockSignals(true);
656
657 // Set available options depending on chosen conversion
658 for (pair<QString, int> preset : presets)
659 conv_threshold_cb_->addItem(preset.first, preset.second);
660
661 map < QString, QVariant > options = base_->get_conversion_options();
662
b9cdbe03 663 if (conv_type == SignalBase::A2LConversionByThreshold) {
52c900ac 664 const vector<double> thresholds = base_->get_conversion_thresholds(
b9cdbe03 665 SignalBase::A2LConversionByThreshold, true);
52c900ac
SA
666 conv_threshold_cb_->addItem(
667 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
668 }
669
2b6e7a72 670 if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
52c900ac 671 const vector<double> thresholds = base_->get_conversion_thresholds(
2b6e7a72 672 SignalBase::A2LConversionBySchmittTrigger, true);
52c900ac
SA
673 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
674 QString::number(thresholds[0], 'f', 1),
675 QString::number(thresholds[1], 'f', 1)), -1);
676 }
677
678 int preset_id = base_->get_current_conversion_preset();
679 conv_threshold_cb_->setCurrentIndex(
680 conv_threshold_cb_->findData(preset_id));
681
682 conv_threshold_cb_->blockSignals(false);
683}
684
430b94aa 685void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
73e377fe
SA
686{
687 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
688 base_->analog_data()->analog_segments();
689
690 if (segments.empty())
691 return;
692
693 static double prev_min = 0, prev_max = 0;
694 double min = 0, max = 0;
695
696 for (shared_ptr<pv::data::AnalogSegment> segment : segments) {
6f925ba9 697 pair<double, double> mm = segment->get_min_max();
73e377fe
SA
698 min = std::min(min, mm.first);
699 max = std::max(max, mm.second);
700 }
701
702 if ((min == prev_min) && (max == prev_max) && !force_update)
703 return;
704
705 prev_min = min;
706 prev_max = max;
707
430b94aa
SA
708 // If we're allowed to alter the div assignment...
709 if (!keep_divs) {
710 // Use all divs for the positive range if there are no negative values
711 if ((min == 0) && (neg_vdivs_ > 0)) {
712 pos_vdivs_ += neg_vdivs_;
713 neg_vdivs_ = 0;
714 }
73e377fe 715
430b94aa
SA
716 // Split up the divs if there are negative values but no negative divs
717 if ((min < 0) && (neg_vdivs_ == 0)) {
718 neg_vdivs_ = pos_vdivs_ / 2;
719 pos_vdivs_ -= neg_vdivs_;
720 }
681b6d5a
SA
721 }
722
430b94aa
SA
723 // If there is still no positive div when we need it, add one
724 // (this can happen when pos_vdivs==neg_vdivs==0)
17c7f31c 725 if ((max > 0) && (pos_vdivs_ == 0)) {
430b94aa 726 pos_vdivs_ = 1;
17c7f31c
SA
727 owner_->extents_changed(false, true);
728 }
430b94aa
SA
729
730 // If there is still no negative div when we need it, add one
731 // (this can happen when pos_vdivs was 0 or 1 when trying to split)
17c7f31c 732 if ((min < 0) && (neg_vdivs_ == 0)) {
430b94aa 733 neg_vdivs_ = 1;
17c7f31c
SA
734 owner_->extents_changed(false, true);
735 }
430b94aa 736
73e377fe
SA
737 double min_value_per_div;
738 if ((pos_vdivs_ > 0) && (neg_vdivs_ > 0))
739 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
740 else if (pos_vdivs_ > 0)
741 min_value_per_div = max / pos_vdivs_;
742 else
743 min_value_per_div = -min / neg_vdivs_;
744
745 // Find first scale value that is bigger than the value we need
746 for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
747 if (get_resolution(i) > min_value_per_div) {
748 scale_index_ = i;
749 break;
750 }
751
752 update_scale();
753}
754
4cffac16
SA
755void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
756{
757 // Add the standard options
758 Signal::populate_popup_form(parent, form);
759
368a37c2
SA
760 QFormLayout *const layout = new QFormLayout;
761
cbb50547 762 // Add div-related settings
430b94aa
SA
763 pvdiv_sb_ = new QSpinBox(parent);
764 pvdiv_sb_->setRange(0, MaximumVDivs);
765 pvdiv_sb_->setValue(pos_vdivs_);
766 connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
459db2c5 767 this, SLOT(on_pos_vdivs_changed(int)));
430b94aa 768 layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
459db2c5 769
430b94aa
SA
770 nvdiv_sb_ = new QSpinBox(parent);
771 nvdiv_sb_->setRange(0, MaximumVDivs);
772 nvdiv_sb_->setValue(neg_vdivs_);
773 connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
459db2c5 774 this, SLOT(on_neg_vdivs_changed(int)));
430b94aa 775 layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
368a37c2 776
cbb50547
SA
777 div_height_sb_ = new QSpinBox(parent);
778 div_height_sb_->setRange(20, 1000);
779 div_height_sb_->setSingleStep(5);
780 div_height_sb_->setSuffix(tr(" pixels"));
781 div_height_sb_->setValue(div_height_);
782 connect(div_height_sb_, SIGNAL(valueChanged(int)),
783 this, SLOT(on_div_height_changed(int)));
784 layout->addRow(tr("Div height"), div_height_sb_);
785
368a37c2
SA
786 // Add the vertical resolution
787 resolution_cb_ = new QComboBox(parent);
788
789 for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
790 const QString label = QString("%1").arg(get_resolution(i));
791 resolution_cb_->insertItem(0, label, QVariant(i));
792 }
793
a970015f 794 int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
368a37c2
SA
795 resolution_cb_->setCurrentIndex(cur_idx);
796
797 connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
798 this, SLOT(on_resolution_changed(int)));
799
800 QGridLayout *const vdiv_layout = new QGridLayout;
801 QLabel *const vdiv_unit = new QLabel(tr("V/div"));
802 vdiv_layout->addWidget(resolution_cb_, 0, 0);
803 vdiv_layout->addWidget(vdiv_unit, 0, 1);
804
805 layout->addRow(tr("Vertical resolution"), vdiv_layout);
806
73e377fe
SA
807 // Add the autoranging checkbox
808 QCheckBox* autoranging_cb = new QCheckBox();
809 autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
810
811 connect(autoranging_cb, SIGNAL(stateChanged(int)),
812 this, SLOT(on_autoranging_changed(int)));
813
814 layout->addRow(tr("Autoranging"), autoranging_cb);
815
a970015f
SA
816 // Add the conversion type dropdown
817 conversion_cb_ = new QComboBox();
818
2b6e7a72
SA
819 conversion_cb_->addItem(tr("none"),
820 SignalBase::NoConversion);
821 conversion_cb_->addItem(tr("to logic via threshold"),
b9cdbe03 822 SignalBase::A2LConversionByThreshold);
2b6e7a72
SA
823 conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
824 SignalBase::A2LConversionBySchmittTrigger);
a970015f 825
06b6ce26 826 cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
a970015f
SA
827 conversion_cb_->setCurrentIndex(cur_idx);
828
7c84c074 829 layout->addRow(tr("Conversion"), conversion_cb_);
a970015f
SA
830
831 connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
832 this, SLOT(on_conversion_changed(int)));
833
52c900ac
SA
834 // Add the conversion threshold settings
835 conv_threshold_cb_ = new QComboBox();
836 conv_threshold_cb_->setEditable(true);
837
838 layout->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
839
840 connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
841 this, SLOT(on_conv_threshold_changed(int)));
842 connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString)),
843 this, SLOT(on_conv_threshold_changed())); // index will be -1
844
a970015f
SA
845 // Add the display type dropdown
846 display_type_cb_ = new QComboBox();
847
c6b017fb
SA
848 display_type_cb_->addItem(tr("analog"), DisplayAnalog);
849 display_type_cb_->addItem(tr("converted"), DisplayConverted);
850 display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
a970015f
SA
851
852 cur_idx = display_type_cb_->findData(QVariant(display_type_));
853 display_type_cb_->setCurrentIndex(cur_idx);
854
c6b017fb 855 layout->addRow(tr("Show traces for"), display_type_cb_);
a970015f 856
b8c4a95b
SA
857 connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
858 this, SLOT(on_display_type_changed(int)));
859
52c900ac
SA
860 // Update the conversion widget contents and states
861 update_conversion_widgets();
862
368a37c2 863 form->addRow(layout);
4cffac16
SA
864}
865
c6d9cf65 866void AnalogSignal::on_min_max_changed(float min, float max)
85715407 867{
c6d9cf65
SA
868 (void)min;
869 (void)max;
870
871 if (autoranging_)
872 perform_autoranging(false, false);
85715407
SA
873}
874
459db2c5
SA
875void AnalogSignal::on_pos_vdivs_changed(int vdivs)
876{
430b94aa
SA
877 if (vdivs == pos_vdivs_)
878 return;
879
459db2c5
SA
880 pos_vdivs_ = vdivs;
881
80067e49
SA
882 // There has to be at least one div, positive or negative
883 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
884 pos_vdivs_ = 1;
885 if (pvdiv_sb_)
886 pvdiv_sb_->setValue(pos_vdivs_);
887 }
888
430b94aa
SA
889 if (autoranging_) {
890 perform_autoranging(true, true);
891
892 // It could be that a positive or negative div was added, so update
893 if (pvdiv_sb_) {
894 pvdiv_sb_->setValue(pos_vdivs_);
895 nvdiv_sb_->setValue(neg_vdivs_);
896 }
897 }
73e377fe 898
459db2c5
SA
899 if (owner_) {
900 // Call order is important, otherwise the lazy event handler won't work
901 owner_->extents_changed(false, true);
902 owner_->row_item_appearance_changed(false, true);
903 }
904}
905
906void AnalogSignal::on_neg_vdivs_changed(int vdivs)
4cffac16 907{
430b94aa
SA
908 if (vdivs == neg_vdivs_)
909 return;
910
459db2c5 911 neg_vdivs_ = vdivs;
4cffac16 912
80067e49
SA
913 // There has to be at least one div, positive or negative
914 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
915 pos_vdivs_ = 1;
916 if (pvdiv_sb_)
917 pvdiv_sb_->setValue(pos_vdivs_);
918 }
919
430b94aa
SA
920 if (autoranging_) {
921 perform_autoranging(true, true);
922
923 // It could be that a positive or negative div was added, so update
924 if (pvdiv_sb_) {
925 pvdiv_sb_->setValue(pos_vdivs_);
926 nvdiv_sb_->setValue(neg_vdivs_);
927 }
928 }
73e377fe 929
75d0779e
SA
930 if (owner_) {
931 // Call order is important, otherwise the lazy event handler won't work
4cffac16 932 owner_->extents_changed(false, true);
75d0779e
SA
933 owner_->row_item_appearance_changed(false, true);
934 }
4cffac16
SA
935}
936
cbb50547
SA
937void AnalogSignal::on_div_height_changed(int height)
938{
939 div_height_ = height;
940 update_scale();
941
942 if (owner_) {
943 // Call order is important, otherwise the lazy event handler won't work
944 owner_->extents_changed(false, true);
945 owner_->row_item_appearance_changed(false, true);
946 }
947}
948
368a37c2
SA
949void AnalogSignal::on_resolution_changed(int index)
950{
951 scale_index_ = resolution_cb_->itemData(index).toInt();
952 update_scale();
953
954 if (owner_)
955 owner_->row_item_appearance_changed(false, true);
956}
4cffac16 957
73e377fe
SA
958void AnalogSignal::on_autoranging_changed(int state)
959{
960 autoranging_ = (state == Qt::Checked);
961
962 if (autoranging_)
430b94aa 963 perform_autoranging(false, true);
73e377fe 964
85715407
SA
965 if (owner_) {
966 // Call order is important, otherwise the lazy event handler won't work
967 owner_->extents_changed(false, true);
73e377fe 968 owner_->row_item_appearance_changed(false, true);
85715407 969 }
73e377fe
SA
970}
971
a970015f
SA
972void AnalogSignal::on_conversion_changed(int index)
973{
2b6e7a72 974 SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
a8fd2759 975
2b6e7a72
SA
976 SignalBase::ConversionType conv_type =
977 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
a8fd2759 978
06b6ce26
SA
979 if (conv_type != old_conv_type) {
980 base_->set_conversion_type(conv_type);
52c900ac 981 update_conversion_widgets();
06b6ce26
SA
982
983 if (owner_)
984 owner_->row_item_appearance_changed(false, true);
a8fd2759 985 }
a970015f
SA
986}
987
52c900ac
SA
988void AnalogSignal::on_conv_threshold_changed(int index)
989{
2b6e7a72 990 SignalBase::ConversionType conv_type = base_->get_conversion_type();
52c900ac
SA
991
992 // Note: index is set to -1 if the text in the combo box matches none of
993 // the entries in the combo box
994
995 if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
996 return;
997
998 // The combo box entry with the custom value has user_data set to -1
999 const int user_data = conv_threshold_cb_->findText(
1000 conv_threshold_cb_->currentText());
1001
1002 const bool use_custom_thr = (index == -1) || (user_data == -1);
1003
b9cdbe03 1004 if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
52c900ac
SA
1005 // Not one of the preset values, try to parse the combo box text
1006 // Note: Regex loosely based on
1007 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1008 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1009 QString re2 = "([a-zA-Z]*)"; // SI unit
1010 QRegExp regex(re1 + re2);
1011
1012 const QString text = conv_threshold_cb_->currentText();
1013 if (!regex.exactMatch(text))
1014 return; // String doesn't match the regex
1015
1016 QStringList tokens = regex.capturedTexts();
1017
1018 // For now, we simply assume that the unit is volt without modifiers
1019 const double thr = tokens.at(1).toDouble();
1020
932bc246
SA
1021 // Only restart the conversion if the threshold was updated.
1022 // We're starting a delayed conversion because the user may still be
1023 // typing and the UI would lag if we kept on restarting it immediately
52c900ac 1024 if (base_->set_conversion_option("threshold_value", thr))
932bc246 1025 base_->start_conversion(true);
52c900ac
SA
1026 }
1027
2b6e7a72 1028 if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
52c900ac
SA
1029 // Not one of the preset values, try to parse the combo box text
1030 // Note: Regex loosely based on
1031 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1032 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1033 QString re2 = "([a-zA-Z]*)"; // SI unit
1034 QString re3 = "\\/"; // Forward slash, not captured
1035 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1036 QString re5 = "([a-zA-Z]*)"; // SI unit
1037 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1038
1039 const QString text = conv_threshold_cb_->currentText();
1040 if (!regex.exactMatch(text))
1041 return; // String doesn't match the regex
1042
1043 QStringList tokens = regex.capturedTexts();
1044
1045 // For now, we simply assume that the unit is volt without modifiers
1046 const double low_thr = tokens.at(1).toDouble();
1047 const double high_thr = tokens.at(3).toDouble();
1048
932bc246
SA
1049 // Only restart the conversion if one of the options was updated.
1050 // We're starting a delayed conversion because the user may still be
1051 // typing and the UI would lag if we kept on restarting it immediately
52c900ac
SA
1052 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1053 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1054 if (o1 || o2)
932bc246 1055 base_->start_conversion(true); // Start delayed conversion
52c900ac
SA
1056 }
1057
f0f9c856 1058 base_->set_conversion_preset((SignalBase::ConversionPreset)index);
52c900ac 1059
932bc246
SA
1060 // Immediately start the conversion if we're not using custom values
1061 // (i.e. we're using one of the presets)
1062 if (!use_custom_thr)
52c900ac
SA
1063 base_->start_conversion();
1064}
1065
1066void AnalogSignal::on_delayed_conversion_starter()
1067{
1068 base_->start_conversion();
1069}
1070
b8c4a95b
SA
1071void AnalogSignal::on_display_type_changed(int index)
1072{
1073 display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1074
1075 if (owner_)
1076 owner_->row_item_appearance_changed(false, true);
1077}
1078
90ee1ed9 1079void AnalogSignal::on_settingViewConversionThresholdDispMode_changed(const QVariant new_value)
2601ce96 1080{
90ee1ed9 1081 conversion_threshold_disp_mode_ = new_value.toInt();
2601ce96
SA
1082
1083 if (owner_)
1084 owner_->row_item_appearance_changed(false, true);
1085}
1086
1573bf16 1087} // namespace trace
f4e57597 1088} // namespace views
aba1dd16 1089} // namespace pv