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 <QHBoxLayout>
42 #include <QMouseEvent>
45 #include <libsigrokcxx/libsigrokcxx.hpp>
47 #include "analogsignal.hpp"
49 #include "logicsignal.hpp"
52 #include "tracegroup.hpp"
53 #include "triggermarker.hpp"
55 #include "viewport.hpp"
57 #include "pv/data/logic.hpp"
58 #include "pv/data/logicsegment.hpp"
59 #include "pv/devices/device.hpp"
60 #include "pv/globalsettings.hpp"
61 #include "pv/session.hpp"
62 #include "pv/util.hpp"
65 #include "decodetrace.hpp"
68 using pv::data::SignalData;
69 using pv::data::Segment;
70 using pv::util::TimeUnit;
71 using pv::util::Timestamp;
73 using std::back_inserter;
76 using std::dynamic_pointer_cast;
80 using std::make_shared;
84 using std::set_difference;
85 using std::shared_ptr;
86 using std::stringstream;
87 using std::unordered_map;
88 using std::unordered_set;
95 const Timestamp View::MaxScale("1e9");
96 const Timestamp View::MinScale("1e-12");
98 const int View::MaxScrollValue = INT_MAX / 2;
99 const int View::MaxViewAutoUpdateRate = 25; // No more than 25 Hz with sticky scrolling
101 const int View::ScaleUnits[3] = {1, 2, 5};
104 CustomAbstractScrollArea::CustomAbstractScrollArea(QWidget *parent) :
105 QAbstractScrollArea(parent)
109 void CustomAbstractScrollArea::setViewportMargins(int left, int top, int right, int bottom)
111 QAbstractScrollArea::setViewportMargins(left, top, right, bottom);
114 bool CustomAbstractScrollArea::viewportEvent(QEvent *event)
116 switch (event->type()) {
118 case QEvent::MouseButtonPress:
119 case QEvent::MouseButtonRelease:
120 case QEvent::MouseButtonDblClick:
121 case QEvent::MouseMove:
123 case QEvent::TouchBegin:
124 case QEvent::TouchUpdate:
125 case QEvent::TouchEnd:
128 return QAbstractScrollArea::viewportEvent(event);
132 View::View(Session &session, bool is_main_view, QWidget *parent) :
133 ViewBase(session, is_main_view, parent),
134 viewport_(new Viewport(*this)),
135 ruler_(new Ruler(*this)),
136 header_(new Header(*this)),
140 updating_scroll_(false),
141 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
142 always_zoom_to_fit_(false),
144 tick_prefix_(pv::util::SIPrefix::yocto),
146 time_unit_(util::TimeUnit::Time),
147 show_cursors_(false),
148 cursors_(new CursorPair(*this)),
149 next_flag_text_('A'),
151 hover_point_(-1, -1),
152 scroll_needs_defaults_(false),
154 size_finalized_(false)
156 GlobalSettings settings;
157 coloured_bg_ = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
159 connect(scrollarea_.horizontalScrollBar(), SIGNAL(valueChanged(int)),
160 this, SLOT(h_scroll_value_changed(int)));
161 connect(scrollarea_.verticalScrollBar(), SIGNAL(valueChanged(int)),
162 this, SLOT(v_scroll_value_changed()));
164 connect(header_, SIGNAL(selection_changed()),
165 ruler_, SLOT(clear_selection()));
166 connect(ruler_, SIGNAL(selection_changed()),
167 header_, SLOT(clear_selection()));
169 connect(header_, SIGNAL(selection_changed()),
170 this, SIGNAL(selection_changed()));
171 connect(ruler_, SIGNAL(selection_changed()),
172 this, SIGNAL(selection_changed()));
174 connect(this, SIGNAL(hover_point_changed()),
175 this, SLOT(on_hover_point_changed()));
177 connect(&lazy_event_handler_, SIGNAL(timeout()),
178 this, SLOT(process_sticky_events()));
179 lazy_event_handler_.setSingleShot(true);
181 connect(&delayed_view_updater_, SIGNAL(timeout()),
182 this, SLOT(perform_delayed_view_update()));
183 delayed_view_updater_.setSingleShot(true);
184 delayed_view_updater_.setInterval(1000 / MaxViewAutoUpdateRate);
186 /* To let the scroll area fill up the parent QWidget (this), we need a layout */
187 QHBoxLayout *layout = new QHBoxLayout(this);
189 layout->setContentsMargins(0, 0, 0, 0);
190 layout->addWidget(&scrollarea_);
192 scrollarea_.setViewport(viewport_);
194 viewport_->installEventFilter(this);
195 ruler_->installEventFilter(this);
196 header_->installEventFilter(this);
198 // Trigger the initial event manually. The default device has signals
199 // which were created before this object came into being
202 // make sure the transparent widgets are on the top
206 // Update the zoom state
207 calculate_tick_spacing();
210 Session& View::session()
215 const Session& View::session() const
220 unordered_set< shared_ptr<Signal> > View::signals() const
225 void View::clear_signals()
230 void View::add_signal(const shared_ptr<Signal> signal)
232 signals_.insert(signal);
236 void View::clear_decode_signals()
238 decode_traces_.clear();
241 void View::add_decode_signal(shared_ptr<data::SignalBase> signalbase)
243 shared_ptr<DecodeTrace> d(
244 new DecodeTrace(session_, signalbase, decode_traces_.size()));
245 decode_traces_.push_back(d);
248 void View::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
250 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
251 if ((*i)->base() == signalbase) {
252 decode_traces_.erase(i);
264 const View* View::view() const
269 Viewport* View::viewport()
274 const Viewport* View::viewport() const
279 void View::save_settings(QSettings &settings) const
281 settings.setValue("scale", scale_);
282 settings.setValue("v_offset",
283 scrollarea_.verticalScrollBar()->sliderPosition());
286 boost::archive::text_oarchive oa(ss);
287 oa << boost::serialization::make_nvp("offset", offset_);
288 settings.setValue("offset", QString::fromStdString(ss.str()));
290 for (shared_ptr<Signal> signal : signals_) {
291 settings.beginGroup(signal->base()->internal_name());
292 signal->save_settings(settings);
297 void View::restore_settings(QSettings &settings)
299 // Note: It is assumed that this function is only called once,
300 // immediately after restoring a previous session.
302 if (settings.contains("scale"))
303 set_scale(settings.value("scale").toDouble());
305 if (settings.contains("offset")) {
306 util::Timestamp offset;
308 ss << settings.value("offset").toString().toStdString();
310 boost::archive::text_iarchive ia(ss);
311 ia >> boost::serialization::make_nvp("offset", offset);
316 for (shared_ptr<Signal> signal : signals_) {
317 settings.beginGroup(signal->base()->internal_name());
318 signal->restore_settings(settings);
322 if (settings.contains("v_offset")) {
323 saved_v_offset_ = settings.value("v_offset").toInt();
324 set_v_offset(saved_v_offset_);
325 scroll_needs_defaults_ = false;
326 // Note: see resizeEvent() for additional information
330 vector< shared_ptr<TimeItem> > View::time_items() const
332 const vector<shared_ptr<Flag>> f(flags());
333 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
334 items.push_back(cursors_);
335 items.push_back(cursors_->first());
336 items.push_back(cursors_->second());
338 for (auto trigger_marker : trigger_markers_)
339 items.push_back(trigger_marker);
344 double View::scale() const
349 void View::set_scale(double scale)
351 if (scale_ != scale) {
353 Q_EMIT scale_changed();
357 const Timestamp& View::offset() const
362 void View::set_offset(const pv::util::Timestamp& offset)
364 if (offset_ != offset) {
366 Q_EMIT offset_changed();
370 int View::owner_visual_v_offset() const
372 return -scrollarea_.verticalScrollBar()->sliderPosition();
375 void View::set_v_offset(int offset)
377 scrollarea_.verticalScrollBar()->setSliderPosition(offset);
382 unsigned int View::depth() const
387 pv::util::SIPrefix View::tick_prefix() const
392 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
394 if (tick_prefix_ != tick_prefix) {
395 tick_prefix_ = tick_prefix;
396 Q_EMIT tick_prefix_changed();
400 unsigned int View::tick_precision() const
402 return tick_precision_;
405 void View::set_tick_precision(unsigned tick_precision)
407 if (tick_precision_ != tick_precision) {
408 tick_precision_ = tick_precision;
409 Q_EMIT tick_precision_changed();
413 const pv::util::Timestamp& View::tick_period() const
418 void View::set_tick_period(const pv::util::Timestamp& tick_period)
420 if (tick_period_ != tick_period) {
421 tick_period_ = tick_period;
422 Q_EMIT tick_period_changed();
426 TimeUnit View::time_unit() const
431 void View::set_time_unit(pv::util::TimeUnit time_unit)
433 if (time_unit_ != time_unit) {
434 time_unit_ = time_unit;
435 Q_EMIT time_unit_changed();
439 void View::zoom(double steps)
441 zoom(steps, viewport_->width() / 2);
444 void View::zoom(double steps, int offset)
446 set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
449 void View::zoom_fit(bool gui_state)
451 // Act as one-shot when stopped, toggle along with the GUI otherwise
452 if (session_.get_capture_state() == Session::Stopped) {
453 always_zoom_to_fit_ = false;
454 always_zoom_to_fit_changed(false);
456 always_zoom_to_fit_ = gui_state;
457 always_zoom_to_fit_changed(gui_state);
460 const pair<Timestamp, Timestamp> extents = get_time_extents();
461 const Timestamp delta = extents.second - extents.first;
462 if (delta < Timestamp("1e-12"))
466 const int w = viewport_->width();
470 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
471 set_scale_offset(scale.convert_to<double>(), extents.first);
474 void View::zoom_one_to_one()
476 using pv::data::SignalData;
478 // Make a set of all the visible data objects
479 set< shared_ptr<SignalData> > visible_data = get_visible_data();
480 if (visible_data.empty())
484 const int w = viewport_->width();
488 set_zoom(1.0 / session_.get_samplerate(), w / 2);
491 void View::set_scale_offset(double scale, const Timestamp& offset)
493 // Disable sticky scrolling / always zoom to fit when acquisition runs
494 // and user drags the viewport
495 if ((scale_ == scale) && (offset_ != offset) &&
496 (session_.get_capture_state() == Session::Running)) {
498 if (sticky_scrolling_) {
499 sticky_scrolling_ = false;
500 sticky_scrolling_changed(false);
503 if (always_zoom_to_fit_) {
504 always_zoom_to_fit_ = false;
505 always_zoom_to_fit_changed(false);
512 calculate_tick_spacing();
519 set< shared_ptr<SignalData> > View::get_visible_data() const
521 // Make a set of all the visible data objects
522 set< shared_ptr<SignalData> > visible_data;
523 for (const shared_ptr<Signal> sig : signals_)
525 visible_data.insert(sig->data());
530 pair<Timestamp, Timestamp> View::get_time_extents() const
532 boost::optional<Timestamp> left_time, right_time;
533 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
534 for (const shared_ptr<SignalData> d : visible_data) {
535 const vector< shared_ptr<Segment> > segments = d->segments();
536 for (const shared_ptr<Segment> &s : segments) {
537 double samplerate = s->samplerate();
538 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
540 const Timestamp start_time = s->start_time();
541 left_time = left_time ?
542 min(*left_time, start_time) :
544 right_time = right_time ?
545 max(*right_time, start_time + d->max_sample_count() / samplerate) :
546 start_time + d->max_sample_count() / samplerate;
550 if (!left_time || !right_time)
551 return make_pair(0, 0);
553 assert(*left_time < *right_time);
554 return make_pair(*left_time, *right_time);
557 void View::enable_show_sampling_points(bool state)
564 void View::enable_show_analog_minor_grid(bool state)
571 void View::enable_coloured_bg(bool state)
573 const vector<shared_ptr<TraceTreeItem>> items(
574 list_by_type<TraceTreeItem>());
576 for (shared_ptr<TraceTreeItem> i : items) {
577 // Can't cast to Trace because it's abstract, so we need to
578 // check for any derived classes individually
580 shared_ptr<AnalogSignal> a = dynamic_pointer_cast<AnalogSignal>(i);
582 a->set_coloured_bg(state);
584 shared_ptr<LogicSignal> l = dynamic_pointer_cast<LogicSignal>(i);
586 l->set_coloured_bg(state);
589 shared_ptr<DecodeTrace> d = dynamic_pointer_cast<DecodeTrace>(i);
591 d->set_coloured_bg(state);
598 bool View::cursors_shown() const
600 return show_cursors_;
603 void View::show_cursors(bool show)
605 show_cursors_ = show;
610 void View::centre_cursors()
612 const double time_width = scale_ * viewport_->width();
613 cursors_->first()->set_time(offset_ + time_width * 0.4);
614 cursors_->second()->set_time(offset_ + time_width * 0.6);
619 shared_ptr<CursorPair> View::cursors() const
624 void View::add_flag(const Timestamp& time)
626 flags_.push_back(make_shared<Flag>(*this, time,
627 QString("%1").arg(next_flag_text_)));
629 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
630 (next_flag_text_ + 1);
632 time_item_appearance_changed(true, true);
635 void View::remove_flag(shared_ptr<Flag> flag)
638 time_item_appearance_changed(true, true);
641 vector< shared_ptr<Flag> > View::flags() const
643 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
644 stable_sort(flags.begin(), flags.end(),
645 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
646 return a->time() < b->time();
652 const QPoint& View::hover_point() const
657 void View::restack_all_trace_tree_items()
659 // Make a list of owners that is sorted from deepest first
660 const vector<shared_ptr<TraceTreeItem>> items(
661 list_by_type<TraceTreeItem>());
662 set< TraceTreeItemOwner* > owners;
663 for (const auto &r : items)
664 owners.insert(r->owner());
665 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
666 sort(sorted_owners.begin(), sorted_owners.end(),
667 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
668 return a->depth() > b->depth(); });
670 // Restack the items recursively
671 for (auto &o : sorted_owners)
674 // Re-assign background colors
675 bool next_bgcolour_state = false;
677 for (auto &o : sorted_owners)
678 next_bgcolour_state = o->reassign_bgcolour_states(next_bgcolour_state);
680 // Animate the items to their destination
681 for (const auto &i : items)
682 i->animate_to_layout_v_offset();
685 void View::trigger_event(util::Timestamp location)
687 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
690 void View::get_scroll_layout(double &length, Timestamp &offset) const
692 const pair<Timestamp, Timestamp> extents = get_time_extents();
693 length = ((extents.second - extents.first) / scale_).convert_to<double>();
694 offset = offset_ / scale_;
697 void View::set_zoom(double scale, int offset)
699 // Reset the "always zoom to fit" feature as the user changed the zoom
700 always_zoom_to_fit_ = false;
701 always_zoom_to_fit_changed(false);
703 const Timestamp cursor_offset = offset_ + scale_ * offset;
704 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
705 const Timestamp new_offset = cursor_offset - new_scale * offset;
706 set_scale_offset(new_scale.convert_to<double>(), new_offset);
709 void View::calculate_tick_spacing()
711 const double SpacingIncrement = 10.0f;
712 const double MinValueSpacing = 40.0f;
714 // Figure out the highest numeric value visible on a label
715 const QSize areaSize = viewport_->size();
716 const Timestamp max_time = max(fabs(offset_),
717 fabs(offset_ + scale_ * areaSize.width()));
719 double min_width = SpacingIncrement;
720 double label_width, tick_period_width;
722 QFontMetrics m(QApplication::font());
724 // Copies of the member variables with the same name, used in the calculation
725 // and written back afterwards, so that we don't emit signals all the time
726 // during the calculation.
727 pv::util::Timestamp tick_period = tick_period_;
728 pv::util::SIPrefix tick_prefix = tick_prefix_;
729 unsigned tick_precision = tick_precision_;
732 const double min_period = scale_ * min_width;
734 const int order = (int)floorf(log10f(min_period));
735 const pv::util::Timestamp order_decimal =
736 pow(pv::util::Timestamp(10), order);
738 // Allow for a margin of error so that a scale unit of 1 can be used.
739 // Otherwise, for a SU of 1 the tick period will almost always be below
740 // the min_period by a small amount - and thus skipped in favor of 2.
741 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
742 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
743 double tp_with_margin;
744 unsigned int unit = 0;
747 tp_with_margin = order_decimal.convert_to<double>() *
748 (ScaleUnits[unit++] + tp_margin);
749 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
751 tick_period = order_decimal * ScaleUnits[unit - 1];
752 tick_prefix = static_cast<pv::util::SIPrefix>(
753 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
755 // Precision is the number of fractional digits required, not
756 // taking the prefix into account (and it must never be negative)
757 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
759 tick_period_width = (tick_period / scale_).convert_to<double>();
761 const QString label_text = Ruler::format_time_with_distance(
762 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
764 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
765 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
768 min_width += SpacingIncrement;
769 } while (tick_period_width < label_width);
771 set_tick_period(tick_period);
772 set_tick_prefix(tick_prefix);
773 set_tick_precision(tick_precision);
776 void View::update_scroll()
779 QScrollBar *hscrollbar = scrollarea_.horizontalScrollBar();
780 QScrollBar *vscrollbar = scrollarea_.verticalScrollBar();
782 const QSize areaSize = viewport_->size();
784 // Set the horizontal scroll bar
787 get_scroll_layout(length, offset);
788 length = max(length - areaSize.width(), 0.0);
790 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
792 hscrollbar->setPageStep(areaSize.width() / 2);
793 hscrollbar->setSingleStep(major_tick_distance);
795 updating_scroll_ = true;
797 if (length < MaxScrollValue) {
798 hscrollbar->setRange(0, length);
799 hscrollbar->setSliderPosition(offset.convert_to<double>());
801 hscrollbar->setRange(0, MaxScrollValue);
802 hscrollbar->setSliderPosition(
803 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
806 updating_scroll_ = false;
808 // Set the vertical scrollbar
809 vscrollbar->setPageStep(areaSize.height());
810 vscrollbar->setSingleStep(areaSize.height() / 8);
812 const pair<int, int> extents = v_extents();
814 // Don't change the scrollbar range if there are no traces
815 if (extents.first != extents.second)
816 vscrollbar->setRange(extents.first - areaSize.height(),
819 if (scroll_needs_defaults_)
820 set_scroll_default();
823 void View::reset_scroll()
825 scrollarea_.verticalScrollBar()->setRange(0, 0);
828 void View::set_scroll_default()
832 const QSize areaSize = viewport_->size();
834 const pair<int, int> extents = v_extents();
835 const int trace_height = extents.second - extents.first;
837 // Do all traces fit in the view?
838 if (areaSize.height() >= trace_height)
839 // Center all traces vertically
840 set_v_offset(extents.first -
841 ((areaSize.height() - trace_height) / 2));
843 // Put the first trace at the top, letting the bottom ones overflow
844 set_v_offset(extents.first);
846 // If we're not sure whether setting the defaults worked as
847 // the window wasn't set up entirely yet, we want to be called
848 // again later to make sure
849 scroll_needs_defaults_ = !size_finalized_;
852 void View::update_layout()
854 scrollarea_.setViewportMargins(
855 header_->sizeHint().width() - Header::BaselineOffset,
856 ruler_->sizeHint().height(), 0, 0);
857 ruler_->setGeometry(viewport_->x(), 0,
858 viewport_->width(), ruler_->extended_size_hint().height());
859 header_->setGeometry(0, viewport_->y(),
860 header_->extended_size_hint().width(), viewport_->height());
864 TraceTreeItemOwner* View::find_prevalent_trace_group(
865 const shared_ptr<sigrok::ChannelGroup> &group,
866 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
871 unordered_set<TraceTreeItemOwner*> owners;
872 vector<TraceTreeItemOwner*> owner_list;
874 // Make a set and a list of all the owners
875 for (const auto &channel : group->channels()) {
876 for (auto entry : signal_map) {
877 if (entry.first->channel() == channel) {
878 TraceTreeItemOwner *const o = (entry.second)->owner();
879 owner_list.push_back(o);
885 // Iterate through the list of owners, and find the most prevalent
886 size_t max_prevalence = 0;
887 TraceTreeItemOwner *prevalent_owner = nullptr;
888 for (TraceTreeItemOwner *owner : owners) {
889 const size_t prevalence = count_if(
890 owner_list.begin(), owner_list.end(),
891 [&](TraceTreeItemOwner *o) { return o == owner; });
892 if (prevalence > max_prevalence) {
893 max_prevalence = prevalence;
894 prevalent_owner = owner;
898 return prevalent_owner;
901 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
902 const vector< shared_ptr<sigrok::Channel> > &channels,
903 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
905 set< shared_ptr<Trace> > &add_list)
907 vector< shared_ptr<Trace> > filtered_traces;
909 for (const auto &channel : channels) {
910 for (auto entry : signal_map) {
911 if (entry.first->channel() == channel) {
912 shared_ptr<Trace> trace = entry.second;
913 const auto list_iter = add_list.find(trace);
914 if (list_iter == add_list.end())
917 filtered_traces.push_back(trace);
918 add_list.erase(list_iter);
923 return filtered_traces;
926 void View::determine_time_unit()
928 // Check whether we know the sample rate and hence can use time as the unit
929 if (time_unit_ == util::TimeUnit::Samples) {
930 // Check all signals but...
931 for (const shared_ptr<Signal> signal : signals_) {
932 const shared_ptr<SignalData> data = signal->data();
934 // ...only check first segment of each
935 const vector< shared_ptr<Segment> > segments = data->segments();
936 if (!segments.empty())
937 if (segments[0]->samplerate()) {
938 set_time_unit(util::TimeUnit::Time);
945 bool View::eventFilter(QObject *object, QEvent *event)
947 const QEvent::Type type = event->type();
948 if (type == QEvent::MouseMove) {
950 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
951 if (object == viewport_)
952 hover_point_ = mouse_event->pos();
953 else if (object == ruler_)
954 hover_point_ = QPoint(mouse_event->x(), 0);
955 else if (object == header_)
956 hover_point_ = QPoint(0, mouse_event->y());
958 hover_point_ = QPoint(-1, -1);
960 hover_point_changed();
962 } else if (type == QEvent::Leave) {
963 hover_point_ = QPoint(-1, -1);
964 hover_point_changed();
967 return QObject::eventFilter(object, event);
970 void View::resizeEvent(QResizeEvent*)
974 // This is somewhat of a hack, unfortunately. We cannot use
975 // set_v_offset() from within restore_settings() as the view
976 // at that point is neither visible nor properly sized.
977 // This is the least intrusive workaround I could come up
978 // with: set the vertical offset (or scroll defaults) when
979 // the view is visible and resized to its final size.
980 // Resize events that are sent when the view is not visible
981 // must be ignored as they have wrong sizes, potentially
982 // preventing the v offset from being set successfully.
985 size_finalized_ = true;
987 if (size_finalized_ && saved_v_offset_) {
988 set_v_offset(saved_v_offset_);
992 if (size_finalized_ && scroll_needs_defaults_)
993 set_scroll_default();
996 void View::row_item_appearance_changed(bool label, bool content)
1001 viewport_->update();
1004 void View::time_item_appearance_changed(bool label, bool content)
1009 viewport_->update();
1012 void View::extents_changed(bool horz, bool vert)
1015 (horz ? TraceTreeItemHExtentsChanged : 0) |
1016 (vert ? TraceTreeItemVExtentsChanged : 0);
1017 lazy_event_handler_.start();
1020 void View::h_scroll_value_changed(int value)
1022 if (updating_scroll_)
1025 // Disable sticky scrolling when user moves the horizontal scroll bar
1026 // during a running acquisition
1027 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1028 sticky_scrolling_ = false;
1029 sticky_scrolling_changed(false);
1032 const int range = scrollarea_.horizontalScrollBar()->maximum();
1033 if (range < MaxScrollValue)
1034 set_offset(scale_ * value);
1038 get_scroll_layout(length, offset);
1039 set_offset(scale_ * length * value / MaxScrollValue);
1043 viewport_->update();
1046 void View::v_scroll_value_changed()
1049 viewport_->update();
1052 void View::signals_changed()
1054 using sigrok::Channel;
1056 vector< shared_ptr<Channel> > channels;
1057 shared_ptr<sigrok::Device> sr_dev;
1059 // Do we need to set the vertical scrollbar to its default position later?
1060 // We do if there are no traces, i.e. the scroll bar has no range set
1061 bool reset_scrollbar =
1062 (scrollarea_.verticalScrollBar()->minimum() ==
1063 scrollarea_.verticalScrollBar()->maximum());
1065 if (!session_.device()) {
1069 sr_dev = session_.device()->device();
1071 channels = sr_dev->channels();
1074 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1076 // Make a list of traces that are being added, and a list of traces
1077 // that are being removed
1078 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1079 const set<shared_ptr<Trace>> prev_traces(
1080 prev_trace_list.begin(), prev_trace_list.end());
1082 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1084 #ifdef ENABLE_DECODE
1085 traces.insert(decode_traces_.begin(), decode_traces_.end());
1088 set< shared_ptr<Trace> > add_traces;
1089 set_difference(traces.begin(), traces.end(),
1090 prev_traces.begin(), prev_traces.end(),
1091 inserter(add_traces, add_traces.begin()));
1093 set< shared_ptr<Trace> > remove_traces;
1094 set_difference(prev_traces.begin(), prev_traces.end(),
1095 traces.begin(), traces.end(),
1096 inserter(remove_traces, remove_traces.begin()));
1098 // Make a look-up table of sigrok Channels to pulseview Signals
1099 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1101 for (const shared_ptr<Signal> &sig : signals_)
1102 signal_map[sig->base()] = sig;
1104 // Populate channel groups
1106 for (auto entry : sr_dev->channel_groups()) {
1107 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1109 if (group->channels().size() <= 1)
1112 // Find best trace group to add to
1113 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1116 // If there is no trace group, create one
1117 shared_ptr<TraceGroup> new_trace_group;
1119 new_trace_group.reset(new TraceGroup());
1120 owner = new_trace_group.get();
1123 // Extract traces for the trace group, removing them from
1125 const vector< shared_ptr<Trace> > new_traces_in_group =
1126 extract_new_traces_for_channels(group->channels(),
1127 signal_map, add_traces);
1129 // Add the traces to the group
1130 const pair<int, int> prev_v_extents = owner->v_extents();
1131 int offset = prev_v_extents.second - prev_v_extents.first;
1132 for (shared_ptr<Trace> trace : new_traces_in_group) {
1134 owner->add_child_item(trace);
1136 const pair<int, int> extents = trace->v_extents();
1137 if (trace->enabled())
1138 offset += -extents.first;
1139 trace->force_to_v_offset(offset);
1140 if (trace->enabled())
1141 offset += extents.second;
1144 if (new_trace_group) {
1145 // Assign proper vertical offsets to each channel in the group
1146 new_trace_group->restack_items();
1148 // If this is a new group, enqueue it in the new top level
1150 if (!new_traces_in_group.empty())
1151 new_top_level_items.push_back(new_trace_group);
1155 // Enqueue the remaining logic channels in a group
1156 vector< shared_ptr<Channel> > logic_channels;
1157 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1158 [](const shared_ptr<Channel>& c) {
1159 return c->type() == sigrok::ChannelType::LOGIC; });
1161 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1162 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1164 if (non_grouped_logic_signals.size() > 0) {
1165 const shared_ptr<TraceGroup> non_grouped_trace_group(
1166 make_shared<TraceGroup>());
1167 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1168 non_grouped_trace_group->add_child_item(trace);
1170 non_grouped_trace_group->restack_items();
1171 new_top_level_items.push_back(non_grouped_trace_group);
1174 // Enqueue the remaining channels as free ungrouped traces
1175 const vector< shared_ptr<Trace> > new_top_level_signals =
1176 extract_new_traces_for_channels(channels, signal_map, add_traces);
1177 new_top_level_items.insert(new_top_level_items.end(),
1178 new_top_level_signals.begin(), new_top_level_signals.end());
1180 // Enqueue any remaining traces i.e. decode traces
1181 new_top_level_items.insert(new_top_level_items.end(),
1182 add_traces.begin(), add_traces.end());
1184 // Remove any removed traces
1185 for (shared_ptr<Trace> trace : remove_traces) {
1186 TraceTreeItemOwner *const owner = trace->owner();
1188 owner->remove_child_item(trace);
1191 // Remove any empty trace groups
1192 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1193 if (group->child_items().size() == 0) {
1194 remove_child_item(group);
1198 // Add and position the pending top levels items
1199 int offset = v_extents().second;
1200 for (auto item : new_top_level_items) {
1201 add_child_item(item);
1203 // Position the item after the last item or at the top if there is none
1204 const pair<int, int> extents = item->v_extents();
1206 if (item->enabled())
1207 offset += -extents.first;
1209 item->force_to_v_offset(offset);
1211 if (item->enabled())
1212 offset += extents.second;
1218 viewport_->update();
1220 if (reset_scrollbar)
1221 set_scroll_default();
1224 void View::capture_state_updated(int state)
1226 if (state == Session::Running) {
1227 set_time_unit(util::TimeUnit::Samples);
1229 trigger_markers_.clear();
1231 // Activate "always zoom to fit" if the setting is enabled and we're
1232 // the main view of this session (other trace views may be used for
1233 // zooming and we don't want to mess them up)
1234 GlobalSettings settings;
1235 bool state = settings.value(GlobalSettings::Key_View_AlwaysZoomToFit).toBool();
1236 if (is_main_view_ && state) {
1237 always_zoom_to_fit_ = true;
1238 always_zoom_to_fit_changed(always_zoom_to_fit_);
1241 // Enable sticky scrolling if the setting is enabled
1242 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1245 if (state == Session::Stopped) {
1246 // After acquisition has stopped we need to re-calculate the ticks once
1247 // as it's otherwise done when the user pans or zooms, which is too late
1248 calculate_tick_spacing();
1250 // Reset "always zoom to fit", the acquisition has stopped
1251 if (always_zoom_to_fit_) {
1252 // Perform a final zoom-to-fit before disabling
1253 zoom_fit(always_zoom_to_fit_);
1254 always_zoom_to_fit_ = false;
1255 always_zoom_to_fit_changed(always_zoom_to_fit_);
1260 void View::data_updated()
1262 if (always_zoom_to_fit_ || sticky_scrolling_) {
1263 if (!delayed_view_updater_.isActive())
1264 delayed_view_updater_.start();
1266 determine_time_unit();
1269 viewport_->update();
1273 void View::perform_delayed_view_update()
1275 if (always_zoom_to_fit_) {
1277 } else if (sticky_scrolling_) {
1278 // Make right side of the view sticky
1281 get_scroll_layout(length, offset);
1283 const QSize areaSize = viewport_->size();
1284 length = max(length - areaSize.width(), 0.0);
1286 set_offset(scale_ * length);
1289 determine_time_unit();
1292 viewport_->update();
1295 void View::process_sticky_events()
1297 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1299 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1300 restack_all_trace_tree_items();
1304 // Clear the sticky events
1308 void View::on_hover_point_changed()
1310 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1311 list_by_type<TraceTreeItem>());
1312 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1313 r->hover_point_changed();
1316 } // namespace TraceView
1317 } // namespace views