Use QMenu->popup() instead of QMenu->exec() everywhere
[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
69 namespace pv {
70 namespace views {
71 namespace trace {
72
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
78 };
79
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);
83
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);
88
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);
93
94 const int64_t AnalogSignal::TracePaintBlockSize = 1024 * 1024;  // 4 MiB (due to float)
95 const float AnalogSignal::EnvelopeThreshold = 64.0f;
96
97 const int AnalogSignal::MaximumVDivs = 10;
98 const int AnalogSignal::MinScaleIndex = -6;
99 const int AnalogSignal::MaxScaleIndex = 7;
100
101 const int AnalogSignal::InfoTextMarginRight = 20;
102 const int AnalogSignal::InfoTextMarginBottom = 5;
103
104 AnalogSignal::AnalogSignal(
105         pv::Session &session,
106         shared_ptr<data::SignalBase> base) :
107         Signal(session, base),
108         scale_index_(4), // 20 per div
109         pos_vdivs_(1),
110         neg_vdivs_(1),
111         resolution_(0),
112         display_type_(DisplayBoth),
113         autoranging_(true),
114         value_at_hover_pos_(std::numeric_limits<float>::quiet_NaN())
115 {
116         axis_pen_ = AxisPen;
117
118         pv::data::Analog* analog_data =
119                 dynamic_cast<pv::data::Analog*>(data().get());
120
121         connect(analog_data, SIGNAL(min_max_changed(float, float)),
122                 this, SLOT(on_min_max_changed(float, float)));
123
124         GlobalSettings gs;
125         conversion_threshold_disp_mode_ =
126                 gs.value(GlobalSettings::Key_View_ConversionThresholdDispMode).toInt();
127
128         div_height_ = gs.value(GlobalSettings::Key_View_DefaultDivHeight).toInt();
129
130         base_->set_color(SignalColors[base_->index() % countof(SignalColors)]);
131         update_scale();
132 }
133
134 shared_ptr<pv::data::SignalData> AnalogSignal::data() const
135 {
136         return base_->analog_data();
137 }
138
139 void AnalogSignal::save_settings(QSettings &settings) const
140 {
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_);
147 }
148
149 void AnalogSignal::restore_settings(QSettings &settings)
150 {
151         if (settings.contains("pos_vdivs"))
152                 pos_vdivs_ = settings.value("pos_vdivs").toInt();
153
154         if (settings.contains("neg_vdivs"))
155                 neg_vdivs_ = settings.value("neg_vdivs").toInt();
156
157         if (settings.contains("scale_index")) {
158                 scale_index_ = settings.value("scale_index").toInt();
159                 update_scale();
160         }
161
162         if (settings.contains("display_type"))
163                 display_type_ = (DisplayType)(settings.value("display_type").toInt());
164
165         if (settings.contains("autoranging"))
166                 autoranging_ = settings.value("autoranging").toBool();
167
168         if (settings.contains("div_height")) {
169                 const int old_height = div_height_;
170                 div_height_ = settings.value("div_height").toInt();
171
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);
176                 }
177         }
178 }
179
180 pair<int, int> AnalogSignal::v_extents() const
181 {
182         const int ph = pos_vdivs_ * div_height_;
183         const int nh = neg_vdivs_ * div_height_;
184         return make_pair(-ph, nh);
185 }
186
187 void AnalogSignal::on_setting_changed(const QString &key, const QVariant &value)
188 {
189         Signal::on_setting_changed(key, value);
190
191         if (key == GlobalSettings::Key_View_ConversionThresholdDispMode)
192                 on_settingViewConversionThresholdDispMode_changed(value);
193 }
194
195 void AnalogSignal::paint_back(QPainter &p, ViewItemPaintParams &pp)
196 {
197         if (!base_->enabled())
198                 return;
199
200         bool paint_thr_bg =
201                 conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Background;
202
203         const vector<double> thresholds = base_->get_conversion_thresholds();
204
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))) {
208
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;
213
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);
220
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));
227                 } else {
228                         int thr = visual_y - thresholds[0] * scale_;
229                         thr = min(max(thr, top), btm);
230
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));
235                 }
236
237                 paint_axis(p, pp, get_visual_y());
238         } else {
239                 Trace::paint_back(p, pp);
240                 paint_axis(p, pp, get_visual_y());
241         }
242 }
243
244 void AnalogSignal::paint_mid(QPainter &p, ViewItemPaintParams &pp)
245 {
246         assert(base_->analog_data());
247         assert(owner_);
248
249         const int y = get_visual_y();
250
251         if (!base_->enabled())
252                 return;
253
254         if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
255                 paint_grid(p, y, pp.left(), pp.right());
256
257                 shared_ptr<pv::data::AnalogSegment> segment = get_analog_segment_to_paint();
258                 if (!segment || (segment->get_sample_count() == 0))
259                         return;
260
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         if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
283                 paint_logic_mid(p, pp);
284 }
285
286 void AnalogSignal::paint_fore(QPainter &p, ViewItemPaintParams &pp)
287 {
288         if (!enabled())
289                 return;
290
291         if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
292                 const int y = get_visual_y();
293
294                 QString infotext;
295
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))
302                                 .arg(resolution_);
303                 } else
304                         infotext = QString("%1 V/div").arg(resolution_);
305
306                 p.setPen(base_->color());
307                 p.setFont(QApplication::font());
308
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);
313
314                 p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
315         }
316
317         if (show_hover_marker_)
318                 paint_hover_marker(p);
319 }
320
321 void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
322 {
323         p.setRenderHint(QPainter::Antialiasing, false);
324
325         GlobalSettings settings;
326         const bool show_analog_minor_grid =
327                 settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
328
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));
334                 }
335         }
336
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));
347                 }
348         }
349
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));
355                 }
356         }
357
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));
368                 }
369         }
370
371         p.setRenderHint(QPainter::Antialiasing, true);
372 }
373
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)
378 {
379         if (end <= start)
380                 return;
381
382         bool paint_thr_dots =
383                 (base_->get_conversion_type() != data::SignalBase::NoConversion) &&
384                 (conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Dots);
385
386         vector<double> thresholds;
387         if (paint_thr_dots)
388                 thresholds = base_->get_conversion_thresholds();
389
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);
395
396         p.setPen(base_->color());
397
398         const int64_t points_count = end - start + 1;
399
400         QPointF *points = new QPointF[points_count];
401         QPointF *point = points;
402
403         vector<QRectF> sampling_points[3];
404
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);
409
410         if (show_hover_marker_)
411                 reset_pixel_values();
412
413         const int w = 2;
414         for (int64_t sample = start; sample <= end; sample++, block_sample++) {
415
416                 // Fetch next block of samples if we finished the current one
417                 if (block_sample == TracePaintBlockSize) {
418                         block_sample = 0;
419                         sample_count = min(points_count - sample, TracePaintBlockSize);
420                         segment->get_samples(sample, sample + sample_count, sample_block);
421                 }
422
423                 const float abs_x = sample / samples_per_pixel - pixels_offset;
424                 const float x = left + abs_x;
425
426                 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
427
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]);
431
432                 // Create the sampling points if needed
433                 if (show_sampling_points) {
434                         int idx = 0;  // Neutral
435
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])
441                                                 idx = 2;  // High
442                                         else if (sample_block[block_sample] < thresholds[0])
443                                                 idx = 1;  // Low
444                                 }
445                         }
446
447                         sampling_points[idx].emplace_back(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
448                 }
449         }
450         delete[] sample_block;
451
452         p.drawPolyline(points, points_count);
453
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());
462                 } else {
463                         p.setPen(SamplingPointColor);
464                         p.drawRects(sampling_points[0].data(), sampling_points[0].size());
465                 }
466         }
467
468         delete[] points;
469 }
470
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)
475 {
476         using pv::data::AnalogSegment;
477
478         // Note: Envelope painting currently doesn't generate a pixel<->value lookup table
479         if (show_hover_marker_)
480                 reset_pixel_values();
481
482         AnalogSegment::EnvelopeSection e;
483         segment->get_envelope_section(e, start, end, samples_per_pixel);
484
485         if (e.length < 2)
486                 return;
487
488         p.setPen(QPen(Qt::NoPen));
489         p.setBrush(base_->color());
490
491         QRectF *const rects = new QRectF[e.length];
492         QRectF *rect = rects;
493
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;
497
498                 const AnalogSegment::EnvelopeSample *const s = e.samples + sample;
499
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_;
504
505                 float h = b - t;
506                 if (h >= 0.0f && h <= 1.0f)
507                         h = 1.0f;
508                 if (h <= 0.0f && h >= -1.0f)
509                         h = -1.0f;
510
511                 *rect++ = QRectF(x, t, 1.0f, h);
512         }
513
514         p.drawRects(rects, e.length);
515
516         delete[] rects;
517         delete[] e.samples;
518 }
519
520 void AnalogSignal::paint_logic_mid(QPainter &p, ViewItemPaintParams &pp)
521 {
522         QLineF *line;
523
524         vector< pair<int64_t, bool> > edges;
525
526         assert(base_);
527
528         const int y = get_visual_y();
529
530         if (!base_->enabled() || !base_->logic_data())
531                 return;
532
533         const int signal_margin =
534                 QFontMetrics(QApplication::font()).height() / 2;
535
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;
540         const float signal_height = low_offset - high_offset;
541
542         shared_ptr<pv::data::LogicSegment> segment = get_logic_segment_to_paint();
543         if (!segment || (segment->get_sample_count() == 0))
544                 return;
545
546         double samplerate = segment->samplerate();
547
548         // Show sample rate as 1Hz when it is unknown
549         if (samplerate == 0.0)
550                 samplerate = 1.0;
551
552         const double pixels_offset = pp.pixels_offset();
553         const pv::util::Timestamp& start_time = segment->start_time();
554         const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
555         const double samples_per_pixel = samplerate * pp.scale();
556         const double pixels_per_sample = 1 / samples_per_pixel;
557         const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
558         const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
559
560         const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
561                 (int64_t)0), last_sample);
562         const uint64_t end_sample = min(max(ceil(end).convert_to<int64_t>(),
563                 (int64_t)0), last_sample);
564
565         segment->get_subsampled_edges(edges, start_sample, end_sample,
566                 samples_per_pixel / LogicSignal::Oversampling, 0);
567         assert(edges.size() >= 2);
568
569         const float first_sample_x =
570                 pp.left() + (edges.front().first / samples_per_pixel - pixels_offset);
571         const float last_sample_x =
572                 pp.left() + (edges.back().first / samples_per_pixel - pixels_offset);
573
574         // Check whether we need to paint the sampling points
575         GlobalSettings settings;
576         const bool show_sampling_points =
577                 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() &&
578                 (samples_per_pixel < 0.25);
579
580         vector<QRectF> sampling_points;
581         float sampling_point_x = first_sample_x;
582         int64_t sampling_point_sample = start_sample;
583         const int w = 2;
584
585         if (show_sampling_points)
586                 sampling_points.reserve(end_sample - start_sample + 1);
587
588         // Check whether we need to fill the high areas
589         const bool fill_high_areas =
590                 settings.value(GlobalSettings::Key_View_FillSignalHighAreas).toBool();
591         float high_start_x;
592         vector<QRectF> high_rects;
593
594         // Paint the edges
595         const unsigned int edge_count = edges.size() - 2;
596         QLineF *const edge_lines = new QLineF[edge_count];
597         line = edge_lines;
598
599         for (auto i = edges.cbegin() + 1; i != edges.cend() - 1; i++) {
600                 const float x = ((*i).first / samples_per_pixel -
601                         pixels_offset) + pp.left();
602                 *line++ = QLineF(x, high_offset, x, low_offset);
603
604                 if (fill_high_areas) {
605                         if ((*i).second)
606                                 high_start_x = x;
607                         else
608                                 high_rects.emplace_back(high_start_x, high_offset,
609                                         x - high_start_x, signal_height);
610                 }
611
612                 if (show_sampling_points)
613                         while (sampling_point_sample < (*i).first) {
614                                 const float y = (*i).second ? low_offset : high_offset;
615                                 sampling_points.emplace_back(
616                                         QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
617                                 sampling_point_sample++;
618                                 sampling_point_x += pixels_per_sample;
619                         };
620         }
621
622         // Calculate the sample points from the last edge to the end of the trace
623         if (show_sampling_points)
624                 while ((uint64_t)sampling_point_sample <= end_sample) {
625                         // Signal changed after the last edge, so the level is inverted
626                         const float y = (edges.cend() - 1)->second ? high_offset : low_offset;
627                         sampling_points.emplace_back(
628                                 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
629                         sampling_point_sample++;
630                         sampling_point_x += pixels_per_sample;
631                 };
632
633         if (fill_high_areas) {
634                 // Add last high rectangle if the signal is still high at the end of the view
635                 if ((edges.cend() - 1)->second)
636                         high_rects.emplace_back(high_start_x, high_offset,
637                                 last_sample_x - high_start_x, signal_height);
638
639                 const QColor fill_color = QColor::fromRgba(settings.value(
640                         GlobalSettings::Key_View_FillSignalHighAreaColor).value<uint32_t>());
641                 p.setPen(fill_color);
642                 p.setBrush(fill_color);
643                 p.drawRects((const QRectF*)(high_rects.data()), high_rects.size());
644         }
645
646         p.setPen(LogicSignal::EdgeColor);
647         p.drawLines(edge_lines, edge_count);
648         delete[] edge_lines;
649
650         // Paint the caps
651         const unsigned int max_cap_line_count = edges.size();
652         QLineF *const cap_lines = new QLineF[max_cap_line_count];
653
654         p.setPen(LogicSignal::HighColor);
655         paint_logic_caps(p, cap_lines, edges, true, samples_per_pixel,
656                 pixels_offset, pp.left(), high_offset);
657         p.setPen(LogicSignal::LowColor);
658         paint_logic_caps(p, cap_lines, edges, false, samples_per_pixel,
659                 pixels_offset, pp.left(), low_offset);
660
661         delete[] cap_lines;
662
663         // Paint the sampling points
664         if (show_sampling_points) {
665                 p.setPen(SamplingPointColor);
666                 p.drawRects(sampling_points.data(), sampling_points.size());
667         }
668 }
669
670 void AnalogSignal::paint_logic_caps(QPainter &p, QLineF *const lines,
671         vector< pair<int64_t, bool> > &edges, bool level,
672         double samples_per_pixel, double pixels_offset, float x_offset,
673         float y_offset)
674 {
675         QLineF *line = lines;
676
677         for (auto i = edges.begin(); i != (edges.end() - 1); i++)
678                 if ((*i).second == level) {
679                         *line++ = QLineF(
680                                 ((*i).first / samples_per_pixel -
681                                         pixels_offset) + x_offset, y_offset,
682                                 ((*(i+1)).first / samples_per_pixel -
683                                         pixels_offset) + x_offset, y_offset);
684                 }
685
686         p.drawLines(lines, line - lines);
687 }
688
689 shared_ptr<pv::data::AnalogSegment> AnalogSignal::get_analog_segment_to_paint() const
690 {
691         shared_ptr<pv::data::AnalogSegment> segment;
692
693         const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
694                 base_->analog_data()->analog_segments();
695
696         if (!segments.empty()) {
697                 if (segment_display_mode_ == ShowLastSegmentOnly)
698                         segment = segments.back();
699
700                 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
701                                 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
702                         try {
703                                 segment = segments.at(current_segment_);
704                         } catch (out_of_range&) {
705                                 qDebug() << "Current analog segment out of range for signal" << base_->name() << ":" << current_segment_;
706                         }
707                 }
708         }
709
710         return segment;
711 }
712
713 shared_ptr<pv::data::LogicSegment> AnalogSignal::get_logic_segment_to_paint() const
714 {
715         shared_ptr<pv::data::LogicSegment> segment;
716
717         const deque< shared_ptr<pv::data::LogicSegment> > &segments =
718                 base_->logic_data()->logic_segments();
719
720         if (!segments.empty()) {
721                 if (segment_display_mode_ == ShowLastSegmentOnly)
722                         segment = segments.back();
723
724                 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
725                                 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
726                         try {
727                                 segment = segments.at(current_segment_);
728                         } catch (out_of_range&) {
729                                 qDebug() << "Current logic segment out of range for signal" << base_->name() << ":" << current_segment_;
730                         }
731                 }
732         }
733
734         return segment;
735 }
736
737 float AnalogSignal::get_resolution(int scale_index)
738 {
739         const float seq[] = {1.0f, 2.0f, 5.0f};
740
741         const int offset = numeric_limits<int>::max() / (2 * countof(seq));
742         const div_t d = div((int)(scale_index + countof(seq) * offset),
743                 countof(seq));
744
745         return powf(10.0f, d.quot - offset) * seq[d.rem];
746 }
747
748 void AnalogSignal::update_scale()
749 {
750         resolution_ = get_resolution(scale_index_);
751         scale_ = div_height_ / resolution_;
752 }
753
754 void AnalogSignal::update_conversion_widgets()
755 {
756         SignalBase::ConversionType conv_type = base_->get_conversion_type();
757
758         // Enable or disable widgets depending on conversion state
759         conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
760         display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
761
762         conv_threshold_cb_->clear();
763
764         vector < pair<QString, int> > presets = base_->get_conversion_presets();
765
766         // Prevent the combo box from firing the "edit text changed" signal
767         // as that would involuntarily select the first entry
768         conv_threshold_cb_->blockSignals(true);
769
770         // Set available options depending on chosen conversion
771         for (pair<QString, int> preset : presets)
772                 conv_threshold_cb_->addItem(preset.first, preset.second);
773
774         map < QString, QVariant > options = base_->get_conversion_options();
775
776         if (conv_type == SignalBase::A2LConversionByThreshold) {
777                 const vector<double> thresholds = base_->get_conversion_thresholds(
778                                 SignalBase::A2LConversionByThreshold, true);
779                 conv_threshold_cb_->addItem(
780                                 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
781         }
782
783         if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
784                 const vector<double> thresholds = base_->get_conversion_thresholds(
785                                 SignalBase::A2LConversionBySchmittTrigger, true);
786                 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
787                                 QString::number(thresholds[0], 'f', 1),
788                                 QString::number(thresholds[1], 'f', 1)), -1);
789         }
790
791         int preset_id = base_->get_current_conversion_preset();
792         conv_threshold_cb_->setCurrentIndex(
793                         conv_threshold_cb_->findData(preset_id));
794
795         conv_threshold_cb_->blockSignals(false);
796 }
797
798 vector<data::LogicSegment::EdgePair> AnalogSignal::get_nearest_level_changes(uint64_t sample_pos)
799 {
800         assert(base_);
801         assert(owner_);
802
803         // Return if there's no logic data or we're showing only the analog trace
804         if (!base_->logic_data() || (display_type_ == DisplayAnalog))
805                 return vector<data::LogicSegment::EdgePair>();
806
807         if (sample_pos == 0)
808                 return vector<LogicSegment::EdgePair>();
809
810         shared_ptr<LogicSegment> segment = get_logic_segment_to_paint();
811         if (!segment || (segment->get_sample_count() == 0))
812                 return vector<LogicSegment::EdgePair>();
813
814         const View *view = owner_->view();
815         assert(view);
816         const double samples_per_pixel = base_->get_samplerate() * view->scale();
817
818         vector<LogicSegment::EdgePair> edges;
819
820         segment->get_surrounding_edges(edges, sample_pos,
821                 samples_per_pixel / LogicSignal::Oversampling, 0);
822
823         if (edges.empty())
824                 return vector<LogicSegment::EdgePair>();
825
826         return edges;
827 }
828
829 void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
830 {
831         const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
832                 base_->analog_data()->analog_segments();
833
834         if (segments.empty())
835                 return;
836
837         static double prev_min = 0, prev_max = 0;
838         double min = 0, max = 0;
839
840         for (shared_ptr<pv::data::AnalogSegment> segment : segments) {
841                 pair<double, double> mm = segment->get_min_max();
842                 min = std::min(min, mm.first);
843                 max = std::max(max, mm.second);
844         }
845
846         if ((min == prev_min) && (max == prev_max) && !force_update)
847                 return;
848
849         prev_min = min;
850         prev_max = max;
851
852         // If we're allowed to alter the div assignment...
853         if (!keep_divs) {
854                 // Use all divs for the positive range if there are no negative values
855                 if ((min == 0) && (neg_vdivs_ > 0)) {
856                         pos_vdivs_ += neg_vdivs_;
857                         neg_vdivs_ = 0;
858                 }
859
860                 // Split up the divs if there are negative values but no negative divs
861                 if ((min < 0) && (neg_vdivs_ == 0)) {
862                         neg_vdivs_ = pos_vdivs_ / 2;
863                         pos_vdivs_ -= neg_vdivs_;
864                 }
865         }
866
867         // If there is still no positive div when we need it, add one
868         // (this can happen when pos_vdivs==neg_vdivs==0)
869         if ((max > 0) && (pos_vdivs_ == 0)) {
870                 pos_vdivs_ = 1;
871                 owner_->extents_changed(false, true);
872         }
873
874         // If there is still no negative div when we need it, add one
875         // (this can happen when pos_vdivs was 0 or 1 when trying to split)
876         if ((min < 0) && (neg_vdivs_ == 0)) {
877                 neg_vdivs_ = 1;
878                 owner_->extents_changed(false, true);
879         }
880
881         double min_value_per_div;
882         if ((pos_vdivs_ > 0) && (neg_vdivs_ >  0))
883                 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
884         else if (pos_vdivs_ > 0)
885                 min_value_per_div = max / pos_vdivs_;
886         else
887                 min_value_per_div = -min / neg_vdivs_;
888
889         // Find first scale value that is bigger than the value we need
890         for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
891                 if (get_resolution(i) > min_value_per_div) {
892                         scale_index_ = i;
893                         break;
894                 }
895
896         update_scale();
897 }
898
899 void AnalogSignal::reset_pixel_values()
900 {
901         value_at_pixel_pos_.clear();
902         current_pixel_pos_ = -1;
903         prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
904 }
905
906 void AnalogSignal::process_next_sample_value(float x, float value)
907 {
908         // Note: NAN is used to indicate the non-existance of a value at this pixel
909
910         if (std::isnan(prev_value_at_pixel_)) {
911                 if (x < 0) {
912                         min_value_at_pixel_ = value;
913                         max_value_at_pixel_ = value;
914                         prev_value_at_pixel_ = value;
915                         current_pixel_pos_ = x;
916                 } else
917                         prev_value_at_pixel_ = std::numeric_limits<float>::quiet_NaN();
918         }
919
920         const int pixel_pos = (int)(x + 0.5);
921
922         if (pixel_pos > current_pixel_pos_) {
923                 if (pixel_pos - current_pixel_pos_ == 1) {
924                         if (std::isnan(prev_value_at_pixel_)) {
925                                 value_at_pixel_pos_.push_back(prev_value_at_pixel_);
926                         } else {
927                                 // Average the min/max range to create one value for the previous pixel
928                                 const float avg = (min_value_at_pixel_ + max_value_at_pixel_) / 2;
929                                 value_at_pixel_pos_.push_back(avg);
930                         }
931                 } else {
932                         // Interpolate values to create values for the intermediate pixels
933                         const float start_value = prev_value_at_pixel_;
934                         const float end_value = value;
935                         const int steps = fabs(pixel_pos - current_pixel_pos_);
936                         const double gradient = (end_value - start_value) / steps;
937                         for (int i = 0; i < steps; i++) {
938                                 if (current_pixel_pos_ + i < 0)
939                                         continue;
940                                 value_at_pixel_pos_.push_back(start_value + i * gradient);
941                         }
942                 }
943
944                 min_value_at_pixel_ = value;
945                 max_value_at_pixel_ = value;
946                 prev_value_at_pixel_ = value;
947                 current_pixel_pos_ = pixel_pos;
948         } else {
949                 // Another sample for the same pixel
950                 if (value < min_value_at_pixel_)
951                         min_value_at_pixel_ = value;
952                 if (value > max_value_at_pixel_)
953                         max_value_at_pixel_ = value;
954         }
955 }
956
957 void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
958 {
959         // Add the standard options
960         Signal::populate_popup_form(parent, form);
961
962         QFormLayout *const layout = new QFormLayout;
963
964         // Add div-related settings
965         pvdiv_sb_ = new QSpinBox(parent);
966         pvdiv_sb_->setRange(0, MaximumVDivs);
967         pvdiv_sb_->setValue(pos_vdivs_);
968         connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
969                 this, SLOT(on_pos_vdivs_changed(int)));
970         layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
971
972         nvdiv_sb_ = new QSpinBox(parent);
973         nvdiv_sb_->setRange(0, MaximumVDivs);
974         nvdiv_sb_->setValue(neg_vdivs_);
975         connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
976                 this, SLOT(on_neg_vdivs_changed(int)));
977         layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
978
979         div_height_sb_ = new QSpinBox(parent);
980         div_height_sb_->setRange(20, 1000);
981         div_height_sb_->setSingleStep(5);
982         div_height_sb_->setSuffix(tr(" pixels"));
983         div_height_sb_->setValue(div_height_);
984         connect(div_height_sb_, SIGNAL(valueChanged(int)),
985                 this, SLOT(on_div_height_changed(int)));
986         layout->addRow(tr("Div height"), div_height_sb_);
987
988         // Add the vertical resolution
989         resolution_cb_ = new QComboBox(parent);
990
991         for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
992                 const QString label = QString("%1").arg(get_resolution(i));
993                 resolution_cb_->insertItem(0, label, QVariant(i));
994         }
995
996         int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
997         resolution_cb_->setCurrentIndex(cur_idx);
998
999         connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
1000                 this, SLOT(on_resolution_changed(int)));
1001
1002         QGridLayout *const vdiv_layout = new QGridLayout;
1003         QLabel *const vdiv_unit = new QLabel(tr("V/div"));
1004         vdiv_layout->addWidget(resolution_cb_, 0, 0);
1005         vdiv_layout->addWidget(vdiv_unit, 0, 1);
1006
1007         layout->addRow(tr("Vertical resolution"), vdiv_layout);
1008
1009         // Add the autoranging checkbox
1010         QCheckBox* autoranging_cb = new QCheckBox();
1011         autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
1012
1013         connect(autoranging_cb, SIGNAL(stateChanged(int)),
1014                 this, SLOT(on_autoranging_changed(int)));
1015
1016         layout->addRow(tr("Autoranging"), autoranging_cb);
1017
1018         // Add the conversion type dropdown
1019         conversion_cb_ = new QComboBox();
1020
1021         conversion_cb_->addItem(tr("none"),
1022                 SignalBase::NoConversion);
1023         conversion_cb_->addItem(tr("to logic via threshold"),
1024                 SignalBase::A2LConversionByThreshold);
1025         conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
1026                 SignalBase::A2LConversionBySchmittTrigger);
1027
1028         cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
1029         conversion_cb_->setCurrentIndex(cur_idx);
1030
1031         layout->addRow(tr("Conversion"), conversion_cb_);
1032
1033         connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
1034                 this, SLOT(on_conversion_changed(int)));
1035
1036     // Add the conversion threshold settings
1037     conv_threshold_cb_ = new QComboBox();
1038     conv_threshold_cb_->setEditable(true);
1039
1040     layout->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
1041
1042     connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
1043             this, SLOT(on_conv_threshold_changed(int)));
1044     connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString&)),
1045             this, SLOT(on_conv_threshold_changed()));  // index will be -1
1046
1047         // Add the display type dropdown
1048         display_type_cb_ = new QComboBox();
1049
1050         display_type_cb_->addItem(tr("analog"), DisplayAnalog);
1051         display_type_cb_->addItem(tr("converted"), DisplayConverted);
1052         display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
1053
1054         cur_idx = display_type_cb_->findData(QVariant(display_type_));
1055         display_type_cb_->setCurrentIndex(cur_idx);
1056
1057         layout->addRow(tr("Show traces for"), display_type_cb_);
1058
1059         connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
1060                 this, SLOT(on_display_type_changed(int)));
1061
1062         // Update the conversion widget contents and states
1063         update_conversion_widgets();
1064
1065         form->addRow(layout);
1066 }
1067
1068 void AnalogSignal::hover_point_changed(const QPoint &hp)
1069 {
1070         Signal::hover_point_changed(hp);
1071
1072         // Note: Even though the view area begins at 0, we exclude 0 because
1073         // that's also the value given when the cursor is over the header to the
1074         // left of the trace paint area
1075         if (hp.x() <= 0) {
1076                 value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1077         } else {
1078                 try {
1079                         value_at_hover_pos_ = value_at_pixel_pos_.at(hp.x());
1080                 } catch (out_of_range&) {
1081                         value_at_hover_pos_ = std::numeric_limits<float>::quiet_NaN();
1082                 }
1083         }
1084 }
1085
1086 void AnalogSignal::on_min_max_changed(float min, float max)
1087 {
1088         (void)min;
1089         (void)max;
1090
1091         if (autoranging_)
1092                 perform_autoranging(false, false);
1093 }
1094
1095 void AnalogSignal::on_pos_vdivs_changed(int vdivs)
1096 {
1097         if (vdivs == pos_vdivs_)
1098                 return;
1099
1100         pos_vdivs_ = vdivs;
1101
1102         // There has to be at least one div, positive or negative
1103         if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1104                 pos_vdivs_ = 1;
1105                 if (pvdiv_sb_)
1106                         pvdiv_sb_->setValue(pos_vdivs_);
1107         }
1108
1109         if (autoranging_) {
1110                 perform_autoranging(true, true);
1111
1112                 // It could be that a positive or negative div was added, so update
1113                 if (pvdiv_sb_) {
1114                         pvdiv_sb_->setValue(pos_vdivs_);
1115                         nvdiv_sb_->setValue(neg_vdivs_);
1116                 }
1117         }
1118
1119         if (owner_) {
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);
1123         }
1124 }
1125
1126 void AnalogSignal::on_neg_vdivs_changed(int vdivs)
1127 {
1128         if (vdivs == neg_vdivs_)
1129                 return;
1130
1131         neg_vdivs_ = vdivs;
1132
1133         // There has to be at least one div, positive or negative
1134         if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
1135                 pos_vdivs_ = 1;
1136                 if (pvdiv_sb_)
1137                         pvdiv_sb_->setValue(pos_vdivs_);
1138         }
1139
1140         if (autoranging_) {
1141                 perform_autoranging(true, true);
1142
1143                 // It could be that a positive or negative div was added, so update
1144                 if (pvdiv_sb_) {
1145                         pvdiv_sb_->setValue(pos_vdivs_);
1146                         nvdiv_sb_->setValue(neg_vdivs_);
1147                 }
1148         }
1149
1150         if (owner_) {
1151                 // Call order is important, otherwise the lazy event handler won't work
1152                 owner_->extents_changed(false, true);
1153                 owner_->row_item_appearance_changed(false, true);
1154         }
1155 }
1156
1157 void AnalogSignal::on_div_height_changed(int height)
1158 {
1159         div_height_ = height;
1160         update_scale();
1161
1162         if (owner_) {
1163                 // Call order is important, otherwise the lazy event handler won't work
1164                 owner_->extents_changed(false, true);
1165                 owner_->row_item_appearance_changed(false, true);
1166         }
1167 }
1168
1169 void AnalogSignal::on_resolution_changed(int index)
1170 {
1171         scale_index_ = resolution_cb_->itemData(index).toInt();
1172         update_scale();
1173
1174         if (owner_)
1175                 owner_->row_item_appearance_changed(false, true);
1176 }
1177
1178 void AnalogSignal::on_autoranging_changed(int state)
1179 {
1180         autoranging_ = (state == Qt::Checked);
1181
1182         if (autoranging_)
1183                 perform_autoranging(false, true);
1184
1185         if (owner_) {
1186                 // Call order is important, otherwise the lazy event handler won't work
1187                 owner_->extents_changed(false, true);
1188                 owner_->row_item_appearance_changed(false, true);
1189         }
1190 }
1191
1192 void AnalogSignal::on_conversion_changed(int index)
1193 {
1194         SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
1195
1196         SignalBase::ConversionType conv_type =
1197                 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
1198
1199         if (conv_type != old_conv_type) {
1200                 base_->set_conversion_type(conv_type);
1201                 update_conversion_widgets();
1202
1203                 if (owner_)
1204                         owner_->row_item_appearance_changed(false, true);
1205         }
1206 }
1207
1208 void AnalogSignal::on_conv_threshold_changed(int index)
1209 {
1210         SignalBase::ConversionType conv_type = base_->get_conversion_type();
1211
1212         // Note: index is set to -1 if the text in the combo box matches none of
1213         // the entries in the combo box
1214
1215         if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
1216                 return;
1217
1218         // The combo box entry with the custom value has user_data set to -1
1219         const int user_data = conv_threshold_cb_->findText(
1220                         conv_threshold_cb_->currentText());
1221
1222         const bool use_custom_thr = (index == -1) || (user_data == -1);
1223
1224         if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
1225                 // Not one of the preset values, try to parse the combo box text
1226                 // Note: Regex loosely based on
1227                 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1228                 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1229                 QString re2 = "([a-zA-Z]*)"; // SI unit
1230                 QRegExp regex(re1 + re2);
1231
1232                 const QString text = conv_threshold_cb_->currentText();
1233                 if (!regex.exactMatch(text))
1234                         return;  // String doesn't match the regex
1235
1236                 QStringList tokens = regex.capturedTexts();
1237
1238                 // For now, we simply assume that the unit is volt without modifiers
1239                 const double thr = tokens.at(1).toDouble();
1240
1241                 // Only restart the conversion if the threshold was updated.
1242                 // We're starting a delayed conversion because the user may still be
1243                 // typing and the UI would lag if we kept on restarting it immediately
1244                 if (base_->set_conversion_option("threshold_value", thr))
1245                         base_->start_conversion(true);
1246         }
1247
1248         if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
1249                 // Not one of the preset values, try to parse the combo box text
1250                 // Note: Regex loosely based on
1251                 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1252                 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1253                 QString re2 = "([a-zA-Z]*)"; // SI unit
1254                 QString re3 = "\\/"; // Forward slash, not captured
1255                 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1256                 QString re5 = "([a-zA-Z]*)"; // SI unit
1257                 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1258
1259                 const QString text = conv_threshold_cb_->currentText();
1260                 if (!regex.exactMatch(text))
1261                         return;  // String doesn't match the regex
1262
1263                 QStringList tokens = regex.capturedTexts();
1264
1265                 // For now, we simply assume that the unit is volt without modifiers
1266                 const double low_thr = tokens.at(1).toDouble();
1267                 const double high_thr = tokens.at(3).toDouble();
1268
1269                 // Only restart the conversion if one of the options was updated.
1270                 // We're starting a delayed conversion because the user may still be
1271                 // typing and the UI would lag if we kept on restarting it immediately
1272                 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1273                 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1274                 if (o1 || o2)
1275                         base_->start_conversion(true);  // Start delayed conversion
1276         }
1277
1278         base_->set_conversion_preset((SignalBase::ConversionPreset)index);
1279
1280         // Immediately start the conversion if we're not using custom values
1281         // (i.e. we're using one of the presets)
1282         if (!use_custom_thr)
1283                 base_->start_conversion();
1284 }
1285
1286 void AnalogSignal::on_delayed_conversion_starter()
1287 {
1288         base_->start_conversion();
1289 }
1290
1291 void AnalogSignal::on_display_type_changed(int index)
1292 {
1293         display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1294
1295         if (owner_)
1296                 owner_->row_item_appearance_changed(false, true);
1297 }
1298
1299 void AnalogSignal::on_settingViewConversionThresholdDispMode_changed(const QVariant new_value)
1300 {
1301         conversion_threshold_disp_mode_ = new_value.toInt();
1302
1303         if (owner_)
1304                 owner_->row_item_appearance_changed(false, true);
1305 }
1306
1307 } // namespace trace
1308 } // namespace views
1309 } // namespace pv