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 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
133 always_zoom_to_fit_(false),
135 tick_prefix_(pv::util::SIPrefix::yocto),
137 time_unit_(util::TimeUnit::Time),
138 show_cursors_(false),
139 cursors_(new CursorPair(*this)),
140 next_flag_text_('A'),
142 hover_point_(-1, -1),
143 scroll_needs_defaults_(false),
146 QVBoxLayout *root_layout = new QVBoxLayout(this);
147 root_layout->setContentsMargins(0, 0, 0, 0);
148 root_layout->addWidget(splitter_);
150 viewport_ = new Viewport(*this);
151 scrollarea_ = new CustomScrollArea(splitter_);
152 scrollarea_->setViewport(viewport_);
153 scrollarea_->setFrameShape(QFrame::NoFrame);
155 ruler_ = new Ruler(*this);
157 header_ = new Header(*this);
158 header_->setMinimumWidth(10); // So that the arrow tips show at least
160 // We put the header into a simple layout so that we can add the top margin,
161 // allowing us to make it line up with the bottom of the ruler
162 QWidget *header_container = new QWidget();
163 header_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
164 QVBoxLayout *header_layout = new QVBoxLayout(header_container);
165 header_layout->setContentsMargins(0, ruler_->sizeHint().height(), 0, 0);
166 header_layout->addWidget(header_);
168 // To let the ruler and scrollarea be on the same split pane, we need a layout
169 QWidget *trace_container = new QWidget();
170 trace_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
171 QVBoxLayout *trace_layout = new QVBoxLayout(trace_container);
172 trace_layout->setSpacing(0); // We don't want space between the ruler and scrollarea
173 trace_layout->setContentsMargins(0, 0, 0, 0);
174 trace_layout->addWidget(ruler_);
175 trace_layout->addWidget(scrollarea_);
177 splitter_->addWidget(header_container);
178 splitter_->addWidget(trace_container);
179 splitter_->setHandleWidth(1); // Don't show a visible rubber band
180 splitter_->setCollapsible(0, false); // Prevent the header from collapsing
181 splitter_->setCollapsible(1, false); // Prevent the traces from collapsing
182 splitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
184 viewport_->installEventFilter(this);
185 ruler_->installEventFilter(this);
186 header_->installEventFilter(this);
188 // Set up settings and event handlers
189 GlobalSettings settings;
190 coloured_bg_ = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
192 connect(scrollarea_->horizontalScrollBar(), SIGNAL(valueChanged(int)),
193 this, SLOT(h_scroll_value_changed(int)));
194 connect(scrollarea_->verticalScrollBar(), SIGNAL(valueChanged(int)),
195 this, SLOT(v_scroll_value_changed()));
197 connect(header_, SIGNAL(selection_changed()),
198 ruler_, SLOT(clear_selection()));
199 connect(ruler_, SIGNAL(selection_changed()),
200 header_, SLOT(clear_selection()));
202 connect(header_, SIGNAL(selection_changed()),
203 this, SIGNAL(selection_changed()));
204 connect(ruler_, SIGNAL(selection_changed()),
205 this, SIGNAL(selection_changed()));
207 connect(this, SIGNAL(hover_point_changed()),
208 this, SLOT(on_hover_point_changed()));
210 connect(&lazy_event_handler_, SIGNAL(timeout()),
211 this, SLOT(process_sticky_events()));
212 lazy_event_handler_.setSingleShot(true);
214 // Trigger the initial event manually. The default device has signals
215 // which were created before this object came into being
218 // make sure the transparent widgets are on the top
222 // Update the zoom state
223 calculate_tick_spacing();
226 Session& View::session()
231 const Session& View::session() const
236 unordered_set< shared_ptr<Signal> > View::signals() const
241 void View::clear_signals()
243 ViewBase::clear_signalbases();
247 void View::add_signal(const shared_ptr<Signal> signal)
249 ViewBase::add_signalbase(signal->base());
250 signals_.insert(signal);
254 void View::clear_decode_signals()
256 decode_traces_.clear();
259 void View::add_decode_signal(shared_ptr<data::SignalBase> signalbase)
261 shared_ptr<DecodeTrace> d(
262 new DecodeTrace(session_, signalbase, decode_traces_.size()));
263 decode_traces_.push_back(d);
266 void View::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
268 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
269 if ((*i)->base() == signalbase) {
270 decode_traces_.erase(i);
282 const View* View::view() const
287 Viewport* View::viewport()
292 const Viewport* View::viewport() const
297 void View::save_settings(QSettings &settings) const
299 settings.setValue("scale", scale_);
300 settings.setValue("v_offset",
301 scrollarea_->verticalScrollBar()->sliderPosition());
303 settings.setValue("splitter_state", splitter_->saveState());
306 boost::archive::text_oarchive oa(ss);
307 oa << boost::serialization::make_nvp("offset", offset_);
308 settings.setValue("offset", QString::fromStdString(ss.str()));
310 for (shared_ptr<Signal> signal : signals_) {
311 settings.beginGroup(signal->base()->internal_name());
312 signal->save_settings(settings);
317 void View::restore_settings(QSettings &settings)
319 // Note: It is assumed that this function is only called once,
320 // immediately after restoring a previous session.
322 if (settings.contains("scale"))
323 set_scale(settings.value("scale").toDouble());
325 if (settings.contains("offset")) {
326 util::Timestamp offset;
328 ss << settings.value("offset").toString().toStdString();
330 boost::archive::text_iarchive ia(ss);
331 ia >> boost::serialization::make_nvp("offset", offset);
336 if (settings.contains("splitter_state"))
337 splitter_->restoreState(settings.value("splitter_state").toByteArray());
339 for (shared_ptr<Signal> signal : signals_) {
340 settings.beginGroup(signal->base()->internal_name());
341 signal->restore_settings(settings);
345 if (settings.contains("v_offset")) {
346 saved_v_offset_ = settings.value("v_offset").toInt();
347 set_v_offset(saved_v_offset_);
348 scroll_needs_defaults_ = false;
349 // Note: see eventFilter() for additional information
353 vector< shared_ptr<TimeItem> > View::time_items() const
355 const vector<shared_ptr<Flag>> f(flags());
356 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
357 items.push_back(cursors_);
358 items.push_back(cursors_->first());
359 items.push_back(cursors_->second());
361 for (auto trigger_marker : trigger_markers_)
362 items.push_back(trigger_marker);
367 double View::scale() const
372 void View::set_scale(double scale)
374 if (scale_ != scale) {
376 Q_EMIT scale_changed();
380 const Timestamp& View::offset() const
385 void View::set_offset(const pv::util::Timestamp& offset)
387 if (offset_ != offset) {
389 Q_EMIT offset_changed();
393 int View::owner_visual_v_offset() const
395 return -scrollarea_->verticalScrollBar()->sliderPosition();
398 void View::set_v_offset(int offset)
400 scrollarea_->verticalScrollBar()->setSliderPosition(offset);
405 unsigned int View::depth() const
410 pv::util::SIPrefix View::tick_prefix() const
415 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
417 if (tick_prefix_ != tick_prefix) {
418 tick_prefix_ = tick_prefix;
419 Q_EMIT tick_prefix_changed();
423 unsigned int View::tick_precision() const
425 return tick_precision_;
428 void View::set_tick_precision(unsigned tick_precision)
430 if (tick_precision_ != tick_precision) {
431 tick_precision_ = tick_precision;
432 Q_EMIT tick_precision_changed();
436 const pv::util::Timestamp& View::tick_period() const
441 void View::set_tick_period(const pv::util::Timestamp& tick_period)
443 if (tick_period_ != tick_period) {
444 tick_period_ = tick_period;
445 Q_EMIT tick_period_changed();
449 TimeUnit View::time_unit() const
454 void View::set_time_unit(pv::util::TimeUnit time_unit)
456 if (time_unit_ != time_unit) {
457 time_unit_ = time_unit;
458 Q_EMIT time_unit_changed();
462 void View::zoom(double steps)
464 zoom(steps, viewport_->width() / 2);
467 void View::zoom(double steps, int offset)
469 set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
472 void View::zoom_fit(bool gui_state)
474 // Act as one-shot when stopped, toggle along with the GUI otherwise
475 if (session_.get_capture_state() == Session::Stopped) {
476 always_zoom_to_fit_ = false;
477 always_zoom_to_fit_changed(false);
479 always_zoom_to_fit_ = gui_state;
480 always_zoom_to_fit_changed(gui_state);
483 const pair<Timestamp, Timestamp> extents = get_time_extents();
484 const Timestamp delta = extents.second - extents.first;
485 if (delta < Timestamp("1e-12"))
489 const int w = viewport_->width();
493 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
494 set_scale_offset(scale.convert_to<double>(), extents.first);
497 void View::zoom_one_to_one()
499 using pv::data::SignalData;
501 // Make a set of all the visible data objects
502 set< shared_ptr<SignalData> > visible_data = get_visible_data();
503 if (visible_data.empty())
507 const int w = viewport_->width();
511 set_zoom(1.0 / session_.get_samplerate(), w / 2);
514 void View::set_scale_offset(double scale, const Timestamp& offset)
516 // Disable sticky scrolling / always zoom to fit when acquisition runs
517 // and user drags the viewport
518 if ((scale_ == scale) && (offset_ != offset) &&
519 (session_.get_capture_state() == Session::Running)) {
521 if (sticky_scrolling_) {
522 sticky_scrolling_ = false;
523 sticky_scrolling_changed(false);
526 if (always_zoom_to_fit_) {
527 always_zoom_to_fit_ = false;
528 always_zoom_to_fit_changed(false);
535 calculate_tick_spacing();
542 set< shared_ptr<SignalData> > View::get_visible_data() const
544 // Make a set of all the visible data objects
545 set< shared_ptr<SignalData> > visible_data;
546 for (const shared_ptr<Signal> sig : signals_)
548 visible_data.insert(sig->data());
553 pair<Timestamp, Timestamp> View::get_time_extents() const
555 boost::optional<Timestamp> left_time, right_time;
556 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
557 for (const shared_ptr<SignalData> d : visible_data) {
558 const vector< shared_ptr<Segment> > segments = d->segments();
559 for (const shared_ptr<Segment> &s : segments) {
560 double samplerate = s->samplerate();
561 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
563 const Timestamp start_time = s->start_time();
564 left_time = left_time ?
565 min(*left_time, start_time) :
567 right_time = right_time ?
568 max(*right_time, start_time + d->max_sample_count() / samplerate) :
569 start_time + d->max_sample_count() / samplerate;
573 if (!left_time || !right_time)
574 return make_pair(0, 0);
576 assert(*left_time < *right_time);
577 return make_pair(*left_time, *right_time);
580 void View::enable_show_sampling_points(bool state)
587 void View::enable_show_analog_minor_grid(bool state)
594 void View::enable_coloured_bg(bool state)
596 coloured_bg_ = state;
600 bool View::coloured_bg() const
605 bool View::cursors_shown() const
607 return show_cursors_;
610 void View::show_cursors(bool show)
612 show_cursors_ = show;
617 void View::centre_cursors()
619 const double time_width = scale_ * viewport_->width();
620 cursors_->first()->set_time(offset_ + time_width * 0.4);
621 cursors_->second()->set_time(offset_ + time_width * 0.6);
626 shared_ptr<CursorPair> View::cursors() const
631 void View::add_flag(const Timestamp& time)
633 flags_.push_back(make_shared<Flag>(*this, time,
634 QString("%1").arg(next_flag_text_)));
636 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
637 (next_flag_text_ + 1);
639 time_item_appearance_changed(true, true);
642 void View::remove_flag(shared_ptr<Flag> flag)
645 time_item_appearance_changed(true, true);
648 vector< shared_ptr<Flag> > View::flags() const
650 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
651 stable_sort(flags.begin(), flags.end(),
652 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
653 return a->time() < b->time();
659 const QPoint& View::hover_point() const
664 void View::restack_all_trace_tree_items()
666 // Make a list of owners that is sorted from deepest first
667 const vector<shared_ptr<TraceTreeItem>> items(
668 list_by_type<TraceTreeItem>());
669 set< TraceTreeItemOwner* > owners;
670 for (const auto &r : items)
671 owners.insert(r->owner());
672 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
673 sort(sorted_owners.begin(), sorted_owners.end(),
674 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
675 return a->depth() > b->depth(); });
677 // Restack the items recursively
678 for (auto &o : sorted_owners)
681 // Animate the items to their destination
682 for (const auto &i : items)
683 i->animate_to_layout_v_offset();
686 void View::trigger_event(util::Timestamp location)
688 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
691 void View::get_scroll_layout(double &length, Timestamp &offset) const
693 const pair<Timestamp, Timestamp> extents = get_time_extents();
694 length = ((extents.second - extents.first) / scale_).convert_to<double>();
695 offset = offset_ / scale_;
698 void View::set_zoom(double scale, int offset)
700 // Reset the "always zoom to fit" feature as the user changed the zoom
701 always_zoom_to_fit_ = false;
702 always_zoom_to_fit_changed(false);
704 const Timestamp cursor_offset = offset_ + scale_ * offset;
705 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
706 const Timestamp new_offset = cursor_offset - new_scale * offset;
707 set_scale_offset(new_scale.convert_to<double>(), new_offset);
710 void View::calculate_tick_spacing()
712 const double SpacingIncrement = 10.0f;
713 const double MinValueSpacing = 40.0f;
715 // Figure out the highest numeric value visible on a label
716 const QSize areaSize = viewport_->size();
717 const Timestamp max_time = max(fabs(offset_),
718 fabs(offset_ + scale_ * areaSize.width()));
720 double min_width = SpacingIncrement;
721 double label_width, tick_period_width;
723 QFontMetrics m(QApplication::font());
725 // Copies of the member variables with the same name, used in the calculation
726 // and written back afterwards, so that we don't emit signals all the time
727 // during the calculation.
728 pv::util::Timestamp tick_period = tick_period_;
729 pv::util::SIPrefix tick_prefix = tick_prefix_;
730 unsigned tick_precision = tick_precision_;
733 const double min_period = scale_ * min_width;
735 const int order = (int)floorf(log10f(min_period));
736 const pv::util::Timestamp order_decimal =
737 pow(pv::util::Timestamp(10), order);
739 // Allow for a margin of error so that a scale unit of 1 can be used.
740 // Otherwise, for a SU of 1 the tick period will almost always be below
741 // the min_period by a small amount - and thus skipped in favor of 2.
742 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
743 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
744 double tp_with_margin;
745 unsigned int unit = 0;
748 tp_with_margin = order_decimal.convert_to<double>() *
749 (ScaleUnits[unit++] + tp_margin);
750 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
752 tick_period = order_decimal * ScaleUnits[unit - 1];
753 tick_prefix = static_cast<pv::util::SIPrefix>(
754 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
756 // Precision is the number of fractional digits required, not
757 // taking the prefix into account (and it must never be negative)
758 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
760 tick_period_width = (tick_period / scale_).convert_to<double>();
762 const QString label_text = Ruler::format_time_with_distance(
763 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
765 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
766 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
769 min_width += SpacingIncrement;
770 } while (tick_period_width < label_width);
772 set_tick_period(tick_period);
773 set_tick_prefix(tick_prefix);
774 set_tick_precision(tick_precision);
777 void View::adjust_top_margin()
781 const QSize areaSize = viewport_->size();
783 const pair<int, int> extents = v_extents();
784 const int top_margin = owner_visual_v_offset() + extents.first;
785 const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
787 // Do we have empty space at the top while the last trace goes out of screen?
788 if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
789 const int trace_height = extents.second - extents.first;
791 // Center everything vertically if there is enough space
792 if (areaSize.height() >= trace_height)
793 set_v_offset(extents.first -
794 ((areaSize.height() - trace_height) / 2));
796 // Remove the top margin to make as many traces fit on screen as possible
797 set_v_offset(extents.first);
801 void View::update_scroll()
804 QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
805 QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
807 const QSize areaSize = viewport_->size();
809 // Set the horizontal scroll bar
812 get_scroll_layout(length, offset);
813 length = max(length - areaSize.width(), 0.0);
815 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
817 hscrollbar->setPageStep(areaSize.width() / 2);
818 hscrollbar->setSingleStep(major_tick_distance);
820 updating_scroll_ = true;
822 if (length < MaxScrollValue) {
823 hscrollbar->setRange(0, length);
824 hscrollbar->setSliderPosition(offset.convert_to<double>());
826 hscrollbar->setRange(0, MaxScrollValue);
827 hscrollbar->setSliderPosition(
828 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
831 updating_scroll_ = false;
833 // Set the vertical scrollbar
834 vscrollbar->setPageStep(areaSize.height());
835 vscrollbar->setSingleStep(areaSize.height() / 8);
837 const pair<int, int> extents = v_extents();
839 // Don't change the scrollbar range if there are no traces
840 if (extents.first != extents.second)
841 vscrollbar->setRange(extents.first - areaSize.height(),
844 if (scroll_needs_defaults_)
845 set_scroll_default();
848 void View::reset_scroll()
850 scrollarea_->verticalScrollBar()->setRange(0, 0);
853 void View::set_scroll_default()
857 const QSize areaSize = viewport_->size();
859 const pair<int, int> extents = v_extents();
860 const int trace_height = extents.second - extents.first;
862 // Do all traces fit in the view?
863 if (areaSize.height() >= trace_height)
864 // Center all traces vertically
865 set_v_offset(extents.first -
866 ((areaSize.height() - trace_height) / 2));
868 // Put the first trace at the top, letting the bottom ones overflow
869 set_v_offset(extents.first);
872 bool View::header_fully_visible() const
874 const int header_pane_width = splitter_->sizes().front();
875 const int header_width = header_->extended_size_hint().width();
877 return (header_pane_width >= header_width);
880 void View::update_layout()
882 // Only adjust pane sizes if the header hasn't been partially hidden by the user
883 if (header_fully_visible()) {
884 int splitter_area_width = 0;
885 for (int w : splitter_->sizes())
886 splitter_area_width += w;
888 // Make sure the header has enough horizontal space to show all labels fully
889 QList<int> pane_sizes;
890 pane_sizes.push_back(header_->extended_size_hint().width());
891 pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
892 splitter_->setSizes(pane_sizes);
898 TraceTreeItemOwner* View::find_prevalent_trace_group(
899 const shared_ptr<sigrok::ChannelGroup> &group,
900 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
905 unordered_set<TraceTreeItemOwner*> owners;
906 vector<TraceTreeItemOwner*> owner_list;
908 // Make a set and a list of all the owners
909 for (const auto &channel : group->channels()) {
910 for (auto entry : signal_map) {
911 if (entry.first->channel() == channel) {
912 TraceTreeItemOwner *const o = (entry.second)->owner();
913 owner_list.push_back(o);
919 // Iterate through the list of owners, and find the most prevalent
920 size_t max_prevalence = 0;
921 TraceTreeItemOwner *prevalent_owner = nullptr;
922 for (TraceTreeItemOwner *owner : owners) {
923 const size_t prevalence = count_if(
924 owner_list.begin(), owner_list.end(),
925 [&](TraceTreeItemOwner *o) { return o == owner; });
926 if (prevalence > max_prevalence) {
927 max_prevalence = prevalence;
928 prevalent_owner = owner;
932 return prevalent_owner;
935 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
936 const vector< shared_ptr<sigrok::Channel> > &channels,
937 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
939 set< shared_ptr<Trace> > &add_list)
941 vector< shared_ptr<Trace> > filtered_traces;
943 for (const auto &channel : channels) {
944 for (auto entry : signal_map) {
945 if (entry.first->channel() == channel) {
946 shared_ptr<Trace> trace = entry.second;
947 const auto list_iter = add_list.find(trace);
948 if (list_iter == add_list.end())
951 filtered_traces.push_back(trace);
952 add_list.erase(list_iter);
957 return filtered_traces;
960 void View::determine_time_unit()
962 // Check whether we know the sample rate and hence can use time as the unit
963 if (time_unit_ == util::TimeUnit::Samples) {
964 // Check all signals but...
965 for (const shared_ptr<Signal> signal : signals_) {
966 const shared_ptr<SignalData> data = signal->data();
968 // ...only check first segment of each
969 const vector< shared_ptr<Segment> > segments = data->segments();
970 if (!segments.empty())
971 if (segments[0]->samplerate()) {
972 set_time_unit(util::TimeUnit::Time);
979 bool View::eventFilter(QObject *object, QEvent *event)
981 const QEvent::Type type = event->type();
982 if (type == QEvent::MouseMove) {
984 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
985 if (object == viewport_)
986 hover_point_ = mouse_event->pos();
987 else if (object == ruler_)
988 hover_point_ = QPoint(mouse_event->x(), 0);
989 else if (object == header_)
990 hover_point_ = QPoint(0, mouse_event->y());
992 hover_point_ = QPoint(-1, -1);
994 hover_point_changed();
996 } else if (type == QEvent::Leave) {
997 hover_point_ = QPoint(-1, -1);
998 hover_point_changed();
999 } else if (type == QEvent::Show) {
1001 // This is somewhat of a hack, unfortunately. We cannot use
1002 // set_v_offset() from within restore_settings() as the view
1003 // at that point is neither visible nor properly sized.
1004 // This is the least intrusive workaround I could come up
1005 // with: set the vertical offset (or scroll defaults) when
1006 // the view is shown, which happens after all widgets were
1007 // resized to their final sizes.
1010 if (scroll_needs_defaults_) {
1011 set_scroll_default();
1012 scroll_needs_defaults_ = false;
1015 if (saved_v_offset_) {
1016 set_v_offset(saved_v_offset_);
1017 saved_v_offset_ = 0;
1021 return QObject::eventFilter(object, event);
1024 void View::resizeEvent(QResizeEvent* event)
1026 // Only adjust the top margin if we shrunk vertically
1027 if (event->size().height() < event->oldSize().height())
1028 adjust_top_margin();
1033 void View::row_item_appearance_changed(bool label, bool content)
1038 viewport_->update();
1041 void View::time_item_appearance_changed(bool label, bool content)
1046 viewport_->update();
1049 void View::extents_changed(bool horz, bool vert)
1052 (horz ? TraceTreeItemHExtentsChanged : 0) |
1053 (vert ? TraceTreeItemVExtentsChanged : 0);
1055 lazy_event_handler_.start();
1058 void View::h_scroll_value_changed(int value)
1060 if (updating_scroll_)
1063 // Disable sticky scrolling when user moves the horizontal scroll bar
1064 // during a running acquisition
1065 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1066 sticky_scrolling_ = false;
1067 sticky_scrolling_changed(false);
1070 const int range = scrollarea_->horizontalScrollBar()->maximum();
1071 if (range < MaxScrollValue)
1072 set_offset(scale_ * value);
1076 get_scroll_layout(length, offset);
1077 set_offset(scale_ * length * value / MaxScrollValue);
1081 viewport_->update();
1084 void View::v_scroll_value_changed()
1087 viewport_->update();
1090 void View::signals_changed()
1092 using sigrok::Channel;
1094 vector< shared_ptr<Channel> > channels;
1095 shared_ptr<sigrok::Device> sr_dev;
1097 // Do we need to set the vertical scrollbar to its default position later?
1098 // We do if there are no traces, i.e. the scroll bar has no range set
1099 bool reset_scrollbar =
1100 (scrollarea_->verticalScrollBar()->minimum() ==
1101 scrollarea_->verticalScrollBar()->maximum());
1103 if (!session_.device()) {
1107 sr_dev = session_.device()->device();
1109 channels = sr_dev->channels();
1112 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1114 // Make a list of traces that are being added, and a list of traces
1115 // that are being removed
1116 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1117 const set<shared_ptr<Trace>> prev_traces(
1118 prev_trace_list.begin(), prev_trace_list.end());
1120 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1122 #ifdef ENABLE_DECODE
1123 traces.insert(decode_traces_.begin(), decode_traces_.end());
1126 set< shared_ptr<Trace> > add_traces;
1127 set_difference(traces.begin(), traces.end(),
1128 prev_traces.begin(), prev_traces.end(),
1129 inserter(add_traces, add_traces.begin()));
1131 set< shared_ptr<Trace> > remove_traces;
1132 set_difference(prev_traces.begin(), prev_traces.end(),
1133 traces.begin(), traces.end(),
1134 inserter(remove_traces, remove_traces.begin()));
1136 // Make a look-up table of sigrok Channels to pulseview Signals
1137 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1139 for (const shared_ptr<Signal> &sig : signals_)
1140 signal_map[sig->base()] = sig;
1142 // Populate channel groups
1144 for (auto entry : sr_dev->channel_groups()) {
1145 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1147 if (group->channels().size() <= 1)
1150 // Find best trace group to add to
1151 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1154 // If there is no trace group, create one
1155 shared_ptr<TraceGroup> new_trace_group;
1157 new_trace_group.reset(new TraceGroup());
1158 owner = new_trace_group.get();
1161 // Extract traces for the trace group, removing them from
1163 const vector< shared_ptr<Trace> > new_traces_in_group =
1164 extract_new_traces_for_channels(group->channels(),
1165 signal_map, add_traces);
1167 // Add the traces to the group
1168 const pair<int, int> prev_v_extents = owner->v_extents();
1169 int offset = prev_v_extents.second - prev_v_extents.first;
1170 for (shared_ptr<Trace> trace : new_traces_in_group) {
1172 owner->add_child_item(trace);
1174 const pair<int, int> extents = trace->v_extents();
1175 if (trace->enabled())
1176 offset += -extents.first;
1177 trace->force_to_v_offset(offset);
1178 if (trace->enabled())
1179 offset += extents.second;
1182 if (new_trace_group) {
1183 // Assign proper vertical offsets to each channel in the group
1184 new_trace_group->restack_items();
1186 // If this is a new group, enqueue it in the new top level
1188 if (!new_traces_in_group.empty())
1189 new_top_level_items.push_back(new_trace_group);
1193 // Enqueue the remaining logic channels in a group
1194 vector< shared_ptr<Channel> > logic_channels;
1195 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1196 [](const shared_ptr<Channel>& c) {
1197 return c->type() == sigrok::ChannelType::LOGIC; });
1199 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1200 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1202 if (non_grouped_logic_signals.size() > 0) {
1203 const shared_ptr<TraceGroup> non_grouped_trace_group(
1204 make_shared<TraceGroup>());
1205 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1206 non_grouped_trace_group->add_child_item(trace);
1208 non_grouped_trace_group->restack_items();
1209 new_top_level_items.push_back(non_grouped_trace_group);
1212 // Enqueue the remaining channels as free ungrouped traces
1213 const vector< shared_ptr<Trace> > new_top_level_signals =
1214 extract_new_traces_for_channels(channels, signal_map, add_traces);
1215 new_top_level_items.insert(new_top_level_items.end(),
1216 new_top_level_signals.begin(), new_top_level_signals.end());
1218 // Enqueue any remaining traces i.e. decode traces
1219 new_top_level_items.insert(new_top_level_items.end(),
1220 add_traces.begin(), add_traces.end());
1222 // Remove any removed traces
1223 for (shared_ptr<Trace> trace : remove_traces) {
1224 TraceTreeItemOwner *const owner = trace->owner();
1226 owner->remove_child_item(trace);
1229 // Remove any empty trace groups
1230 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1231 if (group->child_items().size() == 0) {
1232 remove_child_item(group);
1236 // Add and position the pending top levels items
1237 int offset = v_extents().second;
1238 for (auto item : new_top_level_items) {
1239 add_child_item(item);
1241 // Position the item after the last item or at the top if there is none
1242 const pair<int, int> extents = item->v_extents();
1244 if (item->enabled())
1245 offset += -extents.first;
1247 item->force_to_v_offset(offset);
1249 if (item->enabled())
1250 offset += extents.second;
1256 viewport_->update();
1258 if (reset_scrollbar)
1259 set_scroll_default();
1262 void View::capture_state_updated(int state)
1264 if (state == Session::Running) {
1265 set_time_unit(util::TimeUnit::Samples);
1267 trigger_markers_.clear();
1269 // Activate "always zoom to fit" if the setting is enabled and we're
1270 // the main view of this session (other trace views may be used for
1271 // zooming and we don't want to mess them up)
1272 GlobalSettings settings;
1273 bool state = settings.value(GlobalSettings::Key_View_AlwaysZoomToFit).toBool();
1274 if (is_main_view_ && state) {
1275 always_zoom_to_fit_ = true;
1276 always_zoom_to_fit_changed(always_zoom_to_fit_);
1279 // Enable sticky scrolling if the setting is enabled
1280 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1283 if (state == Session::Stopped) {
1284 // After acquisition has stopped we need to re-calculate the ticks once
1285 // as it's otherwise done when the user pans or zooms, which is too late
1286 calculate_tick_spacing();
1288 // Reset "always zoom to fit", the acquisition has stopped
1289 if (always_zoom_to_fit_) {
1290 // Perform a final zoom-to-fit before disabling
1291 zoom_fit(always_zoom_to_fit_);
1292 always_zoom_to_fit_ = false;
1293 always_zoom_to_fit_changed(always_zoom_to_fit_);
1298 void View::perform_delayed_view_update()
1300 if (always_zoom_to_fit_) {
1302 } else if (sticky_scrolling_) {
1303 // Make right side of the view sticky
1306 get_scroll_layout(length, offset);
1308 const QSize areaSize = viewport_->size();
1309 length = max(length - areaSize.width(), 0.0);
1311 set_offset(scale_ * length);
1314 determine_time_unit();
1317 viewport_->update();
1320 void View::process_sticky_events()
1322 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1324 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1325 restack_all_trace_tree_items();
1329 // Clear the sticky events
1333 void View::on_hover_point_changed()
1335 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1336 list_by_type<TraceTreeItem>());
1337 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1338 r->hover_point_changed();
1341 } // namespace TraceView
1342 } // namespace views