]> sigrok.org Git - pulseview.git/blob - pv/view/view.cpp
Ruler scale calculation optimization
[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-12;
88
89 const int View::MaxScrollValue = INT_MAX / 2;
90 const int View::MaxViewAutoUpdateRate = 25; // No more than 25 Hz with sticky scrolling
91
92 const int View::ScaleUnits[3] = {1, 2, 5};
93
94 View::View(Session &session, QWidget *parent) :
95         QAbstractScrollArea(parent),
96         session_(session),
97         viewport_(new Viewport(*this)),
98         ruler_(new Ruler(*this)),
99         header_(new Header(*this)),
100         scale_(1e-3),
101         offset_(0),
102         updating_scroll_(false),
103         sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
104         always_zoom_to_fit_(false),
105         tick_period_(0.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 = 10.0f;
497         const double MinValueSpacing = 40.0f;
498
499         // Figure out the highest numeric value visible on a label
500         const QSize areaSize = viewport_->size();
501         const double max_time = max(fabs(offset_),
502                 fabs(offset_ + scale_ * areaSize.width()));
503
504         double min_width = SpacingIncrement;
505         double label_width, tick_period_width;
506
507         QFontMetrics m(QApplication::font());
508
509         do {
510                 const double min_period = scale_ * min_width;
511
512                 const int order = (int)floorf(log10f(min_period));
513                 const double order_decimal = pow(10.0, order);
514
515                 // Allow for a margin of error so that a scale unit of 1 can be used.
516                 // Otherwise, for a SU of 1 the tick period will almost always be below
517                 // the min_period by a small amount - and thus skipped in favor of 2.
518                 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
519                 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
520                 double tp_with_margin;
521                 unsigned int unit = 0;
522
523                 do {
524                         tp_with_margin = order_decimal * (ScaleUnits[unit++] + tp_margin);
525                 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
526
527                 tick_period_ = order_decimal * ScaleUnits[unit - 1];
528                 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
529
530                 // Precision is the number of fractional digits required, not
531                 // taking the prefix into account (and it must never be negative)
532                 tick_precision_ = std::max((int)ceil(log10f(1 / tick_period_)), 0);
533
534                 tick_period_width = tick_period_ / scale_;
535
536                 const QString label_text =
537                         format_time(max_time, tick_prefix_, time_unit_, tick_precision_);
538
539                 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
540                         Qt::AlignLeft | Qt::AlignTop, label_text).width() +
541                                 MinValueSpacing;
542
543                 min_width += SpacingIncrement;
544
545         } while (tick_period_width < label_width);
546 }
547
548 void View::update_scroll()
549 {
550         assert(viewport_);
551
552         const QSize areaSize = viewport_->size();
553
554         // Set the horizontal scroll bar
555         double length = 0, offset = 0;
556         get_scroll_layout(length, offset);
557         length = max(length - areaSize.width(), 0.0);
558
559         int major_tick_distance = tick_period_ / scale_;
560
561         horizontalScrollBar()->setPageStep(areaSize.width() / 2);
562         horizontalScrollBar()->setSingleStep(major_tick_distance);
563
564         updating_scroll_ = true;
565
566         if (length < MaxScrollValue) {
567                 horizontalScrollBar()->setRange(0, length);
568                 horizontalScrollBar()->setSliderPosition(offset);
569         } else {
570                 horizontalScrollBar()->setRange(0, MaxScrollValue);
571                 horizontalScrollBar()->setSliderPosition(
572                         offset_ * MaxScrollValue / (scale_ * length));
573         }
574
575         updating_scroll_ = false;
576
577         // Set the vertical scrollbar
578         verticalScrollBar()->setPageStep(areaSize.height());
579         verticalScrollBar()->setSingleStep(areaSize.height() / 8);
580
581         const pair<int, int> extents = v_extents();
582         verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
583                 extents.second - (areaSize.height() / 2));
584 }
585
586 void View::update_layout()
587 {
588         setViewportMargins(
589                 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
590                 ruler_->sizeHint().height(), 0, 0);
591         ruler_->setGeometry(viewport_->x(), 0,
592                 viewport_->width(), ruler_->extended_size_hint().height());
593         header_->setGeometry(0, viewport_->y(),
594                 header_->extended_size_hint().width(), viewport_->height());
595         update_scroll();
596 }
597
598 void View::paint_label(QPainter &p, const QRect &rect, bool hover)
599 {
600         (void)p;
601         (void)rect;
602         (void)hover;
603 }
604
605 QRectF View::label_rect(const QRectF &rect)
606 {
607         (void)rect;
608         return QRectF();
609 }
610
611 RowItemOwner* View::find_prevalent_trace_group(
612         const shared_ptr<sigrok::ChannelGroup> &group,
613         const unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
614                 &signal_map)
615 {
616         assert(group);
617
618         unordered_set<RowItemOwner*> owners;
619         vector<RowItemOwner*> owner_list;
620
621         // Make a set and a list of all the owners
622         for (const auto &channel : group->channels()) {
623                 const auto iter = signal_map.find(channel);
624                 if (iter == signal_map.end())
625                         continue;
626
627                 RowItemOwner *const o = (*iter).second->owner();
628                 owner_list.push_back(o);
629                 owners.insert(o);
630         }
631
632         // Iterate through the list of owners, and find the most prevalent
633         size_t max_prevalence = 0;
634         RowItemOwner *prevalent_owner = nullptr;
635         for (RowItemOwner *owner : owners) {
636                 const size_t prevalence = std::count_if(
637                         owner_list.begin(), owner_list.end(),
638                         [&](RowItemOwner *o) { return o == owner; });
639                 if (prevalence > max_prevalence) {
640                         max_prevalence = prevalence;
641                         prevalent_owner = owner;
642                 }
643         }
644
645         return prevalent_owner;
646 }
647
648 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
649         const vector< shared_ptr<sigrok::Channel> > &channels,
650         const unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
651                 &signal_map,
652         set< shared_ptr<Trace> > &add_list)
653 {
654         vector< shared_ptr<Trace> > filtered_traces;
655
656         for (const auto &channel : channels)
657         {
658                 const auto map_iter = signal_map.find(channel);
659                 if (map_iter == signal_map.end())
660                         continue;
661
662                 shared_ptr<Trace> trace = (*map_iter).second;
663                 const auto list_iter = add_list.find(trace);
664                 if (list_iter == add_list.end())
665                         continue;
666
667                 filtered_traces.push_back(trace);
668                 add_list.erase(list_iter);
669         }
670
671         return filtered_traces;
672 }
673
674 void View::determine_time_unit()
675 {
676         // Check whether we know the sample rate and hence can use time as the unit
677         if (time_unit_ == util::Samples) {
678                 shared_lock<shared_mutex> lock(session().signals_mutex());
679                 const unordered_set< shared_ptr<Signal> > &sigs(session().signals());
680
681                 // Check all signals but...
682                 for (const shared_ptr<Signal> signal : sigs) {
683                         const shared_ptr<SignalData> data = signal->data();
684
685                         // ...only check first segment of each
686                         const vector< shared_ptr<Segment> > segments = data->segments();
687                         if (!segments.empty())
688                                 if (segments[0]->samplerate()) {
689                                         time_unit_ = util::Time;
690                                         break;
691                                 }
692                 }
693         }
694 }
695
696 bool View::eventFilter(QObject *object, QEvent *event)
697 {
698         const QEvent::Type type = event->type();
699         if (type == QEvent::MouseMove) {
700
701                 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
702                 if (object == viewport_)
703                         hover_point_ = mouse_event->pos();
704                 else if (object == ruler_)
705                         hover_point_ = QPoint(mouse_event->x(), 0);
706                 else if (object == header_)
707                         hover_point_ = QPoint(0, mouse_event->y());
708                 else
709                         hover_point_ = QPoint(-1, -1);
710
711                 hover_point_changed();
712
713         } else if (type == QEvent::Leave) {
714                 hover_point_ = QPoint(-1, -1);
715                 hover_point_changed();
716         }
717
718         return QObject::eventFilter(object, event);
719 }
720
721 bool View::viewportEvent(QEvent *e)
722 {
723         switch(e->type()) {
724         case QEvent::Paint:
725         case QEvent::MouseButtonPress:
726         case QEvent::MouseButtonRelease:
727         case QEvent::MouseButtonDblClick:
728         case QEvent::MouseMove:
729         case QEvent::Wheel:
730         case QEvent::TouchBegin:
731         case QEvent::TouchUpdate:
732         case QEvent::TouchEnd:
733                 return false;
734
735         default:
736                 return QAbstractScrollArea::viewportEvent(e);
737         }
738 }
739
740 void View::resizeEvent(QResizeEvent*)
741 {
742         update_layout();
743 }
744
745 void View::row_item_appearance_changed(bool label, bool content)
746 {
747         if (label)
748                 header_->update();
749         if (content)
750                 viewport_->update();
751 }
752
753 void View::time_item_appearance_changed(bool label, bool content)
754 {
755         if (label)
756                 ruler_->update();
757         if (content)
758                 viewport_->update();
759 }
760
761 void View::extents_changed(bool horz, bool vert)
762 {
763         sticky_events_ |=
764                 (horz ? RowItemHExtentsChanged : 0) |
765                 (vert ? RowItemVExtentsChanged : 0);
766         lazy_event_handler_.start();
767 }
768
769 void View::h_scroll_value_changed(int value)
770 {
771         if (updating_scroll_)
772                 return;
773
774         // Disable sticky scrolling when user moves the horizontal scroll bar
775         // during a running acquisition
776         if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
777                 sticky_scrolling_ = false;
778                 sticky_scrolling_changed(false);
779         }
780
781         const int range = horizontalScrollBar()->maximum();
782         if (range < MaxScrollValue)
783                 offset_ = scale_ * value;
784         else {
785                 double length = 0, offset;
786                 get_scroll_layout(length, offset);
787                 offset_ = scale_ * length * value / MaxScrollValue;
788         }
789
790         ruler_->update();
791         viewport_->update();
792 }
793
794 void View::v_scroll_value_changed()
795 {
796         header_->update();
797         viewport_->update();
798 }
799
800 void View::signals_changed()
801 {
802         vector< shared_ptr<RowItem> > new_top_level_items;
803
804         const auto device = session_.device();
805         if (!device)
806                 return;
807
808         shared_ptr<sigrok::Device> sr_dev = device->device();
809         assert(sr_dev);
810
811         // Make a list of traces that are being added, and a list of traces
812         // that are being removed
813         const set<shared_ptr<Trace>> prev_traces = list_by_type<Trace>();
814
815         shared_lock<shared_mutex> lock(session_.signals_mutex());
816         const unordered_set< shared_ptr<Signal> > &sigs(session_.signals());
817
818         set< shared_ptr<Trace> > traces(sigs.begin(), sigs.end());
819
820 #ifdef ENABLE_DECODE
821         const vector< shared_ptr<DecodeTrace> > decode_traces(
822                 session().get_decode_signals());
823         traces.insert(decode_traces.begin(), decode_traces.end());
824 #endif
825
826         set< shared_ptr<Trace> > add_traces;
827         set_difference(traces.begin(), traces.end(),
828                 prev_traces.begin(), prev_traces.end(),
829                 inserter(add_traces, add_traces.begin()));
830
831         set< shared_ptr<Trace> > remove_traces;
832         set_difference(prev_traces.begin(), prev_traces.end(),
833                 traces.begin(), traces.end(),
834                 inserter(remove_traces, remove_traces.begin()));
835
836         // Make a look-up table of sigrok Channels to pulseview Signals
837         unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
838                 signal_map;
839         for (const shared_ptr<Signal> &sig : sigs)
840                 signal_map[sig->channel()] = sig;
841
842         // Populate channel groups
843         for (auto entry : sr_dev->channel_groups())
844         {
845                 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
846
847                 if (group->channels().size() <= 1)
848                         continue;
849
850                 // Find best trace group to add to
851                 RowItemOwner *owner = find_prevalent_trace_group(
852                         group, signal_map);
853
854                 // If there is no trace group, create one
855                 shared_ptr<TraceGroup> new_trace_group;
856                 if (!owner) {
857                         new_trace_group.reset(new TraceGroup());
858                         owner = new_trace_group.get();
859                 }
860
861                 // Extract traces for the trace group, removing them from
862                 // the add list
863                 const vector< shared_ptr<Trace> > new_traces_in_group =
864                         extract_new_traces_for_channels(group->channels(),
865                                 signal_map, add_traces);
866
867                 // Add the traces to the group
868                 const pair<int, int> prev_v_extents = owner->v_extents();
869                 int offset = prev_v_extents.second - prev_v_extents.first;
870                 for (shared_ptr<Trace> trace : new_traces_in_group) {
871                         assert(trace);
872                         owner->add_child_item(trace);
873
874                         const pair<int, int> extents = trace->v_extents();
875                         if (trace->enabled())
876                                 offset += -extents.first;
877                         trace->force_to_v_offset(offset);
878                         if (trace->enabled())
879                                 offset += extents.second;
880                 }
881
882                 // If this is a new group, enqueue it in the new top level
883                 // items list
884                 if (!new_traces_in_group.empty() && new_trace_group)
885                         new_top_level_items.push_back(new_trace_group);
886         }
887
888         // Enqueue the remaining channels as free ungrouped traces
889         const vector< shared_ptr<Trace> > new_top_level_signals =
890                 extract_new_traces_for_channels(sr_dev->channels(),
891                         signal_map, add_traces);
892         new_top_level_items.insert(new_top_level_items.end(),
893                 new_top_level_signals.begin(), new_top_level_signals.end());
894
895         // Enqueue any remaining traces i.e. decode traces
896         new_top_level_items.insert(new_top_level_items.end(),
897                 add_traces.begin(), add_traces.end());
898
899         // Remove any removed traces
900         for (shared_ptr<Trace> trace : remove_traces) {
901                 RowItemOwner *const owner = trace->owner();
902                 assert(owner);
903                 owner->remove_child_item(trace);
904         }
905
906         // Add and position the pending top levels items
907         for (auto item : new_top_level_items) {
908                 add_child_item(item);
909
910                 // Position the item after the last present item
911                 int offset = v_extents().second;
912                 const pair<int, int> extents = item->v_extents();
913                 if (item->enabled())
914                         offset += -extents.first;
915                 item->force_to_v_offset(offset);
916                 if (item->enabled())
917                         offset += extents.second;
918         }
919
920         update_layout();
921
922         header_->update();
923         viewport_->update();
924 }
925
926 void View::capture_state_updated(int state)
927 {
928         if (state == Session::Running)
929                 time_unit_ = util::Samples;
930
931         if (state == Session::Stopped) {
932                 // After acquisition has stopped we need to re-calculate the ticks once
933                 // as it's otherwise done when the user pans or zooms, which is too late
934                 calculate_tick_spacing();
935
936                 // Reset "always zoom to fit", the acquisition has stopped
937                 if (always_zoom_to_fit_) {
938                         always_zoom_to_fit_ = false;
939                         always_zoom_to_fit_changed(false);
940                 }
941         }
942 }
943
944 void View::data_updated()
945 {
946         if (always_zoom_to_fit_ || sticky_scrolling_) {
947                 if (!delayed_view_updater_.isActive())
948                         delayed_view_updater_.start();
949         } else {
950                 determine_time_unit();
951                 update_scroll();
952                 ruler_->update();
953                 viewport_->update();
954         }
955 }
956
957 void View::perform_delayed_view_update()
958 {
959         if (always_zoom_to_fit_)
960                 zoom_fit(true);
961
962         if (sticky_scrolling_) {
963                 // Make right side of the view sticky
964                 double length = 0, offset;
965                 get_scroll_layout(length, offset);
966
967                 const QSize areaSize = viewport_->size();
968                 length = max(length - areaSize.width(), 0.0);
969
970                 offset_ = scale_ * length;
971         }
972
973         determine_time_unit();
974         update_scroll();
975         ruler_->update();
976         viewport_->update();
977 }
978
979 void View::process_sticky_events()
980 {
981         if (sticky_events_ & RowItemHExtentsChanged)
982                 update_layout();
983         if (sticky_events_ & RowItemVExtentsChanged) {
984                 restack_all_row_items();
985                 update_scroll();
986         }
987
988         // Clear the sticky events
989         sticky_events_ = 0;
990 }
991
992 void View::on_hover_point_changed()
993 {
994         for (shared_ptr<RowItem> r : *this)
995                 r->hover_point_changed();
996 }
997
998 } // namespace view
999 } // namespace pv