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