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