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