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()),
128 segment_display_mode_(Trace::ShowLastSegmentOnly),
129 segment_selectable_(false),
132 updating_scroll_(false),
133 settings_restored_(false),
134 header_was_shrunk_(false),
135 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
136 always_zoom_to_fit_(false),
138 tick_prefix_(pv::util::SIPrefix::yocto),
140 time_unit_(util::TimeUnit::Time),
141 show_cursors_(false),
142 cursors_(new CursorPair(*this)),
143 next_flag_text_('A'),
145 hover_point_(-1, -1),
146 scroll_needs_defaults_(true),
148 scale_at_acq_start_(0),
149 offset_at_acq_start_(0),
150 suppress_zoom_to_fit_after_acq_(false)
152 QVBoxLayout *root_layout = new QVBoxLayout(this);
153 root_layout->setContentsMargins(0, 0, 0, 0);
154 root_layout->addWidget(splitter_);
156 viewport_ = new Viewport(*this);
157 scrollarea_ = new CustomScrollArea(splitter_);
158 scrollarea_->setViewport(viewport_);
159 scrollarea_->setFrameShape(QFrame::NoFrame);
161 ruler_ = new Ruler(*this);
163 header_ = new Header(*this);
164 header_->setMinimumWidth(10); // So that the arrow tips show at least
166 // We put the header into a simple layout so that we can add the top margin,
167 // allowing us to make it line up with the bottom of the ruler
168 QWidget *header_container = new QWidget();
169 header_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
170 QVBoxLayout *header_layout = new QVBoxLayout(header_container);
171 header_layout->setContentsMargins(0, ruler_->sizeHint().height(), 0, 0);
172 header_layout->addWidget(header_);
174 // To let the ruler and scrollarea be on the same split pane, we need a layout
175 QWidget *trace_container = new QWidget();
176 trace_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
177 QVBoxLayout *trace_layout = new QVBoxLayout(trace_container);
178 trace_layout->setSpacing(0); // We don't want space between the ruler and scrollarea
179 trace_layout->setContentsMargins(0, 0, 0, 0);
180 trace_layout->addWidget(ruler_);
181 trace_layout->addWidget(scrollarea_);
183 splitter_->addWidget(header_container);
184 splitter_->addWidget(trace_container);
185 splitter_->setHandleWidth(1); // Don't show a visible rubber band
186 splitter_->setCollapsible(0, false); // Prevent the header from collapsing
187 splitter_->setCollapsible(1, false); // Prevent the traces from collapsing
188 splitter_->setStretchFactor(0, 0); // Prevent the panes from being resized
189 splitter_->setStretchFactor(1, 1); // when the entire view is resized
190 splitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
192 viewport_->installEventFilter(this);
193 ruler_->installEventFilter(this);
194 header_->installEventFilter(this);
196 // Set up settings and event handlers
197 GlobalSettings settings;
198 coloured_bg_ = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
200 connect(scrollarea_->horizontalScrollBar(), SIGNAL(valueChanged(int)),
201 this, SLOT(h_scroll_value_changed(int)));
202 connect(scrollarea_->verticalScrollBar(), SIGNAL(valueChanged(int)),
203 this, SLOT(v_scroll_value_changed()));
205 connect(header_, SIGNAL(selection_changed()),
206 ruler_, SLOT(clear_selection()));
207 connect(ruler_, SIGNAL(selection_changed()),
208 header_, SLOT(clear_selection()));
210 connect(header_, SIGNAL(selection_changed()),
211 this, SIGNAL(selection_changed()));
212 connect(ruler_, SIGNAL(selection_changed()),
213 this, SIGNAL(selection_changed()));
215 connect(splitter_, SIGNAL(splitterMoved(int, int)),
216 this, SLOT(on_splitter_moved()));
218 connect(&lazy_event_handler_, SIGNAL(timeout()),
219 this, SLOT(process_sticky_events()));
220 lazy_event_handler_.setSingleShot(true);
222 // Trigger the initial event manually. The default device has signals
223 // which were created before this object came into being
226 // make sure the transparent widgets are on the top
230 // Update the zoom state
231 calculate_tick_spacing();
234 Session& View::session()
239 const Session& View::session() const
244 unordered_set< shared_ptr<Signal> > View::signals() const
249 void View::clear_signals()
251 ViewBase::clear_signalbases();
255 void View::add_signal(const shared_ptr<Signal> signal)
257 ViewBase::add_signalbase(signal->base());
258 signals_.insert(signal);
260 signal->set_segment_display_mode(segment_display_mode_);
262 connect(signal->base().get(), SIGNAL(name_changed(const QString&)),
263 this, SLOT(on_signal_name_changed()));
267 void View::clear_decode_signals()
269 decode_traces_.clear();
272 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
274 shared_ptr<DecodeTrace> d(
275 new DecodeTrace(session_, signal, decode_traces_.size()));
276 decode_traces_.push_back(d);
278 d->set_segment_display_mode(segment_display_mode_);
280 connect(signal.get(), SIGNAL(name_changed(const QString&)),
281 this, SLOT(on_signal_name_changed()));
284 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
286 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
287 if ((*i)->base() == signal) {
288 decode_traces_.erase(i);
300 const View* View::view() const
305 Viewport* View::viewport()
310 const Viewport* View::viewport() const
315 void View::save_settings(QSettings &settings) const
317 settings.setValue("scale", scale_);
318 settings.setValue("v_offset",
319 scrollarea_->verticalScrollBar()->sliderPosition());
321 settings.setValue("splitter_state", splitter_->saveState());
324 boost::archive::text_oarchive oa(ss);
325 oa << boost::serialization::make_nvp("offset", offset_);
326 settings.setValue("offset", QString::fromStdString(ss.str()));
328 for (shared_ptr<Signal> signal : signals_) {
329 settings.beginGroup(signal->base()->internal_name());
330 signal->save_settings(settings);
335 void View::restore_settings(QSettings &settings)
337 // Note: It is assumed that this function is only called once,
338 // immediately after restoring a previous session.
340 if (settings.contains("scale"))
341 set_scale(settings.value("scale").toDouble());
343 if (settings.contains("offset")) {
344 util::Timestamp offset;
346 ss << settings.value("offset").toString().toStdString();
348 boost::archive::text_iarchive ia(ss);
349 ia >> boost::serialization::make_nvp("offset", offset);
354 if (settings.contains("splitter_state"))
355 splitter_->restoreState(settings.value("splitter_state").toByteArray());
357 for (shared_ptr<Signal> signal : signals_) {
358 settings.beginGroup(signal->base()->internal_name());
359 signal->restore_settings(settings);
363 if (settings.contains("v_offset")) {
364 saved_v_offset_ = settings.value("v_offset").toInt();
365 set_v_offset(saved_v_offset_);
366 scroll_needs_defaults_ = false;
367 // Note: see eventFilter() for additional information
370 settings_restored_ = true;
371 suppress_zoom_to_fit_after_acq_ = true;
373 // Update the ruler so that it uses the new scale
374 calculate_tick_spacing();
377 vector< shared_ptr<TimeItem> > View::time_items() const
379 const vector<shared_ptr<Flag>> f(flags());
380 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
381 items.push_back(cursors_);
382 items.push_back(cursors_->first());
383 items.push_back(cursors_->second());
385 for (auto trigger_marker : trigger_markers_)
386 items.push_back(trigger_marker);
391 double View::scale() const
396 void View::set_scale(double scale)
398 if (scale_ != scale) {
404 const Timestamp& View::offset() const
409 void View::set_offset(const pv::util::Timestamp& offset)
411 if (offset_ != offset) {
417 int View::owner_visual_v_offset() const
419 return -scrollarea_->verticalScrollBar()->sliderPosition();
422 void View::set_v_offset(int offset)
424 scrollarea_->verticalScrollBar()->setSliderPosition(offset);
429 unsigned int View::depth() const
434 pv::util::SIPrefix View::tick_prefix() const
439 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
441 if (tick_prefix_ != tick_prefix) {
442 tick_prefix_ = tick_prefix;
443 tick_prefix_changed();
447 unsigned int View::tick_precision() const
449 return tick_precision_;
452 void View::set_tick_precision(unsigned tick_precision)
454 if (tick_precision_ != tick_precision) {
455 tick_precision_ = tick_precision;
456 tick_precision_changed();
460 const pv::util::Timestamp& View::tick_period() const
465 void View::set_tick_period(const pv::util::Timestamp& tick_period)
467 if (tick_period_ != tick_period) {
468 tick_period_ = tick_period;
469 tick_period_changed();
473 TimeUnit View::time_unit() const
478 void View::set_time_unit(pv::util::TimeUnit time_unit)
480 if (time_unit_ != time_unit) {
481 time_unit_ = time_unit;
486 bool View::segment_is_selectable() const
488 return segment_selectable_;
491 void View::set_segment_display_mode(Trace::SegmentDisplayMode mode)
493 for (shared_ptr<Signal> signal : signals_)
494 signal->set_segment_display_mode(mode);
498 segment_selectable_ = true;
500 if (mode == Trace::ShowSingleSegmentOnly)
501 segment_selectable_ = false;
503 segment_display_mode_changed(segment_selectable_);
506 void View::zoom(double steps)
508 zoom(steps, viewport_->width() / 2);
511 void View::zoom(double steps, int offset)
513 set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
516 void View::zoom_fit(bool gui_state)
518 // Act as one-shot when stopped, toggle along with the GUI otherwise
519 if (session_.get_capture_state() == Session::Stopped) {
520 always_zoom_to_fit_ = false;
521 always_zoom_to_fit_changed(false);
523 always_zoom_to_fit_ = gui_state;
524 always_zoom_to_fit_changed(gui_state);
527 const pair<Timestamp, Timestamp> extents = get_time_extents();
528 const Timestamp delta = extents.second - extents.first;
529 if (delta < Timestamp("1e-12"))
533 const int w = viewport_->width();
537 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
538 set_scale_offset(scale.convert_to<double>(), extents.first);
541 void View::zoom_one_to_one()
543 using pv::data::SignalData;
545 // Make a set of all the visible data objects
546 set< shared_ptr<SignalData> > visible_data = get_visible_data();
547 if (visible_data.empty())
551 const int w = viewport_->width();
555 set_zoom(1.0 / session_.get_samplerate(), w / 2);
558 void View::set_scale_offset(double scale, const Timestamp& offset)
560 // Disable sticky scrolling / always zoom to fit when acquisition runs
561 // and user drags the viewport
562 if ((scale_ == scale) && (offset_ != offset) &&
563 (session_.get_capture_state() == Session::Running)) {
565 if (sticky_scrolling_) {
566 sticky_scrolling_ = false;
567 sticky_scrolling_changed(false);
570 if (always_zoom_to_fit_) {
571 always_zoom_to_fit_ = false;
572 always_zoom_to_fit_changed(false);
579 calculate_tick_spacing();
586 set< shared_ptr<SignalData> > View::get_visible_data() const
588 // Make a set of all the visible data objects
589 set< shared_ptr<SignalData> > visible_data;
590 for (const shared_ptr<Signal> sig : signals_)
592 visible_data.insert(sig->data());
597 pair<Timestamp, Timestamp> View::get_time_extents() const
599 boost::optional<Timestamp> left_time, right_time;
600 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
601 for (const shared_ptr<SignalData> d : visible_data) {
602 const vector< shared_ptr<Segment> > segments = d->segments();
603 for (const shared_ptr<Segment> &s : segments) {
604 double samplerate = s->samplerate();
605 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
607 const Timestamp start_time = s->start_time();
608 left_time = left_time ?
609 min(*left_time, start_time) :
611 right_time = right_time ?
612 max(*right_time, start_time + d->max_sample_count() / samplerate) :
613 start_time + d->max_sample_count() / samplerate;
617 if (!left_time || !right_time)
618 return make_pair(0, 0);
620 assert(*left_time < *right_time);
621 return make_pair(*left_time, *right_time);
624 void View::enable_show_sampling_points(bool state)
631 void View::enable_show_analog_minor_grid(bool state)
638 void View::enable_coloured_bg(bool state)
640 coloured_bg_ = state;
644 bool View::coloured_bg() const
649 bool View::cursors_shown() const
651 return show_cursors_;
654 void View::show_cursors(bool show)
656 show_cursors_ = show;
661 void View::centre_cursors()
663 const double time_width = scale_ * viewport_->width();
664 cursors_->first()->set_time(offset_ + time_width * 0.4);
665 cursors_->second()->set_time(offset_ + time_width * 0.6);
670 shared_ptr<CursorPair> View::cursors() const
675 void View::add_flag(const Timestamp& time)
677 flags_.push_back(make_shared<Flag>(*this, time,
678 QString("%1").arg(next_flag_text_)));
680 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
681 (next_flag_text_ + 1);
683 time_item_appearance_changed(true, true);
686 void View::remove_flag(shared_ptr<Flag> flag)
689 time_item_appearance_changed(true, true);
692 vector< shared_ptr<Flag> > View::flags() const
694 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
695 stable_sort(flags.begin(), flags.end(),
696 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
697 return a->time() < b->time();
703 const QPoint& View::hover_point() const
708 void View::restack_all_trace_tree_items()
710 // Make a list of owners that is sorted from deepest first
711 const vector<shared_ptr<TraceTreeItem>> items(
712 list_by_type<TraceTreeItem>());
713 set< TraceTreeItemOwner* > owners;
714 for (const auto &r : items)
715 owners.insert(r->owner());
716 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
717 sort(sorted_owners.begin(), sorted_owners.end(),
718 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
719 return a->depth() > b->depth(); });
721 // Restack the items recursively
722 for (auto &o : sorted_owners)
725 // Animate the items to their destination
726 for (const auto &i : items)
727 i->animate_to_layout_v_offset();
730 void View::trigger_event(util::Timestamp location)
732 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
735 void View::get_scroll_layout(double &length, Timestamp &offset) const
737 const pair<Timestamp, Timestamp> extents = get_time_extents();
738 length = ((extents.second - extents.first) / scale_).convert_to<double>();
739 offset = offset_ / scale_;
742 void View::set_zoom(double scale, int offset)
744 // Reset the "always zoom to fit" feature as the user changed the zoom
745 always_zoom_to_fit_ = false;
746 always_zoom_to_fit_changed(false);
748 const Timestamp cursor_offset = offset_ + scale_ * offset;
749 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
750 const Timestamp new_offset = cursor_offset - new_scale * offset;
751 set_scale_offset(new_scale.convert_to<double>(), new_offset);
754 void View::calculate_tick_spacing()
756 const double SpacingIncrement = 10.0f;
757 const double MinValueSpacing = 40.0f;
759 // Figure out the highest numeric value visible on a label
760 const QSize areaSize = viewport_->size();
761 const Timestamp max_time = max(fabs(offset_),
762 fabs(offset_ + scale_ * areaSize.width()));
764 double min_width = SpacingIncrement;
765 double label_width, tick_period_width;
767 QFontMetrics m(QApplication::font());
769 // Copies of the member variables with the same name, used in the calculation
770 // and written back afterwards, so that we don't emit signals all the time
771 // during the calculation.
772 pv::util::Timestamp tick_period = tick_period_;
773 pv::util::SIPrefix tick_prefix = tick_prefix_;
774 unsigned tick_precision = tick_precision_;
777 const double min_period = scale_ * min_width;
779 const int order = (int)floorf(log10f(min_period));
780 const pv::util::Timestamp order_decimal =
781 pow(pv::util::Timestamp(10), order);
783 // Allow for a margin of error so that a scale unit of 1 can be used.
784 // Otherwise, for a SU of 1 the tick period will almost always be below
785 // the min_period by a small amount - and thus skipped in favor of 2.
786 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
787 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
788 double tp_with_margin;
789 unsigned int unit = 0;
792 tp_with_margin = order_decimal.convert_to<double>() *
793 (ScaleUnits[unit++] + tp_margin);
794 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
796 tick_period = order_decimal * ScaleUnits[unit - 1];
797 tick_prefix = static_cast<pv::util::SIPrefix>(
798 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
800 // Precision is the number of fractional digits required, not
801 // taking the prefix into account (and it must never be negative)
802 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
804 tick_period_width = (tick_period / scale_).convert_to<double>();
806 const QString label_text = Ruler::format_time_with_distance(
807 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
809 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
810 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
813 min_width += SpacingIncrement;
814 } while (tick_period_width < label_width);
816 set_tick_period(tick_period);
817 set_tick_prefix(tick_prefix);
818 set_tick_precision(tick_precision);
821 void View::adjust_top_margin()
825 const QSize areaSize = viewport_->size();
827 const pair<int, int> extents = v_extents();
828 const int top_margin = owner_visual_v_offset() + extents.first;
829 const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
831 // Do we have empty space at the top while the last trace goes out of screen?
832 if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
833 const int trace_height = extents.second - extents.first;
835 // Center everything vertically if there is enough space
836 if (areaSize.height() >= trace_height)
837 set_v_offset(extents.first -
838 ((areaSize.height() - trace_height) / 2));
840 // Remove the top margin to make as many traces fit on screen as possible
841 set_v_offset(extents.first);
845 void View::update_scroll()
848 QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
849 QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
851 const QSize areaSize = viewport_->size();
853 // Set the horizontal scroll bar
856 get_scroll_layout(length, offset);
857 length = max(length - areaSize.width(), 0.0);
859 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
861 hscrollbar->setPageStep(areaSize.width() / 2);
862 hscrollbar->setSingleStep(major_tick_distance);
864 updating_scroll_ = true;
866 if (length < MaxScrollValue) {
867 hscrollbar->setRange(0, length);
868 hscrollbar->setSliderPosition(offset.convert_to<double>());
870 hscrollbar->setRange(0, MaxScrollValue);
871 hscrollbar->setSliderPosition(
872 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
875 updating_scroll_ = false;
877 // Set the vertical scrollbar
878 vscrollbar->setPageStep(areaSize.height());
879 vscrollbar->setSingleStep(areaSize.height() / 8);
881 const pair<int, int> extents = v_extents();
883 // Don't change the scrollbar range if there are no traces
884 if (extents.first != extents.second)
885 vscrollbar->setRange(extents.first - areaSize.height(),
888 if (scroll_needs_defaults_)
889 set_scroll_default();
892 void View::reset_scroll()
894 scrollarea_->verticalScrollBar()->setRange(0, 0);
897 void View::set_scroll_default()
901 const QSize areaSize = viewport_->size();
903 const pair<int, int> extents = v_extents();
904 const int trace_height = extents.second - extents.first;
906 // Do all traces fit in the view?
907 if (areaSize.height() >= trace_height)
908 // Center all traces vertically
909 set_v_offset(extents.first -
910 ((areaSize.height() - trace_height) / 2));
912 // Put the first trace at the top, letting the bottom ones overflow
913 set_v_offset(extents.first);
916 void View::determine_if_header_was_shrunk()
918 const int header_pane_width = splitter_->sizes().front();
919 const int header_width = header_->extended_size_hint().width();
921 // Allow for a slight margin of error so that we also accept
922 // slight differences when e.g. a label name change increased
924 header_was_shrunk_ = (header_pane_width < (header_width - 10));
927 void View::resize_header_to_fit()
929 // Setting the maximum width of the header widget doesn't work as
930 // expected because the splitter would allow the user to make the
931 // pane wider than that, creating empty space as a result.
932 // To make this work, we stricly enforce the maximum width by
933 // expanding the header unless the user shrunk it on purpose.
934 // As we're then setting the width of the header pane, we set the
935 // splitter to the maximum allowed position.
937 int splitter_area_width = 0;
938 for (int w : splitter_->sizes())
939 splitter_area_width += w;
941 // Make sure the header has enough horizontal space to show all labels fully
942 QList<int> pane_sizes;
943 pane_sizes.push_back(header_->extended_size_hint().width());
944 pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
945 splitter_->setSizes(pane_sizes);
948 void View::update_layout()
953 TraceTreeItemOwner* View::find_prevalent_trace_group(
954 const shared_ptr<sigrok::ChannelGroup> &group,
955 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
960 unordered_set<TraceTreeItemOwner*> owners;
961 vector<TraceTreeItemOwner*> owner_list;
963 // Make a set and a list of all the owners
964 for (const auto &channel : group->channels()) {
965 for (auto entry : signal_map) {
966 if (entry.first->channel() == channel) {
967 TraceTreeItemOwner *const o = (entry.second)->owner();
968 owner_list.push_back(o);
974 // Iterate through the list of owners, and find the most prevalent
975 size_t max_prevalence = 0;
976 TraceTreeItemOwner *prevalent_owner = nullptr;
977 for (TraceTreeItemOwner *owner : owners) {
978 const size_t prevalence = count_if(
979 owner_list.begin(), owner_list.end(),
980 [&](TraceTreeItemOwner *o) { return o == owner; });
981 if (prevalence > max_prevalence) {
982 max_prevalence = prevalence;
983 prevalent_owner = owner;
987 return prevalent_owner;
990 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
991 const vector< shared_ptr<sigrok::Channel> > &channels,
992 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
994 set< shared_ptr<Trace> > &add_list)
996 vector< shared_ptr<Trace> > filtered_traces;
998 for (const auto &channel : channels) {
999 for (auto entry : signal_map) {
1000 if (entry.first->channel() == channel) {
1001 shared_ptr<Trace> trace = entry.second;
1002 const auto list_iter = add_list.find(trace);
1003 if (list_iter == add_list.end())
1006 filtered_traces.push_back(trace);
1007 add_list.erase(list_iter);
1012 return filtered_traces;
1015 void View::determine_time_unit()
1017 // Check whether we know the sample rate and hence can use time as the unit
1018 if (time_unit_ == util::TimeUnit::Samples) {
1019 // Check all signals but...
1020 for (const shared_ptr<Signal> signal : signals_) {
1021 const shared_ptr<SignalData> data = signal->data();
1023 // ...only check first segment of each
1024 const vector< shared_ptr<Segment> > segments = data->segments();
1025 if (!segments.empty())
1026 if (segments[0]->samplerate()) {
1027 set_time_unit(util::TimeUnit::Time);
1034 bool View::eventFilter(QObject *object, QEvent *event)
1036 const QEvent::Type type = event->type();
1037 if (type == QEvent::MouseMove) {
1039 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
1040 if (object == viewport_)
1041 hover_point_ = mouse_event->pos();
1042 else if (object == ruler_)
1043 hover_point_ = QPoint(mouse_event->x(), 0);
1044 else if (object == header_)
1045 hover_point_ = QPoint(0, mouse_event->y());
1047 hover_point_ = QPoint(-1, -1);
1049 update_hover_point();
1051 } else if (type == QEvent::Leave) {
1052 hover_point_ = QPoint(-1, -1);
1053 update_hover_point();
1054 } else if (type == QEvent::Show) {
1056 // This is somewhat of a hack, unfortunately. We cannot use
1057 // set_v_offset() from within restore_settings() as the view
1058 // at that point is neither visible nor properly sized.
1059 // This is the least intrusive workaround I could come up
1060 // with: set the vertical offset (or scroll defaults) when
1061 // the view is shown, which happens after all widgets were
1062 // resized to their final sizes.
1065 if (settings_restored_)
1066 determine_if_header_was_shrunk();
1068 resize_header_to_fit();
1070 if (scroll_needs_defaults_) {
1071 set_scroll_default();
1072 scroll_needs_defaults_ = false;
1075 if (saved_v_offset_) {
1076 set_v_offset(saved_v_offset_);
1077 saved_v_offset_ = 0;
1081 return QObject::eventFilter(object, event);
1084 void View::resizeEvent(QResizeEvent* event)
1086 // Only adjust the top margin if we shrunk vertically
1087 if (event->size().height() < event->oldSize().height())
1088 adjust_top_margin();
1093 void View::update_hover_point()
1095 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1096 list_by_type<TraceTreeItem>());
1097 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1098 r->hover_point_changed(hover_point_);
1100 hover_point_changed(hover_point_);
1103 void View::row_item_appearance_changed(bool label, bool content)
1108 viewport_->update();
1111 void View::time_item_appearance_changed(bool label, bool content)
1116 // Make sure the header pane width is updated, too
1121 viewport_->update();
1124 void View::extents_changed(bool horz, bool vert)
1127 (horz ? TraceTreeItemHExtentsChanged : 0) |
1128 (vert ? TraceTreeItemVExtentsChanged : 0);
1130 lazy_event_handler_.start();
1133 void View::on_signal_name_changed()
1135 if (!header_was_shrunk_)
1136 resize_header_to_fit();
1139 void View::on_splitter_moved()
1141 // The header can only shrink when the splitter is moved manually
1142 determine_if_header_was_shrunk();
1144 if (!header_was_shrunk_)
1145 resize_header_to_fit();
1148 void View::h_scroll_value_changed(int value)
1150 if (updating_scroll_)
1153 // Disable sticky scrolling when user moves the horizontal scroll bar
1154 // during a running acquisition
1155 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1156 sticky_scrolling_ = false;
1157 sticky_scrolling_changed(false);
1160 const int range = scrollarea_->horizontalScrollBar()->maximum();
1161 if (range < MaxScrollValue)
1162 set_offset(scale_ * value);
1166 get_scroll_layout(length, offset);
1167 set_offset(scale_ * length * value / MaxScrollValue);
1171 viewport_->update();
1174 void View::v_scroll_value_changed()
1177 viewport_->update();
1180 void View::signals_changed()
1182 using sigrok::Channel;
1184 vector< shared_ptr<Channel> > channels;
1185 shared_ptr<sigrok::Device> sr_dev;
1186 bool signals_added_or_removed = false;
1188 // Do we need to set the vertical scrollbar to its default position later?
1189 // We do if there are no traces, i.e. the scroll bar has no range set
1190 bool reset_scrollbar =
1191 (scrollarea_->verticalScrollBar()->minimum() ==
1192 scrollarea_->verticalScrollBar()->maximum());
1194 if (!session_.device()) {
1198 sr_dev = session_.device()->device();
1200 channels = sr_dev->channels();
1203 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1205 // Make a list of traces that are being added, and a list of traces
1206 // that are being removed
1207 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1208 const set<shared_ptr<Trace>> prev_traces(
1209 prev_trace_list.begin(), prev_trace_list.end());
1211 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1213 #ifdef ENABLE_DECODE
1214 traces.insert(decode_traces_.begin(), decode_traces_.end());
1217 set< shared_ptr<Trace> > add_traces;
1218 set_difference(traces.begin(), traces.end(),
1219 prev_traces.begin(), prev_traces.end(),
1220 inserter(add_traces, add_traces.begin()));
1222 set< shared_ptr<Trace> > remove_traces;
1223 set_difference(prev_traces.begin(), prev_traces.end(),
1224 traces.begin(), traces.end(),
1225 inserter(remove_traces, remove_traces.begin()));
1227 // Make a look-up table of sigrok Channels to pulseview Signals
1228 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1230 for (const shared_ptr<Signal> &sig : signals_)
1231 signal_map[sig->base()] = sig;
1233 // Populate channel groups
1235 for (auto entry : sr_dev->channel_groups()) {
1236 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1238 if (group->channels().size() <= 1)
1241 // Find best trace group to add to
1242 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1245 // If there is no trace group, create one
1246 shared_ptr<TraceGroup> new_trace_group;
1248 new_trace_group.reset(new TraceGroup());
1249 owner = new_trace_group.get();
1252 // Extract traces for the trace group, removing them from
1254 const vector< shared_ptr<Trace> > new_traces_in_group =
1255 extract_new_traces_for_channels(group->channels(),
1256 signal_map, add_traces);
1258 // Add the traces to the group
1259 const pair<int, int> prev_v_extents = owner->v_extents();
1260 int offset = prev_v_extents.second - prev_v_extents.first;
1261 for (shared_ptr<Trace> trace : new_traces_in_group) {
1263 owner->add_child_item(trace);
1265 const pair<int, int> extents = trace->v_extents();
1266 if (trace->enabled())
1267 offset += -extents.first;
1268 trace->force_to_v_offset(offset);
1269 if (trace->enabled())
1270 offset += extents.second;
1273 if (new_trace_group) {
1274 // Assign proper vertical offsets to each channel in the group
1275 new_trace_group->restack_items();
1277 // If this is a new group, enqueue it in the new top level
1279 if (!new_traces_in_group.empty())
1280 new_top_level_items.push_back(new_trace_group);
1284 // Enqueue the remaining logic channels in a group
1285 vector< shared_ptr<Channel> > logic_channels;
1286 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1287 [](const shared_ptr<Channel>& c) {
1288 return c->type() == sigrok::ChannelType::LOGIC; });
1290 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1291 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1293 if (non_grouped_logic_signals.size() > 0) {
1294 const shared_ptr<TraceGroup> non_grouped_trace_group(
1295 make_shared<TraceGroup>());
1296 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1297 non_grouped_trace_group->add_child_item(trace);
1299 non_grouped_trace_group->restack_items();
1300 new_top_level_items.push_back(non_grouped_trace_group);
1303 // Enqueue the remaining channels as free ungrouped traces
1304 const vector< shared_ptr<Trace> > new_top_level_signals =
1305 extract_new_traces_for_channels(channels, signal_map, add_traces);
1306 new_top_level_items.insert(new_top_level_items.end(),
1307 new_top_level_signals.begin(), new_top_level_signals.end());
1309 // Enqueue any remaining traces i.e. decode traces
1310 new_top_level_items.insert(new_top_level_items.end(),
1311 add_traces.begin(), add_traces.end());
1313 // Remove any removed traces
1314 for (shared_ptr<Trace> trace : remove_traces) {
1315 TraceTreeItemOwner *const owner = trace->owner();
1317 owner->remove_child_item(trace);
1318 signals_added_or_removed = true;
1321 // Remove any empty trace groups
1322 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1323 if (group->child_items().size() == 0) {
1324 remove_child_item(group);
1328 // Add and position the pending top levels items
1329 int offset = v_extents().second;
1330 for (auto item : new_top_level_items) {
1331 add_child_item(item);
1333 // Position the item after the last item or at the top if there is none
1334 const pair<int, int> extents = item->v_extents();
1336 if (item->enabled())
1337 offset += -extents.first;
1339 item->force_to_v_offset(offset);
1341 if (item->enabled())
1342 offset += extents.second;
1343 signals_added_or_removed = true;
1347 if (signals_added_or_removed && !header_was_shrunk_)
1348 resize_header_to_fit();
1353 viewport_->update();
1355 if (reset_scrollbar)
1356 set_scroll_default();
1359 void View::capture_state_updated(int state)
1361 GlobalSettings settings;
1363 if (state == Session::Running) {
1364 set_time_unit(util::TimeUnit::Samples);
1366 trigger_markers_.clear();
1368 scale_at_acq_start_ = scale_;
1369 offset_at_acq_start_ = offset_;
1371 // Activate "always zoom to fit" if the setting is enabled and we're
1372 // the main view of this session (other trace views may be used for
1373 // zooming and we don't want to mess them up)
1374 bool state = settings.value(GlobalSettings::Key_View_ZoomToFitDuringAcq).toBool();
1375 if (is_main_view_ && state) {
1376 always_zoom_to_fit_ = true;
1377 always_zoom_to_fit_changed(always_zoom_to_fit_);
1380 // Enable sticky scrolling if the setting is enabled
1381 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1384 if (state == Session::Stopped) {
1385 // After acquisition has stopped we need to re-calculate the ticks once
1386 // as it's otherwise done when the user pans or zooms, which is too late
1387 calculate_tick_spacing();
1389 // Reset "always zoom to fit", the acquisition has stopped
1390 if (always_zoom_to_fit_) {
1391 // Perform a final zoom-to-fit before disabling
1392 zoom_fit(always_zoom_to_fit_);
1393 always_zoom_to_fit_ = false;
1394 always_zoom_to_fit_changed(always_zoom_to_fit_);
1397 bool zoom_to_fit_after_acq =
1398 settings.value(GlobalSettings::Key_View_ZoomToFitAfterAcq).toBool();
1400 // Only perform zoom-to-fit if the user hasn't altered the viewport and
1401 // we didn't restore settings in the meanwhile
1402 if (zoom_to_fit_after_acq &&
1403 !suppress_zoom_to_fit_after_acq_ &&
1404 (scale_ == scale_at_acq_start_) &&
1405 (offset_ == offset_at_acq_start_))
1406 zoom_fit(false); // We're stopped, so the GUI state doesn't matter
1408 suppress_zoom_to_fit_after_acq_ = false;
1412 void View::on_new_segment(int new_segment_id)
1414 on_segment_changed(new_segment_id);
1415 segment_changed(new_segment_id);
1418 void View::on_segment_changed(int segment)
1420 switch (segment_display_mode_) {
1421 case Trace::ShowLastSegmentOnly:
1422 case Trace::ShowSingleSegmentOnly:
1423 current_segment_ = segment - 1;
1424 for (shared_ptr<Signal> signal : signals_)
1425 signal->set_current_segment(current_segment_);
1426 viewport_->update();
1429 case Trace::ShowAllSegments:
1430 case Trace::ShowAccumulatedIntensity:
1436 void View::perform_delayed_view_update()
1438 if (always_zoom_to_fit_) {
1440 } else if (sticky_scrolling_) {
1441 // Make right side of the view sticky
1444 get_scroll_layout(length, offset);
1446 const QSize areaSize = viewport_->size();
1447 length = max(length - areaSize.width(), 0.0);
1449 set_offset(scale_ * length);
1452 determine_time_unit();
1455 viewport_->update();
1458 void View::process_sticky_events()
1460 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1462 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1463 restack_all_trace_tree_items();
1467 // Clear the sticky events
1471 } // namespace trace
1472 } // namespace views