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)),
96 updating_scroll_(false),
100 cursors_(new CursorPair(*this)),
101 next_flag_text_('A'),
104 connect(horizontalScrollBar(), SIGNAL(valueChanged(int)),
105 this, SLOT(h_scroll_value_changed(int)));
106 connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
107 this, SLOT(v_scroll_value_changed(int)));
109 connect(&session_, SIGNAL(signals_changed()),
110 this, SLOT(signals_changed()));
111 connect(&session_, SIGNAL(capture_state_changed(int)),
112 this, SLOT(data_updated()));
113 connect(&session_, SIGNAL(data_received()),
114 this, SLOT(data_updated()));
115 connect(&session_, SIGNAL(frame_ended()),
116 this, SLOT(data_updated()));
118 connect(header_, SIGNAL(signals_moved()),
119 this, SLOT(on_signals_moved()));
121 connect(header_, SIGNAL(selection_changed()),
122 ruler_, SLOT(clear_selection()));
123 connect(ruler_, SIGNAL(selection_changed()),
124 header_, SLOT(clear_selection()));
126 connect(header_, SIGNAL(selection_changed()),
127 this, SIGNAL(selection_changed()));
128 connect(ruler_, SIGNAL(selection_changed()),
129 this, SIGNAL(selection_changed()));
131 connect(this, SIGNAL(hover_point_changed()),
132 this, SLOT(on_hover_point_changed()));
134 connect(&lazy_event_handler_, SIGNAL(timeout()),
135 this, SLOT(process_sticky_events()));
136 lazy_event_handler_.setSingleShot(true);
138 setViewport(viewport_);
140 viewport_->installEventFilter(this);
141 ruler_->installEventFilter(this);
142 header_->installEventFilter(this);
144 // Trigger the initial event manually. The default device has signals
145 // which were created before this object came into being
148 // make sure the transparent widgets are on the top
152 // Update the zoom state
153 calculate_tick_spacing();
156 Session& View::session()
161 const Session& View::session() const
171 const View* View::view() const
176 Viewport* View::viewport()
181 const Viewport* View::viewport() const
186 vector< shared_ptr<TimeItem> > View::time_items() const
188 const vector<shared_ptr<Flag>> f(flags());
189 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
190 items.push_back(cursors_);
191 items.push_back(cursors_->first());
192 items.push_back(cursors_->second());
196 double View::scale() const
201 double View::offset() const
206 int View::owner_visual_v_offset() const
211 unsigned int View::depth() const
216 unsigned int View::tick_prefix() const
221 double View::tick_period() const
226 void View::zoom(double steps)
228 zoom(steps, viewport_->width() / 2);
231 void View::zoom(double steps, int offset)
233 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
236 void View::zoom_fit()
238 const pair<double, double> extents = get_time_extents();
239 const double delta = extents.second - extents.first;
244 const int w = viewport_->width();
248 const double scale = max(min(delta / w, MaxScale), MinScale);
249 set_scale_offset(scale, extents.first);
252 void View::zoom_one_to_one()
254 using pv::data::SignalData;
256 // Make a set of all the visible data objects
257 set< shared_ptr<SignalData> > visible_data = get_visible_data();
258 if (visible_data.empty())
261 double samplerate = 0.0;
262 for (const shared_ptr<SignalData> d : visible_data) {
264 const vector< shared_ptr<Segment> > segments =
266 for (const shared_ptr<Segment> &s : segments)
267 samplerate = max(samplerate, s->samplerate());
270 if (samplerate == 0.0)
274 const int w = viewport_->width();
278 set_zoom(1.0 / samplerate, w / 2);
281 void View::set_scale_offset(double scale, double offset)
286 calculate_tick_spacing();
291 scale_offset_changed();
294 set< shared_ptr<SignalData> > View::get_visible_data() const
296 shared_lock<shared_mutex> lock(session().signals_mutex());
297 const vector< shared_ptr<Signal> > &sigs(session().signals());
299 // Make a set of all the visible data objects
300 set< shared_ptr<SignalData> > visible_data;
301 for (const shared_ptr<Signal> sig : sigs)
303 visible_data.insert(sig->data());
308 pair<double, double> View::get_time_extents() const
310 double left_time = DBL_MAX, right_time = DBL_MIN;
311 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
312 for (const shared_ptr<SignalData> d : visible_data)
314 const vector< shared_ptr<Segment> > segments =
316 for (const shared_ptr<Segment> &s : segments) {
317 double samplerate = s->samplerate();
318 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
320 const double start_time = s->start_time();
321 left_time = min(left_time, start_time);
322 right_time = max(right_time, start_time +
323 d->get_max_sample_count() / samplerate);
327 if (left_time == DBL_MAX && right_time == DBL_MIN)
328 return make_pair(0.0, 0.0);
330 assert(left_time < right_time);
331 return make_pair(left_time, right_time);
334 bool View::cursors_shown() const
336 return show_cursors_;
339 void View::show_cursors(bool show)
341 show_cursors_ = show;
346 void View::centre_cursors()
348 const double time_width = scale_ * viewport_->width();
349 cursors_->first()->set_time(offset_ + time_width * 0.4);
350 cursors_->second()->set_time(offset_ + time_width * 0.6);
355 std::shared_ptr<CursorPair> View::cursors() const
360 void View::add_flag(double time)
362 flags_.push_back(shared_ptr<Flag>(new Flag(*this, time,
363 QString("%1").arg(next_flag_text_))));
364 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
365 (next_flag_text_ + 1);
366 time_item_appearance_changed(true, true);
369 void View::remove_flag(std::shared_ptr<Flag> flag)
372 time_item_appearance_changed(true, true);
375 vector< std::shared_ptr<Flag> > View::flags() const
377 vector< std::shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
378 stable_sort(flags.begin(), flags.end(),
379 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
380 return a->time() < b->time();
386 const QPoint& View::hover_point() const
391 void View::update_viewport()
398 void View::restack_all_row_items()
400 // Make a set of owners
401 unordered_set< RowItemOwner* > owners;
402 for (const auto &r : *this)
403 owners.insert(r->owner());
405 // Make a list that is sorted from deepest first
406 vector< RowItemOwner* > sorted_owners(owners.begin(), owners.end());
407 sort(sorted_owners.begin(), sorted_owners.end(),
408 [](const RowItemOwner* a, const RowItemOwner *b) {
409 return a->depth() > b->depth(); });
411 // Restack the items recursively
412 for (auto &o : sorted_owners)
415 // Animate the items to their destination
416 for (const auto &r : *this)
417 r->animate_to_layout_v_offset();
420 void View::get_scroll_layout(double &length, double &offset) const
422 const pair<double, double> extents = get_time_extents();
423 length = (extents.second - extents.first) / scale_;
424 offset = offset_ / scale_;
427 void View::set_zoom(double scale, int offset)
429 const double cursor_offset = offset_ + scale_ * offset;
430 const double new_scale = max(min(scale, MaxScale), MinScale);
431 const double new_offset = cursor_offset - new_scale * offset;
432 set_scale_offset(new_scale, new_offset);
435 void View::calculate_tick_spacing()
437 const double SpacingIncrement = 32.0f;
438 const double MinValueSpacing = 32.0f;
440 double min_width = SpacingIncrement, typical_width;
442 QFontMetrics m(QApplication::font());
445 const double min_period = scale_ * min_width;
447 const int order = (int)floorf(log10f(min_period));
448 const double order_decimal = pow(10.0, order);
450 unsigned int unit = 0;
453 tick_period_ = order_decimal * ScaleUnits[unit++];
454 } while (tick_period_ < min_period &&
455 unit < countof(ScaleUnits));
457 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
459 typical_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
460 Qt::AlignLeft | Qt::AlignTop,
461 format_time(offset_, tick_prefix_)).width() +
464 min_width += SpacingIncrement;
466 } while(typical_width > tick_period_ / scale_);
469 void View::update_scroll()
473 const QSize areaSize = viewport_->size();
475 // Set the horizontal scroll bar
476 double length = 0, offset = 0;
477 get_scroll_layout(length, offset);
478 length = max(length - areaSize.width(), 0.0);
480 int major_tick_distance = tick_period_ / scale_;
482 horizontalScrollBar()->setPageStep(areaSize.width() / 2);
483 horizontalScrollBar()->setSingleStep(major_tick_distance);
485 updating_scroll_ = true;
487 if (length < MaxScrollValue) {
488 horizontalScrollBar()->setRange(0, length);
489 horizontalScrollBar()->setSliderPosition(offset);
491 horizontalScrollBar()->setRange(0, MaxScrollValue);
492 horizontalScrollBar()->setSliderPosition(
493 offset_ * MaxScrollValue / (scale_ * length));
496 updating_scroll_ = false;
498 // Set the vertical scrollbar
499 verticalScrollBar()->setPageStep(areaSize.height());
500 verticalScrollBar()->setSingleStep(areaSize.height() / 8);
502 const pair<int, int> extents = v_extents();
503 verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
504 extents.second - (areaSize.height() / 2));
507 void View::update_layout()
510 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
511 ruler_->sizeHint().height(), 0, 0);
512 ruler_->setGeometry(viewport_->x(), 0,
513 viewport_->width(), ruler_->extended_size_hint().height());
514 header_->setGeometry(0, viewport_->y(),
515 header_->extended_size_hint().width(), viewport_->height());
519 void View::paint_label(QPainter &p, const QRect &rect, bool hover)
526 QRectF View::label_rect(const QRectF &rect)
532 bool View::add_channels_to_owner(
533 const vector< shared_ptr<sigrok::Channel> > &channels,
534 RowItemOwner *owner, int &offset,
535 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
537 std::function<bool (shared_ptr<RowItem>)> filter_func)
539 bool any_added = false;
543 for (const auto &channel : channels)
545 const auto iter = signal_map.find(channel);
546 if (iter == signal_map.end() ||
547 (filter_func && !filter_func((*iter).second)))
550 shared_ptr<RowItem> row_item = (*iter).second;
551 owner->add_child_item(row_item);
552 apply_offset(row_item, offset);
553 signal_map.erase(iter);
561 void View::apply_offset(shared_ptr<RowItem> row_item, int &offset) {
563 const pair<int, int> extents = row_item->v_extents();
564 if (row_item->enabled())
565 offset += -extents.first;
566 row_item->force_to_v_offset(offset);
567 if (row_item->enabled())
568 offset += extents.second;
571 bool View::eventFilter(QObject *object, QEvent *event)
573 const QEvent::Type type = event->type();
574 if (type == QEvent::MouseMove) {
576 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
577 if (object == viewport_)
578 hover_point_ = mouse_event->pos();
579 else if (object == ruler_)
580 hover_point_ = QPoint(mouse_event->x(), 0);
581 else if (object == header_)
582 hover_point_ = QPoint(0, mouse_event->y());
584 hover_point_ = QPoint(-1, -1);
586 hover_point_changed();
588 } else if (type == QEvent::Leave) {
589 hover_point_ = QPoint(-1, -1);
590 hover_point_changed();
593 return QObject::eventFilter(object, event);
596 bool View::viewportEvent(QEvent *e)
600 case QEvent::MouseButtonPress:
601 case QEvent::MouseButtonRelease:
602 case QEvent::MouseButtonDblClick:
603 case QEvent::MouseMove:
605 case QEvent::TouchBegin:
606 case QEvent::TouchUpdate:
607 case QEvent::TouchEnd:
611 return QAbstractScrollArea::viewportEvent(e);
615 void View::resizeEvent(QResizeEvent*)
620 void View::row_item_appearance_changed(bool label, bool content)
628 void View::time_item_appearance_changed(bool label, bool content)
636 void View::extents_changed(bool horz, bool vert)
639 (horz ? RowItemHExtentsChanged : 0) |
640 (vert ? RowItemVExtentsChanged : 0);
641 lazy_event_handler_.start();
644 void View::h_scroll_value_changed(int value)
646 if (updating_scroll_)
649 const int range = horizontalScrollBar()->maximum();
650 if (range < MaxScrollValue)
651 offset_ = scale_ * value;
653 double length = 0, offset;
654 get_scroll_layout(length, offset);
655 offset_ = scale_ * length * value / MaxScrollValue;
662 void View::v_scroll_value_changed(int value)
669 void View::signals_changed()
673 // Populate the traces
676 shared_ptr<sigrok::Device> device = session_.device();
679 // Collect a set of signals
680 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
683 shared_lock<shared_mutex> lock(session_.signals_mutex());
684 const vector< shared_ptr<Signal> > &sigs(session_.signals());
686 for (const shared_ptr<Signal> &sig : sigs)
687 signal_map[sig->channel()] = sig;
689 // Populate channel groups
690 for (auto entry : device->channel_groups())
692 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
694 if (group->channels().size() <= 1)
697 shared_ptr<TraceGroup> trace_group(new TraceGroup());
698 int child_offset = 0;
699 if (add_channels_to_owner(group->channels(),
700 trace_group.get(), child_offset, signal_map))
702 add_child_item(trace_group);
703 apply_offset(trace_group, offset);
707 // Add the remaining logic channels
708 shared_ptr<TraceGroup> logic_trace_group(new TraceGroup());
709 int child_offset = 0;
711 if (add_channels_to_owner(device->channels(),
712 logic_trace_group.get(), child_offset, signal_map,
713 [](shared_ptr<RowItem> r) -> bool {
714 return dynamic_pointer_cast<LogicSignal>(r) != nullptr;
718 add_child_item(logic_trace_group);
719 apply_offset(logic_trace_group, offset);
722 // Add the remaining channels
723 add_channels_to_owner(device->channels(), this, offset, signal_map);
724 assert(signal_map.empty());
726 // Add decode signals
728 const vector< shared_ptr<DecodeTrace> > decode_sigs(
729 session().get_decode_signals());
730 for (auto s : decode_sigs) {
732 apply_offset(s, offset);
739 void View::data_updated()
741 // Update the scroll bars
748 void View::on_signals_moved()
754 void View::process_sticky_events()
756 if (sticky_events_ & RowItemHExtentsChanged)
758 if (sticky_events_ & RowItemVExtentsChanged)
759 restack_all_row_items();
761 // Clear the sticky events
765 void View::on_hover_point_changed()
767 for (shared_ptr<RowItem> r : *this)
768 r->hover_point_changed();