]> sigrok.org Git - pulseview.git/blame_incremental - pv/views/trace/analogsignal.cpp
Session: Fix issue #67 by improving error handling
[pulseview.git] / pv / views / trace / analogsignal.cpp
... / ...
CommitLineData
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
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include <extdef.h>
21
22#include <cassert>
23#include <cmath>
24#include <cstdlib>
25#include <limits>
26#include <vector>
27
28#include <QApplication>
29#include <QCheckBox>
30#include <QComboBox>
31#include <QDebug>
32#include <QFormLayout>
33#include <QGridLayout>
34#include <QLabel>
35#include <QString>
36
37#include "analogsignal.hpp"
38#include "logicsignal.hpp"
39#include "view.hpp"
40
41#include "pv/util.hpp"
42#include "pv/data/analog.hpp"
43#include "pv/data/analogsegment.hpp"
44#include "pv/data/logic.hpp"
45#include "pv/data/logicsegment.hpp"
46#include "pv/data/signalbase.hpp"
47#include "pv/globalsettings.hpp"
48
49#include <libsigrokcxx/libsigrokcxx.hpp>
50
51using std::deque;
52using std::div;
53using std::div_t;
54// Note that "using std::isnan;" is _not_ put here since that would break
55// compilation on some platforms. Use "std::isnan()" instead in checks below.
56using std::max;
57using std::make_pair;
58using std::min;
59using std::numeric_limits;
60using std::out_of_range;
61using std::pair;
62using std::shared_ptr;
63using std::vector;
64
65using pv::data::LogicSegment;
66using pv::data::SignalBase;
67using pv::util::SIPrefix;
68using pv::util::determine_value_prefix;
69
70namespace pv {
71namespace views {
72namespace trace {
73
74const QPen AnalogSignal::AxisPen(QColor(0, 0, 0, 30 * 256 / 100), 2);
75const QColor AnalogSignal::GridMajorColor = QColor(0, 0, 0, 40 * 256 / 100);
76const QColor AnalogSignal::GridMinorColor = QColor(0, 0, 0, 20 * 256 / 100);
77
78const QColor AnalogSignal::SamplingPointColorLo = QColor(200, 0, 0, 80 * 256 / 100);
79const QColor AnalogSignal::SamplingPointColorNe = QColor(0, 0, 0, 80 * 256 / 100);
80const QColor AnalogSignal::SamplingPointColorHi = QColor(0, 200, 0, 80 * 256 / 100);
81
82const QColor AnalogSignal::ThresholdColor = QColor(0, 0, 0, 30 * 256 / 100);
83const QColor AnalogSignal::ThresholdColorLo = QColor(255, 0, 0, 8 * 256 / 100);
84const QColor AnalogSignal::ThresholdColorNe = QColor(0, 0, 0, 10 * 256 / 100);
85const QColor AnalogSignal::ThresholdColorHi = QColor(0, 255, 0, 8 * 256 / 100);
86
87const int64_t AnalogSignal::TracePaintBlockSize = 1024 * 1024; // 4 MiB (due to float)
88const float AnalogSignal::EnvelopeThreshold = 64.0f;
89
90const int AnalogSignal::MaximumVDivs = 10;
91const int AnalogSignal::MinScaleIndex = -6; // 0.01 units/div
92const int AnalogSignal::MaxScaleIndex = 10; // 1000 units/div
93
94const int AnalogSignal::InfoTextMarginRight = 20;
95const int AnalogSignal::InfoTextMarginBottom = 5;
96
97AnalogSignal::AnalogSignal(pv::Session &session, shared_ptr<data::SignalBase> base) :
98 LogicSignal(session, base),
99 value_at_hover_pos_(std::numeric_limits<float>::quiet_NaN()),
100 scale_index_(4), // 20 per div
101 pos_vdivs_(1),
102 neg_vdivs_(1),
103 resolution_(0),
104 display_type_(DisplayAnalog),
105 autoranging_(true)
106{
107 axis_pen_ = AxisPen;
108
109 pv::data::Analog* analog_data =
110 dynamic_cast<pv::data::Analog*>(base_->analog_data().get());
111
112 connect(analog_data, SIGNAL(min_max_changed(float, float)),
113 this, SLOT(on_min_max_changed(float, float)));
114
115 GlobalSettings settings;
116 show_sampling_points_ =
117 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool();
118 fill_high_areas_ =
119 settings.value(GlobalSettings::Key_View_FillSignalHighAreas).toBool();
120 high_fill_color_ = QColor::fromRgba(settings.value(
121 GlobalSettings::Key_View_FillSignalHighAreaColor).value<uint32_t>());
122 show_analog_minor_grid_ =
123 settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
124 conversion_threshold_disp_mode_ =
125 settings.value(GlobalSettings::Key_View_ConversionThresholdDispMode).toInt();
126 div_height_ = settings.value(GlobalSettings::Key_View_DefaultDivHeight).toInt();
127
128 update_logic_level_offsets();
129 update_scale();
130}
131
132std::map<QString, QVariant> AnalogSignal::save_settings() const
133{
134 LogicSignal::save_settings();
135
136 std::map<QString, QVariant> result;
137
138 result["pos_vdivs"] = pos_vdivs_;
139 result["neg_vdivs"] = neg_vdivs_;
140 result["scale_index"] = scale_index_;
141 result["display_type"] = display_type_;
142 result["autoranging"] = pos_vdivs_;
143 result["div_height"] = div_height_;
144
145 return result;
146}
147
148void AnalogSignal::restore_settings(std::map<QString, QVariant> settings)
149{
150 LogicSignal::restore_settings(settings);
151
152 auto entry = settings.find("pos_vdivs");
153 if (entry != settings.end())
154 pos_vdivs_ = settings["pos_vdivs"].toInt();
155
156 entry = settings.find("neg_vdivs");
157 if (entry != settings.end())
158 neg_vdivs_ = settings["neg_vdivs"].toInt();
159
160 entry = settings.find("scale_index");
161 if (entry != settings.end()) {
162 scale_index_ = settings["scale_index"].toInt();
163 update_scale();
164 }
165
166 entry = settings.find("display_type");
167 if (entry != settings.end())
168 display_type_ = (DisplayType)(settings["display_type"].toInt());
169
170 entry = settings.find("autoranging");
171 if (entry != settings.end())
172 autoranging_ = settings["autoranging"].toBool();
173
174 entry = settings.find("div_height");
175 if (entry != settings.end()) {
176 const int old_height = div_height_;
177 div_height_ = settings["div_height"].toInt();
178
179 update_logic_level_offsets();
180
181 if ((div_height_ != old_height) && owner_) {
182 // Call order is important, otherwise the lazy event handler won't work
183 owner_->extents_changed(false, true);
184 owner_->row_item_appearance_changed(false, true);
185 }
186 }
187}
188
189pair<int, int> AnalogSignal::v_extents() const
190{
191 const int ph = pos_vdivs_ * div_height_;
192 const int nh = neg_vdivs_ * div_height_;
193
194 return make_pair(-ph, nh);
195}
196
197void AnalogSignal::paint_back(QPainter &p, ViewItemPaintParams &pp)
198{
199 if (!base_->enabled())
200 return;
201
202 bool paint_thr_bg =
203 conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Background;
204
205 const vector<double> thresholds = base_->get_conversion_thresholds();
206
207 // Only display thresholds if we have some and we show analog samples
208 if ((thresholds.size() > 0) && paint_thr_bg &&
209 ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth))) {
210
211 const int visual_y = get_visual_y();
212 const pair<int, int> extents = v_extents();
213 const int top = visual_y + extents.first;
214 const int btm = visual_y + extents.second;
215
216 // Draw high/neutral/low areas
217 if (thresholds.size() == 2) {
218 int thr_lo = visual_y - thresholds[0] * scale_;
219 int thr_hi = visual_y - thresholds[1] * scale_;
220 thr_lo = min(max(thr_lo, top), btm);
221 thr_hi = min(max(thr_hi, top), btm);
222
223 p.fillRect(QRectF(pp.left(), top, pp.width(), thr_hi - top),
224 QBrush(ThresholdColorHi));
225 p.fillRect(QRectF(pp.left(), thr_hi, pp.width(), thr_lo - thr_hi),
226 QBrush(ThresholdColorNe));
227 p.fillRect(QRectF(pp.left(), thr_lo, pp.width(), btm - thr_lo),
228 QBrush(ThresholdColorLo));
229 } else {
230 int thr = visual_y - thresholds[0] * scale_;
231 thr = min(max(thr, top), btm);
232
233 p.fillRect(QRectF(pp.left(), top, pp.width(), thr - top),
234 QBrush(ThresholdColorHi));
235 p.fillRect(QRectF(pp.left(), thr, pp.width(), btm - thr),
236 QBrush(ThresholdColorLo));
237 }
238
239 paint_axis(p, pp, get_visual_y());
240 } else {
241 Signal::paint_back(p, pp);
242 paint_axis(p, pp, get_visual_y());
243 }
244}
245
246void AnalogSignal::paint_mid(QPainter &p, ViewItemPaintParams &pp)
247{
248 assert(base_->analog_data());
249 assert(owner_);
250
251 const int y = get_visual_y();
252
253 if (!base_->enabled())
254 return;
255
256 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
257 paint_grid(p, y, pp.left(), pp.right());
258
259 shared_ptr<pv::data::AnalogSegment> segment = get_analog_segment_to_paint();
260
261 if (segment && (segment->get_sample_count() > 0)) {
262 const double pixels_offset = pp.pixels_offset();
263 const double samplerate = max(1.0, segment->samplerate());
264 const pv::util::Timestamp& start_time = segment->start_time();
265 const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
266 const double samples_per_pixel = samplerate * pp.scale();
267 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
268 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
269
270 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
271 (int64_t)0), last_sample);
272 const int64_t end_sample = min(max((ceil(end) + 1).convert_to<int64_t>(),
273 (int64_t)0), last_sample);
274
275 if (samples_per_pixel < EnvelopeThreshold)
276 paint_trace(p, segment, y, pp.left(), start_sample, end_sample,
277 pixels_offset, samples_per_pixel);
278 else
279 paint_envelope(p, segment, y, pp.left(), start_sample, end_sample,
280 pixels_offset, samples_per_pixel);
281 }
282 }
283
284 if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
285 if (base_->logic_data())
286 LogicSignal::paint_mid(p, pp);
287
288 const QString err = base_->get_error_message();
289 if (!err.isEmpty())
290 paint_error(p, pp);
291}
292
293void AnalogSignal::paint_fore(QPainter &p, ViewItemPaintParams &pp)
294{
295 if (!enabled())
296 return;
297
298 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
299 const int y = get_visual_y();
300
301 QString infotext;
302
303 SIPrefix prefix;
304 if (fabs(signal_max_) > fabs(signal_min_))
305 prefix = determine_value_prefix(fabs(signal_max_));
306 else
307 prefix = determine_value_prefix(fabs(signal_min_));
308
309 // Show the info section on the right side of the trace, including
310 // the value at the hover point when the hover marker is enabled
311 // and we have corresponding data available
312 if (show_hover_marker_ && !std::isnan(value_at_hover_pos_)) {
313 infotext = QString("[%1] %2 V/div")
314 .arg(format_value_si(value_at_hover_pos_, prefix, 3, "V", false))
315 .arg(resolution_);
316 } else
317 infotext = QString("%1 V/div").arg(resolution_);
318
319 p.setPen(base_->color());
320 p.setFont(QApplication::font());
321
322 const QRectF bounding_rect = QRectF(pp.left(),
323 y + v_extents().first,
324 pp.width() - InfoTextMarginRight,
325 v_extents().second - v_extents().first - InfoTextMarginBottom);
326
327 p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
328
329 if (show_hover_marker_)
330 paint_hover_marker(p);
331 }
332
333 if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
334 LogicSignal::paint_fore(p, pp);
335}
336
337void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
338{
339 bool was_antialiased = p.testRenderHint(QPainter::Antialiasing);
340 p.setRenderHint(QPainter::Antialiasing, false);
341
342 if (pos_vdivs_ > 0) {
343 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
344 for (int i = 1; i <= pos_vdivs_; i++) {
345 const float dy = i * div_height_;
346 p.drawLine(QLineF(left, y - dy, right, y - dy));
347 }
348 }
349
350 if ((pos_vdivs_ > 0) && show_analog_minor_grid_) {
351 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
352 for (int i = 0; i < pos_vdivs_; i++) {
353 const float dy = i * div_height_;
354 const float dy25 = dy + (0.25 * div_height_);
355 const float dy50 = dy + (0.50 * div_height_);
356 const float dy75 = dy + (0.75 * div_height_);
357 p.drawLine(QLineF(left, y - dy25, right, y - dy25));
358 p.drawLine(QLineF(left, y - dy50, right, y - dy50));
359 p.drawLine(QLineF(left, y - dy75, right, y - dy75));
360 }
361 }
362
363 if (neg_vdivs_ > 0) {
364 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
365 for (int i = 1; i <= neg_vdivs_; i++) {
366 const float dy = i * div_height_;
367 p.drawLine(QLineF(left, y + dy, right, y + dy));
368 }
369 }
370
371 if ((pos_vdivs_ > 0) && show_analog_minor_grid_) {
372 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
373 for (int i = 0; i < neg_vdivs_; i++) {
374 const float dy = i * div_height_;
375 const float dy25 = dy + (0.25 * div_height_);
376 const float dy50 = dy + (0.50 * div_height_);
377 const float dy75 = dy + (0.75 * div_height_);
378 p.drawLine(QLineF(left, y + dy25, right, y + dy25));
379 p.drawLine(QLineF(left, y + dy50, right, y + dy50));
380 p.drawLine(QLineF(left, y + dy75, right, y + dy75));
381 }
382 }
383
384 p.setRenderHint(QPainter::Antialiasing, was_antialiased);
385}
386
387void AnalogSignal::paint_trace(QPainter &p,
388 const shared_ptr<pv::data::AnalogSegment> &segment,
389 int y, int left, const int64_t start, const int64_t end,
390 const double pixels_offset, const double samples_per_pixel)
391{
392 if (end <= start)
393 return;
394
395 bool paint_thr_dots =
396 (base_->get_conversion_type() != data::SignalBase::NoConversion) &&
397 (conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Dots);
398
399 vector<double> thresholds;
400 if (paint_thr_dots)
401 thresholds = base_->get_conversion_thresholds();
402
403 // Calculate and paint the sampling points if enabled and useful
404 GlobalSettings settings;
405 const bool show_sampling_points =
406 (show_sampling_points_ || paint_thr_dots) && (samples_per_pixel < 0.25);
407
408 p.setPen(base_->color());
409
410 const int64_t points_count = end - start + 1;
411
412 QPointF *points = new QPointF[points_count];
413 QPointF *point = points;
414
415 vector<QRectF> sampling_points[3];
416
417 int64_t sample_count = min(points_count, TracePaintBlockSize);
418 int64_t block_sample = 0;
419 float *sample_block = new float[TracePaintBlockSize];
420 segment->get_samples(start, start + sample_count, sample_block);
421
422 if (show_hover_marker_)
423 reset_pixel_values();
424
425 const int w = 2;
426 for (int64_t sample = start; sample <= end; sample++, block_sample++) {
427
428 // Fetch next block of samples if we finished the current one
429 if (block_sample == TracePaintBlockSize) {
430 block_sample = 0;
431 sample_count = min(points_count - sample, TracePaintBlockSize);
432 segment->get_samples(sample, sample + sample_count, sample_block);
433 }
434
435 const float abs_x = sample / samples_per_pixel - pixels_offset;
436 const float x = left + abs_x;
437
438 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
439
440 // Generate the pixel<->value lookup table for the mouse hover
441 if (show_hover_marker_)
442 process_next_sample_value(abs_x, sample_block[block_sample]);
443
444 // Create the sampling points if needed
445 if (show_sampling_points) {
446 int idx = 0; // Neutral
447
448 if (paint_thr_dots) {
449 if (thresholds.size() == 1)
450 idx = (sample_block[block_sample] >= thresholds[0]) ? 2 : 1;
451 else if (thresholds.size() == 2) {
452 if (sample_block[block_sample] > thresholds[1])
453 idx = 2; // High
454 else if (sample_block[block_sample] < thresholds[0])
455 idx = 1; // Low
456 }
457 }
458
459 sampling_points[idx].emplace_back(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
460 }
461 }
462 delete[] sample_block;
463
464 // QPainter::drawPolyline() is slow, let's paint the lines ourselves
465 for (int64_t i = 1; i < points_count; i++)
466 p.drawLine(points[i - 1], points[i]);
467
468 if (show_sampling_points) {
469 if (paint_thr_dots) {
470 p.setPen(SamplingPointColorNe);
471 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
472 p.setPen(SamplingPointColorLo);
473 p.drawRects(sampling_points[1].data(), sampling_points[1].size());
474 p.setPen(SamplingPointColorHi);
475 p.drawRects(sampling_points[2].data(), sampling_points[2].size());
476 } else {
477 p.setPen(SamplingPointColor);
478 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
479 }
480 }
481
482 delete[] points;
483}
484
485void AnalogSignal::paint_envelope(QPainter &p,
486 const shared_ptr<pv::data::AnalogSegment> &segment,
487 int y, int left, const int64_t start, const int64_t end,
488 const double pixels_offset, const double samples_per_pixel)
489{
490 using pv::data::AnalogSegment;
491
492 // Note: Envelope painting currently doesn't generate a pixel<->value lookup table
493 if (show_hover_marker_)
494 reset_pixel_values();
495
496 AnalogSegment::EnvelopeSection e;
497 segment->get_envelope_section(e, start, end, samples_per_pixel);
498
499 if (e.length < 2)
500 return;
501
502 p.setPen(QPen(Qt::NoPen));
503 p.setBrush(base_->color());
504
505 QRectF *const rects = new QRectF[e.length];
506 QRectF *rect = rects;
507
508 for (uint64_t sample = 0; sample < e.length - 1; sample++) {
509 const float x = ((e.scale * sample + e.start) /
510 samples_per_pixel - pixels_offset) + left;
511
512 const AnalogSegment::EnvelopeSample *const s = e.samples + sample;
513
514 // We overlap this sample with the next so that vertical
515 // gaps do not appear during steep rising or falling edges
516 const float b = y - max(s->max, (s + 1)->min) * scale_;
517 const float t = y - min(s->min, (s + 1)->max) * scale_;
518
519 float h = b - t;
520 if (h >= 0.0f && h <= 1.0f)
521 h = 1.0f;
522 if (h <= 0.0f && h >= -1.0f)
523 h = -1.0f;
524
525 *rect++ = QRectF(x, t, 1.0f, h);
526 }
527
528 p.drawRects(rects, e.length);
529
530 delete[] rects;
531 delete[] e.samples;
532}
533
534shared_ptr<pv::data::AnalogSegment> AnalogSignal::get_analog_segment_to_paint() const
535{
536 shared_ptr<pv::data::AnalogSegment> segment;
537
538 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
539 base_->analog_data()->analog_segments();
540
541 if (!segments.empty()) {
542 if (segment_display_mode_ == ShowLastSegmentOnly)
543 segment = segments.back();
544
545 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
546 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
547 try {
548 segment = segments.at(current_segment_);
549 } catch (out_of_range&) {
550 qDebug() << "Current analog segment out of range for signal" << base_->name() << ":" << current_segment_;
551 }
552 }
553 }
554
555 return segment;
556}
557
558float AnalogSignal::get_resolution(int scale_index)
559{
560 const float seq[] = {1.0f, 2.0f, 5.0f};
561
562 const int offset = numeric_limits<int>::max() / (2 * countof(seq));
563 const div_t d = div((int)(scale_index + countof(seq) * offset),
564 countof(seq));
565
566 return powf(10.0f, d.quot - offset) * seq[d.rem];
567}
568
569void AnalogSignal::update_scale()
570{
571 resolution_ = get_resolution(scale_index_);
572 scale_ = div_height_ / resolution_;
573}
574
575void AnalogSignal::update_logic_level_offsets()
576{
577 const int signal_margin = QFontMetrics(QApplication::font()).height() / 2;
578
579 const int ph = min(pos_vdivs_, 1) * div_height_;
580 const int nh = min(neg_vdivs_, 1) * div_height_;
581
582 high_level_offset_ = -ph + signal_margin + 0.5f;
583 low_level_offset_ = nh - signal_margin - 0.5f;
584}
585
586void AnalogSignal::update_conversion_widgets()
587{
588 SignalBase::ConversionType conv_type = base_->get_conversion_type();
589
590 // Enable or disable widgets depending on conversion state
591 conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
592 display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
593
594 conv_threshold_cb_->clear();
595
596 vector < pair<QString, int> > presets = base_->get_conversion_presets();
597
598 // Prevent the combo box from firing the "edit text changed" signal
599 // as that would involuntarily select the first entry
600 conv_threshold_cb_->blockSignals(true);
601
602 // Set available options depending on chosen conversion
603 for (pair<QString, int>& preset : presets)
604 conv_threshold_cb_->addItem(preset.first, preset.second);
605
606 map < QString, QVariant > options = base_->get_conversion_options();
607
608 if (conv_type == SignalBase::A2LConversionByThreshold) {
609 const vector<double> thresholds = base_->get_conversion_thresholds(
610 SignalBase::A2LConversionByThreshold, true);
611 conv_threshold_cb_->addItem(
612 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
613 }
614
615 if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
616 const vector<double> thresholds = base_->get_conversion_thresholds(
617 SignalBase::A2LConversionBySchmittTrigger, true);
618 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
619 QString::number(thresholds[0], 'f', 1),
620 QString::number(thresholds[1], 'f', 1)), -1);
621 }
622
623 int preset_id = base_->get_current_conversion_preset();
624 conv_threshold_cb_->setCurrentIndex(
625 conv_threshold_cb_->findData(preset_id));
626
627 conv_threshold_cb_->blockSignals(false);
628}
629
630vector<data::LogicSegment::EdgePair> AnalogSignal::get_nearest_level_changes(uint64_t sample_pos)
631{
632 assert(base_);
633 assert(owner_);
634
635 // Return if there's no logic data or we're showing only the analog trace
636 if (!base_->logic_data() || (display_type_ == DisplayAnalog))
637 return vector<data::LogicSegment::EdgePair>();
638
639 if (sample_pos == 0)
640 return vector<LogicSegment::EdgePair>();
641
642 shared_ptr<LogicSegment> segment = get_logic_segment_to_paint();
643 if (!segment || (segment->get_sample_count() == 0))
644 return vector<LogicSegment::EdgePair>();
645
646 const View *view = owner_->view();
647 assert(view);
648 const double samples_per_pixel = base_->get_samplerate() * view->scale();
649
650 vector<LogicSegment::EdgePair> edges;
651
652 segment->get_surrounding_edges(edges, sample_pos,
653 samples_per_pixel / LogicSignal::Oversampling, 0);
654
655 if (edges.empty())
656 return vector<LogicSegment::EdgePair>();
657
658 return edges;
659}
660
661void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
662{
663 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
664 base_->analog_data()->analog_segments();
665
666 if (segments.empty())
667 return;
668
669 double min = 0, max = 0;
670
671 for (const shared_ptr<pv::data::AnalogSegment>& segment : segments) {
672 pair<double, double> mm = segment->get_min_max();
673 min = std::min(min, mm.first);
674 max = std::max(max, mm.second);
675 }
676
677 if ((min == signal_min_) && (max == signal_max_) && !force_update)
678 return;
679
680 signal_min_ = min;
681 signal_max_ = max;
682
683 // If we're allowed to alter the div assignment...
684 if (!keep_divs) {
685 // Use all divs for the positive range if there are no negative values
686 if ((min == 0) && (neg_vdivs_ > 0)) {
687 pos_vdivs_ += neg_vdivs_;
688 neg_vdivs_ = 0;
689 }
690
691 // Split up the divs if there are negative values but no negative divs
692 if ((min < 0) && (neg_vdivs_ == 0)) {
693 neg_vdivs_ = pos_vdivs_ / 2;
694 pos_vdivs_ -= neg_vdivs_;
695 }
696 }
697
698 const bool showing_logic = (display_type_ == DisplayConverted) || (display_type_ == DisplayBoth);
699
700 // If there is still no positive div when we need it, add one
701 // (this can happen when pos_vdivs==neg_vdivs==0)
702 if (((max > 0) && (pos_vdivs_ == 0)) || showing_logic) {
703 pos_vdivs_ = 1;
704 owner_->extents_changed(false, true);
705 }
706
707 // If there is still no negative div when we need it, add one
708 // (this can happen when pos_vdivs was 0 or 1 when trying to split)
709 if (((min < 0) && (neg_vdivs_ == 0)) || showing_logic) {
710 neg_vdivs_ = 1;
711 owner_->extents_changed(false, true);
712 }
713
714 double min_value_per_div;
715 if ((pos_vdivs_ > 0) && (neg_vdivs_ > 0))
716 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
717 else if (pos_vdivs_ > 0)
718 min_value_per_div = max / pos_vdivs_;
719 else
720 min_value_per_div = -min / neg_vdivs_;
721
722 // Find first scale value that is bigger than the value we need
723 for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
724 if (get_resolution(i) > min_value_per_div) {
725 scale_index_ = i;
726 break;
727 }
728
729 update_scale();
730}
731
732void AnalogSignal::reset_pixel_values()
733{
734 value_at_pixel_pos_.clear();
735 current_pixel_pos_ = -1;
736 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
737}
738
739void AnalogSignal::process_next_sample_value(float x, float value)
740{
741 // Note: NAN is used to indicate the non-existance of a value at this pixel
742
743 if (std::isnan(prev_value_at_pixel_)) {
744 if (x < 0) {
745 min_value_at_pixel_ = value;
746 max_value_at_pixel_ = value;
747 prev_value_at_pixel_ = value;
748 current_pixel_pos_ = x;
749 } else
750 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
751 }
752
753 const int pixel_pos = (int)(x + 0.5);
754
755 if (pixel_pos > current_pixel_pos_) {
756 if (pixel_pos - current_pixel_pos_ == 1) {
757 if (std::isnan(prev_value_at_pixel_)) {
758 value_at_pixel_pos_.push_back(prev_value_at_pixel_);
759 } else {
760 // Average the min/max range to create one value for the previous pixel
761 const float avg = (min_value_at_pixel_ + max_value_at_pixel_) / 2;
762 value_at_pixel_pos_.push_back(avg);
763 }
764 } else {
765 // Interpolate values to create values for the intermediate pixels
766 const float start_value = prev_value_at_pixel_;
767 const float end_value = value;
768 const int steps = fabs(pixel_pos - current_pixel_pos_);
769 const double gradient = (end_value - start_value) / steps;
770 for (int i = 0; i < steps; i++) {
771 if (current_pixel_pos_ + i < 0)
772 continue;
773 value_at_pixel_pos_.push_back(start_value + i * gradient);
774 }
775 }
776
777 min_value_at_pixel_ = value;
778 max_value_at_pixel_ = value;
779 prev_value_at_pixel_ = value;
780 current_pixel_pos_ = pixel_pos;
781 } else {
782 // Another sample for the same pixel
783 if (value < min_value_at_pixel_)
784 min_value_at_pixel_ = value;
785 if (value > max_value_at_pixel_)
786 max_value_at_pixel_ = value;
787 }
788}
789
790void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
791{
792 // Add the standard options
793 Signal::populate_popup_form(parent, form);
794
795 // Add div-related settings
796 pvdiv_sb_ = new QSpinBox(parent);
797 pvdiv_sb_->setRange(0, MaximumVDivs);
798 pvdiv_sb_->setValue(pos_vdivs_);
799 pvdiv_sb_->setEnabled(!autoranging_);
800 connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
801 this, SLOT(on_pos_vdivs_changed(int)));
802 form->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
803
804 nvdiv_sb_ = new QSpinBox(parent);
805 nvdiv_sb_->setRange(0, MaximumVDivs);
806 nvdiv_sb_->setValue(neg_vdivs_);
807 nvdiv_sb_->setEnabled(!autoranging_);
808 connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
809 this, SLOT(on_neg_vdivs_changed(int)));
810 form->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
811
812 div_height_sb_ = new QSpinBox(parent);
813 div_height_sb_->setRange(20, 1000);
814 div_height_sb_->setSingleStep(5);
815 div_height_sb_->setSuffix(tr(" pixels"));
816 div_height_sb_->setValue(div_height_);
817 connect(div_height_sb_, SIGNAL(valueChanged(int)),
818 this, SLOT(on_div_height_changed(int)));
819 form->addRow(tr("Div height"), div_height_sb_);
820
821 // Add the vertical resolution
822 resolution_cb_ = new QComboBox(parent);
823 resolution_cb_->setEnabled(!autoranging_);
824
825 for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
826 const QString label = QString("%1").arg(get_resolution(i));
827 resolution_cb_->insertItem(0, label, QVariant(i));
828 }
829
830 int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
831 resolution_cb_->setCurrentIndex(cur_idx);
832
833 connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
834 this, SLOT(on_resolution_changed(int)));
835
836 QGridLayout *const vdiv_layout = new QGridLayout;
837 QLabel *const vdiv_unit = new QLabel(tr("V/div"));
838 vdiv_layout->addWidget(resolution_cb_, 0, 0);
839 vdiv_layout->addWidget(vdiv_unit, 0, 1);
840
841 form->addRow(tr("Vertical resolution"), vdiv_layout);
842
843 // Add the autoranging checkbox
844 QCheckBox* autoranging_cb = new QCheckBox();
845 autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
846
847 connect(autoranging_cb, SIGNAL(stateChanged(int)),
848 this, SLOT(on_autoranging_changed(int)));
849
850 form->addRow(tr("Autoranging"), autoranging_cb);
851
852 // Add the conversion type dropdown
853 conversion_cb_ = new QComboBox();
854
855 conversion_cb_->addItem(tr("none"),
856 SignalBase::NoConversion);
857 conversion_cb_->addItem(tr("to logic via threshold"),
858 SignalBase::A2LConversionByThreshold);
859 conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
860 SignalBase::A2LConversionBySchmittTrigger);
861
862 cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
863 conversion_cb_->setCurrentIndex(cur_idx);
864
865 form->addRow(tr("Conversion"), conversion_cb_);
866
867 connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
868 this, SLOT(on_conversion_changed(int)));
869
870 // Add the conversion threshold settings
871 conv_threshold_cb_ = new QComboBox();
872 conv_threshold_cb_->setEditable(true);
873
874 form->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
875
876 connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
877 this, SLOT(on_conv_threshold_changed(int)));
878 connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString&)),
879 this, SLOT(on_conv_threshold_changed())); // index will be -1
880
881 // Add the display type dropdown
882 display_type_cb_ = new QComboBox();
883
884 display_type_cb_->addItem(tr("analog"), DisplayAnalog);
885 display_type_cb_->addItem(tr("converted"), DisplayConverted);
886 display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
887
888 cur_idx = display_type_cb_->findData(QVariant(display_type_));
889 display_type_cb_->setCurrentIndex(cur_idx);
890
891 form->addRow(tr("Show traces for"), display_type_cb_);
892
893 connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
894 this, SLOT(on_display_type_changed(int)));
895
896 // Update the conversion widget contents and states
897 update_conversion_widgets();
898}
899
900void AnalogSignal::hover_point_changed(const QPoint &hp)
901{
902 Signal::hover_point_changed(hp);
903
904 // Note: Even though the view area begins at 0, we exclude 0 because
905 // that's also the value given when the cursor is over the header to the
906 // left of the trace paint area
907 if (hp.x() <= 0) {
908 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
909 } else {
910 if ((size_t)hp.x() < value_at_pixel_pos_.size())
911 value_at_hover_pos_ = value_at_pixel_pos_.at(hp.x());
912 else
913 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
914 }
915}
916
917void AnalogSignal::on_setting_changed(const QString &key, const QVariant &value)
918{
919 Signal::on_setting_changed(key, value);
920
921 if (key == GlobalSettings::Key_View_ShowSamplingPoints)
922 show_sampling_points_ = value.toBool();
923
924 if (key == GlobalSettings::Key_View_FillSignalHighAreas)
925 fill_high_areas_ = value.toBool();
926
927 if (key == GlobalSettings::Key_View_FillSignalHighAreaColor)
928 high_fill_color_ = QColor::fromRgba(value.value<uint32_t>());
929
930 if (key == GlobalSettings::Key_View_ShowAnalogMinorGrid)
931 show_analog_minor_grid_ = value.toBool();
932
933 if (key == GlobalSettings::Key_View_ConversionThresholdDispMode) {
934 conversion_threshold_disp_mode_ = value.toInt();
935
936 if (owner_)
937 owner_->row_item_appearance_changed(false, true);
938 }
939}
940
941void AnalogSignal::on_min_max_changed(float min, float max)
942{
943 if (autoranging_)
944 perform_autoranging(false, false);
945 else {
946 if (min < signal_min_) signal_min_ = min;
947 if (max > signal_max_) signal_max_ = max;
948 }
949}
950
951void AnalogSignal::on_pos_vdivs_changed(int vdivs)
952{
953 if (vdivs == pos_vdivs_)
954 return;
955
956 pos_vdivs_ = vdivs;
957
958 // There has to be at least one div, positive or negative
959 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
960 pos_vdivs_ = 1;
961 if (pvdiv_sb_)
962 pvdiv_sb_->setValue(pos_vdivs_);
963 }
964
965 if (autoranging_) {
966 perform_autoranging(true, true);
967
968 // It could be that a positive or negative div was added, so update
969 if (pvdiv_sb_) {
970 pvdiv_sb_->setValue(pos_vdivs_);
971 nvdiv_sb_->setValue(neg_vdivs_);
972 }
973 }
974
975 update_logic_level_offsets();
976
977 if (owner_) {
978 // Call order is important, otherwise the lazy event handler won't work
979 owner_->extents_changed(false, true);
980 owner_->row_item_appearance_changed(false, true);
981 }
982}
983
984void AnalogSignal::on_neg_vdivs_changed(int vdivs)
985{
986 if (vdivs == neg_vdivs_)
987 return;
988
989 neg_vdivs_ = vdivs;
990
991 // There has to be at least one div, positive or negative
992 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
993 pos_vdivs_ = 1;
994 if (pvdiv_sb_)
995 pvdiv_sb_->setValue(pos_vdivs_);
996 }
997
998 if (autoranging_) {
999 perform_autoranging(true, true);
1000
1001 // It could be that a positive or negative div was added, so update
1002 if (pvdiv_sb_) {
1003 pvdiv_sb_->setValue(pos_vdivs_);
1004 nvdiv_sb_->setValue(neg_vdivs_);
1005 }
1006 }
1007
1008 update_logic_level_offsets();
1009
1010 if (owner_) {
1011 // Call order is important, otherwise the lazy event handler won't work
1012 owner_->extents_changed(false, true);
1013 owner_->row_item_appearance_changed(false, true);
1014 }
1015}
1016
1017void AnalogSignal::on_div_height_changed(int height)
1018{
1019 div_height_ = height;
1020 update_logic_level_offsets();
1021 update_scale();
1022
1023 if (owner_) {
1024 // Call order is important, otherwise the lazy event handler won't work
1025 owner_->extents_changed(false, true);
1026 owner_->row_item_appearance_changed(false, true);
1027 }
1028}
1029
1030void AnalogSignal::on_resolution_changed(int index)
1031{
1032 scale_index_ = resolution_cb_->itemData(index).toInt();
1033 update_scale();
1034
1035 if (owner_)
1036 owner_->row_item_appearance_changed(false, true);
1037}
1038
1039void AnalogSignal::on_autoranging_changed(int state)
1040{
1041 autoranging_ = (state == Qt::Checked);
1042
1043 if (pvdiv_sb_)
1044 pvdiv_sb_->setEnabled(!autoranging_);
1045 if (nvdiv_sb_)
1046 nvdiv_sb_->setEnabled(!autoranging_);
1047 if (resolution_cb_)
1048 resolution_cb_->setEnabled(!autoranging_);
1049
1050 if (autoranging_)
1051 perform_autoranging(false, true);
1052
1053 if (owner_) {
1054 // Call order is important, otherwise the lazy event handler won't work
1055 owner_->extents_changed(false, true);
1056 owner_->row_item_appearance_changed(false, true);
1057 }
1058}
1059
1060void AnalogSignal::on_conversion_changed(int index)
1061{
1062 SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
1063
1064 SignalBase::ConversionType conv_type =
1065 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
1066
1067 if (conv_type != old_conv_type) {
1068 base_->set_conversion_type(conv_type);
1069 update_conversion_widgets();
1070
1071 if (conv_type == SignalBase::ConversionType::NoConversion)
1072 on_display_type_changed(DisplayType::DisplayAnalog);
1073 else
1074 on_display_type_changed(DisplayType::DisplayBoth);
1075
1076 if (owner_)
1077 owner_->row_item_appearance_changed(false, true);
1078 }
1079}
1080
1081void AnalogSignal::on_conv_threshold_changed(int index)
1082{
1083 SignalBase::ConversionType conv_type = base_->get_conversion_type();
1084
1085 // Note: index is set to -1 if the text in the combo box matches none of
1086 // the entries in the combo box
1087
1088 if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
1089 return;
1090
1091 // The combo box entry with the custom value has user_data set to -1
1092 const int user_data = conv_threshold_cb_->findText(
1093 conv_threshold_cb_->currentText());
1094
1095 const bool use_custom_thr = (index == -1) || (user_data == -1);
1096
1097 if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
1098 // Not one of the preset values, try to parse the combo box text
1099 // Note: Regex loosely based on
1100 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1101 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1102 QString re2 = "([a-zA-Z]*)"; // SI unit
1103 QRegExp regex(re1 + re2);
1104
1105 const QString text = conv_threshold_cb_->currentText();
1106 if (!regex.exactMatch(text))
1107 return; // String doesn't match the regex
1108
1109 QStringList tokens = regex.capturedTexts();
1110
1111 // For now, we simply assume that the unit is volt without modifiers
1112 const double thr = tokens.at(1).toDouble();
1113
1114 // Only restart the conversion if the threshold was updated.
1115 // We're starting a delayed conversion because the user may still be
1116 // typing and the UI would lag if we kept on restarting it immediately
1117 if (base_->set_conversion_option("threshold_value", thr))
1118 base_->start_conversion(true);
1119 }
1120
1121 if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
1122 // Not one of the preset values, try to parse the combo box text
1123 // Note: Regex loosely based on
1124 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1125 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1126 QString re2 = "([a-zA-Z]*)"; // SI unit
1127 QString re3 = "\\/"; // Forward slash, not captured
1128 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1129 QString re5 = "([a-zA-Z]*)"; // SI unit
1130 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1131
1132 const QString text = conv_threshold_cb_->currentText();
1133 if (!regex.exactMatch(text))
1134 return; // String doesn't match the regex
1135
1136 QStringList tokens = regex.capturedTexts();
1137
1138 // For now, we simply assume that the unit is volt without modifiers
1139 const double low_thr = tokens.at(1).toDouble();
1140 const double high_thr = tokens.at(3).toDouble();
1141
1142 // Only restart the conversion if one of the options was updated.
1143 // We're starting a delayed conversion because the user may still be
1144 // typing and the UI would lag if we kept on restarting it immediately
1145 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1146 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1147 if (o1 || o2)
1148 base_->start_conversion(true); // Start delayed conversion
1149 }
1150
1151 base_->set_conversion_preset((SignalBase::ConversionPreset)index);
1152
1153 // Immediately start the conversion if we're not using custom values
1154 // (i.e. we're using one of the presets)
1155 if (!use_custom_thr)
1156 base_->start_conversion();
1157}
1158
1159void AnalogSignal::on_delayed_conversion_starter()
1160{
1161 base_->start_conversion();
1162}
1163
1164void AnalogSignal::on_display_type_changed(int index)
1165{
1166 const bool prev_showing_logic = (display_type_ == DisplayConverted) || (display_type_ == DisplayBoth);
1167
1168 display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1169
1170 const bool showing_logic = (display_type_ == DisplayConverted) || (display_type_ == DisplayBoth);
1171
1172 // If we show a logic trace, make sure we have at least one div for each
1173 // polarity as that's where we paint it
1174 if (showing_logic && !prev_showing_logic) {
1175 if (pos_vdivs_ == 0)
1176 on_pos_vdivs_changed(1);
1177 if (neg_vdivs_ == 0)
1178 on_neg_vdivs_changed(1);
1179 }
1180
1181 if (owner_)
1182 owner_->row_item_appearance_changed(false, true);
1183}
1184
1185} // namespace trace
1186} // namespace views
1187} // namespace pv