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