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),
133 updating_scroll_(false),
134 settings_restored_(false),
135 header_was_shrunk_(false),
136 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
137 always_zoom_to_fit_(false),
139 tick_prefix_(pv::util::SIPrefix::yocto),
141 time_unit_(util::TimeUnit::Time),
142 show_cursors_(false),
143 cursors_(new CursorPair(*this)),
144 next_flag_text_('A'),
146 hover_point_(-1, -1),
147 scroll_needs_defaults_(true),
149 scale_at_acq_start_(0),
150 offset_at_acq_start_(0),
151 suppress_zoom_to_fit_after_acq_(false)
153 QVBoxLayout *root_layout = new QVBoxLayout(this);
154 root_layout->setContentsMargins(0, 0, 0, 0);
155 root_layout->addWidget(splitter_);
157 viewport_ = new Viewport(*this);
158 scrollarea_ = new CustomScrollArea(splitter_);
159 scrollarea_->setViewport(viewport_);
160 scrollarea_->setFrameShape(QFrame::NoFrame);
162 ruler_ = new Ruler(*this);
164 header_ = new Header(*this);
165 header_->setMinimumWidth(10); // So that the arrow tips show at least
167 // We put the header into a simple layout so that we can add the top margin,
168 // allowing us to make it line up with the bottom of the ruler
169 QWidget *header_container = new QWidget();
170 header_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
171 QVBoxLayout *header_layout = new QVBoxLayout(header_container);
172 header_layout->setContentsMargins(0, ruler_->sizeHint().height(), 0, 0);
173 header_layout->addWidget(header_);
175 // To let the ruler and scrollarea be on the same split pane, we need a layout
176 QWidget *trace_container = new QWidget();
177 trace_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
178 QVBoxLayout *trace_layout = new QVBoxLayout(trace_container);
179 trace_layout->setSpacing(0); // We don't want space between the ruler and scrollarea
180 trace_layout->setContentsMargins(0, 0, 0, 0);
181 trace_layout->addWidget(ruler_);
182 trace_layout->addWidget(scrollarea_);
184 splitter_->addWidget(header_container);
185 splitter_->addWidget(trace_container);
186 splitter_->setHandleWidth(1); // Don't show a visible rubber band
187 splitter_->setCollapsible(0, false); // Prevent the header from collapsing
188 splitter_->setCollapsible(1, false); // Prevent the traces from collapsing
189 splitter_->setStretchFactor(0, 0); // Prevent the panes from being resized
190 splitter_->setStretchFactor(1, 1); // when the entire view is resized
191 splitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
193 viewport_->installEventFilter(this);
194 ruler_->installEventFilter(this);
195 header_->installEventFilter(this);
197 // Set up settings and event handlers
198 GlobalSettings settings;
199 colored_bg_ = settings.value(GlobalSettings::Key_View_ColoredBG).toBool();
201 GlobalSettings::add_change_handler(this);
203 connect(scrollarea_->horizontalScrollBar(), SIGNAL(valueChanged(int)),
204 this, SLOT(h_scroll_value_changed(int)));
205 connect(scrollarea_->verticalScrollBar(), SIGNAL(valueChanged(int)),
206 this, SLOT(v_scroll_value_changed()));
208 connect(header_, SIGNAL(selection_changed()),
209 ruler_, SLOT(clear_selection()));
210 connect(ruler_, SIGNAL(selection_changed()),
211 header_, SLOT(clear_selection()));
213 connect(header_, SIGNAL(selection_changed()),
214 this, SIGNAL(selection_changed()));
215 connect(ruler_, SIGNAL(selection_changed()),
216 this, SIGNAL(selection_changed()));
218 connect(splitter_, SIGNAL(splitterMoved(int, int)),
219 this, SLOT(on_splitter_moved()));
221 connect(&lazy_event_handler_, SIGNAL(timeout()),
222 this, SLOT(process_sticky_events()));
223 lazy_event_handler_.setSingleShot(true);
225 // Trigger the initial event manually. The default device has signals
226 // which were created before this object came into being
229 // make sure the transparent widgets are on the top
233 // Update the zoom state
234 calculate_tick_spacing();
236 // Make sure the standard bar's segment selector is in sync
237 set_segment_display_mode(segment_display_mode_);
242 GlobalSettings::remove_change_handler(this);
245 Session& View::session()
250 const Session& View::session() const
255 unordered_set< shared_ptr<Signal> > View::signals() const
260 void View::clear_signals()
262 ViewBase::clear_signalbases();
266 void View::add_signal(const shared_ptr<Signal> signal)
268 ViewBase::add_signalbase(signal->base());
269 signals_.insert(signal);
271 signal->set_segment_display_mode(segment_display_mode_);
272 signal->set_current_segment(current_segment_);
274 connect(signal->base().get(), SIGNAL(name_changed(const QString&)),
275 this, SLOT(on_signal_name_changed()));
279 void View::clear_decode_signals()
281 decode_traces_.clear();
284 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
286 shared_ptr<DecodeTrace> d(
287 new DecodeTrace(session_, signal, decode_traces_.size()));
288 decode_traces_.push_back(d);
290 d->set_segment_display_mode(segment_display_mode_);
291 d->set_current_segment(current_segment_);
293 connect(signal.get(), SIGNAL(name_changed(const QString&)),
294 this, SLOT(on_signal_name_changed()));
297 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
299 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
300 if ((*i)->base() == signal) {
301 decode_traces_.erase(i);
313 const View* View::view() const
318 Viewport* View::viewport()
323 const Viewport* View::viewport() const
328 void View::save_settings(QSettings &settings) const
330 settings.setValue("scale", scale_);
331 settings.setValue("v_offset",
332 scrollarea_->verticalScrollBar()->sliderPosition());
334 settings.setValue("splitter_state", splitter_->saveState());
335 settings.setValue("segment_display_mode", segment_display_mode_);
339 boost::archive::text_oarchive oa(ss);
340 oa << boost::serialization::make_nvp("ruler_shift", ruler_shift_);
341 settings.setValue("ruler_shift", QString::fromStdString(ss.str()));
345 boost::archive::text_oarchive oa(ss);
346 oa << boost::serialization::make_nvp("offset", offset_);
347 settings.setValue("offset", QString::fromStdString(ss.str()));
350 for (shared_ptr<Signal> signal : signals_) {
351 settings.beginGroup(signal->base()->internal_name());
352 signal->save_settings(settings);
357 void View::restore_settings(QSettings &settings)
359 // Note: It is assumed that this function is only called once,
360 // immediately after restoring a previous session.
362 if (settings.contains("scale"))
363 set_scale(settings.value("scale").toDouble());
365 if (settings.contains("ruler_shift")) {
366 util::Timestamp shift;
368 ss << settings.value("ruler_shift").toString().toStdString();
370 boost::archive::text_iarchive ia(ss);
371 ia >> boost::serialization::make_nvp("ruler_shift", shift);
373 ruler_shift_ = shift;
376 if (settings.contains("offset")) {
377 util::Timestamp offset;
379 ss << settings.value("offset").toString().toStdString();
381 boost::archive::text_iarchive ia(ss);
382 ia >> boost::serialization::make_nvp("offset", offset);
384 // This also updates ruler_offset_
388 if (settings.contains("splitter_state"))
389 splitter_->restoreState(settings.value("splitter_state").toByteArray());
391 if (settings.contains("segment_display_mode"))
392 set_segment_display_mode(
393 (Trace::SegmentDisplayMode)(settings.value("segment_display_mode").toInt()));
395 for (shared_ptr<Signal> signal : signals_) {
396 settings.beginGroup(signal->base()->internal_name());
397 signal->restore_settings(settings);
401 if (settings.contains("v_offset")) {
402 saved_v_offset_ = settings.value("v_offset").toInt();
403 set_v_offset(saved_v_offset_);
404 scroll_needs_defaults_ = false;
405 // Note: see eventFilter() for additional information
408 settings_restored_ = true;
409 suppress_zoom_to_fit_after_acq_ = true;
411 // Update the ruler so that it uses the new scale
412 calculate_tick_spacing();
415 vector< shared_ptr<TimeItem> > View::time_items() const
417 const vector<shared_ptr<Flag>> f(flags());
418 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
419 items.push_back(cursors_);
420 items.push_back(cursors_->first());
421 items.push_back(cursors_->second());
423 for (auto trigger_marker : trigger_markers_)
424 items.push_back(trigger_marker);
429 double View::scale() const
434 void View::set_scale(double scale)
436 if (scale_ != scale) {
442 void View::set_offset(const pv::util::Timestamp& offset, bool force_update)
444 if ((offset_ != offset) || force_update) {
446 ruler_offset_ = offset_ + ruler_shift_;
451 const Timestamp& View::offset() const
456 const Timestamp& View::ruler_offset() const
458 return ruler_offset_;
461 void View::set_zero_position(pv::util::Timestamp& position)
463 ruler_shift_ = -position;
465 // Force an immediate update of the offsets
466 set_offset(offset_, true);
470 void View::reset_zero_position()
474 // Force an immediate update of the offsets
475 set_offset(offset_, true);
479 int View::owner_visual_v_offset() const
481 return -scrollarea_->verticalScrollBar()->sliderPosition();
484 void View::set_v_offset(int offset)
486 scrollarea_->verticalScrollBar()->setSliderPosition(offset);
491 unsigned int View::depth() const
496 uint32_t View::current_segment() const
498 return current_segment_;
501 pv::util::SIPrefix View::tick_prefix() const
506 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
508 if (tick_prefix_ != tick_prefix) {
509 tick_prefix_ = tick_prefix;
510 tick_prefix_changed();
514 unsigned int View::tick_precision() const
516 return tick_precision_;
519 void View::set_tick_precision(unsigned tick_precision)
521 if (tick_precision_ != tick_precision) {
522 tick_precision_ = tick_precision;
523 tick_precision_changed();
527 const pv::util::Timestamp& View::tick_period() const
532 unsigned int View::minor_tick_count() const
534 return minor_tick_count_;
537 void View::set_tick_period(const pv::util::Timestamp& tick_period)
539 if (tick_period_ != tick_period) {
540 tick_period_ = tick_period;
541 tick_period_changed();
545 TimeUnit View::time_unit() const
550 void View::set_time_unit(pv::util::TimeUnit time_unit)
552 if (time_unit_ != time_unit) {
553 time_unit_ = time_unit;
558 void View::set_current_segment(uint32_t segment_id)
560 current_segment_ = segment_id;
562 for (shared_ptr<Signal> signal : signals_)
563 signal->set_current_segment(current_segment_);
565 for (shared_ptr<DecodeTrace> dt : decode_traces_)
566 dt->set_current_segment(current_segment_);
569 vector<util::Timestamp> triggers = session_.get_triggers(current_segment_);
571 trigger_markers_.clear();
572 for (util::Timestamp timestamp : triggers)
573 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, timestamp));
575 // When enabled, the first trigger for this segment is used as the zero position
576 GlobalSettings settings;
577 bool trigger_is_zero_time = settings.value(GlobalSettings::Key_View_TriggerIsZeroTime).toBool();
579 if (trigger_is_zero_time && (triggers.size() > 0))
580 set_zero_position(triggers.front());
584 segment_changed(segment_id);
587 bool View::segment_is_selectable() const
589 return segment_selectable_;
592 Trace::SegmentDisplayMode View::segment_display_mode() const
594 return segment_display_mode_;
597 void View::set_segment_display_mode(Trace::SegmentDisplayMode mode)
599 trigger_markers_.clear();
601 segment_display_mode_ = mode;
603 for (shared_ptr<Signal> signal : signals_)
604 signal->set_segment_display_mode(mode);
606 uint32_t last_segment = session_.get_segment_count() - 1;
609 case Trace::ShowLastSegmentOnly:
610 if (current_segment_ != last_segment)
611 set_current_segment(last_segment);
614 case Trace::ShowLastCompleteSegmentOnly:
615 // Do nothing if we only have one segment so far
616 if (last_segment > 0) {
617 // If the last segment isn't complete, the previous one must be
618 uint32_t segment_id =
619 (session_.all_segments_complete(last_segment)) ?
620 last_segment : last_segment - 1;
622 if (current_segment_ != segment_id)
623 set_current_segment(segment_id);
627 case Trace::ShowSingleSegmentOnly:
628 case Trace::ShowAllSegments:
629 case Trace::ShowAccumulatedIntensity:
631 // Current segment remains as-is
635 segment_selectable_ = true;
637 if ((mode == Trace::ShowAllSegments) || (mode == Trace::ShowAccumulatedIntensity))
638 segment_selectable_ = false;
642 segment_display_mode_changed((int)mode, segment_selectable_);
645 void View::zoom(double steps)
647 zoom(steps, viewport_->width() / 2);
650 void View::zoom(double steps, int offset)
652 set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
655 void View::zoom_fit(bool gui_state)
657 // Act as one-shot when stopped, toggle along with the GUI otherwise
658 if (session_.get_capture_state() == Session::Stopped) {
659 always_zoom_to_fit_ = false;
660 always_zoom_to_fit_changed(false);
662 always_zoom_to_fit_ = gui_state;
663 always_zoom_to_fit_changed(gui_state);
666 const pair<Timestamp, Timestamp> extents = get_time_extents();
667 const Timestamp delta = extents.second - extents.first;
668 if (delta < Timestamp("1e-12"))
672 const int w = viewport_->width();
676 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
677 set_scale_offset(scale.convert_to<double>(), extents.first);
680 void View::zoom_one_to_one()
682 using pv::data::SignalData;
684 // Make a set of all the visible data objects
685 set< shared_ptr<SignalData> > visible_data = get_visible_data();
686 if (visible_data.empty())
690 const int w = viewport_->width();
694 set_zoom(1.0 / session_.get_samplerate(), w / 2);
697 void View::set_scale_offset(double scale, const Timestamp& offset)
699 // Disable sticky scrolling / always zoom to fit when acquisition runs
700 // and user drags the viewport
701 if ((scale_ == scale) && (offset_ != offset) &&
702 (session_.get_capture_state() == Session::Running)) {
704 if (sticky_scrolling_) {
705 sticky_scrolling_ = false;
706 sticky_scrolling_changed(false);
709 if (always_zoom_to_fit_) {
710 always_zoom_to_fit_ = false;
711 always_zoom_to_fit_changed(false);
718 calculate_tick_spacing();
725 set< shared_ptr<SignalData> > View::get_visible_data() const
727 // Make a set of all the visible data objects
728 set< shared_ptr<SignalData> > visible_data;
729 for (const shared_ptr<Signal> sig : signals_)
731 visible_data.insert(sig->data());
736 pair<Timestamp, Timestamp> View::get_time_extents() const
738 boost::optional<Timestamp> left_time, right_time;
739 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
740 for (const shared_ptr<SignalData> d : visible_data) {
741 const vector< shared_ptr<Segment> > segments = d->segments();
742 for (const shared_ptr<Segment> &s : segments) {
743 double samplerate = s->samplerate();
744 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
746 const Timestamp start_time = s->start_time();
747 left_time = left_time ?
748 min(*left_time, start_time) :
750 right_time = right_time ?
751 max(*right_time, start_time + d->max_sample_count() / samplerate) :
752 start_time + d->max_sample_count() / samplerate;
756 if (!left_time || !right_time)
757 return make_pair(0, 0);
759 assert(*left_time < *right_time);
760 return make_pair(*left_time, *right_time);
763 void View::enable_show_sampling_points(bool state)
770 void View::enable_show_analog_minor_grid(bool state)
777 void View::enable_colored_bg(bool state)
783 bool View::colored_bg() const
788 bool View::cursors_shown() const
790 return show_cursors_;
793 void View::show_cursors(bool show)
795 show_cursors_ = show;
800 void View::centre_cursors()
802 const double time_width = scale_ * viewport_->width();
803 cursors_->first()->set_time(offset_ + time_width * 0.4);
804 cursors_->second()->set_time(offset_ + time_width * 0.6);
809 shared_ptr<CursorPair> View::cursors() const
814 void View::add_flag(const Timestamp& time)
816 flags_.push_back(make_shared<Flag>(*this, time,
817 QString("%1").arg(next_flag_text_)));
819 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
820 (next_flag_text_ + 1);
822 time_item_appearance_changed(true, true);
825 void View::remove_flag(shared_ptr<Flag> flag)
828 time_item_appearance_changed(true, true);
831 vector< shared_ptr<Flag> > View::flags() const
833 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
834 stable_sort(flags.begin(), flags.end(),
835 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
836 return a->time() < b->time();
842 const QPoint& View::hover_point() const
847 void View::restack_all_trace_tree_items()
849 // Make a list of owners that is sorted from deepest first
850 const vector<shared_ptr<TraceTreeItem>> items(
851 list_by_type<TraceTreeItem>());
852 set< TraceTreeItemOwner* > owners;
853 for (const auto &r : items)
854 owners.insert(r->owner());
855 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
856 sort(sorted_owners.begin(), sorted_owners.end(),
857 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
858 return a->depth() > b->depth(); });
860 // Restack the items recursively
861 for (auto &o : sorted_owners)
864 // Animate the items to their destination
865 for (const auto &i : items)
866 i->animate_to_layout_v_offset();
869 void View::on_setting_changed(const QString &key, const QVariant &value)
871 if (key == GlobalSettings::Key_View_TriggerIsZeroTime)
872 on_settingViewTriggerIsZeroTime_changed(value);
875 void View::trigger_event(int segment_id, util::Timestamp location)
877 // TODO This doesn't work if we're showing multiple segments at once
878 if ((uint32_t)segment_id != current_segment_)
881 // Set zero location if the Key_View_TriggerIsZeroTime setting is set and
882 // if this is the first trigger for this segment.
883 GlobalSettings settings;
884 bool trigger_is_zero_time = settings.value(GlobalSettings::Key_View_TriggerIsZeroTime).toBool();
886 size_t trigger_count = session_.get_triggers(current_segment_).size();
888 if (trigger_is_zero_time && trigger_count == 1)
889 set_zero_position(location);
891 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
894 void View::get_scroll_layout(double &length, Timestamp &offset) const
896 const pair<Timestamp, Timestamp> extents = get_time_extents();
897 length = ((extents.second - extents.first) / scale_).convert_to<double>();
898 offset = offset_ / scale_;
901 void View::set_zoom(double scale, int offset)
903 // Reset the "always zoom to fit" feature as the user changed the zoom
904 always_zoom_to_fit_ = false;
905 always_zoom_to_fit_changed(false);
907 const Timestamp cursor_offset = offset_ + scale_ * offset;
908 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
909 const Timestamp new_offset = cursor_offset - new_scale * offset;
910 set_scale_offset(new_scale.convert_to<double>(), new_offset);
913 void View::calculate_tick_spacing()
915 const double SpacingIncrement = 10.0f;
916 const double MinValueSpacing = 40.0f;
918 // Figure out the highest numeric value visible on a label
919 const QSize areaSize = viewport_->size();
920 const Timestamp max_time = max(fabs(offset_),
921 fabs(offset_ + scale_ * areaSize.width()));
923 double min_width = SpacingIncrement;
924 double label_width, tick_period_width;
926 QFontMetrics m(QApplication::font());
928 // Copies of the member variables with the same name, used in the calculation
929 // and written back afterwards, so that we don't emit signals all the time
930 // during the calculation.
931 pv::util::Timestamp tick_period = tick_period_;
932 pv::util::SIPrefix tick_prefix = tick_prefix_;
933 unsigned tick_precision = tick_precision_;
936 const double min_period = scale_ * min_width;
938 const int order = (int)floorf(log10f(min_period));
939 const pv::util::Timestamp order_decimal =
940 pow(pv::util::Timestamp(10), order);
942 // Allow for a margin of error so that a scale unit of 1 can be used.
943 // Otherwise, for a SU of 1 the tick period will almost always be below
944 // the min_period by a small amount - and thus skipped in favor of 2.
945 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
946 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
947 double tp_with_margin;
948 unsigned int unit = 0;
951 tp_with_margin = order_decimal.convert_to<double>() *
952 (ScaleUnits[unit++] + tp_margin);
953 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
955 minor_tick_count_ = (unit == 2) ? 4 : 5;
956 tick_period = order_decimal * ScaleUnits[unit - 1];
957 tick_prefix = static_cast<pv::util::SIPrefix>(
958 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
960 // Precision is the number of fractional digits required, not
961 // taking the prefix into account (and it must never be negative)
962 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
964 tick_period_width = (tick_period / scale_).convert_to<double>();
966 const QString label_text = Ruler::format_time_with_distance(
967 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
969 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
970 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
973 min_width += SpacingIncrement;
974 } while (tick_period_width < label_width);
976 set_tick_period(tick_period);
977 set_tick_prefix(tick_prefix);
978 set_tick_precision(tick_precision);
981 void View::adjust_top_margin()
985 const QSize areaSize = viewport_->size();
987 const pair<int, int> extents = v_extents();
988 const int top_margin = owner_visual_v_offset() + extents.first;
989 const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
991 // Do we have empty space at the top while the last trace goes out of screen?
992 if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
993 const int trace_height = extents.second - extents.first;
995 // Center everything vertically if there is enough space
996 if (areaSize.height() >= trace_height)
997 set_v_offset(extents.first -
998 ((areaSize.height() - trace_height) / 2));
1000 // Remove the top margin to make as many traces fit on screen as possible
1001 set_v_offset(extents.first);
1005 void View::update_scroll()
1008 QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
1009 QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
1011 const QSize areaSize = viewport_->size();
1013 // Set the horizontal scroll bar
1016 get_scroll_layout(length, offset);
1017 length = max(length - areaSize.width(), 0.0);
1019 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
1021 hscrollbar->setPageStep(areaSize.width() / 2);
1022 hscrollbar->setSingleStep(major_tick_distance);
1024 updating_scroll_ = true;
1026 if (length < MaxScrollValue) {
1027 hscrollbar->setRange(0, length);
1028 hscrollbar->setSliderPosition(offset.convert_to<double>());
1030 hscrollbar->setRange(0, MaxScrollValue);
1031 hscrollbar->setSliderPosition(
1032 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
1035 updating_scroll_ = false;
1037 // Set the vertical scrollbar
1038 vscrollbar->setPageStep(areaSize.height());
1039 vscrollbar->setSingleStep(areaSize.height() / 8);
1041 const pair<int, int> extents = v_extents();
1043 // Don't change the scrollbar range if there are no traces
1044 if (extents.first != extents.second)
1045 vscrollbar->setRange(extents.first - areaSize.height(),
1048 if (scroll_needs_defaults_)
1049 set_scroll_default();
1052 void View::reset_scroll()
1054 scrollarea_->verticalScrollBar()->setRange(0, 0);
1057 void View::set_scroll_default()
1061 const QSize areaSize = viewport_->size();
1063 const pair<int, int> extents = v_extents();
1064 const int trace_height = extents.second - extents.first;
1066 // Do all traces fit in the view?
1067 if (areaSize.height() >= trace_height)
1068 // Center all traces vertically
1069 set_v_offset(extents.first -
1070 ((areaSize.height() - trace_height) / 2));
1072 // Put the first trace at the top, letting the bottom ones overflow
1073 set_v_offset(extents.first);
1076 void View::determine_if_header_was_shrunk()
1078 const int header_pane_width = splitter_->sizes().front();
1079 const int header_width = header_->extended_size_hint().width();
1081 // Allow for a slight margin of error so that we also accept
1082 // slight differences when e.g. a label name change increased
1083 // the overall width
1084 header_was_shrunk_ = (header_pane_width < (header_width - 10));
1087 void View::resize_header_to_fit()
1089 // Setting the maximum width of the header widget doesn't work as
1090 // expected because the splitter would allow the user to make the
1091 // pane wider than that, creating empty space as a result.
1092 // To make this work, we stricly enforce the maximum width by
1093 // expanding the header unless the user shrunk it on purpose.
1094 // As we're then setting the width of the header pane, we set the
1095 // splitter to the maximum allowed position.
1097 int splitter_area_width = 0;
1098 for (int w : splitter_->sizes())
1099 splitter_area_width += w;
1101 // Make sure the header has enough horizontal space to show all labels fully
1102 QList<int> pane_sizes;
1103 pane_sizes.push_back(header_->extended_size_hint().width());
1104 pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
1105 splitter_->setSizes(pane_sizes);
1108 void View::update_layout()
1113 TraceTreeItemOwner* View::find_prevalent_trace_group(
1114 const shared_ptr<sigrok::ChannelGroup> &group,
1115 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1120 unordered_set<TraceTreeItemOwner*> owners;
1121 vector<TraceTreeItemOwner*> owner_list;
1123 // Make a set and a list of all the owners
1124 for (const auto &channel : group->channels()) {
1125 for (auto entry : signal_map) {
1126 if (entry.first->channel() == channel) {
1127 TraceTreeItemOwner *const o = (entry.second)->owner();
1128 owner_list.push_back(o);
1134 // Iterate through the list of owners, and find the most prevalent
1135 size_t max_prevalence = 0;
1136 TraceTreeItemOwner *prevalent_owner = nullptr;
1137 for (TraceTreeItemOwner *owner : owners) {
1138 const size_t prevalence = count_if(
1139 owner_list.begin(), owner_list.end(),
1140 [&](TraceTreeItemOwner *o) { return o == owner; });
1141 if (prevalence > max_prevalence) {
1142 max_prevalence = prevalence;
1143 prevalent_owner = owner;
1147 return prevalent_owner;
1150 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
1151 const vector< shared_ptr<sigrok::Channel> > &channels,
1152 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1154 set< shared_ptr<Trace> > &add_list)
1156 vector< shared_ptr<Trace> > filtered_traces;
1158 for (const auto &channel : channels) {
1159 for (auto entry : signal_map) {
1160 if (entry.first->channel() == channel) {
1161 shared_ptr<Trace> trace = entry.second;
1162 const auto list_iter = add_list.find(trace);
1163 if (list_iter == add_list.end())
1166 filtered_traces.push_back(trace);
1167 add_list.erase(list_iter);
1172 return filtered_traces;
1175 void View::determine_time_unit()
1177 // Check whether we know the sample rate and hence can use time as the unit
1178 if (time_unit_ == util::TimeUnit::Samples) {
1179 // Check all signals but...
1180 for (const shared_ptr<Signal> signal : signals_) {
1181 const shared_ptr<SignalData> data = signal->data();
1183 // ...only check first segment of each
1184 const vector< shared_ptr<Segment> > segments = data->segments();
1185 if (!segments.empty())
1186 if (segments[0]->samplerate()) {
1187 set_time_unit(util::TimeUnit::Time);
1194 bool View::eventFilter(QObject *object, QEvent *event)
1196 const QEvent::Type type = event->type();
1197 if (type == QEvent::MouseMove) {
1199 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
1200 if (object == viewport_)
1201 hover_point_ = mouse_event->pos();
1202 else if (object == ruler_)
1203 hover_point_ = QPoint(mouse_event->x(), 0);
1204 else if (object == header_)
1205 hover_point_ = QPoint(0, mouse_event->y());
1207 hover_point_ = QPoint(-1, -1);
1209 update_hover_point();
1211 } else if (type == QEvent::Leave) {
1212 hover_point_ = QPoint(-1, -1);
1213 update_hover_point();
1214 } else if (type == QEvent::Show) {
1216 // This is somewhat of a hack, unfortunately. We cannot use
1217 // set_v_offset() from within restore_settings() as the view
1218 // at that point is neither visible nor properly sized.
1219 // This is the least intrusive workaround I could come up
1220 // with: set the vertical offset (or scroll defaults) when
1221 // the view is shown, which happens after all widgets were
1222 // resized to their final sizes.
1225 if (settings_restored_)
1226 determine_if_header_was_shrunk();
1228 resize_header_to_fit();
1230 if (scroll_needs_defaults_) {
1231 set_scroll_default();
1232 scroll_needs_defaults_ = false;
1235 if (saved_v_offset_) {
1236 set_v_offset(saved_v_offset_);
1237 saved_v_offset_ = 0;
1241 return QObject::eventFilter(object, event);
1244 void View::resizeEvent(QResizeEvent* event)
1246 // Only adjust the top margin if we shrunk vertically
1247 if (event->size().height() < event->oldSize().height())
1248 adjust_top_margin();
1253 void View::update_hover_point()
1255 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1256 list_by_type<TraceTreeItem>());
1257 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1258 r->hover_point_changed(hover_point_);
1260 hover_point_changed(hover_point_);
1263 void View::row_item_appearance_changed(bool label, bool content)
1268 viewport_->update();
1271 void View::time_item_appearance_changed(bool label, bool content)
1276 // Make sure the header pane width is updated, too
1281 viewport_->update();
1284 void View::extents_changed(bool horz, bool vert)
1287 (horz ? TraceTreeItemHExtentsChanged : 0) |
1288 (vert ? TraceTreeItemVExtentsChanged : 0);
1290 lazy_event_handler_.start();
1293 void View::on_signal_name_changed()
1295 if (!header_was_shrunk_)
1296 resize_header_to_fit();
1299 void View::on_splitter_moved()
1301 // The header can only shrink when the splitter is moved manually
1302 determine_if_header_was_shrunk();
1304 if (!header_was_shrunk_)
1305 resize_header_to_fit();
1308 void View::h_scroll_value_changed(int value)
1310 if (updating_scroll_)
1313 // Disable sticky scrolling when user moves the horizontal scroll bar
1314 // during a running acquisition
1315 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1316 sticky_scrolling_ = false;
1317 sticky_scrolling_changed(false);
1320 const int range = scrollarea_->horizontalScrollBar()->maximum();
1321 if (range < MaxScrollValue)
1322 set_offset(scale_ * value);
1326 get_scroll_layout(length, offset);
1327 set_offset(scale_ * length * value / MaxScrollValue);
1331 viewport_->update();
1334 void View::v_scroll_value_changed()
1337 viewport_->update();
1340 void View::signals_changed()
1342 using sigrok::Channel;
1344 vector< shared_ptr<Channel> > channels;
1345 shared_ptr<sigrok::Device> sr_dev;
1346 bool signals_added_or_removed = false;
1348 // Do we need to set the vertical scrollbar to its default position later?
1349 // We do if there are no traces, i.e. the scroll bar has no range set
1350 bool reset_scrollbar =
1351 (scrollarea_->verticalScrollBar()->minimum() ==
1352 scrollarea_->verticalScrollBar()->maximum());
1354 if (!session_.device()) {
1358 sr_dev = session_.device()->device();
1360 channels = sr_dev->channels();
1363 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1365 // Make a list of traces that are being added, and a list of traces
1366 // that are being removed
1367 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1368 const set<shared_ptr<Trace>> prev_traces(
1369 prev_trace_list.begin(), prev_trace_list.end());
1371 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1373 #ifdef ENABLE_DECODE
1374 traces.insert(decode_traces_.begin(), decode_traces_.end());
1377 set< shared_ptr<Trace> > add_traces;
1378 set_difference(traces.begin(), traces.end(),
1379 prev_traces.begin(), prev_traces.end(),
1380 inserter(add_traces, add_traces.begin()));
1382 set< shared_ptr<Trace> > remove_traces;
1383 set_difference(prev_traces.begin(), prev_traces.end(),
1384 traces.begin(), traces.end(),
1385 inserter(remove_traces, remove_traces.begin()));
1387 // Make a look-up table of sigrok Channels to pulseview Signals
1388 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1390 for (const shared_ptr<Signal> &sig : signals_)
1391 signal_map[sig->base()] = sig;
1393 // Populate channel groups
1395 for (auto entry : sr_dev->channel_groups()) {
1396 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1398 if (group->channels().size() <= 1)
1401 // Find best trace group to add to
1402 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1405 // If there is no trace group, create one
1406 shared_ptr<TraceGroup> new_trace_group;
1408 new_trace_group.reset(new TraceGroup());
1409 owner = new_trace_group.get();
1412 // Extract traces for the trace group, removing them from
1414 const vector< shared_ptr<Trace> > new_traces_in_group =
1415 extract_new_traces_for_channels(group->channels(),
1416 signal_map, add_traces);
1418 // Add the traces to the group
1419 const pair<int, int> prev_v_extents = owner->v_extents();
1420 int offset = prev_v_extents.second - prev_v_extents.first;
1421 for (shared_ptr<Trace> trace : new_traces_in_group) {
1423 owner->add_child_item(trace);
1425 const pair<int, int> extents = trace->v_extents();
1426 if (trace->enabled())
1427 offset += -extents.first;
1428 trace->force_to_v_offset(offset);
1429 if (trace->enabled())
1430 offset += extents.second;
1433 if (new_trace_group) {
1434 // Assign proper vertical offsets to each channel in the group
1435 new_trace_group->restack_items();
1437 // If this is a new group, enqueue it in the new top level
1439 if (!new_traces_in_group.empty())
1440 new_top_level_items.push_back(new_trace_group);
1444 // Enqueue the remaining logic channels in a group
1445 vector< shared_ptr<Channel> > logic_channels;
1446 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1447 [](const shared_ptr<Channel>& c) {
1448 return c->type() == sigrok::ChannelType::LOGIC; });
1450 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1451 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1453 if (non_grouped_logic_signals.size() > 0) {
1454 const shared_ptr<TraceGroup> non_grouped_trace_group(
1455 make_shared<TraceGroup>());
1456 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1457 non_grouped_trace_group->add_child_item(trace);
1459 non_grouped_trace_group->restack_items();
1460 new_top_level_items.push_back(non_grouped_trace_group);
1463 // Enqueue the remaining channels as free ungrouped traces
1464 const vector< shared_ptr<Trace> > new_top_level_signals =
1465 extract_new_traces_for_channels(channels, signal_map, add_traces);
1466 new_top_level_items.insert(new_top_level_items.end(),
1467 new_top_level_signals.begin(), new_top_level_signals.end());
1469 // Enqueue any remaining traces i.e. decode traces
1470 new_top_level_items.insert(new_top_level_items.end(),
1471 add_traces.begin(), add_traces.end());
1473 // Remove any removed traces
1474 for (shared_ptr<Trace> trace : remove_traces) {
1475 TraceTreeItemOwner *const owner = trace->owner();
1477 owner->remove_child_item(trace);
1478 signals_added_or_removed = true;
1481 // Remove any empty trace groups
1482 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1483 if (group->child_items().size() == 0) {
1484 remove_child_item(group);
1488 // Add and position the pending top levels items
1489 int offset = v_extents().second;
1490 for (auto item : new_top_level_items) {
1491 add_child_item(item);
1493 // Position the item after the last item or at the top if there is none
1494 const pair<int, int> extents = item->v_extents();
1496 if (item->enabled())
1497 offset += -extents.first;
1499 item->force_to_v_offset(offset);
1501 if (item->enabled())
1502 offset += extents.second;
1503 signals_added_or_removed = true;
1507 if (signals_added_or_removed && !header_was_shrunk_)
1508 resize_header_to_fit();
1513 viewport_->update();
1515 if (reset_scrollbar)
1516 set_scroll_default();
1519 void View::capture_state_updated(int state)
1521 GlobalSettings settings;
1523 if (state == Session::Running) {
1524 set_time_unit(util::TimeUnit::Samples);
1526 trigger_markers_.clear();
1528 scale_at_acq_start_ = scale_;
1529 offset_at_acq_start_ = offset_;
1531 // Activate "always zoom to fit" if the setting is enabled and we're
1532 // the main view of this session (other trace views may be used for
1533 // zooming and we don't want to mess them up)
1534 bool state = settings.value(GlobalSettings::Key_View_ZoomToFitDuringAcq).toBool();
1535 if (is_main_view_ && state) {
1536 always_zoom_to_fit_ = true;
1537 always_zoom_to_fit_changed(always_zoom_to_fit_);
1540 // Enable sticky scrolling if the setting is enabled
1541 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1543 // Reset all traces to segment 0
1544 current_segment_ = 0;
1545 set_current_segment(current_segment_);
1548 if (state == Session::Stopped) {
1549 // After acquisition has stopped we need to re-calculate the ticks once
1550 // as it's otherwise done when the user pans or zooms, which is too late
1551 calculate_tick_spacing();
1553 // Reset "always zoom to fit", the acquisition has stopped
1554 if (always_zoom_to_fit_) {
1555 // Perform a final zoom-to-fit before disabling
1556 zoom_fit(always_zoom_to_fit_);
1557 always_zoom_to_fit_ = false;
1558 always_zoom_to_fit_changed(always_zoom_to_fit_);
1561 bool zoom_to_fit_after_acq =
1562 settings.value(GlobalSettings::Key_View_ZoomToFitAfterAcq).toBool();
1564 // Only perform zoom-to-fit if the user hasn't altered the viewport and
1565 // we didn't restore settings in the meanwhile
1566 if (zoom_to_fit_after_acq &&
1567 !suppress_zoom_to_fit_after_acq_ &&
1568 (scale_ == scale_at_acq_start_) &&
1569 (offset_ == offset_at_acq_start_))
1570 zoom_fit(false); // We're stopped, so the GUI state doesn't matter
1572 suppress_zoom_to_fit_after_acq_ = false;
1576 void View::on_new_segment(int new_segment_id)
1578 on_segment_changed(new_segment_id);
1581 void View::on_segment_completed(int segment_id)
1583 on_segment_changed(segment_id);
1586 void View::on_segment_changed(int segment)
1588 switch (segment_display_mode_) {
1589 case Trace::ShowLastSegmentOnly:
1590 case Trace::ShowSingleSegmentOnly:
1591 set_current_segment(segment);
1594 case Trace::ShowLastCompleteSegmentOnly:
1595 // Only update if all segments are complete
1596 if (session_.all_segments_complete(segment))
1597 set_current_segment(segment);
1600 case Trace::ShowAllSegments:
1601 case Trace::ShowAccumulatedIntensity:
1607 void View::on_settingViewTriggerIsZeroTime_changed(const QVariant new_value)
1609 if (new_value.toBool()) {
1610 // The first trigger for this segment is used as the zero position
1611 vector<util::Timestamp> triggers = session_.get_triggers(current_segment_);
1612 if (triggers.size() > 0)
1613 set_zero_position(triggers.front());
1615 reset_zero_position();
1618 void View::perform_delayed_view_update()
1620 if (always_zoom_to_fit_) {
1622 } else if (sticky_scrolling_) {
1623 // Make right side of the view sticky
1626 get_scroll_layout(length, offset);
1628 const QSize areaSize = viewport_->size();
1629 length = max(length - areaSize.width(), 0.0);
1631 set_offset(scale_ * length);
1634 determine_time_unit();
1637 viewport_->update();
1640 void View::process_sticky_events()
1642 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1644 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1645 restack_all_trace_tree_items();
1649 // Clear the sticky events
1653 } // namespace trace
1654 } // namespace views