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