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, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 #include <libsigrokdecode/libsigrokdecode.h>
33 #include <unordered_set>
35 #include <QApplication>
37 #include <QFontMetrics>
38 #include <QMouseEvent>
41 #include <libsigrokcxx/libsigrokcxx.hpp>
43 #include "decodetrace.hpp"
45 #include "logicsignal.hpp"
48 #include "tracegroup.hpp"
50 #include "viewport.hpp"
52 #include "pv/session.hpp"
53 #include "pv/devices/device.hpp"
54 #include "pv/data/logic.hpp"
55 #include "pv/data/logicsegment.hpp"
56 #include "pv/util.hpp"
58 using boost::shared_lock;
59 using boost::shared_mutex;
61 using pv::data::SignalData;
62 using pv::data::Segment;
63 using pv::util::format_time;
64 using pv::util::TimeUnit;
67 using std::dynamic_pointer_cast;
70 using std::lock_guard;
76 using std::set_difference;
77 using std::shared_ptr;
78 using std::unordered_map;
79 using std::unordered_set;
86 const double View::MaxScale = 1e9;
87 const double View::MinScale = 1e-15;
89 const int View::MaxScrollValue = INT_MAX / 2;
90 const int View::MaxViewAutoUpdateRate = 25; // No more than 25 Hz with sticky scrolling
92 const int View::ScaleUnits[3] = {1, 2, 5};
94 View::View(Session &session, QWidget *parent) :
95 QAbstractScrollArea(parent),
97 viewport_(new Viewport(*this)),
98 ruler_(new Ruler(*this)),
99 header_(new Header(*this)),
102 updating_scroll_(false),
103 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
104 always_zoom_to_fit_(false),
108 time_unit_(util::Time),
109 show_cursors_(false),
110 cursors_(new CursorPair(*this)),
111 next_flag_text_('A'),
114 connect(horizontalScrollBar(), SIGNAL(valueChanged(int)),
115 this, SLOT(h_scroll_value_changed(int)));
116 connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
117 this, SLOT(v_scroll_value_changed()));
119 connect(&session_, SIGNAL(signals_changed()),
120 this, SLOT(signals_changed()));
121 connect(&session_, SIGNAL(capture_state_changed(int)),
122 this, SLOT(capture_state_updated(int)));
123 connect(&session_, SIGNAL(data_received()),
124 this, SLOT(data_updated()));
125 connect(&session_, SIGNAL(frame_ended()),
126 this, SLOT(data_updated()));
128 connect(header_, SIGNAL(selection_changed()),
129 ruler_, SLOT(clear_selection()));
130 connect(ruler_, SIGNAL(selection_changed()),
131 header_, SLOT(clear_selection()));
133 connect(header_, SIGNAL(selection_changed()),
134 this, SIGNAL(selection_changed()));
135 connect(ruler_, SIGNAL(selection_changed()),
136 this, SIGNAL(selection_changed()));
138 connect(this, SIGNAL(hover_point_changed()),
139 this, SLOT(on_hover_point_changed()));
141 connect(&lazy_event_handler_, SIGNAL(timeout()),
142 this, SLOT(process_sticky_events()));
143 lazy_event_handler_.setSingleShot(true);
145 connect(&delayed_view_updater_, SIGNAL(timeout()),
146 this, SLOT(perform_delayed_view_update()));
147 delayed_view_updater_.setSingleShot(true);
148 delayed_view_updater_.setInterval(1000 / MaxViewAutoUpdateRate);
150 setViewport(viewport_);
152 viewport_->installEventFilter(this);
153 ruler_->installEventFilter(this);
154 header_->installEventFilter(this);
156 // Trigger the initial event manually. The default device has signals
157 // which were created before this object came into being
160 // make sure the transparent widgets are on the top
164 // Update the zoom state
165 calculate_tick_spacing();
168 Session& View::session()
173 const Session& View::session() const
183 const View* View::view() const
188 Viewport* View::viewport()
193 const Viewport* View::viewport() const
198 vector< shared_ptr<TimeItem> > View::time_items() const
200 const vector<shared_ptr<Flag>> f(flags());
201 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
202 items.push_back(cursors_);
203 items.push_back(cursors_->first());
204 items.push_back(cursors_->second());
208 double View::scale() const
213 double View::offset() const
218 int View::owner_visual_v_offset() const
220 return -verticalScrollBar()->sliderPosition();
223 void View::set_v_offset(int offset)
225 verticalScrollBar()->setSliderPosition(offset);
230 unsigned int View::depth() const
235 unsigned int View::tick_prefix() const
240 unsigned int View::tick_precision() const
242 return tick_precision_;
245 double View::tick_period() const
250 TimeUnit View::time_unit() const
255 void View::zoom(double steps)
257 zoom(steps, viewport_->width() / 2);
260 void View::zoom(double steps, int offset)
262 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
265 void View::zoom_fit(bool gui_state)
267 // Act as one-shot when stopped, toggle along with the GUI otherwise
268 if (session_.get_capture_state() == Session::Stopped) {
269 always_zoom_to_fit_ = false;
270 always_zoom_to_fit_changed(false);
272 always_zoom_to_fit_ = gui_state;
273 always_zoom_to_fit_changed(gui_state);
276 const pair<double, double> extents = get_time_extents();
277 const double delta = extents.second - extents.first;
282 const int w = viewport_->width();
286 const double scale = max(min(delta / w, MaxScale), MinScale);
287 set_scale_offset(scale, extents.first);
290 void View::zoom_one_to_one()
292 using pv::data::SignalData;
294 // Make a set of all the visible data objects
295 set< shared_ptr<SignalData> > visible_data = get_visible_data();
296 if (visible_data.empty())
299 double samplerate = 0.0;
300 for (const shared_ptr<SignalData> d : visible_data) {
302 const vector< shared_ptr<Segment> > segments =
304 for (const shared_ptr<Segment> &s : segments)
305 samplerate = max(samplerate, s->samplerate());
308 if (samplerate == 0.0)
312 const int w = viewport_->width();
316 set_zoom(1.0 / samplerate, w / 2);
319 void View::set_scale_offset(double scale, double offset)
321 // Disable sticky scrolling / always zoom to fit when acquisition runs
322 // and user drags the viewport
323 if ((scale_ == scale) && (offset_ != offset) &&
324 (session_.get_capture_state() == Session::Running)) {
326 if (sticky_scrolling_) {
327 sticky_scrolling_ = false;
328 sticky_scrolling_changed(false);
331 if (always_zoom_to_fit_) {
332 always_zoom_to_fit_ = false;
333 always_zoom_to_fit_changed(false);
340 calculate_tick_spacing();
345 scale_offset_changed();
348 set< shared_ptr<SignalData> > View::get_visible_data() const
350 shared_lock<shared_mutex> lock(session().signals_mutex());
351 const unordered_set< shared_ptr<Signal> > &sigs(session().signals());
353 // Make a set of all the visible data objects
354 set< shared_ptr<SignalData> > visible_data;
355 for (const shared_ptr<Signal> sig : sigs)
357 visible_data.insert(sig->data());
362 pair<double, double> View::get_time_extents() const
364 double left_time = DBL_MAX, right_time = DBL_MIN;
365 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
366 for (const shared_ptr<SignalData> d : visible_data)
368 const vector< shared_ptr<Segment> > segments =
370 for (const shared_ptr<Segment> &s : segments) {
371 double samplerate = s->samplerate();
372 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
374 const double start_time = s->start_time();
375 left_time = min(left_time, start_time);
376 right_time = max(right_time, start_time +
377 d->max_sample_count() / samplerate);
381 if (left_time == DBL_MAX && right_time == DBL_MIN)
382 return make_pair(0.0, 0.0);
384 assert(left_time < right_time);
385 return make_pair(left_time, right_time);
388 void View::enable_sticky_scrolling(bool state)
390 sticky_scrolling_ = state;
393 bool View::cursors_shown() const
395 return show_cursors_;
398 void View::show_cursors(bool show)
400 show_cursors_ = show;
405 void View::centre_cursors()
407 const double time_width = scale_ * viewport_->width();
408 cursors_->first()->set_time(offset_ + time_width * 0.4);
409 cursors_->second()->set_time(offset_ + time_width * 0.6);
414 std::shared_ptr<CursorPair> View::cursors() const
419 void View::add_flag(double time)
421 flags_.push_back(shared_ptr<Flag>(new Flag(*this, time,
422 QString("%1").arg(next_flag_text_))));
423 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
424 (next_flag_text_ + 1);
425 time_item_appearance_changed(true, true);
428 void View::remove_flag(std::shared_ptr<Flag> flag)
431 time_item_appearance_changed(true, true);
434 vector< std::shared_ptr<Flag> > View::flags() const
436 vector< std::shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
437 stable_sort(flags.begin(), flags.end(),
438 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
439 return a->time() < b->time();
445 const QPoint& View::hover_point() const
450 void View::update_viewport()
457 void View::restack_all_row_items()
459 // Make a list of owners that is sorted from deepest first
460 const auto owners = list_row_item_owners();
461 vector< RowItemOwner* > sorted_owners(owners.begin(), owners.end());
462 sort(sorted_owners.begin(), sorted_owners.end(),
463 [](const RowItemOwner* a, const RowItemOwner *b) {
464 return a->depth() > b->depth(); });
466 // Restack the items recursively
467 for (auto &o : sorted_owners)
470 // Animate the items to their destination
471 for (const auto &r : *this)
472 r->animate_to_layout_v_offset();
475 void View::get_scroll_layout(double &length, double &offset) const
477 const pair<double, double> extents = get_time_extents();
478 length = (extents.second - extents.first) / scale_;
479 offset = offset_ / scale_;
482 void View::set_zoom(double scale, int offset)
484 // Reset the "always zoom to fit" feature as the user changed the zoom
485 always_zoom_to_fit_ = false;
486 always_zoom_to_fit_changed(false);
488 const double cursor_offset = offset_ + scale_ * offset;
489 const double new_scale = max(min(scale, MaxScale), MinScale);
490 const double new_offset = cursor_offset - new_scale * offset;
491 set_scale_offset(new_scale, new_offset);
494 void View::calculate_tick_spacing()
496 const double SpacingIncrement = 32.0f;
497 const double MinValueSpacing = 32.0f;
499 // Figure out the highest numeric value visible on a label
500 const QSize areaSize = viewport_->size();
501 const double max_time = max(fabs(offset_),
502 fabs(offset_ + scale_ * areaSize.width()));
504 double min_width = SpacingIncrement;
505 double label_width, tick_period_width;
507 QFontMetrics m(QApplication::font());
510 const double min_period = scale_ * min_width;
512 const int order = (int)floorf(log10f(min_period));
513 const double order_decimal = pow(10.0, order);
515 unsigned int unit = 0;
518 tick_period_ = order_decimal * ScaleUnits[unit++];
519 } while (tick_period_ < min_period &&
520 unit < countof(ScaleUnits));
522 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
524 // Precision is the number of fractional digits required, not
525 // taking the prefix into account (and it must never be negative)
526 tick_precision_ = std::max((int)ceil(log10f(1 / tick_period_)), 0);
528 tick_period_width = tick_period_ / scale_;
530 const QString label_text =
531 format_time(max_time, tick_prefix_, time_unit_, tick_precision_);
533 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
534 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
537 min_width += SpacingIncrement;
539 } while (tick_period_width < label_width);
542 void View::update_scroll()
546 const QSize areaSize = viewport_->size();
548 // Set the horizontal scroll bar
549 double length = 0, offset = 0;
550 get_scroll_layout(length, offset);
551 length = max(length - areaSize.width(), 0.0);
553 int major_tick_distance = tick_period_ / scale_;
555 horizontalScrollBar()->setPageStep(areaSize.width() / 2);
556 horizontalScrollBar()->setSingleStep(major_tick_distance);
558 updating_scroll_ = true;
560 if (length < MaxScrollValue) {
561 horizontalScrollBar()->setRange(0, length);
562 horizontalScrollBar()->setSliderPosition(offset);
564 horizontalScrollBar()->setRange(0, MaxScrollValue);
565 horizontalScrollBar()->setSliderPosition(
566 offset_ * MaxScrollValue / (scale_ * length));
569 updating_scroll_ = false;
571 // Set the vertical scrollbar
572 verticalScrollBar()->setPageStep(areaSize.height());
573 verticalScrollBar()->setSingleStep(areaSize.height() / 8);
575 const pair<int, int> extents = v_extents();
576 verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
577 extents.second - (areaSize.height() / 2));
580 void View::update_layout()
583 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
584 ruler_->sizeHint().height(), 0, 0);
585 ruler_->setGeometry(viewport_->x(), 0,
586 viewport_->width(), ruler_->extended_size_hint().height());
587 header_->setGeometry(0, viewport_->y(),
588 header_->extended_size_hint().width(), viewport_->height());
592 void View::paint_label(QPainter &p, const QRect &rect, bool hover)
599 QRectF View::label_rect(const QRectF &rect)
605 RowItemOwner* View::find_prevalent_trace_group(
606 const shared_ptr<sigrok::ChannelGroup> &group,
607 const unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
612 unordered_set<RowItemOwner*> owners;
613 vector<RowItemOwner*> owner_list;
615 // Make a set and a list of all the owners
616 for (const auto &channel : group->channels()) {
617 const auto iter = signal_map.find(channel);
618 if (iter == signal_map.end())
621 RowItemOwner *const o = (*iter).second->owner();
622 owner_list.push_back(o);
626 // Iterate through the list of owners, and find the most prevalent
627 size_t max_prevalence = 0;
628 RowItemOwner *prevalent_owner = nullptr;
629 for (RowItemOwner *owner : owners) {
630 const size_t prevalence = std::count_if(
631 owner_list.begin(), owner_list.end(),
632 [&](RowItemOwner *o) { return o == owner; });
633 if (prevalence > max_prevalence) {
634 max_prevalence = prevalence;
635 prevalent_owner = owner;
639 return prevalent_owner;
642 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
643 const vector< shared_ptr<sigrok::Channel> > &channels,
644 const unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
646 set< shared_ptr<Trace> > &add_list)
648 vector< shared_ptr<Trace> > filtered_traces;
650 for (const auto &channel : channels)
652 const auto map_iter = signal_map.find(channel);
653 if (map_iter == signal_map.end())
656 shared_ptr<Trace> trace = (*map_iter).second;
657 const auto list_iter = add_list.find(trace);
658 if (list_iter == add_list.end())
661 filtered_traces.push_back(trace);
662 add_list.erase(list_iter);
665 return filtered_traces;
668 void View::determine_time_unit()
670 // Check whether we know the sample rate and hence can use time as the unit
671 if (time_unit_ == util::Samples) {
672 shared_lock<shared_mutex> lock(session().signals_mutex());
673 const unordered_set< shared_ptr<Signal> > &sigs(session().signals());
675 // Check all signals but...
676 for (const shared_ptr<Signal> signal : sigs) {
677 const shared_ptr<SignalData> data = signal->data();
679 // ...only check first segment of each
680 const vector< shared_ptr<Segment> > segments = data->segments();
681 if (!segments.empty())
682 if (segments[0]->samplerate()) {
683 time_unit_ = util::Time;
690 bool View::eventFilter(QObject *object, QEvent *event)
692 const QEvent::Type type = event->type();
693 if (type == QEvent::MouseMove) {
695 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
696 if (object == viewport_)
697 hover_point_ = mouse_event->pos();
698 else if (object == ruler_)
699 hover_point_ = QPoint(mouse_event->x(), 0);
700 else if (object == header_)
701 hover_point_ = QPoint(0, mouse_event->y());
703 hover_point_ = QPoint(-1, -1);
705 hover_point_changed();
707 } else if (type == QEvent::Leave) {
708 hover_point_ = QPoint(-1, -1);
709 hover_point_changed();
712 return QObject::eventFilter(object, event);
715 bool View::viewportEvent(QEvent *e)
719 case QEvent::MouseButtonPress:
720 case QEvent::MouseButtonRelease:
721 case QEvent::MouseButtonDblClick:
722 case QEvent::MouseMove:
724 case QEvent::TouchBegin:
725 case QEvent::TouchUpdate:
726 case QEvent::TouchEnd:
730 return QAbstractScrollArea::viewportEvent(e);
734 void View::resizeEvent(QResizeEvent*)
739 void View::row_item_appearance_changed(bool label, bool content)
747 void View::time_item_appearance_changed(bool label, bool content)
755 void View::extents_changed(bool horz, bool vert)
758 (horz ? RowItemHExtentsChanged : 0) |
759 (vert ? RowItemVExtentsChanged : 0);
760 lazy_event_handler_.start();
763 void View::h_scroll_value_changed(int value)
765 if (updating_scroll_)
768 // Disable sticky scrolling when user moves the horizontal scroll bar
769 // during a running acquisition
770 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
771 sticky_scrolling_ = false;
772 sticky_scrolling_changed(false);
775 const int range = horizontalScrollBar()->maximum();
776 if (range < MaxScrollValue)
777 offset_ = scale_ * value;
779 double length = 0, offset;
780 get_scroll_layout(length, offset);
781 offset_ = scale_ * length * value / MaxScrollValue;
788 void View::v_scroll_value_changed()
794 void View::signals_changed()
796 vector< shared_ptr<RowItem> > new_top_level_items;
798 const auto device = session_.device();
802 shared_ptr<sigrok::Device> sr_dev = device->device();
805 // Make a list of traces that are being added, and a list of traces
806 // that are being removed
807 const set<shared_ptr<Trace>> prev_traces = list_by_type<Trace>();
809 shared_lock<shared_mutex> lock(session_.signals_mutex());
810 const unordered_set< shared_ptr<Signal> > &sigs(session_.signals());
812 set< shared_ptr<Trace> > traces(sigs.begin(), sigs.end());
815 const vector< shared_ptr<DecodeTrace> > decode_traces(
816 session().get_decode_signals());
817 traces.insert(decode_traces.begin(), decode_traces.end());
820 set< shared_ptr<Trace> > add_traces;
821 set_difference(traces.begin(), traces.end(),
822 prev_traces.begin(), prev_traces.end(),
823 inserter(add_traces, add_traces.begin()));
825 set< shared_ptr<Trace> > remove_traces;
826 set_difference(prev_traces.begin(), prev_traces.end(),
827 traces.begin(), traces.end(),
828 inserter(remove_traces, remove_traces.begin()));
830 // Make a look-up table of sigrok Channels to pulseview Signals
831 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
833 for (const shared_ptr<Signal> &sig : sigs)
834 signal_map[sig->channel()] = sig;
836 // Populate channel groups
837 for (auto entry : sr_dev->channel_groups())
839 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
841 if (group->channels().size() <= 1)
844 // Find best trace group to add to
845 RowItemOwner *owner = find_prevalent_trace_group(
848 // If there is no trace group, create one
849 shared_ptr<TraceGroup> new_trace_group;
851 new_trace_group.reset(new TraceGroup());
852 owner = new_trace_group.get();
855 // Extract traces for the trace group, removing them from
857 const vector< shared_ptr<Trace> > new_traces_in_group =
858 extract_new_traces_for_channels(group->channels(),
859 signal_map, add_traces);
861 // Add the traces to the group
862 const pair<int, int> prev_v_extents = owner->v_extents();
863 int offset = prev_v_extents.second - prev_v_extents.first;
864 for (shared_ptr<Trace> trace : new_traces_in_group) {
866 owner->add_child_item(trace);
868 const pair<int, int> extents = trace->v_extents();
869 if (trace->enabled())
870 offset += -extents.first;
871 trace->force_to_v_offset(offset);
872 if (trace->enabled())
873 offset += extents.second;
876 // If this is a new group, enqueue it in the new top level
878 if (!new_traces_in_group.empty() && new_trace_group)
879 new_top_level_items.push_back(new_trace_group);
882 // Enqueue the remaining channels as free ungrouped traces
883 const vector< shared_ptr<Trace> > new_top_level_signals =
884 extract_new_traces_for_channels(sr_dev->channels(),
885 signal_map, add_traces);
886 new_top_level_items.insert(new_top_level_items.end(),
887 new_top_level_signals.begin(), new_top_level_signals.end());
889 // Enqueue any remaining traces i.e. decode traces
890 new_top_level_items.insert(new_top_level_items.end(),
891 add_traces.begin(), add_traces.end());
893 // Remove any removed traces
894 for (shared_ptr<Trace> trace : remove_traces) {
895 RowItemOwner *const owner = trace->owner();
897 owner->remove_child_item(trace);
900 // Add and position the pending top levels items
901 for (auto item : new_top_level_items) {
902 add_child_item(item);
904 // Position the item after the last present item
905 int offset = v_extents().second;
906 const pair<int, int> extents = item->v_extents();
908 offset += -extents.first;
909 item->force_to_v_offset(offset);
911 offset += extents.second;
920 void View::capture_state_updated(int state)
922 // Reset "always zoom to fit" when we change to the stopped state
923 if (always_zoom_to_fit_ && (state == Session::Stopped)) {
924 always_zoom_to_fit_ = false;
925 always_zoom_to_fit_changed(false);
928 if (state == Session::Running)
929 time_unit_ = util::Samples;
932 void View::data_updated()
934 if (always_zoom_to_fit_ || sticky_scrolling_) {
935 if (!delayed_view_updater_.isActive())
936 delayed_view_updater_.start();
938 determine_time_unit();
945 void View::perform_delayed_view_update()
947 if (always_zoom_to_fit_)
950 if (sticky_scrolling_) {
951 // Make right side of the view sticky
952 double length = 0, offset;
953 get_scroll_layout(length, offset);
955 const QSize areaSize = viewport_->size();
956 length = max(length - areaSize.width(), 0.0);
958 offset_ = scale_ * length;
961 determine_time_unit();
967 void View::process_sticky_events()
969 if (sticky_events_ & RowItemHExtentsChanged)
971 if (sticky_events_ & RowItemVExtentsChanged) {
972 restack_all_row_items();
976 // Clear the sticky events
980 void View::on_hover_point_changed()
982 for (shared_ptr<RowItem> r : *this)
983 r->hover_point_changed();