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