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