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(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
208 unsigned int View::depth() const
213 unsigned int View::tick_prefix() const
218 double View::tick_period() const
223 void View::zoom(double steps)
225 zoom(steps, viewport_->width() / 2);
228 void View::zoom(double steps, int offset)
230 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
233 void View::zoom_fit()
235 const pair<double, double> extents = get_time_extents();
236 const double delta = extents.second - extents.first;
241 const int w = viewport_->width();
245 const double scale = max(min(delta / w, MaxScale), MinScale);
246 set_scale_offset(scale, extents.first);
249 void View::zoom_one_to_one()
251 using pv::data::SignalData;
253 // Make a set of all the visible data objects
254 set< shared_ptr<SignalData> > visible_data = get_visible_data();
255 if (visible_data.empty())
258 double samplerate = 0.0;
259 for (const shared_ptr<SignalData> d : visible_data) {
261 const vector< shared_ptr<Segment> > segments =
263 for (const shared_ptr<Segment> &s : segments)
264 samplerate = max(samplerate, s->samplerate());
267 if (samplerate == 0.0)
271 const int w = viewport_->width();
275 set_zoom(1.0 / samplerate, w / 2);
278 void View::set_scale_offset(double scale, double offset)
283 calculate_tick_spacing();
288 scale_offset_changed();
291 set< shared_ptr<SignalData> > View::get_visible_data() const
293 shared_lock<shared_mutex> lock(session().signals_mutex());
294 const vector< shared_ptr<Signal> > &sigs(session().signals());
296 // Make a set of all the visible data objects
297 set< shared_ptr<SignalData> > visible_data;
298 for (const shared_ptr<Signal> sig : sigs)
300 visible_data.insert(sig->data());
305 pair<double, double> View::get_time_extents() const
307 double left_time = DBL_MAX, right_time = DBL_MIN;
308 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
309 for (const shared_ptr<SignalData> d : visible_data)
311 const vector< shared_ptr<Segment> > segments =
313 for (const shared_ptr<Segment> &s : segments) {
314 double samplerate = s->samplerate();
315 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
317 const double start_time = s->start_time();
318 left_time = min(left_time, start_time);
319 right_time = max(right_time, start_time +
320 d->get_max_sample_count() / samplerate);
324 if (left_time == DBL_MAX && right_time == DBL_MIN)
325 return make_pair(0.0, 0.0);
327 assert(left_time < right_time);
328 return make_pair(left_time, right_time);
331 bool View::cursors_shown() const
333 return show_cursors_;
336 void View::show_cursors(bool show)
338 show_cursors_ = show;
343 void View::centre_cursors()
345 const double time_width = scale_ * viewport_->width();
346 cursors_->first()->set_time(offset_ + time_width * 0.4);
347 cursors_->second()->set_time(offset_ + time_width * 0.6);
352 std::shared_ptr<CursorPair> View::cursors() const
357 void View::add_flag(double time)
359 flags_.push_back(shared_ptr<Flag>(new Flag(*this, time,
360 QString("%1").arg(next_flag_text_))));
361 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
362 (next_flag_text_ + 1);
363 time_item_appearance_changed(true, true);
366 void View::remove_flag(std::shared_ptr<Flag> flag)
369 time_item_appearance_changed(true, true);
372 vector< std::shared_ptr<Flag> > View::flags() const
374 vector< std::shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
375 stable_sort(flags.begin(), flags.end(),
376 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
377 return a->time() < b->time();
383 const QPoint& View::hover_point() const
388 void View::update_viewport()
395 void View::restack_all_row_items()
397 // Make a set of owners
398 unordered_set< RowItemOwner* > owners;
399 for (const auto &r : *this)
400 owners.insert(r->owner());
402 // Make a list that is sorted from deepest first
403 vector< RowItemOwner* > sorted_owners(owners.begin(), owners.end());
404 sort(sorted_owners.begin(), sorted_owners.end(),
405 [](const RowItemOwner* a, const RowItemOwner *b) {
406 return a->depth() > b->depth(); });
408 // Restack the items recursively
409 for (auto &o : sorted_owners)
412 // Animate the items to their destination
413 for (const auto &r : *this)
414 r->animate_to_layout_v_offset();
417 void View::get_scroll_layout(double &length, double &offset) const
419 const pair<double, double> extents = get_time_extents();
420 length = (extents.second - extents.first) / scale_;
421 offset = offset_ / scale_;
424 void View::set_zoom(double scale, int offset)
426 const double cursor_offset = offset_ + scale_ * offset;
427 const double new_scale = max(min(scale, MaxScale), MinScale);
428 const double new_offset = cursor_offset - new_scale * offset;
429 set_scale_offset(new_scale, new_offset);
432 void View::calculate_tick_spacing()
434 const double SpacingIncrement = 32.0f;
435 const double MinValueSpacing = 32.0f;
437 double min_width = SpacingIncrement, typical_width;
439 QFontMetrics m(QApplication::font());
442 const double min_period = scale_ * min_width;
444 const int order = (int)floorf(log10f(min_period));
445 const double order_decimal = pow(10.0, order);
447 unsigned int unit = 0;
450 tick_period_ = order_decimal * ScaleUnits[unit++];
451 } while (tick_period_ < min_period &&
452 unit < countof(ScaleUnits));
454 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
456 typical_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
457 Qt::AlignLeft | Qt::AlignTop,
458 format_time(offset_, tick_prefix_)).width() +
461 min_width += SpacingIncrement;
463 } while(typical_width > tick_period_ / scale_);
466 void View::update_scroll()
470 const QSize areaSize = viewport_->size();
472 // Set the horizontal scroll bar
473 double length = 0, offset = 0;
474 get_scroll_layout(length, offset);
475 length = max(length - areaSize.width(), 0.0);
477 int major_tick_distance = tick_period_ / scale_;
479 horizontalScrollBar()->setPageStep(areaSize.width() / 2);
480 horizontalScrollBar()->setSingleStep(major_tick_distance);
482 updating_scroll_ = true;
484 if (length < MaxScrollValue) {
485 horizontalScrollBar()->setRange(0, length);
486 horizontalScrollBar()->setSliderPosition(offset);
488 horizontalScrollBar()->setRange(0, MaxScrollValue);
489 horizontalScrollBar()->setSliderPosition(
490 offset_ * MaxScrollValue / (scale_ * length));
493 updating_scroll_ = false;
495 // Set the vertical scrollbar
496 verticalScrollBar()->setPageStep(areaSize.height());
497 verticalScrollBar()->setSingleStep(areaSize.height() / 8);
499 const pair<int, int> extents = v_extents();
500 verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
501 extents.second - (areaSize.height() / 2));
504 void View::update_layout()
507 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
508 ruler_->sizeHint().height(), 0, 0);
509 ruler_->setGeometry(viewport_->x(), 0,
510 viewport_->width(), ruler_->extended_size_hint().height());
511 header_->setGeometry(0, viewport_->y(),
512 header_->extended_size_hint().width(), viewport_->height());
516 void View::paint_label(QPainter &p, const QRect &rect, bool hover)
523 QRectF View::label_rect(const QRectF &rect)
529 bool View::add_channels_to_owner(
530 const vector< shared_ptr<sigrok::Channel> > &channels,
531 RowItemOwner *owner, int &offset,
532 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
534 std::function<bool (shared_ptr<RowItem>)> filter_func)
536 bool any_added = false;
540 for (const auto &channel : channels)
542 const auto iter = signal_map.find(channel);
543 if (iter == signal_map.end() ||
544 (filter_func && !filter_func((*iter).second)))
547 shared_ptr<RowItem> row_item = (*iter).second;
548 owner->add_child_item(row_item);
549 apply_offset(row_item, offset);
550 signal_map.erase(iter);
558 void View::apply_offset(shared_ptr<RowItem> row_item, int &offset) {
560 const pair<int, int> extents = row_item->v_extents();
561 if (row_item->enabled())
562 offset += -extents.first;
563 row_item->force_to_v_offset(offset);
564 if (row_item->enabled())
565 offset += extents.second;
568 bool View::eventFilter(QObject *object, QEvent *event)
570 const QEvent::Type type = event->type();
571 if (type == QEvent::MouseMove) {
573 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
574 if (object == viewport_)
575 hover_point_ = mouse_event->pos();
576 else if (object == ruler_)
577 hover_point_ = QPoint(mouse_event->x(), 0);
578 else if (object == header_)
579 hover_point_ = QPoint(0, mouse_event->y());
581 hover_point_ = QPoint(-1, -1);
583 hover_point_changed();
585 } else if (type == QEvent::Leave) {
586 hover_point_ = QPoint(-1, -1);
587 hover_point_changed();
590 return QObject::eventFilter(object, event);
593 bool View::viewportEvent(QEvent *e)
597 case QEvent::MouseButtonPress:
598 case QEvent::MouseButtonRelease:
599 case QEvent::MouseButtonDblClick:
600 case QEvent::MouseMove:
602 case QEvent::TouchBegin:
603 case QEvent::TouchUpdate:
604 case QEvent::TouchEnd:
608 return QAbstractScrollArea::viewportEvent(e);
612 void View::resizeEvent(QResizeEvent*)
617 void View::row_item_appearance_changed(bool label, bool content)
625 void View::time_item_appearance_changed(bool label, bool content)
633 void View::extents_changed(bool horz, bool vert)
636 (horz ? RowItemHExtentsChanged : 0) |
637 (vert ? RowItemVExtentsChanged : 0);
638 lazy_event_handler_.start();
641 void View::h_scroll_value_changed(int value)
643 if (updating_scroll_)
646 const int range = horizontalScrollBar()->maximum();
647 if (range < MaxScrollValue)
648 offset_ = scale_ * value;
650 double length = 0, offset;
651 get_scroll_layout(length, offset);
652 offset_ = scale_ * length * value / MaxScrollValue;
659 void View::v_scroll_value_changed(int value)
666 void View::signals_changed()
670 // Populate the traces
673 shared_ptr<sigrok::Device> device = session_.device();
676 // Collect a set of signals
677 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
680 shared_lock<shared_mutex> lock(session_.signals_mutex());
681 const vector< shared_ptr<Signal> > &sigs(session_.signals());
683 for (const shared_ptr<Signal> &sig : sigs)
684 signal_map[sig->channel()] = sig;
686 // Populate channel groups
687 for (auto entry : device->channel_groups())
689 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
691 if (group->channels().size() <= 1)
694 shared_ptr<TraceGroup> trace_group(new TraceGroup());
695 int child_offset = 0;
696 if (add_channels_to_owner(group->channels(),
697 trace_group.get(), child_offset, signal_map))
699 add_child_item(trace_group);
700 apply_offset(trace_group, offset);
704 // Add the remaining logic channels
705 shared_ptr<TraceGroup> logic_trace_group(new TraceGroup());
706 int child_offset = 0;
708 if (add_channels_to_owner(device->channels(),
709 logic_trace_group.get(), child_offset, signal_map,
710 [](shared_ptr<RowItem> r) -> bool {
711 return dynamic_pointer_cast<LogicSignal>(r) != nullptr;
715 add_child_item(logic_trace_group);
716 apply_offset(logic_trace_group, offset);
719 // Add the remaining channels
720 add_channels_to_owner(device->channels(), this, offset, signal_map);
721 assert(signal_map.empty());
723 // Add decode signals
725 const vector< shared_ptr<DecodeTrace> > decode_sigs(
726 session().get_decode_signals());
727 for (auto s : decode_sigs) {
729 apply_offset(s, offset);
736 void View::data_updated()
738 // Update the scroll bars
745 void View::process_sticky_events()
747 if (sticky_events_ & RowItemHExtentsChanged)
749 if (sticky_events_ & RowItemVExtentsChanged) {
750 restack_all_row_items();
754 // Clear the sticky events
758 void View::on_hover_point_changed()
760 for (shared_ptr<RowItem> r : *this)
761 r->hover_point_changed();