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)));
125 conversion_threshold_disp_mode_ =
126 gs.value(GlobalSettings::Key_View_ConversionThresholdDispMode).toInt();
128 div_height_ = gs.value(GlobalSettings::Key_View_DefaultDivHeight).toInt();
130 base_->set_color(SignalColors[base_->index() % countof(SignalColors)]);
134 shared_ptr<pv::data::SignalData> AnalogSignal::data() const
136 return base_->analog_data();
139 void AnalogSignal::save_settings(QSettings &settings) const
141 settings.setValue("pos_vdivs", pos_vdivs_);
142 settings.setValue("neg_vdivs", neg_vdivs_);
143 settings.setValue("scale_index", scale_index_);
144 settings.setValue("display_type", display_type_);
145 settings.setValue("autoranging", autoranging_);
146 settings.setValue("div_height", div_height_);
149 void AnalogSignal::restore_settings(QSettings &settings)
151 if (settings.contains("pos_vdivs"))
152 pos_vdivs_ = settings.value("pos_vdivs").toInt();
154 if (settings.contains("neg_vdivs"))
155 neg_vdivs_ = settings.value("neg_vdivs").toInt();
157 if (settings.contains("scale_index")) {
158 scale_index_ = settings.value("scale_index").toInt();
162 if (settings.contains("display_type"))
163 display_type_ = (DisplayType)(settings.value("display_type").toInt());
165 if (settings.contains("autoranging"))
166 autoranging_ = settings.value("autoranging").toBool();
168 if (settings.contains("div_height")) {
169 const int old_height = div_height_;
170 div_height_ = settings.value("div_height").toInt();
172 if ((div_height_ != old_height) && owner_) {
173 // Call order is important, otherwise the lazy event handler won't work
174 owner_->extents_changed(false, true);
175 owner_->row_item_appearance_changed(false, true);
180 pair<int, int> AnalogSignal::v_extents() const
182 const int ph = pos_vdivs_ * div_height_;
183 const int nh = neg_vdivs_ * div_height_;
184 return make_pair(-ph, nh);
187 void AnalogSignal::on_setting_changed(const QString &key, const QVariant &value)
189 Signal::on_setting_changed(key, value);
191 if (key == GlobalSettings::Key_View_ConversionThresholdDispMode)
192 on_settingViewConversionThresholdDispMode_changed(value);
195 void AnalogSignal::paint_back(QPainter &p, ViewItemPaintParams &pp)
197 if (!base_->enabled())
201 conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Background;
203 const vector<double> thresholds = base_->get_conversion_thresholds();
205 // Only display thresholds if we have some and we show analog samples
206 if ((thresholds.size() > 0) && paint_thr_bg &&
207 ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth))) {
209 const int visual_y = get_visual_y();
210 const pair<int, int> extents = v_extents();
211 const int top = visual_y + extents.first;
212 const int btm = visual_y + extents.second;
214 // Draw high/neutral/low areas
215 if (thresholds.size() == 2) {
216 int thr_lo = visual_y - thresholds[0] * scale_;
217 int thr_hi = visual_y - thresholds[1] * scale_;
218 thr_lo = min(max(thr_lo, top), btm);
219 thr_hi = min(max(thr_hi, top), btm);
221 p.fillRect(QRectF(pp.left(), top, pp.width(), thr_hi - top),
222 QBrush(ThresholdColorHi));
223 p.fillRect(QRectF(pp.left(), thr_hi, pp.width(), thr_lo - thr_hi),
224 QBrush(ThresholdColorNe));
225 p.fillRect(QRectF(pp.left(), thr_lo, pp.width(), btm - thr_lo),
226 QBrush(ThresholdColorLo));
228 int thr = visual_y - thresholds[0] * scale_;
229 thr = min(max(thr, top), btm);
231 p.fillRect(QRectF(pp.left(), top, pp.width(), thr - top),
232 QBrush(ThresholdColorHi));
233 p.fillRect(QRectF(pp.left(), thr, pp.width(), btm - thr),
234 QBrush(ThresholdColorLo));
237 paint_axis(p, pp, get_visual_y());
239 Trace::paint_back(p, pp);
240 paint_axis(p, pp, get_visual_y());
244 void AnalogSignal::paint_mid(QPainter &p, ViewItemPaintParams &pp)
246 assert(base_->analog_data());
249 const int y = get_visual_y();
251 if (!base_->enabled())
254 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
255 paint_grid(p, y, pp.left(), pp.right());
257 shared_ptr<pv::data::AnalogSegment> segment = get_analog_segment_to_paint();
258 if (!segment || (segment->get_sample_count() == 0))
261 const double pixels_offset = pp.pixels_offset();
262 const double samplerate = max(1.0, segment->samplerate());
263 const pv::util::Timestamp& start_time = segment->start_time();
264 const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
265 const double samples_per_pixel = samplerate * pp.scale();
266 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
267 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
269 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
270 (int64_t)0), last_sample);
271 const int64_t end_sample = min(max((ceil(end) + 1).convert_to<int64_t>(),
272 (int64_t)0), last_sample);
274 if (samples_per_pixel < EnvelopeThreshold)
275 paint_trace(p, segment, y, pp.left(), start_sample, end_sample,
276 pixels_offset, samples_per_pixel);
278 paint_envelope(p, segment, y, pp.left(), start_sample, end_sample,
279 pixels_offset, samples_per_pixel);
282 if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
283 paint_logic_mid(p, pp);
286 void AnalogSignal::paint_fore(QPainter &p, ViewItemPaintParams &pp)
291 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
292 const int y = get_visual_y();
296 // Show the info section on the right side of the trace, including
297 // the value at the hover point when the hover marker is enabled
298 // and we have corresponding data available
299 if (show_hover_marker_ && !std::isnan(value_at_hover_pos_)) {
300 infotext = QString("[%1] %2 V/div")
301 .arg(format_value_si(value_at_hover_pos_, SIPrefix::unspecified, 0, "V", false))
304 infotext = QString("%1 V/div").arg(resolution_);
306 p.setPen(base_->color());
307 p.setFont(QApplication::font());
309 const QRectF bounding_rect = QRectF(pp.left(),
310 y + v_extents().first,
311 pp.width() - InfoTextMarginRight,
312 v_extents().second - v_extents().first - InfoTextMarginBottom);
314 p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
317 if (show_hover_marker_)
318 paint_hover_marker(p);
321 void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
323 p.setRenderHint(QPainter::Antialiasing, false);
325 GlobalSettings settings;
326 const bool show_analog_minor_grid =
327 settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
329 if (pos_vdivs_ > 0) {
330 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
331 for (int i = 1; i <= pos_vdivs_; i++) {
332 const float dy = i * div_height_;
333 p.drawLine(QLineF(left, y - dy, right, y - dy));
337 if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
338 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
339 for (int i = 0; i < pos_vdivs_; i++) {
340 const float dy = i * div_height_;
341 const float dy25 = dy + (0.25 * div_height_);
342 const float dy50 = dy + (0.50 * div_height_);
343 const float dy75 = dy + (0.75 * div_height_);
344 p.drawLine(QLineF(left, y - dy25, right, y - dy25));
345 p.drawLine(QLineF(left, y - dy50, right, y - dy50));
346 p.drawLine(QLineF(left, y - dy75, right, y - dy75));
350 if (neg_vdivs_ > 0) {
351 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
352 for (int i = 1; i <= neg_vdivs_; i++) {
353 const float dy = i * div_height_;
354 p.drawLine(QLineF(left, y + dy, right, y + dy));
358 if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
359 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
360 for (int i = 0; i < neg_vdivs_; i++) {
361 const float dy = i * div_height_;
362 const float dy25 = dy + (0.25 * div_height_);
363 const float dy50 = dy + (0.50 * div_height_);
364 const float dy75 = dy + (0.75 * div_height_);
365 p.drawLine(QLineF(left, y + dy25, right, y + dy25));
366 p.drawLine(QLineF(left, y + dy50, right, y + dy50));
367 p.drawLine(QLineF(left, y + dy75, right, y + dy75));
371 p.setRenderHint(QPainter::Antialiasing, true);
374 void AnalogSignal::paint_trace(QPainter &p,
375 const shared_ptr<pv::data::AnalogSegment> &segment,
376 int y, int left, const int64_t start, const int64_t end,
377 const double pixels_offset, const double samples_per_pixel)
382 bool paint_thr_dots =
383 (base_->get_conversion_type() != data::SignalBase::NoConversion) &&
384 (conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Dots);
386 vector<double> thresholds;
388 thresholds = base_->get_conversion_thresholds();
390 // Calculate and paint the sampling points if enabled and useful
391 GlobalSettings settings;
392 const bool show_sampling_points =
393 (settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() ||
394 paint_thr_dots) && (samples_per_pixel < 0.25);
396 p.setPen(base_->color());
398 const int64_t points_count = end - start + 1;
400 QPointF *points = new QPointF[points_count];
401 QPointF *point = points;
403 vector<QRectF> sampling_points[3];
405 int64_t sample_count = min(points_count, TracePaintBlockSize);
406 int64_t block_sample = 0;
407 float *sample_block = new float[TracePaintBlockSize];
408 segment->get_samples(start, start + sample_count, sample_block);
410 if (show_hover_marker_)
411 reset_pixel_values();
414 for (int64_t sample = start; sample <= end; sample++, block_sample++) {
416 // Fetch next block of samples if we finished the current one
417 if (block_sample == TracePaintBlockSize) {
419 sample_count = min(points_count - sample, TracePaintBlockSize);
420 segment->get_samples(sample, sample + sample_count, sample_block);
423 const float abs_x = sample / samples_per_pixel - pixels_offset;
424 const float x = left + abs_x;
426 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
428 // Generate the pixel<->value lookup table for the mouse hover
429 if (show_hover_marker_)
430 process_next_sample_value(abs_x, sample_block[block_sample]);
432 // Create the sampling points if needed
433 if (show_sampling_points) {
434 int idx = 0; // Neutral
436 if (paint_thr_dots) {
437 if (thresholds.size() == 1)
438 idx = (sample_block[block_sample] >= thresholds[0]) ? 2 : 1;
439 else if (thresholds.size() == 2) {
440 if (sample_block[block_sample] > thresholds[1])
442 else if (sample_block[block_sample] < thresholds[0])
447 sampling_points[idx].emplace_back(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
450 delete[] sample_block;
452 p.drawPolyline(points, points_count);
454 if (show_sampling_points) {
455 if (paint_thr_dots) {
456 p.setPen(SamplingPointColorNe);
457 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
458 p.setPen(SamplingPointColorLo);
459 p.drawRects(sampling_points[1].data(), sampling_points[1].size());
460 p.setPen(SamplingPointColorHi);
461 p.drawRects(sampling_points[2].data(), sampling_points[2].size());
463 p.setPen(SamplingPointColor);
464 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
471 void AnalogSignal::paint_envelope(QPainter &p,
472 const shared_ptr<pv::data::AnalogSegment> &segment,
473 int y, int left, const int64_t start, const int64_t end,
474 const double pixels_offset, const double samples_per_pixel)
476 using pv::data::AnalogSegment;
478 // Note: Envelope painting currently doesn't generate a pixel<->value lookup table
479 if (show_hover_marker_)
480 reset_pixel_values();
482 AnalogSegment::EnvelopeSection e;
483 segment->get_envelope_section(e, start, end, samples_per_pixel);
488 p.setPen(QPen(Qt::NoPen));
489 p.setBrush(base_->color());
491 QRectF *const rects = new QRectF[e.length];
492 QRectF *rect = rects;
494 for (uint64_t sample = 0; sample < e.length - 1; sample++) {
495 const float x = ((e.scale * sample + e.start) /
496 samples_per_pixel - pixels_offset) + left;
498 const AnalogSegment::EnvelopeSample *const s = e.samples + sample;
500 // We overlap this sample with the next so that vertical
501 // gaps do not appear during steep rising or falling edges
502 const float b = y - max(s->max, (s + 1)->min) * scale_;
503 const float t = y - min(s->min, (s + 1)->max) * scale_;
506 if (h >= 0.0f && h <= 1.0f)
508 if (h <= 0.0f && h >= -1.0f)
511 *rect++ = QRectF(x, t, 1.0f, h);
514 p.drawRects(rects, e.length);
520 void AnalogSignal::paint_logic_mid(QPainter &p, ViewItemPaintParams &pp)
524 vector< pair<int64_t, bool> > edges;
528 const int y = get_visual_y();
530 if (!base_->enabled() || !base_->logic_data())
533 const int signal_margin =
534 QFontMetrics(QApplication::font()).height() / 2;
536 const int ph = min(pos_vdivs_, 1) * div_height_;
537 const int nh = min(neg_vdivs_, 1) * div_height_;
538 const float high_offset = y - ph + signal_margin + 0.5f;
539 const float low_offset = y + nh - signal_margin - 0.5f;
541 shared_ptr<pv::data::LogicSegment> segment = get_logic_segment_to_paint();
542 if (!segment || (segment->get_sample_count() == 0))
545 double samplerate = segment->samplerate();
547 // Show sample rate as 1Hz when it is unknown
548 if (samplerate == 0.0)
551 const double pixels_offset = pp.pixels_offset();
552 const pv::util::Timestamp& start_time = segment->start_time();
553 const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
554 const double samples_per_pixel = samplerate * pp.scale();
555 const double pixels_per_sample = 1 / samples_per_pixel;
556 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
557 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
559 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
560 (int64_t)0), last_sample);
561 const uint64_t end_sample = min(max(ceil(end).convert_to<int64_t>(),
562 (int64_t)0), last_sample);
564 segment->get_subsampled_edges(edges, start_sample, end_sample,
565 samples_per_pixel / LogicSignal::Oversampling, 0);
566 assert(edges.size() >= 2);
568 // Check whether we need to paint the sampling points
569 GlobalSettings settings;
570 const bool show_sampling_points =
571 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() &&
572 (samples_per_pixel < 0.25);
574 vector<QRectF> sampling_points;
575 float sampling_point_x = 0.0f;
576 int64_t sampling_point_sample = start_sample;
579 if (show_sampling_points) {
580 sampling_points.reserve(end_sample - start_sample + 1);
581 sampling_point_x = (edges.cbegin()->first / samples_per_pixel - pixels_offset) + pp.left();
585 const unsigned int edge_count = edges.size() - 2;
586 QLineF *const edge_lines = new QLineF[edge_count];
589 for (auto i = edges.cbegin() + 1; i != edges.cend() - 1; i++) {
590 const float x = ((*i).first / samples_per_pixel -
591 pixels_offset) + pp.left();
592 *line++ = QLineF(x, high_offset, x, low_offset);
594 if (show_sampling_points)
595 while (sampling_point_sample < (*i).first) {
596 const float y = (*i).second ? low_offset : high_offset;
597 sampling_points.emplace_back(
598 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
599 sampling_point_sample++;
600 sampling_point_x += pixels_per_sample;
604 // Calculate the sample points from the last edge to the end of the trace
605 if (show_sampling_points)
606 while ((uint64_t)sampling_point_sample <= end_sample) {
607 // Signal changed after the last edge, so the level is inverted
608 const float y = (edges.cend() - 1)->second ? high_offset : low_offset;
609 sampling_points.emplace_back(
610 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
611 sampling_point_sample++;
612 sampling_point_x += pixels_per_sample;
615 p.setPen(LogicSignal::EdgeColor);
616 p.drawLines(edge_lines, edge_count);
620 const unsigned int max_cap_line_count = edges.size();
621 QLineF *const cap_lines = new QLineF[max_cap_line_count];
623 p.setPen(LogicSignal::HighColor);
624 paint_logic_caps(p, cap_lines, edges, true, samples_per_pixel,
625 pixels_offset, pp.left(), high_offset);
626 p.setPen(LogicSignal::LowColor);
627 paint_logic_caps(p, cap_lines, edges, false, samples_per_pixel,
628 pixels_offset, pp.left(), low_offset);
632 // Paint the sampling points
633 if (show_sampling_points) {
634 p.setPen(SamplingPointColor);
635 p.drawRects(sampling_points.data(), sampling_points.size());
639 void AnalogSignal::paint_logic_caps(QPainter &p, QLineF *const lines,
640 vector< pair<int64_t, bool> > &edges, bool level,
641 double samples_per_pixel, double pixels_offset, float x_offset,
644 QLineF *line = lines;
646 for (auto i = edges.begin(); i != (edges.end() - 1); i++)
647 if ((*i).second == level) {
649 ((*i).first / samples_per_pixel -
650 pixels_offset) + x_offset, y_offset,
651 ((*(i+1)).first / samples_per_pixel -
652 pixels_offset) + x_offset, y_offset);
655 p.drawLines(lines, line - lines);
658 shared_ptr<pv::data::AnalogSegment> AnalogSignal::get_analog_segment_to_paint() const
660 shared_ptr<pv::data::AnalogSegment> segment;
662 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
663 base_->analog_data()->analog_segments();
665 if (!segments.empty()) {
666 if (segment_display_mode_ == ShowLastSegmentOnly)
667 segment = segments.back();
669 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
670 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
672 segment = segments.at(current_segment_);
673 } catch (out_of_range&) {
674 qDebug() << "Current analog segment out of range for signal" << base_->name() << ":" << current_segment_;
682 shared_ptr<pv::data::LogicSegment> AnalogSignal::get_logic_segment_to_paint() const
684 shared_ptr<pv::data::LogicSegment> segment;
686 const deque< shared_ptr<pv::data::LogicSegment> > &segments =
687 base_->logic_data()->logic_segments();
689 if (!segments.empty()) {
690 if (segment_display_mode_ == ShowLastSegmentOnly)
691 segment = segments.back();
693 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
694 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
696 segment = segments.at(current_segment_);
697 } catch (out_of_range&) {
698 qDebug() << "Current logic segment out of range for signal" << base_->name() << ":" << current_segment_;
706 float AnalogSignal::get_resolution(int scale_index)
708 const float seq[] = {1.0f, 2.0f, 5.0f};
710 const int offset = numeric_limits<int>::max() / (2 * countof(seq));
711 const div_t d = div((int)(scale_index + countof(seq) * offset),
714 return powf(10.0f, d.quot - offset) * seq[d.rem];
717 void AnalogSignal::update_scale()
719 resolution_ = get_resolution(scale_index_);
720 scale_ = div_height_ / resolution_;
723 void AnalogSignal::update_conversion_widgets()
725 SignalBase::ConversionType conv_type = base_->get_conversion_type();
727 // Enable or disable widgets depending on conversion state
728 conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
729 display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
731 conv_threshold_cb_->clear();
733 vector < pair<QString, int> > presets = base_->get_conversion_presets();
735 // Prevent the combo box from firing the "edit text changed" signal
736 // as that would involuntarily select the first entry
737 conv_threshold_cb_->blockSignals(true);
739 // Set available options depending on chosen conversion
740 for (pair<QString, int> preset : presets)
741 conv_threshold_cb_->addItem(preset.first, preset.second);
743 map < QString, QVariant > options = base_->get_conversion_options();
745 if (conv_type == SignalBase::A2LConversionByThreshold) {
746 const vector<double> thresholds = base_->get_conversion_thresholds(
747 SignalBase::A2LConversionByThreshold, true);
748 conv_threshold_cb_->addItem(
749 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
752 if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
753 const vector<double> thresholds = base_->get_conversion_thresholds(
754 SignalBase::A2LConversionBySchmittTrigger, true);
755 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
756 QString::number(thresholds[0], 'f', 1),
757 QString::number(thresholds[1], 'f', 1)), -1);
760 int preset_id = base_->get_current_conversion_preset();
761 conv_threshold_cb_->setCurrentIndex(
762 conv_threshold_cb_->findData(preset_id));
764 conv_threshold_cb_->blockSignals(false);
767 vector<data::LogicSegment::EdgePair> AnalogSignal::get_nearest_level_changes(uint64_t sample_pos)
772 // Return if there's no logic data or we're showing only the analog trace
773 if (!base_->logic_data() || (display_type_ == DisplayAnalog))
774 return vector<data::LogicSegment::EdgePair>();
777 return vector<LogicSegment::EdgePair>();
779 shared_ptr<LogicSegment> segment = get_logic_segment_to_paint();
780 if (!segment || (segment->get_sample_count() == 0))
781 return vector<LogicSegment::EdgePair>();
783 const View *view = owner_->view();
785 const double samples_per_pixel = base_->get_samplerate() * view->scale();
787 vector<LogicSegment::EdgePair> edges;
789 segment->get_surrounding_edges(edges, sample_pos,
790 samples_per_pixel / LogicSignal::Oversampling, 0);
793 return vector<LogicSegment::EdgePair>();
798 void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
800 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
801 base_->analog_data()->analog_segments();
803 if (segments.empty())
806 static double prev_min = 0, prev_max = 0;
807 double min = 0, max = 0;
809 for (shared_ptr<pv::data::AnalogSegment> segment : segments) {
810 pair<double, double> mm = segment->get_min_max();
811 min = std::min(min, mm.first);
812 max = std::max(max, mm.second);
815 if ((min == prev_min) && (max == prev_max) && !force_update)
821 // If we're allowed to alter the div assignment...
823 // Use all divs for the positive range if there are no negative values
824 if ((min == 0) && (neg_vdivs_ > 0)) {
825 pos_vdivs_ += neg_vdivs_;
829 // Split up the divs if there are negative values but no negative divs
830 if ((min < 0) && (neg_vdivs_ == 0)) {
831 neg_vdivs_ = pos_vdivs_ / 2;
832 pos_vdivs_ -= neg_vdivs_;
836 // If there is still no positive div when we need it, add one
837 // (this can happen when pos_vdivs==neg_vdivs==0)
838 if ((max > 0) && (pos_vdivs_ == 0)) {
840 owner_->extents_changed(false, true);
843 // If there is still no negative div when we need it, add one
844 // (this can happen when pos_vdivs was 0 or 1 when trying to split)
845 if ((min < 0) && (neg_vdivs_ == 0)) {
847 owner_->extents_changed(false, true);
850 double min_value_per_div;
851 if ((pos_vdivs_ > 0) && (neg_vdivs_ > 0))
852 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
853 else if (pos_vdivs_ > 0)
854 min_value_per_div = max / pos_vdivs_;
856 min_value_per_div = -min / neg_vdivs_;
858 // Find first scale value that is bigger than the value we need
859 for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
860 if (get_resolution(i) > min_value_per_div) {
868 void AnalogSignal::reset_pixel_values()
870 value_at_pixel_pos_.clear();
871 current_pixel_pos_ = -1;
872 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
875 void AnalogSignal::process_next_sample_value(float x, float value)
877 // Note: NAN is used to indicate the non-existance of a value at this pixel
879 if (std::isnan(prev_value_at_pixel_)) {
881 min_value_at_pixel_ = value;
882 max_value_at_pixel_ = value;
883 prev_value_at_pixel_ = value;
884 current_pixel_pos_ = x;
886 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
889 const int pixel_pos = (int)(x + 0.5);
891 if (pixel_pos > current_pixel_pos_) {
892 if (pixel_pos - current_pixel_pos_ == 1) {
893 if (std::isnan(prev_value_at_pixel_)) {
894 value_at_pixel_pos_.push_back(prev_value_at_pixel_);
896 // Average the min/max range to create one value for the previous pixel
897 const float avg = (min_value_at_pixel_ + max_value_at_pixel_) / 2;
898 value_at_pixel_pos_.push_back(avg);
901 // Interpolate values to create values for the intermediate pixels
902 const float start_value = prev_value_at_pixel_;
903 const float end_value = value;
904 const int steps = fabs(pixel_pos - current_pixel_pos_);
905 const double gradient = (end_value - start_value) / steps;
906 for (int i = 0; i < steps; i++) {
907 if (current_pixel_pos_ + i < 0)
909 value_at_pixel_pos_.push_back(start_value + i * gradient);
913 min_value_at_pixel_ = value;
914 max_value_at_pixel_ = value;
915 prev_value_at_pixel_ = value;
916 current_pixel_pos_ = pixel_pos;
918 // Another sample for the same pixel
919 if (value < min_value_at_pixel_)
920 min_value_at_pixel_ = value;
921 if (value > max_value_at_pixel_)
922 max_value_at_pixel_ = value;
926 void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
928 // Add the standard options
929 Signal::populate_popup_form(parent, form);
931 QFormLayout *const layout = new QFormLayout;
933 // Add div-related settings
934 pvdiv_sb_ = new QSpinBox(parent);
935 pvdiv_sb_->setRange(0, MaximumVDivs);
936 pvdiv_sb_->setValue(pos_vdivs_);
937 connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
938 this, SLOT(on_pos_vdivs_changed(int)));
939 layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
941 nvdiv_sb_ = new QSpinBox(parent);
942 nvdiv_sb_->setRange(0, MaximumVDivs);
943 nvdiv_sb_->setValue(neg_vdivs_);
944 connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
945 this, SLOT(on_neg_vdivs_changed(int)));
946 layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
948 div_height_sb_ = new QSpinBox(parent);
949 div_height_sb_->setRange(20, 1000);
950 div_height_sb_->setSingleStep(5);
951 div_height_sb_->setSuffix(tr(" pixels"));
952 div_height_sb_->setValue(div_height_);
953 connect(div_height_sb_, SIGNAL(valueChanged(int)),
954 this, SLOT(on_div_height_changed(int)));
955 layout->addRow(tr("Div height"), div_height_sb_);
957 // Add the vertical resolution
958 resolution_cb_ = new QComboBox(parent);
960 for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
961 const QString label = QString("%1").arg(get_resolution(i));
962 resolution_cb_->insertItem(0, label, QVariant(i));
965 int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
966 resolution_cb_->setCurrentIndex(cur_idx);
968 connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
969 this, SLOT(on_resolution_changed(int)));
971 QGridLayout *const vdiv_layout = new QGridLayout;
972 QLabel *const vdiv_unit = new QLabel(tr("V/div"));
973 vdiv_layout->addWidget(resolution_cb_, 0, 0);
974 vdiv_layout->addWidget(vdiv_unit, 0, 1);
976 layout->addRow(tr("Vertical resolution"), vdiv_layout);
978 // Add the autoranging checkbox
979 QCheckBox* autoranging_cb = new QCheckBox();
980 autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
982 connect(autoranging_cb, SIGNAL(stateChanged(int)),
983 this, SLOT(on_autoranging_changed(int)));
985 layout->addRow(tr("Autoranging"), autoranging_cb);
987 // Add the conversion type dropdown
988 conversion_cb_ = new QComboBox();
990 conversion_cb_->addItem(tr("none"),
991 SignalBase::NoConversion);
992 conversion_cb_->addItem(tr("to logic via threshold"),
993 SignalBase::A2LConversionByThreshold);
994 conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
995 SignalBase::A2LConversionBySchmittTrigger);
997 cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
998 conversion_cb_->setCurrentIndex(cur_idx);
1000 layout->addRow(tr("Conversion"), conversion_cb_);
1002 connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
1003 this, SLOT(on_conversion_changed(int)));
1005 // Add the conversion threshold settings
1006 conv_threshold_cb_ = new QComboBox();
1007 conv_threshold_cb_->setEditable(true);
1009 layout->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
1011 connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
1012 this, SLOT(on_conv_threshold_changed(int)));
1013 connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString&)),
1014 this, SLOT(on_conv_threshold_changed())); // index will be -1
1016 // Add the display type dropdown
1017 display_type_cb_ = new QComboBox();
1019 display_type_cb_->addItem(tr("analog"), DisplayAnalog);
1020 display_type_cb_->addItem(tr("converted"), DisplayConverted);
1021 display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
1023 cur_idx = display_type_cb_->findData(QVariant(display_type_));
1024 display_type_cb_->setCurrentIndex(cur_idx);
1026 layout->addRow(tr("Show traces for"), display_type_cb_);
1028 connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
1029 this, SLOT(on_display_type_changed(int)));
1031 // Update the conversion widget contents and states
1032 update_conversion_widgets();
1034 form->addRow(layout);
1037 void AnalogSignal::hover_point_changed(const QPoint &hp)
1039 Signal::hover_point_changed(hp);
1041 // Note: Even though the view area begins at 0, we exclude 0 because
1042 // that's also the value given when the cursor is over the header to the
1043 // left of the trace paint area
1045 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1048 value_at_hover_pos_ = value_at_pixel_pos_.at(hp.x());
1049 } catch (out_of_range&) {
1050 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1055 void AnalogSignal::on_min_max_changed(float min, float max)
1061 perform_autoranging(false, false);
1064 void AnalogSignal::on_pos_vdivs_changed(int vdivs)
1066 if (vdivs == pos_vdivs_)
1071 // There has to be at least one div, positive or negative
1072 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1075 pvdiv_sb_->setValue(pos_vdivs_);
1079 perform_autoranging(true, true);
1081 // It could be that a positive or negative div was added, so update
1083 pvdiv_sb_->setValue(pos_vdivs_);
1084 nvdiv_sb_->setValue(neg_vdivs_);
1089 // Call order is important, otherwise the lazy event handler won't work
1090 owner_->extents_changed(false, true);
1091 owner_->row_item_appearance_changed(false, true);
1095 void AnalogSignal::on_neg_vdivs_changed(int vdivs)
1097 if (vdivs == neg_vdivs_)
1102 // There has to be at least one div, positive or negative
1103 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1106 pvdiv_sb_->setValue(pos_vdivs_);
1110 perform_autoranging(true, true);
1112 // It could be that a positive or negative div was added, so update
1114 pvdiv_sb_->setValue(pos_vdivs_);
1115 nvdiv_sb_->setValue(neg_vdivs_);
1120 // Call order is important, otherwise the lazy event handler won't work
1121 owner_->extents_changed(false, true);
1122 owner_->row_item_appearance_changed(false, true);
1126 void AnalogSignal::on_div_height_changed(int height)
1128 div_height_ = height;
1132 // Call order is important, otherwise the lazy event handler won't work
1133 owner_->extents_changed(false, true);
1134 owner_->row_item_appearance_changed(false, true);
1138 void AnalogSignal::on_resolution_changed(int index)
1140 scale_index_ = resolution_cb_->itemData(index).toInt();
1144 owner_->row_item_appearance_changed(false, true);
1147 void AnalogSignal::on_autoranging_changed(int state)
1149 autoranging_ = (state == Qt::Checked);
1152 perform_autoranging(false, true);
1155 // Call order is important, otherwise the lazy event handler won't work
1156 owner_->extents_changed(false, true);
1157 owner_->row_item_appearance_changed(false, true);
1161 void AnalogSignal::on_conversion_changed(int index)
1163 SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
1165 SignalBase::ConversionType conv_type =
1166 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
1168 if (conv_type != old_conv_type) {
1169 base_->set_conversion_type(conv_type);
1170 update_conversion_widgets();
1173 owner_->row_item_appearance_changed(false, true);
1177 void AnalogSignal::on_conv_threshold_changed(int index)
1179 SignalBase::ConversionType conv_type = base_->get_conversion_type();
1181 // Note: index is set to -1 if the text in the combo box matches none of
1182 // the entries in the combo box
1184 if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
1187 // The combo box entry with the custom value has user_data set to -1
1188 const int user_data = conv_threshold_cb_->findText(
1189 conv_threshold_cb_->currentText());
1191 const bool use_custom_thr = (index == -1) || (user_data == -1);
1193 if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
1194 // Not one of the preset values, try to parse the combo box text
1195 // Note: Regex loosely based on
1196 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1197 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1198 QString re2 = "([a-zA-Z]*)"; // SI unit
1199 QRegExp regex(re1 + re2);
1201 const QString text = conv_threshold_cb_->currentText();
1202 if (!regex.exactMatch(text))
1203 return; // String doesn't match the regex
1205 QStringList tokens = regex.capturedTexts();
1207 // For now, we simply assume that the unit is volt without modifiers
1208 const double thr = tokens.at(1).toDouble();
1210 // Only restart the conversion if the threshold was updated.
1211 // We're starting a delayed conversion because the user may still be
1212 // typing and the UI would lag if we kept on restarting it immediately
1213 if (base_->set_conversion_option("threshold_value", thr))
1214 base_->start_conversion(true);
1217 if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
1218 // Not one of the preset values, try to parse the combo box text
1219 // Note: Regex loosely based on
1220 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1221 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1222 QString re2 = "([a-zA-Z]*)"; // SI unit
1223 QString re3 = "\\/"; // Forward slash, not captured
1224 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1225 QString re5 = "([a-zA-Z]*)"; // SI unit
1226 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1228 const QString text = conv_threshold_cb_->currentText();
1229 if (!regex.exactMatch(text))
1230 return; // String doesn't match the regex
1232 QStringList tokens = regex.capturedTexts();
1234 // For now, we simply assume that the unit is volt without modifiers
1235 const double low_thr = tokens.at(1).toDouble();
1236 const double high_thr = tokens.at(3).toDouble();
1238 // Only restart the conversion if one of the options was updated.
1239 // We're starting a delayed conversion because the user may still be
1240 // typing and the UI would lag if we kept on restarting it immediately
1241 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1242 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1244 base_->start_conversion(true); // Start delayed conversion
1247 base_->set_conversion_preset((SignalBase::ConversionPreset)index);
1249 // Immediately start the conversion if we're not using custom values
1250 // (i.e. we're using one of the presets)
1251 if (!use_custom_thr)
1252 base_->start_conversion();
1255 void AnalogSignal::on_delayed_conversion_starter()
1257 base_->start_conversion();
1260 void AnalogSignal::on_display_type_changed(int index)
1262 display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1265 owner_->row_item_appearance_changed(false, true);
1268 void AnalogSignal::on_settingViewConversionThresholdDispMode_changed(const QVariant new_value)
1270 conversion_threshold_disp_mode_ = new_value.toInt();
1273 owner_->row_item_appearance_changed(false, true);
1276 } // namespace trace
1277 } // namespace views