Don't use deprecated headers.
[pulseview.git] / pv / view / view.cpp
blob23de2087c94120e030834c9e1dfb0e8ec6312952
1 /*
2 * This file is part of the PulseView project.
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
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.
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.
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/>.
20 #ifdef ENABLE_DECODE
21 #include <libsigrokdecode/libsigrokdecode.h>
22 #endif
24 #include <extdef.h>
26 #include <algorithm>
27 #include <cassert>
28 #include <climits>
29 #include <cmath>
30 #include <iostream>
31 #include <iterator>
32 #include <mutex>
33 #include <unordered_set>
35 #include <boost/archive/text_iarchive.hpp>
36 #include <boost/archive/text_oarchive.hpp>
37 #include <boost/serialization/serialization.hpp>
38 #include <boost/thread/locks.hpp>
40 #include <QApplication>
41 #include <QHBoxLayout>
42 #include <QEvent>
43 #include <QFontMetrics>
44 #include <QMouseEvent>
45 #include <QScrollBar>
47 #include <libsigrokcxx/libsigrokcxx.hpp>
49 #include "analogsignal.hpp"
50 #include "header.hpp"
51 #include "logicsignal.hpp"
52 #include "ruler.hpp"
53 #include "signal.hpp"
54 #include "tracegroup.hpp"
55 #include "triggermarker.hpp"
56 #include "view.hpp"
57 #include "viewport.hpp"
59 #include "pv/session.hpp"
60 #include "pv/globalsettings.hpp"
61 #include "pv/devices/device.hpp"
62 #include "pv/data/logic.hpp"
63 #include "pv/data/logicsegment.hpp"
64 #include "pv/util.hpp"
66 #ifdef ENABLE_DECODE
67 #include "decodetrace.hpp"
68 #endif
70 using boost::shared_lock;
71 using boost::shared_mutex;
73 using pv::data::SignalData;
74 using pv::data::Segment;
75 using pv::util::TimeUnit;
76 using pv::util::Timestamp;
78 using std::back_inserter;
79 using std::copy_if;
80 using std::deque;
81 using std::dynamic_pointer_cast;
82 using std::inserter;
83 using std::list;
84 using std::lock_guard;
85 using std::max;
86 using std::make_pair;
87 using std::make_shared;
88 using std::min;
89 using std::pair;
90 using std::set;
91 using std::set_difference;
92 using std::shared_ptr;
93 using std::unordered_map;
94 using std::unordered_set;
95 using std::vector;
96 using std::weak_ptr;
98 namespace pv {
99 namespace views {
100 namespace TraceView {
102 const Timestamp View::MaxScale("1e9");
103 const Timestamp View::MinScale("1e-12");
105 const int View::MaxScrollValue = INT_MAX / 2;
106 const int View::MaxViewAutoUpdateRate = 25; // No more than 25 Hz with sticky scrolling
108 const int View::ScaleUnits[3] = {1, 2, 5};
111 CustomAbstractScrollArea::CustomAbstractScrollArea(QWidget *parent) :
112 QAbstractScrollArea(parent)
116 void CustomAbstractScrollArea::setViewportMargins(int left, int top, int right, int bottom)
118 QAbstractScrollArea::setViewportMargins(left, top, right, bottom);
121 bool CustomAbstractScrollArea::viewportEvent(QEvent *event)
123 switch (event->type()) {
124 case QEvent::Paint:
125 case QEvent::MouseButtonPress:
126 case QEvent::MouseButtonRelease:
127 case QEvent::MouseButtonDblClick:
128 case QEvent::MouseMove:
129 case QEvent::Wheel:
130 case QEvent::TouchBegin:
131 case QEvent::TouchUpdate:
132 case QEvent::TouchEnd:
133 return false;
134 default:
135 return QAbstractScrollArea::viewportEvent(event);
139 View::View(Session &session, bool is_main_view, QWidget *parent) :
140 ViewBase(session, is_main_view, parent),
141 viewport_(new Viewport(*this)),
142 ruler_(new Ruler(*this)),
143 header_(new Header(*this)),
144 scrollarea_(this),
145 scale_(1e-3),
146 offset_(0),
147 updating_scroll_(false),
148 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
149 always_zoom_to_fit_(false),
150 tick_period_(0),
151 tick_prefix_(pv::util::SIPrefix::yocto),
152 tick_precision_(0),
153 time_unit_(util::TimeUnit::Time),
154 show_cursors_(false),
155 cursors_(new CursorPair(*this)),
156 next_flag_text_('A'),
157 trigger_markers_(),
158 hover_point_(-1, -1),
159 scroll_needs_defaults_(false),
160 saved_v_offset_(0),
161 size_finalized_(false)
163 GlobalSettings settings;
164 coloured_bg_ = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
166 connect(scrollarea_.horizontalScrollBar(), SIGNAL(valueChanged(int)),
167 this, SLOT(h_scroll_value_changed(int)));
168 connect(scrollarea_.verticalScrollBar(), SIGNAL(valueChanged(int)),
169 this, SLOT(v_scroll_value_changed()));
171 connect(header_, SIGNAL(selection_changed()),
172 ruler_, SLOT(clear_selection()));
173 connect(ruler_, SIGNAL(selection_changed()),
174 header_, SLOT(clear_selection()));
176 connect(header_, SIGNAL(selection_changed()),
177 this, SIGNAL(selection_changed()));
178 connect(ruler_, SIGNAL(selection_changed()),
179 this, SIGNAL(selection_changed()));
181 connect(this, SIGNAL(hover_point_changed()),
182 this, SLOT(on_hover_point_changed()));
184 connect(&lazy_event_handler_, SIGNAL(timeout()),
185 this, SLOT(process_sticky_events()));
186 lazy_event_handler_.setSingleShot(true);
188 connect(&delayed_view_updater_, SIGNAL(timeout()),
189 this, SLOT(perform_delayed_view_update()));
190 delayed_view_updater_.setSingleShot(true);
191 delayed_view_updater_.setInterval(1000 / MaxViewAutoUpdateRate);
193 /* To let the scroll area fill up the parent QWidget (this), we need a layout */
194 QHBoxLayout *layout = new QHBoxLayout(this);
195 setLayout(layout);
196 layout->setContentsMargins(0, 0, 0, 0);
197 layout->addWidget(&scrollarea_);
199 scrollarea_.setViewport(viewport_);
201 viewport_->installEventFilter(this);
202 ruler_->installEventFilter(this);
203 header_->installEventFilter(this);
205 // Trigger the initial event manually. The default device has signals
206 // which were created before this object came into being
207 signals_changed();
209 // make sure the transparent widgets are on the top
210 ruler_->raise();
211 header_->raise();
213 // Update the zoom state
214 calculate_tick_spacing();
217 Session& View::session()
219 return session_;
222 const Session& View::session() const
224 return session_;
227 std::unordered_set< std::shared_ptr<Signal> > View::signals() const
229 return signals_;
232 void View::clear_signals()
234 signals_.clear();
237 void View::add_signal(const shared_ptr<Signal> signal)
239 signals_.insert(signal);
242 #ifdef ENABLE_DECODE
243 void View::clear_decode_signals()
245 decode_traces_.clear();
248 void View::add_decode_signal(shared_ptr<data::SignalBase> signalbase)
250 shared_ptr<DecodeTrace> d(
251 new DecodeTrace(session_, signalbase, decode_traces_.size()));
252 decode_traces_.push_back(d);
255 void View::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
257 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
258 if ((*i)->base() == signalbase) {
259 decode_traces_.erase(i);
260 signals_changed();
261 return;
264 #endif
266 View* View::view()
268 return this;
271 const View* View::view() const
273 return this;
276 Viewport* View::viewport()
278 return viewport_;
281 const Viewport* View::viewport() const
283 return viewport_;
286 void View::save_settings(QSettings &settings) const
288 settings.setValue("scale", scale_);
289 settings.setValue("v_offset",
290 scrollarea_.verticalScrollBar()->sliderPosition());
292 std::stringstream ss;
293 boost::archive::text_oarchive oa(ss);
294 oa << boost::serialization::make_nvp("offset", offset_);
295 settings.setValue("offset", QString::fromStdString(ss.str()));
297 for (shared_ptr<Signal> signal : signals_) {
298 settings.beginGroup(signal->base()->internal_name());
299 signal->save_settings(settings);
300 settings.endGroup();
304 void View::restore_settings(QSettings &settings)
306 // Note: It is assumed that this function is only called once,
307 // immediately after restoring a previous session.
309 if (settings.contains("scale"))
310 set_scale(settings.value("scale").toDouble());
312 if (settings.contains("offset")) {
313 util::Timestamp offset;
314 std::stringstream ss;
315 ss << settings.value("offset").toString().toStdString();
317 boost::archive::text_iarchive ia(ss);
318 ia >> boost::serialization::make_nvp("offset", offset);
320 set_offset(offset);
323 for (shared_ptr<Signal> signal : signals_) {
324 settings.beginGroup(signal->base()->internal_name());
325 signal->restore_settings(settings);
326 settings.endGroup();
329 if (settings.contains("v_offset")) {
330 saved_v_offset_ = settings.value("v_offset").toInt();
331 set_v_offset(saved_v_offset_);
332 scroll_needs_defaults_ = false;
333 // Note: see resizeEvent() for additional information
337 vector< shared_ptr<TimeItem> > View::time_items() const
339 const vector<shared_ptr<Flag>> f(flags());
340 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
341 items.push_back(cursors_);
342 items.push_back(cursors_->first());
343 items.push_back(cursors_->second());
345 for (auto trigger_marker : trigger_markers_)
346 items.push_back(trigger_marker);
348 return items;
351 double View::scale() const
353 return scale_;
356 void View::set_scale(double scale)
358 if (scale_ != scale) {
359 scale_ = scale;
360 Q_EMIT scale_changed();
364 const Timestamp& View::offset() const
366 return offset_;
369 void View::set_offset(const pv::util::Timestamp& offset)
371 if (offset_ != offset) {
372 offset_ = offset;
373 Q_EMIT offset_changed();
377 int View::owner_visual_v_offset() const
379 return -scrollarea_.verticalScrollBar()->sliderPosition();
382 void View::set_v_offset(int offset)
384 scrollarea_.verticalScrollBar()->setSliderPosition(offset);
385 header_->update();
386 viewport_->update();
389 unsigned int View::depth() const
391 return 0;
394 pv::util::SIPrefix View::tick_prefix() const
396 return tick_prefix_;
399 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
401 if (tick_prefix_ != tick_prefix) {
402 tick_prefix_ = tick_prefix;
403 Q_EMIT tick_prefix_changed();
407 unsigned int View::tick_precision() const
409 return tick_precision_;
412 void View::set_tick_precision(unsigned tick_precision)
414 if (tick_precision_ != tick_precision) {
415 tick_precision_ = tick_precision;
416 Q_EMIT tick_precision_changed();
420 const pv::util::Timestamp& View::tick_period() const
422 return tick_period_;
425 void View::set_tick_period(const pv::util::Timestamp& tick_period)
427 if (tick_period_ != tick_period) {
428 tick_period_ = tick_period;
429 Q_EMIT tick_period_changed();
433 TimeUnit View::time_unit() const
435 return time_unit_;
438 void View::set_time_unit(pv::util::TimeUnit time_unit)
440 if (time_unit_ != time_unit) {
441 time_unit_ = time_unit;
442 Q_EMIT time_unit_changed();
446 void View::zoom(double steps)
448 zoom(steps, viewport_->width() / 2);
451 void View::zoom(double steps, int offset)
453 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
456 void View::zoom_fit(bool gui_state)
458 // Act as one-shot when stopped, toggle along with the GUI otherwise
459 if (session_.get_capture_state() == Session::Stopped) {
460 always_zoom_to_fit_ = false;
461 always_zoom_to_fit_changed(false);
462 } else {
463 always_zoom_to_fit_ = gui_state;
464 always_zoom_to_fit_changed(gui_state);
467 const pair<Timestamp, Timestamp> extents = get_time_extents();
468 const Timestamp delta = extents.second - extents.first;
469 if (delta < Timestamp("1e-12"))
470 return;
472 assert(viewport_);
473 const int w = viewport_->width();
474 if (w <= 0)
475 return;
477 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
478 set_scale_offset(scale.convert_to<double>(), extents.first);
481 void View::zoom_one_to_one()
483 using pv::data::SignalData;
485 // Make a set of all the visible data objects
486 set< shared_ptr<SignalData> > visible_data = get_visible_data();
487 if (visible_data.empty())
488 return;
490 assert(viewport_);
491 const int w = viewport_->width();
492 if (w <= 0)
493 return;
495 set_zoom(1.0 / session_.get_samplerate(), w / 2);
498 void View::set_scale_offset(double scale, const Timestamp& offset)
500 // Disable sticky scrolling / always zoom to fit when acquisition runs
501 // and user drags the viewport
502 if ((scale_ == scale) && (offset_ != offset) &&
503 (session_.get_capture_state() == Session::Running)) {
505 if (sticky_scrolling_) {
506 sticky_scrolling_ = false;
507 sticky_scrolling_changed(false);
510 if (always_zoom_to_fit_) {
511 always_zoom_to_fit_ = false;
512 always_zoom_to_fit_changed(false);
516 set_scale(scale);
517 set_offset(offset);
519 calculate_tick_spacing();
521 update_scroll();
522 ruler_->update();
523 viewport_->update();
526 set< shared_ptr<SignalData> > View::get_visible_data() const
528 // Make a set of all the visible data objects
529 set< shared_ptr<SignalData> > visible_data;
530 for (const shared_ptr<Signal> sig : signals_)
531 if (sig->enabled())
532 visible_data.insert(sig->data());
534 return visible_data;
537 pair<Timestamp, Timestamp> View::get_time_extents() const
539 boost::optional<Timestamp> left_time, right_time;
540 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
541 for (const shared_ptr<SignalData> d : visible_data) {
542 const vector< shared_ptr<Segment> > segments =
543 d->segments();
544 for (const shared_ptr<Segment> &s : segments) {
545 double samplerate = s->samplerate();
546 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
548 const Timestamp start_time = s->start_time();
549 left_time = left_time ?
550 min(*left_time, start_time) :
551 start_time;
552 right_time = right_time ?
553 max(*right_time, start_time + d->max_sample_count() / samplerate) :
554 start_time + d->max_sample_count() / samplerate;
558 if (!left_time || !right_time)
559 return make_pair(0, 0);
561 assert(*left_time < *right_time);
562 return make_pair(*left_time, *right_time);
565 void View::enable_sticky_scrolling(bool state)
567 sticky_scrolling_ = state;
570 void View::toggle_sticky_scrolling(void)
572 sticky_scrolling_ = !sticky_scrolling_;
575 void View::enable_coloured_bg(bool state)
577 const vector<shared_ptr<TraceTreeItem>> items(
578 list_by_type<TraceTreeItem>());
580 for (shared_ptr<TraceTreeItem> i : items) {
581 // Can't cast to Trace because it's abstract, so we need to
582 // check for any derived classes individually
584 shared_ptr<AnalogSignal> a = dynamic_pointer_cast<AnalogSignal>(i);
585 if (a)
586 a->set_coloured_bg(state);
588 shared_ptr<LogicSignal> l = dynamic_pointer_cast<LogicSignal>(i);
589 if (l)
590 l->set_coloured_bg(state);
592 #ifdef ENABLE_DECODE
593 shared_ptr<DecodeTrace> d = dynamic_pointer_cast<DecodeTrace>(i);
594 if (d)
595 d->set_coloured_bg(state);
596 #endif
599 viewport_->update();
602 bool View::cursors_shown() const
604 return show_cursors_;
607 void View::show_cursors(bool show)
609 show_cursors_ = show;
610 ruler_->update();
611 viewport_->update();
614 void View::centre_cursors()
616 const double time_width = scale_ * viewport_->width();
617 cursors_->first()->set_time(offset_ + time_width * 0.4);
618 cursors_->second()->set_time(offset_ + time_width * 0.6);
619 ruler_->update();
620 viewport_->update();
623 std::shared_ptr<CursorPair> View::cursors() const
625 return cursors_;
628 void View::add_flag(const Timestamp& time)
630 flags_.push_back(shared_ptr<Flag>(new Flag(*this, time,
631 QString("%1").arg(next_flag_text_))));
633 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
634 (next_flag_text_ + 1);
636 time_item_appearance_changed(true, true);
639 void View::remove_flag(std::shared_ptr<Flag> flag)
641 flags_.remove(flag);
642 time_item_appearance_changed(true, true);
645 vector< std::shared_ptr<Flag> > View::flags() const
647 vector< std::shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
648 stable_sort(flags.begin(), flags.end(),
649 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
650 return a->time() < b->time();
653 return flags;
656 const QPoint& View::hover_point() const
658 return hover_point_;
661 void View::restack_all_trace_tree_items()
663 // Make a list of owners that is sorted from deepest first
664 const vector<shared_ptr<TraceTreeItem>> items(
665 list_by_type<TraceTreeItem>());
666 set< TraceTreeItemOwner* > owners;
667 for (const auto &r : items)
668 owners.insert(r->owner());
669 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
670 sort(sorted_owners.begin(), sorted_owners.end(),
671 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
672 return a->depth() > b->depth(); });
674 // Restack the items recursively
675 for (auto &o : sorted_owners)
676 o->restack_items();
678 // Re-assign background colors
679 bool next_bgcolour_state = 0;
681 for (auto &o : sorted_owners)
682 next_bgcolour_state = o->reassign_bgcolour_states(next_bgcolour_state);
684 // Animate the items to their destination
685 for (const auto &i : items)
686 i->animate_to_layout_v_offset();
689 void View::trigger_event(util::Timestamp location)
691 trigger_markers_.push_back(shared_ptr<TriggerMarker>(
692 new TriggerMarker(*this, location)));
695 void View::get_scroll_layout(double &length, Timestamp &offset) const
697 const pair<Timestamp, Timestamp> extents = get_time_extents();
698 length = ((extents.second - extents.first) / scale_).convert_to<double>();
699 offset = offset_ / scale_;
702 void View::set_zoom(double scale, int offset)
704 // Reset the "always zoom to fit" feature as the user changed the zoom
705 always_zoom_to_fit_ = false;
706 always_zoom_to_fit_changed(false);
708 const Timestamp cursor_offset = offset_ + scale_ * offset;
709 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
710 const Timestamp new_offset = cursor_offset - new_scale * offset;
711 set_scale_offset(new_scale.convert_to<double>(), new_offset);
714 void View::calculate_tick_spacing()
716 const double SpacingIncrement = 10.0f;
717 const double MinValueSpacing = 40.0f;
719 // Figure out the highest numeric value visible on a label
720 const QSize areaSize = viewport_->size();
721 const Timestamp max_time = max(fabs(offset_),
722 fabs(offset_ + scale_ * areaSize.width()));
724 double min_width = SpacingIncrement;
725 double label_width, tick_period_width;
727 QFontMetrics m(QApplication::font());
729 // Copies of the member variables with the same name, used in the calculation
730 // and written back afterwards, so that we don't emit signals all the time
731 // during the calculation.
732 pv::util::Timestamp tick_period = tick_period_;
733 pv::util::SIPrefix tick_prefix = tick_prefix_;
734 unsigned tick_precision = tick_precision_;
736 do {
737 const double min_period = scale_ * min_width;
739 const int order = (int)floorf(log10f(min_period));
740 const pv::util::Timestamp order_decimal =
741 pow(pv::util::Timestamp(10), order);
743 // Allow for a margin of error so that a scale unit of 1 can be used.
744 // Otherwise, for a SU of 1 the tick period will almost always be below
745 // the min_period by a small amount - and thus skipped in favor of 2.
746 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
747 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
748 double tp_with_margin;
749 unsigned int unit = 0;
751 do {
752 tp_with_margin = order_decimal.convert_to<double>() *
753 (ScaleUnits[unit++] + tp_margin);
754 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
756 tick_period = order_decimal * ScaleUnits[unit - 1];
757 tick_prefix = static_cast<pv::util::SIPrefix>(
758 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
760 // Precision is the number of fractional digits required, not
761 // taking the prefix into account (and it must never be negative)
762 tick_precision = std::max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
764 tick_period_width = (tick_period / scale_).convert_to<double>();
766 const QString label_text = Ruler::format_time_with_distance(
767 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
769 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
770 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
771 MinValueSpacing;
773 min_width += SpacingIncrement;
774 } while (tick_period_width < label_width);
776 set_tick_period(tick_period);
777 set_tick_prefix(tick_prefix);
778 set_tick_precision(tick_precision);
781 void View::update_scroll()
783 assert(viewport_);
784 QScrollBar *hscrollbar = scrollarea_.horizontalScrollBar();
785 QScrollBar *vscrollbar = scrollarea_.verticalScrollBar();
787 const QSize areaSize = viewport_->size();
789 // Set the horizontal scroll bar
790 double length = 0;
791 Timestamp offset;
792 get_scroll_layout(length, offset);
793 length = max(length - areaSize.width(), 0.0);
795 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
797 hscrollbar->setPageStep(areaSize.width() / 2);
798 hscrollbar->setSingleStep(major_tick_distance);
800 updating_scroll_ = true;
802 if (length < MaxScrollValue) {
803 hscrollbar->setRange(0, length);
804 hscrollbar->setSliderPosition(offset.convert_to<double>());
805 } else {
806 hscrollbar->setRange(0, MaxScrollValue);
807 hscrollbar->setSliderPosition(
808 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
811 updating_scroll_ = false;
813 // Set the vertical scrollbar
814 vscrollbar->setPageStep(areaSize.height());
815 vscrollbar->setSingleStep(areaSize.height() / 8);
817 const pair<int, int> extents = v_extents();
819 // Don't change the scrollbar range if there are no traces
820 if (extents.first != extents.second)
821 vscrollbar->setRange(extents.first - areaSize.height(),
822 extents.second);
824 if (scroll_needs_defaults_)
825 set_scroll_default();
828 void View::reset_scroll()
830 scrollarea_.verticalScrollBar()->setRange(0, 0);
833 void View::set_scroll_default()
835 assert(viewport_);
837 const QSize areaSize = viewport_->size();
839 const pair<int, int> extents = v_extents();
840 const int trace_height = extents.second - extents.first;
842 // Do all traces fit in the view?
843 if (areaSize.height() >= trace_height)
844 // Center all traces vertically
845 set_v_offset(extents.first -
846 ((areaSize.height() - trace_height) / 2));
847 else
848 // Put the first trace at the top, letting the bottom ones overflow
849 set_v_offset(extents.first);
851 // If we're not sure whether setting the defaults worked as
852 // the window wasn't set up entirely yet, we want to be called
853 // again later to make sure
854 scroll_needs_defaults_ = !size_finalized_;
857 void View::update_layout()
859 scrollarea_.setViewportMargins(
860 header_->sizeHint().width() - Header::BaselineOffset,
861 ruler_->sizeHint().height(), 0, 0);
862 ruler_->setGeometry(viewport_->x(), 0,
863 viewport_->width(), ruler_->extended_size_hint().height());
864 header_->setGeometry(0, viewport_->y(),
865 header_->extended_size_hint().width(), viewport_->height());
866 update_scroll();
869 TraceTreeItemOwner* View::find_prevalent_trace_group(
870 const shared_ptr<sigrok::ChannelGroup> &group,
871 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
872 &signal_map)
874 assert(group);
876 unordered_set<TraceTreeItemOwner*> owners;
877 vector<TraceTreeItemOwner*> owner_list;
879 // Make a set and a list of all the owners
880 for (const auto &channel : group->channels()) {
881 for (auto entry : signal_map) {
882 if (entry.first->channel() == channel) {
883 TraceTreeItemOwner *const o = (entry.second)->owner();
884 owner_list.push_back(o);
885 owners.insert(o);
890 // Iterate through the list of owners, and find the most prevalent
891 size_t max_prevalence = 0;
892 TraceTreeItemOwner *prevalent_owner = nullptr;
893 for (TraceTreeItemOwner *owner : owners) {
894 const size_t prevalence = std::count_if(
895 owner_list.begin(), owner_list.end(),
896 [&](TraceTreeItemOwner *o) { return o == owner; });
897 if (prevalence > max_prevalence) {
898 max_prevalence = prevalence;
899 prevalent_owner = owner;
903 return prevalent_owner;
906 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
907 const vector< shared_ptr<sigrok::Channel> > &channels,
908 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
909 &signal_map,
910 set< shared_ptr<Trace> > &add_list)
912 vector< shared_ptr<Trace> > filtered_traces;
914 for (const auto &channel : channels) {
915 for (auto entry : signal_map) {
916 if (entry.first->channel() == channel) {
917 shared_ptr<Trace> trace = entry.second;
918 const auto list_iter = add_list.find(trace);
919 if (list_iter == add_list.end())
920 continue;
922 filtered_traces.push_back(trace);
923 add_list.erase(list_iter);
928 return filtered_traces;
931 void View::determine_time_unit()
933 // Check whether we know the sample rate and hence can use time as the unit
934 if (time_unit_ == util::TimeUnit::Samples) {
935 // Check all signals but...
936 for (const shared_ptr<Signal> signal : signals_) {
937 const shared_ptr<SignalData> data = signal->data();
939 // ...only check first segment of each
940 const vector< shared_ptr<Segment> > segments = data->segments();
941 if (!segments.empty())
942 if (segments[0]->samplerate()) {
943 set_time_unit(util::TimeUnit::Time);
944 break;
950 bool View::eventFilter(QObject *object, QEvent *event)
952 const QEvent::Type type = event->type();
953 if (type == QEvent::MouseMove) {
955 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
956 if (object == viewport_)
957 hover_point_ = mouse_event->pos();
958 else if (object == ruler_)
959 hover_point_ = QPoint(mouse_event->x(), 0);
960 else if (object == header_)
961 hover_point_ = QPoint(0, mouse_event->y());
962 else
963 hover_point_ = QPoint(-1, -1);
965 hover_point_changed();
967 } else if (type == QEvent::Leave) {
968 hover_point_ = QPoint(-1, -1);
969 hover_point_changed();
972 return QObject::eventFilter(object, event);
975 void View::resizeEvent(QResizeEvent*)
977 update_layout();
979 // This is somewhat of a hack, unfortunately. We cannot use
980 // set_v_offset() from within restore_settings() as the view
981 // at that point is neither visible nor properly sized.
982 // This is the least intrusive workaround I could come up
983 // with: set the vertical offset (or scroll defaults) when
984 // the view is visible and resized to its final size.
985 // Resize events that are sent when the view is not visible
986 // must be ignored as they have wrong sizes, potentially
987 // preventing the v offset from being set successfully.
989 if (isVisible())
990 size_finalized_ = true;
992 if (size_finalized_ && saved_v_offset_) {
993 set_v_offset(saved_v_offset_);
994 saved_v_offset_ = 0;
997 if (size_finalized_ && scroll_needs_defaults_)
998 set_scroll_default();
1001 void View::row_item_appearance_changed(bool label, bool content)
1003 if (label)
1004 header_->update();
1005 if (content)
1006 viewport_->update();
1009 void View::time_item_appearance_changed(bool label, bool content)
1011 if (label)
1012 ruler_->update();
1013 if (content)
1014 viewport_->update();
1017 void View::extents_changed(bool horz, bool vert)
1019 sticky_events_ |=
1020 (horz ? TraceTreeItemHExtentsChanged : 0) |
1021 (vert ? TraceTreeItemVExtentsChanged : 0);
1022 lazy_event_handler_.start();
1025 void View::h_scroll_value_changed(int value)
1027 if (updating_scroll_)
1028 return;
1030 // Disable sticky scrolling when user moves the horizontal scroll bar
1031 // during a running acquisition
1032 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1033 sticky_scrolling_ = false;
1034 sticky_scrolling_changed(false);
1037 const int range = scrollarea_.horizontalScrollBar()->maximum();
1038 if (range < MaxScrollValue)
1039 set_offset(scale_ * value);
1040 else {
1041 double length = 0;
1042 Timestamp offset;
1043 get_scroll_layout(length, offset);
1044 set_offset(scale_ * length * value / MaxScrollValue);
1047 ruler_->update();
1048 viewport_->update();
1051 void View::v_scroll_value_changed()
1053 header_->update();
1054 viewport_->update();
1057 void View::signals_changed()
1059 using sigrok::Channel;
1061 vector< shared_ptr<Channel> > channels;
1062 shared_ptr<sigrok::Device> sr_dev;
1064 // Do we need to set the vertical scrollbar to its default position later?
1065 // We do if there are no traces, i.e. the scroll bar has no range set
1066 bool reset_scrollbar =
1067 (scrollarea_.verticalScrollBar()->minimum() ==
1068 scrollarea_.verticalScrollBar()->maximum());
1070 if (!session_.device()) {
1071 reset_scroll();
1072 signals_.clear();
1073 } else {
1074 sr_dev = session_.device()->device();
1075 assert(sr_dev);
1076 channels = sr_dev->channels();
1079 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1081 // Make a list of traces that are being added, and a list of traces
1082 // that are being removed
1083 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1084 const set<shared_ptr<Trace>> prev_traces(
1085 prev_trace_list.begin(), prev_trace_list.end());
1087 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1089 #ifdef ENABLE_DECODE
1090 traces.insert(decode_traces_.begin(), decode_traces_.end());
1091 #endif
1093 set< shared_ptr<Trace> > add_traces;
1094 set_difference(traces.begin(), traces.end(),
1095 prev_traces.begin(), prev_traces.end(),
1096 inserter(add_traces, add_traces.begin()));
1098 set< shared_ptr<Trace> > remove_traces;
1099 set_difference(prev_traces.begin(), prev_traces.end(),
1100 traces.begin(), traces.end(),
1101 inserter(remove_traces, remove_traces.begin()));
1103 // Make a look-up table of sigrok Channels to pulseview Signals
1104 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1105 signal_map;
1106 for (const shared_ptr<Signal> &sig : signals_)
1107 signal_map[sig->base()] = sig;
1109 // Populate channel groups
1110 if (sr_dev)
1111 for (auto entry : sr_dev->channel_groups()) {
1112 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1114 if (group->channels().size() <= 1)
1115 continue;
1117 // Find best trace group to add to
1118 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1119 group, signal_map);
1121 // If there is no trace group, create one
1122 shared_ptr<TraceGroup> new_trace_group;
1123 if (!owner) {
1124 new_trace_group.reset(new TraceGroup());
1125 owner = new_trace_group.get();
1128 // Extract traces for the trace group, removing them from
1129 // the add list
1130 const vector< shared_ptr<Trace> > new_traces_in_group =
1131 extract_new_traces_for_channels(group->channels(),
1132 signal_map, add_traces);
1134 // Add the traces to the group
1135 const pair<int, int> prev_v_extents = owner->v_extents();
1136 int offset = prev_v_extents.second - prev_v_extents.first;
1137 for (shared_ptr<Trace> trace : new_traces_in_group) {
1138 assert(trace);
1139 owner->add_child_item(trace);
1141 const pair<int, int> extents = trace->v_extents();
1142 if (trace->enabled())
1143 offset += -extents.first;
1144 trace->force_to_v_offset(offset);
1145 if (trace->enabled())
1146 offset += extents.second;
1149 if (new_trace_group) {
1150 // Assign proper vertical offsets to each channel in the group
1151 new_trace_group->restack_items();
1153 // If this is a new group, enqueue it in the new top level
1154 // items list
1155 if (!new_traces_in_group.empty())
1156 new_top_level_items.push_back(new_trace_group);
1160 // Enqueue the remaining logic channels in a group
1161 vector< shared_ptr<Channel> > logic_channels;
1162 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1163 [](const shared_ptr<Channel>& c) {
1164 return c->type() == sigrok::ChannelType::LOGIC; });
1166 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1167 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1169 if (non_grouped_logic_signals.size() > 0) {
1170 const shared_ptr<TraceGroup> non_grouped_trace_group(
1171 make_shared<TraceGroup>());
1172 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1173 non_grouped_trace_group->add_child_item(trace);
1175 non_grouped_trace_group->restack_items();
1176 new_top_level_items.push_back(non_grouped_trace_group);
1179 // Enqueue the remaining channels as free ungrouped traces
1180 const vector< shared_ptr<Trace> > new_top_level_signals =
1181 extract_new_traces_for_channels(channels, signal_map, add_traces);
1182 new_top_level_items.insert(new_top_level_items.end(),
1183 new_top_level_signals.begin(), new_top_level_signals.end());
1185 // Enqueue any remaining traces i.e. decode traces
1186 new_top_level_items.insert(new_top_level_items.end(),
1187 add_traces.begin(), add_traces.end());
1189 // Remove any removed traces
1190 for (shared_ptr<Trace> trace : remove_traces) {
1191 TraceTreeItemOwner *const owner = trace->owner();
1192 assert(owner);
1193 owner->remove_child_item(trace);
1196 // Remove any empty trace groups
1197 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1198 if (group->child_items().size() == 0) {
1199 remove_child_item(group);
1200 group.reset();
1203 // Add and position the pending top levels items
1204 int offset = v_extents().second;
1205 for (auto item : new_top_level_items) {
1206 add_child_item(item);
1208 // Position the item after the last item or at the top if there is none
1209 const pair<int, int> extents = item->v_extents();
1211 if (item->enabled())
1212 offset += -extents.first;
1214 item->force_to_v_offset(offset);
1216 if (item->enabled())
1217 offset += extents.second;
1220 update_layout();
1222 header_->update();
1223 viewport_->update();
1225 if (reset_scrollbar)
1226 set_scroll_default();
1229 void View::capture_state_updated(int state)
1231 if (state == Session::Running) {
1232 set_time_unit(util::TimeUnit::Samples);
1234 trigger_markers_.clear();
1236 // Activate "always zoom to fit" if the setting is enabled and we're
1237 // the main view of this session (other trace views may be used for
1238 // zooming and we don't want to mess them up)
1239 GlobalSettings settings;
1240 bool state = settings.value(GlobalSettings::Key_View_AlwaysZoomToFit).toBool();
1241 if (is_main_view_ && state) {
1242 always_zoom_to_fit_ = true;
1243 always_zoom_to_fit_changed(always_zoom_to_fit_);
1247 if (state == Session::Stopped) {
1248 // After acquisition has stopped we need to re-calculate the ticks once
1249 // as it's otherwise done when the user pans or zooms, which is too late
1250 calculate_tick_spacing();
1252 // Reset "always zoom to fit", the acquisition has stopped
1253 if (always_zoom_to_fit_) {
1254 // Perform a final zoom-to-fit before disabling
1255 zoom_fit(always_zoom_to_fit_);
1256 always_zoom_to_fit_ = false;
1257 always_zoom_to_fit_changed(always_zoom_to_fit_);
1262 void View::data_updated()
1264 if (always_zoom_to_fit_ || sticky_scrolling_) {
1265 if (!delayed_view_updater_.isActive())
1266 delayed_view_updater_.start();
1267 } else {
1268 determine_time_unit();
1269 update_scroll();
1270 ruler_->update();
1271 viewport_->update();
1275 void View::perform_delayed_view_update()
1277 if (always_zoom_to_fit_) {
1278 zoom_fit(true);
1279 } else if (sticky_scrolling_) {
1280 // Make right side of the view sticky
1281 double length = 0;
1282 Timestamp offset;
1283 get_scroll_layout(length, offset);
1285 const QSize areaSize = viewport_->size();
1286 length = max(length - areaSize.width(), 0.0);
1288 set_offset(scale_ * length);
1291 determine_time_unit();
1292 update_scroll();
1293 ruler_->update();
1294 viewport_->update();
1297 void View::process_sticky_events()
1299 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1300 update_layout();
1301 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1302 restack_all_trace_tree_items();
1303 update_scroll();
1306 // Clear the sticky events
1307 sticky_events_ = 0;
1310 void View::on_hover_point_changed()
1312 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1313 list_by_type<TraceTreeItem>());
1314 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1315 r->hover_point_changed();
1318 } // namespace TraceView
1319 } // namespace views
1320 } // namespace pv