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