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),
107 time_unit_(util::Time),
108 show_cursors_(false),
109 cursors_(new CursorPair(*this)),
110 next_flag_text_('A'),
113 connect(horizontalScrollBar(), SIGNAL(valueChanged(int)),
114 this, SLOT(h_scroll_value_changed(int)));
115 connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
116 this, SLOT(v_scroll_value_changed()));
118 connect(&session_, SIGNAL(signals_changed()),
119 this, SLOT(signals_changed()));
120 connect(&session_, SIGNAL(capture_state_changed(int)),
121 this, SLOT(capture_state_updated(int)));
122 connect(&session_, SIGNAL(data_received()),
123 this, SLOT(data_updated()));
124 connect(&session_, SIGNAL(frame_ended()),
125 this, SLOT(data_updated()));
127 connect(header_, SIGNAL(selection_changed()),
128 ruler_, SLOT(clear_selection()));
129 connect(ruler_, SIGNAL(selection_changed()),
130 header_, SLOT(clear_selection()));
132 connect(header_, SIGNAL(selection_changed()),
133 this, SIGNAL(selection_changed()));
134 connect(ruler_, SIGNAL(selection_changed()),
135 this, SIGNAL(selection_changed()));
137 connect(this, SIGNAL(hover_point_changed()),
138 this, SLOT(on_hover_point_changed()));
140 connect(&lazy_event_handler_, SIGNAL(timeout()),
141 this, SLOT(process_sticky_events()));
142 lazy_event_handler_.setSingleShot(true);
144 connect(&delayed_view_updater_, SIGNAL(timeout()),
145 this, SLOT(perform_delayed_view_update()));
146 delayed_view_updater_.setSingleShot(true);
147 delayed_view_updater_.setInterval(1000 / MaxViewAutoUpdateRate);
149 setViewport(viewport_);
151 viewport_->installEventFilter(this);
152 ruler_->installEventFilter(this);
153 header_->installEventFilter(this);
155 // Trigger the initial event manually. The default device has signals
156 // which were created before this object came into being
159 // make sure the transparent widgets are on the top
163 // Update the zoom state
164 calculate_tick_spacing();
167 Session& View::session()
172 const Session& View::session() const
182 const View* View::view() const
187 Viewport* View::viewport()
192 const Viewport* View::viewport() const
197 vector< shared_ptr<TimeItem> > View::time_items() const
199 const vector<shared_ptr<Flag>> f(flags());
200 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
201 items.push_back(cursors_);
202 items.push_back(cursors_->first());
203 items.push_back(cursors_->second());
207 double View::scale() const
212 double View::offset() const
217 int View::owner_visual_v_offset() const
219 return -verticalScrollBar()->sliderPosition();
222 void View::set_v_offset(int offset)
224 verticalScrollBar()->setSliderPosition(offset);
229 unsigned int View::depth() const
234 unsigned int View::tick_prefix() const
239 double View::tick_period() const
244 TimeUnit View::time_unit() const
249 void View::zoom(double steps)
251 zoom(steps, viewport_->width() / 2);
254 void View::zoom(double steps, int offset)
256 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
259 void View::zoom_fit(bool gui_state)
261 // Act as one-shot when stopped, toggle along with the GUI otherwise
262 if (session_.get_capture_state() == Session::Stopped) {
263 always_zoom_to_fit_ = false;
264 always_zoom_to_fit_changed(false);
266 always_zoom_to_fit_ = gui_state;
267 always_zoom_to_fit_changed(gui_state);
270 const pair<double, double> extents = get_time_extents();
271 const double delta = extents.second - extents.first;
276 const int w = viewport_->width();
280 const double scale = max(min(delta / w, MaxScale), MinScale);
281 set_scale_offset(scale, extents.first);
284 void View::zoom_one_to_one()
286 using pv::data::SignalData;
288 // Make a set of all the visible data objects
289 set< shared_ptr<SignalData> > visible_data = get_visible_data();
290 if (visible_data.empty())
293 double samplerate = 0.0;
294 for (const shared_ptr<SignalData> d : visible_data) {
296 const vector< shared_ptr<Segment> > segments =
298 for (const shared_ptr<Segment> &s : segments)
299 samplerate = max(samplerate, s->samplerate());
302 if (samplerate == 0.0)
306 const int w = viewport_->width();
310 set_zoom(1.0 / samplerate, w / 2);
313 void View::set_scale_offset(double scale, double offset)
315 // Disable sticky scrolling / always zoom to fit when acquisition runs
316 // and user drags the viewport
317 if ((scale_ == scale) && (offset_ != offset) &&
318 (session_.get_capture_state() == Session::Running)) {
320 if (sticky_scrolling_) {
321 sticky_scrolling_ = false;
322 sticky_scrolling_changed(false);
325 if (always_zoom_to_fit_) {
326 always_zoom_to_fit_ = false;
327 always_zoom_to_fit_changed(false);
334 calculate_tick_spacing();
339 scale_offset_changed();
342 set< shared_ptr<SignalData> > View::get_visible_data() const
344 shared_lock<shared_mutex> lock(session().signals_mutex());
345 const unordered_set< shared_ptr<Signal> > &sigs(session().signals());
347 // Make a set of all the visible data objects
348 set< shared_ptr<SignalData> > visible_data;
349 for (const shared_ptr<Signal> sig : sigs)
351 visible_data.insert(sig->data());
356 pair<double, double> View::get_time_extents() const
358 double left_time = DBL_MAX, right_time = DBL_MIN;
359 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
360 for (const shared_ptr<SignalData> d : visible_data)
362 const vector< shared_ptr<Segment> > segments =
364 for (const shared_ptr<Segment> &s : segments) {
365 double samplerate = s->samplerate();
366 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
368 const double start_time = s->start_time();
369 left_time = min(left_time, start_time);
370 right_time = max(right_time, start_time +
371 d->max_sample_count() / samplerate);
375 if (left_time == DBL_MAX && right_time == DBL_MIN)
376 return make_pair(0.0, 0.0);
378 assert(left_time < right_time);
379 return make_pair(left_time, right_time);
382 void View::enable_sticky_scrolling(bool state)
384 sticky_scrolling_ = state;
387 bool View::cursors_shown() const
389 return show_cursors_;
392 void View::show_cursors(bool show)
394 show_cursors_ = show;
399 void View::centre_cursors()
401 const double time_width = scale_ * viewport_->width();
402 cursors_->first()->set_time(offset_ + time_width * 0.4);
403 cursors_->second()->set_time(offset_ + time_width * 0.6);
408 std::shared_ptr<CursorPair> View::cursors() const
413 void View::add_flag(double time)
415 flags_.push_back(shared_ptr<Flag>(new Flag(*this, time,
416 QString("%1").arg(next_flag_text_))));
417 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
418 (next_flag_text_ + 1);
419 time_item_appearance_changed(true, true);
422 void View::remove_flag(std::shared_ptr<Flag> flag)
425 time_item_appearance_changed(true, true);
428 vector< std::shared_ptr<Flag> > View::flags() const
430 vector< std::shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
431 stable_sort(flags.begin(), flags.end(),
432 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
433 return a->time() < b->time();
439 const QPoint& View::hover_point() const
444 void View::update_viewport()
451 void View::restack_all_row_items()
453 // Make a list of owners that is sorted from deepest first
454 const auto owners = list_row_item_owners();
455 vector< RowItemOwner* > sorted_owners(owners.begin(), owners.end());
456 sort(sorted_owners.begin(), sorted_owners.end(),
457 [](const RowItemOwner* a, const RowItemOwner *b) {
458 return a->depth() > b->depth(); });
460 // Restack the items recursively
461 for (auto &o : sorted_owners)
464 // Animate the items to their destination
465 for (const auto &r : *this)
466 r->animate_to_layout_v_offset();
469 void View::get_scroll_layout(double &length, double &offset) const
471 const pair<double, double> extents = get_time_extents();
472 length = (extents.second - extents.first) / scale_;
473 offset = offset_ / scale_;
476 void View::set_zoom(double scale, int offset)
478 // Reset the "always zoom to fit" feature as the user changed the zoom
479 always_zoom_to_fit_ = false;
480 always_zoom_to_fit_changed(false);
482 const double cursor_offset = offset_ + scale_ * offset;
483 const double new_scale = max(min(scale, MaxScale), MinScale);
484 const double new_offset = cursor_offset - new_scale * offset;
485 set_scale_offset(new_scale, new_offset);
488 void View::calculate_tick_spacing()
490 const double SpacingIncrement = 32.0f;
491 const double MinValueSpacing = 32.0f;
493 double min_width = SpacingIncrement, typical_width;
495 QFontMetrics m(QApplication::font());
498 const double min_period = scale_ * min_width;
500 const int order = (int)floorf(log10f(min_period));
501 const double order_decimal = pow(10.0, order);
503 unsigned int unit = 0;
506 tick_period_ = order_decimal * ScaleUnits[unit++];
507 } while (tick_period_ < min_period &&
508 unit < countof(ScaleUnits));
510 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
512 typical_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
513 Qt::AlignLeft | Qt::AlignTop,
514 format_time(offset_, tick_prefix_, time_unit_)).width() +
517 min_width += SpacingIncrement;
519 } while (typical_width > tick_period_ / scale_);
522 void View::update_scroll()
526 const QSize areaSize = viewport_->size();
528 // Set the horizontal scroll bar
529 double length = 0, offset = 0;
530 get_scroll_layout(length, offset);
531 length = max(length - areaSize.width(), 0.0);
533 int major_tick_distance = tick_period_ / scale_;
535 horizontalScrollBar()->setPageStep(areaSize.width() / 2);
536 horizontalScrollBar()->setSingleStep(major_tick_distance);
538 updating_scroll_ = true;
540 if (length < MaxScrollValue) {
541 horizontalScrollBar()->setRange(0, length);
542 horizontalScrollBar()->setSliderPosition(offset);
544 horizontalScrollBar()->setRange(0, MaxScrollValue);
545 horizontalScrollBar()->setSliderPosition(
546 offset_ * MaxScrollValue / (scale_ * length));
549 updating_scroll_ = false;
551 // Set the vertical scrollbar
552 verticalScrollBar()->setPageStep(areaSize.height());
553 verticalScrollBar()->setSingleStep(areaSize.height() / 8);
555 const pair<int, int> extents = v_extents();
556 verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
557 extents.second - (areaSize.height() / 2));
560 void View::update_layout()
563 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
564 ruler_->sizeHint().height(), 0, 0);
565 ruler_->setGeometry(viewport_->x(), 0,
566 viewport_->width(), ruler_->extended_size_hint().height());
567 header_->setGeometry(0, viewport_->y(),
568 header_->extended_size_hint().width(), viewport_->height());
572 void View::paint_label(QPainter &p, const QRect &rect, bool hover)
579 QRectF View::label_rect(const QRectF &rect)
585 RowItemOwner* View::find_prevalent_trace_group(
586 const shared_ptr<sigrok::ChannelGroup> &group,
587 const unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
592 unordered_set<RowItemOwner*> owners;
593 vector<RowItemOwner*> owner_list;
595 // Make a set and a list of all the owners
596 for (const auto &channel : group->channels()) {
597 const auto iter = signal_map.find(channel);
598 if (iter == signal_map.end())
601 RowItemOwner *const o = (*iter).second->owner();
602 owner_list.push_back(o);
606 // Iterate through the list of owners, and find the most prevalent
607 size_t max_prevalence = 0;
608 RowItemOwner *prevalent_owner = nullptr;
609 for (RowItemOwner *owner : owners) {
610 const size_t prevalence = std::count_if(
611 owner_list.begin(), owner_list.end(),
612 [&](RowItemOwner *o) { return o == owner; });
613 if (prevalence > max_prevalence) {
614 max_prevalence = prevalence;
615 prevalent_owner = owner;
619 return prevalent_owner;
622 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
623 const vector< shared_ptr<sigrok::Channel> > &channels,
624 const unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
626 set< shared_ptr<Trace> > &add_list)
628 vector< shared_ptr<Trace> > filtered_traces;
630 for (const auto &channel : channels)
632 const auto map_iter = signal_map.find(channel);
633 if (map_iter == signal_map.end())
636 shared_ptr<Trace> trace = (*map_iter).second;
637 const auto list_iter = add_list.find(trace);
638 if (list_iter == add_list.end())
641 filtered_traces.push_back(trace);
642 add_list.erase(list_iter);
645 return filtered_traces;
648 void View::determine_time_unit()
650 // Check whether we know the sample rate and hence can use time as the unit
651 if (time_unit_ == util::Samples) {
652 shared_lock<shared_mutex> lock(session().signals_mutex());
653 const unordered_set< shared_ptr<Signal> > &sigs(session().signals());
655 // Check all signals but...
656 for (const shared_ptr<Signal> signal : sigs) {
657 const shared_ptr<SignalData> data = signal->data();
659 // ...only check first segment of each
660 const vector< shared_ptr<Segment> > segments = data->segments();
661 if (!segments.empty())
662 if (segments[0]->samplerate()) {
663 time_unit_ = util::Time;
670 bool View::eventFilter(QObject *object, QEvent *event)
672 const QEvent::Type type = event->type();
673 if (type == QEvent::MouseMove) {
675 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
676 if (object == viewport_)
677 hover_point_ = mouse_event->pos();
678 else if (object == ruler_)
679 hover_point_ = QPoint(mouse_event->x(), 0);
680 else if (object == header_)
681 hover_point_ = QPoint(0, mouse_event->y());
683 hover_point_ = QPoint(-1, -1);
685 hover_point_changed();
687 } else if (type == QEvent::Leave) {
688 hover_point_ = QPoint(-1, -1);
689 hover_point_changed();
692 return QObject::eventFilter(object, event);
695 bool View::viewportEvent(QEvent *e)
699 case QEvent::MouseButtonPress:
700 case QEvent::MouseButtonRelease:
701 case QEvent::MouseButtonDblClick:
702 case QEvent::MouseMove:
704 case QEvent::TouchBegin:
705 case QEvent::TouchUpdate:
706 case QEvent::TouchEnd:
710 return QAbstractScrollArea::viewportEvent(e);
714 void View::resizeEvent(QResizeEvent*)
719 void View::row_item_appearance_changed(bool label, bool content)
727 void View::time_item_appearance_changed(bool label, bool content)
735 void View::extents_changed(bool horz, bool vert)
738 (horz ? RowItemHExtentsChanged : 0) |
739 (vert ? RowItemVExtentsChanged : 0);
740 lazy_event_handler_.start();
743 void View::h_scroll_value_changed(int value)
745 if (updating_scroll_)
748 // Disable sticky scrolling when user moves the horizontal scroll bar
749 // during a running acquisition
750 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
751 sticky_scrolling_ = false;
752 sticky_scrolling_changed(false);
755 const int range = horizontalScrollBar()->maximum();
756 if (range < MaxScrollValue)
757 offset_ = scale_ * value;
759 double length = 0, offset;
760 get_scroll_layout(length, offset);
761 offset_ = scale_ * length * value / MaxScrollValue;
768 void View::v_scroll_value_changed()
774 void View::signals_changed()
776 vector< shared_ptr<RowItem> > new_top_level_items;
778 const auto device = session_.device();
782 shared_ptr<sigrok::Device> sr_dev = device->device();
785 // Make a list of traces that are being added, and a list of traces
786 // that are being removed
787 const set<shared_ptr<Trace>> prev_traces = list_by_type<Trace>();
789 shared_lock<shared_mutex> lock(session_.signals_mutex());
790 const unordered_set< shared_ptr<Signal> > &sigs(session_.signals());
792 set< shared_ptr<Trace> > traces(sigs.begin(), sigs.end());
795 const vector< shared_ptr<DecodeTrace> > decode_traces(
796 session().get_decode_signals());
797 traces.insert(decode_traces.begin(), decode_traces.end());
800 set< shared_ptr<Trace> > add_traces;
801 set_difference(traces.begin(), traces.end(),
802 prev_traces.begin(), prev_traces.end(),
803 inserter(add_traces, add_traces.begin()));
805 set< shared_ptr<Trace> > remove_traces;
806 set_difference(prev_traces.begin(), prev_traces.end(),
807 traces.begin(), traces.end(),
808 inserter(remove_traces, remove_traces.begin()));
810 // Make a look-up table of sigrok Channels to pulseview Signals
811 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
813 for (const shared_ptr<Signal> &sig : sigs)
814 signal_map[sig->channel()] = sig;
816 // Populate channel groups
817 for (auto entry : sr_dev->channel_groups())
819 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
821 if (group->channels().size() <= 1)
824 // Find best trace group to add to
825 RowItemOwner *owner = find_prevalent_trace_group(
828 // If there is no trace group, create one
829 shared_ptr<TraceGroup> new_trace_group;
831 new_trace_group.reset(new TraceGroup());
832 owner = new_trace_group.get();
835 // Extract traces for the trace group, removing them from
837 const vector< shared_ptr<Trace> > new_traces_in_group =
838 extract_new_traces_for_channels(group->channels(),
839 signal_map, add_traces);
841 // Add the traces to the group
842 const pair<int, int> prev_v_extents = owner->v_extents();
843 int offset = prev_v_extents.second - prev_v_extents.first;
844 for (shared_ptr<Trace> trace : new_traces_in_group) {
846 owner->add_child_item(trace);
848 const pair<int, int> extents = trace->v_extents();
849 if (trace->enabled())
850 offset += -extents.first;
851 trace->force_to_v_offset(offset);
852 if (trace->enabled())
853 offset += extents.second;
856 // If this is a new group, enqueue it in the new top level
858 if (!new_traces_in_group.empty() && new_trace_group)
859 new_top_level_items.push_back(new_trace_group);
862 // Enqueue the remaining channels as free ungrouped traces
863 const vector< shared_ptr<Trace> > new_top_level_signals =
864 extract_new_traces_for_channels(sr_dev->channels(),
865 signal_map, add_traces);
866 new_top_level_items.insert(new_top_level_items.end(),
867 new_top_level_signals.begin(), new_top_level_signals.end());
869 // Enqueue any remaining traces i.e. decode traces
870 new_top_level_items.insert(new_top_level_items.end(),
871 add_traces.begin(), add_traces.end());
873 // Remove any removed traces
874 for (shared_ptr<Trace> trace : remove_traces) {
875 RowItemOwner *const owner = trace->owner();
877 owner->remove_child_item(trace);
880 // Add and position the pending top levels items
881 for (auto item : new_top_level_items) {
882 add_child_item(item);
884 // Position the item after the last present item
885 int offset = v_extents().second;
886 const pair<int, int> extents = item->v_extents();
888 offset += -extents.first;
889 item->force_to_v_offset(offset);
891 offset += extents.second;
900 void View::capture_state_updated(int state)
902 // Reset "always zoom to fit" when we change to the stopped state
903 if (always_zoom_to_fit_ && (state == Session::Stopped)) {
904 always_zoom_to_fit_ = false;
905 always_zoom_to_fit_changed(false);
908 if (state == Session::Running)
909 time_unit_ = util::Samples;
912 void View::data_updated()
914 if (always_zoom_to_fit_ || sticky_scrolling_) {
915 if (!delayed_view_updater_.isActive())
916 delayed_view_updater_.start();
918 determine_time_unit();
925 void View::perform_delayed_view_update()
927 if (always_zoom_to_fit_)
930 if (sticky_scrolling_) {
931 // Make right side of the view sticky
932 double length = 0, offset;
933 get_scroll_layout(length, offset);
935 const QSize areaSize = viewport_->size();
936 length = max(length - areaSize.width(), 0.0);
938 offset_ = scale_ * length;
941 determine_time_unit();
947 void View::process_sticky_events()
949 if (sticky_events_ & RowItemHExtentsChanged)
951 if (sticky_events_ & RowItemVExtentsChanged) {
952 restack_all_row_items();
956 // Clear the sticky events
960 void View::on_hover_point_changed()
962 for (shared_ptr<RowItem> r : *this)
963 r->hover_point_changed();