]> sigrok.org Git - pulseview.git/blame_incremental - pv/view/view.cpp
Implement "use coloured background" functionality
[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 <algorithm>
28#include <cassert>
29#include <climits>
30#include <cmath>
31#include <iterator>
32#include <mutex>
33#include <unordered_set>
34
35#include <boost/thread/locks.hpp>
36
37#include <QApplication>
38#include <QEvent>
39#include <QFontMetrics>
40#include <QMouseEvent>
41#include <QScrollBar>
42
43#include <libsigrokcxx/libsigrokcxx.hpp>
44
45#include "analogsignal.hpp"
46#include "decodetrace.hpp"
47#include "header.hpp"
48#include "logicsignal.hpp"
49#include "ruler.hpp"
50#include "signal.hpp"
51#include "tracegroup.hpp"
52#include "triggermarker.hpp"
53#include "view.hpp"
54#include "viewport.hpp"
55
56#include "pv/session.hpp"
57#include "pv/devices/device.hpp"
58#include "pv/data/logic.hpp"
59#include "pv/data/logicsegment.hpp"
60#include "pv/util.hpp"
61
62using boost::shared_lock;
63using boost::shared_mutex;
64
65using pv::data::SignalData;
66using pv::data::Segment;
67using pv::util::TimeUnit;
68using pv::util::Timestamp;
69
70using std::back_inserter;
71using std::copy_if;
72using std::deque;
73using std::dynamic_pointer_cast;
74using std::inserter;
75using std::list;
76using std::lock_guard;
77using std::max;
78using std::make_pair;
79using std::make_shared;
80using std::min;
81using std::pair;
82using std::set;
83using std::set_difference;
84using std::shared_ptr;
85using std::unordered_map;
86using std::unordered_set;
87using std::vector;
88using std::weak_ptr;
89
90namespace pv {
91namespace view {
92
93const Timestamp View::MaxScale("1e9");
94const Timestamp View::MinScale("1e-12");
95
96const int View::MaxScrollValue = INT_MAX / 2;
97const int View::MaxViewAutoUpdateRate = 25; // No more than 25 Hz with sticky scrolling
98
99const int View::ScaleUnits[3] = {1, 2, 5};
100
101View::View(Session &session, QWidget *parent) :
102 QAbstractScrollArea(parent),
103 session_(session),
104 viewport_(new Viewport(*this)),
105 ruler_(new Ruler(*this)),
106 header_(new Header(*this)),
107 scale_(1e-3),
108 offset_(0),
109 updating_scroll_(false),
110 sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
111 always_zoom_to_fit_(false),
112 tick_period_(0),
113 tick_prefix_(pv::util::SIPrefix::yocto),
114 tick_precision_(0),
115 time_unit_(util::TimeUnit::Time),
116 show_cursors_(false),
117 cursors_(new CursorPair(*this)),
118 next_flag_text_('A'),
119 trigger_markers_(),
120 hover_point_(-1, -1)
121{
122 connect(horizontalScrollBar(), SIGNAL(valueChanged(int)),
123 this, SLOT(h_scroll_value_changed(int)));
124 connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
125 this, SLOT(v_scroll_value_changed()));
126
127 connect(&session_, SIGNAL(signals_changed()),
128 this, SLOT(signals_changed()));
129 connect(&session_, SIGNAL(capture_state_changed(int)),
130 this, SLOT(capture_state_updated(int)));
131 connect(&session_, SIGNAL(data_received()),
132 this, SLOT(data_updated()));
133 connect(&session_, SIGNAL(frame_ended()),
134 this, SLOT(data_updated()));
135
136 connect(header_, SIGNAL(selection_changed()),
137 ruler_, SLOT(clear_selection()));
138 connect(ruler_, SIGNAL(selection_changed()),
139 header_, SLOT(clear_selection()));
140
141 connect(header_, SIGNAL(selection_changed()),
142 this, SIGNAL(selection_changed()));
143 connect(ruler_, SIGNAL(selection_changed()),
144 this, SIGNAL(selection_changed()));
145
146 connect(this, SIGNAL(hover_point_changed()),
147 this, SLOT(on_hover_point_changed()));
148
149 connect(&lazy_event_handler_, SIGNAL(timeout()),
150 this, SLOT(process_sticky_events()));
151 lazy_event_handler_.setSingleShot(true);
152
153 connect(&delayed_view_updater_, SIGNAL(timeout()),
154 this, SLOT(perform_delayed_view_update()));
155 delayed_view_updater_.setSingleShot(true);
156 delayed_view_updater_.setInterval(1000 / MaxViewAutoUpdateRate);
157
158 setViewport(viewport_);
159
160 viewport_->installEventFilter(this);
161 ruler_->installEventFilter(this);
162 header_->installEventFilter(this);
163
164 // Trigger the initial event manually. The default device has signals
165 // which were created before this object came into being
166 signals_changed();
167
168 // make sure the transparent widgets are on the top
169 ruler_->raise();
170 header_->raise();
171
172 // Update the zoom state
173 calculate_tick_spacing();
174}
175
176Session& View::session()
177{
178 return session_;
179}
180
181const Session& View::session() const
182{
183 return session_;
184}
185
186View* View::view()
187{
188 return this;
189}
190
191const View* View::view() const
192{
193 return this;
194}
195
196Viewport* View::viewport()
197{
198 return viewport_;
199}
200
201const Viewport* View::viewport() const
202{
203 return viewport_;
204}
205
206vector< shared_ptr<TimeItem> > View::time_items() const
207{
208 const vector<shared_ptr<Flag>> f(flags());
209 vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
210 items.push_back(cursors_);
211 items.push_back(cursors_->first());
212 items.push_back(cursors_->second());
213
214 for (auto trigger_marker : trigger_markers_)
215 items.push_back(trigger_marker);
216
217 return items;
218}
219
220double View::scale() const
221{
222 return scale_;
223}
224
225void View::set_scale(double scale)
226{
227 if (scale_ != scale) {
228 scale_ = scale;
229 Q_EMIT scale_changed();
230 }
231}
232
233const Timestamp& View::offset() const
234{
235 return offset_;
236}
237
238void View::set_offset(const pv::util::Timestamp& offset)
239{
240 if (offset_ != offset) {
241 offset_ = offset;
242 Q_EMIT offset_changed();
243 }
244}
245
246int View::owner_visual_v_offset() const
247{
248 return -verticalScrollBar()->sliderPosition();
249}
250
251void View::set_v_offset(int offset)
252{
253 verticalScrollBar()->setSliderPosition(offset);
254 header_->update();
255 viewport_->update();
256}
257
258unsigned int View::depth() const
259{
260 return 0;
261}
262
263pv::util::SIPrefix View::tick_prefix() const
264{
265 return tick_prefix_;
266}
267
268void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
269{
270 if (tick_prefix_ != tick_prefix) {
271 tick_prefix_ = tick_prefix;
272 Q_EMIT tick_prefix_changed();
273 }
274}
275
276unsigned int View::tick_precision() const
277{
278 return tick_precision_;
279}
280
281void View::set_tick_precision(unsigned tick_precision)
282{
283 if (tick_precision_ != tick_precision) {
284 tick_precision_ = tick_precision;
285 Q_EMIT tick_precision_changed();
286 }
287}
288
289const pv::util::Timestamp& View::tick_period() const
290{
291 return tick_period_;
292}
293
294void View::set_tick_period(const pv::util::Timestamp& tick_period)
295{
296 if (tick_period_ != tick_period) {
297 tick_period_ = tick_period;
298 Q_EMIT tick_period_changed();
299 }
300}
301
302TimeUnit View::time_unit() const
303{
304 return time_unit_;
305}
306
307void View::set_time_unit(pv::util::TimeUnit time_unit)
308{
309 if (time_unit_ != time_unit) {
310 time_unit_ = time_unit;
311 Q_EMIT time_unit_changed();
312 }
313}
314
315void View::zoom(double steps)
316{
317 zoom(steps, viewport_->width() / 2);
318}
319
320void View::zoom(double steps, int offset)
321{
322 set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
323}
324
325void View::zoom_fit(bool gui_state)
326{
327 // Act as one-shot when stopped, toggle along with the GUI otherwise
328 if (session_.get_capture_state() == Session::Stopped) {
329 always_zoom_to_fit_ = false;
330 always_zoom_to_fit_changed(false);
331 } else {
332 always_zoom_to_fit_ = gui_state;
333 always_zoom_to_fit_changed(gui_state);
334 }
335
336 const pair<Timestamp, Timestamp> extents = get_time_extents();
337 const Timestamp delta = extents.second - extents.first;
338 if (delta < Timestamp("1e-12"))
339 return;
340
341 assert(viewport_);
342 const int w = viewport_->width();
343 if (w <= 0)
344 return;
345
346 const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
347 set_scale_offset(scale.convert_to<double>(), extents.first);
348}
349
350void View::zoom_one_to_one()
351{
352 using pv::data::SignalData;
353
354 // Make a set of all the visible data objects
355 set< shared_ptr<SignalData> > visible_data = get_visible_data();
356 if (visible_data.empty())
357 return;
358
359 assert(viewport_);
360 const int w = viewport_->width();
361 if (w <= 0)
362 return;
363
364 set_zoom(1.0 / session_.get_samplerate(), w / 2);
365}
366
367void View::set_scale_offset(double scale, const Timestamp& offset)
368{
369 // Disable sticky scrolling / always zoom to fit when acquisition runs
370 // and user drags the viewport
371 if ((scale_ == scale) && (offset_ != offset) &&
372 (session_.get_capture_state() == Session::Running)) {
373
374 if (sticky_scrolling_) {
375 sticky_scrolling_ = false;
376 sticky_scrolling_changed(false);
377 }
378
379 if (always_zoom_to_fit_) {
380 always_zoom_to_fit_ = false;
381 always_zoom_to_fit_changed(false);
382 }
383 }
384
385 set_scale(scale);
386 set_offset(offset);
387
388 calculate_tick_spacing();
389
390 update_scroll();
391 ruler_->update();
392 viewport_->update();
393}
394
395set< shared_ptr<SignalData> > View::get_visible_data() const
396{
397 const unordered_set< shared_ptr<Signal> > sigs(session().signals());
398
399 // Make a set of all the visible data objects
400 set< shared_ptr<SignalData> > visible_data;
401 for (const shared_ptr<Signal> sig : sigs)
402 if (sig->enabled())
403 visible_data.insert(sig->data());
404
405 return visible_data;
406}
407
408pair<Timestamp, Timestamp> View::get_time_extents() const
409{
410 boost::optional<Timestamp> left_time, right_time;
411 const set< shared_ptr<SignalData> > visible_data = get_visible_data();
412 for (const shared_ptr<SignalData> d : visible_data) {
413 const vector< shared_ptr<Segment> > segments =
414 d->segments();
415 for (const shared_ptr<Segment> &s : segments) {
416 double samplerate = s->samplerate();
417 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
418
419 const Timestamp start_time = s->start_time();
420 left_time = left_time ?
421 min(*left_time, start_time) :
422 start_time;
423 right_time = right_time ?
424 max(*right_time, start_time + d->max_sample_count() / samplerate) :
425 start_time + d->max_sample_count() / samplerate;
426 }
427 }
428
429 if (!left_time || !right_time)
430 return make_pair(0, 0);
431
432 assert(*left_time < *right_time);
433 return make_pair(*left_time, *right_time);
434}
435
436void View::enable_sticky_scrolling(bool state)
437{
438 sticky_scrolling_ = state;
439}
440
441void View::enable_coloured_bg(bool state)
442{
443 const vector<shared_ptr<TraceTreeItem>> items(
444 list_by_type<TraceTreeItem>());
445
446 for (shared_ptr<TraceTreeItem> i : items) {
447 // Can't cast to Trace because it's abstract, so we need to
448 // check for any derived classes individually
449
450 shared_ptr<AnalogSignal> a = dynamic_pointer_cast<AnalogSignal>(i);
451 if (a)
452 a->set_coloured_bg(state);
453
454 shared_ptr<LogicSignal> l = dynamic_pointer_cast<LogicSignal>(i);
455 if (l)
456 l->set_coloured_bg(state);
457
458 shared_ptr<DecodeTrace> d = dynamic_pointer_cast<DecodeTrace>(i);
459 if (d)
460 d->set_coloured_bg(state);
461 }
462
463 viewport_->update();
464}
465
466bool View::cursors_shown() const
467{
468 return show_cursors_;
469}
470
471void View::show_cursors(bool show)
472{
473 show_cursors_ = show;
474 ruler_->update();
475 viewport_->update();
476}
477
478void View::centre_cursors()
479{
480 const double time_width = scale_ * viewport_->width();
481 cursors_->first()->set_time(offset_ + time_width * 0.4);
482 cursors_->second()->set_time(offset_ + time_width * 0.6);
483 ruler_->update();
484 viewport_->update();
485}
486
487std::shared_ptr<CursorPair> View::cursors() const
488{
489 return cursors_;
490}
491
492void View::add_flag(const Timestamp& time)
493{
494 flags_.push_back(shared_ptr<Flag>(new Flag(*this, time,
495 QString("%1").arg(next_flag_text_))));
496
497 next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
498 (next_flag_text_ + 1);
499
500 time_item_appearance_changed(true, true);
501}
502
503void View::remove_flag(std::shared_ptr<Flag> flag)
504{
505 flags_.remove(flag);
506 time_item_appearance_changed(true, true);
507}
508
509vector< std::shared_ptr<Flag> > View::flags() const
510{
511 vector< std::shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
512 stable_sort(flags.begin(), flags.end(),
513 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
514 return a->time() < b->time();
515 });
516
517 return flags;
518}
519
520const QPoint& View::hover_point() const
521{
522 return hover_point_;
523}
524
525void View::update_viewport()
526{
527 assert(viewport_);
528 viewport_->update();
529 header_->update();
530}
531
532void View::restack_all_trace_tree_items()
533{
534 // Make a list of owners that is sorted from deepest first
535 const vector<shared_ptr<TraceTreeItem>> items(
536 list_by_type<TraceTreeItem>());
537 set< TraceTreeItemOwner* > owners;
538 for (const auto &r : items)
539 owners.insert(r->owner());
540 vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
541 sort(sorted_owners.begin(), sorted_owners.end(),
542 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
543 return a->depth() > b->depth(); });
544
545 // Restack the items recursively
546 for (auto &o : sorted_owners)
547 o->restack_items();
548
549 // Animate the items to their destination
550 for (const auto &i : items)
551 i->animate_to_layout_v_offset();
552}
553
554void View::trigger_event(util::Timestamp location)
555{
556 trigger_markers_.push_back(shared_ptr<TriggerMarker>(
557 new TriggerMarker(*this, location)));
558}
559
560void View::get_scroll_layout(double &length, Timestamp &offset) const
561{
562 const pair<Timestamp, Timestamp> extents = get_time_extents();
563 length = ((extents.second - extents.first) / scale_).convert_to<double>();
564 offset = offset_ / scale_;
565}
566
567void View::set_zoom(double scale, int offset)
568{
569 // Reset the "always zoom to fit" feature as the user changed the zoom
570 always_zoom_to_fit_ = false;
571 always_zoom_to_fit_changed(false);
572
573 const Timestamp cursor_offset = offset_ + scale_ * offset;
574 const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
575 const Timestamp new_offset = cursor_offset - new_scale * offset;
576 set_scale_offset(new_scale.convert_to<double>(), new_offset);
577}
578
579void View::calculate_tick_spacing()
580{
581 const double SpacingIncrement = 10.0f;
582 const double MinValueSpacing = 40.0f;
583
584 // Figure out the highest numeric value visible on a label
585 const QSize areaSize = viewport_->size();
586 const Timestamp max_time = max(fabs(offset_),
587 fabs(offset_ + scale_ * areaSize.width()));
588
589 double min_width = SpacingIncrement;
590 double label_width, tick_period_width;
591
592 QFontMetrics m(QApplication::font());
593
594 // Copies of the member variables with the same name, used in the calculation
595 // and written back afterwards, so that we don't emit signals all the time
596 // during the calculation.
597 pv::util::Timestamp tick_period = tick_period_;
598 pv::util::SIPrefix tick_prefix = tick_prefix_;
599 unsigned tick_precision = tick_precision_;
600
601 do {
602 const double min_period = scale_ * min_width;
603
604 const int order = (int)floorf(log10f(min_period));
605 const pv::util::Timestamp order_decimal =
606 pow(pv::util::Timestamp(10), order);
607
608 // Allow for a margin of error so that a scale unit of 1 can be used.
609 // Otherwise, for a SU of 1 the tick period will almost always be below
610 // the min_period by a small amount - and thus skipped in favor of 2.
611 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
612 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
613 double tp_with_margin;
614 unsigned int unit = 0;
615
616 do {
617 tp_with_margin = order_decimal.convert_to<double>() *
618 (ScaleUnits[unit++] + tp_margin);
619 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
620
621 tick_period = order_decimal * ScaleUnits[unit - 1];
622 tick_prefix = static_cast<pv::util::SIPrefix>(
623 (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
624
625 // Precision is the number of fractional digits required, not
626 // taking the prefix into account (and it must never be negative)
627 tick_precision = std::max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
628
629 tick_period_width = (tick_period / scale_).convert_to<double>();
630
631 const QString label_text = Ruler::format_time_with_distance(
632 tick_period, max_time, tick_prefix, time_unit_, tick_precision);
633
634 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
635 Qt::AlignLeft | Qt::AlignTop, label_text).width() +
636 MinValueSpacing;
637
638 min_width += SpacingIncrement;
639 } while (tick_period_width < label_width);
640
641 set_tick_period(tick_period);
642 set_tick_prefix(tick_prefix);
643 set_tick_precision(tick_precision);
644}
645
646void View::update_scroll()
647{
648 assert(viewport_);
649
650 const QSize areaSize = viewport_->size();
651
652 // Set the horizontal scroll bar
653 double length = 0;
654 Timestamp offset;
655 get_scroll_layout(length, offset);
656 length = max(length - areaSize.width(), 0.0);
657
658 int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
659
660 horizontalScrollBar()->setPageStep(areaSize.width() / 2);
661 horizontalScrollBar()->setSingleStep(major_tick_distance);
662
663 updating_scroll_ = true;
664
665 if (length < MaxScrollValue) {
666 horizontalScrollBar()->setRange(0, length);
667 horizontalScrollBar()->setSliderPosition(offset.convert_to<double>());
668 } else {
669 horizontalScrollBar()->setRange(0, MaxScrollValue);
670 horizontalScrollBar()->setSliderPosition(
671 (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
672 }
673
674 updating_scroll_ = false;
675
676 // Set the vertical scrollbar
677 verticalScrollBar()->setPageStep(areaSize.height());
678 verticalScrollBar()->setSingleStep(areaSize.height() / 8);
679
680 const pair<int, int> extents = v_extents();
681 verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
682 extents.second - (areaSize.height() / 2));
683}
684
685void View::update_layout()
686{
687 setViewportMargins(
688 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
689 ruler_->sizeHint().height(), 0, 0);
690 ruler_->setGeometry(viewport_->x(), 0,
691 viewport_->width(), ruler_->extended_size_hint().height());
692 header_->setGeometry(0, viewport_->y(),
693 header_->extended_size_hint().width(), viewport_->height());
694 update_scroll();
695}
696
697void View::paint_label(QPainter &p, const QRect &rect, bool hover)
698{
699 (void)p;
700 (void)rect;
701 (void)hover;
702}
703
704QRectF View::label_rect(const QRectF &rect)
705{
706 (void)rect;
707 return QRectF();
708}
709
710TraceTreeItemOwner* View::find_prevalent_trace_group(
711 const shared_ptr<sigrok::ChannelGroup> &group,
712 const unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
713 &signal_map)
714{
715 assert(group);
716
717 unordered_set<TraceTreeItemOwner*> owners;
718 vector<TraceTreeItemOwner*> owner_list;
719
720 // Make a set and a list of all the owners
721 for (const auto &channel : group->channels()) {
722 const auto iter = signal_map.find(channel);
723 if (iter == signal_map.end())
724 continue;
725
726 TraceTreeItemOwner *const o = (*iter).second->owner();
727 owner_list.push_back(o);
728 owners.insert(o);
729 }
730
731 // Iterate through the list of owners, and find the most prevalent
732 size_t max_prevalence = 0;
733 TraceTreeItemOwner *prevalent_owner = nullptr;
734 for (TraceTreeItemOwner *owner : owners) {
735 const size_t prevalence = std::count_if(
736 owner_list.begin(), owner_list.end(),
737 [&](TraceTreeItemOwner *o) { return o == owner; });
738 if (prevalence > max_prevalence) {
739 max_prevalence = prevalence;
740 prevalent_owner = owner;
741 }
742 }
743
744 return prevalent_owner;
745}
746
747vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
748 const vector< shared_ptr<sigrok::Channel> > &channels,
749 const unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
750 &signal_map,
751 set< shared_ptr<Trace> > &add_list)
752{
753 vector< shared_ptr<Trace> > filtered_traces;
754
755 for (const auto &channel : channels) {
756 const auto map_iter = signal_map.find(channel);
757 if (map_iter == signal_map.end())
758 continue;
759
760 shared_ptr<Trace> trace = (*map_iter).second;
761 const auto list_iter = add_list.find(trace);
762 if (list_iter == add_list.end())
763 continue;
764
765 filtered_traces.push_back(trace);
766 add_list.erase(list_iter);
767 }
768
769 return filtered_traces;
770}
771
772void View::determine_time_unit()
773{
774 // Check whether we know the sample rate and hence can use time as the unit
775 if (time_unit_ == util::TimeUnit::Samples) {
776 const unordered_set< shared_ptr<Signal> > sigs(session().signals());
777
778 // Check all signals but...
779 for (const shared_ptr<Signal> signal : sigs) {
780 const shared_ptr<SignalData> data = signal->data();
781
782 // ...only check first segment of each
783 const vector< shared_ptr<Segment> > segments = data->segments();
784 if (!segments.empty())
785 if (segments[0]->samplerate()) {
786 set_time_unit(util::TimeUnit::Time);
787 break;
788 }
789 }
790 }
791}
792
793bool View::eventFilter(QObject *object, QEvent *event)
794{
795 const QEvent::Type type = event->type();
796 if (type == QEvent::MouseMove) {
797
798 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
799 if (object == viewport_)
800 hover_point_ = mouse_event->pos();
801 else if (object == ruler_)
802 hover_point_ = QPoint(mouse_event->x(), 0);
803 else if (object == header_)
804 hover_point_ = QPoint(0, mouse_event->y());
805 else
806 hover_point_ = QPoint(-1, -1);
807
808 hover_point_changed();
809
810 } else if (type == QEvent::Leave) {
811 hover_point_ = QPoint(-1, -1);
812 hover_point_changed();
813 }
814
815 return QObject::eventFilter(object, event);
816}
817
818bool View::viewportEvent(QEvent *e)
819{
820 switch (e->type()) {
821 case QEvent::Paint:
822 case QEvent::MouseButtonPress:
823 case QEvent::MouseButtonRelease:
824 case QEvent::MouseButtonDblClick:
825 case QEvent::MouseMove:
826 case QEvent::Wheel:
827 case QEvent::TouchBegin:
828 case QEvent::TouchUpdate:
829 case QEvent::TouchEnd:
830 return false;
831 default:
832 return QAbstractScrollArea::viewportEvent(e);
833 }
834}
835
836void View::resizeEvent(QResizeEvent*)
837{
838 update_layout();
839}
840
841void View::row_item_appearance_changed(bool label, bool content)
842{
843 if (label)
844 header_->update();
845 if (content)
846 viewport_->update();
847}
848
849void View::time_item_appearance_changed(bool label, bool content)
850{
851 if (label)
852 ruler_->update();
853 if (content)
854 viewport_->update();
855}
856
857void View::extents_changed(bool horz, bool vert)
858{
859 sticky_events_ |=
860 (horz ? TraceTreeItemHExtentsChanged : 0) |
861 (vert ? TraceTreeItemVExtentsChanged : 0);
862 lazy_event_handler_.start();
863}
864
865void View::h_scroll_value_changed(int value)
866{
867 if (updating_scroll_)
868 return;
869
870 // Disable sticky scrolling when user moves the horizontal scroll bar
871 // during a running acquisition
872 if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
873 sticky_scrolling_ = false;
874 sticky_scrolling_changed(false);
875 }
876
877 const int range = horizontalScrollBar()->maximum();
878 if (range < MaxScrollValue)
879 set_offset(scale_ * value);
880 else {
881 double length = 0;
882 Timestamp offset;
883 get_scroll_layout(length, offset);
884 set_offset(scale_ * length * value / MaxScrollValue);
885 }
886
887 ruler_->update();
888 viewport_->update();
889}
890
891void View::v_scroll_value_changed()
892{
893 header_->update();
894 viewport_->update();
895}
896
897void View::signals_changed()
898{
899 using sigrok::Channel;
900
901 vector< shared_ptr<TraceTreeItem> > new_top_level_items;
902
903 const auto device = session_.device();
904 if (!device)
905 return;
906
907 shared_ptr<sigrok::Device> sr_dev = device->device();
908 assert(sr_dev);
909
910 const vector< shared_ptr<Channel> > channels(
911 sr_dev->channels());
912
913 // Make a list of traces that are being added, and a list of traces
914 // that are being removed
915 const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
916 const set<shared_ptr<Trace>> prev_traces(
917 prev_trace_list.begin(), prev_trace_list.end());
918
919 const unordered_set< shared_ptr<Signal> > sigs(session_.signals());
920
921 set< shared_ptr<Trace> > traces(sigs.begin(), sigs.end());
922
923#ifdef ENABLE_DECODE
924 const vector< shared_ptr<DecodeTrace> > decode_traces(
925 session().get_decode_signals());
926 traces.insert(decode_traces.begin(), decode_traces.end());
927#endif
928
929 set< shared_ptr<Trace> > add_traces;
930 set_difference(traces.begin(), traces.end(),
931 prev_traces.begin(), prev_traces.end(),
932 inserter(add_traces, add_traces.begin()));
933
934 set< shared_ptr<Trace> > remove_traces;
935 set_difference(prev_traces.begin(), prev_traces.end(),
936 traces.begin(), traces.end(),
937 inserter(remove_traces, remove_traces.begin()));
938
939 // Make a look-up table of sigrok Channels to pulseview Signals
940 unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
941 signal_map;
942 for (const shared_ptr<Signal> &sig : sigs)
943 signal_map[sig->channel()] = sig;
944
945 // Populate channel groups
946 for (auto entry : sr_dev->channel_groups()) {
947 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
948
949 if (group->channels().size() <= 1)
950 continue;
951
952 // Find best trace group to add to
953 TraceTreeItemOwner *owner = find_prevalent_trace_group(
954 group, signal_map);
955
956 // If there is no trace group, create one
957 shared_ptr<TraceGroup> new_trace_group;
958 if (!owner) {
959 new_trace_group.reset(new TraceGroup());
960 owner = new_trace_group.get();
961 }
962
963 // Extract traces for the trace group, removing them from
964 // the add list
965 const vector< shared_ptr<Trace> > new_traces_in_group =
966 extract_new_traces_for_channels(group->channels(),
967 signal_map, add_traces);
968
969 // Add the traces to the group
970 const pair<int, int> prev_v_extents = owner->v_extents();
971 int offset = prev_v_extents.second - prev_v_extents.first;
972 for (shared_ptr<Trace> trace : new_traces_in_group) {
973 assert(trace);
974 owner->add_child_item(trace);
975
976 const pair<int, int> extents = trace->v_extents();
977 if (trace->enabled())
978 offset += -extents.first;
979 trace->force_to_v_offset(offset);
980 if (trace->enabled())
981 offset += extents.second;
982 }
983
984 // If this is a new group, enqueue it in the new top level
985 // items list
986 if (!new_traces_in_group.empty() && new_trace_group)
987 new_top_level_items.push_back(new_trace_group);
988 }
989
990 // Enqueue the remaining logic channels in a group
991 vector< shared_ptr<Channel> > logic_channels;
992 copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
993 [](const shared_ptr<Channel>& c) {
994 return c->type() == sigrok::ChannelType::LOGIC; });
995 const vector< shared_ptr<Trace> > non_grouped_logic_signals =
996 extract_new_traces_for_channels(logic_channels,
997 signal_map, add_traces);
998 const shared_ptr<TraceGroup> non_grouped_trace_group(
999 make_shared<TraceGroup>());
1000 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1001 non_grouped_trace_group->add_child_item(trace);
1002 new_top_level_items.push_back(non_grouped_trace_group);
1003
1004 // Enqueue the remaining channels as free ungrouped traces
1005 const vector< shared_ptr<Trace> > new_top_level_signals =
1006 extract_new_traces_for_channels(channels,
1007 signal_map, add_traces);
1008 new_top_level_items.insert(new_top_level_items.end(),
1009 new_top_level_signals.begin(), new_top_level_signals.end());
1010
1011 // Enqueue any remaining traces i.e. decode traces
1012 new_top_level_items.insert(new_top_level_items.end(),
1013 add_traces.begin(), add_traces.end());
1014
1015 // Remove any removed traces
1016 for (shared_ptr<Trace> trace : remove_traces) {
1017 TraceTreeItemOwner *const owner = trace->owner();
1018 assert(owner);
1019 owner->remove_child_item(trace);
1020 }
1021
1022 // Add and position the pending top levels items
1023 for (auto item : new_top_level_items) {
1024 add_child_item(item);
1025
1026 // Position the item after the last present item
1027 int offset = v_extents().second;
1028 const pair<int, int> extents = item->v_extents();
1029 if (item->enabled())
1030 offset += -extents.first;
1031 item->force_to_v_offset(offset);
1032 if (item->enabled())
1033 offset += extents.second;
1034 }
1035
1036 update_layout();
1037
1038 header_->update();
1039 viewport_->update();
1040}
1041
1042void View::capture_state_updated(int state)
1043{
1044 if (state == Session::Running) {
1045 set_time_unit(util::TimeUnit::Samples);
1046
1047 trigger_markers_.clear();
1048 }
1049
1050 if (state == Session::Stopped) {
1051 // After acquisition has stopped we need to re-calculate the ticks once
1052 // as it's otherwise done when the user pans or zooms, which is too late
1053 calculate_tick_spacing();
1054
1055 // Reset "always zoom to fit", the acquisition has stopped
1056 if (always_zoom_to_fit_) {
1057 always_zoom_to_fit_ = false;
1058 always_zoom_to_fit_changed(false);
1059 }
1060 }
1061}
1062
1063void View::data_updated()
1064{
1065 if (always_zoom_to_fit_ || sticky_scrolling_) {
1066 if (!delayed_view_updater_.isActive())
1067 delayed_view_updater_.start();
1068 } else {
1069 determine_time_unit();
1070 update_scroll();
1071 ruler_->update();
1072 viewport_->update();
1073 }
1074}
1075
1076void View::perform_delayed_view_update()
1077{
1078 if (always_zoom_to_fit_)
1079 zoom_fit(true);
1080
1081 if (sticky_scrolling_) {
1082 // Make right side of the view sticky
1083 double length = 0;
1084 Timestamp offset;
1085 get_scroll_layout(length, offset);
1086
1087 const QSize areaSize = viewport_->size();
1088 length = max(length - areaSize.width(), 0.0);
1089
1090 set_offset(scale_ * length);
1091 }
1092
1093 determine_time_unit();
1094 update_scroll();
1095 ruler_->update();
1096 viewport_->update();
1097}
1098
1099void View::process_sticky_events()
1100{
1101 if (sticky_events_ & TraceTreeItemHExtentsChanged)
1102 update_layout();
1103 if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1104 restack_all_trace_tree_items();
1105 update_scroll();
1106 }
1107
1108 // Clear the sticky events
1109 sticky_events_ = 0;
1110}
1111
1112void View::on_hover_point_changed()
1113{
1114 const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1115 list_by_type<TraceTreeItem>());
1116 for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1117 r->hover_point_changed();
1118}
1119
1120} // namespace view
1121} // namespace pv