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