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