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>
33 #include <unordered_set>
35 #include <boost/archive/text_iarchive.hpp>
36 #include <boost/archive/text_oarchive.hpp>
37 #include <boost/serialization/serialization.hpp>
38 #include <boost/thread/locks.hpp>
40 #include <QApplication>
41 #include <QHBoxLayout>
43 #include <QFontMetrics>
44 #include <QMouseEvent>
47 #include <libsigrokcxx/libsigrokcxx.hpp>
49 #include "analogsignal.hpp"
51 #include "logicsignal.hpp"
54 #include "tracegroup.hpp"
55 #include "triggermarker.hpp"
57 #include "viewport.hpp"
59 #include "pv/session.hpp"
60 #include "pv/globalsettings.hpp"
61 #include "pv/devices/device.hpp"
62 #include "pv/data/logic.hpp"
63 #include "pv/data/logicsegment.hpp"
64 #include "pv/util.hpp"
67 #include "decodetrace.hpp"
70 using boost::shared_lock;
71 using boost::shared_mutex;
73 using pv::data::SignalData;
74 using pv::data::Segment;
75 using pv::util::TimeUnit;
76 using pv::util::Timestamp;
78 using std::back_inserter;
82 using std::dynamic_pointer_cast;
85 using std::lock_guard;
88 using std::make_shared;
92 using std::set_difference;
93 using std::shared_ptr;
94 using std::stringstream;
95 using std::unordered_map;
96 using std::unordered_set;
102 namespace TraceView {
104 const Timestamp View::MaxScale("1e9");
105 const Timestamp View::MinScale("1e-12");
107 const int View::MaxScrollValue = INT_MAX / 2;
108 const int View::MaxViewAutoUpdateRate = 25; // No more than 25 Hz with sticky scrolling
110 const int View::ScaleUnits[3] = {1, 2, 5};
113 CustomAbstractScrollArea::CustomAbstractScrollArea(QWidget *parent) :
114 QAbstractScrollArea(parent)
118 void CustomAbstractScrollArea::setViewportMargins(int left, int top, int right, int bottom)
120 QAbstractScrollArea::setViewportMargins(left, top, right, bottom);
123 bool CustomAbstractScrollArea::viewportEvent(QEvent *event)
125 switch (event->type()) {
127 case QEvent::MouseButtonPress:
128 case QEvent::MouseButtonRelease:
129 case QEvent::MouseButtonDblClick:
130 case QEvent::MouseMove:
132 case QEvent::TouchBegin:
133 case QEvent::TouchUpdate:
134 case QEvent::TouchEnd:
137 return QAbstractScrollArea::viewportEvent(event);
141 View::View(Session &session, bool is_main_view, QWidget *parent) :
142 ViewBase(session, is_main_view, parent),
143 viewport_(new Viewport(*this)),
144 ruler_(new Ruler(*this)),
145 header_(new Header(*this)),
149 updating_scroll_(false),
150 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
151 always_zoom_to_fit_(false),
153 tick_prefix_(pv::util::SIPrefix::yocto),
155 time_unit_(util::TimeUnit::Time),
156 show_cursors_(false),
157 cursors_(new CursorPair(*this)),
158 next_flag_text_('A'),
160 hover_point_(-1, -1),
161 scroll_needs_defaults_(false),
163 size_finalized_(false)
165 GlobalSettings settings;
166 coloured_bg_ = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
168 connect(scrollarea_.horizontalScrollBar(), SIGNAL(valueChanged(int)),
169 this, SLOT(h_scroll_value_changed(int)));
170 connect(scrollarea_.verticalScrollBar(), SIGNAL(valueChanged(int)),
171 this, SLOT(v_scroll_value_changed()));
173 connect(header_, SIGNAL(selection_changed()),
174 ruler_, SLOT(clear_selection()));
175 connect(ruler_, SIGNAL(selection_changed()),
176 header_, SLOT(clear_selection()));
178 connect(header_, SIGNAL(selection_changed()),
179 this, SIGNAL(selection_changed()));
180 connect(ruler_, SIGNAL(selection_changed()),
181 this, SIGNAL(selection_changed()));
183 connect(this, SIGNAL(hover_point_changed()),
184 this, SLOT(on_hover_point_changed()));
186 connect(&lazy_event_handler_, SIGNAL(timeout()),
187 this, SLOT(process_sticky_events()));
188 lazy_event_handler_.setSingleShot(true);
190 connect(&delayed_view_updater_, SIGNAL(timeout()),
191 this, SLOT(perform_delayed_view_update()));
192 delayed_view_updater_.setSingleShot(true);
193 delayed_view_updater_.setInterval(1000 / MaxViewAutoUpdateRate);
195 /* To let the scroll area fill up the parent QWidget (this), we need a layout */
196 QHBoxLayout *layout = new QHBoxLayout(this);
198 layout->setContentsMargins(0, 0, 0, 0);
199 layout->addWidget(&scrollarea_);
201 scrollarea_.setViewport(viewport_);
203 viewport_->installEventFilter(this);
204 ruler_->installEventFilter(this);
205 header_->installEventFilter(this);
207 // Trigger the initial event manually. The default device has signals
208 // which were created before this object came into being
211 // make sure the transparent widgets are on the top
215 // Update the zoom state
216 calculate_tick_spacing();
219 Session& View::session()
224 const Session& View::session() const
229 unordered_set< shared_ptr<Signal> > View::signals() const
234 void View::clear_signals()
239 void View::add_signal(const shared_ptr<Signal> signal)
241 signals_.insert(signal);
245 void View::clear_decode_signals()
247 decode_traces_.clear();
250 void View::add_decode_signal(shared_ptr<data::SignalBase> signalbase)
252 shared_ptr<DecodeTrace> d(
253 new DecodeTrace(session_, signalbase, decode_traces_.size()));
254 decode_traces_.push_back(d);
257 void View::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
259 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
260 if ((*i)->base() == signalbase) {
261 decode_traces_.erase(i);
273 const View* View::view() const
278 Viewport* View::viewport()
283 const Viewport* View::viewport() const
288 void View::save_settings(QSettings &settings) const
290 settings.setValue("scale", scale_);
291 settings.setValue("v_offset",
292 scrollarea_.verticalScrollBar()->sliderPosition());
295 boost::archive::text_oarchive oa(ss);
296 oa << boost::serialization::make_nvp("offset", offset_);
297 settings.setValue("offset", QString::fromStdString(ss.str()));
299 for (shared_ptr<Signal> signal : signals_) {
300 settings.beginGroup(signal->base()->internal_name());
301 signal->save_settings(settings);
306 void View::restore_settings(QSettings &settings)
308 // Note: It is assumed that this function is only called once,
309 // immediately after restoring a previous session.
311 if (settings.contains("scale"))
312 set_scale(settings.value("scale").toDouble());
314 if (settings.contains("offset")) {
315 util::Timestamp offset;
317 ss << settings.value("offset").toString().toStdString();
319 boost::archive::text_iarchive ia(ss);
320 ia >> boost::serialization::make_nvp("offset", offset);
325 for (shared_ptr<Signal> signal : signals_) {
326 settings.beginGroup(signal->base()->internal_name());
327 signal->restore_settings(settings);
331 if (settings.contains("v_offset")) {
332 saved_v_offset_ = settings.value("v_offset").toInt();
333 set_v_offset(saved_v_offset_);
334 scroll_needs_defaults_ = false;
335 // Note: see resizeEvent() for additional information
339 vector< shared_ptr<TimeItem> > View::time_items() const
341 const vector<shared_ptr<Flag>> f(flags());
342 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
343 items.push_back(cursors_);
344 items.push_back(cursors_->first());
345 items.push_back(cursors_->second());
347 for (auto trigger_marker : trigger_markers_)
348 items.push_back(trigger_marker);
353 double View::scale() const
358 void View::set_scale(double scale)
360 if (scale_ != scale) {
362 Q_EMIT scale_changed();
366 const Timestamp& View::offset() const
371 void View::set_offset(const pv::util::Timestamp& offset)
373 if (offset_ != offset) {
375 Q_EMIT offset_changed();
379 int View::owner_visual_v_offset() const
381 return -scrollarea_.verticalScrollBar()->sliderPosition();
384 void View::set_v_offset(int offset)
386 scrollarea_.verticalScrollBar()->setSliderPosition(offset);
391 unsigned int View::depth() const
396 pv::util::SIPrefix View::tick_prefix() const
401 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
403 if (tick_prefix_ != tick_prefix) {
404 tick_prefix_ = tick_prefix;
405 Q_EMIT tick_prefix_changed();
409 unsigned int View::tick_precision() const
411 return tick_precision_;
414 void View::set_tick_precision(unsigned tick_precision)
416 if (tick_precision_ != tick_precision) {
417 tick_precision_ = tick_precision;
418 Q_EMIT tick_precision_changed();
422 const pv::util::Timestamp& View::tick_period() const
427 void View::set_tick_period(const pv::util::Timestamp& tick_period)
429 if (tick_period_ != tick_period) {
430 tick_period_ = tick_period;
431 Q_EMIT tick_period_changed();
435 TimeUnit View::time_unit() const
440 void View::set_time_unit(pv::util::TimeUnit time_unit)
442 if (time_unit_ != time_unit) {
443 time_unit_ = time_unit;
444 Q_EMIT time_unit_changed();
448 void View::zoom(double steps)
450 zoom(steps, viewport_->width() / 2);
453 void View::zoom(double steps, int offset)
455 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
458 void View::zoom_fit(bool gui_state)
460 // Act as one-shot when stopped, toggle along with the GUI otherwise
461 if (session_.get_capture_state() == Session::Stopped) {
462 always_zoom_to_fit_ = false;
463 always_zoom_to_fit_changed(false);
465 always_zoom_to_fit_ = gui_state;
466 always_zoom_to_fit_changed(gui_state);
469 const pair<Timestamp, Timestamp> extents = get_time_extents();
470 const Timestamp delta = extents.second - extents.first;
471 if (delta < Timestamp("1e-12"))
475 const int w = viewport_->width();
479 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
480 set_scale_offset(scale.convert_to<double>(), extents.first);
483 void View::zoom_one_to_one()
485 using pv::data::SignalData;
487 // Make a set of all the visible data objects
488 set< shared_ptr<SignalData> > visible_data = get_visible_data();
489 if (visible_data.empty())
493 const int w = viewport_->width();
497 set_zoom(1.0 / session_.get_samplerate(), w / 2);
500 void View::set_scale_offset(double scale, const Timestamp& offset)
502 // Disable sticky scrolling / always zoom to fit when acquisition runs
503 // and user drags the viewport
504 if ((scale_ == scale) && (offset_ != offset) &&
505 (session_.get_capture_state() == Session::Running)) {
507 if (sticky_scrolling_) {
508 sticky_scrolling_ = false;
509 sticky_scrolling_changed(false);
512 if (always_zoom_to_fit_) {
513 always_zoom_to_fit_ = false;
514 always_zoom_to_fit_changed(false);
521 calculate_tick_spacing();
528 set< shared_ptr<SignalData> > View::get_visible_data() const
530 // Make a set of all the visible data objects
531 set< shared_ptr<SignalData> > visible_data;
532 for (const shared_ptr<Signal> sig : signals_)
534 visible_data.insert(sig->data());
539 pair<Timestamp, Timestamp> View::get_time_extents() const
541 boost::optional<Timestamp> left_time, right_time;
542 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
543 for (const shared_ptr<SignalData> d : visible_data) {
544 const vector< shared_ptr<Segment> > segments =
546 for (const shared_ptr<Segment> &s : segments) {
547 double samplerate = s->samplerate();
548 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
550 const Timestamp start_time = s->start_time();
551 left_time = left_time ?
552 min(*left_time, start_time) :
554 right_time = right_time ?
555 max(*right_time, start_time + d->max_sample_count() / samplerate) :
556 start_time + d->max_sample_count() / samplerate;
560 if (!left_time || !right_time)
561 return make_pair(0, 0);
563 assert(*left_time < *right_time);
564 return make_pair(*left_time, *right_time);
567 void View::enable_show_sampling_points(bool state)
574 void View::enable_coloured_bg(bool state)
576 const vector<shared_ptr<TraceTreeItem>> items(
577 list_by_type<TraceTreeItem>());
579 for (shared_ptr<TraceTreeItem> i : items) {
580 // Can't cast to Trace because it's abstract, so we need to
581 // check for any derived classes individually
583 shared_ptr<AnalogSignal> a = dynamic_pointer_cast<AnalogSignal>(i);
585 a->set_coloured_bg(state);
587 shared_ptr<LogicSignal> l = dynamic_pointer_cast<LogicSignal>(i);
589 l->set_coloured_bg(state);
592 shared_ptr<DecodeTrace> d = dynamic_pointer_cast<DecodeTrace>(i);
594 d->set_coloured_bg(state);
601 bool View::cursors_shown() const
603 return show_cursors_;
606 void View::show_cursors(bool show)
608 show_cursors_ = show;
613 void View::centre_cursors()
615 const double time_width = scale_ * viewport_->width();
616 cursors_->first()->set_time(offset_ + time_width * 0.4);
617 cursors_->second()->set_time(offset_ + time_width * 0.6);
622 shared_ptr<CursorPair> View::cursors() const
627 void View::add_flag(const Timestamp& time)
629 flags_.push_back(make_shared<Flag>(*this, time,
630 QString("%1").arg(next_flag_text_)));
632 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
633 (next_flag_text_ + 1);
635 time_item_appearance_changed(true, true);
638 void View::remove_flag(shared_ptr<Flag> flag)
641 time_item_appearance_changed(true, true);
644 vector< shared_ptr<Flag> > View::flags() const
646 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
647 stable_sort(flags.begin(), flags.end(),
648 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
649 return a->time() < b->time();
655 const QPoint& View::hover_point() const
660 void View::restack_all_trace_tree_items()
662 // Make a list of owners that is sorted from deepest first
663 const vector<shared_ptr<TraceTreeItem>> items(
664 list_by_type<TraceTreeItem>());
665 set< TraceTreeItemOwner* > owners;
666 for (const auto &r : items)
667 owners.insert(r->owner());
668 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
669 sort(sorted_owners.begin(), sorted_owners.end(),
670 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
671 return a->depth() > b->depth(); });
673 // Restack the items recursively
674 for (auto &o : sorted_owners)
677 // Re-assign background colors
678 bool next_bgcolour_state = false;
680 for (auto &o : sorted_owners)
681 next_bgcolour_state = o->reassign_bgcolour_states(next_bgcolour_state);
683 // Animate the items to their destination
684 for (const auto &i : items)
685 i->animate_to_layout_v_offset();
688 void View::trigger_event(util::Timestamp location)
690 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
693 void View::get_scroll_layout(double &length, Timestamp &offset) const
695 const pair<Timestamp, Timestamp> extents = get_time_extents();
696 length = ((extents.second - extents.first) / scale_).convert_to<double>();
697 offset = offset_ / scale_;
700 void View::set_zoom(double scale, int offset)
702 // Reset the "always zoom to fit" feature as the user changed the zoom
703 always_zoom_to_fit_ = false;
704 always_zoom_to_fit_changed(false);
706 const Timestamp cursor_offset = offset_ + scale_ * offset;
707 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
708 const Timestamp new_offset = cursor_offset - new_scale * offset;
709 set_scale_offset(new_scale.convert_to<double>(), new_offset);
712 void View::calculate_tick_spacing()
714 const double SpacingIncrement = 10.0f;
715 const double MinValueSpacing = 40.0f;
717 // Figure out the highest numeric value visible on a label
718 const QSize areaSize = viewport_->size();
719 const Timestamp max_time = max(fabs(offset_),
720 fabs(offset_ + scale_ * areaSize.width()));
722 double min_width = SpacingIncrement;
723 double label_width, tick_period_width;
725 QFontMetrics m(QApplication::font());
727 // Copies of the member variables with the same name, used in the calculation
728 // and written back afterwards, so that we don't emit signals all the time
729 // during the calculation.
730 pv::util::Timestamp tick_period = tick_period_;
731 pv::util::SIPrefix tick_prefix = tick_prefix_;
732 unsigned tick_precision = tick_precision_;
735 const double min_period = scale_ * min_width;
737 const int order = (int)floorf(log10f(min_period));
738 const pv::util::Timestamp order_decimal =
739 pow(pv::util::Timestamp(10), order);
741 // Allow for a margin of error so that a scale unit of 1 can be used.
742 // Otherwise, for a SU of 1 the tick period will almost always be below
743 // the min_period by a small amount - and thus skipped in favor of 2.
744 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
745 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
746 double tp_with_margin;
747 unsigned int unit = 0;
750 tp_with_margin = order_decimal.convert_to<double>() *
751 (ScaleUnits[unit++] + tp_margin);
752 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
754 tick_period = order_decimal * ScaleUnits[unit - 1];
755 tick_prefix = static_cast<pv::util::SIPrefix>(
756 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
758 // Precision is the number of fractional digits required, not
759 // taking the prefix into account (and it must never be negative)
760 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
762 tick_period_width = (tick_period / scale_).convert_to<double>();
764 const QString label_text = Ruler::format_time_with_distance(
765 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
767 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
768 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
771 min_width += SpacingIncrement;
772 } while (tick_period_width < label_width);
774 set_tick_period(tick_period);
775 set_tick_prefix(tick_prefix);
776 set_tick_precision(tick_precision);
779 void View::update_scroll()
782 QScrollBar *hscrollbar = scrollarea_.horizontalScrollBar();
783 QScrollBar *vscrollbar = scrollarea_.verticalScrollBar();
785 const QSize areaSize = viewport_->size();
787 // Set the horizontal scroll bar
790 get_scroll_layout(length, offset);
791 length = max(length - areaSize.width(), 0.0);
793 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
795 hscrollbar->setPageStep(areaSize.width() / 2);
796 hscrollbar->setSingleStep(major_tick_distance);
798 updating_scroll_ = true;
800 if (length < MaxScrollValue) {
801 hscrollbar->setRange(0, length);
802 hscrollbar->setSliderPosition(offset.convert_to<double>());
804 hscrollbar->setRange(0, MaxScrollValue);
805 hscrollbar->setSliderPosition(
806 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
809 updating_scroll_ = false;
811 // Set the vertical scrollbar
812 vscrollbar->setPageStep(areaSize.height());
813 vscrollbar->setSingleStep(areaSize.height() / 8);
815 const pair<int, int> extents = v_extents();
817 // Don't change the scrollbar range if there are no traces
818 if (extents.first != extents.second)
819 vscrollbar->setRange(extents.first - areaSize.height(),
822 if (scroll_needs_defaults_)
823 set_scroll_default();
826 void View::reset_scroll()
828 scrollarea_.verticalScrollBar()->setRange(0, 0);
831 void View::set_scroll_default()
835 const QSize areaSize = viewport_->size();
837 const pair<int, int> extents = v_extents();
838 const int trace_height = extents.second - extents.first;
840 // Do all traces fit in the view?
841 if (areaSize.height() >= trace_height)
842 // Center all traces vertically
843 set_v_offset(extents.first -
844 ((areaSize.height() - trace_height) / 2));
846 // Put the first trace at the top, letting the bottom ones overflow
847 set_v_offset(extents.first);
849 // If we're not sure whether setting the defaults worked as
850 // the window wasn't set up entirely yet, we want to be called
851 // again later to make sure
852 scroll_needs_defaults_ = !size_finalized_;
855 void View::update_layout()
857 scrollarea_.setViewportMargins(
858 header_->sizeHint().width() - Header::BaselineOffset,
859 ruler_->sizeHint().height(), 0, 0);
860 ruler_->setGeometry(viewport_->x(), 0,
861 viewport_->width(), ruler_->extended_size_hint().height());
862 header_->setGeometry(0, viewport_->y(),
863 header_->extended_size_hint().width(), viewport_->height());
867 TraceTreeItemOwner* View::find_prevalent_trace_group(
868 const shared_ptr<sigrok::ChannelGroup> &group,
869 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
874 unordered_set<TraceTreeItemOwner*> owners;
875 vector<TraceTreeItemOwner*> owner_list;
877 // Make a set and a list of all the owners
878 for (const auto &channel : group->channels()) {
879 for (auto entry : signal_map) {
880 if (entry.first->channel() == channel) {
881 TraceTreeItemOwner *const o = (entry.second)->owner();
882 owner_list.push_back(o);
888 // Iterate through the list of owners, and find the most prevalent
889 size_t max_prevalence = 0;
890 TraceTreeItemOwner *prevalent_owner = nullptr;
891 for (TraceTreeItemOwner *owner : owners) {
892 const size_t prevalence = count_if(
893 owner_list.begin(), owner_list.end(),
894 [&](TraceTreeItemOwner *o) { return o == owner; });
895 if (prevalence > max_prevalence) {
896 max_prevalence = prevalence;
897 prevalent_owner = owner;
901 return prevalent_owner;
904 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
905 const vector< shared_ptr<sigrok::Channel> > &channels,
906 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
908 set< shared_ptr<Trace> > &add_list)
910 vector< shared_ptr<Trace> > filtered_traces;
912 for (const auto &channel : channels) {
913 for (auto entry : signal_map) {
914 if (entry.first->channel() == channel) {
915 shared_ptr<Trace> trace = entry.second;
916 const auto list_iter = add_list.find(trace);
917 if (list_iter == add_list.end())
920 filtered_traces.push_back(trace);
921 add_list.erase(list_iter);
926 return filtered_traces;
929 void View::determine_time_unit()
931 // Check whether we know the sample rate and hence can use time as the unit
932 if (time_unit_ == util::TimeUnit::Samples) {
933 // Check all signals but...
934 for (const shared_ptr<Signal> signal : signals_) {
935 const shared_ptr<SignalData> data = signal->data();
937 // ...only check first segment of each
938 const vector< shared_ptr<Segment> > segments = data->segments();
939 if (!segments.empty())
940 if (segments[0]->samplerate()) {
941 set_time_unit(util::TimeUnit::Time);
948 bool View::eventFilter(QObject *object, QEvent *event)
950 const QEvent::Type type = event->type();
951 if (type == QEvent::MouseMove) {
953 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
954 if (object == viewport_)
955 hover_point_ = mouse_event->pos();
956 else if (object == ruler_)
957 hover_point_ = QPoint(mouse_event->x(), 0);
958 else if (object == header_)
959 hover_point_ = QPoint(0, mouse_event->y());
961 hover_point_ = QPoint(-1, -1);
963 hover_point_changed();
965 } else if (type == QEvent::Leave) {
966 hover_point_ = QPoint(-1, -1);
967 hover_point_changed();
970 return QObject::eventFilter(object, event);
973 void View::resizeEvent(QResizeEvent*)
977 // This is somewhat of a hack, unfortunately. We cannot use
978 // set_v_offset() from within restore_settings() as the view
979 // at that point is neither visible nor properly sized.
980 // This is the least intrusive workaround I could come up
981 // with: set the vertical offset (or scroll defaults) when
982 // the view is visible and resized to its final size.
983 // Resize events that are sent when the view is not visible
984 // must be ignored as they have wrong sizes, potentially
985 // preventing the v offset from being set successfully.
988 size_finalized_ = true;
990 if (size_finalized_ && saved_v_offset_) {
991 set_v_offset(saved_v_offset_);
995 if (size_finalized_ && scroll_needs_defaults_)
996 set_scroll_default();
999 void View::row_item_appearance_changed(bool label, bool content)
1004 viewport_->update();
1007 void View::time_item_appearance_changed(bool label, bool content)
1012 viewport_->update();
1015 void View::extents_changed(bool horz, bool vert)
1018 (horz ? TraceTreeItemHExtentsChanged : 0) |
1019 (vert ? TraceTreeItemVExtentsChanged : 0);
1020 lazy_event_handler_.start();
1023 void View::h_scroll_value_changed(int value)
1025 if (updating_scroll_)
1028 // Disable sticky scrolling when user moves the horizontal scroll bar
1029 // during a running acquisition
1030 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1031 sticky_scrolling_ = false;
1032 sticky_scrolling_changed(false);
1035 const int range = scrollarea_.horizontalScrollBar()->maximum();
1036 if (range < MaxScrollValue)
1037 set_offset(scale_ * value);
1041 get_scroll_layout(length, offset);
1042 set_offset(scale_ * length * value / MaxScrollValue);
1046 viewport_->update();
1049 void View::v_scroll_value_changed()
1052 viewport_->update();
1055 void View::signals_changed()
1057 using sigrok::Channel;
1059 vector< shared_ptr<Channel> > channels;
1060 shared_ptr<sigrok::Device> sr_dev;
1062 // Do we need to set the vertical scrollbar to its default position later?
1063 // We do if there are no traces, i.e. the scroll bar has no range set
1064 bool reset_scrollbar =
1065 (scrollarea_.verticalScrollBar()->minimum() ==
1066 scrollarea_.verticalScrollBar()->maximum());
1068 if (!session_.device()) {
1072 sr_dev = session_.device()->device();
1074 channels = sr_dev->channels();
1077 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1079 // Make a list of traces that are being added, and a list of traces
1080 // that are being removed
1081 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1082 const set<shared_ptr<Trace>> prev_traces(
1083 prev_trace_list.begin(), prev_trace_list.end());
1085 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1087 #ifdef ENABLE_DECODE
1088 traces.insert(decode_traces_.begin(), decode_traces_.end());
1091 set< shared_ptr<Trace> > add_traces;
1092 set_difference(traces.begin(), traces.end(),
1093 prev_traces.begin(), prev_traces.end(),
1094 inserter(add_traces, add_traces.begin()));
1096 set< shared_ptr<Trace> > remove_traces;
1097 set_difference(prev_traces.begin(), prev_traces.end(),
1098 traces.begin(), traces.end(),
1099 inserter(remove_traces, remove_traces.begin()));
1101 // Make a look-up table of sigrok Channels to pulseview Signals
1102 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1104 for (const shared_ptr<Signal> &sig : signals_)
1105 signal_map[sig->base()] = sig;
1107 // Populate channel groups
1109 for (auto entry : sr_dev->channel_groups()) {
1110 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1112 if (group->channels().size() <= 1)
1115 // Find best trace group to add to
1116 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1119 // If there is no trace group, create one
1120 shared_ptr<TraceGroup> new_trace_group;
1122 new_trace_group.reset(new TraceGroup());
1123 owner = new_trace_group.get();
1126 // Extract traces for the trace group, removing them from
1128 const vector< shared_ptr<Trace> > new_traces_in_group =
1129 extract_new_traces_for_channels(group->channels(),
1130 signal_map, add_traces);
1132 // Add the traces to the group
1133 const pair<int, int> prev_v_extents = owner->v_extents();
1134 int offset = prev_v_extents.second - prev_v_extents.first;
1135 for (shared_ptr<Trace> trace : new_traces_in_group) {
1137 owner->add_child_item(trace);
1139 const pair<int, int> extents = trace->v_extents();
1140 if (trace->enabled())
1141 offset += -extents.first;
1142 trace->force_to_v_offset(offset);
1143 if (trace->enabled())
1144 offset += extents.second;
1147 if (new_trace_group) {
1148 // Assign proper vertical offsets to each channel in the group
1149 new_trace_group->restack_items();
1151 // If this is a new group, enqueue it in the new top level
1153 if (!new_traces_in_group.empty())
1154 new_top_level_items.push_back(new_trace_group);
1158 // Enqueue the remaining logic channels in a group
1159 vector< shared_ptr<Channel> > logic_channels;
1160 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1161 [](const shared_ptr<Channel>& c) {
1162 return c->type() == sigrok::ChannelType::LOGIC; });
1164 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1165 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1167 if (non_grouped_logic_signals.size() > 0) {
1168 const shared_ptr<TraceGroup> non_grouped_trace_group(
1169 make_shared<TraceGroup>());
1170 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1171 non_grouped_trace_group->add_child_item(trace);
1173 non_grouped_trace_group->restack_items();
1174 new_top_level_items.push_back(non_grouped_trace_group);
1177 // Enqueue the remaining channels as free ungrouped traces
1178 const vector< shared_ptr<Trace> > new_top_level_signals =
1179 extract_new_traces_for_channels(channels, signal_map, add_traces);
1180 new_top_level_items.insert(new_top_level_items.end(),
1181 new_top_level_signals.begin(), new_top_level_signals.end());
1183 // Enqueue any remaining traces i.e. decode traces
1184 new_top_level_items.insert(new_top_level_items.end(),
1185 add_traces.begin(), add_traces.end());
1187 // Remove any removed traces
1188 for (shared_ptr<Trace> trace : remove_traces) {
1189 TraceTreeItemOwner *const owner = trace->owner();
1191 owner->remove_child_item(trace);
1194 // Remove any empty trace groups
1195 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1196 if (group->child_items().size() == 0) {
1197 remove_child_item(group);
1201 // Add and position the pending top levels items
1202 int offset = v_extents().second;
1203 for (auto item : new_top_level_items) {
1204 add_child_item(item);
1206 // Position the item after the last item or at the top if there is none
1207 const pair<int, int> extents = item->v_extents();
1209 if (item->enabled())
1210 offset += -extents.first;
1212 item->force_to_v_offset(offset);
1214 if (item->enabled())
1215 offset += extents.second;
1221 viewport_->update();
1223 if (reset_scrollbar)
1224 set_scroll_default();
1227 void View::capture_state_updated(int state)
1229 if (state == Session::Running) {
1230 set_time_unit(util::TimeUnit::Samples);
1232 trigger_markers_.clear();
1234 // Activate "always zoom to fit" if the setting is enabled and we're
1235 // the main view of this session (other trace views may be used for
1236 // zooming and we don't want to mess them up)
1237 GlobalSettings settings;
1238 bool state = settings.value(GlobalSettings::Key_View_AlwaysZoomToFit).toBool();
1239 if (is_main_view_ && state) {
1240 always_zoom_to_fit_ = true;
1241 always_zoom_to_fit_changed(always_zoom_to_fit_);
1244 // Enable sticky scrolling if the setting is enabled
1245 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1248 if (state == Session::Stopped) {
1249 // After acquisition has stopped we need to re-calculate the ticks once
1250 // as it's otherwise done when the user pans or zooms, which is too late
1251 calculate_tick_spacing();
1253 // Reset "always zoom to fit", the acquisition has stopped
1254 if (always_zoom_to_fit_) {
1255 // Perform a final zoom-to-fit before disabling
1256 zoom_fit(always_zoom_to_fit_);
1257 always_zoom_to_fit_ = false;
1258 always_zoom_to_fit_changed(always_zoom_to_fit_);
1263 void View::data_updated()
1265 if (always_zoom_to_fit_ || sticky_scrolling_) {
1266 if (!delayed_view_updater_.isActive())
1267 delayed_view_updater_.start();
1269 determine_time_unit();
1272 viewport_->update();
1276 void View::perform_delayed_view_update()
1278 if (always_zoom_to_fit_) {
1280 } else if (sticky_scrolling_) {
1281 // Make right side of the view sticky
1284 get_scroll_layout(length, offset);
1286 const QSize areaSize = viewport_->size();
1287 length = max(length - areaSize.width(), 0.0);
1289 set_offset(scale_ * length);
1292 determine_time_unit();
1295 viewport_->update();
1298 void View::process_sticky_events()
1300 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1302 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1303 restack_all_trace_tree_items();
1307 // Clear the sticky events
1311 void View::on_hover_point_changed()
1313 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1314 list_by_type<TraceTreeItem>());
1315 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1316 r->hover_point_changed();
1319 } // namespace TraceView
1320 } // namespace views