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