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