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 <libsigrokcxx/libsigrokcxx.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/devices/device.hpp"
52 #include "pv/data/logic.hpp"
53 #include "pv/data/logicsegment.hpp"
54 #include "pv/util.hpp"
56 using boost::shared_lock;
57 using boost::shared_mutex;
59 using pv::data::SignalData;
60 using pv::data::Segment;
61 using pv::util::format_time;
64 using std::dynamic_pointer_cast;
66 using std::lock_guard;
72 using std::shared_ptr;
73 using std::unordered_map;
74 using std::unordered_set;
81 const double View::MaxScale = 1e9;
82 const double View::MinScale = 1e-15;
84 const int View::MaxScrollValue = INT_MAX / 2;
86 const int View::ScaleUnits[3] = {1, 2, 5};
88 View::View(Session &session, QWidget *parent) :
89 QAbstractScrollArea(parent),
91 viewport_(new Viewport(*this)),
92 ruler_(new Ruler(*this)),
93 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()));
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(selection_changed()),
119 ruler_, SLOT(clear_selection()));
120 connect(ruler_, SIGNAL(selection_changed()),
121 header_, SLOT(clear_selection()));
123 connect(header_, SIGNAL(selection_changed()),
124 this, SIGNAL(selection_changed()));
125 connect(ruler_, SIGNAL(selection_changed()),
126 this, SIGNAL(selection_changed()));
128 connect(this, SIGNAL(hover_point_changed()),
129 this, SLOT(on_hover_point_changed()));
131 connect(&lazy_event_handler_, SIGNAL(timeout()),
132 this, SLOT(process_sticky_events()));
133 lazy_event_handler_.setSingleShot(true);
135 setViewport(viewport_);
137 viewport_->installEventFilter(this);
138 ruler_->installEventFilter(this);
139 header_->installEventFilter(this);
141 // Trigger the initial event manually. The default device has signals
142 // which were created before this object came into being
145 // make sure the transparent widgets are on the top
149 // Update the zoom state
150 calculate_tick_spacing();
153 Session& View::session()
158 const Session& View::session() const
168 const View* View::view() const
173 Viewport* View::viewport()
178 const Viewport* View::viewport() const
183 vector< shared_ptr<TimeItem> > View::time_items() const
185 const vector<shared_ptr<Flag>> f(flags());
186 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
187 items.push_back(cursors_);
188 items.push_back(cursors_->first());
189 items.push_back(cursors_->second());
193 double View::scale() const
198 double View::offset() const
203 int View::owner_visual_v_offset() const
205 return -verticalScrollBar()->sliderPosition();
208 void View::set_v_offset(int offset)
210 verticalScrollBar()->setSliderPosition(offset);
215 unsigned int View::depth() const
220 unsigned int View::tick_prefix() const
225 double View::tick_period() const
230 void View::zoom(double steps)
232 zoom(steps, viewport_->width() / 2);
235 void View::zoom(double steps, int offset)
237 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
240 void View::zoom_fit()
242 const pair<double, double> extents = get_time_extents();
243 const double delta = extents.second - extents.first;
248 const int w = viewport_->width();
252 const double scale = max(min(delta / w, MaxScale), MinScale);
253 set_scale_offset(scale, extents.first);
256 void View::zoom_one_to_one()
258 using pv::data::SignalData;
260 // Make a set of all the visible data objects
261 set< shared_ptr<SignalData> > visible_data = get_visible_data();
262 if (visible_data.empty())
265 double samplerate = 0.0;
266 for (const shared_ptr<SignalData> d : visible_data) {
268 const vector< shared_ptr<Segment> > segments =
270 for (const shared_ptr<Segment> &s : segments)
271 samplerate = max(samplerate, s->samplerate());
274 if (samplerate == 0.0)
278 const int w = viewport_->width();
282 set_zoom(1.0 / samplerate, w / 2);
285 void View::set_scale_offset(double scale, double offset)
290 calculate_tick_spacing();
295 scale_offset_changed();
298 set< shared_ptr<SignalData> > View::get_visible_data() const
300 shared_lock<shared_mutex> lock(session().signals_mutex());
301 const unordered_set< shared_ptr<Signal> > &sigs(session().signals());
303 // Make a set of all the visible data objects
304 set< shared_ptr<SignalData> > visible_data;
305 for (const shared_ptr<Signal> sig : sigs)
307 visible_data.insert(sig->data());
312 pair<double, double> View::get_time_extents() const
314 double left_time = DBL_MAX, right_time = DBL_MIN;
315 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
316 for (const shared_ptr<SignalData> d : visible_data)
318 const vector< shared_ptr<Segment> > segments =
320 for (const shared_ptr<Segment> &s : segments) {
321 double samplerate = s->samplerate();
322 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
324 const double start_time = s->start_time();
325 left_time = min(left_time, start_time);
326 right_time = max(right_time, start_time +
327 d->max_sample_count() / samplerate);
331 if (left_time == DBL_MAX && right_time == DBL_MIN)
332 return make_pair(0.0, 0.0);
334 assert(left_time < right_time);
335 return make_pair(left_time, right_time);
338 bool View::cursors_shown() const
340 return show_cursors_;
343 void View::show_cursors(bool show)
345 show_cursors_ = show;
350 void View::centre_cursors()
352 const double time_width = scale_ * viewport_->width();
353 cursors_->first()->set_time(offset_ + time_width * 0.4);
354 cursors_->second()->set_time(offset_ + time_width * 0.6);
359 std::shared_ptr<CursorPair> View::cursors() const
364 void View::add_flag(double time)
366 flags_.push_back(shared_ptr<Flag>(new Flag(*this, time,
367 QString("%1").arg(next_flag_text_))));
368 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
369 (next_flag_text_ + 1);
370 time_item_appearance_changed(true, true);
373 void View::remove_flag(std::shared_ptr<Flag> flag)
376 time_item_appearance_changed(true, true);
379 vector< std::shared_ptr<Flag> > View::flags() const
381 vector< std::shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
382 stable_sort(flags.begin(), flags.end(),
383 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
384 return a->time() < b->time();
390 const QPoint& View::hover_point() const
395 void View::update_viewport()
402 void View::restack_all_row_items()
404 // Make a set of owners
405 unordered_set< RowItemOwner* > owners;
406 for (const auto &r : *this)
407 owners.insert(r->owner());
409 // Make a list that is sorted from deepest first
410 vector< RowItemOwner* > sorted_owners(owners.begin(), owners.end());
411 sort(sorted_owners.begin(), sorted_owners.end(),
412 [](const RowItemOwner* a, const RowItemOwner *b) {
413 return a->depth() > b->depth(); });
415 // Restack the items recursively
416 for (auto &o : sorted_owners)
419 // Animate the items to their destination
420 for (const auto &r : *this)
421 r->animate_to_layout_v_offset();
424 void View::get_scroll_layout(double &length, double &offset) const
426 const pair<double, double> extents = get_time_extents();
427 length = (extents.second - extents.first) / scale_;
428 offset = offset_ / scale_;
431 void View::set_zoom(double scale, int offset)
433 const double cursor_offset = offset_ + scale_ * offset;
434 const double new_scale = max(min(scale, MaxScale), MinScale);
435 const double new_offset = cursor_offset - new_scale * offset;
436 set_scale_offset(new_scale, new_offset);
439 void View::calculate_tick_spacing()
441 const double SpacingIncrement = 32.0f;
442 const double MinValueSpacing = 32.0f;
444 double min_width = SpacingIncrement, typical_width;
446 QFontMetrics m(QApplication::font());
449 const double min_period = scale_ * min_width;
451 const int order = (int)floorf(log10f(min_period));
452 const double order_decimal = pow(10.0, order);
454 unsigned int unit = 0;
457 tick_period_ = order_decimal * ScaleUnits[unit++];
458 } while (tick_period_ < min_period &&
459 unit < countof(ScaleUnits));
461 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
463 typical_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
464 Qt::AlignLeft | Qt::AlignTop,
465 format_time(offset_, tick_prefix_)).width() +
468 min_width += SpacingIncrement;
470 } while(typical_width > tick_period_ / scale_);
473 void View::update_scroll()
477 const QSize areaSize = viewport_->size();
479 // Set the horizontal scroll bar
480 double length = 0, offset = 0;
481 get_scroll_layout(length, offset);
482 length = max(length - areaSize.width(), 0.0);
484 int major_tick_distance = tick_period_ / scale_;
486 horizontalScrollBar()->setPageStep(areaSize.width() / 2);
487 horizontalScrollBar()->setSingleStep(major_tick_distance);
489 updating_scroll_ = true;
491 if (length < MaxScrollValue) {
492 horizontalScrollBar()->setRange(0, length);
493 horizontalScrollBar()->setSliderPosition(offset);
495 horizontalScrollBar()->setRange(0, MaxScrollValue);
496 horizontalScrollBar()->setSliderPosition(
497 offset_ * MaxScrollValue / (scale_ * length));
500 updating_scroll_ = false;
502 // Set the vertical scrollbar
503 verticalScrollBar()->setPageStep(areaSize.height());
504 verticalScrollBar()->setSingleStep(areaSize.height() / 8);
506 const pair<int, int> extents = v_extents();
507 verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
508 extents.second - (areaSize.height() / 2));
511 void View::update_layout()
514 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
515 ruler_->sizeHint().height(), 0, 0);
516 ruler_->setGeometry(viewport_->x(), 0,
517 viewport_->width(), ruler_->extended_size_hint().height());
518 header_->setGeometry(0, viewport_->y(),
519 header_->extended_size_hint().width(), viewport_->height());
523 void View::paint_label(QPainter &p, const QRect &rect, bool hover)
530 QRectF View::label_rect(const QRectF &rect)
536 bool View::add_channels_to_owner(
537 const vector< shared_ptr<sigrok::Channel> > &channels,
538 RowItemOwner *owner, int &offset,
539 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
541 std::function<bool (shared_ptr<RowItem>)> filter_func)
543 bool any_added = false;
547 for (const auto &channel : channels)
549 const auto iter = signal_map.find(channel);
550 if (iter == signal_map.end() ||
551 (filter_func && !filter_func((*iter).second)))
554 shared_ptr<RowItem> row_item = (*iter).second;
555 owner->add_child_item(row_item);
556 apply_offset(row_item, offset);
557 signal_map.erase(iter);
565 void View::apply_offset(shared_ptr<RowItem> row_item, int &offset) {
567 const pair<int, int> extents = row_item->v_extents();
568 if (row_item->enabled())
569 offset += -extents.first;
570 row_item->force_to_v_offset(offset);
571 if (row_item->enabled())
572 offset += extents.second;
575 bool View::eventFilter(QObject *object, QEvent *event)
577 const QEvent::Type type = event->type();
578 if (type == QEvent::MouseMove) {
580 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
581 if (object == viewport_)
582 hover_point_ = mouse_event->pos();
583 else if (object == ruler_)
584 hover_point_ = QPoint(mouse_event->x(), 0);
585 else if (object == header_)
586 hover_point_ = QPoint(0, mouse_event->y());
588 hover_point_ = QPoint(-1, -1);
590 hover_point_changed();
592 } else if (type == QEvent::Leave) {
593 hover_point_ = QPoint(-1, -1);
594 hover_point_changed();
597 return QObject::eventFilter(object, event);
600 bool View::viewportEvent(QEvent *e)
604 case QEvent::MouseButtonPress:
605 case QEvent::MouseButtonRelease:
606 case QEvent::MouseButtonDblClick:
607 case QEvent::MouseMove:
609 case QEvent::TouchBegin:
610 case QEvent::TouchUpdate:
611 case QEvent::TouchEnd:
615 return QAbstractScrollArea::viewportEvent(e);
619 void View::resizeEvent(QResizeEvent*)
624 void View::row_item_appearance_changed(bool label, bool content)
632 void View::time_item_appearance_changed(bool label, bool content)
640 void View::extents_changed(bool horz, bool vert)
643 (horz ? RowItemHExtentsChanged : 0) |
644 (vert ? RowItemVExtentsChanged : 0);
645 lazy_event_handler_.start();
648 void View::h_scroll_value_changed(int value)
650 if (updating_scroll_)
653 const int range = horizontalScrollBar()->maximum();
654 if (range < MaxScrollValue)
655 offset_ = scale_ * value;
657 double length = 0, offset;
658 get_scroll_layout(length, offset);
659 offset_ = scale_ * length * value / MaxScrollValue;
666 void View::v_scroll_value_changed()
672 void View::signals_changed()
676 // Populate the traces
679 shared_ptr<sigrok::Device> device = session_.device()->device();
682 // Collect a set of signals
683 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
686 shared_lock<shared_mutex> lock(session_.signals_mutex());
687 const unordered_set< shared_ptr<Signal> > &sigs(session_.signals());
689 for (const shared_ptr<Signal> &sig : sigs)
690 signal_map[sig->channel()] = sig;
692 // Populate channel groups
693 for (auto entry : device->channel_groups())
695 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
697 if (group->channels().size() <= 1)
700 shared_ptr<TraceGroup> trace_group(new TraceGroup());
701 int child_offset = 0;
702 if (add_channels_to_owner(group->channels(),
703 trace_group.get(), child_offset, signal_map))
705 add_child_item(trace_group);
706 apply_offset(trace_group, offset);
710 // Add the remaining logic channels
711 shared_ptr<TraceGroup> logic_trace_group(new TraceGroup());
712 int child_offset = 0;
714 if (add_channels_to_owner(device->channels(),
715 logic_trace_group.get(), child_offset, signal_map,
716 [](shared_ptr<RowItem> r) -> bool {
717 return dynamic_pointer_cast<LogicSignal>(r) != nullptr;
721 add_child_item(logic_trace_group);
722 apply_offset(logic_trace_group, offset);
725 // Add the remaining channels
726 add_channels_to_owner(device->channels(), this, offset, signal_map);
727 assert(signal_map.empty());
729 // Add decode signals
731 const vector< shared_ptr<DecodeTrace> > decode_sigs(
732 session().get_decode_signals());
733 for (auto s : decode_sigs) {
735 apply_offset(s, offset);
742 void View::data_updated()
744 // Update the scroll bars
751 void View::process_sticky_events()
753 if (sticky_events_ & RowItemHExtentsChanged)
755 if (sticky_events_ & RowItemVExtentsChanged) {
756 restack_all_row_items();
760 // Clear the sticky events
764 void View::on_hover_point_changed()
766 for (shared_ptr<RowItem> r : *this)
767 r->hover_point_changed();