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