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