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 value_at_hover_pos_(std::numeric_limits<float>::quiet_NaN()),
109 scale_index_(4), // 20 per div
113 display_type_(DisplayBoth),
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 std::map<QString, QVariant> AnalogSignal::save_settings() const
148 std::map<QString, QVariant> result;
150 result["pos_vdivs"] = pos_vdivs_;
151 result["neg_vdivs"] = neg_vdivs_;
152 result["scale_index"] = scale_index_;
153 result["display_type"] = display_type_;
154 result["autoranging"] = pos_vdivs_;
155 result["div_height"] = div_height_;
160 void AnalogSignal::restore_settings(std::map<QString, QVariant> settings)
162 auto entry = settings.find("pos_vdivs");
163 if (entry != settings.end())
164 pos_vdivs_ = settings["pos_vdivs"].toInt();
166 entry = settings.find("neg_vdivs");
167 if (entry != settings.end())
168 neg_vdivs_ = settings["neg_vdivs"].toInt();
170 entry = settings.find("scale_index");
171 if (entry != settings.end()) {
172 scale_index_ = settings["scale_index"].toInt();
176 entry = settings.find("display_type");
177 if (entry != settings.end())
178 display_type_ = (DisplayType)(settings["display_type"].toInt());
180 entry = settings.find("autoranging");
181 if (entry != settings.end())
182 autoranging_ = settings["autoranging"].toBool();
184 entry = settings.find("div_height");
185 if (entry != settings.end()) {
186 const int old_height = div_height_;
187 div_height_ = settings["div_height"].toInt();
189 if ((div_height_ != old_height) && owner_) {
190 // Call order is important, otherwise the lazy event handler won't work
191 owner_->extents_changed(false, true);
192 owner_->row_item_appearance_changed(false, true);
197 pair<int, int> AnalogSignal::v_extents() const
199 const int ph = pos_vdivs_ * div_height_;
200 const int nh = neg_vdivs_ * div_height_;
201 return make_pair(-ph, nh);
204 void AnalogSignal::paint_back(QPainter &p, ViewItemPaintParams &pp)
206 if (!base_->enabled())
210 conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Background;
212 const vector<double> thresholds = base_->get_conversion_thresholds();
214 // Only display thresholds if we have some and we show analog samples
215 if ((thresholds.size() > 0) && paint_thr_bg &&
216 ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth))) {
218 const int visual_y = get_visual_y();
219 const pair<int, int> extents = v_extents();
220 const int top = visual_y + extents.first;
221 const int btm = visual_y + extents.second;
223 // Draw high/neutral/low areas
224 if (thresholds.size() == 2) {
225 int thr_lo = visual_y - thresholds[0] * scale_;
226 int thr_hi = visual_y - thresholds[1] * scale_;
227 thr_lo = min(max(thr_lo, top), btm);
228 thr_hi = min(max(thr_hi, top), btm);
230 p.fillRect(QRectF(pp.left(), top, pp.width(), thr_hi - top),
231 QBrush(ThresholdColorHi));
232 p.fillRect(QRectF(pp.left(), thr_hi, pp.width(), thr_lo - thr_hi),
233 QBrush(ThresholdColorNe));
234 p.fillRect(QRectF(pp.left(), thr_lo, pp.width(), btm - thr_lo),
235 QBrush(ThresholdColorLo));
237 int thr = visual_y - thresholds[0] * scale_;
238 thr = min(max(thr, top), btm);
240 p.fillRect(QRectF(pp.left(), top, pp.width(), thr - top),
241 QBrush(ThresholdColorHi));
242 p.fillRect(QRectF(pp.left(), thr, pp.width(), btm - thr),
243 QBrush(ThresholdColorLo));
246 paint_axis(p, pp, get_visual_y());
248 Signal::paint_back(p, pp);
249 paint_axis(p, pp, get_visual_y());
253 void AnalogSignal::paint_mid(QPainter &p, ViewItemPaintParams &pp)
255 assert(base_->analog_data());
258 const int y = get_visual_y();
260 if (!base_->enabled())
263 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
264 paint_grid(p, y, pp.left(), pp.right());
266 shared_ptr<pv::data::AnalogSegment> segment = get_analog_segment_to_paint();
267 if (!segment || (segment->get_sample_count() == 0))
270 const double pixels_offset = pp.pixels_offset();
271 const double samplerate = max(1.0, segment->samplerate());
272 const pv::util::Timestamp& start_time = segment->start_time();
273 const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
274 const double samples_per_pixel = samplerate * pp.scale();
275 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
276 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
278 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
279 (int64_t)0), last_sample);
280 const int64_t end_sample = min(max((ceil(end) + 1).convert_to<int64_t>(),
281 (int64_t)0), last_sample);
283 if (samples_per_pixel < EnvelopeThreshold)
284 paint_trace(p, segment, y, pp.left(), start_sample, end_sample,
285 pixels_offset, samples_per_pixel);
287 paint_envelope(p, segment, y, pp.left(), start_sample, end_sample,
288 pixels_offset, samples_per_pixel);
291 if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
292 paint_logic_mid(p, pp);
295 void AnalogSignal::paint_fore(QPainter &p, ViewItemPaintParams &pp)
300 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
301 const int y = get_visual_y();
305 // Show the info section on the right side of the trace, including
306 // the value at the hover point when the hover marker is enabled
307 // and we have corresponding data available
308 if (show_hover_marker_ && !std::isnan(value_at_hover_pos_)) {
309 infotext = QString("[%1] %2 V/div")
310 .arg(format_value_si(value_at_hover_pos_, SIPrefix::unspecified, 2, "V", false))
313 infotext = QString("%1 V/div").arg(resolution_);
315 p.setPen(base_->color());
316 p.setFont(QApplication::font());
318 const QRectF bounding_rect = QRectF(pp.left(),
319 y + v_extents().first,
320 pp.width() - InfoTextMarginRight,
321 v_extents().second - v_extents().first - InfoTextMarginBottom);
323 p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
326 if (show_hover_marker_)
327 paint_hover_marker(p);
330 void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
332 bool was_antialiased = p.testRenderHint(QPainter::Antialiasing);
333 p.setRenderHint(QPainter::Antialiasing, false);
335 if (pos_vdivs_ > 0) {
336 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
337 for (int i = 1; i <= pos_vdivs_; i++) {
338 const float dy = i * div_height_;
339 p.drawLine(QLineF(left, y - dy, right, y - dy));
343 if ((pos_vdivs_ > 0) && show_analog_minor_grid_) {
344 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
345 for (int i = 0; i < pos_vdivs_; i++) {
346 const float dy = i * div_height_;
347 const float dy25 = dy + (0.25 * div_height_);
348 const float dy50 = dy + (0.50 * div_height_);
349 const float dy75 = dy + (0.75 * div_height_);
350 p.drawLine(QLineF(left, y - dy25, right, y - dy25));
351 p.drawLine(QLineF(left, y - dy50, right, y - dy50));
352 p.drawLine(QLineF(left, y - dy75, right, y - dy75));
356 if (neg_vdivs_ > 0) {
357 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
358 for (int i = 1; i <= neg_vdivs_; i++) {
359 const float dy = i * div_height_;
360 p.drawLine(QLineF(left, y + dy, right, y + dy));
364 if ((pos_vdivs_ > 0) && show_analog_minor_grid_) {
365 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
366 for (int i = 0; i < neg_vdivs_; i++) {
367 const float dy = i * div_height_;
368 const float dy25 = dy + (0.25 * div_height_);
369 const float dy50 = dy + (0.50 * div_height_);
370 const float dy75 = dy + (0.75 * div_height_);
371 p.drawLine(QLineF(left, y + dy25, right, y + dy25));
372 p.drawLine(QLineF(left, y + dy50, right, y + dy50));
373 p.drawLine(QLineF(left, y + dy75, right, y + dy75));
377 p.setRenderHint(QPainter::Antialiasing, was_antialiased);
380 void AnalogSignal::paint_trace(QPainter &p,
381 const shared_ptr<pv::data::AnalogSegment> &segment,
382 int y, int left, const int64_t start, const int64_t end,
383 const double pixels_offset, const double samples_per_pixel)
388 bool paint_thr_dots =
389 (base_->get_conversion_type() != data::SignalBase::NoConversion) &&
390 (conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Dots);
392 vector<double> thresholds;
394 thresholds = base_->get_conversion_thresholds();
396 // Calculate and paint the sampling points if enabled and useful
397 GlobalSettings settings;
398 const bool show_sampling_points =
399 (show_sampling_points_ || paint_thr_dots) && (samples_per_pixel < 0.25);
401 p.setPen(base_->color());
403 const int64_t points_count = end - start + 1;
405 QPointF *points = new QPointF[points_count];
406 QPointF *point = points;
408 vector<QRectF> sampling_points[3];
410 int64_t sample_count = min(points_count, TracePaintBlockSize);
411 int64_t block_sample = 0;
412 float *sample_block = new float[TracePaintBlockSize];
413 segment->get_samples(start, start + sample_count, sample_block);
415 if (show_hover_marker_)
416 reset_pixel_values();
419 for (int64_t sample = start; sample <= end; sample++, block_sample++) {
421 // Fetch next block of samples if we finished the current one
422 if (block_sample == TracePaintBlockSize) {
424 sample_count = min(points_count - sample, TracePaintBlockSize);
425 segment->get_samples(sample, sample + sample_count, sample_block);
428 const float abs_x = sample / samples_per_pixel - pixels_offset;
429 const float x = left + abs_x;
431 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
433 // Generate the pixel<->value lookup table for the mouse hover
434 if (show_hover_marker_)
435 process_next_sample_value(abs_x, sample_block[block_sample]);
437 // Create the sampling points if needed
438 if (show_sampling_points) {
439 int idx = 0; // Neutral
441 if (paint_thr_dots) {
442 if (thresholds.size() == 1)
443 idx = (sample_block[block_sample] >= thresholds[0]) ? 2 : 1;
444 else if (thresholds.size() == 2) {
445 if (sample_block[block_sample] > thresholds[1])
447 else if (sample_block[block_sample] < thresholds[0])
452 sampling_points[idx].emplace_back(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
455 delete[] sample_block;
457 // QPainter::drawPolyline() is slow, let's paint the lines ourselves
458 for (int64_t i = 1; i < points_count; i++)
459 p.drawLine(points[i - 1], points[i]);
461 if (show_sampling_points) {
462 if (paint_thr_dots) {
463 p.setPen(SamplingPointColorNe);
464 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
465 p.setPen(SamplingPointColorLo);
466 p.drawRects(sampling_points[1].data(), sampling_points[1].size());
467 p.setPen(SamplingPointColorHi);
468 p.drawRects(sampling_points[2].data(), sampling_points[2].size());
470 p.setPen(SamplingPointColor);
471 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
478 void AnalogSignal::paint_envelope(QPainter &p,
479 const shared_ptr<pv::data::AnalogSegment> &segment,
480 int y, int left, const int64_t start, const int64_t end,
481 const double pixels_offset, const double samples_per_pixel)
483 using pv::data::AnalogSegment;
485 // Note: Envelope painting currently doesn't generate a pixel<->value lookup table
486 if (show_hover_marker_)
487 reset_pixel_values();
489 AnalogSegment::EnvelopeSection e;
490 segment->get_envelope_section(e, start, end, samples_per_pixel);
495 p.setPen(QPen(Qt::NoPen));
496 p.setBrush(base_->color());
498 QRectF *const rects = new QRectF[e.length];
499 QRectF *rect = rects;
501 for (uint64_t sample = 0; sample < e.length - 1; sample++) {
502 const float x = ((e.scale * sample + e.start) /
503 samples_per_pixel - pixels_offset) + left;
505 const AnalogSegment::EnvelopeSample *const s = e.samples + sample;
507 // We overlap this sample with the next so that vertical
508 // gaps do not appear during steep rising or falling edges
509 const float b = y - max(s->max, (s + 1)->min) * scale_;
510 const float t = y - min(s->min, (s + 1)->max) * scale_;
513 if (h >= 0.0f && h <= 1.0f)
515 if (h <= 0.0f && h >= -1.0f)
518 *rect++ = QRectF(x, t, 1.0f, h);
521 p.drawRects(rects, e.length);
527 void AnalogSignal::paint_logic_mid(QPainter &p, ViewItemPaintParams &pp)
531 vector< pair<int64_t, bool> > edges;
535 const int y = get_visual_y();
537 if (!base_->enabled() || !base_->logic_data())
540 const int signal_margin =
541 QFontMetrics(QApplication::font()).height() / 2;
543 const int ph = min(pos_vdivs_, 1) * div_height_;
544 const int nh = min(neg_vdivs_, 1) * div_height_;
545 const float high_offset = y - ph + signal_margin + 0.5f;
546 const float low_offset = y + nh - signal_margin - 0.5f;
547 const float signal_height = low_offset - high_offset;
549 shared_ptr<pv::data::LogicSegment> segment = get_logic_segment_to_paint();
550 if (!segment || (segment->get_sample_count() == 0))
553 double samplerate = segment->samplerate();
555 // Show sample rate as 1Hz when it is unknown
556 if (samplerate == 0.0)
559 const double pixels_offset = pp.pixels_offset();
560 const pv::util::Timestamp& start_time = segment->start_time();
561 const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
562 const double samples_per_pixel = samplerate * pp.scale();
563 const double pixels_per_sample = 1 / samples_per_pixel;
564 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
565 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
567 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
568 (int64_t)0), last_sample);
569 const uint64_t end_sample = min(max(ceil(end).convert_to<int64_t>(),
570 (int64_t)0), last_sample);
572 segment->get_subsampled_edges(edges, start_sample, end_sample,
573 samples_per_pixel / LogicSignal::Oversampling, 0);
574 assert(edges.size() >= 2);
576 const float first_sample_x =
577 pp.left() + (edges.front().first / samples_per_pixel - pixels_offset);
578 const float last_sample_x =
579 pp.left() + (edges.back().first / samples_per_pixel - pixels_offset);
581 // Check whether we need to paint the sampling points
582 const bool show_sampling_points = show_sampling_points_ && (samples_per_pixel < 0.25);
583 vector<QRectF> sampling_points;
584 float sampling_point_x = first_sample_x;
585 int64_t sampling_point_sample = start_sample;
588 if (show_sampling_points)
589 sampling_points.reserve(end_sample - start_sample + 1);
591 vector<QRectF> high_rects;
593 bool rising_edge_seen = false;
596 const unsigned int edge_count = edges.size() - 2;
597 QLineF *const edge_lines = new QLineF[edge_count];
600 if (edges.front().second) {
601 // Beginning of trace is high
602 rising_edge_x = first_sample_x;
603 rising_edge_seen = true;
606 for (auto i = edges.cbegin() + 1; i != edges.cend() - 1; i++) {
607 // Note: multiple edges occupying a single pixel are represented by an edge
608 // with undefined logic level. This means that only the first falling edge
609 // after a rising edge corresponds to said rising edge - and vice versa. If
610 // more edges with the same logic level follow, they denote multiple edges.
612 const float x = pp.left() + ((*i).first / samples_per_pixel - pixels_offset);
613 *line++ = QLineF(x, high_offset, x, low_offset);
615 if (fill_high_areas_) {
616 // Any edge terminates a high area
617 if (rising_edge_seen) {
618 const int width = x - rising_edge_x;
620 high_rects.emplace_back(rising_edge_x, high_offset,
621 width, signal_height);
622 rising_edge_seen = false;
625 // Only rising edges start high areas
628 rising_edge_seen = true;
632 if (show_sampling_points)
633 while (sampling_point_sample < (*i).first) {
634 const float y = (*i).second ? low_offset : high_offset;
635 sampling_points.emplace_back(
636 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
637 sampling_point_sample++;
638 sampling_point_x += pixels_per_sample;
642 // Calculate the sample points from the last edge to the end of the trace
643 if (show_sampling_points)
644 while ((uint64_t)sampling_point_sample <= end_sample) {
645 // Signal changed after the last edge, so the level is inverted
646 const float y = (edges.cend() - 1)->second ? high_offset : low_offset;
647 sampling_points.emplace_back(
648 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
649 sampling_point_sample++;
650 sampling_point_x += pixels_per_sample;
653 if (fill_high_areas_) {
654 // Add last high rectangle if the signal is still high at the end of the trace
655 if (rising_edge_seen && (edges.cend() - 1)->second)
656 high_rects.emplace_back(rising_edge_x, high_offset,
657 last_sample_x - rising_edge_x, signal_height);
659 p.setPen(high_fill_color_);
660 p.setBrush(high_fill_color_);
661 p.drawRects((const QRectF*)(high_rects.data()), high_rects.size());
664 p.setPen(LogicSignal::EdgeColor);
665 p.drawLines(edge_lines, edge_count);
669 const unsigned int max_cap_line_count = edges.size();
670 QLineF *const cap_lines = new QLineF[max_cap_line_count];
672 p.setPen(LogicSignal::HighColor);
673 paint_logic_caps(p, cap_lines, edges, true, samples_per_pixel,
674 pixels_offset, pp.left(), high_offset);
675 p.setPen(LogicSignal::LowColor);
676 paint_logic_caps(p, cap_lines, edges, false, samples_per_pixel,
677 pixels_offset, pp.left(), low_offset);
681 // Paint the sampling points
682 if (show_sampling_points) {
683 p.setPen(SamplingPointColor);
684 p.drawRects(sampling_points.data(), sampling_points.size());
688 void AnalogSignal::paint_logic_caps(QPainter &p, QLineF *const lines,
689 vector< pair<int64_t, bool> > &edges, bool level,
690 double samples_per_pixel, double pixels_offset, float x_offset,
693 QLineF *line = lines;
695 for (auto i = edges.begin(); i != (edges.end() - 1); i++)
696 if ((*i).second == level) {
698 ((*i).first / samples_per_pixel -
699 pixels_offset) + x_offset, y_offset,
700 ((*(i+1)).first / samples_per_pixel -
701 pixels_offset) + x_offset, y_offset);
704 p.drawLines(lines, line - lines);
707 shared_ptr<pv::data::AnalogSegment> AnalogSignal::get_analog_segment_to_paint() const
709 shared_ptr<pv::data::AnalogSegment> segment;
711 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
712 base_->analog_data()->analog_segments();
714 if (!segments.empty()) {
715 if (segment_display_mode_ == ShowLastSegmentOnly)
716 segment = segments.back();
718 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
719 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
721 segment = segments.at(current_segment_);
722 } catch (out_of_range&) {
723 qDebug() << "Current analog segment out of range for signal" << base_->name() << ":" << current_segment_;
731 shared_ptr<pv::data::LogicSegment> AnalogSignal::get_logic_segment_to_paint() const
733 shared_ptr<pv::data::LogicSegment> segment;
735 const deque< shared_ptr<pv::data::LogicSegment> > &segments =
736 base_->logic_data()->logic_segments();
738 if (!segments.empty()) {
739 if (segment_display_mode_ == ShowLastSegmentOnly)
740 segment = segments.back();
742 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
743 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
745 segment = segments.at(current_segment_);
746 } catch (out_of_range&) {
747 qDebug() << "Current logic segment out of range for signal" << base_->name() << ":" << current_segment_;
755 float AnalogSignal::get_resolution(int scale_index)
757 const float seq[] = {1.0f, 2.0f, 5.0f};
759 const int offset = numeric_limits<int>::max() / (2 * countof(seq));
760 const div_t d = div((int)(scale_index + countof(seq) * offset),
763 return powf(10.0f, d.quot - offset) * seq[d.rem];
766 void AnalogSignal::update_scale()
768 resolution_ = get_resolution(scale_index_);
769 scale_ = div_height_ / resolution_;
772 void AnalogSignal::update_conversion_widgets()
774 SignalBase::ConversionType conv_type = base_->get_conversion_type();
776 // Enable or disable widgets depending on conversion state
777 conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
778 display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
780 conv_threshold_cb_->clear();
782 vector < pair<QString, int> > presets = base_->get_conversion_presets();
784 // Prevent the combo box from firing the "edit text changed" signal
785 // as that would involuntarily select the first entry
786 conv_threshold_cb_->blockSignals(true);
788 // Set available options depending on chosen conversion
789 for (pair<QString, int>& preset : presets)
790 conv_threshold_cb_->addItem(preset.first, preset.second);
792 map < QString, QVariant > options = base_->get_conversion_options();
794 if (conv_type == SignalBase::A2LConversionByThreshold) {
795 const vector<double> thresholds = base_->get_conversion_thresholds(
796 SignalBase::A2LConversionByThreshold, true);
797 conv_threshold_cb_->addItem(
798 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
801 if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
802 const vector<double> thresholds = base_->get_conversion_thresholds(
803 SignalBase::A2LConversionBySchmittTrigger, true);
804 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
805 QString::number(thresholds[0], 'f', 1),
806 QString::number(thresholds[1], 'f', 1)), -1);
809 int preset_id = base_->get_current_conversion_preset();
810 conv_threshold_cb_->setCurrentIndex(
811 conv_threshold_cb_->findData(preset_id));
813 conv_threshold_cb_->blockSignals(false);
816 vector<data::LogicSegment::EdgePair> AnalogSignal::get_nearest_level_changes(uint64_t sample_pos)
821 // Return if there's no logic data or we're showing only the analog trace
822 if (!base_->logic_data() || (display_type_ == DisplayAnalog))
823 return vector<data::LogicSegment::EdgePair>();
826 return vector<LogicSegment::EdgePair>();
828 shared_ptr<LogicSegment> segment = get_logic_segment_to_paint();
829 if (!segment || (segment->get_sample_count() == 0))
830 return vector<LogicSegment::EdgePair>();
832 const View *view = owner_->view();
834 const double samples_per_pixel = base_->get_samplerate() * view->scale();
836 vector<LogicSegment::EdgePair> edges;
838 segment->get_surrounding_edges(edges, sample_pos,
839 samples_per_pixel / LogicSignal::Oversampling, 0);
842 return vector<LogicSegment::EdgePair>();
847 void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
849 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
850 base_->analog_data()->analog_segments();
852 if (segments.empty())
855 double signal_min_ = 0, signal_max_ = 0;
856 double min = 0, max = 0;
858 for (const shared_ptr<pv::data::AnalogSegment>& segment : segments) {
859 pair<double, double> mm = segment->get_min_max();
860 min = std::min(min, mm.first);
861 max = std::max(max, mm.second);
864 if ((min == signal_min_) && (max == signal_max_) && !force_update)
870 // If we're allowed to alter the div assignment...
872 // Use all divs for the positive range if there are no negative values
873 if ((min == 0) && (neg_vdivs_ > 0)) {
874 pos_vdivs_ += neg_vdivs_;
878 // Split up the divs if there are negative values but no negative divs
879 if ((min < 0) && (neg_vdivs_ == 0)) {
880 neg_vdivs_ = pos_vdivs_ / 2;
881 pos_vdivs_ -= neg_vdivs_;
885 // If there is still no positive div when we need it, add one
886 // (this can happen when pos_vdivs==neg_vdivs==0)
887 if ((max > 0) && (pos_vdivs_ == 0)) {
889 owner_->extents_changed(false, true);
892 // If there is still no negative div when we need it, add one
893 // (this can happen when pos_vdivs was 0 or 1 when trying to split)
894 if ((min < 0) && (neg_vdivs_ == 0)) {
896 owner_->extents_changed(false, true);
899 double min_value_per_div;
900 if ((pos_vdivs_ > 0) && (neg_vdivs_ > 0))
901 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
902 else if (pos_vdivs_ > 0)
903 min_value_per_div = max / pos_vdivs_;
905 min_value_per_div = -min / neg_vdivs_;
907 // Find first scale value that is bigger than the value we need
908 for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
909 if (get_resolution(i) > min_value_per_div) {
917 void AnalogSignal::reset_pixel_values()
919 value_at_pixel_pos_.clear();
920 current_pixel_pos_ = -1;
921 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
924 void AnalogSignal::process_next_sample_value(float x, float value)
926 // Note: NAN is used to indicate the non-existance of a value at this pixel
928 if (std::isnan(prev_value_at_pixel_)) {
930 min_value_at_pixel_ = value;
931 max_value_at_pixel_ = value;
932 prev_value_at_pixel_ = value;
933 current_pixel_pos_ = x;
935 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
938 const int pixel_pos = (int)(x + 0.5);
940 if (pixel_pos > current_pixel_pos_) {
941 if (pixel_pos - current_pixel_pos_ == 1) {
942 if (std::isnan(prev_value_at_pixel_)) {
943 value_at_pixel_pos_.push_back(prev_value_at_pixel_);
945 // Average the min/max range to create one value for the previous pixel
946 const float avg = (min_value_at_pixel_ + max_value_at_pixel_) / 2;
947 value_at_pixel_pos_.push_back(avg);
950 // Interpolate values to create values for the intermediate pixels
951 const float start_value = prev_value_at_pixel_;
952 const float end_value = value;
953 const int steps = fabs(pixel_pos - current_pixel_pos_);
954 const double gradient = (end_value - start_value) / steps;
955 for (int i = 0; i < steps; i++) {
956 if (current_pixel_pos_ + i < 0)
958 value_at_pixel_pos_.push_back(start_value + i * gradient);
962 min_value_at_pixel_ = value;
963 max_value_at_pixel_ = value;
964 prev_value_at_pixel_ = value;
965 current_pixel_pos_ = pixel_pos;
967 // Another sample for the same pixel
968 if (value < min_value_at_pixel_)
969 min_value_at_pixel_ = value;
970 if (value > max_value_at_pixel_)
971 max_value_at_pixel_ = value;
975 void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
977 // Add the standard options
978 Signal::populate_popup_form(parent, form);
980 QFormLayout *const layout = new QFormLayout;
982 // Add div-related settings
983 pvdiv_sb_ = new QSpinBox(parent);
984 pvdiv_sb_->setRange(0, MaximumVDivs);
985 pvdiv_sb_->setValue(pos_vdivs_);
986 connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
987 this, SLOT(on_pos_vdivs_changed(int)));
988 layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
990 nvdiv_sb_ = new QSpinBox(parent);
991 nvdiv_sb_->setRange(0, MaximumVDivs);
992 nvdiv_sb_->setValue(neg_vdivs_);
993 connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
994 this, SLOT(on_neg_vdivs_changed(int)));
995 layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
997 div_height_sb_ = new QSpinBox(parent);
998 div_height_sb_->setRange(20, 1000);
999 div_height_sb_->setSingleStep(5);
1000 div_height_sb_->setSuffix(tr(" pixels"));
1001 div_height_sb_->setValue(div_height_);
1002 connect(div_height_sb_, SIGNAL(valueChanged(int)),
1003 this, SLOT(on_div_height_changed(int)));
1004 layout->addRow(tr("Div height"), div_height_sb_);
1006 // Add the vertical resolution
1007 resolution_cb_ = new QComboBox(parent);
1009 for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
1010 const QString label = QString("%1").arg(get_resolution(i));
1011 resolution_cb_->insertItem(0, label, QVariant(i));
1014 int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
1015 resolution_cb_->setCurrentIndex(cur_idx);
1017 connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
1018 this, SLOT(on_resolution_changed(int)));
1020 QGridLayout *const vdiv_layout = new QGridLayout;
1021 QLabel *const vdiv_unit = new QLabel(tr("V/div"));
1022 vdiv_layout->addWidget(resolution_cb_, 0, 0);
1023 vdiv_layout->addWidget(vdiv_unit, 0, 1);
1025 layout->addRow(tr("Vertical resolution"), vdiv_layout);
1027 // Add the autoranging checkbox
1028 QCheckBox* autoranging_cb = new QCheckBox();
1029 autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
1031 connect(autoranging_cb, SIGNAL(stateChanged(int)),
1032 this, SLOT(on_autoranging_changed(int)));
1034 layout->addRow(tr("Autoranging"), autoranging_cb);
1036 // Add the conversion type dropdown
1037 conversion_cb_ = new QComboBox();
1039 conversion_cb_->addItem(tr("none"),
1040 SignalBase::NoConversion);
1041 conversion_cb_->addItem(tr("to logic via threshold"),
1042 SignalBase::A2LConversionByThreshold);
1043 conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
1044 SignalBase::A2LConversionBySchmittTrigger);
1046 cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
1047 conversion_cb_->setCurrentIndex(cur_idx);
1049 layout->addRow(tr("Conversion"), conversion_cb_);
1051 connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
1052 this, SLOT(on_conversion_changed(int)));
1054 // Add the conversion threshold settings
1055 conv_threshold_cb_ = new QComboBox();
1056 conv_threshold_cb_->setEditable(true);
1058 layout->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
1060 connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
1061 this, SLOT(on_conv_threshold_changed(int)));
1062 connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString&)),
1063 this, SLOT(on_conv_threshold_changed())); // index will be -1
1065 // Add the display type dropdown
1066 display_type_cb_ = new QComboBox();
1068 display_type_cb_->addItem(tr("analog"), DisplayAnalog);
1069 display_type_cb_->addItem(tr("converted"), DisplayConverted);
1070 display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
1072 cur_idx = display_type_cb_->findData(QVariant(display_type_));
1073 display_type_cb_->setCurrentIndex(cur_idx);
1075 layout->addRow(tr("Show traces for"), display_type_cb_);
1077 connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
1078 this, SLOT(on_display_type_changed(int)));
1080 // Update the conversion widget contents and states
1081 update_conversion_widgets();
1083 form->addRow(layout);
1086 void AnalogSignal::hover_point_changed(const QPoint &hp)
1088 Signal::hover_point_changed(hp);
1090 // Note: Even though the view area begins at 0, we exclude 0 because
1091 // that's also the value given when the cursor is over the header to the
1092 // left of the trace paint area
1094 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1096 if ((size_t)hp.x() < value_at_pixel_pos_.size())
1097 value_at_hover_pos_ = value_at_pixel_pos_.at(hp.x());
1099 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1103 void AnalogSignal::on_setting_changed(const QString &key, const QVariant &value)
1105 Signal::on_setting_changed(key, value);
1107 if (key == GlobalSettings::Key_View_ShowSamplingPoints)
1108 show_sampling_points_ = value.toBool();
1110 if (key == GlobalSettings::Key_View_FillSignalHighAreas)
1111 fill_high_areas_ = value.toBool();
1113 if (key == GlobalSettings::Key_View_FillSignalHighAreaColor)
1114 high_fill_color_ = QColor::fromRgba(value.value<uint32_t>());
1116 if (key == GlobalSettings::Key_View_ShowAnalogMinorGrid)
1117 show_analog_minor_grid_ = value.toBool();
1119 if (key == GlobalSettings::Key_View_ConversionThresholdDispMode) {
1120 conversion_threshold_disp_mode_ = value.toInt();
1123 owner_->row_item_appearance_changed(false, true);
1127 void AnalogSignal::on_min_max_changed(float min, float max)
1133 perform_autoranging(false, false);
1136 void AnalogSignal::on_pos_vdivs_changed(int vdivs)
1138 if (vdivs == pos_vdivs_)
1143 // There has to be at least one div, positive or negative
1144 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1147 pvdiv_sb_->setValue(pos_vdivs_);
1151 perform_autoranging(true, true);
1153 // It could be that a positive or negative div was added, so update
1155 pvdiv_sb_->setValue(pos_vdivs_);
1156 nvdiv_sb_->setValue(neg_vdivs_);
1161 // Call order is important, otherwise the lazy event handler won't work
1162 owner_->extents_changed(false, true);
1163 owner_->row_item_appearance_changed(false, true);
1167 void AnalogSignal::on_neg_vdivs_changed(int vdivs)
1169 if (vdivs == neg_vdivs_)
1174 // There has to be at least one div, positive or negative
1175 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1178 pvdiv_sb_->setValue(pos_vdivs_);
1182 perform_autoranging(true, true);
1184 // It could be that a positive or negative div was added, so update
1186 pvdiv_sb_->setValue(pos_vdivs_);
1187 nvdiv_sb_->setValue(neg_vdivs_);
1192 // Call order is important, otherwise the lazy event handler won't work
1193 owner_->extents_changed(false, true);
1194 owner_->row_item_appearance_changed(false, true);
1198 void AnalogSignal::on_div_height_changed(int height)
1200 div_height_ = height;
1204 // Call order is important, otherwise the lazy event handler won't work
1205 owner_->extents_changed(false, true);
1206 owner_->row_item_appearance_changed(false, true);
1210 void AnalogSignal::on_resolution_changed(int index)
1212 scale_index_ = resolution_cb_->itemData(index).toInt();
1216 owner_->row_item_appearance_changed(false, true);
1219 void AnalogSignal::on_autoranging_changed(int state)
1221 autoranging_ = (state == Qt::Checked);
1224 perform_autoranging(false, true);
1227 // Call order is important, otherwise the lazy event handler won't work
1228 owner_->extents_changed(false, true);
1229 owner_->row_item_appearance_changed(false, true);
1233 void AnalogSignal::on_conversion_changed(int index)
1235 SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
1237 SignalBase::ConversionType conv_type =
1238 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
1240 if (conv_type != old_conv_type) {
1241 base_->set_conversion_type(conv_type);
1242 update_conversion_widgets();
1245 owner_->row_item_appearance_changed(false, true);
1249 void AnalogSignal::on_conv_threshold_changed(int index)
1251 SignalBase::ConversionType conv_type = base_->get_conversion_type();
1253 // Note: index is set to -1 if the text in the combo box matches none of
1254 // the entries in the combo box
1256 if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
1259 // The combo box entry with the custom value has user_data set to -1
1260 const int user_data = conv_threshold_cb_->findText(
1261 conv_threshold_cb_->currentText());
1263 const bool use_custom_thr = (index == -1) || (user_data == -1);
1265 if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
1266 // Not one of the preset values, try to parse the combo box text
1267 // Note: Regex loosely based on
1268 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1269 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1270 QString re2 = "([a-zA-Z]*)"; // SI unit
1271 QRegExp regex(re1 + re2);
1273 const QString text = conv_threshold_cb_->currentText();
1274 if (!regex.exactMatch(text))
1275 return; // String doesn't match the regex
1277 QStringList tokens = regex.capturedTexts();
1279 // For now, we simply assume that the unit is volt without modifiers
1280 const double thr = tokens.at(1).toDouble();
1282 // Only restart the conversion if the threshold was updated.
1283 // We're starting a delayed conversion because the user may still be
1284 // typing and the UI would lag if we kept on restarting it immediately
1285 if (base_->set_conversion_option("threshold_value", thr))
1286 base_->start_conversion(true);
1289 if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
1290 // Not one of the preset values, try to parse the combo box text
1291 // Note: Regex loosely based on
1292 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1293 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1294 QString re2 = "([a-zA-Z]*)"; // SI unit
1295 QString re3 = "\\/"; // Forward slash, not captured
1296 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1297 QString re5 = "([a-zA-Z]*)"; // SI unit
1298 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1300 const QString text = conv_threshold_cb_->currentText();
1301 if (!regex.exactMatch(text))
1302 return; // String doesn't match the regex
1304 QStringList tokens = regex.capturedTexts();
1306 // For now, we simply assume that the unit is volt without modifiers
1307 const double low_thr = tokens.at(1).toDouble();
1308 const double high_thr = tokens.at(3).toDouble();
1310 // Only restart the conversion if one of the options was updated.
1311 // We're starting a delayed conversion because the user may still be
1312 // typing and the UI would lag if we kept on restarting it immediately
1313 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1314 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1316 base_->start_conversion(true); // Start delayed conversion
1319 base_->set_conversion_preset((SignalBase::ConversionPreset)index);
1321 // Immediately start the conversion if we're not using custom values
1322 // (i.e. we're using one of the presets)
1323 if (!use_custom_thr)
1324 base_->start_conversion();
1327 void AnalogSignal::on_delayed_conversion_starter()
1329 base_->start_conversion();
1332 void AnalogSignal::on_display_type_changed(int index)
1334 display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1337 owner_->row_item_appearance_changed(false, true);
1340 } // namespace trace
1341 } // namespace views