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