DecodeTrace: Speed up painting by not copying the annotations
[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::add_change_handler(this);
120
121         GlobalSettings gs;
122         conversion_threshold_disp_mode_ =
123                 gs.value(GlobalSettings::Key_View_ConversionThresholdDispMode).toInt();
124
125         div_height_ = gs.value(GlobalSettings::Key_View_DefaultDivHeight).toInt();
126
127         base_->set_color(SignalColors[base_->index() % countof(SignalColors)]);
128         update_scale();
129 }
130
131 AnalogSignal::~AnalogSignal()
132 {
133         GlobalSettings::remove_change_handler(this);
134 }
135
136 shared_ptr<pv::data::SignalData> AnalogSignal::data() const
137 {
138         return base_->analog_data();
139 }
140
141 void AnalogSignal::save_settings(QSettings &settings) const
142 {
143         settings.setValue("pos_vdivs", pos_vdivs_);
144         settings.setValue("neg_vdivs", neg_vdivs_);
145         settings.setValue("scale_index", scale_index_);
146         settings.setValue("display_type", display_type_);
147         settings.setValue("autoranging", autoranging_);
148         settings.setValue("div_height", div_height_);
149 }
150
151 void AnalogSignal::restore_settings(QSettings &settings)
152 {
153         if (settings.contains("pos_vdivs"))
154                 pos_vdivs_ = settings.value("pos_vdivs").toInt();
155
156         if (settings.contains("neg_vdivs"))
157                 neg_vdivs_ = settings.value("neg_vdivs").toInt();
158
159         if (settings.contains("scale_index")) {
160                 scale_index_ = settings.value("scale_index").toInt();
161                 update_scale();
162         }
163
164         if (settings.contains("display_type"))
165                 display_type_ = (DisplayType)(settings.value("display_type").toInt());
166
167         if (settings.contains("autoranging"))
168                 autoranging_ = settings.value("autoranging").toBool();
169
170         if (settings.contains("div_height")) {
171                 const int old_height = div_height_;
172                 div_height_ = settings.value("div_height").toInt();
173
174                 if ((div_height_ != old_height) && owner_) {
175                         // Call order is important, otherwise the lazy event handler won't work
176                         owner_->extents_changed(false, true);
177                         owner_->row_item_appearance_changed(false, true);
178                 }
179         }
180 }
181
182 pair<int, int> AnalogSignal::v_extents() const
183 {
184         const int ph = pos_vdivs_ * div_height_;
185         const int nh = neg_vdivs_ * div_height_;
186         return make_pair(-ph, nh);
187 }
188
189 int AnalogSignal::scale_handle_offset() const
190 {
191         const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
192
193         return ((scale_index_drag_offset_ - scale_index_) * h / 4) - h / 2;
194 }
195
196 void AnalogSignal::scale_handle_dragged(int offset)
197 {
198         const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
199
200         scale_index_ = scale_index_drag_offset_ - (offset + h / 2) / (h / 4);
201
202         update_scale();
203 }
204
205 void AnalogSignal::scale_handle_drag_release()
206 {
207         scale_index_drag_offset_ = scale_index_;
208         update_scale();
209 }
210
211 void AnalogSignal::on_setting_changed(const QString &key, const QVariant &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
333 void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
334 {
335         p.setRenderHint(QPainter::Antialiasing, false);
336
337         GlobalSettings settings;
338         const bool show_analog_minor_grid =
339                 settings.value(GlobalSettings::Key_View_ShowAnalogMinorGrid).toBool();
340
341         if (pos_vdivs_ > 0) {
342                 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
343                 for (int i = 1; i <= pos_vdivs_; i++) {
344                         const float dy = i * div_height_;
345                         p.drawLine(QLineF(left, y - dy, right, y - dy));
346                 }
347         }
348
349         if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
350                 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
351                 for (int i = 0; i < pos_vdivs_; i++) {
352                         const float dy = i * div_height_;
353                         const float dy25 = dy + (0.25 * div_height_);
354                         const float dy50 = dy + (0.50 * div_height_);
355                         const float dy75 = dy + (0.75 * div_height_);
356                         p.drawLine(QLineF(left, y - dy25, right, y - dy25));
357                         p.drawLine(QLineF(left, y - dy50, right, y - dy50));
358                         p.drawLine(QLineF(left, y - dy75, right, y - dy75));
359                 }
360         }
361
362         if (neg_vdivs_ > 0) {
363                 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
364                 for (int i = 1; i <= neg_vdivs_; i++) {
365                         const float dy = i * div_height_;
366                         p.drawLine(QLineF(left, y + dy, right, y + dy));
367                 }
368         }
369
370         if ((pos_vdivs_ > 0) && show_analog_minor_grid) {
371                 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
372                 for (int i = 0; i < neg_vdivs_; i++) {
373                         const float dy = i * div_height_;
374                         const float dy25 = dy + (0.25 * div_height_);
375                         const float dy50 = dy + (0.50 * div_height_);
376                         const float dy75 = dy + (0.75 * div_height_);
377                         p.drawLine(QLineF(left, y + dy25, right, y + dy25));
378                         p.drawLine(QLineF(left, y + dy50, right, y + dy50));
379                         p.drawLine(QLineF(left, y + dy75, right, y + dy75));
380                 }
381         }
382
383         p.setRenderHint(QPainter::Antialiasing, true);
384 }
385
386 void AnalogSignal::paint_trace(QPainter &p,
387         const shared_ptr<pv::data::AnalogSegment> &segment,
388         int y, int left, const int64_t start, const int64_t end,
389         const double pixels_offset, const double samples_per_pixel)
390 {
391         if (end <= start)
392                 return;
393
394         bool paint_thr_dots =
395                 (base_->get_conversion_type() != data::SignalBase::NoConversion) &&
396                 (conversion_threshold_disp_mode_ == GlobalSettings::ConvThrDispMode_Dots);
397
398         vector<double> thresholds;
399         if (paint_thr_dots)
400                 thresholds = base_->get_conversion_thresholds();
401
402         // Calculate and paint the sampling points if enabled and useful
403         GlobalSettings settings;
404         const bool show_sampling_points =
405                 (settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() ||
406                 paint_thr_dots) && (samples_per_pixel < 0.25);
407
408         p.setPen(base_->color());
409
410         const int64_t points_count = end - start;
411
412         QPointF *points = new QPointF[points_count];
413         QPointF *point = points;
414
415         vector<QRectF> sampling_points[3];
416
417         int64_t sample_count = min(points_count, TracePaintBlockSize);
418         int64_t block_sample = 0;
419         float *sample_block = new float[TracePaintBlockSize];
420         segment->get_samples(start, start + sample_count, sample_block);
421
422         const int w = 2;
423         for (int64_t sample = start; sample != end; sample++, block_sample++) {
424
425                 if (block_sample == TracePaintBlockSize) {
426                         block_sample = 0;
427                         sample_count = min(points_count - sample, TracePaintBlockSize);
428                         segment->get_samples(sample, sample + sample_count, sample_block);
429                 }
430
431                 const float x = (sample / samples_per_pixel -
432                         pixels_offset) + left;
433
434                 *point++ = QPointF(x, y - sample_block[block_sample] * scale_);
435
436                 if (show_sampling_points) {
437                         int idx = 0;  // Neutral
438
439                         if (paint_thr_dots) {
440                                 if (thresholds.size() == 1)
441                                         idx = (sample_block[block_sample] >= thresholds[0]) ? 2 : 1;
442                                 else if (thresholds.size() == 2) {
443                                         if (sample_block[block_sample] > thresholds[1])
444                                                 idx = 2;  // High
445                                         else if (sample_block[block_sample] < thresholds[0])
446                                                 idx = 1;  // Low
447                                 }
448                         }
449
450                         sampling_points[idx].emplace_back(x - (w / 2), y - sample_block[block_sample] * scale_ - (w / 2), w, w);
451                 }
452         }
453         delete[] sample_block;
454
455         p.drawPolyline(points, points_count);
456
457         if (show_sampling_points) {
458                 if (paint_thr_dots) {
459                         p.setPen(SamplingPointColorNe);
460                         p.drawRects(sampling_points[0].data(), sampling_points[0].size());
461                         p.setPen(SamplingPointColorLo);
462                         p.drawRects(sampling_points[1].data(), sampling_points[1].size());
463                         p.setPen(SamplingPointColorHi);
464                         p.drawRects(sampling_points[2].data(), sampling_points[2].size());
465                 } else {
466                         p.setPen(SamplingPointColor);
467                         p.drawRects(sampling_points[0].data(), sampling_points[0].size());
468                 }
469         }
470
471         delete[] points;
472 }
473
474 void AnalogSignal::paint_envelope(QPainter &p,
475         const shared_ptr<pv::data::AnalogSegment> &segment,
476         int y, int left, const int64_t start, const int64_t end,
477         const double pixels_offset, const double samples_per_pixel)
478 {
479         using pv::data::AnalogSegment;
480
481         AnalogSegment::EnvelopeSection e;
482         segment->get_envelope_section(e, start, end, samples_per_pixel);
483
484         if (e.length < 2)
485                 return;
486
487         p.setPen(QPen(Qt::NoPen));
488         p.setBrush(base_->color());
489
490         QRectF *const rects = new QRectF[e.length];
491         QRectF *rect = rects;
492
493         for (uint64_t sample = 0; sample < e.length - 1; sample++) {
494                 const float x = ((e.scale * sample + e.start) /
495                         samples_per_pixel - pixels_offset) + left;
496                 const AnalogSegment::EnvelopeSample *const s =
497                         e.samples + sample;
498
499                 // We overlap this sample with the next so that vertical
500                 // gaps do not appear during steep rising or falling edges
501                 const float b = y - max(s->max, (s + 1)->min) * scale_;
502                 const float t = y - min(s->min, (s + 1)->max) * scale_;
503
504                 float h = b - t;
505                 if (h >= 0.0f && h <= 1.0f)
506                         h = 1.0f;
507                 if (h <= 0.0f && h >= -1.0f)
508                         h = -1.0f;
509
510                 *rect++ = QRectF(x, t, 1.0f, h);
511         }
512
513         p.drawRects(rects, e.length);
514
515         delete[] rects;
516         delete[] e.samples;
517 }
518
519 void AnalogSignal::paint_logic_mid(QPainter &p, ViewItemPaintParams &pp)
520 {
521         QLineF *line;
522
523         vector< pair<int64_t, bool> > edges;
524
525         assert(base_);
526
527         const int y = get_visual_y();
528
529         if (!base_->enabled() || !base_->logic_data())
530                 return;
531
532         const int signal_margin =
533                 QFontMetrics(QApplication::font()).height() / 2;
534
535         const int ph = min(pos_vdivs_, 1) * div_height_;
536         const int nh = min(neg_vdivs_, 1) * div_height_;
537         const float high_offset = y - ph + signal_margin + 0.5f;
538         const float low_offset = y + nh - signal_margin - 0.5f;
539
540         shared_ptr<pv::data::LogicSegment> segment = get_logic_segment_to_paint();
541         if (!segment || (segment->get_sample_count() == 0))
542                 return;
543
544         double samplerate = segment->samplerate();
545
546         // Show sample rate as 1Hz when it is unknown
547         if (samplerate == 0.0)
548                 samplerate = 1.0;
549
550         const double pixels_offset = pp.pixels_offset();
551         const pv::util::Timestamp& start_time = segment->start_time();
552         const int64_t last_sample = (int64_t)segment->get_sample_count() - 1;
553         const double samples_per_pixel = samplerate * pp.scale();
554         const double pixels_per_sample = 1 / samples_per_pixel;
555         const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
556         const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
557
558         const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
559                 (int64_t)0), last_sample);
560         const uint64_t end_sample = min(max(ceil(end).convert_to<int64_t>(),
561                 (int64_t)0), last_sample);
562
563         segment->get_subsampled_edges(edges, start_sample, end_sample,
564                 samples_per_pixel / LogicSignal::Oversampling, 0);
565         assert(edges.size() >= 2);
566
567         // Check whether we need to paint the sampling points
568         GlobalSettings settings;
569         const bool show_sampling_points =
570                 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool() &&
571                 (samples_per_pixel < 0.25);
572
573         vector<QRectF> sampling_points;
574         float sampling_point_x = 0.0f;
575         int64_t sampling_point_sample = start_sample;
576         const int w = 2;
577
578         if (show_sampling_points) {
579                 sampling_points.reserve(end_sample - start_sample + 1);
580                 sampling_point_x = (edges.cbegin()->first / samples_per_pixel - pixels_offset) + pp.left();
581         }
582
583         // Paint the edges
584         const unsigned int edge_count = edges.size() - 2;
585         QLineF *const edge_lines = new QLineF[edge_count];
586         line = edge_lines;
587
588         for (auto i = edges.cbegin() + 1; i != edges.cend() - 1; i++) {
589                 const float x = ((*i).first / samples_per_pixel -
590                         pixels_offset) + pp.left();
591                 *line++ = QLineF(x, high_offset, x, low_offset);
592
593                 if (show_sampling_points)
594                         while (sampling_point_sample < (*i).first) {
595                                 const float y = (*i).second ? low_offset : high_offset;
596                                 sampling_points.emplace_back(
597                                         QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
598                                 sampling_point_sample++;
599                                 sampling_point_x += pixels_per_sample;
600                         };
601         }
602
603         // Calculate the sample points from the last edge to the end of the trace
604         if (show_sampling_points)
605                 while ((uint64_t)sampling_point_sample <= end_sample) {
606                         // Signal changed after the last edge, so the level is inverted
607                         const float y = (edges.cend() - 1)->second ? high_offset : low_offset;
608                         sampling_points.emplace_back(
609                                 QRectF(sampling_point_x - (w / 2), y - (w / 2), w, w));
610                         sampling_point_sample++;
611                         sampling_point_x += pixels_per_sample;
612                 };
613
614         p.setPen(LogicSignal::EdgeColor);
615         p.drawLines(edge_lines, edge_count);
616         delete[] edge_lines;
617
618         // Paint the caps
619         const unsigned int max_cap_line_count = edges.size();
620         QLineF *const cap_lines = new QLineF[max_cap_line_count];
621
622         p.setPen(LogicSignal::HighColor);
623         paint_logic_caps(p, cap_lines, edges, true, samples_per_pixel,
624                 pixels_offset, pp.left(), high_offset);
625         p.setPen(LogicSignal::LowColor);
626         paint_logic_caps(p, cap_lines, edges, false, samples_per_pixel,
627                 pixels_offset, pp.left(), low_offset);
628
629         delete[] cap_lines;
630
631         // Paint the sampling points
632         if (show_sampling_points) {
633                 p.setPen(SamplingPointColor);
634                 p.drawRects(sampling_points.data(), sampling_points.size());
635         }
636 }
637
638 void AnalogSignal::paint_logic_caps(QPainter &p, QLineF *const lines,
639         vector< pair<int64_t, bool> > &edges, bool level,
640         double samples_per_pixel, double pixels_offset, float x_offset,
641         float y_offset)
642 {
643         QLineF *line = lines;
644
645         for (auto i = edges.begin(); i != (edges.end() - 1); i++)
646                 if ((*i).second == level) {
647                         *line++ = QLineF(
648                                 ((*i).first / samples_per_pixel -
649                                         pixels_offset) + x_offset, y_offset,
650                                 ((*(i+1)).first / samples_per_pixel -
651                                         pixels_offset) + x_offset, y_offset);
652                 }
653
654         p.drawLines(lines, line - lines);
655 }
656
657 shared_ptr<pv::data::AnalogSegment> AnalogSignal::get_analog_segment_to_paint() const
658 {
659         shared_ptr<pv::data::AnalogSegment> segment;
660
661         const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
662                 base_->analog_data()->analog_segments();
663
664         if (!segments.empty()) {
665                 if (segment_display_mode_ == ShowLastSegmentOnly)
666                         segment = segments.back();
667
668                 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
669                                 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
670                         try {
671                                 segment = segments.at(current_segment_);
672                         } catch (out_of_range&) {
673                                 qDebug() << "Current analog segment out of range for signal" << base_->name() << ":" << current_segment_;
674                         }
675                 }
676         }
677
678         return segment;
679 }
680
681 shared_ptr<pv::data::LogicSegment> AnalogSignal::get_logic_segment_to_paint() const
682 {
683         shared_ptr<pv::data::LogicSegment> segment;
684
685         const deque< shared_ptr<pv::data::LogicSegment> > &segments =
686                 base_->logic_data()->logic_segments();
687
688         if (!segments.empty()) {
689                 if (segment_display_mode_ == ShowLastSegmentOnly)
690                         segment = segments.back();
691
692                 if ((segment_display_mode_ == ShowSingleSegmentOnly) ||
693                                 (segment_display_mode_ == ShowLastCompleteSegmentOnly)) {
694                         try {
695                                 segment = segments.at(current_segment_);
696                         } catch (out_of_range&) {
697                                 qDebug() << "Current logic segment out of range for signal" << base_->name() << ":" << current_segment_;
698                         }
699                 }
700         }
701
702         return segment;
703 }
704
705 float AnalogSignal::get_resolution(int scale_index)
706 {
707         const float seq[] = {1.0f, 2.0f, 5.0f};
708
709         const int offset = numeric_limits<int>::max() / (2 * countof(seq));
710         const div_t d = div((int)(scale_index + countof(seq) * offset),
711                 countof(seq));
712
713         return powf(10.0f, d.quot - offset) * seq[d.rem];
714 }
715
716 void AnalogSignal::update_scale()
717 {
718         resolution_ = get_resolution(scale_index_);
719         scale_ = div_height_ / resolution_;
720 }
721
722 void AnalogSignal::update_conversion_widgets()
723 {
724         SignalBase::ConversionType conv_type = base_->get_conversion_type();
725
726         // Enable or disable widgets depending on conversion state
727         conv_threshold_cb_->setEnabled(conv_type != SignalBase::NoConversion);
728         display_type_cb_->setEnabled(conv_type != SignalBase::NoConversion);
729
730         conv_threshold_cb_->clear();
731
732         vector < pair<QString, int> > presets = base_->get_conversion_presets();
733
734         // Prevent the combo box from firing the "edit text changed" signal
735         // as that would involuntarily select the first entry
736         conv_threshold_cb_->blockSignals(true);
737
738         // Set available options depending on chosen conversion
739         for (pair<QString, int> preset : presets)
740                 conv_threshold_cb_->addItem(preset.first, preset.second);
741
742         map < QString, QVariant > options = base_->get_conversion_options();
743
744         if (conv_type == SignalBase::A2LConversionByThreshold) {
745                 const vector<double> thresholds = base_->get_conversion_thresholds(
746                                 SignalBase::A2LConversionByThreshold, true);
747                 conv_threshold_cb_->addItem(
748                                 QString("%1V").arg(QString::number(thresholds[0], 'f', 1)), -1);
749         }
750
751         if (conv_type == SignalBase::A2LConversionBySchmittTrigger) {
752                 const vector<double> thresholds = base_->get_conversion_thresholds(
753                                 SignalBase::A2LConversionBySchmittTrigger, true);
754                 conv_threshold_cb_->addItem(QString("%1V/%2V").arg(
755                                 QString::number(thresholds[0], 'f', 1),
756                                 QString::number(thresholds[1], 'f', 1)), -1);
757         }
758
759         int preset_id = base_->get_current_conversion_preset();
760         conv_threshold_cb_->setCurrentIndex(
761                         conv_threshold_cb_->findData(preset_id));
762
763         conv_threshold_cb_->blockSignals(false);
764 }
765
766 void AnalogSignal::perform_autoranging(bool keep_divs, bool force_update)
767 {
768         const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
769                 base_->analog_data()->analog_segments();
770
771         if (segments.empty())
772                 return;
773
774         static double prev_min = 0, prev_max = 0;
775         double min = 0, max = 0;
776
777         for (shared_ptr<pv::data::AnalogSegment> segment : segments) {
778                 pair<double, double> mm = segment->get_min_max();
779                 min = std::min(min, mm.first);
780                 max = std::max(max, mm.second);
781         }
782
783         if ((min == prev_min) && (max == prev_max) && !force_update)
784                 return;
785
786         prev_min = min;
787         prev_max = max;
788
789         // If we're allowed to alter the div assignment...
790         if (!keep_divs) {
791                 // Use all divs for the positive range if there are no negative values
792                 if ((min == 0) && (neg_vdivs_ > 0)) {
793                         pos_vdivs_ += neg_vdivs_;
794                         neg_vdivs_ = 0;
795                 }
796
797                 // Split up the divs if there are negative values but no negative divs
798                 if ((min < 0) && (neg_vdivs_ == 0)) {
799                         neg_vdivs_ = pos_vdivs_ / 2;
800                         pos_vdivs_ -= neg_vdivs_;
801                 }
802         }
803
804         // If there is still no positive div when we need it, add one
805         // (this can happen when pos_vdivs==neg_vdivs==0)
806         if ((max > 0) && (pos_vdivs_ == 0)) {
807                 pos_vdivs_ = 1;
808                 owner_->extents_changed(false, true);
809         }
810
811         // If there is still no negative div when we need it, add one
812         // (this can happen when pos_vdivs was 0 or 1 when trying to split)
813         if ((min < 0) && (neg_vdivs_ == 0)) {
814                 neg_vdivs_ = 1;
815                 owner_->extents_changed(false, true);
816         }
817
818         double min_value_per_div;
819         if ((pos_vdivs_ > 0) && (neg_vdivs_ >  0))
820                 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
821         else if (pos_vdivs_ > 0)
822                 min_value_per_div = max / pos_vdivs_;
823         else
824                 min_value_per_div = -min / neg_vdivs_;
825
826         // Find first scale value that is bigger than the value we need
827         for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
828                 if (get_resolution(i) > min_value_per_div) {
829                         scale_index_ = i;
830                         break;
831                 }
832
833         update_scale();
834 }
835
836 void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
837 {
838         // Add the standard options
839         Signal::populate_popup_form(parent, form);
840
841         QFormLayout *const layout = new QFormLayout;
842
843         // Add div-related settings
844         pvdiv_sb_ = new QSpinBox(parent);
845         pvdiv_sb_->setRange(0, MaximumVDivs);
846         pvdiv_sb_->setValue(pos_vdivs_);
847         connect(pvdiv_sb_, SIGNAL(valueChanged(int)),
848                 this, SLOT(on_pos_vdivs_changed(int)));
849         layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb_);
850
851         nvdiv_sb_ = new QSpinBox(parent);
852         nvdiv_sb_->setRange(0, MaximumVDivs);
853         nvdiv_sb_->setValue(neg_vdivs_);
854         connect(nvdiv_sb_, SIGNAL(valueChanged(int)),
855                 this, SLOT(on_neg_vdivs_changed(int)));
856         layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb_);
857
858         div_height_sb_ = new QSpinBox(parent);
859         div_height_sb_->setRange(20, 1000);
860         div_height_sb_->setSingleStep(5);
861         div_height_sb_->setSuffix(tr(" pixels"));
862         div_height_sb_->setValue(div_height_);
863         connect(div_height_sb_, SIGNAL(valueChanged(int)),
864                 this, SLOT(on_div_height_changed(int)));
865         layout->addRow(tr("Div height"), div_height_sb_);
866
867         // Add the vertical resolution
868         resolution_cb_ = new QComboBox(parent);
869
870         for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
871                 const QString label = QString("%1").arg(get_resolution(i));
872                 resolution_cb_->insertItem(0, label, QVariant(i));
873         }
874
875         int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
876         resolution_cb_->setCurrentIndex(cur_idx);
877
878         connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
879                 this, SLOT(on_resolution_changed(int)));
880
881         QGridLayout *const vdiv_layout = new QGridLayout;
882         QLabel *const vdiv_unit = new QLabel(tr("V/div"));
883         vdiv_layout->addWidget(resolution_cb_, 0, 0);
884         vdiv_layout->addWidget(vdiv_unit, 0, 1);
885
886         layout->addRow(tr("Vertical resolution"), vdiv_layout);
887
888         // Add the autoranging checkbox
889         QCheckBox* autoranging_cb = new QCheckBox();
890         autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
891
892         connect(autoranging_cb, SIGNAL(stateChanged(int)),
893                 this, SLOT(on_autoranging_changed(int)));
894
895         layout->addRow(tr("Autoranging"), autoranging_cb);
896
897         // Add the conversion type dropdown
898         conversion_cb_ = new QComboBox();
899
900         conversion_cb_->addItem(tr("none"),
901                 SignalBase::NoConversion);
902         conversion_cb_->addItem(tr("to logic via threshold"),
903                 SignalBase::A2LConversionByThreshold);
904         conversion_cb_->addItem(tr("to logic via schmitt-trigger"),
905                 SignalBase::A2LConversionBySchmittTrigger);
906
907         cur_idx = conversion_cb_->findData(QVariant(base_->get_conversion_type()));
908         conversion_cb_->setCurrentIndex(cur_idx);
909
910         layout->addRow(tr("Conversion"), conversion_cb_);
911
912         connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
913                 this, SLOT(on_conversion_changed(int)));
914
915     // Add the conversion threshold settings
916     conv_threshold_cb_ = new QComboBox();
917     conv_threshold_cb_->setEditable(true);
918
919     layout->addRow(tr("Conversion threshold(s)"), conv_threshold_cb_);
920
921     connect(conv_threshold_cb_, SIGNAL(currentIndexChanged(int)),
922             this, SLOT(on_conv_threshold_changed(int)));
923     connect(conv_threshold_cb_, SIGNAL(editTextChanged(const QString)),
924             this, SLOT(on_conv_threshold_changed()));  // index will be -1
925
926         // Add the display type dropdown
927         display_type_cb_ = new QComboBox();
928
929         display_type_cb_->addItem(tr("analog"), DisplayAnalog);
930         display_type_cb_->addItem(tr("converted"), DisplayConverted);
931         display_type_cb_->addItem(tr("analog+converted"), DisplayBoth);
932
933         cur_idx = display_type_cb_->findData(QVariant(display_type_));
934         display_type_cb_->setCurrentIndex(cur_idx);
935
936         layout->addRow(tr("Show traces for"), display_type_cb_);
937
938         connect(display_type_cb_, SIGNAL(currentIndexChanged(int)),
939                 this, SLOT(on_display_type_changed(int)));
940
941         // Update the conversion widget contents and states
942         update_conversion_widgets();
943
944         form->addRow(layout);
945 }
946
947 void AnalogSignal::on_min_max_changed(float min, float max)
948 {
949         (void)min;
950         (void)max;
951
952         if (autoranging_)
953                 perform_autoranging(false, false);
954 }
955
956 void AnalogSignal::on_pos_vdivs_changed(int vdivs)
957 {
958         if (vdivs == pos_vdivs_)
959                 return;
960
961         pos_vdivs_ = vdivs;
962
963         // There has to be at least one div, positive or negative
964         if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
965                 pos_vdivs_ = 1;
966                 if (pvdiv_sb_)
967                         pvdiv_sb_->setValue(pos_vdivs_);
968         }
969
970         if (autoranging_) {
971                 perform_autoranging(true, true);
972
973                 // It could be that a positive or negative div was added, so update
974                 if (pvdiv_sb_) {
975                         pvdiv_sb_->setValue(pos_vdivs_);
976                         nvdiv_sb_->setValue(neg_vdivs_);
977                 }
978         }
979
980         if (owner_) {
981                 // Call order is important, otherwise the lazy event handler won't work
982                 owner_->extents_changed(false, true);
983                 owner_->row_item_appearance_changed(false, true);
984         }
985 }
986
987 void AnalogSignal::on_neg_vdivs_changed(int vdivs)
988 {
989         if (vdivs == neg_vdivs_)
990                 return;
991
992         neg_vdivs_ = vdivs;
993
994         // There has to be at least one div, positive or negative
995         if ((neg_vdivs_ == 0) && (pos_vdivs_ == 0)) {
996                 pos_vdivs_ = 1;
997                 if (pvdiv_sb_)
998                         pvdiv_sb_->setValue(pos_vdivs_);
999         }
1000
1001         if (autoranging_) {
1002                 perform_autoranging(true, true);
1003
1004                 // It could be that a positive or negative div was added, so update
1005                 if (pvdiv_sb_) {
1006                         pvdiv_sb_->setValue(pos_vdivs_);
1007                         nvdiv_sb_->setValue(neg_vdivs_);
1008                 }
1009         }
1010
1011         if (owner_) {
1012                 // Call order is important, otherwise the lazy event handler won't work
1013                 owner_->extents_changed(false, true);
1014                 owner_->row_item_appearance_changed(false, true);
1015         }
1016 }
1017
1018 void AnalogSignal::on_div_height_changed(int height)
1019 {
1020         div_height_ = height;
1021         update_scale();
1022
1023         if (owner_) {
1024                 // Call order is important, otherwise the lazy event handler won't work
1025                 owner_->extents_changed(false, true);
1026                 owner_->row_item_appearance_changed(false, true);
1027         }
1028 }
1029
1030 void AnalogSignal::on_resolution_changed(int index)
1031 {
1032         scale_index_ = resolution_cb_->itemData(index).toInt();
1033         update_scale();
1034
1035         if (owner_)
1036                 owner_->row_item_appearance_changed(false, true);
1037 }
1038
1039 void AnalogSignal::on_autoranging_changed(int state)
1040 {
1041         autoranging_ = (state == Qt::Checked);
1042
1043         if (autoranging_)
1044                 perform_autoranging(false, true);
1045
1046         if (owner_) {
1047                 // Call order is important, otherwise the lazy event handler won't work
1048                 owner_->extents_changed(false, true);
1049                 owner_->row_item_appearance_changed(false, true);
1050         }
1051 }
1052
1053 void AnalogSignal::on_conversion_changed(int index)
1054 {
1055         SignalBase::ConversionType old_conv_type = base_->get_conversion_type();
1056
1057         SignalBase::ConversionType conv_type =
1058                 (SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
1059
1060         if (conv_type != old_conv_type) {
1061                 base_->set_conversion_type(conv_type);
1062                 update_conversion_widgets();
1063
1064                 if (owner_)
1065                         owner_->row_item_appearance_changed(false, true);
1066         }
1067 }
1068
1069 void AnalogSignal::on_conv_threshold_changed(int index)
1070 {
1071         SignalBase::ConversionType conv_type = base_->get_conversion_type();
1072
1073         // Note: index is set to -1 if the text in the combo box matches none of
1074         // the entries in the combo box
1075
1076         if ((index == -1) && (conv_threshold_cb_->currentText().length() == 0))
1077                 return;
1078
1079         // The combo box entry with the custom value has user_data set to -1
1080         const int user_data = conv_threshold_cb_->findText(
1081                         conv_threshold_cb_->currentText());
1082
1083         const bool use_custom_thr = (index == -1) || (user_data == -1);
1084
1085         if (conv_type == SignalBase::A2LConversionByThreshold && use_custom_thr) {
1086                 // Not one of the preset values, try to parse the combo box text
1087                 // Note: Regex loosely based on
1088                 // https://txt2re.com/index-c++.php3?s=0.1V&1&-13
1089                 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1090                 QString re2 = "([a-zA-Z]*)"; // SI unit
1091                 QRegExp regex(re1 + re2);
1092
1093                 const QString text = conv_threshold_cb_->currentText();
1094                 if (!regex.exactMatch(text))
1095                         return;  // String doesn't match the regex
1096
1097                 QStringList tokens = regex.capturedTexts();
1098
1099                 // For now, we simply assume that the unit is volt without modifiers
1100                 const double thr = tokens.at(1).toDouble();
1101
1102                 // Only restart the conversion if the threshold was updated.
1103                 // We're starting a delayed conversion because the user may still be
1104                 // typing and the UI would lag if we kept on restarting it immediately
1105                 if (base_->set_conversion_option("threshold_value", thr))
1106                         base_->start_conversion(true);
1107         }
1108
1109         if (conv_type == SignalBase::A2LConversionBySchmittTrigger && use_custom_thr) {
1110                 // Not one of the preset values, try to parse the combo box text
1111                 // Note: Regex loosely based on
1112                 // https://txt2re.com/index-c++.php3?s=0.1V/0.2V&2&14&-22&3&15
1113                 QString re1 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1114                 QString re2 = "([a-zA-Z]*)"; // SI unit
1115                 QString re3 = "\\/"; // Forward slash, not captured
1116                 QString re4 = "([+-]?\\d*[\\.,]?\\d*)"; // Float value
1117                 QString re5 = "([a-zA-Z]*)"; // SI unit
1118                 QRegExp regex(re1 + re2 + re3 + re4 + re5);
1119
1120                 const QString text = conv_threshold_cb_->currentText();
1121                 if (!regex.exactMatch(text))
1122                         return;  // String doesn't match the regex
1123
1124                 QStringList tokens = regex.capturedTexts();
1125
1126                 // For now, we simply assume that the unit is volt without modifiers
1127                 const double low_thr = tokens.at(1).toDouble();
1128                 const double high_thr = tokens.at(3).toDouble();
1129
1130                 // Only restart the conversion if one of the options was updated.
1131                 // We're starting a delayed conversion because the user may still be
1132                 // typing and the UI would lag if we kept on restarting it immediately
1133                 bool o1 = base_->set_conversion_option("threshold_value_low", low_thr);
1134                 bool o2 = base_->set_conversion_option("threshold_value_high", high_thr);
1135                 if (o1 || o2)
1136                         base_->start_conversion(true);  // Start delayed conversion
1137         }
1138
1139         base_->set_conversion_preset((SignalBase::ConversionPreset)index);
1140
1141         // Immediately start the conversion if we're not using custom values
1142         // (i.e. we're using one of the presets)
1143         if (!use_custom_thr)
1144                 base_->start_conversion();
1145 }
1146
1147 void AnalogSignal::on_delayed_conversion_starter()
1148 {
1149         base_->start_conversion();
1150 }
1151
1152 void AnalogSignal::on_display_type_changed(int index)
1153 {
1154         display_type_ = (DisplayType)(display_type_cb_->itemData(index).toInt());
1155
1156         if (owner_)
1157                 owner_->row_item_appearance_changed(false, true);
1158 }
1159
1160 void AnalogSignal::on_settingViewConversionThresholdDispMode_changed(const QVariant new_value)
1161 {
1162         conversion_threshold_disp_mode_ = new_value.toInt();
1163
1164         if (owner_)
1165                 owner_->row_item_appearance_changed(false, true);
1166 }
1167
1168 } // namespace trace
1169 } // namespace views
1170 } // namespace pv