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