]> sigrok.org Git - pulseview.git/blame_incremental - pv/view/view.cpp
ViewItem: Moved in LabelPadding
[pulseview.git] / pv / view / view.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5 *
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.
10 *
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.
15 *
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
19 */
20
21#ifdef ENABLE_DECODE
22#include <libsigrokdecode/libsigrokdecode.h>
23#endif
24
25#include <extdef.h>
26
27#include <cassert>
28#include <climits>
29#include <cmath>
30#include <mutex>
31#include <unordered_set>
32
33#include <QApplication>
34#include <QEvent>
35#include <QFontMetrics>
36#include <QMouseEvent>
37#include <QScrollBar>
38
39#include <libsigrok/libsigrok.hpp>
40
41#include "decodetrace.hpp"
42#include "header.hpp"
43#include "logicsignal.hpp"
44#include "ruler.hpp"
45#include "signal.hpp"
46#include "tracegroup.hpp"
47#include "view.hpp"
48#include "viewport.hpp"
49
50#include "pv/session.hpp"
51#include "pv/data/logic.hpp"
52#include "pv/data/logicsegment.hpp"
53#include "pv/util.hpp"
54
55using boost::shared_lock;
56using boost::shared_mutex;
57
58using pv::data::SignalData;
59using pv::data::Segment;
60using pv::util::format_time;
61
62using std::deque;
63using std::dynamic_pointer_cast;
64using std::list;
65using std::lock_guard;
66using std::max;
67using std::make_pair;
68using std::min;
69using std::pair;
70using std::set;
71using std::shared_ptr;
72using std::unordered_map;
73using std::unordered_set;
74using std::vector;
75using std::weak_ptr;
76
77namespace pv {
78namespace view {
79
80const double View::MaxScale = 1e9;
81const double View::MinScale = 1e-15;
82
83const int View::MaxScrollValue = INT_MAX / 2;
84
85const int View::ScaleUnits[3] = {1, 2, 5};
86
87View::View(Session &session, QWidget *parent) :
88 QAbstractScrollArea(parent),
89 session_(session),
90 viewport_(new Viewport(*this)),
91 ruler_(new Ruler(*this)),
92 header_(new Header(*this)),
93 scale_(1e-6),
94 offset_(0),
95 v_offset_(0),
96 updating_scroll_(false),
97 tick_period_(0.0),
98 tick_prefix_(0),
99 show_cursors_(false),
100 cursors_(new CursorPair(*this)),
101 next_flag_text_('A'),
102 hover_point_(-1, -1)
103{
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)));
108
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()));
117
118 connect(header_, SIGNAL(signals_moved()),
119 this, SLOT(on_signals_moved()));
120
121 connect(header_, SIGNAL(selection_changed()),
122 ruler_, SLOT(clear_selection()));
123 connect(ruler_, SIGNAL(selection_changed()),
124 header_, SLOT(clear_selection()));
125
126 connect(header_, SIGNAL(selection_changed()),
127 this, SIGNAL(selection_changed()));
128 connect(ruler_, SIGNAL(selection_changed()),
129 this, SIGNAL(selection_changed()));
130
131 connect(this, SIGNAL(hover_point_changed()),
132 this, SLOT(on_hover_point_changed()));
133
134 connect(&lazy_event_handler_, SIGNAL(timeout()),
135 this, SLOT(process_sticky_events()));
136 lazy_event_handler_.setSingleShot(true);
137
138 setViewport(viewport_);
139
140 viewport_->installEventFilter(this);
141 ruler_->installEventFilter(this);
142 header_->installEventFilter(this);
143
144 // Trigger the initial event manually. The default device has signals
145 // which were created before this object came into being
146 signals_changed();
147
148 // make sure the transparent widgets are on the top
149 ruler_->raise();
150 header_->raise();
151
152 // Update the zoom state
153 calculate_tick_spacing();
154}
155
156Session& View::session()
157{
158 return session_;
159}
160
161const Session& View::session() const
162{
163 return session_;
164}
165
166View* View::view()
167{
168 return this;
169}
170
171const View* View::view() const
172{
173 return this;
174}
175
176Viewport* View::viewport()
177{
178 return viewport_;
179}
180
181const Viewport* View::viewport() const
182{
183 return viewport_;
184}
185
186vector< shared_ptr<TimeItem> > View::time_items() const
187{
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());
193 return items;
194}
195
196double View::scale() const
197{
198 return scale_;
199}
200
201double View::offset() const
202{
203 return offset_;
204}
205
206int View::owner_visual_v_offset() const
207{
208 return -v_offset_;
209}
210
211unsigned int View::depth() const
212{
213 return 0;
214}
215
216unsigned int View::tick_prefix() const
217{
218 return tick_prefix_;
219}
220
221double View::tick_period() const
222{
223 return tick_period_;
224}
225
226void View::zoom(double steps)
227{
228 zoom(steps, viewport_->width() / 2);
229}
230
231void View::zoom(double steps, int offset)
232{
233 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
234}
235
236void View::zoom_fit()
237{
238 const pair<double, double> extents = get_time_extents();
239 const double delta = extents.second - extents.first;
240 if (delta < 1e-12)
241 return;
242
243 assert(viewport_);
244 const int w = viewport_->width();
245 if (w <= 0)
246 return;
247
248 const double scale = max(min(delta / w, MaxScale), MinScale);
249 set_scale_offset(scale, extents.first);
250}
251
252void View::zoom_one_to_one()
253{
254 using pv::data::SignalData;
255
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())
259 return;
260
261 double samplerate = 0.0;
262 for (const shared_ptr<SignalData> d : visible_data) {
263 assert(d);
264 const vector< shared_ptr<Segment> > segments =
265 d->segments();
266 for (const shared_ptr<Segment> &s : segments)
267 samplerate = max(samplerate, s->samplerate());
268 }
269
270 if (samplerate == 0.0)
271 return;
272
273 assert(viewport_);
274 const int w = viewport_->width();
275 if (w <= 0)
276 return;
277
278 set_zoom(1.0 / samplerate, w / 2);
279}
280
281void View::set_scale_offset(double scale, double offset)
282{
283 scale_ = scale;
284 offset_ = offset;
285
286 calculate_tick_spacing();
287
288 update_scroll();
289 ruler_->update();
290 viewport_->update();
291 scale_offset_changed();
292}
293
294set< shared_ptr<SignalData> > View::get_visible_data() const
295{
296 shared_lock<shared_mutex> lock(session().signals_mutex());
297 const vector< shared_ptr<Signal> > &sigs(session().signals());
298
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)
302 if (sig->enabled())
303 visible_data.insert(sig->data());
304
305 return visible_data;
306}
307
308pair<double, double> View::get_time_extents() const
309{
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)
313 {
314 const vector< shared_ptr<Segment> > segments =
315 d->segments();
316 for (const shared_ptr<Segment> &s : segments) {
317 double samplerate = s->samplerate();
318 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
319
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);
324 }
325 }
326
327 if (left_time == DBL_MAX && right_time == DBL_MIN)
328 return make_pair(0.0, 0.0);
329
330 assert(left_time < right_time);
331 return make_pair(left_time, right_time);
332}
333
334bool View::cursors_shown() const
335{
336 return show_cursors_;
337}
338
339void View::show_cursors(bool show)
340{
341 show_cursors_ = show;
342 ruler_->update();
343 viewport_->update();
344}
345
346void View::centre_cursors()
347{
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);
351 ruler_->update();
352 viewport_->update();
353}
354
355std::shared_ptr<CursorPair> View::cursors() const
356{
357 return cursors_;
358}
359
360void View::add_flag(double time)
361{
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);
367}
368
369void View::remove_flag(std::shared_ptr<Flag> flag)
370{
371 flags_.remove(flag);
372 time_item_appearance_changed(true, true);
373}
374
375vector< std::shared_ptr<Flag> > View::flags() const
376{
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();
381 });
382
383 return flags;
384}
385
386const QPoint& View::hover_point() const
387{
388 return hover_point_;
389}
390
391void View::update_viewport()
392{
393 assert(viewport_);
394 viewport_->update();
395 header_->update();
396}
397
398void View::restack_all_row_items()
399{
400 // Make a set of owners
401 unordered_set< RowItemOwner* > owners;
402 for (const auto &r : *this)
403 owners.insert(r->owner());
404
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(); });
410
411 // Restack the items recursively
412 for (auto &o : sorted_owners)
413 o->restack_items();
414
415 // Animate the items to their destination
416 for (const auto &r : *this)
417 r->animate_to_layout_v_offset();
418}
419
420void View::get_scroll_layout(double &length, double &offset) const
421{
422 const pair<double, double> extents = get_time_extents();
423 length = (extents.second - extents.first) / scale_;
424 offset = offset_ / scale_;
425}
426
427void View::set_zoom(double scale, int offset)
428{
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);
433}
434
435void View::calculate_tick_spacing()
436{
437 const double SpacingIncrement = 32.0f;
438 const double MinValueSpacing = 32.0f;
439
440 double min_width = SpacingIncrement, typical_width;
441
442 QFontMetrics m(QApplication::font());
443
444 do {
445 const double min_period = scale_ * min_width;
446
447 const int order = (int)floorf(log10f(min_period));
448 const double order_decimal = pow(10.0, order);
449
450 unsigned int unit = 0;
451
452 do {
453 tick_period_ = order_decimal * ScaleUnits[unit++];
454 } while (tick_period_ < min_period &&
455 unit < countof(ScaleUnits));
456
457 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
458
459 typical_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
460 Qt::AlignLeft | Qt::AlignTop,
461 format_time(offset_, tick_prefix_)).width() +
462 MinValueSpacing;
463
464 min_width += SpacingIncrement;
465
466 } while(typical_width > tick_period_ / scale_);
467}
468
469void View::update_scroll()
470{
471 assert(viewport_);
472
473 const QSize areaSize = viewport_->size();
474
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);
479
480 int major_tick_distance = tick_period_ / scale_;
481
482 horizontalScrollBar()->setPageStep(areaSize.width() / 2);
483 horizontalScrollBar()->setSingleStep(major_tick_distance);
484
485 updating_scroll_ = true;
486
487 if (length < MaxScrollValue) {
488 horizontalScrollBar()->setRange(0, length);
489 horizontalScrollBar()->setSliderPosition(offset);
490 } else {
491 horizontalScrollBar()->setRange(0, MaxScrollValue);
492 horizontalScrollBar()->setSliderPosition(
493 offset_ * MaxScrollValue / (scale_ * length));
494 }
495
496 updating_scroll_ = false;
497
498 // Set the vertical scrollbar
499 verticalScrollBar()->setPageStep(areaSize.height());
500 verticalScrollBar()->setSingleStep(areaSize.height() / 8);
501
502 const pair<int, int> extents = v_extents();
503 verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
504 extents.second - (areaSize.height() / 2));
505}
506
507void View::update_layout()
508{
509 setViewportMargins(
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());
516 update_scroll();
517}
518
519void View::paint_label(QPainter &p, const QRect &rect, bool hover)
520{
521 (void)p;
522 (void)rect;
523 (void)hover;
524}
525
526QRectF View::label_rect(const QRectF &rect)
527{
528 (void)rect;
529 return QRectF();
530}
531
532bool 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> >
536 &signal_map,
537 std::function<bool (shared_ptr<RowItem>)> filter_func)
538{
539 bool any_added = false;
540
541 assert(owner);
542
543 for (const auto &channel : channels)
544 {
545 const auto iter = signal_map.find(channel);
546 if (iter == signal_map.end() ||
547 (filter_func && !filter_func((*iter).second)))
548 continue;
549
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);
554
555 any_added = true;
556 }
557
558 return any_added;
559}
560
561void View::apply_offset(shared_ptr<RowItem> row_item, int &offset) {
562 assert(row_item);
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;
569}
570
571bool View::eventFilter(QObject *object, QEvent *event)
572{
573 const QEvent::Type type = event->type();
574 if (type == QEvent::MouseMove) {
575
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());
583 else
584 hover_point_ = QPoint(-1, -1);
585
586 hover_point_changed();
587
588 } else if (type == QEvent::Leave) {
589 hover_point_ = QPoint(-1, -1);
590 hover_point_changed();
591 }
592
593 return QObject::eventFilter(object, event);
594}
595
596bool View::viewportEvent(QEvent *e)
597{
598 switch(e->type()) {
599 case QEvent::Paint:
600 case QEvent::MouseButtonPress:
601 case QEvent::MouseButtonRelease:
602 case QEvent::MouseButtonDblClick:
603 case QEvent::MouseMove:
604 case QEvent::Wheel:
605 case QEvent::TouchBegin:
606 case QEvent::TouchUpdate:
607 case QEvent::TouchEnd:
608 return false;
609
610 default:
611 return QAbstractScrollArea::viewportEvent(e);
612 }
613}
614
615void View::resizeEvent(QResizeEvent*)
616{
617 update_layout();
618}
619
620void View::row_item_appearance_changed(bool label, bool content)
621{
622 if (label)
623 header_->update();
624 if (content)
625 viewport_->update();
626}
627
628void View::time_item_appearance_changed(bool label, bool content)
629{
630 if (label)
631 ruler_->update();
632 if (content)
633 viewport_->update();
634}
635
636void View::extents_changed(bool horz, bool vert)
637{
638 sticky_events_ |=
639 (horz ? RowItemHExtentsChanged : 0) |
640 (vert ? RowItemVExtentsChanged : 0);
641 lazy_event_handler_.start();
642}
643
644void View::h_scroll_value_changed(int value)
645{
646 if (updating_scroll_)
647 return;
648
649 const int range = horizontalScrollBar()->maximum();
650 if (range < MaxScrollValue)
651 offset_ = scale_ * value;
652 else {
653 double length = 0, offset;
654 get_scroll_layout(length, offset);
655 offset_ = scale_ * length * value / MaxScrollValue;
656 }
657
658 ruler_->update();
659 viewport_->update();
660}
661
662void View::v_scroll_value_changed(int value)
663{
664 v_offset_ = value;
665 header_->update();
666 viewport_->update();
667}
668
669void View::signals_changed()
670{
671 int offset = 0;
672
673 // Populate the traces
674 clear_child_items();
675
676 shared_ptr<sigrok::Device> device = session_.device();
677 assert(device);
678
679 // Collect a set of signals
680 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
681 signal_map;
682
683 shared_lock<shared_mutex> lock(session_.signals_mutex());
684 const vector< shared_ptr<Signal> > &sigs(session_.signals());
685
686 for (const shared_ptr<Signal> &sig : sigs)
687 signal_map[sig->channel()] = sig;
688
689 // Populate channel groups
690 for (auto entry : device->channel_groups())
691 {
692 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
693
694 if (group->channels().size() <= 1)
695 continue;
696
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))
701 {
702 add_child_item(trace_group);
703 apply_offset(trace_group, offset);
704 }
705 }
706
707 // Add the remaining logic channels
708 shared_ptr<TraceGroup> logic_trace_group(new TraceGroup());
709 int child_offset = 0;
710
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;
715 }))
716
717 {
718 add_child_item(logic_trace_group);
719 apply_offset(logic_trace_group, offset);
720 }
721
722 // Add the remaining channels
723 add_channels_to_owner(device->channels(), this, offset, signal_map);
724 assert(signal_map.empty());
725
726 // Add decode signals
727#ifdef ENABLE_DECODE
728 const vector< shared_ptr<DecodeTrace> > decode_sigs(
729 session().get_decode_signals());
730 for (auto s : decode_sigs) {
731 add_child_item(s);
732 apply_offset(s, offset);
733 }
734#endif
735
736 update_layout();
737}
738
739void View::data_updated()
740{
741 // Update the scroll bars
742 update_scroll();
743
744 // Repaint the view
745 viewport_->update();
746}
747
748void View::on_signals_moved()
749{
750 update_scroll();
751 signals_moved();
752}
753
754void View::process_sticky_events()
755{
756 if (sticky_events_ & RowItemHExtentsChanged)
757 update_layout();
758 if (sticky_events_ & RowItemVExtentsChanged)
759 restack_all_row_items();
760
761 // Clear the sticky events
762 sticky_events_ = 0;
763}
764
765void View::on_hover_point_changed()
766{
767 for (shared_ptr<RowItem> r : *this)
768 r->hover_point_changed();
769}
770
771} // namespace view
772} // namespace pv