2 * This file is part of the PulseView project.
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
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.
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.
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/>.
28 #include <QApplication>
32 #include <QFormLayout>
33 #include <QGridLayout>
37 #include "analogsignal.hpp"
38 #include "logicsignal.hpp"
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"
49 #include <libsigrokcxx/libsigrokcxx.hpp>
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.
59 using std::numeric_limits;
60 using std::out_of_range;
62 using std::shared_ptr;
65 using pv::data::LogicSegment;
66 using pv::data::SignalBase;
67 using pv::util::SIPrefix;
73 const QColor AnalogSignal::SignalColors[4] = {
74 QColor(0xC4, 0xA0, 0x00), // Yellow
75 QColor(0x87, 0x20, 0x7A), // Magenta
76 QColor(0x20, 0x4A, 0x87), // Blue
77 QColor(0x4E, 0x9A, 0x06) // Green
80 const QPen AnalogSignal::AxisPen(QColor(0, 0, 0, 30 * 256 / 100), 2);
81 const QColor AnalogSignal::GridMajorColor = QColor(0, 0, 0, 40 * 256 / 100);
82 const QColor AnalogSignal::GridMinorColor = QColor(0, 0, 0, 20 * 256 / 100);
84 const QColor AnalogSignal::SamplingPointColor(0x77, 0x77, 0x77);
85 const QColor AnalogSignal::SamplingPointColorLo = QColor(200, 0, 0, 80 * 256 / 100);
86 const QColor AnalogSignal::SamplingPointColorNe = QColor(0, 0, 0, 80 * 256 / 100);
87 const QColor AnalogSignal::SamplingPointColorHi = QColor(0, 200, 0, 80 * 256 / 100);
89 const QColor AnalogSignal::ThresholdColor = QColor(0, 0, 0, 30 * 256 / 100);
90 const QColor AnalogSignal::ThresholdColorLo = QColor(255, 0, 0, 8 * 256 / 100);
91 const QColor AnalogSignal::ThresholdColorNe = QColor(0, 0, 0, 10 * 256 / 100);
92 const QColor AnalogSignal::ThresholdColorHi = QColor(0, 255, 0, 8 * 256 / 100);
94 const int64_t AnalogSignal::TracePaintBlockSize = 1024 * 1024; // 4 MiB (due to float)
95 const float AnalogSignal::EnvelopeThreshold = 64.0f;
97 const int AnalogSignal::MaximumVDivs = 10;
98 const int AnalogSignal::MinScaleIndex = -6;
99 const int AnalogSignal::MaxScaleIndex = 7;
101 const int AnalogSignal::InfoTextMarginRight = 20;
102 const int AnalogSignal::InfoTextMarginBottom = 5;
104 AnalogSignal::AnalogSignal(
105 pv::Session &session,
106 shared_ptr<data::SignalBase> base) :
107 Signal(session, base),
108 scale_index_(4), // 20 per div
112 display_type_(DisplayBoth),
114 value_at_hover_pos_(std::numeric_limits<float>::quiet_NaN())
118 pv::data::Analog* analog_data =
119 dynamic_cast<pv::data::Analog*>(data().get());
121 connect(analog_data, SIGNAL(min_max_changed(float, float)),
122 this, SLOT(on_min_max_changed(float, float)));
124 GlobalSettings settings;
125 show_sampling_points_ =
126 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool();
128 settings.value(GlobalSettings::Key_View_FillSignalHighAreas).toBool();
129 high_fill_color_ = QColor::fromRgba(settings.value(
130 GlobalSettings::Key_View_FillSignalHighAreaColor).value<uint32_t>());
131 show_analog_minor_grid_ =
132 settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
133 conversion_threshold_disp_mode_ =
134 settings.value(GlobalSettings::Key_View_ConversionThresholdDispMode).toInt();
135 div_height_ = settings.value(GlobalSettings::Key_View_DefaultDivHeight).toInt();
137 base_->set_color(SignalColors[base_->index() % countof(SignalColors)]);
141 shared_ptr<pv::data::SignalData> AnalogSignal::data() const
143 return base_->analog_data();
146 void AnalogSignal::save_settings(QSettings &settings) const
148 settings.setValue("pos_vdivs", pos_vdivs_);
149 settings.setValue("neg_vdivs", neg_vdivs_);
150 settings.setValue("scale_index", scale_index_);
151 settings.setValue("display_type", display_type_);
152 settings.setValue("autoranging", autoranging_);
153 settings.setValue("div_height", div_height_);
156 void AnalogSignal::restore_settings(QSettings &settings)
158 if (settings.contains("pos_vdivs"))
159 pos_vdivs_ = settings.value("pos_vdivs").toInt();
161 if (settings.contains("neg_vdivs"))
162 neg_vdivs_ = settings.value("neg_vdivs").toInt();
164 if (settings.contains("scale_index")) {
165 scale_index_ = settings.value("scale_index").toInt();
169 if (settings.contains("display_type"))
170 display_type_ = (DisplayType)(settings.value("display_type").toInt());
172 if (settings.contains("autoranging"))
173 autoranging_ = settings.value("autoranging").toBool();
175 if (settings.contains("div_height")) {
176 const int old_height = div_height_;
177 div_height_ = settings.value("div_height").toInt();
179 if ((div_height_ != old_height) && owner_) {
180 // Call order is important, otherwise the lazy event handler won't work
181 owner_->extents_changed(false, true);
182 owner_->row_item_appearance_changed(false, true);
187 pair<int, int> AnalogSignal::v_extents() const
189 const int ph = pos_vdivs_ * div_height_;
190 const int nh = neg_vdivs_ * div_height_;
191 return make_pair(-ph, nh);
194 void AnalogSignal::paint_back(QPainter &p, ViewItemPaintParams &pp)
196 if (!base_->enabled())
200 conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Background;
202 const vector<double> thresholds = base_->get_conversion_thresholds();
204 // Only display thresholds if we have some and we show analog samples
205 if ((thresholds.size() > 0) && paint_thr_bg &&
206 ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth))) {
208 const int visual_y = get_visual_y();
209 const pair<int, int> extents = v_extents();
210 const int top = visual_y + extents.first;
211 const int btm = visual_y + extents.second;
213 // Draw high/neutral/low areas
214 if (thresholds.size() == 2) {
215 int thr_lo = visual_y - thresholds[0] * scale_;
216 int thr_hi = visual_y - thresholds[1] * scale_;
217 thr_lo = min(max(thr_lo, top), btm);
218 thr_hi = min(max(thr_hi, top), btm);
220 p.fillRect(QRectF(pp.left(), top, pp.width(), thr_hi - top),
221 QBrush(ThresholdColorHi));
222 p.fillRect(QRectF(pp.left(), thr_hi, pp.width(), thr_lo - thr_hi),
223 QBrush(ThresholdColorNe));
224 p.fillRect(QRectF(pp.left(), thr_lo, pp.width(), btm - thr_lo),
225 QBrush(ThresholdColorLo));
227 int thr = visual_y - thresholds[0] * scale_;
228 thr = min(max(thr, top), btm);
230 p.fillRect(QRectF(pp.left(), top, pp.width(), thr - top),
231 QBrush(ThresholdColorHi));
232 p.fillRect(QRectF(pp.left(), thr, pp.width(), btm - thr),
233 QBrush(ThresholdColorLo));
236 paint_axis(p, pp, get_visual_y());
238 Signal::paint_back(p, pp);
239 paint_axis(p, pp, get_visual_y());
243 void AnalogSignal::paint_mid(QPainter &p, ViewItemPaintParams &pp)
245 assert(base_->analog_data());
248 const int y = get_visual_y();
250 if (!base_->enabled())
253 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
254 paint_grid(p, y, pp.left(), pp.right());
256 shared_ptr<pv::data::AnalogSegment> segment = get_analog_segment_to_paint();
257 if (!segment || (segment->get_sample_count() == 0))
260 const double pixels_offset = pp.pixels_offset();
261 const double samplerate = max(1.0, segment->samplerate());
262 const pv::util::Timestamp& start_time = segment->start_time();
263 const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
264 const double samples_per_pixel = samplerate * pp.scale();
265 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
266 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
268 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
269 (int64_t)0), last_sample);
270 const int64_t end_sample = min(max((ceil(end) + 1).convert_to<int64_t>(),
271 (int64_t)0), last_sample);
273 if (samples_per_pixel < EnvelopeThreshold)
274 paint_trace(p, segment, y, pp.left(), start_sample, end_sample,
275 pixels_offset, samples_per_pixel);
277 paint_envelope(p, segment, y, pp.left(), start_sample, end_sample,
278 pixels_offset, samples_per_pixel);
281 if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
282 paint_logic_mid(p, pp);
285 void AnalogSignal::paint_fore(QPainter &p, ViewItemPaintParams &pp)
290 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
291 const int y = get_visual_y();
295 // Show the info section on the right side of the trace, including
296 // the value at the hover point when the hover marker is enabled
297 // and we have corresponding data available
298 if (show_hover_marker_ && !std::isnan(value_at_hover_pos_)) {
299 infotext = QString("[%1] %2 V/div")
300 .arg(format_value_si(value_at_hover_pos_, SIPrefix::unspecified, 2, "V", false))
303 infotext = QString("%1 V/div").arg(resolution_);
305 p.setPen(base_->color());
306 p.setFont(QApplication::font());
308 const QRectF bounding_rect = QRectF(pp.left(),
309 y + v_extents().first,
310 pp.width() - InfoTextMarginRight,
311 v_extents().second - v_extents().first - InfoTextMarginBottom);
313 p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
316 if (show_hover_marker_)
317 paint_hover_marker(p);
320 void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
322 bool was_antialiased = p.testRenderHint(QPainter::Antialiasing);
323 p.setRenderHint(QPainter::Antialiasing, false);
325 if (pos_vdivs_ > 0) {
326 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
327 for (int i = 1; i <= pos_vdivs_; i++) {
328 const float dy = i * div_height_;
329 p.drawLine(QLineF(left, y - dy, right, y - dy));
333 if ((pos_vdivs_ > 0) && show_analog_minor_grid_) {
334 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
335 for (int i = 0; i < pos_vdivs_; i++) {
336 const float dy = i * div_height_;
337 const float dy25 = dy + (0.25 * div_height_);
338 const float dy50 = dy + (0.50 * div_height_);
339 const float dy75 = dy + (0.75 * div_height_);
340 p.drawLine(QLineF(left, y - dy25, right, y - dy25));
341 p.drawLine(QLineF(left, y - dy50, right, y - dy50));
342 p.drawLine(QLineF(left, y - dy75, right, y - dy75));
346 if (neg_vdivs_ > 0) {
347 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
348 for (int i = 1; i <= neg_vdivs_; i++) {
349 const float dy = i * div_height_;
350 p.drawLine(QLineF(left, y + dy, right, y + dy));
354 if ((pos_vdivs_ > 0) && show_analog_minor_grid_) {
355 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
356 for (int i = 0; i < neg_vdivs_; i++) {
357 const float dy = i * div_height_;
358 const float dy25 = dy + (0.25 * div_height_);
359 const float dy50 = dy + (0.50 * div_height_);
360 const float dy75 = dy + (0.75 * div_height_);
361 p.drawLine(QLineF(left, y + dy25, right, y + dy25));
362 p.drawLine(QLineF(left, y + dy50, right, y + dy50));
363 p.drawLine(QLineF(left, y + dy75, right, y + dy75));
367 p.setRenderHint(QPainter::Antialiasing, was_antialiased);
370 void AnalogSignal::paint_trace(QPainter &p,
371 const shared_ptr<pv::data::AnalogSegment> &segment,
372 int y, int left, const int64_t start, const int64_t end,
373 const double pixels_offset, const double samples_per_pixel)
378 bool paint_thr_dots =
379 (base_->get_conversion_type() != data::SignalBase::NoConversion) &&
380 (conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Dots);
382 vector<double> thresholds;
384 thresholds = base_->get_conversion_thresholds();
386 // Calculate and paint the sampling points if enabled and useful
387 GlobalSettings settings;
388 const bool show_sampling_points =
389 (show_sampling_points_ || paint_thr_dots) && (samples_per_pixel < 0.25);
391 p.setPen(base_->color());
393 const int64_t points_count = end - start + 1;
395 QPointF *points = new QPointF[points_count];
396 QPointF *point = points;
398 vector<QRectF> sampling_points[3];
400 int64_t sample_count = min(points_count, TracePaintBlockSize);
401 int64_t block_sample = 0;
402 float *sample_block = new float[TracePaintBlockSize];
403 segment->get_samples(start, start + sample_count, sample_block);
405 if (show_hover_marker_)
406 reset_pixel_values();
409 for (int64_t sample = start; sample <= end; sample++, block_sample++) {
411 // Fetch next block of samples if we finished the current one
412 if (block_sample == TracePaintBlockSize) {
414 sample_count = min(points_count - sample, TracePaintBlockSize);
415 segment->get_samples(sample, sample + sample_count, sample_block);
418 const float abs_x = sample / samples_per_pixel - pixels_offset;
419 const float x = left + abs_x;
421 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
423 // Generate the pixel<->value lookup table for the mouse hover
424 if (show_hover_marker_)
425 process_next_sample_value(abs_x, sample_block[block_sample]);
427 // Create the sampling points if needed
428 if (show_sampling_points) {
429 int idx = 0; // Neutral
431 if (paint_thr_dots) {
432 if (thresholds.size() == 1)
433 idx = (sample_block[block_sample] >= thresholds[0]) ? 2 : 1;
434 else if (thresholds.size() == 2) {
435 if (sample_block[block_sample] > thresholds[1])
437 else if (sample_block[block_sample] < thresholds[0])
442 sampling_points[idx].emplace_back(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
445 delete[] sample_block;
447 // QPainter::drawPolyline() is slow, let's paint the lines ourselves
448 for (int64_t i = 1; i < points_count; i++)
449 p.drawLine(points[i - 1], points[i]);
451 if (show_sampling_points) {
452 if (paint_thr_dots) {
453 p.setPen(SamplingPointColorNe);
454 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
455 p.setPen(SamplingPointColorLo);
456 p.drawRects(sampling_points[1].data(), sampling_points[1].size());
457 p.setPen(SamplingPointColorHi);
458 p.drawRects(sampling_points[2].data(), sampling_points[2].size());
460 p.setPen(SamplingPointColor);
461 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
468 void AnalogSignal::paint_envelope(QPainter &p,
469 const shared_ptr<pv::data::AnalogSegment> &segment,
470 int y, int left, const int64_t start, const int64_t end,
471 const double pixels_offset, const double samples_per_pixel)
473 using pv::data::AnalogSegment;
475 // Note: Envelope painting currently doesn't generate a pixel<->value lookup table
476 if (show_hover_marker_)
477 reset_pixel_values();
479 AnalogSegment::EnvelopeSection e;
480 segment->get_envelope_section(e, start, end, samples_per_pixel);
485 p.setPen(QPen(Qt::NoPen));
486 p.setBrush(base_->color());
488 QRectF *const rects = new QRectF[e.length];
489 QRectF *rect = rects;
491 for (uint64_t sample = 0; sample < e.length - 1; sample++) {
492 const float x = ((e.scale * sample + e.start) /
493 samples_per_pixel - pixels_offset) + left;
495 const AnalogSegment::EnvelopeSample *const s = e.samples + sample;
497 // We overlap this sample with the next so that vertical
498 // gaps do not appear during steep rising or falling edges
499 const float b = y - max(s->max, (s + 1)->min) * scale_;
500 const float t = y - min(s->min, (s + 1)->max) * scale_;
503 if (h >= 0.0f && h <= 1.0f)
505 if (h <= 0.0f && h >= -1.0f)
508 *rect++ = QRectF(x, t, 1.0f, h);
511 p.drawRects(rects, e.length);
517 void AnalogSignal::paint_logic_mid(QPainter &p, ViewItemPaintParams &pp)
521 vector< pair<int64_t, bool> > edges;
525 const int y = get_visual_y();
527 if (!base_->enabled() || !base_->logic_data())
530 const int signal_margin =
531 QFontMetrics(QApplication::font()).height() / 2;
533 const int ph = min(pos_vdivs_, 1) * div_height_;
534 const int nh = min(neg_vdivs_, 1) * div_height_;
535 const float high_offset = y - ph + signal_margin + 0.5f;
536 const float low_offset = y + nh - signal_margin - 0.5f;
537 const float signal_height = low_offset - high_offset;
539 shared_ptr<pv::data::LogicSegment> segment = get_logic_segment_to_paint();
540 if (!segment || (segment->get_sample_count() == 0))
543 double samplerate = segment->samplerate();
545 // Show sample rate as 1Hz when it is unknown
546 if (samplerate == 0.0)
549 const double pixels_offset = pp.pixels_offset();
550 const pv::util::Timestamp& start_time = segment->start_time();
551 const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
552 const double samples_per_pixel = samplerate * pp.scale();
553 const double pixels_per_sample = 1 / samples_per_pixel;
554 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
555 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
557 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
558 (int64_t)0), last_sample);
559 const uint64_t end_sample = min(max(ceil(end).convert_to<int64_t>(),
560 (int64_t)0), last_sample);
562 segment->get_subsampled_edges(edges, start_sample, end_sample,
563 samples_per_pixel / LogicSignal::Oversampling, 0);
564 assert(edges.size() >= 2);
566 const float first_sample_x =
567 pp.left() + (edges.front().first / samples_per_pixel - pixels_offset);
568 const float last_sample_x =
569 pp.left() + (edges.back().first / samples_per_pixel - pixels_offset);
571 // Check whether we need to paint the sampling points
572 const bool show_sampling_points = show_sampling_points_ && (samples_per_pixel < 0.25);
573 vector<QRectF> sampling_points;
574 float sampling_point_x = first_sample_x;
575 int64_t sampling_point_sample = start_sample;
578 if (show_sampling_points)
579 sampling_points.reserve(end_sample - start_sample + 1);
581 vector<QRectF> high_rects;
583 bool rising_edge_seen = false;
586 const unsigned int edge_count = edges.size() - 2;
587 QLineF *const edge_lines = new QLineF[edge_count];
590 if (edges.front().second) {
591 // Beginning of trace is high
592 rising_edge_x = first_sample_x;
593 rising_edge_seen = true;
596 for (auto i = edges.cbegin() + 1; i != edges.cend() - 1; i++) {
597 // Note: multiple edges occupying a single pixel are represented by an edge
598 // with undefined logic level. This means that only the first falling edge
599 // after a rising edge corresponds to said rising edge - and vice versa. If
600 // more edges with the same logic level follow, they denote multiple edges.
602 const float x = pp.left() + ((*i).first / samples_per_pixel - pixels_offset);
603 *line++ = QLineF(x, high_offset, x, low_offset);
605 if (fill_high_areas_) {
606 // Any edge terminates a high area
607 if (rising_edge_seen) {
608 const int width = x - rising_edge_x;
610 high_rects.emplace_back(rising_edge_x, high_offset,
611 width, signal_height);
612 rising_edge_seen = false;
615 // Only rising edges start high areas
618 rising_edge_seen = true;
622 if (show_sampling_points)
623 while (sampling_point_sample < (*i).first) {
624 const float y = (*i).second ? low_offset : high_offset;
625 sampling_points.emplace_back(
626 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
627 sampling_point_sample++;
628 sampling_point_x += pixels_per_sample;
632 // Calculate the sample points from the last edge to the end of the trace
633 if (show_sampling_points)
634 while ((uint64_t)sampling_point_sample <= end_sample) {
635 // Signal changed after the last edge, so the level is inverted
636 const float y = (edges.cend() - 1)->second ? high_offset : low_offset;
637 sampling_points.emplace_back(
638 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
639 sampling_point_sample++;
640 sampling_point_x += pixels_per_sample;
643 if (fill_high_areas_) {
644 // Add last high rectangle if the signal is still high at the end of the trace
645 if (rising_edge_seen && (edges.cend() - 1)->second)
646 high_rects.emplace_back(rising_edge_x, high_offset,
647 last_sample_x - rising_edge_x, signal_height);
649 p.setPen(high_fill_color_);
650 p.setBrush(high_fill_color_);
651 p.drawRects((const QRectF*)(high_rects.data()), high_rects.size());
654 p.setPen(LogicSignal::EdgeColor);
655 p.drawLines(edge_lines, edge_count);
659 const unsigned int max_cap_line_count = edges.size();
660 QLineF *const cap_lines = new QLineF[max_cap_line_count];
662 p.setPen(LogicSignal::HighColor);
663 paint_logic_caps(p, cap_lines, edges, true, samples_per_pixel,
664 pixels_offset, pp.left(), high_offset);
665 p.setPen(LogicSignal::LowColor);
666 paint_logic_caps(p, cap_lines, edges, false, samples_per_pixel,
667 pixels_offset, pp.left(), low_offset);
671 // Paint the sampling points
672 if (show_sampling_points) {
673 p.setPen(SamplingPointColor);
674 p.drawRects(sampling_points.data(), sampling_points.size());
678 void AnalogSignal::paint_logic_caps(QPainter &p, QLineF *const lines,
679 vector< pair<int64_t, bool> > &edges, bool level,
680 double samples_per_pixel, double pixels_offset, float x_offset,
683 QLineF *line = lines;
685 for (auto i = edges.begin(); i != (edges.end() - 1); i++)
686 if ((*i).second == level) {
688 ((*i).first / samples_per_pixel -
689 pixels_offset) + x_offset, y_offset,
690 ((*(i+1)).first / samples_per_pixel -
691 pixels_offset) + x_offset, y_offset);
694 p.drawLines(lines, line - lines);
697 shared_ptr<pv::data::AnalogSegment> AnalogSignal::get_analog_segment_to_paint() const
699 shared_ptr<pv::data::AnalogSegment> segment;
701 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
702 base_->analog_data()->analog_segments();
704 if (!segments.empty()) {
705 if (segment_display_mode_ == ShowLastSegmentOnly)
706 segment = segments.back();
708 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
709 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
711 segment = segments.at(current_segment_);
712 } catch (out_of_range&) {
713 qDebug() << "Current analog segment out of range for signal" << base_->name() << ":" << current_segment_;
721 shared_ptr<pv::data::LogicSegment> AnalogSignal::get_logic_segment_to_paint() const
723 shared_ptr<pv::data::LogicSegment> segment;
725 const deque< shared_ptr<pv::data::LogicSegment> > &segments =
726 base_->logic_data()->logic_segments();
728 if (!segments.empty()) {
729 if (segment_display_mode_ == ShowLastSegmentOnly)
730 segment = segments.back();
732 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
733 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
735 segment = segments.at(current_segment_);
736 } catch (out_of_range&) {
737 qDebug() << "Current logic segment out of range for signal" << base_->name() << ":" << current_segment_;
745 float AnalogSignal::get_resolution(int scale_index)
747 const float seq[] = {1.0f, 2.0f, 5.0f};
749 const int offset = numeric_limits<int>::max() / (2 * countof(seq));
750 const div_t d = div((int)(scale_index + countof(seq) * offset),
753 return powf(10.0f, d.quot - offset) * seq[d.rem];
756 void AnalogSignal::update_scale()
758 resolution_ = get_resolution(scale_index_);
759 scale_ = div_height_ / resolution_;
762 void AnalogSignal::update_conversion_widgets()
764 SignalBase::ConversionType conv_type = base_->get_conversion_type();
766 // Enable or disable widgets depending on conversion state
767 conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
768 display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
770 conv_threshold_cb_->clear();
772 vector < pair<QString, int> > presets = base_->get_conversion_presets();
774 // Prevent the combo box from firing the "edit text changed" signal
775 // as that would involuntarily select the first entry
776 conv_threshold_cb_->blockSignals(true);
778 // Set available options depending on chosen conversion
779 for (pair<QString, int>& preset : presets)
780 conv_threshold_cb_->addItem(preset.first, preset.second);
782 map < QString, QVariant > options = base_->get_conversion_options();
784 if (conv_type == SignalBase::A2LConversionByThreshold) {
785 const vector<double> thresholds = base_->get_conversion_thresholds(
786 SignalBase::A2LConversionByThreshold, true);
787 conv_threshold_cb_->addItem(
788 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
791 if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
792 const vector<double> thresholds = base_->get_conversion_thresholds(
793 SignalBase::A2LConversionBySchmittTrigger, true);
794 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
795 QString::number(thresholds[0], 'f', 1),
796 QString::number(thresholds[1], 'f', 1)), -1);
799 int preset_id = base_->get_current_conversion_preset();
800 conv_threshold_cb_->setCurrentIndex(
801 conv_threshold_cb_->findData(preset_id));
803 conv_threshold_cb_->blockSignals(false);
806 vector<data::LogicSegment::EdgePair> AnalogSignal::get_nearest_level_changes(uint64_t sample_pos)
811 // Return if there's no logic data or we're showing only the analog trace
812 if (!base_->logic_data() || (display_type_ == DisplayAnalog))
813 return vector<data::LogicSegment::EdgePair>();
816 return vector<LogicSegment::EdgePair>();
818 shared_ptr<LogicSegment> segment = get_logic_segment_to_paint();
819 if (!segment || (segment->get_sample_count() == 0))
820 return vector<LogicSegment::EdgePair>();
822 const View *view = owner_->view();
824 const double samples_per_pixel = base_->get_samplerate() * view->scale();
826 vector<LogicSegment::EdgePair> edges;
828 segment->get_surrounding_edges(edges, sample_pos,
829 samples_per_pixel / LogicSignal::Oversampling, 0);
832 return vector<LogicSegment::EdgePair>();
837 void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
839 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
840 base_->analog_data()->analog_segments();
842 if (segments.empty())
845 static double prev_min = 0, prev_max = 0;
846 double min = 0, max = 0;
848 for (const shared_ptr<pv::data::AnalogSegment>& segment : segments) {
849 pair<double, double> mm = segment->get_min_max();
850 min = std::min(min, mm.first);
851 max = std::max(max, mm.second);
854 if ((min == prev_min) && (max == prev_max) && !force_update)
860 // If we're allowed to alter the div assignment...
862 // Use all divs for the positive range if there are no negative values
863 if ((min == 0) && (neg_vdivs_ > 0)) {
864 pos_vdivs_ += neg_vdivs_;
868 // Split up the divs if there are negative values but no negative divs
869 if ((min < 0) && (neg_vdivs_ == 0)) {
870 neg_vdivs_ = pos_vdivs_ / 2;
871 pos_vdivs_ -= neg_vdivs_;
875 // If there is still no positive div when we need it, add one
876 // (this can happen when pos_vdivs==neg_vdivs==0)
877 if ((max > 0) && (pos_vdivs_ == 0)) {
879 owner_->extents_changed(false, true);
882 // If there is still no negative div when we need it, add one
883 // (this can happen when pos_vdivs was 0 or 1 when trying to split)
884 if ((min < 0) && (neg_vdivs_ == 0)) {
886 owner_->extents_changed(false, true);
889 double min_value_per_div;
890 if ((pos_vdivs_ > 0) && (neg_vdivs_ > 0))
891 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
892 else if (pos_vdivs_ > 0)
893 min_value_per_div = max / pos_vdivs_;
895 min_value_per_div = -min / neg_vdivs_;
897 // Find first scale value that is bigger than the value we need
898 for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
899 if (get_resolution(i) > min_value_per_div) {
907 void AnalogSignal::reset_pixel_values()
909 value_at_pixel_pos_.clear();
910 current_pixel_pos_ = -1;
911 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
914 void AnalogSignal::process_next_sample_value(float x, float value)
916 // Note: NAN is used to indicate the non-existance of a value at this pixel
918 if (std::isnan(prev_value_at_pixel_)) {
920 min_value_at_pixel_ = value;
921 max_value_at_pixel_ = value;
922 prev_value_at_pixel_ = value;
923 current_pixel_pos_ = x;
925 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
928 const int pixel_pos = (int)(x + 0.5);
930 if (pixel_pos > current_pixel_pos_) {
931 if (pixel_pos - current_pixel_pos_ == 1) {
932 if (std::isnan(prev_value_at_pixel_)) {
933 value_at_pixel_pos_.push_back(prev_value_at_pixel_);
935 // Average the min/max range to create one value for the previous pixel
936 const float avg = (min_value_at_pixel_ + max_value_at_pixel_) / 2;
937 value_at_pixel_pos_.push_back(avg);
940 // Interpolate values to create values for the intermediate pixels
941 const float start_value = prev_value_at_pixel_;
942 const float end_value = value;
943 const int steps = fabs(pixel_pos - current_pixel_pos_);
944 const double gradient = (end_value - start_value) / steps;
945 for (int i = 0; i < steps; i++) {
946 if (current_pixel_pos_ + i < 0)
948 value_at_pixel_pos_.push_back(start_value + i * gradient);
952 min_value_at_pixel_ = value;
953 max_value_at_pixel_ = value;
954 prev_value_at_pixel_ = value;
955 current_pixel_pos_ = pixel_pos;
957 // Another sample for the same pixel
958 if (value < min_value_at_pixel_)
959 min_value_at_pixel_ = value;
960 if (value > max_value_at_pixel_)
961 max_value_at_pixel_ = value;
965 void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
967 // Add the standard options
968 Signal::populate_popup_form(parent, form);
970 QFormLayout *const layout = new QFormLayout;
972 // Add div-related settings
973 pvdiv_sb_ = new QSpinBox(parent);
974 pvdiv_sb_->setRange(0, MaximumVDivs);
975 pvdiv_sb_->setValue(pos_vdivs_);
976 connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
977 this, SLOT(on_pos_vdivs_changed(int)));
978 layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
980 nvdiv_sb_ = new QSpinBox(parent);
981 nvdiv_sb_->setRange(0, MaximumVDivs);
982 nvdiv_sb_->setValue(neg_vdivs_);
983 connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
984 this, SLOT(on_neg_vdivs_changed(int)));
985 layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
987 div_height_sb_ = new QSpinBox(parent);
988 div_height_sb_->setRange(20, 1000);
989 div_height_sb_->setSingleStep(5);
990 div_height_sb_->setSuffix(tr(" pixels"));
991 div_height_sb_->setValue(div_height_);
992 connect(div_height_sb_, SIGNAL(valueChanged(int)),
993 this, SLOT(on_div_height_changed(int)));
994 layout->addRow(tr("Div height"), div_height_sb_);
996 // Add the vertical resolution
997 resolution_cb_ = new QComboBox(parent);
999 for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
1000 const QString label = QString("%1").arg(get_resolution(i));
1001 resolution_cb_->insertItem(0, label, QVariant(i));
1004 int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
1005 resolution_cb_->setCurrentIndex(cur_idx);
1007 connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
1008 this, SLOT(on_resolution_changed(int)));
1010 QGridLayout *const vdiv_layout = new QGridLayout;
1011 QLabel *const vdiv_unit = new QLabel(tr("V/div"));
1012 vdiv_layout->addWidget(resolution_cb_, 0, 0);
1013 vdiv_layout->addWidget(vdiv_unit, 0, 1);
1015 layout->addRow(tr("Vertical resolution"), vdiv_layout);
1017 // Add the autoranging checkbox
1018 QCheckBox* autoranging_cb = new QCheckBox();
1019 autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
1021 connect(autoranging_cb, SIGNAL(stateChanged(int)),
1022 this, SLOT(on_autoranging_changed(int)));
1024 layout->addRow(tr("Autoranging"), autoranging_cb);
1026 // Add the conversion type dropdown
1027 conversion_cb_ = new QComboBox();
1029 conversion_cb_->addItem(tr("none"),
1030 SignalBase::NoConversion);
1031 conversion_cb_->addItem(tr("to logic via threshold"),
1032 SignalBase::A2LConversionByThreshold);
1033 conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
1034 SignalBase::A2LConversionBySchmittTrigger);
1036 cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
1037 conversion_cb_->setCurrentIndex(cur_idx);
1039 layout->addRow(tr("Conversion"), conversion_cb_);
1041 connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
1042 this, SLOT(on_conversion_changed(int)));
1044 // Add the conversion threshold settings
1045 conv_threshold_cb_ = new QComboBox();
1046 conv_threshold_cb_->setEditable(true);
1048 layout->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
1050 connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
1051 this, SLOT(on_conv_threshold_changed(int)));
1052 connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString&)),
1053 this, SLOT(on_conv_threshold_changed())); // index will be -1
1055 // Add the display type dropdown
1056 display_type_cb_ = new QComboBox();
1058 display_type_cb_->addItem(tr("analog"), DisplayAnalog);
1059 display_type_cb_->addItem(tr("converted"), DisplayConverted);
1060 display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
1062 cur_idx = display_type_cb_->findData(QVariant(display_type_));
1063 display_type_cb_->setCurrentIndex(cur_idx);
1065 layout->addRow(tr("Show traces for"), display_type_cb_);
1067 connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
1068 this, SLOT(on_display_type_changed(int)));
1070 // Update the conversion widget contents and states
1071 update_conversion_widgets();
1073 form->addRow(layout);
1076 void AnalogSignal::hover_point_changed(const QPoint &hp)
1078 Signal::hover_point_changed(hp);
1080 // Note: Even though the view area begins at 0, we exclude 0 because
1081 // that's also the value given when the cursor is over the header to the
1082 // left of the trace paint area
1084 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1087 value_at_hover_pos_ = value_at_pixel_pos_.at(hp.x());
1088 } catch (out_of_range&) {
1089 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1094 void AnalogSignal::on_setting_changed(const QString &key, const QVariant &value)
1096 Signal::on_setting_changed(key, value);
1098 if (key == GlobalSettings::Key_View_ShowSamplingPoints)
1099 show_sampling_points_ = value.toBool();
1101 if (key == GlobalSettings::Key_View_FillSignalHighAreas)
1102 fill_high_areas_ = value.toBool();
1104 if (key == GlobalSettings::Key_View_FillSignalHighAreaColor)
1105 high_fill_color_ = QColor::fromRgba(value.value<uint32_t>());
1107 if (key == GlobalSettings::Key_View_ShowAnalogMinorGrid)
1108 show_analog_minor_grid_ = value.toBool();
1110 if (key == GlobalSettings::Key_View_ConversionThresholdDispMode) {
1111 conversion_threshold_disp_mode_ = value.toInt();
1114 owner_->row_item_appearance_changed(false, true);
1118 void AnalogSignal::on_min_max_changed(float min, float max)
1124 perform_autoranging(false, false);
1127 void AnalogSignal::on_pos_vdivs_changed(int vdivs)
1129 if (vdivs == pos_vdivs_)
1134 // There has to be at least one div, positive or negative
1135 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1138 pvdiv_sb_->setValue(pos_vdivs_);
1142 perform_autoranging(true, true);
1144 // It could be that a positive or negative div was added, so update
1146 pvdiv_sb_->setValue(pos_vdivs_);
1147 nvdiv_sb_->setValue(neg_vdivs_);
1152 // Call order is important, otherwise the lazy event handler won't work
1153 owner_->extents_changed(false, true);
1154 owner_->row_item_appearance_changed(false, true);
1158 void AnalogSignal::on_neg_vdivs_changed(int vdivs)
1160 if (vdivs == neg_vdivs_)
1165 // There has to be at least one div, positive or negative
1166 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1169 pvdiv_sb_->setValue(pos_vdivs_);
1173 perform_autoranging(true, true);
1175 // It could be that a positive or negative div was added, so update
1177 pvdiv_sb_->setValue(pos_vdivs_);
1178 nvdiv_sb_->setValue(neg_vdivs_);
1183 // Call order is important, otherwise the lazy event handler won't work
1184 owner_->extents_changed(false, true);
1185 owner_->row_item_appearance_changed(false, true);
1189 void AnalogSignal::on_div_height_changed(int height)
1191 div_height_ = height;
1195 // Call order is important, otherwise the lazy event handler won't work
1196 owner_->extents_changed(false, true);
1197 owner_->row_item_appearance_changed(false, true);
1201 void AnalogSignal::on_resolution_changed(int index)
1203 scale_index_ = resolution_cb_->itemData(index).toInt();
1207 owner_->row_item_appearance_changed(false, true);
1210 void AnalogSignal::on_autoranging_changed(int state)
1212 autoranging_ = (state == Qt::Checked);
1215 perform_autoranging(false, true);
1218 // Call order is important, otherwise the lazy event handler won't work
1219 owner_->extents_changed(false, true);
1220 owner_->row_item_appearance_changed(false, true);
1224 void AnalogSignal::on_conversion_changed(int index)
1226 SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
1228 SignalBase::ConversionType conv_type =
1229 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
1231 if (conv_type != old_conv_type) {
1232 base_->set_conversion_type(conv_type);
1233 update_conversion_widgets();
1236 owner_->row_item_appearance_changed(false, true);
1240 void AnalogSignal::on_conv_threshold_changed(int index)
1242 SignalBase::ConversionType conv_type = base_->get_conversion_type();
1244 // Note: index is set to -1 if the text in the combo box matches none of
1245 // the entries in the combo box
1247 if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
1250 // The combo box entry with the custom value has user_data set to -1
1251 const int user_data = conv_threshold_cb_->findText(
1252 conv_threshold_cb_->currentText());
1254 const bool use_custom_thr = (index == -1) || (user_data == -1);
1256 if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
1257 // Not one of the preset values, try to parse the combo box text
1258 // Note: Regex loosely based on
1259 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1260 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1261 QString re2 = "([a-zA-Z]*)"; // SI unit
1262 QRegExp regex(re1 + re2);
1264 const QString text = conv_threshold_cb_->currentText();
1265 if (!regex.exactMatch(text))
1266 return; // String doesn't match the regex
1268 QStringList tokens = regex.capturedTexts();
1270 // For now, we simply assume that the unit is volt without modifiers
1271 const double thr = tokens.at(1).toDouble();
1273 // Only restart the conversion if the threshold was updated.
1274 // We're starting a delayed conversion because the user may still be
1275 // typing and the UI would lag if we kept on restarting it immediately
1276 if (base_->set_conversion_option("threshold_value", thr))
1277 base_->start_conversion(true);
1280 if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
1281 // Not one of the preset values, try to parse the combo box text
1282 // Note: Regex loosely based on
1283 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1284 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1285 QString re2 = "([a-zA-Z]*)"; // SI unit
1286 QString re3 = "\\/"; // Forward slash, not captured
1287 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1288 QString re5 = "([a-zA-Z]*)"; // SI unit
1289 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1291 const QString text = conv_threshold_cb_->currentText();
1292 if (!regex.exactMatch(text))
1293 return; // String doesn't match the regex
1295 QStringList tokens = regex.capturedTexts();
1297 // For now, we simply assume that the unit is volt without modifiers
1298 const double low_thr = tokens.at(1).toDouble();
1299 const double high_thr = tokens.at(3).toDouble();
1301 // Only restart the conversion if one of the options was updated.
1302 // We're starting a delayed conversion because the user may still be
1303 // typing and the UI would lag if we kept on restarting it immediately
1304 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1305 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1307 base_->start_conversion(true); // Start delayed conversion
1310 base_->set_conversion_preset((SignalBase::ConversionPreset)index);
1312 // Immediately start the conversion if we're not using custom values
1313 // (i.e. we're using one of the presets)
1314 if (!use_custom_thr)
1315 base_->start_conversion();
1318 void AnalogSignal::on_delayed_conversion_starter()
1320 base_->start_conversion();
1323 void AnalogSignal::on_display_type_changed(int index)
1325 display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1328 owner_->row_item_appearance_changed(false, true);
1331 } // namespace trace
1332 } // namespace views