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>
58 using std::numeric_limits;
59 using std::out_of_range;
61 using std::shared_ptr;
64 using pv::data::SignalBase;
65 using pv::util::SIPrefix;
71 const QColor AnalogSignal::SignalColors[4] = {
72 QColor(0xC4, 0xA0, 0x00), // Yellow
73 QColor(0x87, 0x20, 0x7A), // Magenta
74 QColor(0x20, 0x4A, 0x87), // Blue
75 QColor(0x4E, 0x9A, 0x06) // Green
78 const QPen AnalogSignal::AxisPen(QColor(0, 0, 0, 30 * 256 / 100), 2);
79 const QColor AnalogSignal::GridMajorColor = QColor(0, 0, 0, 40 * 256 / 100);
80 const QColor AnalogSignal::GridMinorColor = QColor(0, 0, 0, 20 * 256 / 100);
82 const QColor AnalogSignal::SamplingPointColor(0x77, 0x77, 0x77);
83 const QColor AnalogSignal::SamplingPointColorLo = QColor(200, 0, 0, 80 * 256 / 100);
84 const QColor AnalogSignal::SamplingPointColorNe = QColor(0, 0, 0, 80 * 256 / 100);
85 const QColor AnalogSignal::SamplingPointColorHi = QColor(0, 200, 0, 80 * 256 / 100);
87 const QColor AnalogSignal::ThresholdColor = QColor(0, 0, 0, 30 * 256 / 100);
88 const QColor AnalogSignal::ThresholdColorLo = QColor(255, 0, 0, 8 * 256 / 100);
89 const QColor AnalogSignal::ThresholdColorNe = QColor(0, 0, 0, 10 * 256 / 100);
90 const QColor AnalogSignal::ThresholdColorHi = QColor(0, 255, 0, 8 * 256 / 100);
92 const int64_t AnalogSignal::TracePaintBlockSize = 1024 * 1024; // 4 MiB (due to float)
93 const float AnalogSignal::EnvelopeThreshold = 64.0f;
95 const int AnalogSignal::MaximumVDivs = 10;
96 const int AnalogSignal::MinScaleIndex = -6;
97 const int AnalogSignal::MaxScaleIndex = 7;
99 const int AnalogSignal::InfoTextMarginRight = 20;
100 const int AnalogSignal::InfoTextMarginBottom = 5;
102 AnalogSignal::AnalogSignal(
103 pv::Session &session,
104 shared_ptr<data::SignalBase> base) :
105 Signal(session, base),
106 scale_index_(4), // 20 per div
107 scale_index_drag_offset_(0),
111 display_type_(DisplayBoth),
116 pv::data::Analog* analog_data =
117 dynamic_cast<pv::data::Analog*>(data().get());
119 connect(analog_data, SIGNAL(min_max_changed(float, float)),
120 this, SLOT(on_min_max_changed(float, float)));
123 conversion_threshold_disp_mode_ =
124 gs.value(GlobalSettings::Key_View_ConversionThresholdDispMode).toInt();
126 div_height_ = gs.value(GlobalSettings::Key_View_DefaultDivHeight).toInt();
128 base_->set_color(SignalColors[base_->index() % countof(SignalColors)]);
132 shared_ptr<pv::data::SignalData> AnalogSignal::data() const
134 return base_->analog_data();
137 void AnalogSignal::save_settings(QSettings &settings) const
139 settings.setValue("pos_vdivs", pos_vdivs_);
140 settings.setValue("neg_vdivs", neg_vdivs_);
141 settings.setValue("scale_index", scale_index_);
142 settings.setValue("display_type", display_type_);
143 settings.setValue("autoranging", autoranging_);
144 settings.setValue("div_height", div_height_);
147 void AnalogSignal::restore_settings(QSettings &settings)
149 if (settings.contains("pos_vdivs"))
150 pos_vdivs_ = settings.value("pos_vdivs").toInt();
152 if (settings.contains("neg_vdivs"))
153 neg_vdivs_ = settings.value("neg_vdivs").toInt();
155 if (settings.contains("scale_index")) {
156 scale_index_ = settings.value("scale_index").toInt();
160 if (settings.contains("display_type"))
161 display_type_ = (DisplayType)(settings.value("display_type").toInt());
163 if (settings.contains("autoranging"))
164 autoranging_ = settings.value("autoranging").toBool();
166 if (settings.contains("div_height")) {
167 const int old_height = div_height_;
168 div_height_ = settings.value("div_height").toInt();
170 if ((div_height_ != old_height) && owner_) {
171 // Call order is important, otherwise the lazy event handler won't work
172 owner_->extents_changed(false, true);
173 owner_->row_item_appearance_changed(false, true);
178 pair<int, int> AnalogSignal::v_extents() const
180 const int ph = pos_vdivs_ * div_height_;
181 const int nh = neg_vdivs_ * div_height_;
182 return make_pair(-ph, nh);
185 int AnalogSignal::scale_handle_offset() const
187 const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
189 return ((scale_index_drag_offset_ - scale_index_) * h / 4) - h / 2;
192 void AnalogSignal::scale_handle_dragged(int offset)
194 const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
196 scale_index_ = scale_index_drag_offset_ - (offset + h / 2) / (h / 4);
201 void AnalogSignal::scale_handle_drag_release()
203 scale_index_drag_offset_ = scale_index_;
207 void AnalogSignal::on_setting_changed(const QString &key, const QVariant &value)
209 Signal::on_setting_changed(key, value);
211 if (key == GlobalSettings::Key_View_ConversionThresholdDispMode)
212 on_settingViewConversionThresholdDispMode_changed(value);
215 void AnalogSignal::paint_back(QPainter &p, ViewItemPaintParams &pp)
217 if (!base_->enabled())
221 conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Background;
223 const vector<double> thresholds = base_->get_conversion_thresholds();
225 // Only display thresholds if we have some and we show analog samples
226 if ((thresholds.size() > 0) && paint_thr_bg &&
227 ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth))) {
229 const int visual_y = get_visual_y();
230 const pair<int, int> extents = v_extents();
231 const int top = visual_y + extents.first;
232 const int btm = visual_y + extents.second;
234 // Draw high/neutral/low areas
235 if (thresholds.size() == 2) {
236 int thr_lo = visual_y - thresholds[0] * scale_;
237 int thr_hi = visual_y - thresholds[1] * scale_;
238 thr_lo = min(max(thr_lo, top), btm);
239 thr_hi = min(max(thr_hi, top), btm);
241 p.fillRect(QRectF(pp.left(), top, pp.width(), thr_hi - top),
242 QBrush(ThresholdColorHi));
243 p.fillRect(QRectF(pp.left(), thr_hi, pp.width(), thr_lo - thr_hi),
244 QBrush(ThresholdColorNe));
245 p.fillRect(QRectF(pp.left(), thr_lo, pp.width(), btm - thr_lo),
246 QBrush(ThresholdColorLo));
248 int thr = visual_y - thresholds[0] * scale_;
249 thr = min(max(thr, top), btm);
251 p.fillRect(QRectF(pp.left(), top, pp.width(), thr - top),
252 QBrush(ThresholdColorHi));
253 p.fillRect(QRectF(pp.left(), thr, pp.width(), btm - thr),
254 QBrush(ThresholdColorLo));
257 paint_axis(p, pp, get_visual_y());
259 Trace::paint_back(p, pp);
260 paint_axis(p, pp, get_visual_y());
264 void AnalogSignal::paint_mid(QPainter &p, ViewItemPaintParams &pp)
266 assert(base_->analog_data());
269 const int y = get_visual_y();
271 if (!base_->enabled())
274 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
275 paint_grid(p, y, pp.left(), pp.right());
277 shared_ptr<pv::data::AnalogSegment> segment = get_analog_segment_to_paint();
278 if (!segment || (segment->get_sample_count() == 0))
281 const double pixels_offset = pp.pixels_offset();
282 const double samplerate = max(1.0, segment->samplerate());
283 const pv::util::Timestamp& start_time = segment->start_time();
284 const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
285 const double samples_per_pixel = samplerate * pp.scale();
286 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
287 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
289 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
290 (int64_t)0), last_sample);
291 const int64_t end_sample = min(max((ceil(end) + 1).convert_to<int64_t>(),
292 (int64_t)0), last_sample);
294 if (samples_per_pixel < EnvelopeThreshold)
295 paint_trace(p, segment, y, pp.left(), start_sample, end_sample,
296 pixels_offset, samples_per_pixel);
298 paint_envelope(p, segment, y, pp.left(), start_sample, end_sample,
299 pixels_offset, samples_per_pixel);
302 if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
303 paint_logic_mid(p, pp);
306 void AnalogSignal::paint_fore(QPainter &p, ViewItemPaintParams &pp)
311 if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
312 const int y = get_visual_y();
316 // Show the info section on the right side of the trace, including
317 // the value at the hover point when the hover marker is enabled
318 // and we have corresponding data available
319 if (show_hover_marker_ && !isnan(value_at_hover_pos_)) {
320 infotext = QString("[%1] %2 V/div")
321 .arg(format_value_si(value_at_hover_pos_, SIPrefix::unspecified, 0, "V", false))
324 infotext = QString("%1 V/div").arg(resolution_);
326 p.setPen(base_->color());
327 p.setFont(QApplication::font());
329 const QRectF bounding_rect = QRectF(pp.left(),
330 y + v_extents().first,
331 pp.width() - InfoTextMarginRight,
332 v_extents().second - v_extents().first - InfoTextMarginBottom);
334 p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
337 if (show_hover_marker_)
338 paint_hover_marker(p);
341 void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
343 p.setRenderHint(QPainter::Antialiasing, false);
345 GlobalSettings settings;
346 const bool show_analog_minor_grid =
347 settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
349 if (pos_vdivs_ > 0) {
350 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
351 for (int i = 1; i <= pos_vdivs_; i++) {
352 const float dy = i * div_height_;
353 p.drawLine(QLineF(left, y - dy, right, y - dy));
357 if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
358 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
359 for (int i = 0; i < pos_vdivs_; i++) {
360 const float dy = i * div_height_;
361 const float dy25 = dy + (0.25 * div_height_);
362 const float dy50 = dy + (0.50 * div_height_);
363 const float dy75 = dy + (0.75 * div_height_);
364 p.drawLine(QLineF(left, y - dy25, right, y - dy25));
365 p.drawLine(QLineF(left, y - dy50, right, y - dy50));
366 p.drawLine(QLineF(left, y - dy75, right, y - dy75));
370 if (neg_vdivs_ > 0) {
371 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
372 for (int i = 1; i <= neg_vdivs_; i++) {
373 const float dy = i * div_height_;
374 p.drawLine(QLineF(left, y + dy, right, y + dy));
378 if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
379 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
380 for (int i = 0; i < neg_vdivs_; i++) {
381 const float dy = i * div_height_;
382 const float dy25 = dy + (0.25 * div_height_);
383 const float dy50 = dy + (0.50 * div_height_);
384 const float dy75 = dy + (0.75 * div_height_);
385 p.drawLine(QLineF(left, y + dy25, right, y + dy25));
386 p.drawLine(QLineF(left, y + dy50, right, y + dy50));
387 p.drawLine(QLineF(left, y + dy75, right, y + dy75));
391 p.setRenderHint(QPainter::Antialiasing, true);
394 void AnalogSignal::paint_trace(QPainter &p,
395 const shared_ptr<pv::data::AnalogSegment> &segment,
396 int y, int left, const int64_t start, const int64_t end,
397 const double pixels_offset, const double samples_per_pixel)
402 bool paint_thr_dots =
403 (base_->get_conversion_type() != data::SignalBase::NoConversion) &&
404 (conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Dots);
406 vector<double> thresholds;
408 thresholds = base_->get_conversion_thresholds();
410 // Calculate and paint the sampling points if enabled and useful
411 GlobalSettings settings;
412 const bool show_sampling_points =
413 (settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() ||
414 paint_thr_dots) && (samples_per_pixel < 0.25);
416 p.setPen(base_->color());
418 const int64_t points_count = end - start + 1;
420 QPointF *points = new QPointF[points_count];
421 QPointF *point = points;
423 vector<QRectF> sampling_points[3];
425 int64_t sample_count = min(points_count, TracePaintBlockSize);
426 int64_t block_sample = 0;
427 float *sample_block = new float[TracePaintBlockSize];
428 segment->get_samples(start, start + sample_count, sample_block);
430 if (show_hover_marker_)
431 reset_pixel_values();
434 for (int64_t sample = start; sample <= end; sample++, block_sample++) {
436 // Fetch next block of samples if we finished the current one
437 if (block_sample == TracePaintBlockSize) {
439 sample_count = min(points_count - sample, TracePaintBlockSize);
440 segment->get_samples(sample, sample + sample_count, sample_block);
443 const float abs_x = sample / samples_per_pixel - pixels_offset;
444 const float x = left + abs_x;
446 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
448 // Generate the pixel<->value lookup table for the mouse hover
449 if (show_hover_marker_)
450 process_next_sample_value(abs_x, sample_block[block_sample]);
452 // Create the sampling points if needed
453 if (show_sampling_points) {
454 int idx = 0; // Neutral
456 if (paint_thr_dots) {
457 if (thresholds.size() == 1)
458 idx = (sample_block[block_sample] >= thresholds[0]) ? 2 : 1;
459 else if (thresholds.size() == 2) {
460 if (sample_block[block_sample] > thresholds[1])
462 else if (sample_block[block_sample] < thresholds[0])
467 sampling_points[idx].emplace_back(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
470 delete[] sample_block;
472 p.drawPolyline(points, points_count);
474 if (show_sampling_points) {
475 if (paint_thr_dots) {
476 p.setPen(SamplingPointColorNe);
477 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
478 p.setPen(SamplingPointColorLo);
479 p.drawRects(sampling_points[1].data(), sampling_points[1].size());
480 p.setPen(SamplingPointColorHi);
481 p.drawRects(sampling_points[2].data(), sampling_points[2].size());
483 p.setPen(SamplingPointColor);
484 p.drawRects(sampling_points[0].data(), sampling_points[0].size());
491 void AnalogSignal::paint_envelope(QPainter &p,
492 const shared_ptr<pv::data::AnalogSegment> &segment,
493 int y, int left, const int64_t start, const int64_t end,
494 const double pixels_offset, const double samples_per_pixel)
496 using pv::data::AnalogSegment;
498 // Note: Envelope painting currently doesn't generate a pixel<->value lookup table
499 if (show_hover_marker_)
500 reset_pixel_values();
502 AnalogSegment::EnvelopeSection e;
503 segment->get_envelope_section(e, start, end, samples_per_pixel);
508 p.setPen(QPen(Qt::NoPen));
509 p.setBrush(base_->color());
511 QRectF *const rects = new QRectF[e.length];
512 QRectF *rect = rects;
514 for (uint64_t sample = 0; sample < e.length - 1; sample++) {
515 const float x = ((e.scale * sample + e.start) /
516 samples_per_pixel - pixels_offset) + left;
518 const AnalogSegment::EnvelopeSample *const s = e.samples + sample;
520 // We overlap this sample with the next so that vertical
521 // gaps do not appear during steep rising or falling edges
522 const float b = y - max(s->max, (s + 1)->min) * scale_;
523 const float t = y - min(s->min, (s + 1)->max) * scale_;
526 if (h >= 0.0f && h <= 1.0f)
528 if (h <= 0.0f && h >= -1.0f)
531 *rect++ = QRectF(x, t, 1.0f, h);
534 p.drawRects(rects, e.length);
540 void AnalogSignal::paint_logic_mid(QPainter &p, ViewItemPaintParams &pp)
544 vector< pair<int64_t, bool> > edges;
548 const int y = get_visual_y();
550 if (!base_->enabled() || !base_->logic_data())
553 const int signal_margin =
554 QFontMetrics(QApplication::font()).height() / 2;
556 const int ph = min(pos_vdivs_, 1) * div_height_;
557 const int nh = min(neg_vdivs_, 1) * div_height_;
558 const float high_offset = y - ph + signal_margin + 0.5f;
559 const float low_offset = y + nh - signal_margin - 0.5f;
561 shared_ptr<pv::data::LogicSegment> segment = get_logic_segment_to_paint();
562 if (!segment || (segment->get_sample_count() == 0))
565 double samplerate = segment->samplerate();
567 // Show sample rate as 1Hz when it is unknown
568 if (samplerate == 0.0)
571 const double pixels_offset = pp.pixels_offset();
572 const pv::util::Timestamp& start_time = segment->start_time();
573 const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
574 const double samples_per_pixel = samplerate * pp.scale();
575 const double pixels_per_sample = 1 / samples_per_pixel;
576 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
577 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
579 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
580 (int64_t)0), last_sample);
581 const uint64_t end_sample = min(max(ceil(end).convert_to<int64_t>(),
582 (int64_t)0), last_sample);
584 segment->get_subsampled_edges(edges, start_sample, end_sample,
585 samples_per_pixel / LogicSignal::Oversampling, 0);
586 assert(edges.size() >= 2);
588 // Check whether we need to paint the sampling points
589 GlobalSettings settings;
590 const bool show_sampling_points =
591 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() &&
592 (samples_per_pixel < 0.25);
594 vector<QRectF> sampling_points;
595 float sampling_point_x = 0.0f;
596 int64_t sampling_point_sample = start_sample;
599 if (show_sampling_points) {
600 sampling_points.reserve(end_sample - start_sample + 1);
601 sampling_point_x = (edges.cbegin()->first / samples_per_pixel - pixels_offset) + pp.left();
605 const unsigned int edge_count = edges.size() - 2;
606 QLineF *const edge_lines = new QLineF[edge_count];
609 for (auto i = edges.cbegin() + 1; i != edges.cend() - 1; i++) {
610 const float x = ((*i).first / samples_per_pixel -
611 pixels_offset) + pp.left();
612 *line++ = QLineF(x, high_offset, x, low_offset);
614 if (show_sampling_points)
615 while (sampling_point_sample < (*i).first) {
616 const float y = (*i).second ? low_offset : high_offset;
617 sampling_points.emplace_back(
618 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
619 sampling_point_sample++;
620 sampling_point_x += pixels_per_sample;
624 // Calculate the sample points from the last edge to the end of the trace
625 if (show_sampling_points)
626 while ((uint64_t)sampling_point_sample <= end_sample) {
627 // Signal changed after the last edge, so the level is inverted
628 const float y = (edges.cend() - 1)->second ? high_offset : low_offset;
629 sampling_points.emplace_back(
630 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
631 sampling_point_sample++;
632 sampling_point_x += pixels_per_sample;
635 p.setPen(LogicSignal::EdgeColor);
636 p.drawLines(edge_lines, edge_count);
640 const unsigned int max_cap_line_count = edges.size();
641 QLineF *const cap_lines = new QLineF[max_cap_line_count];
643 p.setPen(LogicSignal::HighColor);
644 paint_logic_caps(p, cap_lines, edges, true, samples_per_pixel,
645 pixels_offset, pp.left(), high_offset);
646 p.setPen(LogicSignal::LowColor);
647 paint_logic_caps(p, cap_lines, edges, false, samples_per_pixel,
648 pixels_offset, pp.left(), low_offset);
652 // Paint the sampling points
653 if (show_sampling_points) {
654 p.setPen(SamplingPointColor);
655 p.drawRects(sampling_points.data(), sampling_points.size());
659 void AnalogSignal::paint_logic_caps(QPainter &p, QLineF *const lines,
660 vector< pair<int64_t, bool> > &edges, bool level,
661 double samples_per_pixel, double pixels_offset, float x_offset,
664 QLineF *line = lines;
666 for (auto i = edges.begin(); i != (edges.end() - 1); i++)
667 if ((*i).second == level) {
669 ((*i).first / samples_per_pixel -
670 pixels_offset) + x_offset, y_offset,
671 ((*(i+1)).first / samples_per_pixel -
672 pixels_offset) + x_offset, y_offset);
675 p.drawLines(lines, line - lines);
678 shared_ptr<pv::data::AnalogSegment> AnalogSignal::get_analog_segment_to_paint() const
680 shared_ptr<pv::data::AnalogSegment> segment;
682 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
683 base_->analog_data()->analog_segments();
685 if (!segments.empty()) {
686 if (segment_display_mode_ == ShowLastSegmentOnly)
687 segment = segments.back();
689 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
690 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
692 segment = segments.at(current_segment_);
693 } catch (out_of_range&) {
694 qDebug() << "Current analog segment out of range for signal" << base_->name() << ":" << current_segment_;
702 shared_ptr<pv::data::LogicSegment> AnalogSignal::get_logic_segment_to_paint() const
704 shared_ptr<pv::data::LogicSegment> segment;
706 const deque< shared_ptr<pv::data::LogicSegment> > &segments =
707 base_->logic_data()->logic_segments();
709 if (!segments.empty()) {
710 if (segment_display_mode_ == ShowLastSegmentOnly)
711 segment = segments.back();
713 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
714 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
716 segment = segments.at(current_segment_);
717 } catch (out_of_range&) {
718 qDebug() << "Current logic segment out of range for signal" << base_->name() << ":" << current_segment_;
726 float AnalogSignal::get_resolution(int scale_index)
728 const float seq[] = {1.0f, 2.0f, 5.0f};
730 const int offset = numeric_limits<int>::max() / (2 * countof(seq));
731 const div_t d = div((int)(scale_index + countof(seq) * offset),
734 return powf(10.0f, d.quot - offset) * seq[d.rem];
737 void AnalogSignal::update_scale()
739 resolution_ = get_resolution(scale_index_);
740 scale_ = div_height_ / resolution_;
743 void AnalogSignal::update_conversion_widgets()
745 SignalBase::ConversionType conv_type = base_->get_conversion_type();
747 // Enable or disable widgets depending on conversion state
748 conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
749 display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
751 conv_threshold_cb_->clear();
753 vector < pair<QString, int> > presets = base_->get_conversion_presets();
755 // Prevent the combo box from firing the "edit text changed" signal
756 // as that would involuntarily select the first entry
757 conv_threshold_cb_->blockSignals(true);
759 // Set available options depending on chosen conversion
760 for (pair<QString, int> preset : presets)
761 conv_threshold_cb_->addItem(preset.first, preset.second);
763 map < QString, QVariant > options = base_->get_conversion_options();
765 if (conv_type == SignalBase::A2LConversionByThreshold) {
766 const vector<double> thresholds = base_->get_conversion_thresholds(
767 SignalBase::A2LConversionByThreshold, true);
768 conv_threshold_cb_->addItem(
769 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
772 if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
773 const vector<double> thresholds = base_->get_conversion_thresholds(
774 SignalBase::A2LConversionBySchmittTrigger, true);
775 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
776 QString::number(thresholds[0], 'f', 1),
777 QString::number(thresholds[1], 'f', 1)), -1);
780 int preset_id = base_->get_current_conversion_preset();
781 conv_threshold_cb_->setCurrentIndex(
782 conv_threshold_cb_->findData(preset_id));
784 conv_threshold_cb_->blockSignals(false);
787 void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
789 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
790 base_->analog_data()->analog_segments();
792 if (segments.empty())
795 static double prev_min = 0, prev_max = 0;
796 double min = 0, max = 0;
798 for (shared_ptr<pv::data::AnalogSegment> segment : segments) {
799 pair<double, double> mm = segment->get_min_max();
800 min = std::min(min, mm.first);
801 max = std::max(max, mm.second);
804 if ((min == prev_min) && (max == prev_max) && !force_update)
810 // If we're allowed to alter the div assignment...
812 // Use all divs for the positive range if there are no negative values
813 if ((min == 0) && (neg_vdivs_ > 0)) {
814 pos_vdivs_ += neg_vdivs_;
818 // Split up the divs if there are negative values but no negative divs
819 if ((min < 0) && (neg_vdivs_ == 0)) {
820 neg_vdivs_ = pos_vdivs_ / 2;
821 pos_vdivs_ -= neg_vdivs_;
825 // If there is still no positive div when we need it, add one
826 // (this can happen when pos_vdivs==neg_vdivs==0)
827 if ((max > 0) && (pos_vdivs_ == 0)) {
829 owner_->extents_changed(false, true);
832 // If there is still no negative div when we need it, add one
833 // (this can happen when pos_vdivs was 0 or 1 when trying to split)
834 if ((min < 0) && (neg_vdivs_ == 0)) {
836 owner_->extents_changed(false, true);
839 double min_value_per_div;
840 if ((pos_vdivs_ > 0) && (neg_vdivs_ > 0))
841 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
842 else if (pos_vdivs_ > 0)
843 min_value_per_div = max / pos_vdivs_;
845 min_value_per_div = -min / neg_vdivs_;
847 // Find first scale value that is bigger than the value we need
848 for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
849 if (get_resolution(i) > min_value_per_div) {
857 void AnalogSignal::reset_pixel_values()
859 value_at_pixel_pos_.clear();
860 current_pixel_pos_ = -1;
861 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
864 void AnalogSignal::process_next_sample_value(float x, float value)
866 // Note: NAN is used to indicate the non-existance of a value at this pixel
868 if (isnan(prev_value_at_pixel_)) {
870 min_value_at_pixel_ = value;
871 max_value_at_pixel_ = value;
872 prev_value_at_pixel_ = value;
873 current_pixel_pos_ = x;
875 prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
878 const int pixel_pos = (int)(x + 0.5);
880 if (pixel_pos > current_pixel_pos_) {
881 if (pixel_pos - current_pixel_pos_ == 1) {
882 if (isnan(prev_value_at_pixel_)) {
883 value_at_pixel_pos_.push_back(prev_value_at_pixel_);
885 // Average the min/max range to create one value for the previous pixel
886 const float avg = (min_value_at_pixel_ + max_value_at_pixel_) / 2;
887 value_at_pixel_pos_.push_back(avg);
890 // Interpolate values to create values for the intermediate pixels
891 const float start_value = prev_value_at_pixel_;
892 const float end_value = value;
893 const int steps = fabs(pixel_pos - current_pixel_pos_);
894 const double gradient = (end_value - start_value) / steps;
895 for (int i = 0; i < steps; i++) {
896 if (current_pixel_pos_ + i < 0)
898 value_at_pixel_pos_.push_back(start_value + i * gradient);
902 min_value_at_pixel_ = value;
903 max_value_at_pixel_ = value;
904 prev_value_at_pixel_ = value;
905 current_pixel_pos_ = pixel_pos;
907 // Another sample for the same pixel
908 if (value < min_value_at_pixel_)
909 min_value_at_pixel_ = value;
910 if (value > max_value_at_pixel_)
911 max_value_at_pixel_ = value;
915 void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
917 // Add the standard options
918 Signal::populate_popup_form(parent, form);
920 QFormLayout *const layout = new QFormLayout;
922 // Add div-related settings
923 pvdiv_sb_ = new QSpinBox(parent);
924 pvdiv_sb_->setRange(0, MaximumVDivs);
925 pvdiv_sb_->setValue(pos_vdivs_);
926 connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
927 this, SLOT(on_pos_vdivs_changed(int)));
928 layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
930 nvdiv_sb_ = new QSpinBox(parent);
931 nvdiv_sb_->setRange(0, MaximumVDivs);
932 nvdiv_sb_->setValue(neg_vdivs_);
933 connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
934 this, SLOT(on_neg_vdivs_changed(int)));
935 layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
937 div_height_sb_ = new QSpinBox(parent);
938 div_height_sb_->setRange(20, 1000);
939 div_height_sb_->setSingleStep(5);
940 div_height_sb_->setSuffix(tr(" pixels"));
941 div_height_sb_->setValue(div_height_);
942 connect(div_height_sb_, SIGNAL(valueChanged(int)),
943 this, SLOT(on_div_height_changed(int)));
944 layout->addRow(tr("Div height"), div_height_sb_);
946 // Add the vertical resolution
947 resolution_cb_ = new QComboBox(parent);
949 for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
950 const QString label = QString("%1").arg(get_resolution(i));
951 resolution_cb_->insertItem(0, label, QVariant(i));
954 int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
955 resolution_cb_->setCurrentIndex(cur_idx);
957 connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
958 this, SLOT(on_resolution_changed(int)));
960 QGridLayout *const vdiv_layout = new QGridLayout;
961 QLabel *const vdiv_unit = new QLabel(tr("V/div"));
962 vdiv_layout->addWidget(resolution_cb_, 0, 0);
963 vdiv_layout->addWidget(vdiv_unit, 0, 1);
965 layout->addRow(tr("Vertical resolution"), vdiv_layout);
967 // Add the autoranging checkbox
968 QCheckBox* autoranging_cb = new QCheckBox();
969 autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
971 connect(autoranging_cb, SIGNAL(stateChanged(int)),
972 this, SLOT(on_autoranging_changed(int)));
974 layout->addRow(tr("Autoranging"), autoranging_cb);
976 // Add the conversion type dropdown
977 conversion_cb_ = new QComboBox();
979 conversion_cb_->addItem(tr("none"),
980 SignalBase::NoConversion);
981 conversion_cb_->addItem(tr("to logic via threshold"),
982 SignalBase::A2LConversionByThreshold);
983 conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
984 SignalBase::A2LConversionBySchmittTrigger);
986 cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
987 conversion_cb_->setCurrentIndex(cur_idx);
989 layout->addRow(tr("Conversion"), conversion_cb_);
991 connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
992 this, SLOT(on_conversion_changed(int)));
994 // Add the conversion threshold settings
995 conv_threshold_cb_ = new QComboBox();
996 conv_threshold_cb_->setEditable(true);
998 layout->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
1000 connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
1001 this, SLOT(on_conv_threshold_changed(int)));
1002 connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString)),
1003 this, SLOT(on_conv_threshold_changed())); // index will be -1
1005 // Add the display type dropdown
1006 display_type_cb_ = new QComboBox();
1008 display_type_cb_->addItem(tr("analog"), DisplayAnalog);
1009 display_type_cb_->addItem(tr("converted"), DisplayConverted);
1010 display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
1012 cur_idx = display_type_cb_->findData(QVariant(display_type_));
1013 display_type_cb_->setCurrentIndex(cur_idx);
1015 layout->addRow(tr("Show traces for"), display_type_cb_);
1017 connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
1018 this, SLOT(on_display_type_changed(int)));
1020 // Update the conversion widget contents and states
1021 update_conversion_widgets();
1023 form->addRow(layout);
1026 void AnalogSignal::hover_point_changed(const QPoint &hp)
1028 Signal::hover_point_changed(hp);
1030 // Note: Even though the view area begins at 0, we exclude 0 because
1031 // that's also the value given when the cursor is over the header to the
1032 // left of the trace paint area
1034 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1037 value_at_hover_pos_ = value_at_pixel_pos_.at(hp.x());
1038 } catch (out_of_range) {
1039 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1044 void AnalogSignal::on_min_max_changed(float min, float max)
1050 perform_autoranging(false, false);
1053 void AnalogSignal::on_pos_vdivs_changed(int vdivs)
1055 if (vdivs == pos_vdivs_)
1060 // There has to be at least one div, positive or negative
1061 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1064 pvdiv_sb_->setValue(pos_vdivs_);
1068 perform_autoranging(true, true);
1070 // It could be that a positive or negative div was added, so update
1072 pvdiv_sb_->setValue(pos_vdivs_);
1073 nvdiv_sb_->setValue(neg_vdivs_);
1078 // Call order is important, otherwise the lazy event handler won't work
1079 owner_->extents_changed(false, true);
1080 owner_->row_item_appearance_changed(false, true);
1084 void AnalogSignal::on_neg_vdivs_changed(int vdivs)
1086 if (vdivs == neg_vdivs_)
1091 // There has to be at least one div, positive or negative
1092 if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1095 pvdiv_sb_->setValue(pos_vdivs_);
1099 perform_autoranging(true, true);
1101 // It could be that a positive or negative div was added, so update
1103 pvdiv_sb_->setValue(pos_vdivs_);
1104 nvdiv_sb_->setValue(neg_vdivs_);
1109 // Call order is important, otherwise the lazy event handler won't work
1110 owner_->extents_changed(false, true);
1111 owner_->row_item_appearance_changed(false, true);
1115 void AnalogSignal::on_div_height_changed(int height)
1117 div_height_ = height;
1121 // Call order is important, otherwise the lazy event handler won't work
1122 owner_->extents_changed(false, true);
1123 owner_->row_item_appearance_changed(false, true);
1127 void AnalogSignal::on_resolution_changed(int index)
1129 scale_index_ = resolution_cb_->itemData(index).toInt();
1133 owner_->row_item_appearance_changed(false, true);
1136 void AnalogSignal::on_autoranging_changed(int state)
1138 autoranging_ = (state == Qt::Checked);
1141 perform_autoranging(false, true);
1144 // Call order is important, otherwise the lazy event handler won't work
1145 owner_->extents_changed(false, true);
1146 owner_->row_item_appearance_changed(false, true);
1150 void AnalogSignal::on_conversion_changed(int index)
1152 SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
1154 SignalBase::ConversionType conv_type =
1155 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
1157 if (conv_type != old_conv_type) {
1158 base_->set_conversion_type(conv_type);
1159 update_conversion_widgets();
1162 owner_->row_item_appearance_changed(false, true);
1166 void AnalogSignal::on_conv_threshold_changed(int index)
1168 SignalBase::ConversionType conv_type = base_->get_conversion_type();
1170 // Note: index is set to -1 if the text in the combo box matches none of
1171 // the entries in the combo box
1173 if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
1176 // The combo box entry with the custom value has user_data set to -1
1177 const int user_data = conv_threshold_cb_->findText(
1178 conv_threshold_cb_->currentText());
1180 const bool use_custom_thr = (index == -1) || (user_data == -1);
1182 if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
1183 // Not one of the preset values, try to parse the combo box text
1184 // Note: Regex loosely based on
1185 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1186 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1187 QString re2 = "([a-zA-Z]*)"; // SI unit
1188 QRegExp regex(re1 + re2);
1190 const QString text = conv_threshold_cb_->currentText();
1191 if (!regex.exactMatch(text))
1192 return; // String doesn't match the regex
1194 QStringList tokens = regex.capturedTexts();
1196 // For now, we simply assume that the unit is volt without modifiers
1197 const double thr = tokens.at(1).toDouble();
1199 // Only restart the conversion if the threshold was updated.
1200 // We're starting a delayed conversion because the user may still be
1201 // typing and the UI would lag if we kept on restarting it immediately
1202 if (base_->set_conversion_option("threshold_value", thr))
1203 base_->start_conversion(true);
1206 if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
1207 // Not one of the preset values, try to parse the combo box text
1208 // Note: Regex loosely based on
1209 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1210 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1211 QString re2 = "([a-zA-Z]*)"; // SI unit
1212 QString re3 = "\\/"; // Forward slash, not captured
1213 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1214 QString re5 = "([a-zA-Z]*)"; // SI unit
1215 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1217 const QString text = conv_threshold_cb_->currentText();
1218 if (!regex.exactMatch(text))
1219 return; // String doesn't match the regex
1221 QStringList tokens = regex.capturedTexts();
1223 // For now, we simply assume that the unit is volt without modifiers
1224 const double low_thr = tokens.at(1).toDouble();
1225 const double high_thr = tokens.at(3).toDouble();
1227 // Only restart the conversion if one of the options was updated.
1228 // We're starting a delayed conversion because the user may still be
1229 // typing and the UI would lag if we kept on restarting it immediately
1230 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1231 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1233 base_->start_conversion(true); // Start delayed conversion
1236 base_->set_conversion_preset((SignalBase::ConversionPreset)index);
1238 // Immediately start the conversion if we're not using custom values
1239 // (i.e. we're using one of the presets)
1240 if (!use_custom_thr)
1241 base_->start_conversion();
1244 void AnalogSignal::on_delayed_conversion_starter()
1246 base_->start_conversion();
1249 void AnalogSignal::on_display_type_changed(int index)
1251 display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1254 owner_->row_item_appearance_changed(false, true);
1257 void AnalogSignal::on_settingViewConversionThresholdDispMode_changed(const QVariant new_value)
1259 conversion_threshold_disp_mode_ = new_value.toInt();
1262 owner_->row_item_appearance_changed(false, true);
1265 } // namespace trace
1266 } // namespace views