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 void View::set_v_offset(int offset)
209 verticalScrollBar()->setSliderPosition(offset);
214 unsigned int View::depth() const
219 unsigned int View::tick_prefix() const
224 double View::tick_period() const
229 void View::zoom(double steps)
231 zoom(steps, viewport_->width() / 2);
234 void View::zoom(double steps, int offset)
236 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
239 void View::zoom_fit()
241 const pair<double, double> extents = get_time_extents();
242 const double delta = extents.second - extents.first;
247 const int w = viewport_->width();
251 const double scale = max(min(delta / w, MaxScale), MinScale);
252 set_scale_offset(scale, extents.first);
255 void View::zoom_one_to_one()
257 using pv::data::SignalData;
259 // Make a set of all the visible data objects
260 set< shared_ptr<SignalData> > visible_data = get_visible_data();
261 if (visible_data.empty())
264 double samplerate = 0.0;
265 for (const shared_ptr<SignalData> d : visible_data) {
267 const vector< shared_ptr<Segment> > segments =
269 for (const shared_ptr<Segment> &s : segments)
270 samplerate = max(samplerate, s->samplerate());
273 if (samplerate == 0.0)
277 const int w = viewport_->width();
281 set_zoom(1.0 / samplerate, w / 2);
284 void View::set_scale_offset(double scale, double offset)
289 calculate_tick_spacing();
294 scale_offset_changed();
297 set< shared_ptr<SignalData> > View::get_visible_data() const
299 shared_lock<shared_mutex> lock(session().signals_mutex());
300 const vector< shared_ptr<Signal> > &sigs(session().signals());
302 // Make a set of all the visible data objects
303 set< shared_ptr<SignalData> > visible_data;
304 for (const shared_ptr<Signal> sig : sigs)
306 visible_data.insert(sig->data());
311 pair<double, double> View::get_time_extents() const
313 double left_time = DBL_MAX, right_time = DBL_MIN;
314 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
315 for (const shared_ptr<SignalData> d : visible_data)
317 const vector< shared_ptr<Segment> > segments =
319 for (const shared_ptr<Segment> &s : segments) {
320 double samplerate = s->samplerate();
321 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
323 const double start_time = s->start_time();
324 left_time = min(left_time, start_time);
325 right_time = max(right_time, start_time +
326 d->get_max_sample_count() / samplerate);
330 if (left_time == DBL_MAX && right_time == DBL_MIN)
331 return make_pair(0.0, 0.0);
333 assert(left_time < right_time);
334 return make_pair(left_time, right_time);
337 bool View::cursors_shown() const
339 return show_cursors_;
342 void View::show_cursors(bool show)
344 show_cursors_ = show;
349 void View::centre_cursors()
351 const double time_width = scale_ * viewport_->width();
352 cursors_->first()->set_time(offset_ + time_width * 0.4);
353 cursors_->second()->set_time(offset_ + time_width * 0.6);
358 std::shared_ptr<CursorPair> View::cursors() const
363 void View::add_flag(double time)
365 flags_.push_back(shared_ptr<Flag>(new Flag(*this, time,
366 QString("%1").arg(next_flag_text_))));
367 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
368 (next_flag_text_ + 1);
369 time_item_appearance_changed(true, true);
372 void View::remove_flag(std::shared_ptr<Flag> flag)
375 time_item_appearance_changed(true, true);
378 vector< std::shared_ptr<Flag> > View::flags() const
380 vector< std::shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
381 stable_sort(flags.begin(), flags.end(),
382 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
383 return a->time() < b->time();
389 const QPoint& View::hover_point() const
394 void View::update_viewport()
401 void View::restack_all_row_items()
403 // Make a set of owners
404 unordered_set< RowItemOwner* > owners;
405 for (const auto &r : *this)
406 owners.insert(r->owner());
408 // Make a list that is sorted from deepest first
409 vector< RowItemOwner* > sorted_owners(owners.begin(), owners.end());
410 sort(sorted_owners.begin(), sorted_owners.end(),
411 [](const RowItemOwner* a, const RowItemOwner *b) {
412 return a->depth() > b->depth(); });
414 // Restack the items recursively
415 for (auto &o : sorted_owners)
418 // Animate the items to their destination
419 for (const auto &r : *this)
420 r->animate_to_layout_v_offset();
423 void View::get_scroll_layout(double &length, double &offset) const
425 const pair<double, double> extents = get_time_extents();
426 length = (extents.second - extents.first) / scale_;
427 offset = offset_ / scale_;
430 void View::set_zoom(double scale, int offset)
432 const double cursor_offset = offset_ + scale_ * offset;
433 const double new_scale = max(min(scale, MaxScale), MinScale);
434 const double new_offset = cursor_offset - new_scale * offset;
435 set_scale_offset(new_scale, new_offset);
438 void View::calculate_tick_spacing()
440 const double SpacingIncrement = 32.0f;
441 const double MinValueSpacing = 32.0f;
443 double min_width = SpacingIncrement, typical_width;
445 QFontMetrics m(QApplication::font());
448 const double min_period = scale_ * min_width;
450 const int order = (int)floorf(log10f(min_period));
451 const double order_decimal = pow(10.0, order);
453 unsigned int unit = 0;
456 tick_period_ = order_decimal * ScaleUnits[unit++];
457 } while (tick_period_ < min_period &&
458 unit < countof(ScaleUnits));
460 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
462 typical_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
463 Qt::AlignLeft | Qt::AlignTop,
464 format_time(offset_, tick_prefix_)).width() +
467 min_width += SpacingIncrement;
469 } while(typical_width > tick_period_ / scale_);
472 void View::update_scroll()
476 const QSize areaSize = viewport_->size();
478 // Set the horizontal scroll bar
479 double length = 0, offset = 0;
480 get_scroll_layout(length, offset);
481 length = max(length - areaSize.width(), 0.0);
483 int major_tick_distance = tick_period_ / scale_;
485 horizontalScrollBar()->setPageStep(areaSize.width() / 2);
486 horizontalScrollBar()->setSingleStep(major_tick_distance);
488 updating_scroll_ = true;
490 if (length < MaxScrollValue) {
491 horizontalScrollBar()->setRange(0, length);
492 horizontalScrollBar()->setSliderPosition(offset);
494 horizontalScrollBar()->setRange(0, MaxScrollValue);
495 horizontalScrollBar()->setSliderPosition(
496 offset_ * MaxScrollValue / (scale_ * length));
499 updating_scroll_ = false;
501 // Set the vertical scrollbar
502 verticalScrollBar()->setPageStep(areaSize.height());
503 verticalScrollBar()->setSingleStep(areaSize.height() / 8);
505 const pair<int, int> extents = v_extents();
506 verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
507 extents.second - (areaSize.height() / 2));
510 void View::update_layout()
513 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
514 ruler_->sizeHint().height(), 0, 0);
515 ruler_->setGeometry(viewport_->x(), 0,
516 viewport_->width(), ruler_->extended_size_hint().height());
517 header_->setGeometry(0, viewport_->y(),
518 header_->extended_size_hint().width(), viewport_->height());
522 void View::paint_label(QPainter &p, const QRect &rect, bool hover)
529 QRectF View::label_rect(const QRectF &rect)
535 bool View::add_channels_to_owner(
536 const vector< shared_ptr<sigrok::Channel> > &channels,
537 RowItemOwner *owner, int &offset,
538 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
540 std::function<bool (shared_ptr<RowItem>)> filter_func)
542 bool any_added = false;
546 for (const auto &channel : channels)
548 const auto iter = signal_map.find(channel);
549 if (iter == signal_map.end() ||
550 (filter_func && !filter_func((*iter).second)))
553 shared_ptr<RowItem> row_item = (*iter).second;
554 owner->add_child_item(row_item);
555 apply_offset(row_item, offset);
556 signal_map.erase(iter);
564 void View::apply_offset(shared_ptr<RowItem> row_item, int &offset) {
566 const pair<int, int> extents = row_item->v_extents();
567 if (row_item->enabled())
568 offset += -extents.first;
569 row_item->force_to_v_offset(offset);
570 if (row_item->enabled())
571 offset += extents.second;
574 bool View::eventFilter(QObject *object, QEvent *event)
576 const QEvent::Type type = event->type();
577 if (type == QEvent::MouseMove) {
579 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
580 if (object == viewport_)
581 hover_point_ = mouse_event->pos();
582 else if (object == ruler_)
583 hover_point_ = QPoint(mouse_event->x(), 0);
584 else if (object == header_)
585 hover_point_ = QPoint(0, mouse_event->y());
587 hover_point_ = QPoint(-1, -1);
589 hover_point_changed();
591 } else if (type == QEvent::Leave) {
592 hover_point_ = QPoint(-1, -1);
593 hover_point_changed();
596 return QObject::eventFilter(object, event);
599 bool View::viewportEvent(QEvent *e)
603 case QEvent::MouseButtonPress:
604 case QEvent::MouseButtonRelease:
605 case QEvent::MouseButtonDblClick:
606 case QEvent::MouseMove:
608 case QEvent::TouchBegin:
609 case QEvent::TouchUpdate:
610 case QEvent::TouchEnd:
614 return QAbstractScrollArea::viewportEvent(e);
618 void View::resizeEvent(QResizeEvent*)
623 void View::row_item_appearance_changed(bool label, bool content)
631 void View::time_item_appearance_changed(bool label, bool content)
639 void View::extents_changed(bool horz, bool vert)
642 (horz ? RowItemHExtentsChanged : 0) |
643 (vert ? RowItemVExtentsChanged : 0);
644 lazy_event_handler_.start();
647 void View::h_scroll_value_changed(int value)
649 if (updating_scroll_)
652 const int range = horizontalScrollBar()->maximum();
653 if (range < MaxScrollValue)
654 offset_ = scale_ * value;
656 double length = 0, offset;
657 get_scroll_layout(length, offset);
658 offset_ = scale_ * length * value / MaxScrollValue;
665 void View::v_scroll_value_changed()
671 void View::signals_changed()
675 // Populate the traces
678 shared_ptr<sigrok::Device> device = session_.device();
681 // Collect a set of signals
682 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
685 shared_lock<shared_mutex> lock(session_.signals_mutex());
686 const vector< shared_ptr<Signal> > &sigs(session_.signals());
688 for (const shared_ptr<Signal> &sig : sigs)
689 signal_map[sig->channel()] = sig;
691 // Populate channel groups
692 for (auto entry : device->channel_groups())
694 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
696 if (group->channels().size() <= 1)
699 shared_ptr<TraceGroup> trace_group(new TraceGroup());
700 int child_offset = 0;
701 if (add_channels_to_owner(group->channels(),
702 trace_group.get(), child_offset, signal_map))
704 add_child_item(trace_group);
705 apply_offset(trace_group, offset);
709 // Add the remaining logic channels
710 shared_ptr<TraceGroup> logic_trace_group(new TraceGroup());
711 int child_offset = 0;
713 if (add_channels_to_owner(device->channels(),
714 logic_trace_group.get(), child_offset, signal_map,
715 [](shared_ptr<RowItem> r) -> bool {
716 return dynamic_pointer_cast<LogicSignal>(r) != nullptr;
720 add_child_item(logic_trace_group);
721 apply_offset(logic_trace_group, offset);
724 // Add the remaining channels
725 add_channels_to_owner(device->channels(), this, offset, signal_map);
726 assert(signal_map.empty());
728 // Add decode signals
730 const vector< shared_ptr<DecodeTrace> > decode_sigs(
731 session().get_decode_signals());
732 for (auto s : decode_sigs) {
734 apply_offset(s, offset);
741 void View::data_updated()
743 // Update the scroll bars
750 void View::process_sticky_events()
752 if (sticky_events_ & RowItemHExtentsChanged)
754 if (sticky_events_ & RowItemVExtentsChanged) {
755 restack_all_row_items();
759 // Clear the sticky events
763 void View::on_hover_point_changed()
765 for (shared_ptr<RowItem> r : *this)
766 r->hover_point_changed();