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