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