]> sigrok.org Git - pulseview.git/blame_incremental - pv/view/view.cpp
desktop file: Add additional Development category.
[pulseview.git] / pv / view / view.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#ifdef ENABLE_DECODE
21#include <libsigrokdecode/libsigrokdecode.h>
22#endif
23
24#include <extdef.h>
25
26#include <algorithm>
27#include <cassert>
28#include <climits>
29#include <cmath>
30#include <iostream>
31#include <iterator>
32#include <unordered_set>
33
34#include <boost/archive/text_iarchive.hpp>
35#include <boost/archive/text_oarchive.hpp>
36#include <boost/serialization/serialization.hpp>
37
38#include <QApplication>
39#include <QEvent>
40#include <QFontMetrics>
41#include <QHBoxLayout>
42#include <QMouseEvent>
43#include <QScrollBar>
44
45#include <libsigrokcxx/libsigrokcxx.hpp>
46
47#include "analogsignal.hpp"
48#include "header.hpp"
49#include "logicsignal.hpp"
50#include "ruler.hpp"
51#include "signal.hpp"
52#include "tracegroup.hpp"
53#include "triggermarker.hpp"
54#include "view.hpp"
55#include "viewport.hpp"
56
57#include "pv/data/logic.hpp"
58#include "pv/data/logicsegment.hpp"
59#include "pv/devices/device.hpp"
60#include "pv/globalsettings.hpp"
61#include "pv/session.hpp"
62#include "pv/util.hpp"
63
64#ifdef ENABLE_DECODE
65#include "decodetrace.hpp"
66#endif
67
68using pv::data::SignalData;
69using pv::data::Segment;
70using pv::util::TimeUnit;
71using pv::util::Timestamp;
72
73using std::back_inserter;
74using std::copy_if;
75using std::count_if;
76using std::dynamic_pointer_cast;
77using std::inserter;
78using std::max;
79using std::make_pair;
80using std::make_shared;
81using std::min;
82using std::pair;
83using std::set;
84using std::set_difference;
85using std::shared_ptr;
86using std::stringstream;
87using std::unordered_map;
88using std::unordered_set;
89using std::vector;
90
91namespace pv {
92namespace views {
93namespace TraceView {
94
95const Timestamp View::MaxScale("1e9");
96const Timestamp View::MinScale("1e-12");
97
98const int View::MaxScrollValue = INT_MAX / 2;
99
100const int View::ScaleUnits[3] = {1, 2, 5};
101
102
103CustomAbstractScrollArea::CustomAbstractScrollArea(QWidget *parent) :
104 QAbstractScrollArea(parent)
105{
106}
107
108void CustomAbstractScrollArea::setViewportMargins(int left, int top, int right, int bottom)
109{
110 QAbstractScrollArea::setViewportMargins(left, top, right, bottom);
111}
112
113bool CustomAbstractScrollArea::viewportEvent(QEvent *event)
114{
115 switch (event->type()) {
116 case QEvent::Paint:
117 case QEvent::MouseButtonPress:
118 case QEvent::MouseButtonRelease:
119 case QEvent::MouseButtonDblClick:
120 case QEvent::MouseMove:
121 case QEvent::Wheel:
122 case QEvent::TouchBegin:
123 case QEvent::TouchUpdate:
124 case QEvent::TouchEnd:
125 return false;
126 default:
127 return QAbstractScrollArea::viewportEvent(event);
128 }
129}
130
131View::View(Session &session, bool is_main_view, QWidget *parent) :
132 ViewBase(session, is_main_view, parent),
133 viewport_(new Viewport(*this)),
134 ruler_(new Ruler(*this)),
135 header_(new Header(*this)),
136 scrollarea_(this),
137 scale_(1e-3),
138 offset_(0),
139 updating_scroll_(false),
140 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
141 always_zoom_to_fit_(false),
142 tick_period_(0),
143 tick_prefix_(pv::util::SIPrefix::yocto),
144 tick_precision_(0),
145 time_unit_(util::TimeUnit::Time),
146 show_cursors_(false),
147 cursors_(new CursorPair(*this)),
148 next_flag_text_('A'),
149 trigger_markers_(),
150 hover_point_(-1, -1),
151 scroll_needs_defaults_(false),
152 saved_v_offset_(0)
153{
154 GlobalSettings settings;
155 coloured_bg_ = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
156
157 connect(scrollarea_.horizontalScrollBar(), SIGNAL(valueChanged(int)),
158 this, SLOT(h_scroll_value_changed(int)));
159 connect(scrollarea_.verticalScrollBar(), SIGNAL(valueChanged(int)),
160 this, SLOT(v_scroll_value_changed()));
161
162 connect(header_, SIGNAL(selection_changed()),
163 ruler_, SLOT(clear_selection()));
164 connect(ruler_, SIGNAL(selection_changed()),
165 header_, SLOT(clear_selection()));
166
167 connect(header_, SIGNAL(selection_changed()),
168 this, SIGNAL(selection_changed()));
169 connect(ruler_, SIGNAL(selection_changed()),
170 this, SIGNAL(selection_changed()));
171
172 connect(this, SIGNAL(hover_point_changed()),
173 this, SLOT(on_hover_point_changed()));
174
175 connect(&lazy_event_handler_, SIGNAL(timeout()),
176 this, SLOT(process_sticky_events()));
177 lazy_event_handler_.setSingleShot(true);
178
179 /* To let the scroll area fill up the parent QWidget (this), we need a layout */
180 QHBoxLayout *layout = new QHBoxLayout(this);
181 setLayout(layout);
182 layout->setContentsMargins(0, 0, 0, 0);
183 layout->addWidget(&scrollarea_);
184
185 scrollarea_.setViewport(viewport_);
186
187 viewport_->installEventFilter(this);
188 ruler_->installEventFilter(this);
189 header_->installEventFilter(this);
190
191 // Trigger the initial event manually. The default device has signals
192 // which were created before this object came into being
193 signals_changed();
194
195 // make sure the transparent widgets are on the top
196 ruler_->raise();
197 header_->raise();
198
199 // Update the zoom state
200 calculate_tick_spacing();
201}
202
203Session& View::session()
204{
205 return session_;
206}
207
208const Session& View::session() const
209{
210 return session_;
211}
212
213unordered_set< shared_ptr<Signal> > View::signals() const
214{
215 return signals_;
216}
217
218void View::clear_signals()
219{
220 ViewBase::clear_signalbases();
221 signals_.clear();
222}
223
224void View::add_signal(const shared_ptr<Signal> signal)
225{
226 ViewBase::add_signalbase(signal->base());
227 signals_.insert(signal);
228}
229
230#ifdef ENABLE_DECODE
231void View::clear_decode_signals()
232{
233 decode_traces_.clear();
234}
235
236void View::add_decode_signal(shared_ptr<data::SignalBase> signalbase)
237{
238 shared_ptr<DecodeTrace> d(
239 new DecodeTrace(session_, signalbase, decode_traces_.size()));
240 decode_traces_.push_back(d);
241}
242
243void View::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
244{
245 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
246 if ((*i)->base() == signalbase) {
247 decode_traces_.erase(i);
248 signals_changed();
249 return;
250 }
251}
252#endif
253
254View* View::view()
255{
256 return this;
257}
258
259const View* View::view() const
260{
261 return this;
262}
263
264Viewport* View::viewport()
265{
266 return viewport_;
267}
268
269const Viewport* View::viewport() const
270{
271 return viewport_;
272}
273
274void View::save_settings(QSettings &settings) const
275{
276 settings.setValue("scale", scale_);
277 settings.setValue("v_offset",
278 scrollarea_.verticalScrollBar()->sliderPosition());
279
280 stringstream ss;
281 boost::archive::text_oarchive oa(ss);
282 oa << boost::serialization::make_nvp("offset", offset_);
283 settings.setValue("offset", QString::fromStdString(ss.str()));
284
285 for (shared_ptr<Signal> signal : signals_) {
286 settings.beginGroup(signal->base()->internal_name());
287 signal->save_settings(settings);
288 settings.endGroup();
289 }
290}
291
292void View::restore_settings(QSettings &settings)
293{
294 // Note: It is assumed that this function is only called once,
295 // immediately after restoring a previous session.
296
297 if (settings.contains("scale"))
298 set_scale(settings.value("scale").toDouble());
299
300 if (settings.contains("offset")) {
301 util::Timestamp offset;
302 stringstream ss;
303 ss << settings.value("offset").toString().toStdString();
304
305 boost::archive::text_iarchive ia(ss);
306 ia >> boost::serialization::make_nvp("offset", offset);
307
308 set_offset(offset);
309 }
310
311 for (shared_ptr<Signal> signal : signals_) {
312 settings.beginGroup(signal->base()->internal_name());
313 signal->restore_settings(settings);
314 settings.endGroup();
315 }
316
317 if (settings.contains("v_offset")) {
318 saved_v_offset_ = settings.value("v_offset").toInt();
319 set_v_offset(saved_v_offset_);
320 scroll_needs_defaults_ = false;
321 // Note: see eventFilter() for additional information
322 }
323}
324
325vector< shared_ptr<TimeItem> > View::time_items() const
326{
327 const vector<shared_ptr<Flag>> f(flags());
328 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
329 items.push_back(cursors_);
330 items.push_back(cursors_->first());
331 items.push_back(cursors_->second());
332
333 for (auto trigger_marker : trigger_markers_)
334 items.push_back(trigger_marker);
335
336 return items;
337}
338
339double View::scale() const
340{
341 return scale_;
342}
343
344void View::set_scale(double scale)
345{
346 if (scale_ != scale) {
347 scale_ = scale;
348 Q_EMIT scale_changed();
349 }
350}
351
352const Timestamp& View::offset() const
353{
354 return offset_;
355}
356
357void View::set_offset(const pv::util::Timestamp& offset)
358{
359 if (offset_ != offset) {
360 offset_ = offset;
361 Q_EMIT offset_changed();
362 }
363}
364
365int View::owner_visual_v_offset() const
366{
367 return -scrollarea_.verticalScrollBar()->sliderPosition();
368}
369
370void View::set_v_offset(int offset)
371{
372 scrollarea_.verticalScrollBar()->setSliderPosition(offset);
373 header_->update();
374 viewport_->update();
375}
376
377unsigned int View::depth() const
378{
379 return 0;
380}
381
382pv::util::SIPrefix View::tick_prefix() const
383{
384 return tick_prefix_;
385}
386
387void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
388{
389 if (tick_prefix_ != tick_prefix) {
390 tick_prefix_ = tick_prefix;
391 Q_EMIT tick_prefix_changed();
392 }
393}
394
395unsigned int View::tick_precision() const
396{
397 return tick_precision_;
398}
399
400void View::set_tick_precision(unsigned tick_precision)
401{
402 if (tick_precision_ != tick_precision) {
403 tick_precision_ = tick_precision;
404 Q_EMIT tick_precision_changed();
405 }
406}
407
408const pv::util::Timestamp& View::tick_period() const
409{
410 return tick_period_;
411}
412
413void View::set_tick_period(const pv::util::Timestamp& tick_period)
414{
415 if (tick_period_ != tick_period) {
416 tick_period_ = tick_period;
417 Q_EMIT tick_period_changed();
418 }
419}
420
421TimeUnit View::time_unit() const
422{
423 return time_unit_;
424}
425
426void View::set_time_unit(pv::util::TimeUnit time_unit)
427{
428 if (time_unit_ != time_unit) {
429 time_unit_ = time_unit;
430 Q_EMIT time_unit_changed();
431 }
432}
433
434void View::zoom(double steps)
435{
436 zoom(steps, viewport_->width() / 2);
437}
438
439void View::zoom(double steps, int offset)
440{
441 set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
442}
443
444void View::zoom_fit(bool gui_state)
445{
446 // Act as one-shot when stopped, toggle along with the GUI otherwise
447 if (session_.get_capture_state() == Session::Stopped) {
448 always_zoom_to_fit_ = false;
449 always_zoom_to_fit_changed(false);
450 } else {
451 always_zoom_to_fit_ = gui_state;
452 always_zoom_to_fit_changed(gui_state);
453 }
454
455 const pair<Timestamp, Timestamp> extents = get_time_extents();
456 const Timestamp delta = extents.second - extents.first;
457 if (delta < Timestamp("1e-12"))
458 return;
459
460 assert(viewport_);
461 const int w = viewport_->width();
462 if (w <= 0)
463 return;
464
465 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
466 set_scale_offset(scale.convert_to<double>(), extents.first);
467}
468
469void View::zoom_one_to_one()
470{
471 using pv::data::SignalData;
472
473 // Make a set of all the visible data objects
474 set< shared_ptr<SignalData> > visible_data = get_visible_data();
475 if (visible_data.empty())
476 return;
477
478 assert(viewport_);
479 const int w = viewport_->width();
480 if (w <= 0)
481 return;
482
483 set_zoom(1.0 / session_.get_samplerate(), w / 2);
484}
485
486void View::set_scale_offset(double scale, const Timestamp& offset)
487{
488 // Disable sticky scrolling / always zoom to fit when acquisition runs
489 // and user drags the viewport
490 if ((scale_ == scale) && (offset_ != offset) &&
491 (session_.get_capture_state() == Session::Running)) {
492
493 if (sticky_scrolling_) {
494 sticky_scrolling_ = false;
495 sticky_scrolling_changed(false);
496 }
497
498 if (always_zoom_to_fit_) {
499 always_zoom_to_fit_ = false;
500 always_zoom_to_fit_changed(false);
501 }
502 }
503
504 set_scale(scale);
505 set_offset(offset);
506
507 calculate_tick_spacing();
508
509 update_scroll();
510 ruler_->update();
511 viewport_->update();
512}
513
514set< shared_ptr<SignalData> > View::get_visible_data() const
515{
516 // Make a set of all the visible data objects
517 set< shared_ptr<SignalData> > visible_data;
518 for (const shared_ptr<Signal> sig : signals_)
519 if (sig->enabled())
520 visible_data.insert(sig->data());
521
522 return visible_data;
523}
524
525pair<Timestamp, Timestamp> View::get_time_extents() const
526{
527 boost::optional<Timestamp> left_time, right_time;
528 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
529 for (const shared_ptr<SignalData> d : visible_data) {
530 const vector< shared_ptr<Segment> > segments = d->segments();
531 for (const shared_ptr<Segment> &s : segments) {
532 double samplerate = s->samplerate();
533 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
534
535 const Timestamp start_time = s->start_time();
536 left_time = left_time ?
537 min(*left_time, start_time) :
538 start_time;
539 right_time = right_time ?
540 max(*right_time, start_time + d->max_sample_count() / samplerate) :
541 start_time + d->max_sample_count() / samplerate;
542 }
543 }
544
545 if (!left_time || !right_time)
546 return make_pair(0, 0);
547
548 assert(*left_time < *right_time);
549 return make_pair(*left_time, *right_time);
550}
551
552void View::enable_show_sampling_points(bool state)
553{
554 (void)state;
555
556 viewport_->update();
557}
558
559void View::enable_show_analog_minor_grid(bool state)
560{
561 (void)state;
562
563 viewport_->update();
564}
565
566void View::enable_coloured_bg(bool state)
567{
568 coloured_bg_ = state;
569 viewport_->update();
570}
571
572bool View::coloured_bg() const
573{
574 return coloured_bg_;
575}
576
577bool View::cursors_shown() const
578{
579 return show_cursors_;
580}
581
582void View::show_cursors(bool show)
583{
584 show_cursors_ = show;
585 ruler_->update();
586 viewport_->update();
587}
588
589void View::centre_cursors()
590{
591 const double time_width = scale_ * viewport_->width();
592 cursors_->first()->set_time(offset_ + time_width * 0.4);
593 cursors_->second()->set_time(offset_ + time_width * 0.6);
594 ruler_->update();
595 viewport_->update();
596}
597
598shared_ptr<CursorPair> View::cursors() const
599{
600 return cursors_;
601}
602
603void View::add_flag(const Timestamp& time)
604{
605 flags_.push_back(make_shared<Flag>(*this, time,
606 QString("%1").arg(next_flag_text_)));
607
608 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
609 (next_flag_text_ + 1);
610
611 time_item_appearance_changed(true, true);
612}
613
614void View::remove_flag(shared_ptr<Flag> flag)
615{
616 flags_.remove(flag);
617 time_item_appearance_changed(true, true);
618}
619
620vector< shared_ptr<Flag> > View::flags() const
621{
622 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
623 stable_sort(flags.begin(), flags.end(),
624 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
625 return a->time() < b->time();
626 });
627
628 return flags;
629}
630
631const QPoint& View::hover_point() const
632{
633 return hover_point_;
634}
635
636void View::restack_all_trace_tree_items()
637{
638 // Make a list of owners that is sorted from deepest first
639 const vector<shared_ptr<TraceTreeItem>> items(
640 list_by_type<TraceTreeItem>());
641 set< TraceTreeItemOwner* > owners;
642 for (const auto &r : items)
643 owners.insert(r->owner());
644 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
645 sort(sorted_owners.begin(), sorted_owners.end(),
646 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
647 return a->depth() > b->depth(); });
648
649 // Restack the items recursively
650 for (auto &o : sorted_owners)
651 o->restack_items();
652
653 // Animate the items to their destination
654 for (const auto &i : items)
655 i->animate_to_layout_v_offset();
656}
657
658void View::trigger_event(util::Timestamp location)
659{
660 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
661}
662
663void View::get_scroll_layout(double &length, Timestamp &offset) const
664{
665 const pair<Timestamp, Timestamp> extents = get_time_extents();
666 length = ((extents.second - extents.first) / scale_).convert_to<double>();
667 offset = offset_ / scale_;
668}
669
670void View::set_zoom(double scale, int offset)
671{
672 // Reset the "always zoom to fit" feature as the user changed the zoom
673 always_zoom_to_fit_ = false;
674 always_zoom_to_fit_changed(false);
675
676 const Timestamp cursor_offset = offset_ + scale_ * offset;
677 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
678 const Timestamp new_offset = cursor_offset - new_scale * offset;
679 set_scale_offset(new_scale.convert_to<double>(), new_offset);
680}
681
682void View::calculate_tick_spacing()
683{
684 const double SpacingIncrement = 10.0f;
685 const double MinValueSpacing = 40.0f;
686
687 // Figure out the highest numeric value visible on a label
688 const QSize areaSize = viewport_->size();
689 const Timestamp max_time = max(fabs(offset_),
690 fabs(offset_ + scale_ * areaSize.width()));
691
692 double min_width = SpacingIncrement;
693 double label_width, tick_period_width;
694
695 QFontMetrics m(QApplication::font());
696
697 // Copies of the member variables with the same name, used in the calculation
698 // and written back afterwards, so that we don't emit signals all the time
699 // during the calculation.
700 pv::util::Timestamp tick_period = tick_period_;
701 pv::util::SIPrefix tick_prefix = tick_prefix_;
702 unsigned tick_precision = tick_precision_;
703
704 do {
705 const double min_period = scale_ * min_width;
706
707 const int order = (int)floorf(log10f(min_period));
708 const pv::util::Timestamp order_decimal =
709 pow(pv::util::Timestamp(10), order);
710
711 // Allow for a margin of error so that a scale unit of 1 can be used.
712 // Otherwise, for a SU of 1 the tick period will almost always be below
713 // the min_period by a small amount - and thus skipped in favor of 2.
714 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
715 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
716 double tp_with_margin;
717 unsigned int unit = 0;
718
719 do {
720 tp_with_margin = order_decimal.convert_to<double>() *
721 (ScaleUnits[unit++] + tp_margin);
722 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
723
724 tick_period = order_decimal * ScaleUnits[unit - 1];
725 tick_prefix = static_cast<pv::util::SIPrefix>(
726 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
727
728 // Precision is the number of fractional digits required, not
729 // taking the prefix into account (and it must never be negative)
730 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
731
732 tick_period_width = (tick_period / scale_).convert_to<double>();
733
734 const QString label_text = Ruler::format_time_with_distance(
735 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
736
737 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
738 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
739 MinValueSpacing;
740
741 min_width += SpacingIncrement;
742 } while (tick_period_width < label_width);
743
744 set_tick_period(tick_period);
745 set_tick_prefix(tick_prefix);
746 set_tick_precision(tick_precision);
747}
748
749void View::adjust_top_margin()
750{
751 assert(viewport_);
752
753 const QSize areaSize = viewport_->size();
754
755 const pair<int, int> extents = v_extents();
756 const int top_margin = owner_visual_v_offset() + extents.first;
757 const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
758
759 // Do we have empty space at the top while the last trace goes out of screen?
760 if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
761 const int trace_height = extents.second - extents.first;
762
763 // Center everything vertically if there is enough space
764 if (areaSize.height() >= trace_height)
765 set_v_offset(extents.first -
766 ((areaSize.height() - trace_height) / 2));
767 else
768 // Remove the top margin to make as many traces fit on screen as possible
769 set_v_offset(extents.first);
770 }
771}
772
773void View::update_scroll()
774{
775 assert(viewport_);
776 QScrollBar *hscrollbar = scrollarea_.horizontalScrollBar();
777 QScrollBar *vscrollbar = scrollarea_.verticalScrollBar();
778
779 const QSize areaSize = viewport_->size();
780
781 // Set the horizontal scroll bar
782 double length = 0;
783 Timestamp offset;
784 get_scroll_layout(length, offset);
785 length = max(length - areaSize.width(), 0.0);
786
787 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
788
789 hscrollbar->setPageStep(areaSize.width() / 2);
790 hscrollbar->setSingleStep(major_tick_distance);
791
792 updating_scroll_ = true;
793
794 if (length < MaxScrollValue) {
795 hscrollbar->setRange(0, length);
796 hscrollbar->setSliderPosition(offset.convert_to<double>());
797 } else {
798 hscrollbar->setRange(0, MaxScrollValue);
799 hscrollbar->setSliderPosition(
800 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
801 }
802
803 updating_scroll_ = false;
804
805 // Set the vertical scrollbar
806 vscrollbar->setPageStep(areaSize.height());
807 vscrollbar->setSingleStep(areaSize.height() / 8);
808
809 const pair<int, int> extents = v_extents();
810
811 // Don't change the scrollbar range if there are no traces
812 if (extents.first != extents.second)
813 vscrollbar->setRange(extents.first - areaSize.height(),
814 extents.second);
815
816 if (scroll_needs_defaults_)
817 set_scroll_default();
818}
819
820void View::reset_scroll()
821{
822 scrollarea_.verticalScrollBar()->setRange(0, 0);
823}
824
825void View::set_scroll_default()
826{
827 assert(viewport_);
828
829 const QSize areaSize = viewport_->size();
830
831 const pair<int, int> extents = v_extents();
832 const int trace_height = extents.second - extents.first;
833
834 // Do all traces fit in the view?
835 if (areaSize.height() >= trace_height)
836 // Center all traces vertically
837 set_v_offset(extents.first -
838 ((areaSize.height() - trace_height) / 2));
839 else
840 // Put the first trace at the top, letting the bottom ones overflow
841 set_v_offset(extents.first);
842}
843
844void View::update_layout()
845{
846 scrollarea_.setViewportMargins(
847 header_->sizeHint().width() - Header::BaselineOffset,
848 ruler_->sizeHint().height(), 0, 0);
849 ruler_->setGeometry(viewport_->x(), 0,
850 viewport_->width(), ruler_->extended_size_hint().height());
851 header_->setGeometry(0, viewport_->y(),
852 header_->extended_size_hint().width(), viewport_->height());
853 update_scroll();
854}
855
856TraceTreeItemOwner* View::find_prevalent_trace_group(
857 const shared_ptr<sigrok::ChannelGroup> &group,
858 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
859 &signal_map)
860{
861 assert(group);
862
863 unordered_set<TraceTreeItemOwner*> owners;
864 vector<TraceTreeItemOwner*> owner_list;
865
866 // Make a set and a list of all the owners
867 for (const auto &channel : group->channels()) {
868 for (auto entry : signal_map) {
869 if (entry.first->channel() == channel) {
870 TraceTreeItemOwner *const o = (entry.second)->owner();
871 owner_list.push_back(o);
872 owners.insert(o);
873 }
874 }
875 }
876
877 // Iterate through the list of owners, and find the most prevalent
878 size_t max_prevalence = 0;
879 TraceTreeItemOwner *prevalent_owner = nullptr;
880 for (TraceTreeItemOwner *owner : owners) {
881 const size_t prevalence = count_if(
882 owner_list.begin(), owner_list.end(),
883 [&](TraceTreeItemOwner *o) { return o == owner; });
884 if (prevalence > max_prevalence) {
885 max_prevalence = prevalence;
886 prevalent_owner = owner;
887 }
888 }
889
890 return prevalent_owner;
891}
892
893vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
894 const vector< shared_ptr<sigrok::Channel> > &channels,
895 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
896 &signal_map,
897 set< shared_ptr<Trace> > &add_list)
898{
899 vector< shared_ptr<Trace> > filtered_traces;
900
901 for (const auto &channel : channels) {
902 for (auto entry : signal_map) {
903 if (entry.first->channel() == channel) {
904 shared_ptr<Trace> trace = entry.second;
905 const auto list_iter = add_list.find(trace);
906 if (list_iter == add_list.end())
907 continue;
908
909 filtered_traces.push_back(trace);
910 add_list.erase(list_iter);
911 }
912 }
913 }
914
915 return filtered_traces;
916}
917
918void View::determine_time_unit()
919{
920 // Check whether we know the sample rate and hence can use time as the unit
921 if (time_unit_ == util::TimeUnit::Samples) {
922 // Check all signals but...
923 for (const shared_ptr<Signal> signal : signals_) {
924 const shared_ptr<SignalData> data = signal->data();
925
926 // ...only check first segment of each
927 const vector< shared_ptr<Segment> > segments = data->segments();
928 if (!segments.empty())
929 if (segments[0]->samplerate()) {
930 set_time_unit(util::TimeUnit::Time);
931 break;
932 }
933 }
934 }
935}
936
937bool View::eventFilter(QObject *object, QEvent *event)
938{
939 const QEvent::Type type = event->type();
940 if (type == QEvent::MouseMove) {
941
942 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
943 if (object == viewport_)
944 hover_point_ = mouse_event->pos();
945 else if (object == ruler_)
946 hover_point_ = QPoint(mouse_event->x(), 0);
947 else if (object == header_)
948 hover_point_ = QPoint(0, mouse_event->y());
949 else
950 hover_point_ = QPoint(-1, -1);
951
952 hover_point_changed();
953
954 } else if (type == QEvent::Leave) {
955 hover_point_ = QPoint(-1, -1);
956 hover_point_changed();
957 } else if (type == QEvent::Show) {
958
959 // This is somewhat of a hack, unfortunately. We cannot use
960 // set_v_offset() from within restore_settings() as the view
961 // at that point is neither visible nor properly sized.
962 // This is the least intrusive workaround I could come up
963 // with: set the vertical offset (or scroll defaults) when
964 // the view is shown, which happens after all widgets were
965 // resized to their final sizes.
966 update_layout();
967
968 if (scroll_needs_defaults_) {
969 set_scroll_default();
970 scroll_needs_defaults_ = false;
971 }
972
973 if (saved_v_offset_) {
974 set_v_offset(saved_v_offset_);
975 saved_v_offset_ = 0;
976 }
977 }
978
979 return QObject::eventFilter(object, event);
980}
981
982void View::resizeEvent(QResizeEvent* event)
983{
984 // Only adjust the top margin if we shrunk vertically
985 if (event->size().height() < event->oldSize().height())
986 adjust_top_margin();
987
988 update_layout();
989}
990
991void View::row_item_appearance_changed(bool label, bool content)
992{
993 if (label)
994 header_->update();
995 if (content)
996 viewport_->update();
997}
998
999void View::time_item_appearance_changed(bool label, bool content)
1000{
1001 if (label)
1002 ruler_->update();
1003 if (content)
1004 viewport_->update();
1005}
1006
1007void View::extents_changed(bool horz, bool vert)
1008{
1009 sticky_events_ |=
1010 (horz ? TraceTreeItemHExtentsChanged : 0) |
1011 (vert ? TraceTreeItemVExtentsChanged : 0);
1012
1013 lazy_event_handler_.start();
1014}
1015
1016void View::h_scroll_value_changed(int value)
1017{
1018 if (updating_scroll_)
1019 return;
1020
1021 // Disable sticky scrolling when user moves the horizontal scroll bar
1022 // during a running acquisition
1023 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1024 sticky_scrolling_ = false;
1025 sticky_scrolling_changed(false);
1026 }
1027
1028 const int range = scrollarea_.horizontalScrollBar()->maximum();
1029 if (range < MaxScrollValue)
1030 set_offset(scale_ * value);
1031 else {
1032 double length = 0;
1033 Timestamp offset;
1034 get_scroll_layout(length, offset);
1035 set_offset(scale_ * length * value / MaxScrollValue);
1036 }
1037
1038 ruler_->update();
1039 viewport_->update();
1040}
1041
1042void View::v_scroll_value_changed()
1043{
1044 header_->update();
1045 viewport_->update();
1046}
1047
1048void View::signals_changed()
1049{
1050 using sigrok::Channel;
1051
1052 vector< shared_ptr<Channel> > channels;
1053 shared_ptr<sigrok::Device> sr_dev;
1054
1055 // Do we need to set the vertical scrollbar to its default position later?
1056 // We do if there are no traces, i.e. the scroll bar has no range set
1057 bool reset_scrollbar =
1058 (scrollarea_.verticalScrollBar()->minimum() ==
1059 scrollarea_.verticalScrollBar()->maximum());
1060
1061 if (!session_.device()) {
1062 reset_scroll();
1063 signals_.clear();
1064 } else {
1065 sr_dev = session_.device()->device();
1066 assert(sr_dev);
1067 channels = sr_dev->channels();
1068 }
1069
1070 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1071
1072 // Make a list of traces that are being added, and a list of traces
1073 // that are being removed
1074 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1075 const set<shared_ptr<Trace>> prev_traces(
1076 prev_trace_list.begin(), prev_trace_list.end());
1077
1078 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1079
1080#ifdef ENABLE_DECODE
1081 traces.insert(decode_traces_.begin(), decode_traces_.end());
1082#endif
1083
1084 set< shared_ptr<Trace> > add_traces;
1085 set_difference(traces.begin(), traces.end(),
1086 prev_traces.begin(), prev_traces.end(),
1087 inserter(add_traces, add_traces.begin()));
1088
1089 set< shared_ptr<Trace> > remove_traces;
1090 set_difference(prev_traces.begin(), prev_traces.end(),
1091 traces.begin(), traces.end(),
1092 inserter(remove_traces, remove_traces.begin()));
1093
1094 // Make a look-up table of sigrok Channels to pulseview Signals
1095 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1096 signal_map;
1097 for (const shared_ptr<Signal> &sig : signals_)
1098 signal_map[sig->base()] = sig;
1099
1100 // Populate channel groups
1101 if (sr_dev)
1102 for (auto entry : sr_dev->channel_groups()) {
1103 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1104
1105 if (group->channels().size() <= 1)
1106 continue;
1107
1108 // Find best trace group to add to
1109 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1110 group, signal_map);
1111
1112 // If there is no trace group, create one
1113 shared_ptr<TraceGroup> new_trace_group;
1114 if (!owner) {
1115 new_trace_group.reset(new TraceGroup());
1116 owner = new_trace_group.get();
1117 }
1118
1119 // Extract traces for the trace group, removing them from
1120 // the add list
1121 const vector< shared_ptr<Trace> > new_traces_in_group =
1122 extract_new_traces_for_channels(group->channels(),
1123 signal_map, add_traces);
1124
1125 // Add the traces to the group
1126 const pair<int, int> prev_v_extents = owner->v_extents();
1127 int offset = prev_v_extents.second - prev_v_extents.first;
1128 for (shared_ptr<Trace> trace : new_traces_in_group) {
1129 assert(trace);
1130 owner->add_child_item(trace);
1131
1132 const pair<int, int> extents = trace->v_extents();
1133 if (trace->enabled())
1134 offset += -extents.first;
1135 trace->force_to_v_offset(offset);
1136 if (trace->enabled())
1137 offset += extents.second;
1138 }
1139
1140 if (new_trace_group) {
1141 // Assign proper vertical offsets to each channel in the group
1142 new_trace_group->restack_items();
1143
1144 // If this is a new group, enqueue it in the new top level
1145 // items list
1146 if (!new_traces_in_group.empty())
1147 new_top_level_items.push_back(new_trace_group);
1148 }
1149 }
1150
1151 // Enqueue the remaining logic channels in a group
1152 vector< shared_ptr<Channel> > logic_channels;
1153 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1154 [](const shared_ptr<Channel>& c) {
1155 return c->type() == sigrok::ChannelType::LOGIC; });
1156
1157 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1158 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1159
1160 if (non_grouped_logic_signals.size() > 0) {
1161 const shared_ptr<TraceGroup> non_grouped_trace_group(
1162 make_shared<TraceGroup>());
1163 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1164 non_grouped_trace_group->add_child_item(trace);
1165
1166 non_grouped_trace_group->restack_items();
1167 new_top_level_items.push_back(non_grouped_trace_group);
1168 }
1169
1170 // Enqueue the remaining channels as free ungrouped traces
1171 const vector< shared_ptr<Trace> > new_top_level_signals =
1172 extract_new_traces_for_channels(channels, signal_map, add_traces);
1173 new_top_level_items.insert(new_top_level_items.end(),
1174 new_top_level_signals.begin(), new_top_level_signals.end());
1175
1176 // Enqueue any remaining traces i.e. decode traces
1177 new_top_level_items.insert(new_top_level_items.end(),
1178 add_traces.begin(), add_traces.end());
1179
1180 // Remove any removed traces
1181 for (shared_ptr<Trace> trace : remove_traces) {
1182 TraceTreeItemOwner *const owner = trace->owner();
1183 assert(owner);
1184 owner->remove_child_item(trace);
1185 }
1186
1187 // Remove any empty trace groups
1188 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1189 if (group->child_items().size() == 0) {
1190 remove_child_item(group);
1191 group.reset();
1192 }
1193
1194 // Add and position the pending top levels items
1195 int offset = v_extents().second;
1196 for (auto item : new_top_level_items) {
1197 add_child_item(item);
1198
1199 // Position the item after the last item or at the top if there is none
1200 const pair<int, int> extents = item->v_extents();
1201
1202 if (item->enabled())
1203 offset += -extents.first;
1204
1205 item->force_to_v_offset(offset);
1206
1207 if (item->enabled())
1208 offset += extents.second;
1209 }
1210
1211 update_layout();
1212
1213 header_->update();
1214 viewport_->update();
1215
1216 if (reset_scrollbar)
1217 set_scroll_default();
1218}
1219
1220void View::capture_state_updated(int state)
1221{
1222 if (state == Session::Running) {
1223 set_time_unit(util::TimeUnit::Samples);
1224
1225 trigger_markers_.clear();
1226
1227 // Activate "always zoom to fit" if the setting is enabled and we're
1228 // the main view of this session (other trace views may be used for
1229 // zooming and we don't want to mess them up)
1230 GlobalSettings settings;
1231 bool state = settings.value(GlobalSettings::Key_View_AlwaysZoomToFit).toBool();
1232 if (is_main_view_ && state) {
1233 always_zoom_to_fit_ = true;
1234 always_zoom_to_fit_changed(always_zoom_to_fit_);
1235 }
1236
1237 // Enable sticky scrolling if the setting is enabled
1238 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1239 }
1240
1241 if (state == Session::Stopped) {
1242 // After acquisition has stopped we need to re-calculate the ticks once
1243 // as it's otherwise done when the user pans or zooms, which is too late
1244 calculate_tick_spacing();
1245
1246 // Reset "always zoom to fit", the acquisition has stopped
1247 if (always_zoom_to_fit_) {
1248 // Perform a final zoom-to-fit before disabling
1249 zoom_fit(always_zoom_to_fit_);
1250 always_zoom_to_fit_ = false;
1251 always_zoom_to_fit_changed(always_zoom_to_fit_);
1252 }
1253 }
1254}
1255
1256void View::perform_delayed_view_update()
1257{
1258 if (always_zoom_to_fit_) {
1259 zoom_fit(true);
1260 } else if (sticky_scrolling_) {
1261 // Make right side of the view sticky
1262 double length = 0;
1263 Timestamp offset;
1264 get_scroll_layout(length, offset);
1265
1266 const QSize areaSize = viewport_->size();
1267 length = max(length - areaSize.width(), 0.0);
1268
1269 set_offset(scale_ * length);
1270 }
1271
1272 determine_time_unit();
1273 update_scroll();
1274 ruler_->update();
1275 viewport_->update();
1276}
1277
1278void View::process_sticky_events()
1279{
1280 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1281 update_layout();
1282 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1283 restack_all_trace_tree_items();
1284 update_scroll();
1285 }
1286
1287 // Clear the sticky events
1288 sticky_events_ = 0;
1289}
1290
1291void View::on_hover_point_changed()
1292{
1293 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1294 list_by_type<TraceTreeItem>());
1295 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1296 r->hover_point_changed();
1297}
1298
1299} // namespace TraceView
1300} // namespace views
1301} // namespace pv