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