]> sigrok.org Git - pulseview.git/blob - pv/view/analogsignal.cpp
AnalogSignal: Add conversion type and display type
[pulseview.git] / pv / view / 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
27 #include <QApplication>
28 #include <QCheckBox>
29 #include <QComboBox>
30 #include <QFormLayout>
31 #include <QGridLayout>
32 #include <QLabel>
33 #include <QSpinBox>
34 #include <QString>
35
36 #include "analogsignal.hpp"
37 #include "pv/data/analog.hpp"
38 #include "pv/data/analogsegment.hpp"
39 #include "pv/data/signalbase.hpp"
40 #include "pv/view/view.hpp"
41 #include "pv/globalsettings.hpp"
42
43 #include <libsigrokcxx/libsigrokcxx.hpp>
44
45 using std::deque;
46 using std::div;
47 using std::div_t;
48 using std::max;
49 using std::make_pair;
50 using std::min;
51 using std::numeric_limits;
52 using std::pair;
53 using std::shared_ptr;
54
55 namespace pv {
56 namespace views {
57 namespace TraceView {
58
59 const QColor AnalogSignal::SignalColours[4] = {
60         QColor(0xC4, 0xA0, 0x00),       // Yellow
61         QColor(0x87, 0x20, 0x7A),       // Magenta
62         QColor(0x20, 0x4A, 0x87),       // Blue
63         QColor(0x4E, 0x9A, 0x06)        // Green
64 };
65
66 const QColor AnalogSignal::GridMajorColor = QColor(0, 0, 0, 40*256/100);
67 const QColor AnalogSignal::GridMinorColor = QColor(0, 0, 0, 20*256/100);
68
69 const QColor AnalogSignal::SamplingPointColour(0x77, 0x77, 0x77);
70
71 const float AnalogSignal::EnvelopeThreshold = 256.0f;
72
73 const int AnalogSignal::MaximumVDivs = 10;
74 const int AnalogSignal::MinScaleIndex = -6;
75 const int AnalogSignal::MaxScaleIndex = 7;
76
77 const int AnalogSignal::InfoTextMarginRight = 20;
78 const int AnalogSignal::InfoTextMarginBottom = 5;
79
80 AnalogSignal::AnalogSignal(
81         pv::Session &session,
82         shared_ptr<data::SignalBase> base) :
83         Signal(session, base),
84         scale_index_(4), // 20 per div
85         scale_index_drag_offset_(0),
86         div_height_(3 * QFontMetrics(QApplication::font()).height()),
87         pos_vdivs_(1),
88         neg_vdivs_(1),
89         resolution_(0),
90         conversion_type_(data::SignalBase::NoConversion),
91         display_type_(DisplayBoth),
92         autoranging_(true)
93 {
94         pv::data::Analog* analog_data =
95                 dynamic_cast<pv::data::Analog*>(data().get());
96
97         connect(analog_data, SIGNAL(samples_added(QObject*, uint64_t, uint64_t)),
98                 this, SLOT(on_samples_added()));
99
100         base_->set_colour(SignalColours[base_->index() % countof(SignalColours)]);
101         update_scale();
102 }
103
104 shared_ptr<pv::data::SignalData> AnalogSignal::data() const
105 {
106         return base_->analog_data();
107 }
108
109 void AnalogSignal::save_settings(QSettings &settings) const
110 {
111         settings.setValue("pos_vdivs", pos_vdivs_);
112         settings.setValue("neg_vdivs", neg_vdivs_);
113         settings.setValue("scale_index", scale_index_);
114         settings.setValue("conversion_type", conversion_type_);
115         settings.setValue("display_type", display_type_);
116         settings.setValue("autoranging", autoranging_);
117 }
118
119 void AnalogSignal::restore_settings(QSettings &settings)
120 {
121         if (settings.contains("pos_vdivs"))
122                 pos_vdivs_ = settings.value("pos_vdivs").toInt();
123
124         if (settings.contains("neg_vdivs"))
125                 neg_vdivs_ = settings.value("neg_vdivs").toInt();
126
127         if (settings.contains("scale_index")) {
128                 scale_index_ = settings.value("scale_index").toInt();
129                 update_scale();
130         }
131
132         if (settings.contains("conversion_type"))
133                 conversion_type_ = (data::SignalBase::ConversionType)(settings.value("conversion_type").toInt());
134
135         if (settings.contains("display_type"))
136                 display_type_ = (DisplayType)(settings.value("display_type").toInt());
137
138         if (settings.contains("autoranging"))
139                 autoranging_ = settings.value("autoranging").toBool();
140 }
141
142 pair<int, int> AnalogSignal::v_extents() const
143 {
144         const int ph = pos_vdivs_ * div_height_;
145         const int nh = neg_vdivs_ * div_height_;
146         return make_pair(-ph, nh);
147 }
148
149 int AnalogSignal::scale_handle_offset() const
150 {
151         const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
152
153         return ((scale_index_drag_offset_ - scale_index_) *
154                 h / 4) - h / 2;
155 }
156
157 void AnalogSignal::scale_handle_dragged(int offset)
158 {
159         const int h = (pos_vdivs_ + neg_vdivs_) * div_height_;
160
161         scale_index_ = scale_index_drag_offset_ -
162                 (offset + h / 2) / (h / 4);
163
164         update_scale();
165 }
166
167 void AnalogSignal::scale_handle_drag_release()
168 {
169         scale_index_drag_offset_ = scale_index_;
170         update_scale();
171 }
172
173 void AnalogSignal::paint_back(QPainter &p, const ViewItemPaintParams &pp)
174 {
175         if (base_->enabled()) {
176                 Trace::paint_back(p, pp);
177                 paint_axis(p, pp, get_visual_y());
178         }
179 }
180
181 void AnalogSignal::paint_mid(QPainter &p, const ViewItemPaintParams &pp)
182 {
183         assert(base_->analog_data());
184         assert(owner_);
185
186         const int y = get_visual_y();
187
188         if (!base_->enabled())
189                 return;
190
191         paint_grid(p, y, pp.left(), pp.right());
192
193         const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
194                 base_->analog_data()->analog_segments();
195         if (segments.empty())
196                 return;
197
198         const shared_ptr<pv::data::AnalogSegment> &segment =
199                 segments.front();
200
201         const double pixels_offset = pp.pixels_offset();
202         const double samplerate = max(1.0, segment->samplerate());
203         const pv::util::Timestamp& start_time = segment->start_time();
204         const int64_t last_sample = segment->get_sample_count() - 1;
205         const double samples_per_pixel = samplerate * pp.scale();
206         const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
207         const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
208
209         const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
210                 (int64_t)0), last_sample);
211         const int64_t end_sample = min(max((ceil(end) + 1).convert_to<int64_t>(),
212                 (int64_t)0), last_sample);
213
214         if (samples_per_pixel < EnvelopeThreshold)
215                 paint_trace(p, segment, y, pp.left(),
216                         start_sample, end_sample,
217                         pixels_offset, samples_per_pixel);
218         else
219                 paint_envelope(p, segment, y, pp.left(),
220                         start_sample, end_sample,
221                         pixels_offset, samples_per_pixel);
222 }
223
224 void AnalogSignal::paint_fore(QPainter &p, const ViewItemPaintParams &pp)
225 {
226         if (!enabled())
227                 return;
228
229         const int y = get_visual_y();
230
231         // Show the info section on the right side of the trace
232         const QString infotext = QString("%1 V/div").arg(resolution_);
233
234         p.setPen(base_->colour());
235         p.setFont(QApplication::font());
236
237         const QRectF bounding_rect = QRectF(pp.left(),
238                         y + v_extents().first,
239                         pp.width() - InfoTextMarginRight,
240                         v_extents().second - v_extents().first - InfoTextMarginBottom);
241
242         p.drawText(bounding_rect, Qt::AlignRight | Qt::AlignBottom, infotext);
243 }
244
245 void AnalogSignal::paint_grid(QPainter &p, int y, int left, int right)
246 {
247         p.setRenderHint(QPainter::Antialiasing, false);
248
249         if (pos_vdivs_ > 0) {
250                 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
251                 for (int i = 1; i <= pos_vdivs_; i++) {
252                         const float dy = i * div_height_;
253                         p.drawLine(QLineF(left, y - dy, right, y - dy));
254                 }
255
256                 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
257                 for (int i = 0; i < pos_vdivs_; i++) {
258                         const float dy = i * div_height_;
259                         const float dy25 = dy + (0.25 * div_height_);
260                         const float dy50 = dy + (0.50 * div_height_);
261                         const float dy75 = dy + (0.75 * div_height_);
262                         p.drawLine(QLineF(left, y - dy25, right, y - dy25));
263                         p.drawLine(QLineF(left, y - dy50, right, y - dy50));
264                         p.drawLine(QLineF(left, y - dy75, right, y - dy75));
265                 }
266         }
267
268         if (neg_vdivs_ > 0) {
269                 p.setPen(QPen(GridMajorColor, 1, Qt::DashLine));
270                 for (int i = 1; i <= neg_vdivs_; i++) {
271                         const float dy = i * div_height_;
272                         p.drawLine(QLineF(left, y + dy, right, y + dy));
273                 }
274
275                 p.setPen(QPen(GridMinorColor, 1, Qt::DashLine));
276                 for (int i = 0; i < neg_vdivs_; i++) {
277                         const float dy = i * div_height_;
278                         const float dy25 = dy + (0.25 * div_height_);
279                         const float dy50 = dy + (0.50 * div_height_);
280                         const float dy75 = dy + (0.75 * div_height_);
281                         p.drawLine(QLineF(left, y + dy25, right, y + dy25));
282                         p.drawLine(QLineF(left, y + dy50, right, y + dy50));
283                         p.drawLine(QLineF(left, y + dy75, right, y + dy75));
284                 }
285         }
286
287         p.setRenderHint(QPainter::Antialiasing, true);
288 }
289
290 void AnalogSignal::paint_trace(QPainter &p,
291         const shared_ptr<pv::data::AnalogSegment> &segment,
292         int y, int left, const int64_t start, const int64_t end,
293         const double pixels_offset, const double samples_per_pixel)
294 {
295         p.setPen(base_->colour());
296
297         const int64_t points_count = end - start;
298
299         QPointF *points = new QPointF[points_count];
300         QPointF *point = points;
301
302         QRectF *const sampling_points = new QRectF[points_count];
303         QRectF *sampling_point = sampling_points;
304
305         pv::data::SegmentAnalogDataIterator* it =
306                 segment->begin_sample_iteration(start);
307
308         const int w = 2;
309         for (int64_t sample = start; sample != end; sample++) {
310                 const float x = (sample / samples_per_pixel -
311                         pixels_offset) + left;
312
313                 *point++ = QPointF(x, y - *((float*)it->value) * scale_);
314                 *sampling_point++ = QRectF(x - (w / 2), y - *((float*)it->value) * scale_ - (w / 2), w, w);
315
316                 segment->continue_sample_iteration(it, 1);
317         }
318         segment->end_sample_iteration(it);
319
320         p.drawPolyline(points, points_count);
321
322         // Paint the sampling points if enabled
323         GlobalSettings settings;
324         const bool show_sampling_points =
325                 settings.value(GlobalSettings::Key_View_ShowSamplingPoints).toBool();
326
327         if (show_sampling_points && (samples_per_pixel < 0.25)) {
328                 p.setPen(SamplingPointColour);
329                 p.drawRects(sampling_points, points_count);
330         }
331
332         delete[] points;
333         delete[] sampling_points;
334 }
335
336 void AnalogSignal::paint_envelope(QPainter &p,
337         const shared_ptr<pv::data::AnalogSegment> &segment,
338         int y, int left, const int64_t start, const int64_t end,
339         const double pixels_offset, const double samples_per_pixel)
340 {
341         using pv::data::AnalogSegment;
342
343         AnalogSegment::EnvelopeSection e;
344         segment->get_envelope_section(e, start, end, samples_per_pixel);
345
346         if (e.length < 2)
347                 return;
348
349         p.setPen(QPen(Qt::NoPen));
350         p.setBrush(base_->colour());
351
352         QRectF *const rects = new QRectF[e.length];
353         QRectF *rect = rects;
354
355         for (uint64_t sample = 0; sample < e.length-1; sample++) {
356                 const float x = ((e.scale * sample + e.start) /
357                         samples_per_pixel - pixels_offset) + left;
358                 const AnalogSegment::EnvelopeSample *const s =
359                         e.samples + sample;
360
361                 // We overlap this sample with the next so that vertical
362                 // gaps do not appear during steep rising or falling edges
363                 const float b = y - max(s->max, (s+1)->min) * scale_;
364                 const float t = y - min(s->min, (s+1)->max) * scale_;
365
366                 float h = b - t;
367                 if (h >= 0.0f && h <= 1.0f)
368                         h = 1.0f;
369                 if (h <= 0.0f && h >= -1.0f)
370                         h = -1.0f;
371
372                 *rect++ = QRectF(x, t, 1.0f, h);
373         }
374
375         p.drawRects(rects, e.length);
376
377         delete[] rects;
378         delete[] e.samples;
379 }
380
381 float AnalogSignal::get_resolution(int scale_index)
382 {
383         const float seq[] = {1.0f, 2.0f, 5.0f};
384
385         const int offset = numeric_limits<int>::max() / (2 * countof(seq));
386         const div_t d = div((int)(scale_index + countof(seq) * offset),
387                 countof(seq));
388
389         return powf(10.0f, d.quot - offset) * seq[d.rem];
390 }
391
392 void AnalogSignal::update_scale()
393 {
394         resolution_ = get_resolution(scale_index_);
395         scale_ = div_height_ / resolution_;
396 }
397
398 void AnalogSignal::perform_autoranging(bool force_update)
399 {
400         const deque< shared_ptr<pv::data::AnalogSegment> > &segments =
401                 base_->analog_data()->analog_segments();
402
403         if (segments.empty())
404                 return;
405
406         static double prev_min = 0, prev_max = 0;
407         double min = 0, max = 0;
408
409         for (shared_ptr<pv::data::AnalogSegment> segment : segments) {
410                 pair<double, double> mm = segment->get_min_max();
411                 min = std::min(min, mm.first);
412                 max = std::max(max, mm.second);
413         }
414
415         if ((min == prev_min) && (max == prev_max) && !force_update)
416                 return;
417
418         prev_min = min;
419         prev_max = max;
420
421         // Use all divs for the positive range if there are no negative values
422         if ((min == 0) && (neg_vdivs_ > 0)) {
423                 pos_vdivs_ += neg_vdivs_;
424                 neg_vdivs_ = 0;
425         }
426
427         // Split up the divs if there are negative values but no negative divs
428         if ((min < 0) && (neg_vdivs_ == 0)) {
429                 neg_vdivs_ = pos_vdivs_ / 2;
430                 pos_vdivs_ -= neg_vdivs_;
431         }
432
433         double min_value_per_div;
434         if ((pos_vdivs_ > 0) && (neg_vdivs_ >  0))
435                 min_value_per_div = std::max(max / pos_vdivs_, -min / neg_vdivs_);
436         else if (pos_vdivs_ > 0)
437                 min_value_per_div = max / pos_vdivs_;
438         else
439                 min_value_per_div = -min / neg_vdivs_;
440
441         // Find first scale value that is bigger than the value we need
442         for (int i = MinScaleIndex; i < MaxScaleIndex; i++)
443                 if (get_resolution(i) > min_value_per_div) {
444                         scale_index_ = i;
445                         break;
446                 }
447
448         update_scale();
449 }
450
451 void AnalogSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
452 {
453         // Add the standard options
454         Signal::populate_popup_form(parent, form);
455
456         QFormLayout *const layout = new QFormLayout;
457
458         // Add the number of vdivs
459         QSpinBox *pvdiv_sb = new QSpinBox(parent);
460         pvdiv_sb->setRange(0, MaximumVDivs);
461         pvdiv_sb->setValue(pos_vdivs_);
462         connect(pvdiv_sb, SIGNAL(valueChanged(int)),
463                 this, SLOT(on_pos_vdivs_changed(int)));
464         layout->addRow(tr("Number of pos vertical divs"), pvdiv_sb);
465
466         QSpinBox *nvdiv_sb = new QSpinBox(parent);
467         nvdiv_sb->setRange(0, MaximumVDivs);
468         nvdiv_sb->setValue(neg_vdivs_);
469         connect(nvdiv_sb, SIGNAL(valueChanged(int)),
470                 this, SLOT(on_neg_vdivs_changed(int)));
471         layout->addRow(tr("Number of neg vertical divs"), nvdiv_sb);
472
473         // Add the vertical resolution
474         resolution_cb_ = new QComboBox(parent);
475
476         for (int i = MinScaleIndex; i < MaxScaleIndex; i++) {
477                 const QString label = QString("%1").arg(get_resolution(i));
478                 resolution_cb_->insertItem(0, label, QVariant(i));
479         }
480
481         int cur_idx = resolution_cb_->findData(QVariant(scale_index_));
482         resolution_cb_->setCurrentIndex(cur_idx);
483
484         connect(resolution_cb_, SIGNAL(currentIndexChanged(int)),
485                 this, SLOT(on_resolution_changed(int)));
486
487         QGridLayout *const vdiv_layout = new QGridLayout;
488         QLabel *const vdiv_unit = new QLabel(tr("V/div"));
489         vdiv_layout->addWidget(resolution_cb_, 0, 0);
490         vdiv_layout->addWidget(vdiv_unit, 0, 1);
491
492         layout->addRow(tr("Vertical resolution"), vdiv_layout);
493
494         // Add the autoranging checkbox
495         QCheckBox* autoranging_cb = new QCheckBox();
496         autoranging_cb->setCheckState(autoranging_ ? Qt::Checked : Qt::Unchecked);
497
498         connect(autoranging_cb, SIGNAL(stateChanged(int)),
499                 this, SLOT(on_autoranging_changed(int)));
500
501         layout->addRow(tr("Autoranging"), autoranging_cb);
502
503         // Add the conversion type dropdown
504         conversion_cb_ = new QComboBox();
505
506         conversion_cb_->addItem("none", data::SignalBase::NoConversion);
507         conversion_cb_->addItem("to logic via threshold", data::SignalBase::A2LConversionByTreshold);
508         conversion_cb_->addItem("to logic via schmitt-trigger", data::SignalBase::A2LConversionBySchmittTrigger);
509
510         cur_idx = conversion_cb_->findData(QVariant(conversion_type_));
511         conversion_cb_->setCurrentIndex(cur_idx);
512
513         layout->addRow(tr("Conversion"), conversion_cb_);
514
515         connect(conversion_cb_, SIGNAL(currentIndexChanged(int)),
516                 this, SLOT(on_conversion_changed(int)));
517
518         // Add the display type dropdown
519         display_type_cb_ = new QComboBox();
520
521         display_type_cb_->addItem(tr("Analog"), DisplayAnalog);
522         display_type_cb_->addItem(tr("Converted"), DisplayConverted);
523         display_type_cb_->addItem(tr("Both"), DisplayBoth);
524
525         cur_idx = display_type_cb_->findData(QVariant(display_type_));
526         display_type_cb_->setCurrentIndex(cur_idx);
527
528         layout->addRow(tr("Traces to show:"), display_type_cb_);
529
530         form->addRow(layout);
531 }
532
533 void AnalogSignal::on_samples_added()
534 {
535         perform_autoranging();
536
537         if (owner_) {
538                 // Call order is important, otherwise the lazy event handler won't work
539                 owner_->extents_changed(false, true);
540                 owner_->row_item_appearance_changed(false, true);
541         }
542 }
543
544 void AnalogSignal::on_pos_vdivs_changed(int vdivs)
545 {
546         pos_vdivs_ = vdivs;
547
548         if (autoranging_)
549                 perform_autoranging(true);
550
551         if (owner_) {
552                 // Call order is important, otherwise the lazy event handler won't work
553                 owner_->extents_changed(false, true);
554                 owner_->row_item_appearance_changed(false, true);
555         }
556 }
557
558 void AnalogSignal::on_neg_vdivs_changed(int vdivs)
559 {
560         neg_vdivs_ = vdivs;
561
562         if (autoranging_)
563                 perform_autoranging(true);
564
565         if (owner_) {
566                 // Call order is important, otherwise the lazy event handler won't work
567                 owner_->extents_changed(false, true);
568                 owner_->row_item_appearance_changed(false, true);
569         }
570 }
571
572 void AnalogSignal::on_resolution_changed(int index)
573 {
574         scale_index_ = resolution_cb_->itemData(index).toInt();
575         update_scale();
576
577         if (owner_)
578                 owner_->row_item_appearance_changed(false, true);
579 }
580
581 void AnalogSignal::on_autoranging_changed(int state)
582 {
583         autoranging_ = (state == Qt::Checked);
584
585         if (autoranging_)
586                 perform_autoranging(true);
587
588         if (owner_) {
589                 // Call order is important, otherwise the lazy event handler won't work
590                 owner_->extents_changed(false, true);
591                 owner_->row_item_appearance_changed(false, true);
592         }
593 }
594
595 void AnalogSignal::on_conversion_changed(int index)
596 {
597         conversion_type_ = (data::SignalBase::ConversionType)(conversion_cb_->itemData(index).toInt());
598         base_->set_conversion_type(conversion_type_);
599 }
600
601 } // namespace TraceView
602 } // namespace views
603 } // namespace pv