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(15); // 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());
304 boost::archive::text_oarchive oa(ss);
305 oa << boost::serialization::make_nvp("offset", offset_);
306 settings.setValue("offset", QString::fromStdString(ss.str()));
308 for (shared_ptr<Signal> signal : signals_) {
309 settings.beginGroup(signal->base()->internal_name());
310 signal->save_settings(settings);
315 void View::restore_settings(QSettings &settings)
317 // Note: It is assumed that this function is only called once,
318 // immediately after restoring a previous session.
320 if (settings.contains("scale"))
321 set_scale(settings.value("scale").toDouble());
323 if (settings.contains("offset")) {
324 util::Timestamp offset;
326 ss << settings.value("offset").toString().toStdString();
328 boost::archive::text_iarchive ia(ss);
329 ia >> boost::serialization::make_nvp("offset", offset);
334 for (shared_ptr<Signal> signal : signals_) {
335 settings.beginGroup(signal->base()->internal_name());
336 signal->restore_settings(settings);
340 if (settings.contains("v_offset")) {
341 saved_v_offset_ = settings.value("v_offset").toInt();
342 set_v_offset(saved_v_offset_);
343 scroll_needs_defaults_ = false;
344 // Note: see eventFilter() for additional information
348 vector< shared_ptr<TimeItem> > View::time_items() const
350 const vector<shared_ptr<Flag>> f(flags());
351 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
352 items.push_back(cursors_);
353 items.push_back(cursors_->first());
354 items.push_back(cursors_->second());
356 for (auto trigger_marker : trigger_markers_)
357 items.push_back(trigger_marker);
362 double View::scale() const
367 void View::set_scale(double scale)
369 if (scale_ != scale) {
371 Q_EMIT scale_changed();
375 const Timestamp& View::offset() const
380 void View::set_offset(const pv::util::Timestamp& offset)
382 if (offset_ != offset) {
384 Q_EMIT offset_changed();
388 int View::owner_visual_v_offset() const
390 return -scrollarea_->verticalScrollBar()->sliderPosition();
393 void View::set_v_offset(int offset)
395 scrollarea_->verticalScrollBar()->setSliderPosition(offset);
400 unsigned int View::depth() const
405 pv::util::SIPrefix View::tick_prefix() const
410 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
412 if (tick_prefix_ != tick_prefix) {
413 tick_prefix_ = tick_prefix;
414 Q_EMIT tick_prefix_changed();
418 unsigned int View::tick_precision() const
420 return tick_precision_;
423 void View::set_tick_precision(unsigned tick_precision)
425 if (tick_precision_ != tick_precision) {
426 tick_precision_ = tick_precision;
427 Q_EMIT tick_precision_changed();
431 const pv::util::Timestamp& View::tick_period() const
436 void View::set_tick_period(const pv::util::Timestamp& tick_period)
438 if (tick_period_ != tick_period) {
439 tick_period_ = tick_period;
440 Q_EMIT tick_period_changed();
444 TimeUnit View::time_unit() const
449 void View::set_time_unit(pv::util::TimeUnit time_unit)
451 if (time_unit_ != time_unit) {
452 time_unit_ = time_unit;
453 Q_EMIT time_unit_changed();
457 void View::zoom(double steps)
459 zoom(steps, viewport_->width() / 2);
462 void View::zoom(double steps, int offset)
464 set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
467 void View::zoom_fit(bool gui_state)
469 // Act as one-shot when stopped, toggle along with the GUI otherwise
470 if (session_.get_capture_state() == Session::Stopped) {
471 always_zoom_to_fit_ = false;
472 always_zoom_to_fit_changed(false);
474 always_zoom_to_fit_ = gui_state;
475 always_zoom_to_fit_changed(gui_state);
478 const pair<Timestamp, Timestamp> extents = get_time_extents();
479 const Timestamp delta = extents.second - extents.first;
480 if (delta < Timestamp("1e-12"))
484 const int w = viewport_->width();
488 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
489 set_scale_offset(scale.convert_to<double>(), extents.first);
492 void View::zoom_one_to_one()
494 using pv::data::SignalData;
496 // Make a set of all the visible data objects
497 set< shared_ptr<SignalData> > visible_data = get_visible_data();
498 if (visible_data.empty())
502 const int w = viewport_->width();
506 set_zoom(1.0 / session_.get_samplerate(), w / 2);
509 void View::set_scale_offset(double scale, const Timestamp& offset)
511 // Disable sticky scrolling / always zoom to fit when acquisition runs
512 // and user drags the viewport
513 if ((scale_ == scale) && (offset_ != offset) &&
514 (session_.get_capture_state() == Session::Running)) {
516 if (sticky_scrolling_) {
517 sticky_scrolling_ = false;
518 sticky_scrolling_changed(false);
521 if (always_zoom_to_fit_) {
522 always_zoom_to_fit_ = false;
523 always_zoom_to_fit_changed(false);
530 calculate_tick_spacing();
537 set< shared_ptr<SignalData> > View::get_visible_data() const
539 // Make a set of all the visible data objects
540 set< shared_ptr<SignalData> > visible_data;
541 for (const shared_ptr<Signal> sig : signals_)
543 visible_data.insert(sig->data());
548 pair<Timestamp, Timestamp> View::get_time_extents() const
550 boost::optional<Timestamp> left_time, right_time;
551 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
552 for (const shared_ptr<SignalData> d : visible_data) {
553 const vector< shared_ptr<Segment> > segments = d->segments();
554 for (const shared_ptr<Segment> &s : segments) {
555 double samplerate = s->samplerate();
556 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
558 const Timestamp start_time = s->start_time();
559 left_time = left_time ?
560 min(*left_time, start_time) :
562 right_time = right_time ?
563 max(*right_time, start_time + d->max_sample_count() / samplerate) :
564 start_time + d->max_sample_count() / samplerate;
568 if (!left_time || !right_time)
569 return make_pair(0, 0);
571 assert(*left_time < *right_time);
572 return make_pair(*left_time, *right_time);
575 void View::enable_show_sampling_points(bool state)
582 void View::enable_show_analog_minor_grid(bool state)
589 void View::enable_coloured_bg(bool state)
591 coloured_bg_ = state;
595 bool View::coloured_bg() const
600 bool View::cursors_shown() const
602 return show_cursors_;
605 void View::show_cursors(bool show)
607 show_cursors_ = show;
612 void View::centre_cursors()
614 const double time_width = scale_ * viewport_->width();
615 cursors_->first()->set_time(offset_ + time_width * 0.4);
616 cursors_->second()->set_time(offset_ + time_width * 0.6);
621 shared_ptr<CursorPair> View::cursors() const
626 void View::add_flag(const Timestamp& time)
628 flags_.push_back(make_shared<Flag>(*this, time,
629 QString("%1").arg(next_flag_text_)));
631 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
632 (next_flag_text_ + 1);
634 time_item_appearance_changed(true, true);
637 void View::remove_flag(shared_ptr<Flag> flag)
640 time_item_appearance_changed(true, true);
643 vector< shared_ptr<Flag> > View::flags() const
645 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
646 stable_sort(flags.begin(), flags.end(),
647 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
648 return a->time() < b->time();
654 const QPoint& View::hover_point() const
659 void View::restack_all_trace_tree_items()
661 // Make a list of owners that is sorted from deepest first
662 const vector<shared_ptr<TraceTreeItem>> items(
663 list_by_type<TraceTreeItem>());
664 set< TraceTreeItemOwner* > owners;
665 for (const auto &r : items)
666 owners.insert(r->owner());
667 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
668 sort(sorted_owners.begin(), sorted_owners.end(),
669 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
670 return a->depth() > b->depth(); });
672 // Restack the items recursively
673 for (auto &o : sorted_owners)
676 // Animate the items to their destination
677 for (const auto &i : items)
678 i->animate_to_layout_v_offset();
681 void View::trigger_event(util::Timestamp location)
683 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
686 void View::get_scroll_layout(double &length, Timestamp &offset) const
688 const pair<Timestamp, Timestamp> extents = get_time_extents();
689 length = ((extents.second - extents.first) / scale_).convert_to<double>();
690 offset = offset_ / scale_;
693 void View::set_zoom(double scale, int offset)
695 // Reset the "always zoom to fit" feature as the user changed the zoom
696 always_zoom_to_fit_ = false;
697 always_zoom_to_fit_changed(false);
699 const Timestamp cursor_offset = offset_ + scale_ * offset;
700 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
701 const Timestamp new_offset = cursor_offset - new_scale * offset;
702 set_scale_offset(new_scale.convert_to<double>(), new_offset);
705 void View::calculate_tick_spacing()
707 const double SpacingIncrement = 10.0f;
708 const double MinValueSpacing = 40.0f;
710 // Figure out the highest numeric value visible on a label
711 const QSize areaSize = viewport_->size();
712 const Timestamp max_time = max(fabs(offset_),
713 fabs(offset_ + scale_ * areaSize.width()));
715 double min_width = SpacingIncrement;
716 double label_width, tick_period_width;
718 QFontMetrics m(QApplication::font());
720 // Copies of the member variables with the same name, used in the calculation
721 // and written back afterwards, so that we don't emit signals all the time
722 // during the calculation.
723 pv::util::Timestamp tick_period = tick_period_;
724 pv::util::SIPrefix tick_prefix = tick_prefix_;
725 unsigned tick_precision = tick_precision_;
728 const double min_period = scale_ * min_width;
730 const int order = (int)floorf(log10f(min_period));
731 const pv::util::Timestamp order_decimal =
732 pow(pv::util::Timestamp(10), order);
734 // Allow for a margin of error so that a scale unit of 1 can be used.
735 // Otherwise, for a SU of 1 the tick period will almost always be below
736 // the min_period by a small amount - and thus skipped in favor of 2.
737 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
738 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
739 double tp_with_margin;
740 unsigned int unit = 0;
743 tp_with_margin = order_decimal.convert_to<double>() *
744 (ScaleUnits[unit++] + tp_margin);
745 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
747 tick_period = order_decimal * ScaleUnits[unit - 1];
748 tick_prefix = static_cast<pv::util::SIPrefix>(
749 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
751 // Precision is the number of fractional digits required, not
752 // taking the prefix into account (and it must never be negative)
753 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
755 tick_period_width = (tick_period / scale_).convert_to<double>();
757 const QString label_text = Ruler::format_time_with_distance(
758 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
760 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
761 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
764 min_width += SpacingIncrement;
765 } while (tick_period_width < label_width);
767 set_tick_period(tick_period);
768 set_tick_prefix(tick_prefix);
769 set_tick_precision(tick_precision);
772 void View::adjust_top_margin()
776 const QSize areaSize = viewport_->size();
778 const pair<int, int> extents = v_extents();
779 const int top_margin = owner_visual_v_offset() + extents.first;
780 const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
782 // Do we have empty space at the top while the last trace goes out of screen?
783 if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
784 const int trace_height = extents.second - extents.first;
786 // Center everything vertically if there is enough space
787 if (areaSize.height() >= trace_height)
788 set_v_offset(extents.first -
789 ((areaSize.height() - trace_height) / 2));
791 // Remove the top margin to make as many traces fit on screen as possible
792 set_v_offset(extents.first);
796 void View::update_scroll()
799 QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
800 QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
802 const QSize areaSize = viewport_->size();
804 // Set the horizontal scroll bar
807 get_scroll_layout(length, offset);
808 length = max(length - areaSize.width(), 0.0);
810 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
812 hscrollbar->setPageStep(areaSize.width() / 2);
813 hscrollbar->setSingleStep(major_tick_distance);
815 updating_scroll_ = true;
817 if (length < MaxScrollValue) {
818 hscrollbar->setRange(0, length);
819 hscrollbar->setSliderPosition(offset.convert_to<double>());
821 hscrollbar->setRange(0, MaxScrollValue);
822 hscrollbar->setSliderPosition(
823 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
826 updating_scroll_ = false;
828 // Set the vertical scrollbar
829 vscrollbar->setPageStep(areaSize.height());
830 vscrollbar->setSingleStep(areaSize.height() / 8);
832 const pair<int, int> extents = v_extents();
834 // Don't change the scrollbar range if there are no traces
835 if (extents.first != extents.second)
836 vscrollbar->setRange(extents.first - areaSize.height(),
839 if (scroll_needs_defaults_)
840 set_scroll_default();
843 void View::reset_scroll()
845 scrollarea_->verticalScrollBar()->setRange(0, 0);
848 void View::set_scroll_default()
852 const QSize areaSize = viewport_->size();
854 const pair<int, int> extents = v_extents();
855 const int trace_height = extents.second - extents.first;
857 // Do all traces fit in the view?
858 if (areaSize.height() >= trace_height)
859 // Center all traces vertically
860 set_v_offset(extents.first -
861 ((areaSize.height() - trace_height) / 2));
863 // Put the first trace at the top, letting the bottom ones overflow
864 set_v_offset(extents.first);
867 bool View::header_fully_visible() const
869 const int header_pane_width = splitter_->sizes().front();
870 const int header_width = header_->extended_size_hint().width();
872 return (header_pane_width >= header_width);
875 void View::update_layout()
877 // Only adjust pane sizes if the header hasn't been partially hidden by the user
878 if (header_fully_visible()) {
879 int splitter_area_width = 0;
880 for (int w : splitter_->sizes())
881 splitter_area_width += w;
883 // Make sure the header has enough horizontal space to show all labels fully
884 QList<int> pane_sizes;
885 pane_sizes.push_back(header_->extended_size_hint().width());
886 pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
887 splitter_->setSizes(pane_sizes);
893 TraceTreeItemOwner* View::find_prevalent_trace_group(
894 const shared_ptr<sigrok::ChannelGroup> &group,
895 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
900 unordered_set<TraceTreeItemOwner*> owners;
901 vector<TraceTreeItemOwner*> owner_list;
903 // Make a set and a list of all the owners
904 for (const auto &channel : group->channels()) {
905 for (auto entry : signal_map) {
906 if (entry.first->channel() == channel) {
907 TraceTreeItemOwner *const o = (entry.second)->owner();
908 owner_list.push_back(o);
914 // Iterate through the list of owners, and find the most prevalent
915 size_t max_prevalence = 0;
916 TraceTreeItemOwner *prevalent_owner = nullptr;
917 for (TraceTreeItemOwner *owner : owners) {
918 const size_t prevalence = count_if(
919 owner_list.begin(), owner_list.end(),
920 [&](TraceTreeItemOwner *o) { return o == owner; });
921 if (prevalence > max_prevalence) {
922 max_prevalence = prevalence;
923 prevalent_owner = owner;
927 return prevalent_owner;
930 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
931 const vector< shared_ptr<sigrok::Channel> > &channels,
932 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
934 set< shared_ptr<Trace> > &add_list)
936 vector< shared_ptr<Trace> > filtered_traces;
938 for (const auto &channel : channels) {
939 for (auto entry : signal_map) {
940 if (entry.first->channel() == channel) {
941 shared_ptr<Trace> trace = entry.second;
942 const auto list_iter = add_list.find(trace);
943 if (list_iter == add_list.end())
946 filtered_traces.push_back(trace);
947 add_list.erase(list_iter);
952 return filtered_traces;
955 void View::determine_time_unit()
957 // Check whether we know the sample rate and hence can use time as the unit
958 if (time_unit_ == util::TimeUnit::Samples) {
959 // Check all signals but...
960 for (const shared_ptr<Signal> signal : signals_) {
961 const shared_ptr<SignalData> data = signal->data();
963 // ...only check first segment of each
964 const vector< shared_ptr<Segment> > segments = data->segments();
965 if (!segments.empty())
966 if (segments[0]->samplerate()) {
967 set_time_unit(util::TimeUnit::Time);
974 bool View::eventFilter(QObject *object, QEvent *event)
976 const QEvent::Type type = event->type();
977 if (type == QEvent::MouseMove) {
979 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
980 if (object == viewport_)
981 hover_point_ = mouse_event->pos();
982 else if (object == ruler_)
983 hover_point_ = QPoint(mouse_event->x(), 0);
984 else if (object == header_)
985 hover_point_ = QPoint(0, mouse_event->y());
987 hover_point_ = QPoint(-1, -1);
989 hover_point_changed();
991 } else if (type == QEvent::Leave) {
992 hover_point_ = QPoint(-1, -1);
993 hover_point_changed();
994 } else if (type == QEvent::Show) {
996 // This is somewhat of a hack, unfortunately. We cannot use
997 // set_v_offset() from within restore_settings() as the view
998 // at that point is neither visible nor properly sized.
999 // This is the least intrusive workaround I could come up
1000 // with: set the vertical offset (or scroll defaults) when
1001 // the view is shown, which happens after all widgets were
1002 // resized to their final sizes.
1005 if (scroll_needs_defaults_) {
1006 set_scroll_default();
1007 scroll_needs_defaults_ = false;
1010 if (saved_v_offset_) {
1011 set_v_offset(saved_v_offset_);
1012 saved_v_offset_ = 0;
1016 return QObject::eventFilter(object, event);
1019 void View::resizeEvent(QResizeEvent* event)
1021 // Only adjust the top margin if we shrunk vertically
1022 if (event->size().height() < event->oldSize().height())
1023 adjust_top_margin();
1028 void View::row_item_appearance_changed(bool label, bool content)
1033 viewport_->update();
1036 void View::time_item_appearance_changed(bool label, bool content)
1041 viewport_->update();
1044 void View::extents_changed(bool horz, bool vert)
1047 (horz ? TraceTreeItemHExtentsChanged : 0) |
1048 (vert ? TraceTreeItemVExtentsChanged : 0);
1050 lazy_event_handler_.start();
1053 void View::h_scroll_value_changed(int value)
1055 if (updating_scroll_)
1058 // Disable sticky scrolling when user moves the horizontal scroll bar
1059 // during a running acquisition
1060 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1061 sticky_scrolling_ = false;
1062 sticky_scrolling_changed(false);
1065 const int range = scrollarea_->horizontalScrollBar()->maximum();
1066 if (range < MaxScrollValue)
1067 set_offset(scale_ * value);
1071 get_scroll_layout(length, offset);
1072 set_offset(scale_ * length * value / MaxScrollValue);
1076 viewport_->update();
1079 void View::v_scroll_value_changed()
1082 viewport_->update();
1085 void View::signals_changed()
1087 using sigrok::Channel;
1089 vector< shared_ptr<Channel> > channels;
1090 shared_ptr<sigrok::Device> sr_dev;
1092 // Do we need to set the vertical scrollbar to its default position later?
1093 // We do if there are no traces, i.e. the scroll bar has no range set
1094 bool reset_scrollbar =
1095 (scrollarea_->verticalScrollBar()->minimum() ==
1096 scrollarea_->verticalScrollBar()->maximum());
1098 if (!session_.device()) {
1102 sr_dev = session_.device()->device();
1104 channels = sr_dev->channels();
1107 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1109 // Make a list of traces that are being added, and a list of traces
1110 // that are being removed
1111 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1112 const set<shared_ptr<Trace>> prev_traces(
1113 prev_trace_list.begin(), prev_trace_list.end());
1115 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1117 #ifdef ENABLE_DECODE
1118 traces.insert(decode_traces_.begin(), decode_traces_.end());
1121 set< shared_ptr<Trace> > add_traces;
1122 set_difference(traces.begin(), traces.end(),
1123 prev_traces.begin(), prev_traces.end(),
1124 inserter(add_traces, add_traces.begin()));
1126 set< shared_ptr<Trace> > remove_traces;
1127 set_difference(prev_traces.begin(), prev_traces.end(),
1128 traces.begin(), traces.end(),
1129 inserter(remove_traces, remove_traces.begin()));
1131 // Make a look-up table of sigrok Channels to pulseview Signals
1132 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1134 for (const shared_ptr<Signal> &sig : signals_)
1135 signal_map[sig->base()] = sig;
1137 // Populate channel groups
1139 for (auto entry : sr_dev->channel_groups()) {
1140 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1142 if (group->channels().size() <= 1)
1145 // Find best trace group to add to
1146 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1149 // If there is no trace group, create one
1150 shared_ptr<TraceGroup> new_trace_group;
1152 new_trace_group.reset(new TraceGroup());
1153 owner = new_trace_group.get();
1156 // Extract traces for the trace group, removing them from
1158 const vector< shared_ptr<Trace> > new_traces_in_group =
1159 extract_new_traces_for_channels(group->channels(),
1160 signal_map, add_traces);
1162 // Add the traces to the group
1163 const pair<int, int> prev_v_extents = owner->v_extents();
1164 int offset = prev_v_extents.second - prev_v_extents.first;
1165 for (shared_ptr<Trace> trace : new_traces_in_group) {
1167 owner->add_child_item(trace);
1169 const pair<int, int> extents = trace->v_extents();
1170 if (trace->enabled())
1171 offset += -extents.first;
1172 trace->force_to_v_offset(offset);
1173 if (trace->enabled())
1174 offset += extents.second;
1177 if (new_trace_group) {
1178 // Assign proper vertical offsets to each channel in the group
1179 new_trace_group->restack_items();
1181 // If this is a new group, enqueue it in the new top level
1183 if (!new_traces_in_group.empty())
1184 new_top_level_items.push_back(new_trace_group);
1188 // Enqueue the remaining logic channels in a group
1189 vector< shared_ptr<Channel> > logic_channels;
1190 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1191 [](const shared_ptr<Channel>& c) {
1192 return c->type() == sigrok::ChannelType::LOGIC; });
1194 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1195 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1197 if (non_grouped_logic_signals.size() > 0) {
1198 const shared_ptr<TraceGroup> non_grouped_trace_group(
1199 make_shared<TraceGroup>());
1200 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1201 non_grouped_trace_group->add_child_item(trace);
1203 non_grouped_trace_group->restack_items();
1204 new_top_level_items.push_back(non_grouped_trace_group);
1207 // Enqueue the remaining channels as free ungrouped traces
1208 const vector< shared_ptr<Trace> > new_top_level_signals =
1209 extract_new_traces_for_channels(channels, signal_map, add_traces);
1210 new_top_level_items.insert(new_top_level_items.end(),
1211 new_top_level_signals.begin(), new_top_level_signals.end());
1213 // Enqueue any remaining traces i.e. decode traces
1214 new_top_level_items.insert(new_top_level_items.end(),
1215 add_traces.begin(), add_traces.end());
1217 // Remove any removed traces
1218 for (shared_ptr<Trace> trace : remove_traces) {
1219 TraceTreeItemOwner *const owner = trace->owner();
1221 owner->remove_child_item(trace);
1224 // Remove any empty trace groups
1225 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1226 if (group->child_items().size() == 0) {
1227 remove_child_item(group);
1231 // Add and position the pending top levels items
1232 int offset = v_extents().second;
1233 for (auto item : new_top_level_items) {
1234 add_child_item(item);
1236 // Position the item after the last item or at the top if there is none
1237 const pair<int, int> extents = item->v_extents();
1239 if (item->enabled())
1240 offset += -extents.first;
1242 item->force_to_v_offset(offset);
1244 if (item->enabled())
1245 offset += extents.second;
1251 viewport_->update();
1253 if (reset_scrollbar)
1254 set_scroll_default();
1257 void View::capture_state_updated(int state)
1259 if (state == Session::Running) {
1260 set_time_unit(util::TimeUnit::Samples);
1262 trigger_markers_.clear();
1264 // Activate "always zoom to fit" if the setting is enabled and we're
1265 // the main view of this session (other trace views may be used for
1266 // zooming and we don't want to mess them up)
1267 GlobalSettings settings;
1268 bool state = settings.value(GlobalSettings::Key_View_AlwaysZoomToFit).toBool();
1269 if (is_main_view_ && state) {
1270 always_zoom_to_fit_ = true;
1271 always_zoom_to_fit_changed(always_zoom_to_fit_);
1274 // Enable sticky scrolling if the setting is enabled
1275 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1278 if (state == Session::Stopped) {
1279 // After acquisition has stopped we need to re-calculate the ticks once
1280 // as it's otherwise done when the user pans or zooms, which is too late
1281 calculate_tick_spacing();
1283 // Reset "always zoom to fit", the acquisition has stopped
1284 if (always_zoom_to_fit_) {
1285 // Perform a final zoom-to-fit before disabling
1286 zoom_fit(always_zoom_to_fit_);
1287 always_zoom_to_fit_ = false;
1288 always_zoom_to_fit_changed(always_zoom_to_fit_);
1293 void View::perform_delayed_view_update()
1295 if (always_zoom_to_fit_) {
1297 } else if (sticky_scrolling_) {
1298 // Make right side of the view sticky
1301 get_scroll_layout(length, offset);
1303 const QSize areaSize = viewport_->size();
1304 length = max(length - areaSize.width(), 0.0);
1306 set_offset(scale_ * length);
1309 determine_time_unit();
1312 viewport_->update();
1315 void View::process_sticky_events()
1317 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1319 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1320 restack_all_trace_tree_items();
1324 // Clear the sticky events
1328 void View::on_hover_point_changed()
1330 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1331 list_by_type<TraceTreeItem>());
1332 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1333 r->hover_point_changed();
1336 } // namespace TraceView
1337 } // namespace views