]> sigrok.org Git - pulseview.git/blob - pv/views/trace/analogsignal.cpp
Implement segment display mode handling and update notifications
[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                         try {
663                                 segment = segments.at(current_segment_);
664                         } catch (out_of_range) {
665                                 qDebug() << "Current analog segment out of range for signal" << base_->name();
666                         }
667                 }
668         }
669
670         return segment;
671 }
672
673 shared_ptr<pv::data::LogicSegment> AnalogSignal::get_logic_segment_to_paint() const
674 {
675         shared_ptr<pv::data::LogicSegment> segment;
676
677         const deque< shared_ptr<pv::data::LogicSegment> > &segments =
678                 base_->logic_data()->logic_segments();
679
680         if (!segments.empty()) {
681                 if (segment_display_mode_ == ShowLastSegmentOnly)
682                         segment = segments.back();
683
684                 if (segment_display_mode_ == ShowSingleSegmentOnly) {
685                         try {
686                                 segment = segments.at(current_segment_);
687                         } catch (out_of_range) {
688                                 qDebug() << "Current logic segment out of range for signal" << base_->name();
689                         }
690                 }
691         }
692
693         return segment;
694 }
695
696 float AnalogSignal::get_resolution(int scale_index)
697 {
698         const float seq[] = {1.0f, 2.0f, 5.0f};
699
700         const int offset = numeric_limits<int>::max() / (2 * countof(seq));
701         const div_t d = div((int)(scale_index + countof(seq) * offset),
702                 countof(seq));
703
704         return powf(10.0f, d.quot - offset) * seq[d.rem];
705 }
706
707 void AnalogSignal::update_scale()
708 {
709         resolution_ = get_resolution(scale_index_);
710         scale_ = div_height_ / resolution_;
711 }
712
713 void AnalogSignal::update_conversion_widgets()
714 {
715         SignalBase::ConversionType conv_type = base_->get_conversion_type();
716
717         // Enable or disable widgets depending on conversion state
718         conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
719         display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
720
721         conv_threshold_cb_->clear();
722
723         vector < pair<QString, int> > presets = base_->get_conversion_presets();
724
725         // Prevent the combo box from firing the "edit text changed" signal
726         // as that would involuntarily select the first entry
727         conv_threshold_cb_->blockSignals(true);
728
729         // Set available options depending on chosen conversion
730         for (pair<QString, int> preset : presets)
731                 conv_threshold_cb_->addItem(preset.first, preset.second);
732
733         map < QString, QVariant > options = base_->get_conversion_options();
734
735         if (conv_type == SignalBase::A2LConversionByThreshold) {
736                 const vector<double> thresholds = base_->get_conversion_thresholds(
737                                 SignalBase::A2LConversionByThreshold, true);
738                 conv_threshold_cb_->addItem(
739                                 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
740         }
741
742         if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
743                 const vector<double> thresholds = base_->get_conversion_thresholds(
744                                 SignalBase::A2LConversionBySchmittTrigger, true);
745                 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
746                                 QString::number(thresholds[0], 'f', 1),
747                                 QString::number(thresholds[1], 'f', 1)), -1);
748         }
749
750         int preset_id = base_->get_current_conversion_preset();
751         conv_threshold_cb_->setCurrentIndex(
752                         conv_threshold_cb_->findData(preset_id));
753
754         conv_threshold_cb_->blockSignals(false);
755 }
756
757 void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
758 {
759         const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
760                 base_->analog_data()->analog_segments();
761
762         if (segments.empty())
763                 return;
764
765         static double prev_min = 0, prev_max = 0;
766         double min = 0, max = 0;
767
768         for (shared_ptr<pv::data::AnalogSegment> segment : segments) {
769                 pair<double, double> mm = segment->get_min_max();
770                 min = std::min(min, mm.first);
771                 max = std::max(max, mm.second);
772         }
773
774         if ((min == prev_min) && (max == prev_max) && !force_update)
775                 return;
776
777         prev_min = min;
778         prev_max = max;
779
780         // If we're allowed to alter the div assignment...
781         if (!keep_divs) {
782                 // Use all divs for the positive range if there are no negative values
783                 if ((min == 0) && (neg_vdivs_ > 0)) {
784                         pos_vdivs_ += neg_vdivs_;
785                         neg_vdivs_ = 0;
786                 }
787
788                 // Split up the divs if there are negative values but no negative divs
789                 if ((min < 0) && (neg_vdivs_ == 0)) {
790                         neg_vdivs_ = pos_vdivs_ / 2;
791                         pos_vdivs_ -= neg_vdivs_;
792                 }
793         }
794
795         // If there is still no positive div when we need it, add one
796         // (this can happen when pos_vdivs==neg_vdivs==0)
797         if ((max > 0) && (pos_vdivs_ == 0)) {
798                 pos_vdivs_ = 1;
799                 owner_->extents_changed(false, true);
800         }
801
802         // If there is still no negative div when we need it, add one
803         // (this can happen when pos_vdivs was 0 or 1 when trying to split)
804         if ((min < 0) && (neg_vdivs_ == 0)) {
805                 neg_vdivs_ = 1;
806                 owner_->extents_changed(false, true);
807         }
808
809         double min_value_per_div;
810         if ((pos_vdivs_ > 0) && (neg_vdivs_ >  0))
811                 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
812         else if (pos_vdivs_ > 0)
813                 min_value_per_div = max / pos_vdivs_;
814         else
815                 min_value_per_div = -min / neg_vdivs_;
816
817         // Find first scale value that is bigger than the value we need
818         for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
819                 if (get_resolution(i) > min_value_per_div) {
820                         scale_index_ = i;
821                         break;
822                 }
823
824         update_scale();
825 }
826
827 void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
828 {
829         // Add the standard options
830         Signal::populate_popup_form(parent, form);
831
832         QFormLayout *const layout = new QFormLayout;
833
834         // Add div-related settings
835         pvdiv_sb_ = new QSpinBox(parent);
836         pvdiv_sb_->setRange(0, MaximumVDivs);
837         pvdiv_sb_->setValue(pos_vdivs_);
838         connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
839                 this, SLOT(on_pos_vdivs_changed(int)));
840         layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
841
842         nvdiv_sb_ = new QSpinBox(parent);
843         nvdiv_sb_->setRange(0, MaximumVDivs);
844         nvdiv_sb_->setValue(neg_vdivs_);
845         connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
846                 this, SLOT(on_neg_vdivs_changed(int)));
847         layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
848
849         div_height_sb_ = new QSpinBox(parent);
850         div_height_sb_->setRange(20, 1000);
851         div_height_sb_->setSingleStep(5);
852         div_height_sb_->setSuffix(tr(" pixels"));
853         div_height_sb_->setValue(div_height_);
854         connect(div_height_sb_, SIGNAL(valueChanged(int)),
855                 this, SLOT(on_div_height_changed(int)));
856         layout->addRow(tr("Div height"), div_height_sb_);
857
858         // Add the vertical resolution
859         resolution_cb_ = new QComboBox(parent);
860
861         for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
862                 const QString label = QString("%1").arg(get_resolution(i));
863                 resolution_cb_->insertItem(0, label, QVariant(i));
864         }
865
866         int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
867         resolution_cb_->setCurrentIndex(cur_idx);
868
869         connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
870                 this, SLOT(on_resolution_changed(int)));
871
872         QGridLayout *const vdiv_layout = new QGridLayout;
873         QLabel *const vdiv_unit = new QLabel(tr("V/div"));
874         vdiv_layout->addWidget(resolution_cb_, 0, 0);
875         vdiv_layout->addWidget(vdiv_unit, 0, 1);
876
877         layout->addRow(tr("Vertical resolution"), vdiv_layout);
878
879         // Add the autoranging checkbox
880         QCheckBox* autoranging_cb = new QCheckBox();
881         autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
882
883         connect(autoranging_cb, SIGNAL(stateChanged(int)),
884                 this, SLOT(on_autoranging_changed(int)));
885
886         layout->addRow(tr("Autoranging"), autoranging_cb);
887
888         // Add the conversion type dropdown
889         conversion_cb_ = new QComboBox();
890
891         conversion_cb_->addItem(tr("none"),
892                 SignalBase::NoConversion);
893         conversion_cb_->addItem(tr("to logic via threshold"),
894                 SignalBase::A2LConversionByThreshold);
895         conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
896                 SignalBase::A2LConversionBySchmittTrigger);
897
898         cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
899         conversion_cb_->setCurrentIndex(cur_idx);
900
901         layout->addRow(tr("Conversion"), conversion_cb_);
902
903         connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
904                 this, SLOT(on_conversion_changed(int)));
905
906     // Add the conversion threshold settings
907     conv_threshold_cb_ = new QComboBox();
908     conv_threshold_cb_->setEditable(true);
909
910     layout->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
911
912     connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
913             this, SLOT(on_conv_threshold_changed(int)));
914     connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString)),
915             this, SLOT(on_conv_threshold_changed()));  // index will be -1
916
917         // Add the display type dropdown
918         display_type_cb_ = new QComboBox();
919
920         display_type_cb_->addItem(tr("analog"), DisplayAnalog);
921         display_type_cb_->addItem(tr("converted"), DisplayConverted);
922         display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
923
924         cur_idx = display_type_cb_->findData(QVariant(display_type_));
925         display_type_cb_->setCurrentIndex(cur_idx);
926
927         layout->addRow(tr("Show traces for"), display_type_cb_);
928
929         connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
930                 this, SLOT(on_display_type_changed(int)));
931
932         // Update the conversion widget contents and states
933         update_conversion_widgets();
934
935         form->addRow(layout);
936 }
937
938 void AnalogSignal::on_min_max_changed(float min, float max)
939 {
940         (void)min;
941         (void)max;
942
943         if (autoranging_)
944                 perform_autoranging(false, false);
945 }
946
947 void AnalogSignal::on_pos_vdivs_changed(int vdivs)
948 {
949         if (vdivs == pos_vdivs_)
950                 return;
951
952         pos_vdivs_ = vdivs;
953
954         // There has to be at least one div, positive or negative
955         if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
956                 pos_vdivs_ = 1;
957                 if (pvdiv_sb_)
958                         pvdiv_sb_->setValue(pos_vdivs_);
959         }
960
961         if (autoranging_) {
962                 perform_autoranging(true, true);
963
964                 // It could be that a positive or negative div was added, so update
965                 if (pvdiv_sb_) {
966                         pvdiv_sb_->setValue(pos_vdivs_);
967                         nvdiv_sb_->setValue(neg_vdivs_);
968                 }
969         }
970
971         if (owner_) {
972                 // Call order is important, otherwise the lazy event handler won't work
973                 owner_->extents_changed(false, true);
974                 owner_->row_item_appearance_changed(false, true);
975         }
976 }
977
978 void AnalogSignal::on_neg_vdivs_changed(int vdivs)
979 {
980         if (vdivs == neg_vdivs_)
981                 return;
982
983         neg_vdivs_ = vdivs;
984
985         // There has to be at least one div, positive or negative
986         if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
987                 pos_vdivs_ = 1;
988                 if (pvdiv_sb_)
989                         pvdiv_sb_->setValue(pos_vdivs_);
990         }
991
992         if (autoranging_) {
993                 perform_autoranging(true, true);
994
995                 // It could be that a positive or negative div was added, so update
996                 if (pvdiv_sb_) {
997                         pvdiv_sb_->setValue(pos_vdivs_);
998                         nvdiv_sb_->setValue(neg_vdivs_);
999                 }
1000         }
1001
1002         if (owner_) {
1003                 // Call order is important, otherwise the lazy event handler won't work
1004                 owner_->extents_changed(false, true);
1005                 owner_->row_item_appearance_changed(false, true);
1006         }
1007 }
1008
1009 void AnalogSignal::on_div_height_changed(int height)
1010 {
1011         div_height_ = height;
1012         update_scale();
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_resolution_changed(int index)
1022 {
1023         scale_index_ = resolution_cb_->itemData(index).toInt();
1024         update_scale();
1025
1026         if (owner_)
1027                 owner_->row_item_appearance_changed(false, true);
1028 }
1029
1030 void AnalogSignal::on_autoranging_changed(int state)
1031 {
1032         autoranging_ = (state == Qt::Checked);
1033
1034         if (autoranging_)
1035                 perform_autoranging(false, true);
1036
1037         if (owner_) {
1038                 // Call order is important, otherwise the lazy event handler won't work
1039                 owner_->extents_changed(false, true);
1040                 owner_->row_item_appearance_changed(false, true);
1041         }
1042 }
1043
1044 void AnalogSignal::on_conversion_changed(int index)
1045 {
1046         SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
1047
1048         SignalBase::ConversionType conv_type =
1049                 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
1050
1051         if (conv_type != old_conv_type) {
1052                 base_->set_conversion_type(conv_type);
1053                 update_conversion_widgets();
1054
1055                 if (owner_)
1056                         owner_->row_item_appearance_changed(false, true);
1057         }
1058 }
1059
1060 void AnalogSignal::on_conv_threshold_changed(int index)
1061 {
1062         SignalBase::ConversionType conv_type = base_->get_conversion_type();
1063
1064         // Note: index is set to -1 if the text in the combo box matches none of
1065         // the entries in the combo box
1066
1067         if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
1068                 return;
1069
1070         // The combo box entry with the custom value has user_data set to -1
1071         const int user_data = conv_threshold_cb_->findText(
1072                         conv_threshold_cb_->currentText());
1073
1074         const bool use_custom_thr = (index == -1) || (user_data == -1);
1075
1076         if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
1077                 // Not one of the preset values, try to parse the combo box text
1078                 // Note: Regex loosely based on
1079                 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1080                 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1081                 QString re2 = "([a-zA-Z]*)"; // SI unit
1082                 QRegExp regex(re1 + re2);
1083
1084                 const QString text = conv_threshold_cb_->currentText();
1085                 if (!regex.exactMatch(text))
1086                         return;  // String doesn't match the regex
1087
1088                 QStringList tokens = regex.capturedTexts();
1089
1090                 // For now, we simply assume that the unit is volt without modifiers
1091                 const double thr = tokens.at(1).toDouble();
1092
1093                 // Only restart the conversion if the threshold was updated.
1094                 // We're starting a delayed conversion because the user may still be
1095                 // typing and the UI would lag if we kept on restarting it immediately
1096                 if (base_->set_conversion_option("threshold_value", thr))
1097                         base_->start_conversion(true);
1098         }
1099
1100         if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
1101                 // Not one of the preset values, try to parse the combo box text
1102                 // Note: Regex loosely based on
1103                 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1104                 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1105                 QString re2 = "([a-zA-Z]*)"; // SI unit
1106                 QString re3 = "\\/"; // Forward slash, not captured
1107                 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1108                 QString re5 = "([a-zA-Z]*)"; // SI unit
1109                 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1110
1111                 const QString text = conv_threshold_cb_->currentText();
1112                 if (!regex.exactMatch(text))
1113                         return;  // String doesn't match the regex
1114
1115                 QStringList tokens = regex.capturedTexts();
1116
1117                 // For now, we simply assume that the unit is volt without modifiers
1118                 const double low_thr = tokens.at(1).toDouble();
1119                 const double high_thr = tokens.at(3).toDouble();
1120
1121                 // Only restart the conversion if one of the options was updated.
1122                 // We're starting a delayed conversion because the user may still be
1123                 // typing and the UI would lag if we kept on restarting it immediately
1124                 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1125                 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1126                 if (o1 || o2)
1127                         base_->start_conversion(true);  // Start delayed conversion
1128         }
1129
1130         base_->set_conversion_preset((SignalBase::ConversionPreset)index);
1131
1132         // Immediately start the conversion if we're not using custom values
1133         // (i.e. we're using one of the presets)
1134         if (!use_custom_thr)
1135                 base_->start_conversion();
1136 }
1137
1138 void AnalogSignal::on_delayed_conversion_starter()
1139 {
1140         base_->start_conversion();
1141 }
1142
1143 void AnalogSignal::on_display_type_changed(int index)
1144 {
1145         display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1146
1147         if (owner_)
1148                 owner_->row_item_appearance_changed(false, true);
1149 }
1150
1151 void AnalogSignal::on_settingViewConversionThresholdDispMode_changed(const QVariant new_value)
1152 {
1153         conversion_threshold_disp_mode_ = new_value.toInt();
1154
1155         if (owner_)
1156                 owner_->row_item_appearance_changed(false, true);
1157 }
1158
1159 } // namespace trace
1160 } // namespace views
1161 } // namespace pv