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/>.
21 #include <libsigrokdecode/libsigrokdecode.h>
32 #include <unordered_set>
34 #include <boost/archive/text_iarchive.hpp>
35 #include <boost/archive/text_oarchive.hpp>
36 #include <boost/serialization/serialization.hpp>
38 #include <QApplication>
40 #include <QFontMetrics>
41 #include <QMouseEvent>
43 #include <QVBoxLayout>
45 #include <libsigrokcxx/libsigrokcxx.hpp>
47 #include "analogsignal.hpp"
49 #include "logicsignal.hpp"
52 #include "tracegroup.hpp"
53 #include "triggermarker.hpp"
55 #include "viewport.hpp"
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"
65 #include "decodetrace.hpp"
68 using pv::data::SignalData;
69 using pv::data::Segment;
70 using pv::util::TimeUnit;
71 using pv::util::Timestamp;
73 using std::back_inserter;
76 using std::dynamic_pointer_cast;
80 using std::make_shared;
84 using std::set_difference;
85 using std::shared_ptr;
86 using std::stringstream;
87 using std::unordered_map;
88 using std::unordered_set;
95 const Timestamp View::MaxScale("1e9");
96 const Timestamp View::MinScale("1e-12");
98 const int View::MaxScrollValue = INT_MAX / 2;
100 const int View::ScaleUnits[3] = {1, 2, 5};
103 CustomScrollArea::CustomScrollArea(QWidget *parent) :
104 QAbstractScrollArea(parent)
108 bool CustomScrollArea::viewportEvent(QEvent *event)
110 switch (event->type()) {
112 case QEvent::MouseButtonPress:
113 case QEvent::MouseButtonRelease:
114 case QEvent::MouseButtonDblClick:
115 case QEvent::MouseMove:
117 case QEvent::TouchBegin:
118 case QEvent::TouchUpdate:
119 case QEvent::TouchEnd:
122 return QAbstractScrollArea::viewportEvent(event);
126 View::View(Session &session, bool is_main_view, QWidget *parent) :
127 ViewBase(session, is_main_view, parent),
128 splitter_(new QSplitter()),
131 updating_scroll_(false),
132 settings_restored_(false),
133 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
134 always_zoom_to_fit_(false),
136 tick_prefix_(pv::util::SIPrefix::yocto),
138 time_unit_(util::TimeUnit::Time),
139 show_cursors_(false),
140 cursors_(new CursorPair(*this)),
141 next_flag_text_('A'),
143 hover_point_(-1, -1),
144 scroll_needs_defaults_(true),
147 QVBoxLayout *root_layout = new QVBoxLayout(this);
148 root_layout->setContentsMargins(0, 0, 0, 0);
149 root_layout->addWidget(splitter_);
151 viewport_ = new Viewport(*this);
152 scrollarea_ = new CustomScrollArea(splitter_);
153 scrollarea_->setViewport(viewport_);
154 scrollarea_->setFrameShape(QFrame::NoFrame);
156 ruler_ = new Ruler(*this);
158 header_ = new Header(*this);
159 header_->setMinimumWidth(10); // So that the arrow tips show at least
161 // We put the header into a simple layout so that we can add the top margin,
162 // allowing us to make it line up with the bottom of the ruler
163 QWidget *header_container = new QWidget();
164 header_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
165 QVBoxLayout *header_layout = new QVBoxLayout(header_container);
166 header_layout->setContentsMargins(0, ruler_->sizeHint().height(), 0, 0);
167 header_layout->addWidget(header_);
169 // To let the ruler and scrollarea be on the same split pane, we need a layout
170 QWidget *trace_container = new QWidget();
171 trace_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
172 QVBoxLayout *trace_layout = new QVBoxLayout(trace_container);
173 trace_layout->setSpacing(0); // We don't want space between the ruler and scrollarea
174 trace_layout->setContentsMargins(0, 0, 0, 0);
175 trace_layout->addWidget(ruler_);
176 trace_layout->addWidget(scrollarea_);
178 splitter_->addWidget(header_container);
179 splitter_->addWidget(trace_container);
180 splitter_->setHandleWidth(1); // Don't show a visible rubber band
181 splitter_->setCollapsible(0, false); // Prevent the header from collapsing
182 splitter_->setCollapsible(1, false); // Prevent the traces from collapsing
183 splitter_->setStretchFactor(0, 0); // Prevent the panes from being resized
184 splitter_->setStretchFactor(1, 1); // when the entire view is resized
185 splitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
187 viewport_->installEventFilter(this);
188 ruler_->installEventFilter(this);
189 header_->installEventFilter(this);
191 // Set up settings and event handlers
192 GlobalSettings settings;
193 coloured_bg_ = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
195 connect(scrollarea_->horizontalScrollBar(), SIGNAL(valueChanged(int)),
196 this, SLOT(h_scroll_value_changed(int)));
197 connect(scrollarea_->verticalScrollBar(), SIGNAL(valueChanged(int)),
198 this, SLOT(v_scroll_value_changed()));
200 connect(header_, SIGNAL(selection_changed()),
201 ruler_, SLOT(clear_selection()));
202 connect(ruler_, SIGNAL(selection_changed()),
203 header_, SLOT(clear_selection()));
205 connect(header_, SIGNAL(selection_changed()),
206 this, SIGNAL(selection_changed()));
207 connect(ruler_, SIGNAL(selection_changed()),
208 this, SIGNAL(selection_changed()));
210 connect(splitter_, SIGNAL(splitterMoved(int, int)),
211 this, SLOT(on_splitter_moved()));
213 connect(this, SIGNAL(hover_point_changed()),
214 this, SLOT(on_hover_point_changed()));
216 connect(&lazy_event_handler_, SIGNAL(timeout()),
217 this, SLOT(process_sticky_events()));
218 lazy_event_handler_.setSingleShot(true);
220 // Trigger the initial event manually. The default device has signals
221 // which were created before this object came into being
224 // make sure the transparent widgets are on the top
228 // Update the zoom state
229 calculate_tick_spacing();
232 Session& View::session()
237 const Session& View::session() const
242 unordered_set< shared_ptr<Signal> > View::signals() const
247 void View::clear_signals()
249 ViewBase::clear_signalbases();
253 void View::add_signal(const shared_ptr<Signal> signal)
255 ViewBase::add_signalbase(signal->base());
256 signals_.insert(signal);
260 void View::clear_decode_signals()
262 decode_traces_.clear();
265 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
267 shared_ptr<DecodeTrace> d(
268 new DecodeTrace(session_, signal, decode_traces_.size()));
269 decode_traces_.push_back(d);
272 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
274 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
275 if ((*i)->base() == signal) {
276 decode_traces_.erase(i);
288 const View* View::view() const
293 Viewport* View::viewport()
298 const Viewport* View::viewport() const
303 void View::save_settings(QSettings &settings) const
305 settings.setValue("scale", scale_);
306 settings.setValue("v_offset",
307 scrollarea_->verticalScrollBar()->sliderPosition());
309 settings.setValue("splitter_state", splitter_->saveState());
312 boost::archive::text_oarchive oa(ss);
313 oa << boost::serialization::make_nvp("offset", offset_);
314 settings.setValue("offset", QString::fromStdString(ss.str()));
316 for (shared_ptr<Signal> signal : signals_) {
317 settings.beginGroup(signal->base()->internal_name());
318 signal->save_settings(settings);
323 void View::restore_settings(QSettings &settings)
325 // Note: It is assumed that this function is only called once,
326 // immediately after restoring a previous session.
328 if (settings.contains("scale"))
329 set_scale(settings.value("scale").toDouble());
331 if (settings.contains("offset")) {
332 util::Timestamp offset;
334 ss << settings.value("offset").toString().toStdString();
336 boost::archive::text_iarchive ia(ss);
337 ia >> boost::serialization::make_nvp("offset", offset);
342 if (settings.contains("splitter_state"))
343 splitter_->restoreState(settings.value("splitter_state").toByteArray());
345 for (shared_ptr<Signal> signal : signals_) {
346 settings.beginGroup(signal->base()->internal_name());
347 signal->restore_settings(settings);
351 if (settings.contains("v_offset")) {
352 saved_v_offset_ = settings.value("v_offset").toInt();
353 set_v_offset(saved_v_offset_);
354 scroll_needs_defaults_ = false;
355 // Note: see eventFilter() for additional information
358 settings_restored_ = true;
361 vector< shared_ptr<TimeItem> > View::time_items() const
363 const vector<shared_ptr<Flag>> f(flags());
364 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
365 items.push_back(cursors_);
366 items.push_back(cursors_->first());
367 items.push_back(cursors_->second());
369 for (auto trigger_marker : trigger_markers_)
370 items.push_back(trigger_marker);
375 double View::scale() const
380 void View::set_scale(double scale)
382 if (scale_ != scale) {
388 const Timestamp& View::offset() const
393 void View::set_offset(const pv::util::Timestamp& offset)
395 if (offset_ != offset) {
401 int View::owner_visual_v_offset() const
403 return -scrollarea_->verticalScrollBar()->sliderPosition();
406 void View::set_v_offset(int offset)
408 scrollarea_->verticalScrollBar()->setSliderPosition(offset);
413 unsigned int View::depth() const
418 pv::util::SIPrefix View::tick_prefix() const
423 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
425 if (tick_prefix_ != tick_prefix) {
426 tick_prefix_ = tick_prefix;
427 tick_prefix_changed();
431 unsigned int View::tick_precision() const
433 return tick_precision_;
436 void View::set_tick_precision(unsigned tick_precision)
438 if (tick_precision_ != tick_precision) {
439 tick_precision_ = tick_precision;
440 tick_precision_changed();
444 const pv::util::Timestamp& View::tick_period() const
449 void View::set_tick_period(const pv::util::Timestamp& tick_period)
451 if (tick_period_ != tick_period) {
452 tick_period_ = tick_period;
453 tick_period_changed();
457 TimeUnit View::time_unit() const
462 void View::set_time_unit(pv::util::TimeUnit time_unit)
464 if (time_unit_ != time_unit) {
465 time_unit_ = time_unit;
470 void View::zoom(double steps)
472 zoom(steps, viewport_->width() / 2);
475 void View::zoom(double steps, int offset)
477 set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
480 void View::zoom_fit(bool gui_state)
482 // Act as one-shot when stopped, toggle along with the GUI otherwise
483 if (session_.get_capture_state() == Session::Stopped) {
484 always_zoom_to_fit_ = false;
485 always_zoom_to_fit_changed(false);
487 always_zoom_to_fit_ = gui_state;
488 always_zoom_to_fit_changed(gui_state);
491 const pair<Timestamp, Timestamp> extents = get_time_extents();
492 const Timestamp delta = extents.second - extents.first;
493 if (delta < Timestamp("1e-12"))
497 const int w = viewport_->width();
501 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
502 set_scale_offset(scale.convert_to<double>(), extents.first);
505 void View::zoom_one_to_one()
507 using pv::data::SignalData;
509 // Make a set of all the visible data objects
510 set< shared_ptr<SignalData> > visible_data = get_visible_data();
511 if (visible_data.empty())
515 const int w = viewport_->width();
519 set_zoom(1.0 / session_.get_samplerate(), w / 2);
522 void View::set_scale_offset(double scale, const Timestamp& offset)
524 // Disable sticky scrolling / always zoom to fit when acquisition runs
525 // and user drags the viewport
526 if ((scale_ == scale) && (offset_ != offset) &&
527 (session_.get_capture_state() == Session::Running)) {
529 if (sticky_scrolling_) {
530 sticky_scrolling_ = false;
531 sticky_scrolling_changed(false);
534 if (always_zoom_to_fit_) {
535 always_zoom_to_fit_ = false;
536 always_zoom_to_fit_changed(false);
543 calculate_tick_spacing();
550 set< shared_ptr<SignalData> > View::get_visible_data() const
552 // Make a set of all the visible data objects
553 set< shared_ptr<SignalData> > visible_data;
554 for (const shared_ptr<Signal> sig : signals_)
556 visible_data.insert(sig->data());
561 pair<Timestamp, Timestamp> View::get_time_extents() const
563 boost::optional<Timestamp> left_time, right_time;
564 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
565 for (const shared_ptr<SignalData> d : visible_data) {
566 const vector< shared_ptr<Segment> > segments = d->segments();
567 for (const shared_ptr<Segment> &s : segments) {
568 double samplerate = s->samplerate();
569 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
571 const Timestamp start_time = s->start_time();
572 left_time = left_time ?
573 min(*left_time, start_time) :
575 right_time = right_time ?
576 max(*right_time, start_time + d->max_sample_count() / samplerate) :
577 start_time + d->max_sample_count() / samplerate;
581 if (!left_time || !right_time)
582 return make_pair(0, 0);
584 assert(*left_time < *right_time);
585 return make_pair(*left_time, *right_time);
588 void View::enable_show_sampling_points(bool state)
595 void View::enable_show_analog_minor_grid(bool state)
602 void View::enable_coloured_bg(bool state)
604 coloured_bg_ = state;
608 bool View::coloured_bg() const
613 bool View::cursors_shown() const
615 return show_cursors_;
618 void View::show_cursors(bool show)
620 show_cursors_ = show;
625 void View::centre_cursors()
627 const double time_width = scale_ * viewport_->width();
628 cursors_->first()->set_time(offset_ + time_width * 0.4);
629 cursors_->second()->set_time(offset_ + time_width * 0.6);
634 shared_ptr<CursorPair> View::cursors() const
639 void View::add_flag(const Timestamp& time)
641 flags_.push_back(make_shared<Flag>(*this, time,
642 QString("%1").arg(next_flag_text_)));
644 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
645 (next_flag_text_ + 1);
647 time_item_appearance_changed(true, true);
650 void View::remove_flag(shared_ptr<Flag> flag)
653 time_item_appearance_changed(true, true);
656 vector< shared_ptr<Flag> > View::flags() const
658 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
659 stable_sort(flags.begin(), flags.end(),
660 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
661 return a->time() < b->time();
667 const QPoint& View::hover_point() const
672 void View::restack_all_trace_tree_items()
674 // Make a list of owners that is sorted from deepest first
675 const vector<shared_ptr<TraceTreeItem>> items(
676 list_by_type<TraceTreeItem>());
677 set< TraceTreeItemOwner* > owners;
678 for (const auto &r : items)
679 owners.insert(r->owner());
680 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
681 sort(sorted_owners.begin(), sorted_owners.end(),
682 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
683 return a->depth() > b->depth(); });
685 // Restack the items recursively
686 for (auto &o : sorted_owners)
689 // Animate the items to their destination
690 for (const auto &i : items)
691 i->animate_to_layout_v_offset();
694 void View::trigger_event(util::Timestamp location)
696 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
699 void View::get_scroll_layout(double &length, Timestamp &offset) const
701 const pair<Timestamp, Timestamp> extents = get_time_extents();
702 length = ((extents.second - extents.first) / scale_).convert_to<double>();
703 offset = offset_ / scale_;
706 void View::set_zoom(double scale, int offset)
708 // Reset the "always zoom to fit" feature as the user changed the zoom
709 always_zoom_to_fit_ = false;
710 always_zoom_to_fit_changed(false);
712 const Timestamp cursor_offset = offset_ + scale_ * offset;
713 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
714 const Timestamp new_offset = cursor_offset - new_scale * offset;
715 set_scale_offset(new_scale.convert_to<double>(), new_offset);
718 void View::calculate_tick_spacing()
720 const double SpacingIncrement = 10.0f;
721 const double MinValueSpacing = 40.0f;
723 // Figure out the highest numeric value visible on a label
724 const QSize areaSize = viewport_->size();
725 const Timestamp max_time = max(fabs(offset_),
726 fabs(offset_ + scale_ * areaSize.width()));
728 double min_width = SpacingIncrement;
729 double label_width, tick_period_width;
731 QFontMetrics m(QApplication::font());
733 // Copies of the member variables with the same name, used in the calculation
734 // and written back afterwards, so that we don't emit signals all the time
735 // during the calculation.
736 pv::util::Timestamp tick_period = tick_period_;
737 pv::util::SIPrefix tick_prefix = tick_prefix_;
738 unsigned tick_precision = tick_precision_;
741 const double min_period = scale_ * min_width;
743 const int order = (int)floorf(log10f(min_period));
744 const pv::util::Timestamp order_decimal =
745 pow(pv::util::Timestamp(10), order);
747 // Allow for a margin of error so that a scale unit of 1 can be used.
748 // Otherwise, for a SU of 1 the tick period will almost always be below
749 // the min_period by a small amount - and thus skipped in favor of 2.
750 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
751 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
752 double tp_with_margin;
753 unsigned int unit = 0;
756 tp_with_margin = order_decimal.convert_to<double>() *
757 (ScaleUnits[unit++] + tp_margin);
758 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
760 tick_period = order_decimal * ScaleUnits[unit - 1];
761 tick_prefix = static_cast<pv::util::SIPrefix>(
762 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
764 // Precision is the number of fractional digits required, not
765 // taking the prefix into account (and it must never be negative)
766 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
768 tick_period_width = (tick_period / scale_).convert_to<double>();
770 const QString label_text = Ruler::format_time_with_distance(
771 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
773 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
774 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
777 min_width += SpacingIncrement;
778 } while (tick_period_width < label_width);
780 set_tick_period(tick_period);
781 set_tick_prefix(tick_prefix);
782 set_tick_precision(tick_precision);
785 void View::adjust_top_margin()
789 const QSize areaSize = viewport_->size();
791 const pair<int, int> extents = v_extents();
792 const int top_margin = owner_visual_v_offset() + extents.first;
793 const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
795 // Do we have empty space at the top while the last trace goes out of screen?
796 if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
797 const int trace_height = extents.second - extents.first;
799 // Center everything vertically if there is enough space
800 if (areaSize.height() >= trace_height)
801 set_v_offset(extents.first -
802 ((areaSize.height() - trace_height) / 2));
804 // Remove the top margin to make as many traces fit on screen as possible
805 set_v_offset(extents.first);
809 void View::update_scroll()
812 QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
813 QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
815 const QSize areaSize = viewport_->size();
817 // Set the horizontal scroll bar
820 get_scroll_layout(length, offset);
821 length = max(length - areaSize.width(), 0.0);
823 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
825 hscrollbar->setPageStep(areaSize.width() / 2);
826 hscrollbar->setSingleStep(major_tick_distance);
828 updating_scroll_ = true;
830 if (length < MaxScrollValue) {
831 hscrollbar->setRange(0, length);
832 hscrollbar->setSliderPosition(offset.convert_to<double>());
834 hscrollbar->setRange(0, MaxScrollValue);
835 hscrollbar->setSliderPosition(
836 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
839 updating_scroll_ = false;
841 // Set the vertical scrollbar
842 vscrollbar->setPageStep(areaSize.height());
843 vscrollbar->setSingleStep(areaSize.height() / 8);
845 const pair<int, int> extents = v_extents();
847 // Don't change the scrollbar range if there are no traces
848 if (extents.first != extents.second)
849 vscrollbar->setRange(extents.first - areaSize.height(),
852 if (scroll_needs_defaults_)
853 set_scroll_default();
856 void View::reset_scroll()
858 scrollarea_->verticalScrollBar()->setRange(0, 0);
861 void View::set_scroll_default()
865 const QSize areaSize = viewport_->size();
867 const pair<int, int> extents = v_extents();
868 const int trace_height = extents.second - extents.first;
870 // Do all traces fit in the view?
871 if (areaSize.height() >= trace_height)
872 // Center all traces vertically
873 set_v_offset(extents.first -
874 ((areaSize.height() - trace_height) / 2));
876 // Put the first trace at the top, letting the bottom ones overflow
877 set_v_offset(extents.first);
880 bool View::header_was_shrunk() const
882 const int header_pane_width = splitter_->sizes().front();
883 const int header_width = header_->extended_size_hint().width();
885 // Allow for a slight margin of error so that we also accept
886 // slight differences when e.g. a label name change increased
888 return (header_pane_width < (header_width - 10));
891 void View::expand_header_to_fit()
893 int splitter_area_width = 0;
894 for (int w : splitter_->sizes())
895 splitter_area_width += w;
897 // Make sure the header has enough horizontal space to show all labels fully
898 QList<int> pane_sizes;
899 pane_sizes.push_back(header_->extended_size_hint().width());
900 pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
901 splitter_->setSizes(pane_sizes);
904 void View::update_layout()
909 TraceTreeItemOwner* View::find_prevalent_trace_group(
910 const shared_ptr<sigrok::ChannelGroup> &group,
911 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
916 unordered_set<TraceTreeItemOwner*> owners;
917 vector<TraceTreeItemOwner*> owner_list;
919 // Make a set and a list of all the owners
920 for (const auto &channel : group->channels()) {
921 for (auto entry : signal_map) {
922 if (entry.first->channel() == channel) {
923 TraceTreeItemOwner *const o = (entry.second)->owner();
924 owner_list.push_back(o);
930 // Iterate through the list of owners, and find the most prevalent
931 size_t max_prevalence = 0;
932 TraceTreeItemOwner *prevalent_owner = nullptr;
933 for (TraceTreeItemOwner *owner : owners) {
934 const size_t prevalence = count_if(
935 owner_list.begin(), owner_list.end(),
936 [&](TraceTreeItemOwner *o) { return o == owner; });
937 if (prevalence > max_prevalence) {
938 max_prevalence = prevalence;
939 prevalent_owner = owner;
943 return prevalent_owner;
946 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
947 const vector< shared_ptr<sigrok::Channel> > &channels,
948 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
950 set< shared_ptr<Trace> > &add_list)
952 vector< shared_ptr<Trace> > filtered_traces;
954 for (const auto &channel : channels) {
955 for (auto entry : signal_map) {
956 if (entry.first->channel() == channel) {
957 shared_ptr<Trace> trace = entry.second;
958 const auto list_iter = add_list.find(trace);
959 if (list_iter == add_list.end())
962 filtered_traces.push_back(trace);
963 add_list.erase(list_iter);
968 return filtered_traces;
971 void View::determine_time_unit()
973 // Check whether we know the sample rate and hence can use time as the unit
974 if (time_unit_ == util::TimeUnit::Samples) {
975 // Check all signals but...
976 for (const shared_ptr<Signal> signal : signals_) {
977 const shared_ptr<SignalData> data = signal->data();
979 // ...only check first segment of each
980 const vector< shared_ptr<Segment> > segments = data->segments();
981 if (!segments.empty())
982 if (segments[0]->samplerate()) {
983 set_time_unit(util::TimeUnit::Time);
990 bool View::eventFilter(QObject *object, QEvent *event)
992 const QEvent::Type type = event->type();
993 if (type == QEvent::MouseMove) {
995 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
996 if (object == viewport_)
997 hover_point_ = mouse_event->pos();
998 else if (object == ruler_)
999 hover_point_ = QPoint(mouse_event->x(), 0);
1000 else if (object == header_)
1001 hover_point_ = QPoint(0, mouse_event->y());
1003 hover_point_ = QPoint(-1, -1);
1005 hover_point_changed();
1007 } else if (type == QEvent::Leave) {
1008 hover_point_ = QPoint(-1, -1);
1009 hover_point_changed();
1010 } else if (type == QEvent::Show) {
1012 // This is somewhat of a hack, unfortunately. We cannot use
1013 // set_v_offset() from within restore_settings() as the view
1014 // at that point is neither visible nor properly sized.
1015 // This is the least intrusive workaround I could come up
1016 // with: set the vertical offset (or scroll defaults) when
1017 // the view is shown, which happens after all widgets were
1018 // resized to their final sizes.
1021 if (!settings_restored_)
1022 expand_header_to_fit();
1024 if (scroll_needs_defaults_) {
1025 set_scroll_default();
1026 scroll_needs_defaults_ = false;
1029 if (saved_v_offset_) {
1030 set_v_offset(saved_v_offset_);
1031 saved_v_offset_ = 0;
1035 return QObject::eventFilter(object, event);
1038 void View::resizeEvent(QResizeEvent* event)
1040 // Only adjust the top margin if we shrunk vertically
1041 if (event->size().height() < event->oldSize().height())
1042 adjust_top_margin();
1047 void View::row_item_appearance_changed(bool label, bool content)
1052 viewport_->update();
1055 void View::time_item_appearance_changed(bool label, bool content)
1060 // Make sure the header pane width is updated, too
1065 viewport_->update();
1068 void View::extents_changed(bool horz, bool vert)
1071 (horz ? TraceTreeItemHExtentsChanged : 0) |
1072 (vert ? TraceTreeItemVExtentsChanged : 0);
1074 lazy_event_handler_.start();
1077 void View::on_splitter_moved()
1079 // Setting the maximum width of the header widget doesn't work as
1080 // expected because the splitter would allow the user to make the
1081 // pane wider than that, creating empty space as a result.
1082 // To make this work, we stricly enforce the maximum width by
1083 // expanding the header unless the user shrunk it on purpose.
1084 // As we're then setting the width of the header pane, we set the
1085 // splitter to the maximum allowed position.
1086 if (!header_was_shrunk())
1087 expand_header_to_fit();
1090 void View::h_scroll_value_changed(int value)
1092 if (updating_scroll_)
1095 // Disable sticky scrolling when user moves the horizontal scroll bar
1096 // during a running acquisition
1097 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1098 sticky_scrolling_ = false;
1099 sticky_scrolling_changed(false);
1102 const int range = scrollarea_->horizontalScrollBar()->maximum();
1103 if (range < MaxScrollValue)
1104 set_offset(scale_ * value);
1108 get_scroll_layout(length, offset);
1109 set_offset(scale_ * length * value / MaxScrollValue);
1113 viewport_->update();
1116 void View::v_scroll_value_changed()
1119 viewport_->update();
1122 void View::signals_changed()
1124 using sigrok::Channel;
1126 vector< shared_ptr<Channel> > channels;
1127 shared_ptr<sigrok::Device> sr_dev;
1129 // Do we need to set the vertical scrollbar to its default position later?
1130 // We do if there are no traces, i.e. the scroll bar has no range set
1131 bool reset_scrollbar =
1132 (scrollarea_->verticalScrollBar()->minimum() ==
1133 scrollarea_->verticalScrollBar()->maximum());
1135 if (!session_.device()) {
1139 sr_dev = session_.device()->device();
1141 channels = sr_dev->channels();
1144 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1146 // Make a list of traces that are being added, and a list of traces
1147 // that are being removed
1148 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1149 const set<shared_ptr<Trace>> prev_traces(
1150 prev_trace_list.begin(), prev_trace_list.end());
1152 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1154 #ifdef ENABLE_DECODE
1155 traces.insert(decode_traces_.begin(), decode_traces_.end());
1158 set< shared_ptr<Trace> > add_traces;
1159 set_difference(traces.begin(), traces.end(),
1160 prev_traces.begin(), prev_traces.end(),
1161 inserter(add_traces, add_traces.begin()));
1163 set< shared_ptr<Trace> > remove_traces;
1164 set_difference(prev_traces.begin(), prev_traces.end(),
1165 traces.begin(), traces.end(),
1166 inserter(remove_traces, remove_traces.begin()));
1168 // Make a look-up table of sigrok Channels to pulseview Signals
1169 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1171 for (const shared_ptr<Signal> &sig : signals_)
1172 signal_map[sig->base()] = sig;
1174 // Populate channel groups
1176 for (auto entry : sr_dev->channel_groups()) {
1177 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1179 if (group->channels().size() <= 1)
1182 // Find best trace group to add to
1183 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1186 // If there is no trace group, create one
1187 shared_ptr<TraceGroup> new_trace_group;
1189 new_trace_group.reset(new TraceGroup());
1190 owner = new_trace_group.get();
1193 // Extract traces for the trace group, removing them from
1195 const vector< shared_ptr<Trace> > new_traces_in_group =
1196 extract_new_traces_for_channels(group->channels(),
1197 signal_map, add_traces);
1199 // Add the traces to the group
1200 const pair<int, int> prev_v_extents = owner->v_extents();
1201 int offset = prev_v_extents.second - prev_v_extents.first;
1202 for (shared_ptr<Trace> trace : new_traces_in_group) {
1204 owner->add_child_item(trace);
1206 const pair<int, int> extents = trace->v_extents();
1207 if (trace->enabled())
1208 offset += -extents.first;
1209 trace->force_to_v_offset(offset);
1210 if (trace->enabled())
1211 offset += extents.second;
1214 if (new_trace_group) {
1215 // Assign proper vertical offsets to each channel in the group
1216 new_trace_group->restack_items();
1218 // If this is a new group, enqueue it in the new top level
1220 if (!new_traces_in_group.empty())
1221 new_top_level_items.push_back(new_trace_group);
1225 // Enqueue the remaining logic channels in a group
1226 vector< shared_ptr<Channel> > logic_channels;
1227 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1228 [](const shared_ptr<Channel>& c) {
1229 return c->type() == sigrok::ChannelType::LOGIC; });
1231 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1232 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1234 if (non_grouped_logic_signals.size() > 0) {
1235 const shared_ptr<TraceGroup> non_grouped_trace_group(
1236 make_shared<TraceGroup>());
1237 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1238 non_grouped_trace_group->add_child_item(trace);
1240 non_grouped_trace_group->restack_items();
1241 new_top_level_items.push_back(non_grouped_trace_group);
1244 // Enqueue the remaining channels as free ungrouped traces
1245 const vector< shared_ptr<Trace> > new_top_level_signals =
1246 extract_new_traces_for_channels(channels, signal_map, add_traces);
1247 new_top_level_items.insert(new_top_level_items.end(),
1248 new_top_level_signals.begin(), new_top_level_signals.end());
1250 // Enqueue any remaining traces i.e. decode traces
1251 new_top_level_items.insert(new_top_level_items.end(),
1252 add_traces.begin(), add_traces.end());
1254 // Remove any removed traces
1255 for (shared_ptr<Trace> trace : remove_traces) {
1256 TraceTreeItemOwner *const owner = trace->owner();
1258 owner->remove_child_item(trace);
1261 // Remove any empty trace groups
1262 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1263 if (group->child_items().size() == 0) {
1264 remove_child_item(group);
1268 // Add and position the pending top levels items
1269 int offset = v_extents().second;
1270 for (auto item : new_top_level_items) {
1271 add_child_item(item);
1273 // Position the item after the last item or at the top if there is none
1274 const pair<int, int> extents = item->v_extents();
1276 if (item->enabled())
1277 offset += -extents.first;
1279 item->force_to_v_offset(offset);
1281 if (item->enabled())
1282 offset += extents.second;
1286 if (!new_top_level_items.empty())
1287 // Expand the header pane because the header should become fully
1288 // visible when new signals are added
1289 expand_header_to_fit();
1294 viewport_->update();
1296 if (reset_scrollbar)
1297 set_scroll_default();
1300 void View::capture_state_updated(int state)
1302 if (state == Session::Running) {
1303 set_time_unit(util::TimeUnit::Samples);
1305 trigger_markers_.clear();
1307 // Activate "always zoom to fit" if the setting is enabled and we're
1308 // the main view of this session (other trace views may be used for
1309 // zooming and we don't want to mess them up)
1310 GlobalSettings settings;
1311 bool state = settings.value(GlobalSettings::Key_View_AlwaysZoomToFit).toBool();
1312 if (is_main_view_ && state) {
1313 always_zoom_to_fit_ = true;
1314 always_zoom_to_fit_changed(always_zoom_to_fit_);
1317 // Enable sticky scrolling if the setting is enabled
1318 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1321 if (state == Session::Stopped) {
1322 // After acquisition has stopped we need to re-calculate the ticks once
1323 // as it's otherwise done when the user pans or zooms, which is too late
1324 calculate_tick_spacing();
1326 // Reset "always zoom to fit", the acquisition has stopped
1327 if (always_zoom_to_fit_) {
1328 // Perform a final zoom-to-fit before disabling
1329 zoom_fit(always_zoom_to_fit_);
1330 always_zoom_to_fit_ = false;
1331 always_zoom_to_fit_changed(always_zoom_to_fit_);
1336 void View::perform_delayed_view_update()
1338 if (always_zoom_to_fit_) {
1340 } else if (sticky_scrolling_) {
1341 // Make right side of the view sticky
1344 get_scroll_layout(length, offset);
1346 const QSize areaSize = viewport_->size();
1347 length = max(length - areaSize.width(), 0.0);
1349 set_offset(scale_ * length);
1352 determine_time_unit();
1355 viewport_->update();
1358 void View::process_sticky_events()
1360 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1362 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1363 restack_all_trace_tree_items();
1367 // Clear the sticky events
1371 void View::on_hover_point_changed()
1373 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1374 list_by_type<TraceTreeItem>());
1375 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1376 r->hover_point_changed();
1379 } // namespace trace
1380 } // namespace views