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