]> sigrok.org Git - pulseview.git/blame - pv/views/trace/analogsignal.cpp
Implement graphical display of A2L thresholds
[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
6f925ba9
UH
49using std::deque;
50using std::div;
51using std::div_t;
819f4c25 52using std::max;
a5d93c27 53using std::make_pair;
819f4c25 54using std::min;
6f925ba9
UH
55using std::numeric_limits;
56using std::pair;
f9abf97e 57using std::shared_ptr;
a8fd2759 58using std::vector;
aba1dd16 59
2b6e7a72
SA
60using pv::data::SignalBase;
61
aba1dd16 62namespace pv {
f4e57597 63namespace views {
1573bf16 64namespace trace {
aba1dd16 65
568b90d4
JH
66const QColor AnalogSignal::SignalColours[4] = {
67 QColor(0xC4, 0xA0, 0x00), // Yellow
68 QColor(0x87, 0x20, 0x7A), // Magenta
69 QColor(0x20, 0x4A, 0x87), // Blue
70 QColor(0x4E, 0x9A, 0x06) // Green
71};
72
c063290a
UH
73const QColor AnalogSignal::GridMajorColor = QColor(0, 0, 0, 40 * 256 / 100);
74const QColor AnalogSignal::GridMinorColor = QColor(0, 0, 0, 20 * 256 / 100);
37b9fed4 75
8de1e1b2
UH
76const QColor AnalogSignal::SamplingPointColour(0x77, 0x77, 0x77);
77
4433246b
SA
78const QColor AnalogSignal::ThresholdColor = QColor(0, 0, 0, 30 * 256 / 100);
79
fdfd5b3e
SA
80const int64_t AnalogSignal::TracePaintBlockSize = 1024 * 1024; // 4 MiB (due to float)
81const float AnalogSignal::EnvelopeThreshold = 64.0f;
7c68ddae 82
4cffac16 83const int AnalogSignal::MaximumVDivs = 10;
368a37c2
SA
84const int AnalogSignal::MinScaleIndex = -6;
85const int AnalogSignal::MaxScaleIndex = 7;
4cffac16 86
03cc651d
SA
87const int AnalogSignal::InfoTextMarginRight = 20;
88const int AnalogSignal::InfoTextMarginBottom = 5;
89
b86aa8f4 90AnalogSignal::AnalogSignal(
2b81ae46 91 pv::Session &session,
cbd2a2de 92 shared_ptr<data::SignalBase> base) :
73a25a6e 93 Signal(session, base),
834a4f1b 94 scale_index_(4), // 20 per div
37b9fed4 95 scale_index_drag_offset_(0),
459db2c5
SA
96 pos_vdivs_(1),
97 neg_vdivs_(1),
73e377fe 98 resolution_(0),
a970015f 99 display_type_(DisplayBoth),
1f1d55ce 100 autoranging_(true)
aba1dd16 101{
85715407
SA
102 pv::data::Analog* analog_data =
103 dynamic_cast<pv::data::Analog*>(data().get());
104
105 connect(analog_data, SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
106 this, SLOT(on_samples_added()));
107
52c900ac
SA
108 connect(&delayed_conversion_starter_, SIGNAL(timeout()),
109 this, SLOT(on_delayed_conversion_starter()));
110 delayed_conversion_starter_.setSingleShot(true);
111 delayed_conversion_starter_.setInterval(1000); // 1s timeout
112
cbb50547
SA
113 GlobalSettings gs;
114 div_height_ = gs.value(GlobalSettings::Key_View_DefaultDivHeight).toInt();
115
73a25a6e 116 base_->set_colour(SignalColours[base_->index() % countof(SignalColours)]);
834a4f1b 117 update_scale();
aba1dd16
JH
118}
119
3009b5b3
JH
120shared_ptr<pv::data::SignalData> AnalogSignal::data() const
121{
cbd2a2de 122 return base_->analog_data();
9a0cd293
JH
123}
124
3a21afa6
SA
125void AnalogSignal::save_settings(QSettings &settings) const
126{
459db2c5
SA
127 settings.setValue("pos_vdivs", pos_vdivs_);
128 settings.setValue("neg_vdivs", neg_vdivs_);
3a21afa6 129 settings.setValue("scale_index", scale_index_);
a970015f 130 settings.setValue("display_type", display_type_);
73e377fe 131 settings.setValue("autoranging", autoranging_);
cbb50547 132 settings.setValue("div_height", div_height_);
3a21afa6
SA
133}
134
135void AnalogSignal::restore_settings(QSettings &settings)
136{
459db2c5
SA
137 if (settings.contains("pos_vdivs"))
138 pos_vdivs_ = settings.value("pos_vdivs").toInt();
139
140 if (settings.contains("neg_vdivs"))
141 neg_vdivs_ = settings.value("neg_vdivs").toInt();
3a21afa6
SA
142
143 if (settings.contains("scale_index")) {
144 scale_index_ = settings.value("scale_index").toInt();
145 update_scale();
146 }
73e377fe 147
a970015f
SA
148 if (settings.contains("display_type"))
149 display_type_ = (DisplayType)(settings.value("display_type").toInt());
150
73e377fe
SA
151 if (settings.contains("autoranging"))
152 autoranging_ = settings.value("autoranging").toBool();
cbb50547
SA
153
154 if (settings.contains("div_height")) {
155 const int old_height = div_height_;
156 div_height_ = settings.value("div_height").toInt();
157
158 if ((div_height_ != old_height) && owner_) {
159 // Call order is important, otherwise the lazy event handler won't work
160 owner_->extents_changed(false, true);
161 owner_->row_item_appearance_changed(false, true);
162 }
163 }
3a21afa6
SA
164}
165
6f925ba9 166pair<int, int> AnalogSignal::v_extents() const
a5d93c27 167{
459db2c5
SA
168 const int ph = pos_vdivs_ * div_height_;
169 const int nh = neg_vdivs_ * div_height_;
170 return make_pair(-ph, nh);
a5d93c27
JH
171}
172
214470fc
JH
173int AnalogSignal::scale_handle_offset() const
174{
459db2c5 175 const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
37b9fed4 176
c063290a 177 return ((scale_index_drag_offset_ - scale_index_) * h / 4) - h / 2;
214470fc
JH
178}
179
180void AnalogSignal::scale_handle_dragged(int offset)
181{
459db2c5 182 const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
37b9fed4 183
c063290a 184 scale_index_ = scale_index_drag_offset_ - (offset + h / 2) / (h / 4);
834a4f1b
SA
185
186 update_scale();
8a2fafcc
JH
187}
188
189void AnalogSignal::scale_handle_drag_release()
190{
191 scale_index_drag_offset_ = scale_index_;
834a4f1b 192 update_scale();
214470fc
JH
193}
194
60938e04 195void AnalogSignal::paint_back(QPainter &p, ViewItemPaintParams &pp)
fe08b6e8 196{
73a25a6e 197 if (base_->enabled()) {
99af6802 198 Trace::paint_back(p, pp);
97904bf7 199 paint_axis(p, pp, get_visual_y());
99af6802 200 }
fe08b6e8
JH
201}
202
60938e04 203void AnalogSignal::paint_mid(QPainter &p, ViewItemPaintParams &pp)
aba1dd16 204{
cbd2a2de 205 assert(base_->analog_data());
8dbbc7f0 206 assert(owner_);
a8acb46e 207
be9e7b4b 208 const int y = get_visual_y();
01fd3263 209
73a25a6e 210 if (!base_->enabled())
cec48d16
JH
211 return;
212
a8fd2759
SA
213 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
214 paint_grid(p, y, pp.left(), pp.right());
215
216 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
217 base_->analog_data()->analog_segments();
218 if (segments.empty())
219 return;
220
221 const shared_ptr<pv::data::AnalogSegment> &segment =
222 segments.front();
223
224 const double pixels_offset = pp.pixels_offset();
225 const double samplerate = max(1.0, segment->samplerate());
226 const pv::util::Timestamp& start_time = segment->start_time();
227 const int64_t last_sample = segment->get_sample_count() - 1;
228 const double samples_per_pixel = samplerate * pp.scale();
229 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
230 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
231
232 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
233 (int64_t)0), last_sample);
234 const int64_t end_sample = min(max((ceil(end) + 1).convert_to<int64_t>(),
235 (int64_t)0), last_sample);
236
237 if (samples_per_pixel < EnvelopeThreshold)
238 paint_trace(p, segment, y, pp.left(),
239 start_sample, end_sample,
240 pixels_offset, samples_per_pixel);
241 else
242 paint_envelope(p, segment, y, pp.left(),
243 start_sample, end_sample,
244 pixels_offset, samples_per_pixel);
245 }
a8acb46e 246
4433246b
SA
247 const SignalBase::ConversionType conv_type = base_->get_conversion_type();
248
249 if (((conv_type == SignalBase::A2LConversionByThreshold) ||
250 (conv_type == SignalBase::A2LConversionBySchmittTrigger))) {
251
252 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth))
253 paint_conversion_thresholds(p, pp);
a8acb46e 254
4433246b 255 if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
a8fd2759 256 paint_logic_mid(p, pp);
a8fd2759 257 }
7c68ddae
JH
258}
259
60938e04 260void AnalogSignal::paint_fore(QPainter &p, ViewItemPaintParams &pp)
03cc651d
SA
261{
262 if (!enabled())
263 return;
264
b8c4a95b
SA
265 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
266 const int y = get_visual_y();
03cc651d 267
b8c4a95b
SA
268 // Show the info section on the right side of the trace
269 const QString infotext = QString("%1 V/div").arg(resolution_);
03cc651d 270
b8c4a95b
SA
271 p.setPen(base_->colour());
272 p.setFont(QApplication::font());
03cc651d 273
b8c4a95b
SA
274 const QRectF bounding_rect = QRectF(pp.left(),
275 y + v_extents().first,
276 pp.width() - InfoTextMarginRight,
277 v_extents().second - v_extents().first - InfoTextMarginBottom);
03cc651d 278
b8c4a95b
SA
279 p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
280 }
03cc651d
SA
281}
282
37b9fed4
SA
283void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
284{
46a0cadc
SA
285 p.setRenderHint(QPainter::Antialiasing, false);
286
8ad61f40
UH
287 GlobalSettings settings;
288 const bool show_analog_minor_grid =
289 settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
290
459db2c5
SA
291 if (pos_vdivs_ > 0) {
292 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
293 for (int i = 1; i <= pos_vdivs_; i++) {
294 const float dy = i * div_height_;
295 p.drawLine(QLineF(left, y - dy, right, y - dy));
296 }
8ad61f40 297 }
459db2c5 298
8ad61f40 299 if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
459db2c5
SA
300 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
301 for (int i = 0; i < pos_vdivs_; i++) {
302 const float dy = i * div_height_;
303 const float dy25 = dy + (0.25 * div_height_);
304 const float dy50 = dy + (0.50 * div_height_);
305 const float dy75 = dy + (0.75 * div_height_);
306 p.drawLine(QLineF(left, y - dy25, right, y - dy25));
307 p.drawLine(QLineF(left, y - dy50, right, y - dy50));
308 p.drawLine(QLineF(left, y - dy75, right, y - dy75));
309 }
37b9fed4
SA
310 }
311
459db2c5
SA
312 if (neg_vdivs_ > 0) {
313 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
314 for (int i = 1; i <= neg_vdivs_; i++) {
315 const float dy = i * div_height_;
316 p.drawLine(QLineF(left, y + dy, right, y + dy));
317 }
8ad61f40 318 }
459db2c5 319
8ad61f40 320 if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
459db2c5
SA
321 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
322 for (int i = 0; i < neg_vdivs_; i++) {
323 const float dy = i * div_height_;
324 const float dy25 = dy + (0.25 * div_height_);
325 const float dy50 = dy + (0.50 * div_height_);
326 const float dy75 = dy + (0.75 * div_height_);
327 p.drawLine(QLineF(left, y + dy25, right, y + dy25));
328 p.drawLine(QLineF(left, y + dy50, right, y + dy50));
329 p.drawLine(QLineF(left, y + dy75, right, y + dy75));
330 }
37b9fed4 331 }
46a0cadc
SA
332
333 p.setRenderHint(QPainter::Antialiasing, true);
37b9fed4
SA
334}
335
7c68ddae 336void AnalogSignal::paint_trace(QPainter &p,
f3d66e52 337 const shared_ptr<pv::data::AnalogSegment> &segment,
7c68ddae
JH
338 int y, int left, const int64_t start, const int64_t end,
339 const double pixels_offset, const double samples_per_pixel)
340{
fdfd5b3e
SA
341 if (end <= start)
342 return;
343
344 // Calculate and paint the sampling points if enabled and useful
345 GlobalSettings settings;
346 const bool show_sampling_points =
347 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() &&
348 (samples_per_pixel < 0.25);
349
73a25a6e 350 p.setPen(base_->colour());
7c68ddae 351
76ce6c7a
UH
352 const int64_t points_count = end - start;
353
354 QPointF *points = new QPointF[points_count];
a8acb46e
JH
355 QPointF *point = points;
356
fdfd5b3e
SA
357 QRectF *sampling_points = nullptr;
358 if (show_sampling_points)
359 sampling_points = new QRectF[points_count];
8de1e1b2
UH
360 QRectF *sampling_point = sampling_points;
361
fdfd5b3e
SA
362 int64_t sample_count = min(points_count, TracePaintBlockSize);
363 int64_t block_sample = 0;
b82243f7
SA
364 float *sample_block = new float[TracePaintBlockSize];
365 segment->get_samples(start, start + sample_count, sample_block);
26a883ed 366
8de1e1b2 367 const int w = 2;
fdfd5b3e
SA
368 for (int64_t sample = start; sample != end; sample++, block_sample++) {
369
370 if (block_sample == TracePaintBlockSize) {
371 block_sample = 0;
fdfd5b3e 372 sample_count = min(points_count - sample, TracePaintBlockSize);
b82243f7 373 segment->get_samples(sample, sample + sample_count, sample_block);
fdfd5b3e
SA
374 }
375
a8acb46e 376 const float x = (sample / samples_per_pixel -
2658961b 377 pixels_offset) + left;
26a883ed 378
fdfd5b3e 379 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
8de1e1b2 380
fdfd5b3e
SA
381 if (show_sampling_points)
382 *sampling_point++ =
383 QRectF(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
a8acb46e 384 }
fdfd5b3e 385 delete[] sample_block;
a8acb46e 386
76ce6c7a 387 p.drawPolyline(points, points_count);
a8acb46e 388
fdfd5b3e 389 if (show_sampling_points) {
8de1e1b2
UH
390 p.setPen(SamplingPointColour);
391 p.drawRects(sampling_points, points_count);
fdfd5b3e 392 delete[] sampling_points;
8de1e1b2
UH
393 }
394
a8acb46e 395 delete[] points;
aba1dd16
JH
396}
397
7c68ddae 398void AnalogSignal::paint_envelope(QPainter &p,
f3d66e52 399 const shared_ptr<pv::data::AnalogSegment> &segment,
7c68ddae
JH
400 int y, int left, const int64_t start, const int64_t end,
401 const double pixels_offset, const double samples_per_pixel)
402{
f3d66e52 403 using pv::data::AnalogSegment;
7c68ddae 404
f3d66e52
JH
405 AnalogSegment::EnvelopeSection e;
406 segment->get_envelope_section(e, start, end, samples_per_pixel);
7c68ddae
JH
407
408 if (e.length < 2)
409 return;
410
819f4c25 411 p.setPen(QPen(Qt::NoPen));
73a25a6e 412 p.setBrush(base_->colour());
7c68ddae
JH
413
414 QRectF *const rects = new QRectF[e.length];
415 QRectF *rect = rects;
416
c063290a 417 for (uint64_t sample = 0; sample < e.length - 1; sample++) {
7c68ddae
JH
418 const float x = ((e.scale * sample + e.start) /
419 samples_per_pixel - pixels_offset) + left;
f3d66e52 420 const AnalogSegment::EnvelopeSample *const s =
7c68ddae
JH
421 e.samples + sample;
422
423 // We overlap this sample with the next so that vertical
424 // gaps do not appear during steep rising or falling edges
c063290a
UH
425 const float b = y - max(s->max, (s + 1)->min) * scale_;
426 const float t = y - min(s->min, (s + 1)->max) * scale_;
7c68ddae
JH
427
428 float h = b - t;
f3290553 429 if (h >= 0.0f && h <= 1.0f)
7c68ddae 430 h = 1.0f;
f3290553 431 if (h <= 0.0f && h >= -1.0f)
7c68ddae
JH
432 h = -1.0f;
433
434 *rect++ = QRectF(x, t, 1.0f, h);
435 }
436
437 p.drawRects(rects, e.length);
438
439 delete[] rects;
440 delete[] e.samples;
441}
442
4433246b
SA
443void AnalogSignal::paint_conversion_thresholds(QPainter &p,
444 ViewItemPaintParams &pp)
445{
446 if (!base_->enabled() || !base_->logic_data())
447 return;
448
449 // TODO Register a change handler instead of querying this with every repaint
450 GlobalSettings settings;
451 const bool show_conversion_thresholds =
452 settings.value(GlobalSettings::Key_View_ShowConversionThresholds).toBool();
453
454 if (!show_conversion_thresholds)
455 return;
456
457 const vector<double> thresholds = base_->get_conversion_thresholds();
458 const int y = get_visual_y();
459
460 p.setRenderHint(QPainter::Antialiasing, false);
461
462 p.setPen(ThresholdColor);
463
464 if (thresholds.size() == 2) {
465 // Draw as hatched block because two thresholds denote lower/upper level
466 const double thr_y0 = y - thresholds[0] * scale_;
467 const double thr_y1 = y - thresholds[1] * scale_;
468 p.fillRect(QRect(pp.left(), thr_y0, pp.right(), thr_y1 - thr_y0),
469 QBrush(ThresholdColor, Qt::BDiagPattern));
470 } else {
471 // Draw as individual lines
472 for (const double thr : thresholds) {
473 const double thr_y = y - thr * scale_;
474 p.drawLine(QPointF(pp.left(), thr_y), QPointF(pp.right(), thr_y));
475 }
476 }
477
478 p.setRenderHint(QPainter::Antialiasing, true);
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
85715407
SA
866void AnalogSignal::on_samples_added()
867{
430b94aa 868 perform_autoranging(false, false);
85715407
SA
869}
870
459db2c5
SA
871void AnalogSignal::on_pos_vdivs_changed(int vdivs)
872{
430b94aa
SA
873 if (vdivs == pos_vdivs_)
874 return;
875
459db2c5
SA
876 pos_vdivs_ = vdivs;
877
80067e49
SA
878 // There has to be at least one div, positive or negative
879 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
880 pos_vdivs_ = 1;
881 if (pvdiv_sb_)
882 pvdiv_sb_->setValue(pos_vdivs_);
883 }
884
430b94aa
SA
885 if (autoranging_) {
886 perform_autoranging(true, true);
887
888 // It could be that a positive or negative div was added, so update
889 if (pvdiv_sb_) {
890 pvdiv_sb_->setValue(pos_vdivs_);
891 nvdiv_sb_->setValue(neg_vdivs_);
892 }
893 }
73e377fe 894
459db2c5
SA
895 if (owner_) {
896 // Call order is important, otherwise the lazy event handler won't work
897 owner_->extents_changed(false, true);
898 owner_->row_item_appearance_changed(false, true);
899 }
900}
901
902void AnalogSignal::on_neg_vdivs_changed(int vdivs)
4cffac16 903{
430b94aa
SA
904 if (vdivs == neg_vdivs_)
905 return;
906
459db2c5 907 neg_vdivs_ = vdivs;
4cffac16 908
80067e49
SA
909 // There has to be at least one div, positive or negative
910 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
911 pos_vdivs_ = 1;
912 if (pvdiv_sb_)
913 pvdiv_sb_->setValue(pos_vdivs_);
914 }
915
430b94aa
SA
916 if (autoranging_) {
917 perform_autoranging(true, true);
918
919 // It could be that a positive or negative div was added, so update
920 if (pvdiv_sb_) {
921 pvdiv_sb_->setValue(pos_vdivs_);
922 nvdiv_sb_->setValue(neg_vdivs_);
923 }
924 }
73e377fe 925
75d0779e
SA
926 if (owner_) {
927 // Call order is important, otherwise the lazy event handler won't work
4cffac16 928 owner_->extents_changed(false, true);
75d0779e
SA
929 owner_->row_item_appearance_changed(false, true);
930 }
4cffac16
SA
931}
932
cbb50547
SA
933void AnalogSignal::on_div_height_changed(int height)
934{
935 div_height_ = height;
936 update_scale();
937
938 if (owner_) {
939 // Call order is important, otherwise the lazy event handler won't work
940 owner_->extents_changed(false, true);
941 owner_->row_item_appearance_changed(false, true);
942 }
943}
944
368a37c2
SA
945void AnalogSignal::on_resolution_changed(int index)
946{
947 scale_index_ = resolution_cb_->itemData(index).toInt();
948 update_scale();
949
950 if (owner_)
951 owner_->row_item_appearance_changed(false, true);
952}
4cffac16 953
73e377fe
SA
954void AnalogSignal::on_autoranging_changed(int state)
955{
956 autoranging_ = (state == Qt::Checked);
957
958 if (autoranging_)
430b94aa 959 perform_autoranging(false, true);
73e377fe 960
85715407
SA
961 if (owner_) {
962 // Call order is important, otherwise the lazy event handler won't work
963 owner_->extents_changed(false, true);
73e377fe 964 owner_->row_item_appearance_changed(false, true);
85715407 965 }
73e377fe
SA
966}
967
a970015f
SA
968void AnalogSignal::on_conversion_changed(int index)
969{
2b6e7a72 970 SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
a8fd2759 971
2b6e7a72
SA
972 SignalBase::ConversionType conv_type =
973 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
a8fd2759 974
06b6ce26
SA
975 if (conv_type != old_conv_type) {
976 base_->set_conversion_type(conv_type);
52c900ac 977 update_conversion_widgets();
06b6ce26
SA
978
979 if (owner_)
980 owner_->row_item_appearance_changed(false, true);
a8fd2759 981 }
a970015f
SA
982}
983
52c900ac
SA
984void AnalogSignal::on_conv_threshold_changed(int index)
985{
2b6e7a72 986 SignalBase::ConversionType conv_type = base_->get_conversion_type();
52c900ac
SA
987
988 // Note: index is set to -1 if the text in the combo box matches none of
989 // the entries in the combo box
990
991 if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
992 return;
993
994 // The combo box entry with the custom value has user_data set to -1
995 const int user_data = conv_threshold_cb_->findText(
996 conv_threshold_cb_->currentText());
997
998 const bool use_custom_thr = (index == -1) || (user_data == -1);
999
b9cdbe03 1000 if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
52c900ac
SA
1001 // Not one of the preset values, try to parse the combo box text
1002 // Note: Regex loosely based on
1003 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1004 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1005 QString re2 = "([a-zA-Z]*)"; // SI unit
1006 QRegExp regex(re1 + re2);
1007
1008 const QString text = conv_threshold_cb_->currentText();
1009 if (!regex.exactMatch(text))
1010 return; // String doesn't match the regex
1011
1012 QStringList tokens = regex.capturedTexts();
1013
1014 // For now, we simply assume that the unit is volt without modifiers
1015 const double thr = tokens.at(1).toDouble();
1016
1017 // Only restart the conversion if the threshold was updated
1018 if (base_->set_conversion_option("threshold_value", thr))
1019 delayed_conversion_starter_.start();
1020 }
1021
2b6e7a72 1022 if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
52c900ac
SA
1023 // Not one of the preset values, try to parse the combo box text
1024 // Note: Regex loosely based on
1025 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1026 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1027 QString re2 = "([a-zA-Z]*)"; // SI unit
1028 QString re3 = "\\/"; // Forward slash, not captured
1029 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1030 QString re5 = "([a-zA-Z]*)"; // SI unit
1031 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1032
1033 const QString text = conv_threshold_cb_->currentText();
1034 if (!regex.exactMatch(text))
1035 return; // String doesn't match the regex
1036
1037 QStringList tokens = regex.capturedTexts();
1038
1039 // For now, we simply assume that the unit is volt without modifiers
1040 const double low_thr = tokens.at(1).toDouble();
1041 const double high_thr = tokens.at(3).toDouble();
1042
1043 // Only restart the conversion if one of the options was updated
1044 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1045 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1046 if (o1 || o2)
1047 delayed_conversion_starter_.start();
1048 }
1049
1050 base_->set_conversion_preset(index);
1051
1052 // Immediately start the conversion if we're not asking for a delayed reaction
1053 if (!delayed_conversion_starter_.isActive())
1054 base_->start_conversion();
1055}
1056
1057void AnalogSignal::on_delayed_conversion_starter()
1058{
1059 base_->start_conversion();
1060}
1061
b8c4a95b
SA
1062void AnalogSignal::on_display_type_changed(int index)
1063{
1064 display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1065
1066 if (owner_)
1067 owner_->row_item_appearance_changed(false, true);
1068}
1069
1573bf16 1070} // namespace trace
f4e57597 1071} // namespace views
aba1dd16 1072} // namespace pv