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>
42 #include <QMouseEvent>
44 #include <QVBoxLayout>
46 #include <libsigrokcxx/libsigrokcxx.hpp>
48 #include "analogsignal.hpp"
50 #include "logicsignal.hpp"
53 #include "tracegroup.hpp"
54 #include "triggermarker.hpp"
56 #include "viewport.hpp"
58 #include "pv/data/logic.hpp"
59 #include "pv/data/logicsegment.hpp"
60 #include "pv/devices/device.hpp"
61 #include "pv/globalsettings.hpp"
62 #include "pv/session.hpp"
63 #include "pv/util.hpp"
66 #include "decodetrace.hpp"
69 using pv::data::SignalData;
70 using pv::data::Segment;
71 using pv::util::TimeUnit;
72 using pv::util::Timestamp;
74 using std::back_inserter;
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;
100 const int View::ScaleUnits[3] = {1, 2, 5};
103 CustomScrollArea::CustomScrollArea(QWidget *parent) :
104 QAbstractScrollArea(parent)
108 bool CustomScrollArea::viewportEvent(QEvent *event)
110 switch (event->type()) {
112 case QEvent::MouseButtonPress:
113 case QEvent::MouseButtonRelease:
114 case QEvent::MouseButtonDblClick:
115 case QEvent::MouseMove:
117 case QEvent::TouchBegin:
118 case QEvent::TouchUpdate:
119 case QEvent::TouchEnd:
122 return QAbstractScrollArea::viewportEvent(event);
126 View::View(Session &session, bool is_main_view, QWidget *parent) :
127 ViewBase(session, is_main_view, parent),
129 // Note: Place defaults in View::reset_view_state(), not here
130 splitter_(new QSplitter()),
131 header_was_shrunk_(false), // The splitter remains unchanged after a reset, so this goes here
132 sticky_scrolling_(false) // Default setting is set in MainWindow::setup_ui()
134 QVBoxLayout *root_layout = new QVBoxLayout(this);
135 root_layout->setContentsMargins(0, 0, 0, 0);
136 root_layout->addWidget(splitter_);
138 viewport_ = new Viewport(*this);
139 scrollarea_ = new CustomScrollArea(splitter_);
140 scrollarea_->setViewport(viewport_);
141 scrollarea_->setFrameShape(QFrame::NoFrame);
143 ruler_ = new Ruler(*this);
145 header_ = new Header(*this);
146 header_->setMinimumWidth(10); // So that the arrow tips show at least
148 // We put the header into a simple layout so that we can add the top margin,
149 // allowing us to make it line up with the bottom of the ruler
150 QWidget *header_container = new QWidget();
151 header_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
152 QVBoxLayout *header_layout = new QVBoxLayout(header_container);
153 header_layout->setContentsMargins(0, ruler_->sizeHint().height(), 0, 0);
154 header_layout->addWidget(header_);
156 // To let the ruler and scrollarea be on the same split pane, we need a layout
157 QWidget *trace_container = new QWidget();
158 trace_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
159 QVBoxLayout *trace_layout = new QVBoxLayout(trace_container);
160 trace_layout->setSpacing(0); // We don't want space between the ruler and scrollarea
161 trace_layout->setContentsMargins(0, 0, 0, 0);
162 trace_layout->addWidget(ruler_);
163 trace_layout->addWidget(scrollarea_);
165 splitter_->addWidget(header_container);
166 splitter_->addWidget(trace_container);
167 splitter_->setHandleWidth(1); // Don't show a visible rubber band
168 splitter_->setCollapsible(0, false); // Prevent the header from collapsing
169 splitter_->setCollapsible(1, false); // Prevent the traces from collapsing
170 splitter_->setStretchFactor(0, 0); // Prevent the panes from being resized
171 splitter_->setStretchFactor(1, 1); // when the entire view is resized
172 splitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
174 viewport_->installEventFilter(this);
175 ruler_->installEventFilter(this);
176 header_->installEventFilter(this);
178 // Set up settings and event handlers
179 GlobalSettings settings;
180 colored_bg_ = settings.value(GlobalSettings::Key_View_ColoredBG).toBool();
182 GlobalSettings::add_change_handler(this);
184 connect(scrollarea_->horizontalScrollBar(), SIGNAL(valueChanged(int)),
185 this, SLOT(h_scroll_value_changed(int)));
186 connect(scrollarea_->verticalScrollBar(), SIGNAL(valueChanged(int)),
187 this, SLOT(v_scroll_value_changed()));
189 connect(header_, SIGNAL(selection_changed()),
190 ruler_, SLOT(clear_selection()));
191 connect(ruler_, SIGNAL(selection_changed()),
192 header_, SLOT(clear_selection()));
194 connect(header_, SIGNAL(selection_changed()),
195 this, SIGNAL(selection_changed()));
196 connect(ruler_, SIGNAL(selection_changed()),
197 this, SIGNAL(selection_changed()));
199 connect(splitter_, SIGNAL(splitterMoved(int, int)),
200 this, SLOT(on_splitter_moved()));
202 connect(&lazy_event_handler_, SIGNAL(timeout()),
203 this, SLOT(process_sticky_events()));
204 lazy_event_handler_.setSingleShot(true);
206 // Trigger the initial event manually. The default device has signals
207 // which were created before this object came into being
210 // make sure the transparent widgets are on the top
219 GlobalSettings::remove_change_handler(this);
222 void View::reset_view_state()
224 ViewBase::reset_view_state();
226 segment_display_mode_ = Trace::ShowLastSegmentOnly;
227 segment_selectable_ = false;
231 updating_scroll_ = false;
232 settings_restored_ = false;
233 always_zoom_to_fit_ = false;
235 tick_prefix_ = pv::util::SIPrefix::yocto;
237 time_unit_ = util::TimeUnit::Time;
238 show_cursors_ = false;
239 cursors_ = make_shared<CursorPair>(*this);
240 next_flag_text_ = 'A';
241 trigger_markers_.clear();
242 hover_point_ = QPoint(-1, -1);
243 scroll_needs_defaults_ = true;
245 scale_at_acq_start_ = 0;
246 offset_at_acq_start_ = 0;
247 suppress_zoom_to_fit_after_acq_ = false;
249 show_cursors_ = false;
250 cursor_state_changed(show_cursors_);
253 // Update the zoom state
254 calculate_tick_spacing();
256 // Make sure the standard bar's segment selector is in sync
257 set_segment_display_mode(segment_display_mode_);
260 Session& View::session()
265 const Session& View::session() const
270 unordered_set< shared_ptr<Signal> > View::signals() const
275 void View::clear_signals()
277 ViewBase::clear_signalbases();
281 void View::add_signal(const shared_ptr<Signal> signal)
283 ViewBase::add_signalbase(signal->base());
284 signals_.insert(signal);
286 signal->set_segment_display_mode(segment_display_mode_);
287 signal->set_current_segment(current_segment_);
289 connect(signal->base().get(), SIGNAL(name_changed(const QString&)),
290 this, SLOT(on_signal_name_changed()));
294 void View::clear_decode_signals()
296 decode_traces_.clear();
299 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
301 shared_ptr<DecodeTrace> d(
302 new DecodeTrace(session_, signal, decode_traces_.size()));
303 decode_traces_.push_back(d);
305 d->set_segment_display_mode(segment_display_mode_);
306 d->set_current_segment(current_segment_);
308 connect(signal.get(), SIGNAL(name_changed(const QString&)),
309 this, SLOT(on_signal_name_changed()));
312 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
314 for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
315 if ((*i)->base() == signal) {
316 decode_traces_.erase(i);
328 const View* View::view() const
333 Viewport* View::viewport()
338 const Viewport* View::viewport() const
343 void View::save_settings(QSettings &settings) const
345 settings.setValue("scale", scale_);
346 settings.setValue("v_offset",
347 scrollarea_->verticalScrollBar()->sliderPosition());
349 settings.setValue("splitter_state", splitter_->saveState());
350 settings.setValue("segment_display_mode", segment_display_mode_);
354 boost::archive::text_oarchive oa(ss);
355 oa << boost::serialization::make_nvp("ruler_shift", ruler_shift_);
356 settings.setValue("ruler_shift", QString::fromStdString(ss.str()));
360 boost::archive::text_oarchive oa(ss);
361 oa << boost::serialization::make_nvp("offset", offset_);
362 settings.setValue("offset", QString::fromStdString(ss.str()));
365 for (shared_ptr<Signal> signal : signals_) {
366 settings.beginGroup(signal->base()->internal_name());
367 signal->save_settings(settings);
372 void View::restore_settings(QSettings &settings)
374 // Note: It is assumed that this function is only called once,
375 // immediately after restoring a previous session.
377 if (settings.contains("scale"))
378 set_scale(settings.value("scale").toDouble());
380 if (settings.contains("ruler_shift")) {
381 util::Timestamp shift;
383 ss << settings.value("ruler_shift").toString().toStdString();
386 boost::archive::text_iarchive ia(ss);
387 ia >> boost::serialization::make_nvp("ruler_shift", shift);
388 ruler_shift_ = shift;
389 } catch (boost::archive::archive_exception&) {
390 qDebug() << "Could not restore the view ruler shift";
394 if (settings.contains("offset")) {
395 util::Timestamp offset;
397 ss << settings.value("offset").toString().toStdString();
400 boost::archive::text_iarchive ia(ss);
401 ia >> boost::serialization::make_nvp("offset", offset);
402 // This also updates ruler_offset_
404 } catch (boost::archive::archive_exception&) {
405 qDebug() << "Could not restore the view offset";
409 if (settings.contains("splitter_state"))
410 splitter_->restoreState(settings.value("splitter_state").toByteArray());
412 if (settings.contains("segment_display_mode"))
413 set_segment_display_mode(
414 (Trace::SegmentDisplayMode)(settings.value("segment_display_mode").toInt()));
416 for (shared_ptr<Signal> signal : signals_) {
417 settings.beginGroup(signal->base()->internal_name());
418 signal->restore_settings(settings);
422 if (settings.contains("v_offset")) {
423 saved_v_offset_ = settings.value("v_offset").toInt();
424 set_v_offset(saved_v_offset_);
425 scroll_needs_defaults_ = false;
426 // Note: see eventFilter() for additional information
429 settings_restored_ = true;
430 suppress_zoom_to_fit_after_acq_ = true;
432 // Update the ruler so that it uses the new scale
433 calculate_tick_spacing();
436 vector< shared_ptr<TimeItem> > View::time_items() const
438 const vector<shared_ptr<Flag>> f(flags());
439 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
442 items.push_back(cursors_);
443 items.push_back(cursors_->first());
444 items.push_back(cursors_->second());
447 for (auto trigger_marker : trigger_markers_)
448 items.push_back(trigger_marker);
453 double View::scale() const
458 void View::set_scale(double scale)
460 if (scale_ != scale) {
466 void View::set_offset(const pv::util::Timestamp& offset, bool force_update)
468 if ((offset_ != offset) || force_update) {
470 ruler_offset_ = offset_ + ruler_shift_;
475 const Timestamp& View::offset() const
480 const Timestamp& View::ruler_offset() const
482 return ruler_offset_;
485 void View::set_zero_position(pv::util::Timestamp& position)
487 ruler_shift_ = -position;
489 // Force an immediate update of the offsets
490 set_offset(offset_, true);
494 void View::reset_zero_position()
498 // Force an immediate update of the offsets
499 set_offset(offset_, true);
503 int View::owner_visual_v_offset() const
505 return -scrollarea_->verticalScrollBar()->sliderPosition();
508 void View::set_v_offset(int offset)
510 scrollarea_->verticalScrollBar()->setSliderPosition(offset);
515 unsigned int View::depth() const
520 uint32_t View::current_segment() const
522 return current_segment_;
525 pv::util::SIPrefix View::tick_prefix() const
530 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
532 if (tick_prefix_ != tick_prefix) {
533 tick_prefix_ = tick_prefix;
534 tick_prefix_changed();
538 unsigned int View::tick_precision() const
540 return tick_precision_;
543 void View::set_tick_precision(unsigned tick_precision)
545 if (tick_precision_ != tick_precision) {
546 tick_precision_ = tick_precision;
547 tick_precision_changed();
551 const pv::util::Timestamp& View::tick_period() const
556 unsigned int View::minor_tick_count() const
558 return minor_tick_count_;
561 void View::set_tick_period(const pv::util::Timestamp& tick_period)
563 if (tick_period_ != tick_period) {
564 tick_period_ = tick_period;
565 tick_period_changed();
569 TimeUnit View::time_unit() const
574 void View::set_time_unit(pv::util::TimeUnit time_unit)
576 if (time_unit_ != time_unit) {
577 time_unit_ = time_unit;
582 void View::set_current_segment(uint32_t segment_id)
584 current_segment_ = segment_id;
586 for (shared_ptr<Signal> signal : signals_)
587 signal->set_current_segment(current_segment_);
589 for (shared_ptr<DecodeTrace> dt : decode_traces_)
590 dt->set_current_segment(current_segment_);
593 vector<util::Timestamp> triggers = session_.get_triggers(current_segment_);
595 trigger_markers_.clear();
596 for (util::Timestamp timestamp : triggers)
597 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, timestamp));
599 // When enabled, the first trigger for this segment is used as the zero position
600 GlobalSettings settings;
601 bool trigger_is_zero_time = settings.value(GlobalSettings::Key_View_TriggerIsZeroTime).toBool();
603 if (trigger_is_zero_time && (triggers.size() > 0))
604 set_zero_position(triggers.front());
608 segment_changed(segment_id);
611 bool View::segment_is_selectable() const
613 return segment_selectable_;
616 Trace::SegmentDisplayMode View::segment_display_mode() const
618 return segment_display_mode_;
621 void View::set_segment_display_mode(Trace::SegmentDisplayMode mode)
623 segment_display_mode_ = mode;
625 for (shared_ptr<Signal> signal : signals_)
626 signal->set_segment_display_mode(mode);
628 uint32_t last_segment = session_.get_segment_count() - 1;
631 case Trace::ShowLastSegmentOnly:
632 if (current_segment_ != last_segment)
633 set_current_segment(last_segment);
636 case Trace::ShowLastCompleteSegmentOnly:
637 // Do nothing if we only have one segment so far
638 if (last_segment > 0) {
639 // If the last segment isn't complete, the previous one must be
640 uint32_t segment_id =
641 (session_.all_segments_complete(last_segment)) ?
642 last_segment : last_segment - 1;
644 if (current_segment_ != segment_id)
645 set_current_segment(segment_id);
649 case Trace::ShowSingleSegmentOnly:
650 case Trace::ShowAllSegments:
651 case Trace::ShowAccumulatedIntensity:
653 // Current segment remains as-is
657 segment_selectable_ = true;
659 if ((mode == Trace::ShowAllSegments) || (mode == Trace::ShowAccumulatedIntensity))
660 segment_selectable_ = false;
664 segment_display_mode_changed((int)mode, segment_selectable_);
667 void View::zoom(double steps)
669 zoom(steps, viewport_->width() / 2);
672 void View::zoom(double steps, int offset)
674 set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
677 void View::zoom_fit(bool gui_state)
679 // Act as one-shot when stopped, toggle along with the GUI otherwise
680 if (session_.get_capture_state() == Session::Stopped) {
681 always_zoom_to_fit_ = false;
682 always_zoom_to_fit_changed(false);
684 always_zoom_to_fit_ = gui_state;
685 always_zoom_to_fit_changed(gui_state);
688 const pair<Timestamp, Timestamp> extents = get_time_extents();
689 const Timestamp delta = extents.second - extents.first;
690 if (delta < Timestamp("1e-12"))
694 const int w = viewport_->width();
698 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
699 set_scale_offset(scale.convert_to<double>(), extents.first);
702 void View::set_scale_offset(double scale, const Timestamp& offset)
704 // Disable sticky scrolling / always zoom to fit when acquisition runs
705 // and user drags the viewport
706 if ((scale_ == scale) && (offset_ != offset) &&
707 (session_.get_capture_state() == Session::Running)) {
709 if (sticky_scrolling_) {
710 sticky_scrolling_ = false;
711 sticky_scrolling_changed(false);
714 if (always_zoom_to_fit_) {
715 always_zoom_to_fit_ = false;
716 always_zoom_to_fit_changed(false);
723 calculate_tick_spacing();
730 set< shared_ptr<SignalData> > View::get_visible_data() const
732 // Make a set of all the visible data objects
733 set< shared_ptr<SignalData> > visible_data;
734 for (const shared_ptr<Signal> sig : signals_)
736 visible_data.insert(sig->data());
741 pair<Timestamp, Timestamp> View::get_time_extents() const
743 boost::optional<Timestamp> left_time, right_time;
744 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
745 for (const shared_ptr<SignalData> d : visible_data) {
746 const vector< shared_ptr<Segment> > segments = d->segments();
747 for (const shared_ptr<Segment> &s : segments) {
748 double samplerate = s->samplerate();
749 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
751 const Timestamp start_time = s->start_time();
752 left_time = left_time ?
753 min(*left_time, start_time) :
755 right_time = right_time ?
756 max(*right_time, start_time + d->max_sample_count() / samplerate) :
757 start_time + d->max_sample_count() / samplerate;
761 if (!left_time || !right_time)
762 return make_pair(0, 0);
764 assert(*left_time < *right_time);
765 return make_pair(*left_time, *right_time);
768 void View::enable_show_sampling_points(bool state)
775 void View::enable_show_analog_minor_grid(bool state)
782 void View::enable_colored_bg(bool state)
788 bool View::colored_bg() const
793 bool View::cursors_shown() const
795 return show_cursors_;
798 void View::show_cursors(bool show)
800 show_cursors_ = show;
801 cursor_state_changed(show);
806 void View::centre_cursors()
809 const double time_width = scale_ * viewport_->width();
810 cursors_->first()->set_time(offset_ + time_width * 0.4);
811 cursors_->second()->set_time(offset_ + time_width * 0.6);
818 shared_ptr<CursorPair> View::cursors() const
823 void View::add_flag(const Timestamp& time)
825 flags_.push_back(make_shared<Flag>(*this, time,
826 QString("%1").arg(next_flag_text_)));
828 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
829 (next_flag_text_ + 1);
831 time_item_appearance_changed(true, true);
834 void View::remove_flag(shared_ptr<Flag> flag)
837 time_item_appearance_changed(true, true);
840 vector< shared_ptr<Flag> > View::flags() const
842 vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
843 stable_sort(flags.begin(), flags.end(),
844 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
845 return a->time() < b->time();
851 const QPoint& View::hover_point() const
856 void View::restack_all_trace_tree_items()
858 // Make a list of owners that is sorted from deepest first
859 const vector<shared_ptr<TraceTreeItem>> items(
860 list_by_type<TraceTreeItem>());
861 set< TraceTreeItemOwner* > owners;
862 for (const auto &r : items)
863 owners.insert(r->owner());
864 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
865 sort(sorted_owners.begin(), sorted_owners.end(),
866 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
867 return a->depth() > b->depth(); });
869 // Restack the items recursively
870 for (auto &o : sorted_owners)
873 // Animate the items to their destination
874 for (const auto &i : items)
875 i->animate_to_layout_v_offset();
878 int View::header_width() const
880 return header_->extended_size_hint().width();
883 void View::on_setting_changed(const QString &key, const QVariant &value)
885 if (key == GlobalSettings::Key_View_TriggerIsZeroTime)
886 on_settingViewTriggerIsZeroTime_changed(value);
889 void View::trigger_event(int segment_id, util::Timestamp location)
891 // TODO This doesn't work if we're showing multiple segments at once
892 if ((uint32_t)segment_id != current_segment_)
895 // Set zero location if the Key_View_TriggerIsZeroTime setting is set and
896 // if this is the first trigger for this segment.
897 GlobalSettings settings;
898 bool trigger_is_zero_time = settings.value(GlobalSettings::Key_View_TriggerIsZeroTime).toBool();
900 size_t trigger_count = session_.get_triggers(current_segment_).size();
902 if (trigger_is_zero_time && trigger_count == 1)
903 set_zero_position(location);
905 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
908 void View::get_scroll_layout(double &length, Timestamp &offset) const
910 const pair<Timestamp, Timestamp> extents = get_time_extents();
911 length = ((extents.second - extents.first) / scale_).convert_to<double>();
912 offset = offset_ / scale_;
915 void View::set_zoom(double scale, int offset)
917 // Reset the "always zoom to fit" feature as the user changed the zoom
918 always_zoom_to_fit_ = false;
919 always_zoom_to_fit_changed(false);
921 const Timestamp cursor_offset = offset_ + scale_ * offset;
922 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
923 const Timestamp new_offset = cursor_offset - new_scale * offset;
924 set_scale_offset(new_scale.convert_to<double>(), new_offset);
927 void View::calculate_tick_spacing()
929 const double SpacingIncrement = 10.0f;
930 const double MinValueSpacing = 40.0f;
932 // Figure out the highest numeric value visible on a label
933 const QSize areaSize = viewport_->size();
934 const Timestamp max_time = max(fabs(offset_),
935 fabs(offset_ + scale_ * areaSize.width()));
937 double min_width = SpacingIncrement;
938 double label_width, tick_period_width;
940 QFontMetrics m(QApplication::font());
942 // Copies of the member variables with the same name, used in the calculation
943 // and written back afterwards, so that we don't emit signals all the time
944 // during the calculation.
945 pv::util::Timestamp tick_period = tick_period_;
946 pv::util::SIPrefix tick_prefix = tick_prefix_;
947 unsigned tick_precision = tick_precision_;
950 const double min_period = scale_ * min_width;
952 const int order = (int)floorf(log10f(min_period));
953 const pv::util::Timestamp order_decimal =
954 pow(pv::util::Timestamp(10), order);
956 // Allow for a margin of error so that a scale unit of 1 can be used.
957 // Otherwise, for a SU of 1 the tick period will almost always be below
958 // the min_period by a small amount - and thus skipped in favor of 2.
959 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
960 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
961 double tp_with_margin;
962 unsigned int unit = 0;
965 tp_with_margin = order_decimal.convert_to<double>() *
966 (ScaleUnits[unit++] + tp_margin);
967 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
969 minor_tick_count_ = (unit == 2) ? 4 : 5;
970 tick_period = order_decimal * ScaleUnits[unit - 1];
971 tick_prefix = static_cast<pv::util::SIPrefix>(
972 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
974 // Precision is the number of fractional digits required, not
975 // taking the prefix into account (and it must never be negative)
976 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
978 tick_period_width = (tick_period / scale_).convert_to<double>();
980 const QString label_text = Ruler::format_time_with_distance(
981 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
983 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
984 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
987 min_width += SpacingIncrement;
988 } while (tick_period_width < label_width);
990 set_tick_period(tick_period);
991 set_tick_prefix(tick_prefix);
992 set_tick_precision(tick_precision);
995 void View::adjust_top_margin()
999 const QSize areaSize = viewport_->size();
1001 const pair<int, int> extents = v_extents();
1002 const int top_margin = owner_visual_v_offset() + extents.first;
1003 const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
1005 // Do we have empty space at the top while the last trace goes out of screen?
1006 if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
1007 const int trace_height = extents.second - extents.first;
1009 // Center everything vertically if there is enough space
1010 if (areaSize.height() >= trace_height)
1011 set_v_offset(extents.first -
1012 ((areaSize.height() - trace_height) / 2));
1014 // Remove the top margin to make as many traces fit on screen as possible
1015 set_v_offset(extents.first);
1019 void View::update_scroll()
1022 QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
1023 QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
1025 const QSize areaSize = viewport_->size();
1027 // Set the horizontal scroll bar
1030 get_scroll_layout(length, offset);
1031 length = max(length - areaSize.width(), 0.0);
1033 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
1035 hscrollbar->setPageStep(areaSize.width() / 2);
1036 hscrollbar->setSingleStep(major_tick_distance);
1038 updating_scroll_ = true;
1040 if (length < MaxScrollValue) {
1041 hscrollbar->setRange(0, length);
1042 hscrollbar->setSliderPosition(offset.convert_to<double>());
1044 hscrollbar->setRange(0, MaxScrollValue);
1045 hscrollbar->setSliderPosition(
1046 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
1049 updating_scroll_ = false;
1051 // Set the vertical scrollbar
1052 vscrollbar->setPageStep(areaSize.height());
1053 vscrollbar->setSingleStep(areaSize.height() / 8);
1055 const pair<int, int> extents = v_extents();
1057 // Don't change the scrollbar range if there are no traces
1058 if (extents.first != extents.second)
1059 vscrollbar->setRange(extents.first - areaSize.height(),
1062 if (scroll_needs_defaults_) {
1063 set_scroll_default();
1064 scroll_needs_defaults_ = false;
1068 void View::reset_scroll()
1070 scrollarea_->verticalScrollBar()->setRange(0, 0);
1073 void View::set_scroll_default()
1077 const QSize areaSize = viewport_->size();
1079 const pair<int, int> extents = v_extents();
1080 const int trace_height = extents.second - extents.first;
1082 // Do all traces fit in the view?
1083 if (areaSize.height() >= trace_height)
1084 // Center all traces vertically
1085 set_v_offset(extents.first -
1086 ((areaSize.height() - trace_height) / 2));
1088 // Put the first trace at the top, letting the bottom ones overflow
1089 set_v_offset(extents.first);
1092 void View::determine_if_header_was_shrunk()
1094 const int header_pane_width = splitter_->sizes().front();
1096 // Allow for a slight margin of error so that we also accept
1097 // slight differences when e.g. a label name change increased
1098 // the overall width
1099 header_was_shrunk_ = (header_pane_width < (header_width() - 10));
1102 void View::resize_header_to_fit()
1104 // Setting the maximum width of the header widget doesn't work as
1105 // expected because the splitter would allow the user to make the
1106 // pane wider than that, creating empty space as a result.
1107 // To make this work, we stricly enforce the maximum width by
1108 // expanding the header unless the user shrunk it on purpose.
1109 // As we're then setting the width of the header pane, we set the
1110 // splitter to the maximum allowed position.
1112 int splitter_area_width = 0;
1113 for (int w : splitter_->sizes())
1114 splitter_area_width += w;
1116 // Make sure the header has enough horizontal space to show all labels fully
1117 QList<int> pane_sizes;
1118 pane_sizes.push_back(header_->extended_size_hint().width());
1119 pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
1120 splitter_->setSizes(pane_sizes);
1123 void View::update_layout()
1128 TraceTreeItemOwner* View::find_prevalent_trace_group(
1129 const shared_ptr<sigrok::ChannelGroup> &group,
1130 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1135 unordered_set<TraceTreeItemOwner*> owners;
1136 vector<TraceTreeItemOwner*> owner_list;
1138 // Make a set and a list of all the owners
1139 for (const auto &channel : group->channels()) {
1140 for (auto entry : signal_map) {
1141 if (entry.first->channel() == channel) {
1142 TraceTreeItemOwner *const o = (entry.second)->owner();
1143 owner_list.push_back(o);
1149 // Iterate through the list of owners, and find the most prevalent
1150 size_t max_prevalence = 0;
1151 TraceTreeItemOwner *prevalent_owner = nullptr;
1152 for (TraceTreeItemOwner *owner : owners) {
1153 const size_t prevalence = count_if(
1154 owner_list.begin(), owner_list.end(),
1155 [&](TraceTreeItemOwner *o) { return o == owner; });
1156 if (prevalence > max_prevalence) {
1157 max_prevalence = prevalence;
1158 prevalent_owner = owner;
1162 return prevalent_owner;
1165 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
1166 const vector< shared_ptr<sigrok::Channel> > &channels,
1167 const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1169 set< shared_ptr<Trace> > &add_list)
1171 vector< shared_ptr<Trace> > filtered_traces;
1173 for (const auto &channel : channels) {
1174 for (auto entry : signal_map) {
1175 if (entry.first->channel() == channel) {
1176 shared_ptr<Trace> trace = entry.second;
1177 const auto list_iter = add_list.find(trace);
1178 if (list_iter == add_list.end())
1181 filtered_traces.push_back(trace);
1182 add_list.erase(list_iter);
1187 return filtered_traces;
1190 void View::determine_time_unit()
1192 // Check whether we know the sample rate and hence can use time as the unit
1193 if (time_unit_ == util::TimeUnit::Samples) {
1194 // Check all signals but...
1195 for (const shared_ptr<Signal> signal : signals_) {
1196 const shared_ptr<SignalData> data = signal->data();
1198 // ...only check first segment of each
1199 const vector< shared_ptr<Segment> > segments = data->segments();
1200 if (!segments.empty())
1201 if (segments[0]->samplerate()) {
1202 set_time_unit(util::TimeUnit::Time);
1209 bool View::eventFilter(QObject *object, QEvent *event)
1211 const QEvent::Type type = event->type();
1212 if (type == QEvent::MouseMove) {
1214 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
1215 if (object == viewport_)
1216 hover_point_ = mouse_event->pos();
1217 else if (object == ruler_)
1218 hover_point_ = QPoint(mouse_event->x(), 0);
1219 else if (object == header_)
1220 hover_point_ = QPoint(0, mouse_event->y());
1222 hover_point_ = QPoint(-1, -1);
1224 update_hover_point();
1226 } else if (type == QEvent::Leave) {
1227 hover_point_ = QPoint(-1, -1);
1228 update_hover_point();
1229 } else if (type == QEvent::Show) {
1231 // This is somewhat of a hack, unfortunately. We cannot use
1232 // set_v_offset() from within restore_settings() as the view
1233 // at that point is neither visible nor properly sized.
1234 // This is the least intrusive workaround I could come up
1235 // with: set the vertical offset (or scroll defaults) when
1236 // the view is shown, which happens after all widgets were
1237 // resized to their final sizes.
1240 if (settings_restored_)
1241 determine_if_header_was_shrunk();
1243 resize_header_to_fit();
1245 if (scroll_needs_defaults_) {
1246 set_scroll_default();
1247 scroll_needs_defaults_ = false;
1250 if (saved_v_offset_) {
1251 set_v_offset(saved_v_offset_);
1252 saved_v_offset_ = 0;
1256 return QObject::eventFilter(object, event);
1259 void View::contextMenuEvent(QContextMenuEvent *event)
1261 QPoint pos = event->pos() - QPoint(0, ruler_->sizeHint().height());
1263 const shared_ptr<ViewItem> r = viewport_->get_mouse_over_item(pos);
1267 QMenu *menu = r->create_view_context_menu(this, pos);
1269 menu->exec(event->globalPos());
1272 void View::resizeEvent(QResizeEvent* event)
1274 // Only adjust the top margin if we shrunk vertically
1275 if (event->size().height() < event->oldSize().height())
1276 adjust_top_margin();
1281 void View::update_hover_point()
1283 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1284 list_by_type<TraceTreeItem>());
1285 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1286 r->hover_point_changed(hover_point_);
1288 hover_point_changed(hover_point_);
1291 void View::row_item_appearance_changed(bool label, bool content)
1296 viewport_->update();
1299 void View::time_item_appearance_changed(bool label, bool content)
1304 // Make sure the header pane width is updated, too
1309 viewport_->update();
1312 void View::extents_changed(bool horz, bool vert)
1315 (horz ? TraceTreeItemHExtentsChanged : 0) |
1316 (vert ? TraceTreeItemVExtentsChanged : 0);
1318 lazy_event_handler_.stop();
1319 lazy_event_handler_.start();
1322 void View::on_signal_name_changed()
1324 if (!header_was_shrunk_)
1325 resize_header_to_fit();
1328 void View::on_splitter_moved()
1330 // The header can only shrink when the splitter is moved manually
1331 determine_if_header_was_shrunk();
1333 if (!header_was_shrunk_)
1334 resize_header_to_fit();
1337 void View::h_scroll_value_changed(int value)
1339 if (updating_scroll_)
1342 // Disable sticky scrolling when user moves the horizontal scroll bar
1343 // during a running acquisition
1344 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1345 sticky_scrolling_ = false;
1346 sticky_scrolling_changed(false);
1349 const int range = scrollarea_->horizontalScrollBar()->maximum();
1350 if (range < MaxScrollValue)
1351 set_offset(scale_ * value);
1355 get_scroll_layout(length, offset);
1356 set_offset(scale_ * length * value / MaxScrollValue);
1360 viewport_->update();
1363 void View::v_scroll_value_changed()
1366 viewport_->update();
1369 void View::signals_changed()
1371 using sigrok::Channel;
1373 vector< shared_ptr<Channel> > channels;
1374 shared_ptr<sigrok::Device> sr_dev;
1375 bool signals_added_or_removed = false;
1377 // Do we need to set the vertical scrollbar to its default position later?
1378 // We do if there are no traces, i.e. the scroll bar has no range set
1379 bool reset_scrollbar =
1380 (scrollarea_->verticalScrollBar()->minimum() ==
1381 scrollarea_->verticalScrollBar()->maximum());
1383 if (!session_.device()) {
1387 sr_dev = session_.device()->device();
1389 channels = sr_dev->channels();
1392 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1394 // Make a list of traces that are being added, and a list of traces
1395 // that are being removed
1396 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1397 const set<shared_ptr<Trace>> prev_traces(
1398 prev_trace_list.begin(), prev_trace_list.end());
1400 set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1402 #ifdef ENABLE_DECODE
1403 traces.insert(decode_traces_.begin(), decode_traces_.end());
1406 set< shared_ptr<Trace> > add_traces;
1407 set_difference(traces.begin(), traces.end(),
1408 prev_traces.begin(), prev_traces.end(),
1409 inserter(add_traces, add_traces.begin()));
1411 set< shared_ptr<Trace> > remove_traces;
1412 set_difference(prev_traces.begin(), prev_traces.end(),
1413 traces.begin(), traces.end(),
1414 inserter(remove_traces, remove_traces.begin()));
1416 // Make a look-up table of sigrok Channels to pulseview Signals
1417 unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1419 for (const shared_ptr<Signal> &sig : signals_)
1420 signal_map[sig->base()] = sig;
1422 // Populate channel groups
1424 for (auto entry : sr_dev->channel_groups()) {
1425 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1427 if (group->channels().size() <= 1)
1430 // Find best trace group to add to
1431 TraceTreeItemOwner *owner = find_prevalent_trace_group(
1434 // If there is no trace group, create one
1435 shared_ptr<TraceGroup> new_trace_group;
1437 new_trace_group.reset(new TraceGroup());
1438 owner = new_trace_group.get();
1441 // Extract traces for the trace group, removing them from
1443 const vector< shared_ptr<Trace> > new_traces_in_group =
1444 extract_new_traces_for_channels(group->channels(),
1445 signal_map, add_traces);
1447 // Add the traces to the group
1448 const pair<int, int> prev_v_extents = owner->v_extents();
1449 int offset = prev_v_extents.second - prev_v_extents.first;
1450 for (shared_ptr<Trace> trace : new_traces_in_group) {
1452 owner->add_child_item(trace);
1454 const pair<int, int> extents = trace->v_extents();
1455 if (trace->enabled())
1456 offset += -extents.first;
1457 trace->force_to_v_offset(offset);
1458 if (trace->enabled())
1459 offset += extents.second;
1462 if (new_trace_group) {
1463 // Assign proper vertical offsets to each channel in the group
1464 new_trace_group->restack_items();
1466 // If this is a new group, enqueue it in the new top level
1468 if (!new_traces_in_group.empty())
1469 new_top_level_items.push_back(new_trace_group);
1473 // Enqueue the remaining logic channels in a group
1474 vector< shared_ptr<Channel> > logic_channels;
1475 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1476 [](const shared_ptr<Channel>& c) {
1477 return c->type() == sigrok::ChannelType::LOGIC; });
1479 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1480 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1482 if (non_grouped_logic_signals.size() > 0) {
1483 const shared_ptr<TraceGroup> non_grouped_trace_group(
1484 make_shared<TraceGroup>());
1485 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1486 non_grouped_trace_group->add_child_item(trace);
1488 non_grouped_trace_group->restack_items();
1489 new_top_level_items.push_back(non_grouped_trace_group);
1492 // Enqueue the remaining channels as free ungrouped traces
1493 const vector< shared_ptr<Trace> > new_top_level_signals =
1494 extract_new_traces_for_channels(channels, signal_map, add_traces);
1495 new_top_level_items.insert(new_top_level_items.end(),
1496 new_top_level_signals.begin(), new_top_level_signals.end());
1498 // Enqueue any remaining traces i.e. decode traces
1499 new_top_level_items.insert(new_top_level_items.end(),
1500 add_traces.begin(), add_traces.end());
1502 // Remove any removed traces
1503 for (shared_ptr<Trace> trace : remove_traces) {
1504 TraceTreeItemOwner *const owner = trace->owner();
1506 owner->remove_child_item(trace);
1507 signals_added_or_removed = true;
1510 // Remove any empty trace groups
1511 for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1512 if (group->child_items().size() == 0) {
1513 remove_child_item(group);
1517 // Add and position the pending top levels items
1518 int offset = v_extents().second;
1519 for (auto item : new_top_level_items) {
1520 add_child_item(item);
1522 // Position the item after the last item or at the top if there is none
1523 const pair<int, int> extents = item->v_extents();
1525 if (item->enabled())
1526 offset += -extents.first;
1528 item->force_to_v_offset(offset);
1530 if (item->enabled())
1531 offset += extents.second;
1532 signals_added_or_removed = true;
1536 if (signals_added_or_removed && !header_was_shrunk_)
1537 resize_header_to_fit();
1542 viewport_->update();
1544 if (reset_scrollbar)
1545 set_scroll_default();
1548 void View::capture_state_updated(int state)
1550 GlobalSettings settings;
1552 if (state == Session::Running) {
1553 set_time_unit(util::TimeUnit::Samples);
1555 trigger_markers_.clear();
1557 scale_at_acq_start_ = scale_;
1558 offset_at_acq_start_ = offset_;
1560 // Activate "always zoom to fit" if the setting is enabled and we're
1561 // the main view of this session (other trace views may be used for
1562 // zooming and we don't want to mess them up)
1563 bool state = settings.value(GlobalSettings::Key_View_ZoomToFitDuringAcq).toBool();
1564 if (is_main_view_ && state) {
1565 always_zoom_to_fit_ = true;
1566 always_zoom_to_fit_changed(always_zoom_to_fit_);
1569 // Enable sticky scrolling if the setting is enabled
1570 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1572 // Reset all traces to segment 0
1573 current_segment_ = 0;
1574 set_current_segment(current_segment_);
1577 if (state == Session::Stopped) {
1578 // After acquisition has stopped we need to re-calculate the ticks once
1579 // as it's otherwise done when the user pans or zooms, which is too late
1580 calculate_tick_spacing();
1582 // Reset "always zoom to fit", the acquisition has stopped
1583 if (always_zoom_to_fit_) {
1584 // Perform a final zoom-to-fit before disabling
1585 zoom_fit(always_zoom_to_fit_);
1586 always_zoom_to_fit_ = false;
1587 always_zoom_to_fit_changed(always_zoom_to_fit_);
1590 bool zoom_to_fit_after_acq =
1591 settings.value(GlobalSettings::Key_View_ZoomToFitAfterAcq).toBool();
1593 // Only perform zoom-to-fit if the user hasn't altered the viewport and
1594 // we didn't restore settings in the meanwhile
1595 if (zoom_to_fit_after_acq &&
1596 !suppress_zoom_to_fit_after_acq_ &&
1597 (scale_ == scale_at_acq_start_) &&
1598 (offset_ == offset_at_acq_start_))
1599 zoom_fit(false); // We're stopped, so the GUI state doesn't matter
1601 suppress_zoom_to_fit_after_acq_ = false;
1605 void View::on_new_segment(int new_segment_id)
1607 on_segment_changed(new_segment_id);
1610 void View::on_segment_completed(int segment_id)
1612 on_segment_changed(segment_id);
1615 void View::on_segment_changed(int segment)
1617 switch (segment_display_mode_) {
1618 case Trace::ShowLastSegmentOnly:
1619 case Trace::ShowSingleSegmentOnly:
1620 set_current_segment(segment);
1623 case Trace::ShowLastCompleteSegmentOnly:
1624 // Only update if all segments are complete
1625 if (session_.all_segments_complete(segment))
1626 set_current_segment(segment);
1629 case Trace::ShowAllSegments:
1630 case Trace::ShowAccumulatedIntensity:
1636 void View::on_settingViewTriggerIsZeroTime_changed(const QVariant new_value)
1638 if (new_value.toBool()) {
1639 // The first trigger for this segment is used as the zero position
1640 vector<util::Timestamp> triggers = session_.get_triggers(current_segment_);
1641 if (triggers.size() > 0)
1642 set_zero_position(triggers.front());
1644 reset_zero_position();
1647 void View::perform_delayed_view_update()
1649 if (always_zoom_to_fit_) {
1651 } else if (sticky_scrolling_) {
1652 // Make right side of the view sticky
1655 get_scroll_layout(length, offset);
1657 const QSize areaSize = viewport_->size();
1658 length = max(length - areaSize.width(), 0.0);
1660 set_offset(scale_ * length);
1663 determine_time_unit();
1666 viewport_->update();
1669 void View::process_sticky_events()
1671 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1673 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1674 restack_all_trace_tree_items();
1678 // Clear the sticky events
1682 } // namespace trace
1683 } // namespace views