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