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;
79 using std::make_shared;
83 using std::set_difference;
84 using std::shared_ptr;
85 using std::stringstream;
86 using std::unordered_map;
87 using std::unordered_set;
94 const Timestamp View::MaxScale("1e9");
95 const Timestamp View::MinScale("1e-12");
97 const int View::MaxScrollValue = INT_MAX / 2;
99 const int View::ScaleUnits[3] = {1, 2, 5};
102 CustomScrollArea::CustomScrollArea(QWidget *parent) :
103 QAbstractScrollArea(parent)
107 bool CustomScrollArea::viewportEvent(QEvent *event)
109 switch (event->type()) {
111 case QEvent::MouseButtonPress:
112 case QEvent::MouseButtonRelease:
113 case QEvent::MouseButtonDblClick:
114 case QEvent::MouseMove:
116 case QEvent::TouchBegin:
117 case QEvent::TouchUpdate:
118 case QEvent::TouchEnd:
121 return QAbstractScrollArea::viewportEvent(event);
125 View::View(Session &session, bool is_main_view, QWidget *parent) :
126 ViewBase(session, is_main_view, parent),
127 splitter_(new QSplitter()),
130 updating_scroll_(false),
131 settings_restored_(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_(true),
145 scale_at_acq_start_(0),
146 offset_at_acq_start_(0),
147 suppress_zoom_to_fit_after_acq_(false)
149 QVBoxLayout *root_layout = new QVBoxLayout(this);
150 root_layout->setContentsMargins(0, 0, 0, 0);
151 root_layout->addWidget(splitter_);
153 viewport_ = new Viewport(*this);
154 scrollarea_ = new CustomScrollArea(splitter_);
155 scrollarea_->setViewport(viewport_);
156 scrollarea_->setFrameShape(QFrame::NoFrame);
158 ruler_ = new Ruler(*this);
160 header_ = new Header(*this);
161 header_->setMinimumWidth(10); // So that the arrow tips show at least
163 // We put the header into a simple layout so that we can add the top margin,
164 // allowing us to make it line up with the bottom of the ruler
165 QWidget *header_container = new QWidget();
166 header_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
167 QVBoxLayout *header_layout = new QVBoxLayout(header_container);
168 header_layout->setContentsMargins(0, ruler_->sizeHint().height(), 0, 0);
169 header_layout->addWidget(header_);
171 // To let the ruler and scrollarea be on the same split pane, we need a layout
172 QWidget *trace_container = new QWidget();
173 trace_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
174 QVBoxLayout *trace_layout = new QVBoxLayout(trace_container);
175 trace_layout->setSpacing(0); // We don't want space between the ruler and scrollarea
176 trace_layout->setContentsMargins(0, 0, 0, 0);
177 trace_layout->addWidget(ruler_);
178 trace_layout->addWidget(scrollarea_);
180 splitter_->addWidget(header_container);
181 splitter_->addWidget(trace_container);
182 splitter_->setHandleWidth(1); // Don't show a visible rubber band
183 splitter_->setCollapsible(0, false); // Prevent the header from collapsing
184 splitter_->setCollapsible(1, false); // Prevent the traces from collapsing
185 splitter_->setStretchFactor(0, 0); // Prevent the panes from being resized
186 splitter_->setStretchFactor(1, 1); // when the entire view is resized
187 splitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
189 viewport_->installEventFilter(this);
190 ruler_->installEventFilter(this);
191 header_->installEventFilter(this);
193 // Set up settings and event handlers
194 GlobalSettings settings;
195 coloured_bg_ = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
197 connect(scrollarea_->horizontalScrollBar(), SIGNAL(valueChanged(int)),
198 this, SLOT(h_scroll_value_changed(int)));
199 connect(scrollarea_->verticalScrollBar(), SIGNAL(valueChanged(int)),
200 this, SLOT(v_scroll_value_changed()));
202 connect(header_, SIGNAL(selection_changed()),
203 ruler_, SLOT(clear_selection()));
204 connect(ruler_, SIGNAL(selection_changed()),
205 header_, SLOT(clear_selection()));
207 connect(header_, SIGNAL(selection_changed()),
208 this, SIGNAL(selection_changed()));
209 connect(ruler_, SIGNAL(selection_changed()),
210 this, SIGNAL(selection_changed()));
212 connect(splitter_, SIGNAL(splitterMoved(int, int)),
213 this, SLOT(on_splitter_moved()));
215 connect(&lazy_event_handler_, SIGNAL(timeout()),
216 this, SLOT(process_sticky_events()));
217 lazy_event_handler_.setSingleShot(true);
219 // Trigger the initial event manually. The default device has signals
220 // which were created before this object came into being
223 // make sure the transparent widgets are on the top
227 // Update the zoom state
228 calculate_tick_spacing();
231 Session& View::session()
236 const Session& View::session() const
241 unordered_set< shared_ptr<Signal> > View::signals() const
246 void View::clear_signals()
248 ViewBase::clear_signalbases();
252 void View::add_signal(const shared_ptr<Signal> signal)
254 ViewBase::add_signalbase(signal->base());
255 signals_.insert(signal);
257 connect(signal->base().get(), SIGNAL(name_changed(const QString&)),
258 this, SLOT(on_signal_name_changed()));
262 void View::clear_decode_signals()
264 decode_traces_.clear();
267 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
269 shared_ptr<DecodeTrace> d(
270 new DecodeTrace(session_, signal, decode_traces_.size()));
271 decode_traces_.push_back(d);
273 connect(signal.get(), SIGNAL(name_changed(const QString&)),
274 this, SLOT(on_signal_name_changed()));
277 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
279 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
280 if ((*i)->base() == signal) {
281 decode_traces_.erase(i);
293 const View* View::view() const
298 Viewport* View::viewport()
303 const Viewport* View::viewport() const
308 void View::save_settings(QSettings &settings) const
310 settings.setValue("scale", scale_);
311 settings.setValue("v_offset",
312 scrollarea_->verticalScrollBar()->sliderPosition());
314 settings.setValue("splitter_state", splitter_->saveState());
317 boost::archive::text_oarchive oa(ss);
318 oa << boost::serialization::make_nvp("offset", offset_);
319 settings.setValue("offset", QString::fromStdString(ss.str()));
321 for (shared_ptr<Signal> signal : signals_) {
322 settings.beginGroup(signal->base()->internal_name());
323 signal->save_settings(settings);
328 void View::restore_settings(QSettings &settings)
330 // Note: It is assumed that this function is only called once,
331 // immediately after restoring a previous session.
333 if (settings.contains("scale"))
334 set_scale(settings.value("scale").toDouble());
336 if (settings.contains("offset")) {
337 util::Timestamp offset;
339 ss << settings.value("offset").toString().toStdString();
341 boost::archive::text_iarchive ia(ss);
342 ia >> boost::serialization::make_nvp("offset", offset);
347 if (settings.contains("splitter_state"))
348 splitter_->restoreState(settings.value("splitter_state").toByteArray());
350 for (shared_ptr<Signal> signal : signals_) {
351 settings.beginGroup(signal->base()->internal_name());
352 signal->restore_settings(settings);
356 if (settings.contains("v_offset")) {
357 saved_v_offset_ = settings.value("v_offset").toInt();
358 set_v_offset(saved_v_offset_);
359 scroll_needs_defaults_ = false;
360 // Note: see eventFilter() for additional information
363 settings_restored_ = true;
364 suppress_zoom_to_fit_after_acq_ = true;
366 // Update the ruler so that it uses the new scale
367 calculate_tick_spacing();
370 vector< shared_ptr<TimeItem> > View::time_items() const
372 const vector<shared_ptr<Flag>> f(flags());
373 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
374 items.push_back(cursors_);
375 items.push_back(cursors_->first());
376 items.push_back(cursors_->second());
378 for (auto trigger_marker : trigger_markers_)
379 items.push_back(trigger_marker);
384 double View::scale() const
389 void View::set_scale(double scale)
391 if (scale_ != scale) {
397 const Timestamp& View::offset() const
402 void View::set_offset(const pv::util::Timestamp& offset)
404 if (offset_ != offset) {
410 int View::owner_visual_v_offset() const
412 return -scrollarea_->verticalScrollBar()->sliderPosition();
415 void View::set_v_offset(int offset)
417 scrollarea_->verticalScrollBar()->setSliderPosition(offset);
422 unsigned int View::depth() const
427 pv::util::SIPrefix View::tick_prefix() const
432 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
434 if (tick_prefix_ != tick_prefix) {
435 tick_prefix_ = tick_prefix;
436 tick_prefix_changed();
440 unsigned int View::tick_precision() const
442 return tick_precision_;
445 void View::set_tick_precision(unsigned tick_precision)
447 if (tick_precision_ != tick_precision) {
448 tick_precision_ = tick_precision;
449 tick_precision_changed();
453 const pv::util::Timestamp& View::tick_period() const
458 void View::set_tick_period(const pv::util::Timestamp& tick_period)
460 if (tick_period_ != tick_period) {
461 tick_period_ = tick_period;
462 tick_period_changed();
466 TimeUnit View::time_unit() const
471 void View::set_time_unit(pv::util::TimeUnit time_unit)
473 if (time_unit_ != time_unit) {
474 time_unit_ = time_unit;
479 void View::zoom(double steps)
481 zoom(steps, viewport_->width() / 2);
484 void View::zoom(double steps, int offset)
486 set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
489 void View::zoom_fit(bool gui_state)
491 // Act as one-shot when stopped, toggle along with the GUI otherwise
492 if (session_.get_capture_state() == Session::Stopped) {
493 always_zoom_to_fit_ = false;
494 always_zoom_to_fit_changed(false);
496 always_zoom_to_fit_ = gui_state;
497 always_zoom_to_fit_changed(gui_state);
500 const pair<Timestamp, Timestamp> extents = get_time_extents();
501 const Timestamp delta = extents.second - extents.first;
502 if (delta < Timestamp("1e-12"))
506 const int w = viewport_->width();
510 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
511 set_scale_offset(scale.convert_to<double>(), extents.first);
514 void View::zoom_one_to_one()
516 using pv::data::SignalData;
518 // Make a set of all the visible data objects
519 set< shared_ptr<SignalData> > visible_data = get_visible_data();
520 if (visible_data.empty())
524 const int w = viewport_->width();
528 set_zoom(1.0 / session_.get_samplerate(), w / 2);
531 void View::set_scale_offset(double scale, const Timestamp& offset)
533 // Disable sticky scrolling / always zoom to fit when acquisition runs
534 // and user drags the viewport
535 if ((scale_ == scale) && (offset_ != offset) &&
536 (session_.get_capture_state() == Session::Running)) {
538 if (sticky_scrolling_) {
539 sticky_scrolling_ = false;
540 sticky_scrolling_changed(false);
543 if (always_zoom_to_fit_) {
544 always_zoom_to_fit_ = false;
545 always_zoom_to_fit_changed(false);
552 calculate_tick_spacing();
559 set< shared_ptr<SignalData> > View::get_visible_data() const
561 // Make a set of all the visible data objects
562 set< shared_ptr<SignalData> > visible_data;
563 for (const shared_ptr<Signal> sig : signals_)
565 visible_data.insert(sig->data());
570 pair<Timestamp, Timestamp> View::get_time_extents() const
572 boost::optional<Timestamp> left_time, right_time;
573 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
574 for (const shared_ptr<SignalData> d : visible_data) {
575 const vector< shared_ptr<Segment> > segments = d->segments();
576 for (const shared_ptr<Segment> &s : segments) {
577 double samplerate = s->samplerate();
578 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
580 const Timestamp start_time = s->start_time();
581 left_time = left_time ?
582 min(*left_time, start_time) :
584 right_time = right_time ?
585 max(*right_time, start_time + d->max_sample_count() / samplerate) :
586 start_time + d->max_sample_count() / samplerate;
590 if (!left_time || !right_time)
591 return make_pair(0, 0);
593 assert(*left_time < *right_time);
594 return make_pair(*left_time, *right_time);
597 void View::enable_show_sampling_points(bool state)
604 void View::enable_show_analog_minor_grid(bool state)
611 void View::enable_coloured_bg(bool state)
613 coloured_bg_ = state;
617 bool View::coloured_bg() const
622 bool View::cursors_shown() const
624 return show_cursors_;
627 void View::show_cursors(bool show)
629 show_cursors_ = show;
634 void View::centre_cursors()
636 const double time_width = scale_ * viewport_->width();
637 cursors_->first()->set_time(offset_ + time_width * 0.4);
638 cursors_->second()->set_time(offset_ + time_width * 0.6);
643 shared_ptr<CursorPair> View::cursors() const
648 void View::add_flag(const Timestamp& time)
650 flags_.push_back(make_shared<Flag>(*this, time,
651 QString("%1").arg(next_flag_text_)));
653 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
654 (next_flag_text_ + 1);
656 time_item_appearance_changed(true, true);
659 void View::remove_flag(shared_ptr<Flag> flag)
662 time_item_appearance_changed(true, true);
665 vector< shared_ptr<Flag> > View::flags() const
667 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
668 stable_sort(flags.begin(), flags.end(),
669 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
670 return a->time() < b->time();
676 const QPoint& View::hover_point() const
681 void View::restack_all_trace_tree_items()
683 // Make a list of owners that is sorted from deepest first
684 const vector<shared_ptr<TraceTreeItem>> items(
685 list_by_type<TraceTreeItem>());
686 set< TraceTreeItemOwner* > owners;
687 for (const auto &r : items)
688 owners.insert(r->owner());
689 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
690 sort(sorted_owners.begin(), sorted_owners.end(),
691 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
692 return a->depth() > b->depth(); });
694 // Restack the items recursively
695 for (auto &o : sorted_owners)
698 // Animate the items to their destination
699 for (const auto &i : items)
700 i->animate_to_layout_v_offset();
703 void View::trigger_event(util::Timestamp location)
705 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
708 void View::get_scroll_layout(double &length, Timestamp &offset) const
710 const pair<Timestamp, Timestamp> extents = get_time_extents();
711 length = ((extents.second - extents.first) / scale_).convert_to<double>();
712 offset = offset_ / scale_;
715 void View::set_zoom(double scale, int offset)
717 // Reset the "always zoom to fit" feature as the user changed the zoom
718 always_zoom_to_fit_ = false;
719 always_zoom_to_fit_changed(false);
721 const Timestamp cursor_offset = offset_ + scale_ * offset;
722 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
723 const Timestamp new_offset = cursor_offset - new_scale * offset;
724 set_scale_offset(new_scale.convert_to<double>(), new_offset);
727 void View::calculate_tick_spacing()
729 const double SpacingIncrement = 10.0f;
730 const double MinValueSpacing = 40.0f;
732 // Figure out the highest numeric value visible on a label
733 const QSize areaSize = viewport_->size();
734 const Timestamp max_time = max(fabs(offset_),
735 fabs(offset_ + scale_ * areaSize.width()));
737 double min_width = SpacingIncrement;
738 double label_width, tick_period_width;
740 QFontMetrics m(QApplication::font());
742 // Copies of the member variables with the same name, used in the calculation
743 // and written back afterwards, so that we don't emit signals all the time
744 // during the calculation.
745 pv::util::Timestamp tick_period = tick_period_;
746 pv::util::SIPrefix tick_prefix = tick_prefix_;
747 unsigned tick_precision = tick_precision_;
750 const double min_period = scale_ * min_width;
752 const int order = (int)floorf(log10f(min_period));
753 const pv::util::Timestamp order_decimal =
754 pow(pv::util::Timestamp(10), order);
756 // Allow for a margin of error so that a scale unit of 1 can be used.
757 // Otherwise, for a SU of 1 the tick period will almost always be below
758 // the min_period by a small amount - and thus skipped in favor of 2.
759 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
760 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
761 double tp_with_margin;
762 unsigned int unit = 0;
765 tp_with_margin = order_decimal.convert_to<double>() *
766 (ScaleUnits[unit++] + tp_margin);
767 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
769 tick_period = order_decimal * ScaleUnits[unit - 1];
770 tick_prefix = static_cast<pv::util::SIPrefix>(
771 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
773 // Precision is the number of fractional digits required, not
774 // taking the prefix into account (and it must never be negative)
775 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
777 tick_period_width = (tick_period / scale_).convert_to<double>();
779 const QString label_text = Ruler::format_time_with_distance(
780 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
782 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
783 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
786 min_width += SpacingIncrement;
787 } while (tick_period_width < label_width);
789 set_tick_period(tick_period);
790 set_tick_prefix(tick_prefix);
791 set_tick_precision(tick_precision);
794 void View::adjust_top_margin()
798 const QSize areaSize = viewport_->size();
800 const pair<int, int> extents = v_extents();
801 const int top_margin = owner_visual_v_offset() + extents.first;
802 const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
804 // Do we have empty space at the top while the last trace goes out of screen?
805 if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
806 const int trace_height = extents.second - extents.first;
808 // Center everything vertically if there is enough space
809 if (areaSize.height() >= trace_height)
810 set_v_offset(extents.first -
811 ((areaSize.height() - trace_height) / 2));
813 // Remove the top margin to make as many traces fit on screen as possible
814 set_v_offset(extents.first);
818 void View::update_scroll()
821 QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
822 QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
824 const QSize areaSize = viewport_->size();
826 // Set the horizontal scroll bar
829 get_scroll_layout(length, offset);
830 length = max(length - areaSize.width(), 0.0);
832 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
834 hscrollbar->setPageStep(areaSize.width() / 2);
835 hscrollbar->setSingleStep(major_tick_distance);
837 updating_scroll_ = true;
839 if (length < MaxScrollValue) {
840 hscrollbar->setRange(0, length);
841 hscrollbar->setSliderPosition(offset.convert_to<double>());
843 hscrollbar->setRange(0, MaxScrollValue);
844 hscrollbar->setSliderPosition(
845 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
848 updating_scroll_ = false;
850 // Set the vertical scrollbar
851 vscrollbar->setPageStep(areaSize.height());
852 vscrollbar->setSingleStep(areaSize.height() / 8);
854 const pair<int, int> extents = v_extents();
856 // Don't change the scrollbar range if there are no traces
857 if (extents.first != extents.second)
858 vscrollbar->setRange(extents.first - areaSize.height(),
861 if (scroll_needs_defaults_)
862 set_scroll_default();
865 void View::reset_scroll()
867 scrollarea_->verticalScrollBar()->setRange(0, 0);
870 void View::set_scroll_default()
874 const QSize areaSize = viewport_->size();
876 const pair<int, int> extents = v_extents();
877 const int trace_height = extents.second - extents.first;
879 // Do all traces fit in the view?
880 if (areaSize.height() >= trace_height)
881 // Center all traces vertically
882 set_v_offset(extents.first -
883 ((areaSize.height() - trace_height) / 2));
885 // Put the first trace at the top, letting the bottom ones overflow
886 set_v_offset(extents.first);
889 bool View::header_was_shrunk() const
891 const int header_pane_width = splitter_->sizes().front();
892 const int header_width = header_->extended_size_hint().width();
894 // Allow for a slight margin of error so that we also accept
895 // slight differences when e.g. a label name change increased
897 return (header_pane_width < (header_width - 10));
900 void View::expand_header_to_fit()
902 int splitter_area_width = 0;
903 for (int w : splitter_->sizes())
904 splitter_area_width += w;
906 // Make sure the header has enough horizontal space to show all labels fully
907 QList<int> pane_sizes;
908 pane_sizes.push_back(header_->extended_size_hint().width());
909 pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
910 splitter_->setSizes(pane_sizes);
913 void View::update_layout()
918 TraceTreeItemOwner* View::find_prevalent_trace_group(
919 const shared_ptr<sigrok::ChannelGroup> &group,
920 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
925 unordered_set<TraceTreeItemOwner*> owners;
926 vector<TraceTreeItemOwner*> owner_list;
928 // Make a set and a list of all the owners
929 for (const auto &channel : group->channels()) {
930 for (auto entry : signal_map) {
931 if (entry.first->channel() == channel) {
932 TraceTreeItemOwner *const o = (entry.second)->owner();
933 owner_list.push_back(o);
939 // Iterate through the list of owners, and find the most prevalent
940 size_t max_prevalence = 0;
941 TraceTreeItemOwner *prevalent_owner = nullptr;
942 for (TraceTreeItemOwner *owner : owners) {
943 const size_t prevalence = count_if(
944 owner_list.begin(), owner_list.end(),
945 [&](TraceTreeItemOwner *o) { return o == owner; });
946 if (prevalence > max_prevalence) {
947 max_prevalence = prevalence;
948 prevalent_owner = owner;
952 return prevalent_owner;
955 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
956 const vector< shared_ptr<sigrok::Channel> > &channels,
957 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
959 set< shared_ptr<Trace> > &add_list)
961 vector< shared_ptr<Trace> > filtered_traces;
963 for (const auto &channel : channels) {
964 for (auto entry : signal_map) {
965 if (entry.first->channel() == channel) {
966 shared_ptr<Trace> trace = entry.second;
967 const auto list_iter = add_list.find(trace);
968 if (list_iter == add_list.end())
971 filtered_traces.push_back(trace);
972 add_list.erase(list_iter);
977 return filtered_traces;
980 void View::determine_time_unit()
982 // Check whether we know the sample rate and hence can use time as the unit
983 if (time_unit_ == util::TimeUnit::Samples) {
984 // Check all signals but...
985 for (const shared_ptr<Signal> signal : signals_) {
986 const shared_ptr<SignalData> data = signal->data();
988 // ...only check first segment of each
989 const vector< shared_ptr<Segment> > segments = data->segments();
990 if (!segments.empty())
991 if (segments[0]->samplerate()) {
992 set_time_unit(util::TimeUnit::Time);
999 bool View::eventFilter(QObject *object, QEvent *event)
1001 const QEvent::Type type = event->type();
1002 if (type == QEvent::MouseMove) {
1004 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
1005 if (object == viewport_)
1006 hover_point_ = mouse_event->pos();
1007 else if (object == ruler_)
1008 hover_point_ = QPoint(mouse_event->x(), 0);
1009 else if (object == header_)
1010 hover_point_ = QPoint(0, mouse_event->y());
1012 hover_point_ = QPoint(-1, -1);
1014 update_hover_point();
1016 } else if (type == QEvent::Leave) {
1017 hover_point_ = QPoint(-1, -1);
1018 update_hover_point();
1019 } else if (type == QEvent::Show) {
1021 // This is somewhat of a hack, unfortunately. We cannot use
1022 // set_v_offset() from within restore_settings() as the view
1023 // at that point is neither visible nor properly sized.
1024 // This is the least intrusive workaround I could come up
1025 // with: set the vertical offset (or scroll defaults) when
1026 // the view is shown, which happens after all widgets were
1027 // resized to their final sizes.
1030 if (!settings_restored_)
1031 expand_header_to_fit();
1033 if (scroll_needs_defaults_) {
1034 set_scroll_default();
1035 scroll_needs_defaults_ = false;
1038 if (saved_v_offset_) {
1039 set_v_offset(saved_v_offset_);
1040 saved_v_offset_ = 0;
1044 return QObject::eventFilter(object, event);
1047 void View::resizeEvent(QResizeEvent* event)
1049 // Only adjust the top margin if we shrunk vertically
1050 if (event->size().height() < event->oldSize().height())
1051 adjust_top_margin();
1056 void View::update_hover_point()
1058 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1059 list_by_type<TraceTreeItem>());
1060 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1061 r->hover_point_changed(hover_point_);
1063 hover_point_changed(hover_point_);
1066 void View::row_item_appearance_changed(bool label, bool content)
1071 viewport_->update();
1074 void View::time_item_appearance_changed(bool label, bool content)
1079 // Make sure the header pane width is updated, too
1084 viewport_->update();
1087 void View::extents_changed(bool horz, bool vert)
1090 (horz ? TraceTreeItemHExtentsChanged : 0) |
1091 (vert ? TraceTreeItemVExtentsChanged : 0);
1093 lazy_event_handler_.start();
1096 void View::on_signal_name_changed()
1098 if (!header_was_shrunk())
1099 expand_header_to_fit();
1102 void View::on_splitter_moved()
1104 // Setting the maximum width of the header widget doesn't work as
1105 // expected because the splitter would allow the user to make the
1106 // pane wider than that, creating empty space as a result.
1107 // To make this work, we stricly enforce the maximum width by
1108 // expanding the header unless the user shrunk it on purpose.
1109 // As we're then setting the width of the header pane, we set the
1110 // splitter to the maximum allowed position.
1111 if (!header_was_shrunk())
1112 expand_header_to_fit();
1115 void View::h_scroll_value_changed(int value)
1117 if (updating_scroll_)
1120 // Disable sticky scrolling when user moves the horizontal scroll bar
1121 // during a running acquisition
1122 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1123 sticky_scrolling_ = false;
1124 sticky_scrolling_changed(false);
1127 const int range = scrollarea_->horizontalScrollBar()->maximum();
1128 if (range < MaxScrollValue)
1129 set_offset(scale_ * value);
1133 get_scroll_layout(length, offset);
1134 set_offset(scale_ * length * value / MaxScrollValue);
1138 viewport_->update();
1141 void View::v_scroll_value_changed()
1144 viewport_->update();
1147 void View::signals_changed()
1149 using sigrok::Channel;
1151 vector< shared_ptr<Channel> > channels;
1152 shared_ptr<sigrok::Device> sr_dev;
1154 // Do we need to set the vertical scrollbar to its default position later?
1155 // We do if there are no traces, i.e. the scroll bar has no range set
1156 bool reset_scrollbar =
1157 (scrollarea_->verticalScrollBar()->minimum() ==
1158 scrollarea_->verticalScrollBar()->maximum());
1160 if (!session_.device()) {
1164 sr_dev = session_.device()->device();
1166 channels = sr_dev->channels();
1169 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1171 // Make a list of traces that are being added, and a list of traces
1172 // that are being removed
1173 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1174 const set<shared_ptr<Trace>> prev_traces(
1175 prev_trace_list.begin(), prev_trace_list.end());
1177 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1179 #ifdef ENABLE_DECODE
1180 traces.insert(decode_traces_.begin(), decode_traces_.end());
1183 set< shared_ptr<Trace> > add_traces;
1184 set_difference(traces.begin(), traces.end(),
1185 prev_traces.begin(), prev_traces.end(),
1186 inserter(add_traces, add_traces.begin()));
1188 set< shared_ptr<Trace> > remove_traces;
1189 set_difference(prev_traces.begin(), prev_traces.end(),
1190 traces.begin(), traces.end(),
1191 inserter(remove_traces, remove_traces.begin()));
1193 // Make a look-up table of sigrok Channels to pulseview Signals
1194 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1196 for (const shared_ptr<Signal> &sig : signals_)
1197 signal_map[sig->base()] = sig;
1199 // Populate channel groups
1201 for (auto entry : sr_dev->channel_groups()) {
1202 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1204 if (group->channels().size() <= 1)
1207 // Find best trace group to add to
1208 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1211 // If there is no trace group, create one
1212 shared_ptr<TraceGroup> new_trace_group;
1214 new_trace_group.reset(new TraceGroup());
1215 owner = new_trace_group.get();
1218 // Extract traces for the trace group, removing them from
1220 const vector< shared_ptr<Trace> > new_traces_in_group =
1221 extract_new_traces_for_channels(group->channels(),
1222 signal_map, add_traces);
1224 // Add the traces to the group
1225 const pair<int, int> prev_v_extents = owner->v_extents();
1226 int offset = prev_v_extents.second - prev_v_extents.first;
1227 for (shared_ptr<Trace> trace : new_traces_in_group) {
1229 owner->add_child_item(trace);
1231 const pair<int, int> extents = trace->v_extents();
1232 if (trace->enabled())
1233 offset += -extents.first;
1234 trace->force_to_v_offset(offset);
1235 if (trace->enabled())
1236 offset += extents.second;
1239 if (new_trace_group) {
1240 // Assign proper vertical offsets to each channel in the group
1241 new_trace_group->restack_items();
1243 // If this is a new group, enqueue it in the new top level
1245 if (!new_traces_in_group.empty())
1246 new_top_level_items.push_back(new_trace_group);
1250 // Enqueue the remaining logic channels in a group
1251 vector< shared_ptr<Channel> > logic_channels;
1252 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1253 [](const shared_ptr<Channel>& c) {
1254 return c->type() == sigrok::ChannelType::LOGIC; });
1256 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1257 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1259 if (non_grouped_logic_signals.size() > 0) {
1260 const shared_ptr<TraceGroup> non_grouped_trace_group(
1261 make_shared<TraceGroup>());
1262 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1263 non_grouped_trace_group->add_child_item(trace);
1265 non_grouped_trace_group->restack_items();
1266 new_top_level_items.push_back(non_grouped_trace_group);
1269 // Enqueue the remaining channels as free ungrouped traces
1270 const vector< shared_ptr<Trace> > new_top_level_signals =
1271 extract_new_traces_for_channels(channels, signal_map, add_traces);
1272 new_top_level_items.insert(new_top_level_items.end(),
1273 new_top_level_signals.begin(), new_top_level_signals.end());
1275 // Enqueue any remaining traces i.e. decode traces
1276 new_top_level_items.insert(new_top_level_items.end(),
1277 add_traces.begin(), add_traces.end());
1279 // Remove any removed traces
1280 for (shared_ptr<Trace> trace : remove_traces) {
1281 TraceTreeItemOwner *const owner = trace->owner();
1283 owner->remove_child_item(trace);
1286 // Remove any empty trace groups
1287 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1288 if (group->child_items().size() == 0) {
1289 remove_child_item(group);
1293 // Add and position the pending top levels items
1294 int offset = v_extents().second;
1295 for (auto item : new_top_level_items) {
1296 add_child_item(item);
1298 // Position the item after the last item or at the top if there is none
1299 const pair<int, int> extents = item->v_extents();
1301 if (item->enabled())
1302 offset += -extents.first;
1304 item->force_to_v_offset(offset);
1306 if (item->enabled())
1307 offset += extents.second;
1311 if (!new_top_level_items.empty())
1312 // Expand the header pane because the header should become fully
1313 // visible when new signals are added
1314 expand_header_to_fit();
1319 viewport_->update();
1321 if (reset_scrollbar)
1322 set_scroll_default();
1325 void View::capture_state_updated(int state)
1327 GlobalSettings settings;
1329 if (state == Session::Running) {
1330 set_time_unit(util::TimeUnit::Samples);
1332 trigger_markers_.clear();
1334 scale_at_acq_start_ = scale_;
1335 offset_at_acq_start_ = offset_;
1337 // Activate "always zoom to fit" if the setting is enabled and we're
1338 // the main view of this session (other trace views may be used for
1339 // zooming and we don't want to mess them up)
1340 bool state = settings.value(GlobalSettings::Key_View_ZoomToFitDuringAcq).toBool();
1341 if (is_main_view_ && state) {
1342 always_zoom_to_fit_ = true;
1343 always_zoom_to_fit_changed(always_zoom_to_fit_);
1346 // Enable sticky scrolling if the setting is enabled
1347 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1350 if (state == Session::Stopped) {
1351 // After acquisition has stopped we need to re-calculate the ticks once
1352 // as it's otherwise done when the user pans or zooms, which is too late
1353 calculate_tick_spacing();
1355 // Reset "always zoom to fit", the acquisition has stopped
1356 if (always_zoom_to_fit_) {
1357 // Perform a final zoom-to-fit before disabling
1358 zoom_fit(always_zoom_to_fit_);
1359 always_zoom_to_fit_ = false;
1360 always_zoom_to_fit_changed(always_zoom_to_fit_);
1363 bool zoom_to_fit_after_acq =
1364 settings.value(GlobalSettings::Key_View_ZoomToFitAfterAcq).toBool();
1366 // Only perform zoom-to-fit if the user hasn't altered the viewport and
1367 // we didn't restore settings in the meanwhile
1368 if (zoom_to_fit_after_acq &&
1369 !suppress_zoom_to_fit_after_acq_ &&
1370 (scale_ == scale_at_acq_start_) &&
1371 (offset_ == offset_at_acq_start_))
1372 zoom_fit(false); // We're stopped, so the GUI state doesn't matter
1374 suppress_zoom_to_fit_after_acq_ = false;
1378 void View::on_segment_changed(int segment)
1380 current_segment_ = segment - 1;
1382 for (shared_ptr<Signal> signal : signals_)
1383 signal->set_current_segment(current_segment_);
1385 viewport_->update();
1388 void View::perform_delayed_view_update()
1390 if (always_zoom_to_fit_) {
1392 } else if (sticky_scrolling_) {
1393 // Make right side of the view sticky
1396 get_scroll_layout(length, offset);
1398 const QSize areaSize = viewport_->size();
1399 length = max(length - areaSize.width(), 0.0);
1401 set_offset(scale_ * length);
1404 determine_time_unit();
1407 viewport_->update();
1410 void View::process_sticky_events()
1412 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1414 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1415 restack_all_trace_tree_items();
1419 // Clear the sticky events
1423 } // namespace trace
1424 } // namespace views