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