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>
31 #include <unordered_set>
33 #include <QApplication>
35 #include <QFontMetrics>
36 #include <QMouseEvent>
39 #include <libsigrok/libsigrok.hpp>
41 #include "decodetrace.hpp"
43 #include "logicsignal.hpp"
46 #include "tracegroup.hpp"
48 #include "viewport.hpp"
50 #include "pv/session.hpp"
51 #include "pv/data/logic.hpp"
52 #include "pv/data/logicsegment.hpp"
53 #include "pv/util.hpp"
55 using boost::shared_lock;
56 using boost::shared_mutex;
58 using pv::data::SignalData;
59 using pv::data::Segment;
60 using pv::util::format_time;
63 using std::dynamic_pointer_cast;
65 using std::lock_guard;
71 using std::shared_ptr;
72 using std::unordered_map;
73 using std::unordered_set;
80 const double View::MaxScale = 1e9;
81 const double View::MinScale = 1e-15;
83 const int View::MaxScrollValue = INT_MAX / 2;
85 const int View::ScaleUnits[3] = {1, 2, 5};
87 View::View(Session &session, QWidget *parent) :
88 QAbstractScrollArea(parent),
90 viewport_(new Viewport(*this)),
91 ruler_(new Ruler(*this)),
92 header_(new Header(*this)),
95 updating_scroll_(false),
99 cursors_(new CursorPair(*this)),
100 next_flag_text_('A'),
103 connect(horizontalScrollBar(), SIGNAL(valueChanged(int)),
104 this, SLOT(h_scroll_value_changed(int)));
105 connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
106 this, SLOT(v_scroll_value_changed()));
108 connect(&session_, SIGNAL(signals_changed()),
109 this, SLOT(signals_changed()));
110 connect(&session_, SIGNAL(capture_state_changed(int)),
111 this, SLOT(data_updated()));
112 connect(&session_, SIGNAL(data_received()),
113 this, SLOT(data_updated()));
114 connect(&session_, SIGNAL(frame_ended()),
115 this, SLOT(data_updated()));
117 connect(header_, SIGNAL(selection_changed()),
118 ruler_, SLOT(clear_selection()));
119 connect(ruler_, SIGNAL(selection_changed()),
120 header_, SLOT(clear_selection()));
122 connect(header_, SIGNAL(selection_changed()),
123 this, SIGNAL(selection_changed()));
124 connect(ruler_, SIGNAL(selection_changed()),
125 this, SIGNAL(selection_changed()));
127 connect(this, SIGNAL(hover_point_changed()),
128 this, SLOT(on_hover_point_changed()));
130 connect(&lazy_event_handler_, SIGNAL(timeout()),
131 this, SLOT(process_sticky_events()));
132 lazy_event_handler_.setSingleShot(true);
134 setViewport(viewport_);
136 viewport_->installEventFilter(this);
137 ruler_->installEventFilter(this);
138 header_->installEventFilter(this);
140 // Trigger the initial event manually. The default device has signals
141 // which were created before this object came into being
144 // make sure the transparent widgets are on the top
148 // Update the zoom state
149 calculate_tick_spacing();
152 Session& View::session()
157 const Session& View::session() const
167 const View* View::view() const
172 Viewport* View::viewport()
177 const Viewport* View::viewport() const
182 vector< shared_ptr<TimeItem> > View::time_items() const
184 const vector<shared_ptr<Flag>> f(flags());
185 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
186 items.push_back(cursors_);
187 items.push_back(cursors_->first());
188 items.push_back(cursors_->second());
192 double View::scale() const
197 double View::offset() const
202 int View::owner_visual_v_offset() const
204 return -verticalScrollBar()->sliderPosition();
207 unsigned int View::depth() const
212 unsigned int View::tick_prefix() const
217 double View::tick_period() const
222 void View::zoom(double steps)
224 zoom(steps, viewport_->width() / 2);
227 void View::zoom(double steps, int offset)
229 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
232 void View::zoom_fit()
234 const pair<double, double> extents = get_time_extents();
235 const double delta = extents.second - extents.first;
240 const int w = viewport_->width();
244 const double scale = max(min(delta / w, MaxScale), MinScale);
245 set_scale_offset(scale, extents.first);
248 void View::zoom_one_to_one()
250 using pv::data::SignalData;
252 // Make a set of all the visible data objects
253 set< shared_ptr<SignalData> > visible_data = get_visible_data();
254 if (visible_data.empty())
257 double samplerate = 0.0;
258 for (const shared_ptr<SignalData> d : visible_data) {
260 const vector< shared_ptr<Segment> > segments =
262 for (const shared_ptr<Segment> &s : segments)
263 samplerate = max(samplerate, s->samplerate());
266 if (samplerate == 0.0)
270 const int w = viewport_->width();
274 set_zoom(1.0 / samplerate, w / 2);
277 void View::set_scale_offset(double scale, double offset)
282 calculate_tick_spacing();
287 scale_offset_changed();
290 set< shared_ptr<SignalData> > View::get_visible_data() const
292 shared_lock<shared_mutex> lock(session().signals_mutex());
293 const vector< shared_ptr<Signal> > &sigs(session().signals());
295 // Make a set of all the visible data objects
296 set< shared_ptr<SignalData> > visible_data;
297 for (const shared_ptr<Signal> sig : sigs)
299 visible_data.insert(sig->data());
304 pair<double, double> View::get_time_extents() const
306 double left_time = DBL_MAX, right_time = DBL_MIN;
307 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
308 for (const shared_ptr<SignalData> d : visible_data)
310 const vector< shared_ptr<Segment> > segments =
312 for (const shared_ptr<Segment> &s : segments) {
313 double samplerate = s->samplerate();
314 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
316 const double start_time = s->start_time();
317 left_time = min(left_time, start_time);
318 right_time = max(right_time, start_time +
319 d->get_max_sample_count() / samplerate);
323 if (left_time == DBL_MAX && right_time == DBL_MIN)
324 return make_pair(0.0, 0.0);
326 assert(left_time < right_time);
327 return make_pair(left_time, right_time);
330 bool View::cursors_shown() const
332 return show_cursors_;
335 void View::show_cursors(bool show)
337 show_cursors_ = show;
342 void View::centre_cursors()
344 const double time_width = scale_ * viewport_->width();
345 cursors_->first()->set_time(offset_ + time_width * 0.4);
346 cursors_->second()->set_time(offset_ + time_width * 0.6);
351 std::shared_ptr<CursorPair> View::cursors() const
356 void View::add_flag(double time)
358 flags_.push_back(shared_ptr<Flag>(new Flag(*this, time,
359 QString("%1").arg(next_flag_text_))));
360 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
361 (next_flag_text_ + 1);
362 time_item_appearance_changed(true, true);
365 void View::remove_flag(std::shared_ptr<Flag> flag)
368 time_item_appearance_changed(true, true);
371 vector< std::shared_ptr<Flag> > View::flags() const
373 vector< std::shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
374 stable_sort(flags.begin(), flags.end(),
375 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
376 return a->time() < b->time();
382 const QPoint& View::hover_point() const
387 void View::update_viewport()
394 void View::restack_all_row_items()
396 // Make a set of owners
397 unordered_set< RowItemOwner* > owners;
398 for (const auto &r : *this)
399 owners.insert(r->owner());
401 // Make a list that is sorted from deepest first
402 vector< RowItemOwner* > sorted_owners(owners.begin(), owners.end());
403 sort(sorted_owners.begin(), sorted_owners.end(),
404 [](const RowItemOwner* a, const RowItemOwner *b) {
405 return a->depth() > b->depth(); });
407 // Restack the items recursively
408 for (auto &o : sorted_owners)
411 // Animate the items to their destination
412 for (const auto &r : *this)
413 r->animate_to_layout_v_offset();
416 void View::get_scroll_layout(double &length, double &offset) const
418 const pair<double, double> extents = get_time_extents();
419 length = (extents.second - extents.first) / scale_;
420 offset = offset_ / scale_;
423 void View::set_zoom(double scale, int offset)
425 const double cursor_offset = offset_ + scale_ * offset;
426 const double new_scale = max(min(scale, MaxScale), MinScale);
427 const double new_offset = cursor_offset - new_scale * offset;
428 set_scale_offset(new_scale, new_offset);
431 void View::calculate_tick_spacing()
433 const double SpacingIncrement = 32.0f;
434 const double MinValueSpacing = 32.0f;
436 double min_width = SpacingIncrement, typical_width;
438 QFontMetrics m(QApplication::font());
441 const double min_period = scale_ * min_width;
443 const int order = (int)floorf(log10f(min_period));
444 const double order_decimal = pow(10.0, order);
446 unsigned int unit = 0;
449 tick_period_ = order_decimal * ScaleUnits[unit++];
450 } while (tick_period_ < min_period &&
451 unit < countof(ScaleUnits));
453 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
455 typical_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
456 Qt::AlignLeft | Qt::AlignTop,
457 format_time(offset_, tick_prefix_)).width() +
460 min_width += SpacingIncrement;
462 } while(typical_width > tick_period_ / scale_);
465 void View::update_scroll()
469 const QSize areaSize = viewport_->size();
471 // Set the horizontal scroll bar
472 double length = 0, offset = 0;
473 get_scroll_layout(length, offset);
474 length = max(length - areaSize.width(), 0.0);
476 int major_tick_distance = tick_period_ / scale_;
478 horizontalScrollBar()->setPageStep(areaSize.width() / 2);
479 horizontalScrollBar()->setSingleStep(major_tick_distance);
481 updating_scroll_ = true;
483 if (length < MaxScrollValue) {
484 horizontalScrollBar()->setRange(0, length);
485 horizontalScrollBar()->setSliderPosition(offset);
487 horizontalScrollBar()->setRange(0, MaxScrollValue);
488 horizontalScrollBar()->setSliderPosition(
489 offset_ * MaxScrollValue / (scale_ * length));
492 updating_scroll_ = false;
494 // Set the vertical scrollbar
495 verticalScrollBar()->setPageStep(areaSize.height());
496 verticalScrollBar()->setSingleStep(areaSize.height() / 8);
498 const pair<int, int> extents = v_extents();
499 verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
500 extents.second - (areaSize.height() / 2));
503 void View::update_layout()
506 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
507 ruler_->sizeHint().height(), 0, 0);
508 ruler_->setGeometry(viewport_->x(), 0,
509 viewport_->width(), ruler_->extended_size_hint().height());
510 header_->setGeometry(0, viewport_->y(),
511 header_->extended_size_hint().width(), viewport_->height());
515 void View::paint_label(QPainter &p, const QRect &rect, bool hover)
522 QRectF View::label_rect(const QRectF &rect)
528 bool View::add_channels_to_owner(
529 const vector< shared_ptr<sigrok::Channel> > &channels,
530 RowItemOwner *owner, int &offset,
531 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
533 std::function<bool (shared_ptr<RowItem>)> filter_func)
535 bool any_added = false;
539 for (const auto &channel : channels)
541 const auto iter = signal_map.find(channel);
542 if (iter == signal_map.end() ||
543 (filter_func && !filter_func((*iter).second)))
546 shared_ptr<RowItem> row_item = (*iter).second;
547 owner->add_child_item(row_item);
548 apply_offset(row_item, offset);
549 signal_map.erase(iter);
557 void View::apply_offset(shared_ptr<RowItem> row_item, int &offset) {
559 const pair<int, int> extents = row_item->v_extents();
560 if (row_item->enabled())
561 offset += -extents.first;
562 row_item->force_to_v_offset(offset);
563 if (row_item->enabled())
564 offset += extents.second;
567 bool View::eventFilter(QObject *object, QEvent *event)
569 const QEvent::Type type = event->type();
570 if (type == QEvent::MouseMove) {
572 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
573 if (object == viewport_)
574 hover_point_ = mouse_event->pos();
575 else if (object == ruler_)
576 hover_point_ = QPoint(mouse_event->x(), 0);
577 else if (object == header_)
578 hover_point_ = QPoint(0, mouse_event->y());
580 hover_point_ = QPoint(-1, -1);
582 hover_point_changed();
584 } else if (type == QEvent::Leave) {
585 hover_point_ = QPoint(-1, -1);
586 hover_point_changed();
589 return QObject::eventFilter(object, event);
592 bool View::viewportEvent(QEvent *e)
596 case QEvent::MouseButtonPress:
597 case QEvent::MouseButtonRelease:
598 case QEvent::MouseButtonDblClick:
599 case QEvent::MouseMove:
601 case QEvent::TouchBegin:
602 case QEvent::TouchUpdate:
603 case QEvent::TouchEnd:
607 return QAbstractScrollArea::viewportEvent(e);
611 void View::resizeEvent(QResizeEvent*)
616 void View::row_item_appearance_changed(bool label, bool content)
624 void View::time_item_appearance_changed(bool label, bool content)
632 void View::extents_changed(bool horz, bool vert)
635 (horz ? RowItemHExtentsChanged : 0) |
636 (vert ? RowItemVExtentsChanged : 0);
637 lazy_event_handler_.start();
640 void View::h_scroll_value_changed(int value)
642 if (updating_scroll_)
645 const int range = horizontalScrollBar()->maximum();
646 if (range < MaxScrollValue)
647 offset_ = scale_ * value;
649 double length = 0, offset;
650 get_scroll_layout(length, offset);
651 offset_ = scale_ * length * value / MaxScrollValue;
658 void View::v_scroll_value_changed()
664 void View::signals_changed()
668 // Populate the traces
671 shared_ptr<sigrok::Device> device = session_.device();
674 // Collect a set of signals
675 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
678 shared_lock<shared_mutex> lock(session_.signals_mutex());
679 const vector< shared_ptr<Signal> > &sigs(session_.signals());
681 for (const shared_ptr<Signal> &sig : sigs)
682 signal_map[sig->channel()] = sig;
684 // Populate channel groups
685 for (auto entry : device->channel_groups())
687 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
689 if (group->channels().size() <= 1)
692 shared_ptr<TraceGroup> trace_group(new TraceGroup());
693 int child_offset = 0;
694 if (add_channels_to_owner(group->channels(),
695 trace_group.get(), child_offset, signal_map))
697 add_child_item(trace_group);
698 apply_offset(trace_group, offset);
702 // Add the remaining logic channels
703 shared_ptr<TraceGroup> logic_trace_group(new TraceGroup());
704 int child_offset = 0;
706 if (add_channels_to_owner(device->channels(),
707 logic_trace_group.get(), child_offset, signal_map,
708 [](shared_ptr<RowItem> r) -> bool {
709 return dynamic_pointer_cast<LogicSignal>(r) != nullptr;
713 add_child_item(logic_trace_group);
714 apply_offset(logic_trace_group, offset);
717 // Add the remaining channels
718 add_channels_to_owner(device->channels(), this, offset, signal_map);
719 assert(signal_map.empty());
721 // Add decode signals
723 const vector< shared_ptr<DecodeTrace> > decode_sigs(
724 session().get_decode_signals());
725 for (auto s : decode_sigs) {
727 apply_offset(s, offset);
734 void View::data_updated()
736 // Update the scroll bars
743 void View::process_sticky_events()
745 if (sticky_events_ & RowItemHExtentsChanged)
747 if (sticky_events_ & RowItemVExtentsChanged) {
748 restack_all_row_items();
752 // Clear the sticky events
756 void View::on_hover_point_changed()
758 for (shared_ptr<RowItem> r : *this)
759 r->hover_point_changed();