Convert threshold display setting to a multi-value choice
[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 <QFormLayout>
32 #include <QGridLayout>
33 #include <QLabel>
34 #include <QString>
35
36 #include "analogsignal.hpp"
37 #include "logicsignal.hpp"
38 #include "view.hpp"
39
40 #include "pv/data/analog.hpp"
41 #include "pv/data/analogsegment.hpp"
42 #include "pv/data/logic.hpp"
43 #include "pv/data/logicsegment.hpp"
44 #include "pv/data/signalbase.hpp"
45 #include "pv/globalsettings.hpp"
46
47 #include <libsigrokcxx/libsigrokcxx.hpp>
48
49 using std::bind;
50 using std::deque;
51 using std::div;
52 using std::div_t;
53 using std::max;
54 using std::make_pair;
55 using std::min;
56 using std::numeric_limits;
57 using std::pair;
58 using std::placeholders::_1;
59 using std::shared_ptr;
60 using std::vector;
61
62 using pv::data::SignalBase;
63
64 namespace pv {
65 namespace views {
66 namespace trace {
67
68 const QColor AnalogSignal::SignalColours[4] = {
69         QColor(0xC4, 0xA0, 0x00),       // Yellow
70         QColor(0x87, 0x20, 0x7A),       // Magenta
71         QColor(0x20, 0x4A, 0x87),       // Blue
72         QColor(0x4E, 0x9A, 0x06)        // Green
73 };
74
75 const QPen AnalogSignal::AxisPen(QColor(0, 0, 0, 30 * 256 / 100), 2);
76 const QColor AnalogSignal::GridMajorColor = QColor(0, 0, 0, 40 * 256 / 100);
77 const QColor AnalogSignal::GridMinorColor = QColor(0, 0, 0, 20 * 256 / 100);
78
79 const QColor AnalogSignal::SamplingPointColour(0x77, 0x77, 0x77);
80
81 const QColor AnalogSignal::ThresholdColor = QColor(0, 0, 0, 30 * 256 / 100);
82 const QColor AnalogSignal::ThresholdColorLo = QColor(255, 0, 0, 8 * 256 / 100);
83 const QColor AnalogSignal::ThresholdColorNe = QColor(0,   0, 0, 10 * 256 / 100);
84 const QColor AnalogSignal::ThresholdColorHi = QColor(0, 255, 0, 8 * 256 / 100);
85
86 const int64_t AnalogSignal::TracePaintBlockSize = 1024 * 1024;  // 4 MiB (due to float)
87 const float AnalogSignal::EnvelopeThreshold = 64.0f;
88
89 const int AnalogSignal::MaximumVDivs = 10;
90 const int AnalogSignal::MinScaleIndex = -6;
91 const int AnalogSignal::MaxScaleIndex = 7;
92
93 const int AnalogSignal::InfoTextMarginRight = 20;
94 const int AnalogSignal::InfoTextMarginBottom = 5;
95
96 AnalogSignal::AnalogSignal(
97         pv::Session &session,
98         shared_ptr<data::SignalBase> base) :
99         Signal(session, base),
100         scale_index_(4), // 20 per div
101         scale_index_drag_offset_(0),
102         pos_vdivs_(1),
103         neg_vdivs_(1),
104         resolution_(0),
105         display_type_(DisplayBoth),
106         autoranging_(true)
107 {
108         axis_pen_ = AxisPen;
109
110         pv::data::Analog* analog_data =
111                 dynamic_cast<pv::data::Analog*>(data().get());
112
113         connect(analog_data, SIGNAL(min_max_changed(float, float)),
114                 this, SLOT(on_min_max_changed(float, float)));
115
116         GlobalSettings::register_change_handler(GlobalSettings::Key_View_ConversionThresholdDispMode,
117                 bind(&AnalogSignal::on_settingViewConversionThresholdDispMode_changed, this, _1));
118
119         GlobalSettings gs;
120         conversion_threshold_disp_mode_ =
121                 gs.value(GlobalSettings::Key_View_ConversionThresholdDispMode).toInt();
122
123         div_height_ = gs.value(GlobalSettings::Key_View_DefaultDivHeight).toInt();
124
125         base_->set_colour(SignalColours[base_->index() % countof(SignalColours)]);
126         update_scale();
127 }
128
129 shared_ptr<pv::data::SignalData> AnalogSignal::data() const
130 {
131         return base_->analog_data();
132 }
133
134 void AnalogSignal::save_settings(QSettings &settings) const
135 {
136         settings.setValue("pos_vdivs", pos_vdivs_);
137         settings.setValue("neg_vdivs", neg_vdivs_);
138         settings.setValue("scale_index", scale_index_);
139         settings.setValue("display_type", display_type_);
140         settings.setValue("autoranging", autoranging_);
141         settings.setValue("div_height", div_height_);
142 }
143
144 void AnalogSignal::restore_settings(QSettings &settings)
145 {
146         if (settings.contains("pos_vdivs"))
147                 pos_vdivs_ = settings.value("pos_vdivs").toInt();
148
149         if (settings.contains("neg_vdivs"))
150                 neg_vdivs_ = settings.value("neg_vdivs").toInt();
151
152         if (settings.contains("scale_index")) {
153                 scale_index_ = settings.value("scale_index").toInt();
154                 update_scale();
155         }
156
157         if (settings.contains("display_type"))
158                 display_type_ = (DisplayType)(settings.value("display_type").toInt());
159
160         if (settings.contains("autoranging"))
161                 autoranging_ = settings.value("autoranging").toBool();
162
163         if (settings.contains("div_height")) {
164                 const int old_height = div_height_;
165                 div_height_ = settings.value("div_height").toInt();
166
167                 if ((div_height_ != old_height) && owner_) {
168                         // Call order is important, otherwise the lazy event handler won't work
169                         owner_->extents_changed(false, true);
170                         owner_->row_item_appearance_changed(false, true);
171                 }
172         }
173 }
174
175 pair<int, int> AnalogSignal::v_extents() const
176 {
177         const int ph = pos_vdivs_ * div_height_;
178         const int nh = neg_vdivs_ * div_height_;
179         return make_pair(-ph, nh);
180 }
181
182 int AnalogSignal::scale_handle_offset() const
183 {
184         const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
185
186         return ((scale_index_drag_offset_ - scale_index_) * h / 4) - h / 2;
187 }
188
189 void AnalogSignal::scale_handle_dragged(int offset)
190 {
191         const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
192
193         scale_index_ = scale_index_drag_offset_ - (offset + h / 2) / (h / 4);
194
195         update_scale();
196 }
197
198 void AnalogSignal::scale_handle_drag_release()
199 {
200         scale_index_drag_offset_ = scale_index_;
201         update_scale();
202 }
203
204 void AnalogSignal::paint_back(QPainter &p, ViewItemPaintParams &pp)
205 {
206         if (!base_->enabled())
207                 return;
208
209         bool paint_thr_bg =
210                 conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Background;
211
212         const vector<double> thresholds = base_->get_conversion_thresholds();
213
214         // Only display thresholds if we have some and we show analog samples
215         if ((thresholds.size() > 0) && paint_thr_bg &&
216                 ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth))) {
217
218                 const int visual_y = get_visual_y();
219                 const pair<int, int> extents = v_extents();
220                 const int top = visual_y + extents.first;
221                 const int btm = visual_y + extents.second;
222
223                 // Draw high/neutral/low areas
224                 if (thresholds.size() == 2) {
225                         const double thr_lo = visual_y - thresholds[0] * scale_;
226                         const double thr_hi = visual_y - thresholds[1] * scale_;
227
228                         p.fillRect(QRectF(pp.left(), top, pp.width(), thr_hi - top),
229                                 QBrush(ThresholdColorHi));
230                         p.fillRect(QRectF(pp.left(), thr_hi, pp.width(), thr_lo - thr_hi),
231                                 QBrush(ThresholdColorNe));
232                         p.fillRect(QRectF(pp.left(), thr_lo, pp.width(), btm - thr_lo),
233                                 QBrush(ThresholdColorLo));
234                 } else {
235                         const double thr = visual_y - thresholds[0] * scale_;
236
237                         p.fillRect(QRectF(pp.left(), top, pp.width(), thr - top),
238                                 QBrush(ThresholdColorHi));
239                         p.fillRect(QRectF(pp.left(), thr, pp.width(), btm - thr),
240                                 QBrush(ThresholdColorLo));
241                 }
242
243                 paint_axis(p, pp, get_visual_y());
244         } else {
245                 Trace::paint_back(p, pp);
246                 paint_axis(p, pp, get_visual_y());
247         }
248 }
249
250 void AnalogSignal::paint_mid(QPainter &p, ViewItemPaintParams &pp)
251 {
252         assert(base_->analog_data());
253         assert(owner_);
254
255         const int y = get_visual_y();
256
257         if (!base_->enabled())
258                 return;
259
260         if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
261                 paint_grid(p, y, pp.left(), pp.right());
262
263                 const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
264                         base_->analog_data()->analog_segments();
265                 if (segments.empty())
266                         return;
267
268                 const shared_ptr<pv::data::AnalogSegment> &segment =
269                         segments.front();
270
271                 const double pixels_offset = pp.pixels_offset();
272                 const double samplerate = max(1.0, segment->samplerate());
273                 const pv::util::Timestamp& start_time = segment->start_time();
274                 const int64_t last_sample = segment->get_sample_count() - 1;
275                 const double samples_per_pixel = samplerate * pp.scale();
276                 const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
277                 const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
278
279                 const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
280                         (int64_t)0), last_sample);
281                 const int64_t end_sample = min(max((ceil(end) + 1).convert_to<int64_t>(),
282                         (int64_t)0), last_sample);
283
284                 if (samples_per_pixel < EnvelopeThreshold)
285                         paint_trace(p, segment, y, pp.left(),
286                                 start_sample, end_sample,
287                                 pixels_offset, samples_per_pixel);
288                 else
289                         paint_envelope(p, segment, y, pp.left(),
290                                 start_sample, end_sample,
291                                 pixels_offset, samples_per_pixel);
292         }
293
294         if ((display_type_ == DisplayConverted) || (display_type_ == DisplayBoth))
295                 paint_logic_mid(p, pp);
296 }
297
298 void AnalogSignal::paint_fore(QPainter &p, ViewItemPaintParams &pp)
299 {
300         if (!enabled())
301                 return;
302
303         if ((display_type_ == DisplayAnalog) || (display_type_ == DisplayBoth)) {
304                 const int y = get_visual_y();
305
306                 // Show the info section on the right side of the trace
307                 const QString infotext = QString("%1 V/div").arg(resolution_);
308
309                 p.setPen(base_->colour());
310                 p.setFont(QApplication::font());
311
312                 const QRectF bounding_rect = QRectF(pp.left(),
313                                 y + v_extents().first,
314                                 pp.width() - InfoTextMarginRight,
315                                 v_extents().second - v_extents().first - InfoTextMarginBottom);
316
317                 p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
318         }
319 }
320
321 void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
322 {
323         p.setRenderHint(QPainter::Antialiasing, false);
324
325         GlobalSettings settings;
326         const bool show_analog_minor_grid =
327                 settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
328
329         if (pos_vdivs_ > 0) {
330                 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
331                 for (int i = 1; i <= pos_vdivs_; i++) {
332                         const float dy = i * div_height_;
333                         p.drawLine(QLineF(left, y - dy, right, y - dy));
334                 }
335         }
336
337         if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
338                 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
339                 for (int i = 0; i < pos_vdivs_; i++) {
340                         const float dy = i * div_height_;
341                         const float dy25 = dy + (0.25 * div_height_);
342                         const float dy50 = dy + (0.50 * div_height_);
343                         const float dy75 = dy + (0.75 * div_height_);
344                         p.drawLine(QLineF(left, y - dy25, right, y - dy25));
345                         p.drawLine(QLineF(left, y - dy50, right, y - dy50));
346                         p.drawLine(QLineF(left, y - dy75, right, y - dy75));
347                 }
348         }
349
350         if (neg_vdivs_ > 0) {
351                 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
352                 for (int i = 1; i <= neg_vdivs_; i++) {
353                         const float dy = i * div_height_;
354                         p.drawLine(QLineF(left, y + dy, right, y + dy));
355                 }
356         }
357
358         if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
359                 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
360                 for (int i = 0; i < neg_vdivs_; i++) {
361                         const float dy = i * div_height_;
362                         const float dy25 = dy + (0.25 * div_height_);
363                         const float dy50 = dy + (0.50 * div_height_);
364                         const float dy75 = dy + (0.75 * div_height_);
365                         p.drawLine(QLineF(left, y + dy25, right, y + dy25));
366                         p.drawLine(QLineF(left, y + dy50, right, y + dy50));
367                         p.drawLine(QLineF(left, y + dy75, right, y + dy75));
368                 }
369         }
370
371         p.setRenderHint(QPainter::Antialiasing, true);
372 }
373
374 void AnalogSignal::paint_trace(QPainter &p,
375         const shared_ptr<pv::data::AnalogSegment> &segment,
376         int y, int left, const int64_t start, const int64_t end,
377         const double pixels_offset, const double samples_per_pixel)
378 {
379         if (end <= start)
380                 return;
381
382         // Calculate and paint the sampling points if enabled and useful
383         GlobalSettings settings;
384         const bool show_sampling_points =
385                 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() &&
386                 (samples_per_pixel < 0.25);
387
388         p.setPen(base_->colour());
389
390         const int64_t points_count = end - start;
391
392         QPointF *points = new QPointF[points_count];
393         QPointF *point = points;
394
395         QRectF *sampling_points = nullptr;
396         if (show_sampling_points)
397                  sampling_points = new QRectF[points_count];
398         QRectF *sampling_point = sampling_points;
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         const int w = 2;
406         for (int64_t sample = start; sample != end; sample++, block_sample++) {
407
408                 if (block_sample == TracePaintBlockSize) {
409                         block_sample = 0;
410                         sample_count = min(points_count - sample, TracePaintBlockSize);
411                         segment->get_samples(sample, sample + sample_count, sample_block);
412                 }
413
414                 const float x = (sample / samples_per_pixel -
415                         pixels_offset) + left;
416
417                 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
418
419                 if (show_sampling_points)
420                         *sampling_point++ =
421                                 QRectF(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
422         }
423         delete[] sample_block;
424
425         p.drawPolyline(points, points_count);
426
427         if (show_sampling_points) {
428                 p.setPen(SamplingPointColour);
429                 p.drawRects(sampling_points, points_count);
430                 delete[] sampling_points;
431         }
432
433         delete[] points;
434 }
435
436 void AnalogSignal::paint_envelope(QPainter &p,
437         const shared_ptr<pv::data::AnalogSegment> &segment,
438         int y, int left, const int64_t start, const int64_t end,
439         const double pixels_offset, const double samples_per_pixel)
440 {
441         using pv::data::AnalogSegment;
442
443         AnalogSegment::EnvelopeSection e;
444         segment->get_envelope_section(e, start, end, samples_per_pixel);
445
446         if (e.length < 2)
447                 return;
448
449         p.setPen(QPen(Qt::NoPen));
450         p.setBrush(base_->colour());
451
452         QRectF *const rects = new QRectF[e.length];
453         QRectF *rect = rects;
454
455         for (uint64_t sample = 0; sample < e.length - 1; sample++) {
456                 const float x = ((e.scale * sample + e.start) /
457                         samples_per_pixel - pixels_offset) + left;
458                 const AnalogSegment::EnvelopeSample *const s =
459                         e.samples + sample;
460
461                 // We overlap this sample with the next so that vertical
462                 // gaps do not appear during steep rising or falling edges
463                 const float b = y - max(s->max, (s + 1)->min) * scale_;
464                 const float t = y - min(s->min, (s + 1)->max) * scale_;
465
466                 float h = b - t;
467                 if (h >= 0.0f && h <= 1.0f)
468                         h = 1.0f;
469                 if (h <= 0.0f && h >= -1.0f)
470                         h = -1.0f;
471
472                 *rect++ = QRectF(x, t, 1.0f, h);
473         }
474
475         p.drawRects(rects, e.length);
476
477         delete[] rects;
478         delete[] e.samples;
479 }
480
481 void AnalogSignal::paint_logic_mid(QPainter &p, ViewItemPaintParams &pp)
482 {
483         QLineF *line;
484
485         vector< pair<int64_t, bool> > edges;
486
487         assert(base_);
488
489         const int y = get_visual_y();
490
491         if (!base_->enabled() || !base_->logic_data())
492                 return;
493
494         const int signal_margin =
495                 QFontMetrics(QApplication::font()).height() / 2;
496
497         const int ph = min(pos_vdivs_, 1) * div_height_;
498         const int nh = min(neg_vdivs_, 1) * div_height_;
499         const float high_offset = y - ph + signal_margin + 0.5f;
500         const float low_offset = y + nh - signal_margin - 0.5f;
501
502         const deque< shared_ptr<pv::data::LogicSegment> > &segments =
503                 base_->logic_data()->logic_segments();
504
505         if (segments.empty())
506                 return;
507
508         const shared_ptr<pv::data::LogicSegment> &segment =
509                 segments.front();
510
511         double samplerate = segment->samplerate();
512
513         // Show sample rate as 1Hz when it is unknown
514         if (samplerate == 0.0)
515                 samplerate = 1.0;
516
517         const double pixels_offset = pp.pixels_offset();
518         const pv::util::Timestamp& start_time = segment->start_time();
519         const int64_t last_sample = segment->get_sample_count() - 1;
520         const double samples_per_pixel = samplerate * pp.scale();
521         const double pixels_per_sample = 1 / samples_per_pixel;
522         const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
523         const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
524
525         const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
526                 (int64_t)0), last_sample);
527         const uint64_t end_sample = min(max(ceil(end).convert_to<int64_t>(),
528                 (int64_t)0), last_sample);
529
530         segment->get_subsampled_edges(edges, start_sample, end_sample,
531                 samples_per_pixel / LogicSignal::Oversampling, 0);
532         assert(edges.size() >= 2);
533
534         // Check whether we need to paint the sampling points
535         GlobalSettings settings;
536         const bool show_sampling_points =
537                 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() &&
538                 (samples_per_pixel < 0.25);
539
540         vector<QRectF> sampling_points;
541         float sampling_point_x = 0.0f;
542         int64_t sampling_point_sample = start_sample;
543         const int w = 2;
544
545         if (show_sampling_points) {
546                 sampling_points.reserve(end_sample - start_sample + 1);
547                 sampling_point_x = (edges.cbegin()->first / samples_per_pixel - pixels_offset) + pp.left();
548         }
549
550         // Paint the edges
551         const unsigned int edge_count = edges.size() - 2;
552         QLineF *const edge_lines = new QLineF[edge_count];
553         line = edge_lines;
554
555         for (auto i = edges.cbegin() + 1; i != edges.cend() - 1; i++) {
556                 const float x = ((*i).first / samples_per_pixel -
557                         pixels_offset) + pp.left();
558                 *line++ = QLineF(x, high_offset, x, low_offset);
559
560                 if (show_sampling_points)
561                         while (sampling_point_sample < (*i).first) {
562                                 const float y = (*i).second ? low_offset : high_offset;
563                                 sampling_points.emplace_back(
564                                         QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
565                                 sampling_point_sample++;
566                                 sampling_point_x += pixels_per_sample;
567                         };
568         }
569
570         // Calculate the sample points from the last edge to the end of the trace
571         if (show_sampling_points)
572                 while ((uint64_t)sampling_point_sample <= end_sample) {
573                         // Signal changed after the last edge, so the level is inverted
574                         const float y = (edges.cend() - 1)->second ? high_offset : low_offset;
575                         sampling_points.emplace_back(
576                                 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
577                         sampling_point_sample++;
578                         sampling_point_x += pixels_per_sample;
579                 };
580
581         p.setPen(LogicSignal::EdgeColour);
582         p.drawLines(edge_lines, edge_count);
583         delete[] edge_lines;
584
585         // Paint the caps
586         const unsigned int max_cap_line_count = edges.size();
587         QLineF *const cap_lines = new QLineF[max_cap_line_count];
588
589         p.setPen(LogicSignal::HighColour);
590         paint_logic_caps(p, cap_lines, edges, true, samples_per_pixel,
591                 pixels_offset, pp.left(), high_offset);
592         p.setPen(LogicSignal::LowColour);
593         paint_logic_caps(p, cap_lines, edges, false, samples_per_pixel,
594                 pixels_offset, pp.left(), low_offset);
595
596         delete[] cap_lines;
597
598         // Paint the sampling points
599         if (show_sampling_points) {
600                 p.setPen(SamplingPointColour);
601                 p.drawRects(sampling_points.data(), sampling_points.size());
602         }
603 }
604
605 void AnalogSignal::paint_logic_caps(QPainter &p, QLineF *const lines,
606         vector< pair<int64_t, bool> > &edges, bool level,
607         double samples_per_pixel, double pixels_offset, float x_offset,
608         float y_offset)
609 {
610         QLineF *line = lines;
611
612         for (auto i = edges.begin(); i != (edges.end() - 1); i++)
613                 if ((*i).second == level) {
614                         *line++ = QLineF(
615                                 ((*i).first / samples_per_pixel -
616                                         pixels_offset) + x_offset, y_offset,
617                                 ((*(i+1)).first / samples_per_pixel -
618                                         pixels_offset) + x_offset, y_offset);
619                 }
620
621         p.drawLines(lines, line - lines);
622 }
623
624 float AnalogSignal::get_resolution(int scale_index)
625 {
626         const float seq[] = {1.0f, 2.0f, 5.0f};
627
628         const int offset = numeric_limits<int>::max() / (2 * countof(seq));
629         const div_t d = div((int)(scale_index + countof(seq) * offset),
630                 countof(seq));
631
632         return powf(10.0f, d.quot - offset) * seq[d.rem];
633 }
634
635 void AnalogSignal::update_scale()
636 {
637         resolution_ = get_resolution(scale_index_);
638         scale_ = div_height_ / resolution_;
639 }
640
641 void AnalogSignal::update_conversion_widgets()
642 {
643         SignalBase::ConversionType conv_type = base_->get_conversion_type();
644
645         // Enable or disable widgets depending on conversion state
646         conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
647         display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
648
649         conv_threshold_cb_->clear();
650
651         vector < pair<QString, int> > presets = base_->get_conversion_presets();
652
653         // Prevent the combo box from firing the "edit text changed" signal
654         // as that would involuntarily select the first entry
655         conv_threshold_cb_->blockSignals(true);
656
657         // Set available options depending on chosen conversion
658         for (pair<QString, int> preset : presets)
659                 conv_threshold_cb_->addItem(preset.first, preset.second);
660
661         map < QString, QVariant > options = base_->get_conversion_options();
662
663         if (conv_type == SignalBase::A2LConversionByThreshold) {
664                 const vector<double> thresholds = base_->get_conversion_thresholds(
665                                 SignalBase::A2LConversionByThreshold, true);
666                 conv_threshold_cb_->addItem(
667                                 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
668         }
669
670         if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
671                 const vector<double> thresholds = base_->get_conversion_thresholds(
672                                 SignalBase::A2LConversionBySchmittTrigger, true);
673                 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
674                                 QString::number(thresholds[0], 'f', 1),
675                                 QString::number(thresholds[1], 'f', 1)), -1);
676         }
677
678         int preset_id = base_->get_current_conversion_preset();
679         conv_threshold_cb_->setCurrentIndex(
680                         conv_threshold_cb_->findData(preset_id));
681
682         conv_threshold_cb_->blockSignals(false);
683 }
684
685 void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
686 {
687         const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
688                 base_->analog_data()->analog_segments();
689
690         if (segments.empty())
691                 return;
692
693         static double prev_min = 0, prev_max = 0;
694         double min = 0, max = 0;
695
696         for (shared_ptr<pv::data::AnalogSegment> segment : segments) {
697                 pair<double, double> mm = segment->get_min_max();
698                 min = std::min(min, mm.first);
699                 max = std::max(max, mm.second);
700         }
701
702         if ((min == prev_min) && (max == prev_max) && !force_update)
703                 return;
704
705         prev_min = min;
706         prev_max = max;
707
708         // If we're allowed to alter the div assignment...
709         if (!keep_divs) {
710                 // Use all divs for the positive range if there are no negative values
711                 if ((min == 0) && (neg_vdivs_ > 0)) {
712                         pos_vdivs_ += neg_vdivs_;
713                         neg_vdivs_ = 0;
714                 }
715
716                 // Split up the divs if there are negative values but no negative divs
717                 if ((min < 0) && (neg_vdivs_ == 0)) {
718                         neg_vdivs_ = pos_vdivs_ / 2;
719                         pos_vdivs_ -= neg_vdivs_;
720                 }
721         }
722
723         // If there is still no positive div when we need it, add one
724         // (this can happen when pos_vdivs==neg_vdivs==0)
725         if ((max > 0) && (pos_vdivs_ == 0)) {
726                 pos_vdivs_ = 1;
727                 owner_->extents_changed(false, true);
728         }
729
730         // If there is still no negative div when we need it, add one
731         // (this can happen when pos_vdivs was 0 or 1 when trying to split)
732         if ((min < 0) && (neg_vdivs_ == 0)) {
733                 neg_vdivs_ = 1;
734                 owner_->extents_changed(false, true);
735         }
736
737         double min_value_per_div;
738         if ((pos_vdivs_ > 0) && (neg_vdivs_ >  0))
739                 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
740         else if (pos_vdivs_ > 0)
741                 min_value_per_div = max / pos_vdivs_;
742         else
743                 min_value_per_div = -min / neg_vdivs_;
744
745         // Find first scale value that is bigger than the value we need
746         for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
747                 if (get_resolution(i) > min_value_per_div) {
748                         scale_index_ = i;
749                         break;
750                 }
751
752         update_scale();
753 }
754
755 void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
756 {
757         // Add the standard options
758         Signal::populate_popup_form(parent, form);
759
760         QFormLayout *const layout = new QFormLayout;
761
762         // Add div-related settings
763         pvdiv_sb_ = new QSpinBox(parent);
764         pvdiv_sb_->setRange(0, MaximumVDivs);
765         pvdiv_sb_->setValue(pos_vdivs_);
766         connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
767                 this, SLOT(on_pos_vdivs_changed(int)));
768         layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
769
770         nvdiv_sb_ = new QSpinBox(parent);
771         nvdiv_sb_->setRange(0, MaximumVDivs);
772         nvdiv_sb_->setValue(neg_vdivs_);
773         connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
774                 this, SLOT(on_neg_vdivs_changed(int)));
775         layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
776
777         div_height_sb_ = new QSpinBox(parent);
778         div_height_sb_->setRange(20, 1000);
779         div_height_sb_->setSingleStep(5);
780         div_height_sb_->setSuffix(tr(" pixels"));
781         div_height_sb_->setValue(div_height_);
782         connect(div_height_sb_, SIGNAL(valueChanged(int)),
783                 this, SLOT(on_div_height_changed(int)));
784         layout->addRow(tr("Div height"), div_height_sb_);
785
786         // Add the vertical resolution
787         resolution_cb_ = new QComboBox(parent);
788
789         for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
790                 const QString label = QString("%1").arg(get_resolution(i));
791                 resolution_cb_->insertItem(0, label, QVariant(i));
792         }
793
794         int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
795         resolution_cb_->setCurrentIndex(cur_idx);
796
797         connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
798                 this, SLOT(on_resolution_changed(int)));
799
800         QGridLayout *const vdiv_layout = new QGridLayout;
801         QLabel *const vdiv_unit = new QLabel(tr("V/div"));
802         vdiv_layout->addWidget(resolution_cb_, 0, 0);
803         vdiv_layout->addWidget(vdiv_unit, 0, 1);
804
805         layout->addRow(tr("Vertical resolution"), vdiv_layout);
806
807         // Add the autoranging checkbox
808         QCheckBox* autoranging_cb = new QCheckBox();
809         autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
810
811         connect(autoranging_cb, SIGNAL(stateChanged(int)),
812                 this, SLOT(on_autoranging_changed(int)));
813
814         layout->addRow(tr("Autoranging"), autoranging_cb);
815
816         // Add the conversion type dropdown
817         conversion_cb_ = new QComboBox();
818
819         conversion_cb_->addItem(tr("none"),
820                 SignalBase::NoConversion);
821         conversion_cb_->addItem(tr("to logic via threshold"),
822                 SignalBase::A2LConversionByThreshold);
823         conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
824                 SignalBase::A2LConversionBySchmittTrigger);
825
826         cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
827         conversion_cb_->setCurrentIndex(cur_idx);
828
829         layout->addRow(tr("Conversion"), conversion_cb_);
830
831         connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
832                 this, SLOT(on_conversion_changed(int)));
833
834     // Add the conversion threshold settings
835     conv_threshold_cb_ = new QComboBox();
836     conv_threshold_cb_->setEditable(true);
837
838     layout->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
839
840     connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
841             this, SLOT(on_conv_threshold_changed(int)));
842     connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString)),
843             this, SLOT(on_conv_threshold_changed()));  // index will be -1
844
845         // Add the display type dropdown
846         display_type_cb_ = new QComboBox();
847
848         display_type_cb_->addItem(tr("analog"), DisplayAnalog);
849         display_type_cb_->addItem(tr("converted"), DisplayConverted);
850         display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
851
852         cur_idx = display_type_cb_->findData(QVariant(display_type_));
853         display_type_cb_->setCurrentIndex(cur_idx);
854
855         layout->addRow(tr("Show traces for"), display_type_cb_);
856
857         connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
858                 this, SLOT(on_display_type_changed(int)));
859
860         // Update the conversion widget contents and states
861         update_conversion_widgets();
862
863         form->addRow(layout);
864 }
865
866 void AnalogSignal::on_min_max_changed(float min, float max)
867 {
868         (void)min;
869         (void)max;
870
871         if (autoranging_)
872                 perform_autoranging(false, false);
873 }
874
875 void AnalogSignal::on_pos_vdivs_changed(int vdivs)
876 {
877         if (vdivs == pos_vdivs_)
878                 return;
879
880         pos_vdivs_ = vdivs;
881
882         // There has to be at least one div, positive or negative
883         if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
884                 pos_vdivs_ = 1;
885                 if (pvdiv_sb_)
886                         pvdiv_sb_->setValue(pos_vdivs_);
887         }
888
889         if (autoranging_) {
890                 perform_autoranging(true, true);
891
892                 // It could be that a positive or negative div was added, so update
893                 if (pvdiv_sb_) {
894                         pvdiv_sb_->setValue(pos_vdivs_);
895                         nvdiv_sb_->setValue(neg_vdivs_);
896                 }
897         }
898
899         if (owner_) {
900                 // Call order is important, otherwise the lazy event handler won't work
901                 owner_->extents_changed(false, true);
902                 owner_->row_item_appearance_changed(false, true);
903         }
904 }
905
906 void AnalogSignal::on_neg_vdivs_changed(int vdivs)
907 {
908         if (vdivs == neg_vdivs_)
909                 return;
910
911         neg_vdivs_ = vdivs;
912
913         // There has to be at least one div, positive or negative
914         if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
915                 pos_vdivs_ = 1;
916                 if (pvdiv_sb_)
917                         pvdiv_sb_->setValue(pos_vdivs_);
918         }
919
920         if (autoranging_) {
921                 perform_autoranging(true, true);
922
923                 // It could be that a positive or negative div was added, so update
924                 if (pvdiv_sb_) {
925                         pvdiv_sb_->setValue(pos_vdivs_);
926                         nvdiv_sb_->setValue(neg_vdivs_);
927                 }
928         }
929
930         if (owner_) {
931                 // Call order is important, otherwise the lazy event handler won't work
932                 owner_->extents_changed(false, true);
933                 owner_->row_item_appearance_changed(false, true);
934         }
935 }
936
937 void AnalogSignal::on_div_height_changed(int height)
938 {
939         div_height_ = height;
940         update_scale();
941
942         if (owner_) {
943                 // Call order is important, otherwise the lazy event handler won't work
944                 owner_->extents_changed(false, true);
945                 owner_->row_item_appearance_changed(false, true);
946         }
947 }
948
949 void AnalogSignal::on_resolution_changed(int index)
950 {
951         scale_index_ = resolution_cb_->itemData(index).toInt();
952         update_scale();
953
954         if (owner_)
955                 owner_->row_item_appearance_changed(false, true);
956 }
957
958 void AnalogSignal::on_autoranging_changed(int state)
959 {
960         autoranging_ = (state == Qt::Checked);
961
962         if (autoranging_)
963                 perform_autoranging(false, true);
964
965         if (owner_) {
966                 // Call order is important, otherwise the lazy event handler won't work
967                 owner_->extents_changed(false, true);
968                 owner_->row_item_appearance_changed(false, true);
969         }
970 }
971
972 void AnalogSignal::on_conversion_changed(int index)
973 {
974         SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
975
976         SignalBase::ConversionType conv_type =
977                 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
978
979         if (conv_type != old_conv_type) {
980                 base_->set_conversion_type(conv_type);
981                 update_conversion_widgets();
982
983                 if (owner_)
984                         owner_->row_item_appearance_changed(false, true);
985         }
986 }
987
988 void AnalogSignal::on_conv_threshold_changed(int index)
989 {
990         SignalBase::ConversionType conv_type = base_->get_conversion_type();
991
992         // Note: index is set to -1 if the text in the combo box matches none of
993         // the entries in the combo box
994
995         if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
996                 return;
997
998         // The combo box entry with the custom value has user_data set to -1
999         const int user_data = conv_threshold_cb_->findText(
1000                         conv_threshold_cb_->currentText());
1001
1002         const bool use_custom_thr = (index == -1) || (user_data == -1);
1003
1004         if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
1005                 // Not one of the preset values, try to parse the combo box text
1006                 // Note: Regex loosely based on
1007                 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1008                 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1009                 QString re2 = "([a-zA-Z]*)"; // SI unit
1010                 QRegExp regex(re1 + re2);
1011
1012                 const QString text = conv_threshold_cb_->currentText();
1013                 if (!regex.exactMatch(text))
1014                         return;  // String doesn't match the regex
1015
1016                 QStringList tokens = regex.capturedTexts();
1017
1018                 // For now, we simply assume that the unit is volt without modifiers
1019                 const double thr = tokens.at(1).toDouble();
1020
1021                 // Only restart the conversion if the threshold was updated.
1022                 // We're starting a delayed conversion because the user may still be
1023                 // typing and the UI would lag if we kept on restarting it immediately
1024                 if (base_->set_conversion_option("threshold_value", thr))
1025                         base_->start_conversion(true);
1026         }
1027
1028         if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
1029                 // Not one of the preset values, try to parse the combo box text
1030                 // Note: Regex loosely based on
1031                 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1032                 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1033                 QString re2 = "([a-zA-Z]*)"; // SI unit
1034                 QString re3 = "\\/"; // Forward slash, not captured
1035                 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1036                 QString re5 = "([a-zA-Z]*)"; // SI unit
1037                 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1038
1039                 const QString text = conv_threshold_cb_->currentText();
1040                 if (!regex.exactMatch(text))
1041                         return;  // String doesn't match the regex
1042
1043                 QStringList tokens = regex.capturedTexts();
1044
1045                 // For now, we simply assume that the unit is volt without modifiers
1046                 const double low_thr = tokens.at(1).toDouble();
1047                 const double high_thr = tokens.at(3).toDouble();
1048
1049                 // Only restart the conversion if one of the options was updated.
1050                 // We're starting a delayed conversion because the user may still be
1051                 // typing and the UI would lag if we kept on restarting it immediately
1052                 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1053                 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1054                 if (o1 || o2)
1055                         base_->start_conversion(true);  // Start delayed conversion
1056         }
1057
1058         base_->set_conversion_preset((SignalBase::ConversionPreset)index);
1059
1060         // Immediately start the conversion if we're not using custom values
1061         // (i.e. we're using one of the presets)
1062         if (!use_custom_thr)
1063                 base_->start_conversion();
1064 }
1065
1066 void AnalogSignal::on_delayed_conversion_starter()
1067 {
1068         base_->start_conversion();
1069 }
1070
1071 void AnalogSignal::on_display_type_changed(int index)
1072 {
1073         display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1074
1075         if (owner_)
1076                 owner_->row_item_appearance_changed(false, true);
1077 }
1078
1079 void AnalogSignal::on_settingViewConversionThresholdDispMode_changed(const QVariant new_value)
1080 {
1081         conversion_threshold_disp_mode_ = new_value.toInt();
1082
1083         if (owner_)
1084                 owner_->row_item_appearance_changed(false, true);
1085 }
1086
1087 } // namespace trace
1088 } // namespace views
1089 } // namespace pv