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