d2e9006075d698f1af96b9ba8a77aa27df02d96f
[pulseview.git] / pv / views / trace / 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, see <http://www.gnu.org/licenses/>.
18  */
19
20 #ifdef ENABLE_DECODE
21 #include <libsigrokdecode/libsigrokdecode.h>
22 #endif
23
24 #include <extdef.h>
25
26 #include <algorithm>
27 #include <cassert>
28 #include <climits>
29 #include <cmath>
30 #include <iostream>
31 #include <iterator>
32 #include <unordered_set>
33
34 #include <boost/archive/text_iarchive.hpp>
35 #include <boost/archive/text_oarchive.hpp>
36 #include <boost/serialization/serialization.hpp>
37
38 #include <QApplication>
39 #include <QEvent>
40 #include <QFontMetrics>
41 #include <QMenu>
42 #include <QMouseEvent>
43 #include <QScrollBar>
44 #include <QVBoxLayout>
45
46 #include <libsigrokcxx/libsigrokcxx.hpp>
47
48 #include "analogsignal.hpp"
49 #include "header.hpp"
50 #include "logicsignal.hpp"
51 #include "ruler.hpp"
52 #include "signal.hpp"
53 #include "tracegroup.hpp"
54 #include "triggermarker.hpp"
55 #include "view.hpp"
56 #include "viewport.hpp"
57
58 #include "pv/data/logic.hpp"
59 #include "pv/data/logicsegment.hpp"
60 #include "pv/devices/device.hpp"
61 #include "pv/globalsettings.hpp"
62 #include "pv/session.hpp"
63 #include "pv/util.hpp"
64
65 #ifdef ENABLE_DECODE
66 #include "decodetrace.hpp"
67 #endif
68
69 using pv::data::SignalData;
70 using pv::data::Segment;
71 using pv::util::TimeUnit;
72 using pv::util::Timestamp;
73
74 using std::back_inserter;
75 using std::copy_if;
76 using std::count_if;
77 using std::inserter;
78 using std::max;
79 using std::make_pair;
80 using std::make_shared;
81 using std::min;
82 using std::numeric_limits;
83 using std::pair;
84 using std::set;
85 using std::set_difference;
86 using std::shared_ptr;
87 using std::stringstream;
88 using std::unordered_map;
89 using std::unordered_set;
90 using std::vector;
91
92 namespace pv {
93 namespace views {
94 namespace trace {
95
96 const Timestamp View::MaxScale("1e9");
97 const Timestamp View::MinScale("1e-12");
98
99 const int View::MaxScrollValue = INT_MAX / 2;
100
101 const int View::ScaleUnits[3] = {1, 2, 5};
102
103
104 CustomScrollArea::CustomScrollArea(QWidget *parent) :
105         QAbstractScrollArea(parent)
106 {
107 }
108
109 bool CustomScrollArea::viewportEvent(QEvent *event)
110 {
111         switch (event->type()) {
112         case QEvent::Paint:
113         case QEvent::MouseButtonPress:
114         case QEvent::MouseButtonRelease:
115         case QEvent::MouseButtonDblClick:
116         case QEvent::MouseMove:
117         case QEvent::Wheel:
118         case QEvent::TouchBegin:
119         case QEvent::TouchUpdate:
120         case QEvent::TouchEnd:
121                 return false;
122         default:
123                 return QAbstractScrollArea::viewportEvent(event);
124         }
125 }
126
127 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
128         ViewBase(session, is_main_view, parent),
129
130         // Note: Place defaults in View::reset_view_state(), not here
131         splitter_(new QSplitter()),
132         header_was_shrunk_(false),  // The splitter remains unchanged after a reset, so this goes here
133         sticky_scrolling_(false),  // Default setting is set in MainWindow::setup_ui()
134         scroll_needs_defaults_(true)
135 {
136         QVBoxLayout *root_layout = new QVBoxLayout(this);
137         root_layout->setContentsMargins(0, 0, 0, 0);
138         root_layout->addWidget(splitter_);
139
140         viewport_ = new Viewport(*this);
141         scrollarea_ = new CustomScrollArea(splitter_);
142         scrollarea_->setViewport(viewport_);
143         scrollarea_->setFrameShape(QFrame::NoFrame);
144
145         ruler_ = new Ruler(*this);
146
147         header_ = new Header(*this);
148         header_->setMinimumWidth(10);  // So that the arrow tips show at least
149
150         // We put the header into a simple layout so that we can add the top margin,
151         // allowing us to make it line up with the bottom of the ruler
152         QWidget *header_container = new QWidget();
153         header_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
154         QVBoxLayout *header_layout = new QVBoxLayout(header_container);
155         header_layout->setContentsMargins(0, ruler_->sizeHint().height(), 0, 0);
156         header_layout->addWidget(header_);
157
158         // To let the ruler and scrollarea be on the same split pane, we need a layout
159         QWidget *trace_container = new QWidget();
160         trace_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
161         QVBoxLayout *trace_layout = new QVBoxLayout(trace_container);
162         trace_layout->setSpacing(0);  // We don't want space between the ruler and scrollarea
163         trace_layout->setContentsMargins(0, 0, 0, 0);
164         trace_layout->addWidget(ruler_);
165         trace_layout->addWidget(scrollarea_);
166
167         splitter_->addWidget(header_container);
168         splitter_->addWidget(trace_container);
169         splitter_->setHandleWidth(1);  // Don't show a visible rubber band
170         splitter_->setCollapsible(0, false);  // Prevent the header from collapsing
171         splitter_->setCollapsible(1, false);  // Prevent the traces from collapsing
172         splitter_->setStretchFactor(0, 0);  // Prevent the panes from being resized
173         splitter_->setStretchFactor(1, 1);  // when the entire view is resized
174         splitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
175
176         viewport_->installEventFilter(this);
177         ruler_->installEventFilter(this);
178         header_->installEventFilter(this);
179
180         // Set up settings and event handlers
181         GlobalSettings settings;
182         colored_bg_ = settings.value(GlobalSettings::Key_View_ColoredBG).toBool();
183         snap_distance_ = settings.value(GlobalSettings::Key_View_SnapDistance).toInt();
184
185         GlobalSettings::add_change_handler(this);
186
187         connect(scrollarea_->horizontalScrollBar(), SIGNAL(valueChanged(int)),
188                 this, SLOT(h_scroll_value_changed(int)));
189         connect(scrollarea_->verticalScrollBar(), SIGNAL(valueChanged(int)),
190                 this, SLOT(v_scroll_value_changed()));
191
192         connect(header_, SIGNAL(selection_changed()),
193                 ruler_, SLOT(clear_selection()));
194         connect(ruler_, SIGNAL(selection_changed()),
195                 header_, SLOT(clear_selection()));
196
197         connect(header_, SIGNAL(selection_changed()),
198                 this, SIGNAL(selection_changed()));
199         connect(ruler_, SIGNAL(selection_changed()),
200                 this, SIGNAL(selection_changed()));
201
202         connect(splitter_, SIGNAL(splitterMoved(int, int)),
203                 this, SLOT(on_splitter_moved()));
204
205         connect(&lazy_event_handler_, SIGNAL(timeout()),
206                 this, SLOT(process_sticky_events()));
207         lazy_event_handler_.setSingleShot(true);
208
209         // Set up local keyboard shortcuts
210         zoom_in_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Plus), this,
211                         SLOT(on_zoom_in_shortcut_triggered()), nullptr, Qt::WidgetWithChildrenShortcut);
212         zoom_in_shortcut_->setAutoRepeat(false);
213
214         zoom_out_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Minus), this,
215                 SLOT(on_zoom_out_shortcut_triggered()), nullptr, Qt::WidgetWithChildrenShortcut);
216         zoom_out_shortcut_->setAutoRepeat(false);
217
218         zoom_in_shortcut_2_ = new QShortcut(QKeySequence(Qt::Key_Up), this,
219                 SLOT(on_zoom_in_shortcut_triggered()), nullptr, Qt::WidgetWithChildrenShortcut);
220         zoom_out_shortcut_2_ = new QShortcut(QKeySequence(Qt::Key_Down), this,
221                 SLOT(on_zoom_out_shortcut_triggered()), nullptr, Qt::WidgetWithChildrenShortcut);
222
223         home_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Home), this,
224                 SLOT(on_scroll_to_start_shortcut_triggered()), nullptr, Qt::WidgetWithChildrenShortcut);
225         home_shortcut_->setAutoRepeat(false);
226
227         end_shortcut_ = new QShortcut(QKeySequence(Qt::Key_End), this,
228                 SLOT(on_scroll_to_end_shortcut_triggered()), nullptr, Qt::WidgetWithChildrenShortcut);
229         end_shortcut_->setAutoRepeat(false);
230
231         // Trigger the initial event manually. The default device has signals
232         // which were created before this object came into being
233         signals_changed();
234
235         // Make sure the transparent widgets are on the top
236         ruler_->raise();
237         header_->raise();
238
239         reset_view_state();
240 }
241
242 View::~View()
243 {
244         GlobalSettings::remove_change_handler(this);
245 }
246
247 ViewType View::get_type() const
248 {
249         return ViewTypeTrace;
250 }
251
252 void View::reset_view_state()
253 {
254         ViewBase::reset_view_state();
255
256         segment_display_mode_ = Trace::ShowLastSegmentOnly;
257         segment_selectable_ = false;
258         scale_ = 1e-3;
259         offset_ = 0;
260         ruler_offset_ = 0;
261         updating_scroll_ = false;
262         settings_restored_ = false;
263         always_zoom_to_fit_ = false;
264         tick_period_ = 0;
265         tick_prefix_ = pv::util::SIPrefix::yocto;
266         tick_precision_ = 0;
267         time_unit_ = util::TimeUnit::Time;
268         show_cursors_ = false;
269         cursors_ = make_shared<CursorPair>(*this);
270         next_flag_text_ = 'A';
271         trigger_markers_.clear();
272         hover_widget_ = nullptr;
273         hover_point_ = QPoint(-1, -1);
274         scroll_needs_defaults_ = true;
275         saved_v_offset_ = 0;
276         scale_at_acq_start_ = 0;
277         offset_at_acq_start_ = 0;
278         suppress_zoom_to_fit_after_acq_ = false;
279
280         show_cursors_ = false;
281         cursor_state_changed(show_cursors_);
282         flags_.clear();
283
284         // Update the zoom state
285         calculate_tick_spacing();
286
287         // Make sure the standard bar's segment selector is in sync
288         set_segment_display_mode(segment_display_mode_);
289 }
290
291 Session& View::session()
292 {
293         return session_;
294 }
295
296 const Session& View::session() const
297 {
298         return session_;
299 }
300
301 unordered_set< shared_ptr<Signal> > View::signals() const
302 {
303         return signals_;
304 }
305
306 shared_ptr<Signal> View::get_signal_by_signalbase(shared_ptr<data::SignalBase> base) const
307 {
308         shared_ptr<Signal> ret_val;
309
310         for (const shared_ptr<Signal> s : signals_)
311                 if (s->base() == base) {
312                         ret_val = s;
313                         break;
314                 }
315
316         return ret_val;
317 }
318
319 void View::clear_signals()
320 {
321         ViewBase::clear_signals();
322         signals_.clear();
323 }
324
325 void View::add_signal(const shared_ptr<Signal> signal)
326 {
327         ViewBase::add_signalbase(signal->base());
328         signals_.insert(signal);
329
330         signal->set_segment_display_mode(segment_display_mode_);
331         signal->set_current_segment(current_segment_);
332
333         connect(signal->base().get(), SIGNAL(name_changed(const QString&)),
334                 this, SLOT(on_signal_name_changed()));
335 }
336
337 #ifdef ENABLE_DECODE
338 void View::clear_decode_signals()
339 {
340         ViewBase::clear_decode_signals();
341         decode_traces_.clear();
342 }
343
344 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
345 {
346         ViewBase::add_decode_signal(signal);
347
348         shared_ptr<DecodeTrace> d(
349                 new DecodeTrace(session_, signal, decode_traces_.size()));
350         decode_traces_.push_back(d);
351
352         d->set_segment_display_mode(segment_display_mode_);
353         d->set_current_segment(current_segment_);
354
355         connect(signal.get(), SIGNAL(name_changed(const QString&)),
356                 this, SLOT(on_signal_name_changed()));
357 }
358
359 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
360 {
361         for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
362                 if ((*i)->base() == signal) {
363                         decode_traces_.erase(i);
364                         signals_changed();
365                         return;
366                 }
367
368         ViewBase::remove_decode_signal(signal);
369 }
370 #endif
371
372 shared_ptr<Signal> View::get_signal_under_mouse_cursor() const
373 {
374         return signal_under_mouse_cursor_;
375 }
376
377 View* View::view()
378 {
379         return this;
380 }
381
382 const View* View::view() const
383 {
384         return this;
385 }
386
387 Viewport* View::viewport()
388 {
389         return viewport_;
390 }
391
392 const Viewport* View::viewport() const
393 {
394         return viewport_;
395 }
396
397 const Ruler* View::ruler() const
398 {
399         return ruler_;
400 }
401
402 void View::save_settings(QSettings &settings) const
403 {
404         settings.setValue("scale", scale_);
405         settings.setValue("v_offset",
406                 scrollarea_->verticalScrollBar()->sliderPosition());
407
408         settings.setValue("splitter_state", splitter_->saveState());
409         settings.setValue("segment_display_mode", segment_display_mode_);
410
411         {
412                 stringstream ss;
413                 boost::archive::text_oarchive oa(ss);
414                 oa << boost::serialization::make_nvp("offset", offset_);
415                 settings.setValue("offset", QString::fromStdString(ss.str()));
416         }
417
418         for (const shared_ptr<Signal>& signal : signals_) {
419                 settings.beginGroup(signal->base()->internal_name());
420                 signal->save_settings(settings);
421                 settings.endGroup();
422         }
423 }
424
425 void View::restore_settings(QSettings &settings)
426 {
427         // Note: It is assumed that this function is only called once,
428         // immediately after restoring a previous session.
429
430         if (settings.contains("scale"))
431                 set_scale(settings.value("scale").toDouble());
432
433         if (settings.contains("offset")) {
434                 util::Timestamp offset;
435                 stringstream ss;
436                 ss << settings.value("offset").toString().toStdString();
437
438                 try {
439                         boost::archive::text_iarchive ia(ss);
440                         ia >> boost::serialization::make_nvp("offset", offset);
441                         // This also updates ruler_offset_
442                         set_offset(offset);
443                 } catch (boost::archive::archive_exception&) {
444                         qDebug() << "Could not restore the view offset";
445                 }
446         }
447
448         if (settings.contains("splitter_state"))
449                 splitter_->restoreState(settings.value("splitter_state").toByteArray());
450
451         if (settings.contains("segment_display_mode"))
452                 set_segment_display_mode(
453                         (Trace::SegmentDisplayMode)(settings.value("segment_display_mode").toInt()));
454
455         for (shared_ptr<Signal> signal : signals_) {
456                 settings.beginGroup(signal->base()->internal_name());
457                 signal->restore_settings(settings);
458                 settings.endGroup();
459         }
460
461         if (settings.contains("v_offset")) {
462                 saved_v_offset_ = settings.value("v_offset").toInt();
463                 set_v_offset(saved_v_offset_);
464                 scroll_needs_defaults_ = false;
465                 // Note: see eventFilter() for additional information
466         }
467
468         settings_restored_ = true;
469         suppress_zoom_to_fit_after_acq_ = true;
470
471         // Update the ruler so that it uses the new scale
472         calculate_tick_spacing();
473 }
474
475 vector< shared_ptr<TimeItem> > View::time_items() const
476 {
477         const vector<shared_ptr<Flag>> f(flags());
478         vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
479
480         if (cursors_) {
481                 items.push_back(cursors_);
482                 items.push_back(cursors_->first());
483                 items.push_back(cursors_->second());
484         }
485
486         for (auto& trigger_marker : trigger_markers_)
487                 items.push_back(trigger_marker);
488
489         return items;
490 }
491
492 double View::scale() const
493 {
494         return scale_;
495 }
496
497 void View::set_scale(double scale)
498 {
499         if (scale_ != scale) {
500                 scale_ = scale;
501                 scale_changed();
502         }
503 }
504
505 void View::set_offset(const pv::util::Timestamp& offset, bool force_update)
506 {
507         if ((offset_ != offset) || force_update) {
508                 offset_ = offset;
509                 ruler_offset_ = offset_ + zero_offset_;
510                 offset_changed();
511         }
512 }
513
514 const Timestamp& View::offset() const
515 {
516         return offset_;
517 }
518
519 const Timestamp& View::ruler_offset() const
520 {
521         return ruler_offset_;
522 }
523
524 void View::set_zero_position(const pv::util::Timestamp& position)
525 {
526         zero_offset_ = -position;
527
528         // Force an immediate update of the offsets
529         set_offset(offset_, true);
530         ruler_->update();
531 }
532
533 void View::reset_zero_position()
534 {
535         zero_offset_ = 0;
536
537         // Force an immediate update of the offsets
538         set_offset(offset_, true);
539         ruler_->update();
540 }
541
542 pv::util::Timestamp View::zero_offset() const
543 {
544         return zero_offset_;
545 }
546
547 int View::owner_visual_v_offset() const
548 {
549         return -scrollarea_->verticalScrollBar()->sliderPosition();
550 }
551
552 void View::set_v_offset(int offset)
553 {
554         scrollarea_->verticalScrollBar()->setSliderPosition(offset);
555         header_->update();
556         viewport_->update();
557 }
558
559 void View::set_h_offset(int offset)
560 {
561         scrollarea_->horizontalScrollBar()->setSliderPosition(offset);
562         header_->update();
563         viewport_->update();
564 }
565
566 int View::get_h_scrollbar_maximum() const
567 {
568         return scrollarea_->horizontalScrollBar()->maximum();
569 }
570
571 unsigned int View::depth() const
572 {
573         return 0;
574 }
575
576 uint32_t View::current_segment() const
577 {
578         return current_segment_;
579 }
580
581 pv::util::SIPrefix View::tick_prefix() const
582 {
583         return tick_prefix_;
584 }
585
586 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
587 {
588         if (tick_prefix_ != tick_prefix) {
589                 tick_prefix_ = tick_prefix;
590                 tick_prefix_changed();
591         }
592 }
593
594 unsigned int View::tick_precision() const
595 {
596         return tick_precision_;
597 }
598
599 void View::set_tick_precision(unsigned tick_precision)
600 {
601         if (tick_precision_ != tick_precision) {
602                 tick_precision_ = tick_precision;
603                 tick_precision_changed();
604         }
605 }
606
607 const pv::util::Timestamp& View::tick_period() const
608 {
609         return tick_period_;
610 }
611
612 unsigned int View::minor_tick_count() const
613 {
614         return minor_tick_count_;
615 }
616
617 void View::set_tick_period(const pv::util::Timestamp& tick_period)
618 {
619         if (tick_period_ != tick_period) {
620                 tick_period_ = tick_period;
621                 tick_period_changed();
622         }
623 }
624
625 TimeUnit View::time_unit() const
626 {
627         return time_unit_;
628 }
629
630 void View::set_time_unit(pv::util::TimeUnit time_unit)
631 {
632         if (time_unit_ != time_unit) {
633                 time_unit_ = time_unit;
634                 time_unit_changed();
635         }
636 }
637
638 void View::set_current_segment(uint32_t segment_id)
639 {
640         current_segment_ = segment_id;
641
642         for (const shared_ptr<Signal>& signal : signals_)
643                 signal->set_current_segment(current_segment_);
644 #ifdef ENABLE_DECODE
645         for (shared_ptr<DecodeTrace>& dt : decode_traces_)
646                 dt->set_current_segment(current_segment_);
647 #endif
648
649         vector<util::Timestamp> triggers = session_.get_triggers(current_segment_);
650
651         trigger_markers_.clear();
652         for (util::Timestamp timestamp : triggers)
653                 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, timestamp));
654
655         // When enabled, the first trigger for this segment is used as the zero position
656         GlobalSettings settings;
657         bool trigger_is_zero_time = settings.value(GlobalSettings::Key_View_TriggerIsZeroTime).toBool();
658
659         if (trigger_is_zero_time && (triggers.size() > 0))
660                 set_zero_position(triggers.front());
661
662         viewport_->update();
663
664         segment_changed(segment_id);
665 }
666
667 bool View::segment_is_selectable() const
668 {
669         return segment_selectable_;
670 }
671
672 Trace::SegmentDisplayMode View::segment_display_mode() const
673 {
674         return segment_display_mode_;
675 }
676
677 void View::set_segment_display_mode(Trace::SegmentDisplayMode mode)
678 {
679         segment_display_mode_ = mode;
680
681         for (const shared_ptr<Signal>& signal : signals_)
682                 signal->set_segment_display_mode(mode);
683
684         uint32_t last_segment = session_.get_segment_count() - 1;
685
686         switch (mode) {
687         case Trace::ShowLastSegmentOnly:
688                 if (current_segment_ != last_segment)
689                         set_current_segment(last_segment);
690                 break;
691
692         case Trace::ShowLastCompleteSegmentOnly:
693                 // Do nothing if we only have one segment so far
694                 if (last_segment > 0) {
695                         // If the last segment isn't complete, the previous one must be
696                         uint32_t segment_id =
697                                 (session_.all_segments_complete(last_segment)) ?
698                                 last_segment : last_segment - 1;
699
700                         if (current_segment_ != segment_id)
701                                 set_current_segment(segment_id);
702                 }
703                 break;
704
705         case Trace::ShowSingleSegmentOnly:
706         case Trace::ShowAllSegments:
707         case Trace::ShowAccumulatedIntensity:
708         default:
709                 // Current segment remains as-is
710                 break;
711         }
712
713         segment_selectable_ = true;
714
715         if ((mode == Trace::ShowAllSegments) || (mode == Trace::ShowAccumulatedIntensity))
716                 segment_selectable_ = false;
717
718         viewport_->update();
719
720         segment_display_mode_changed((int)mode, segment_selectable_);
721 }
722
723 void View::zoom(double steps)
724 {
725         zoom(steps, viewport_->width() / 2);
726 }
727
728 void View::zoom(double steps, int offset)
729 {
730         set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
731 }
732
733 void View::zoom_fit(bool gui_state)
734 {
735         // Act as one-shot when stopped, toggle along with the GUI otherwise
736         if (session_.get_capture_state() == Session::Stopped) {
737                 always_zoom_to_fit_ = false;
738                 always_zoom_to_fit_changed(false);
739         } else {
740                 always_zoom_to_fit_ = gui_state;
741                 always_zoom_to_fit_changed(gui_state);
742         }
743
744         const pair<Timestamp, Timestamp> extents = get_time_extents();
745         const Timestamp delta = extents.second - extents.first;
746         if (delta < Timestamp("1e-12"))
747                 return;
748
749         assert(viewport_);
750         const int w = viewport_->width();
751         if (w <= 0)
752                 return;
753
754         const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
755         set_scale_offset(scale.convert_to<double>(), extents.first);
756 }
757
758 void View::set_scale_offset(double scale, const Timestamp& offset)
759 {
760         // Disable sticky scrolling / always zoom to fit when acquisition runs
761         // and user drags the viewport
762         if ((scale_ == scale) && (offset_ != offset) &&
763                         (session_.get_capture_state() == Session::Running)) {
764
765                 if (sticky_scrolling_) {
766                         sticky_scrolling_ = false;
767                         sticky_scrolling_changed(false);
768                 }
769
770                 if (always_zoom_to_fit_) {
771                         always_zoom_to_fit_ = false;
772                         always_zoom_to_fit_changed(false);
773                 }
774         }
775
776         set_scale(scale);
777         set_offset(offset);
778
779         calculate_tick_spacing();
780
781         update_scroll();
782         ruler_->update();
783         viewport_->update();
784 }
785
786 set< shared_ptr<SignalData> > View::get_visible_data() const
787 {
788         // Make a set of all the visible data objects
789         set< shared_ptr<SignalData> > visible_data;
790         for (const shared_ptr<Signal>& sig : signals_)
791                 if (sig->enabled())
792                         visible_data.insert(sig->data());
793
794         return visible_data;
795 }
796
797 pair<Timestamp, Timestamp> View::get_time_extents() const
798 {
799         boost::optional<Timestamp> left_time, right_time;
800         const set< shared_ptr<SignalData> > visible_data = get_visible_data();
801         for (const shared_ptr<SignalData>& d : visible_data) {
802                 const vector< shared_ptr<Segment> > segments = d->segments();
803                 for (const shared_ptr<Segment>& s : segments) {
804                         double samplerate = s->samplerate();
805                         samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
806
807                         const Timestamp start_time = s->start_time();
808                         left_time = left_time ?
809                                 min(*left_time, start_time) :
810                                                 start_time;
811                         right_time = right_time ?
812                                 max(*right_time, start_time + d->max_sample_count() / samplerate) :
813                                                  start_time + d->max_sample_count() / samplerate;
814                 }
815         }
816
817         if (!left_time || !right_time)
818                 return make_pair(0, 0);
819
820         assert(*left_time < *right_time);
821         return make_pair(*left_time, *right_time);
822 }
823
824 bool View::colored_bg() const
825 {
826         return colored_bg_;
827 }
828
829 bool View::cursors_shown() const
830 {
831         return show_cursors_;
832 }
833
834 void View::show_cursors(bool show)
835 {
836         if (show_cursors_ != show) {
837                 show_cursors_ = show;
838
839                 cursor_state_changed(show);
840                 ruler_->update();
841                 viewport_->update();
842         }
843 }
844
845 void View::set_cursors(pv::util::Timestamp& first, pv::util::Timestamp& second)
846 {
847         assert(cursors_);
848
849         cursors_->first()->set_time(first);
850         cursors_->second()->set_time(second);
851
852         ruler_->update();
853         viewport_->update();
854 }
855
856 void View::centre_cursors()
857 {
858         assert(cursors_);
859
860         const double time_width = scale_ * viewport_->width();
861         cursors_->first()->set_time(offset_ + time_width * 0.4);
862         cursors_->second()->set_time(offset_ + time_width * 0.6);
863
864         ruler_->update();
865         viewport_->update();
866 }
867
868 shared_ptr<CursorPair> View::cursors() const
869 {
870         return cursors_;
871 }
872
873 shared_ptr<Flag> View::add_flag(const Timestamp& time)
874 {
875         shared_ptr<Flag> flag =
876                 make_shared<Flag>(*this, time, QString("%1").arg(next_flag_text_));
877         flags_.push_back(flag);
878
879         next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
880                 (next_flag_text_ + 1);
881
882         time_item_appearance_changed(true, true);
883         return flag;
884 }
885
886 void View::remove_flag(shared_ptr<Flag> flag)
887 {
888         flags_.remove(flag);
889         time_item_appearance_changed(true, true);
890 }
891
892 vector< shared_ptr<Flag> > View::flags() const
893 {
894         vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
895         stable_sort(flags.begin(), flags.end(),
896                 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
897                         return a->time() < b->time();
898                 });
899
900         return flags;
901 }
902
903 const QPoint& View::hover_point() const
904 {
905         return hover_point_;
906 }
907
908 const QWidget* View::hover_widget() const
909 {
910         return hover_widget_;
911 }
912
913 int64_t View::get_nearest_level_change(const QPoint &p)
914 {
915         // Is snapping disabled?
916         if (snap_distance_ == 0)
917                 return -1;
918
919         struct entry_t {
920                 entry_t(shared_ptr<Signal> s) :
921                         signal(s), delta(numeric_limits<int64_t>::max()), sample(-1), is_dense(false) {}
922                 shared_ptr<Signal> signal;
923                 int64_t delta;
924                 int64_t sample;
925                 bool is_dense;
926         };
927
928         vector<entry_t> list;
929
930         // Create list of signals to consider
931         if (signal_under_mouse_cursor_)
932                 list.emplace_back(signal_under_mouse_cursor_);
933         else
934                 for (shared_ptr<Signal> s : signals_) {
935                         if (!s->enabled())
936                                 continue;
937
938                         list.emplace_back(s);
939                 }
940
941         // Get data for listed signals
942         for (entry_t &e : list) {
943                 // Calculate sample number from cursor position
944                 const double samples_per_pixel = e.signal->base()->get_samplerate() * scale();
945                 const int64_t x_offset = offset().convert_to<double>() / scale();
946                 const int64_t sample_num = max(((x_offset + p.x()) * samples_per_pixel), 0.0);
947
948                 vector<data::LogicSegment::EdgePair> edges =
949                         e.signal->get_nearest_level_changes(sample_num);
950
951                 if (edges.empty())
952                         continue;
953
954                 // Check first edge
955                 const int64_t first_sample_delta = abs(sample_num - edges.front().first);
956                 const int64_t first_delta = first_sample_delta / samples_per_pixel;
957                 e.delta = first_delta;
958                 e.sample = edges.front().first;
959
960                 // Check second edge if available
961                 if (edges.size() == 2) {
962                         // Note: -1 because this is usually the right edge and sample points are left-aligned
963                         const int64_t second_sample_delta = abs(sample_num - edges.back().first - 1);
964                         const int64_t second_delta = second_sample_delta / samples_per_pixel;
965
966                         // If both edges are too close, we mark this signal as being dense
967                         if ((first_delta + second_delta) <= snap_distance_)
968                                 e.is_dense = true;
969
970                         if (second_delta < first_delta) {
971                                 e.delta = second_delta;
972                                 e.sample = edges.back().first;
973                         }
974                 }
975         }
976
977         // Look for the best match: non-dense first, then dense
978         entry_t *match = nullptr;
979
980         for (entry_t &e : list) {
981                 if (e.delta > snap_distance_ || e.is_dense)
982                         continue;
983
984                 if (match) {
985                         if (e.delta < match->delta)
986                                 match = &e;
987                 } else
988                         match = &e;
989         }
990
991         if (!match) {
992                 for (entry_t &e : list) {
993                         if (!e.is_dense)
994                                 continue;
995
996                         if (match) {
997                                 if (e.delta < match->delta)
998                                         match = &e;
999                         } else
1000                                 match = &e;
1001                 }
1002         }
1003
1004         if (match) {
1005                 // Somewhat ugly hack to make TimeItem::drag_by() work
1006                 signal_under_mouse_cursor_ = match->signal;
1007
1008                 return match->sample;
1009         }
1010
1011         return -1;
1012 }
1013
1014 void View::restack_all_trace_tree_items()
1015 {
1016         // Make a list of owners that is sorted from deepest first
1017         const vector<shared_ptr<TraceTreeItem>> items(
1018                 list_by_type<TraceTreeItem>());
1019         set< TraceTreeItemOwner* > owners;
1020         for (const auto &r : items)
1021                 owners.insert(r->owner());
1022         vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
1023         sort(sorted_owners.begin(), sorted_owners.end(),
1024                 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
1025                         return a->depth() > b->depth(); });
1026
1027         // Restack the items recursively
1028         for (auto &o : sorted_owners)
1029                 o->restack_items();
1030
1031         // Animate the items to their destination
1032         for (const auto &i : items)
1033                 i->animate_to_layout_v_offset();
1034 }
1035
1036 int View::header_width() const
1037 {
1038          return header_->extended_size_hint().width();
1039 }
1040
1041 void View::on_setting_changed(const QString &key, const QVariant &value)
1042 {
1043         GlobalSettings settings;
1044
1045         if (key == GlobalSettings::Key_View_ColoredBG) {
1046                 colored_bg_ = settings.value(GlobalSettings::Key_View_ColoredBG).toBool();
1047                 viewport_->update();
1048         }
1049
1050         if ((key == GlobalSettings::Key_View_ShowSamplingPoints) ||
1051            (key == GlobalSettings::Key_View_ShowAnalogMinorGrid))
1052                 viewport_->update();
1053
1054         if (key == GlobalSettings::Key_View_TriggerIsZeroTime)
1055                 on_settingViewTriggerIsZeroTime_changed(value);
1056
1057         if (key == GlobalSettings::Key_View_SnapDistance)
1058                 snap_distance_ = settings.value(GlobalSettings::Key_View_SnapDistance).toInt();
1059 }
1060
1061 void View::trigger_event(int segment_id, util::Timestamp location)
1062 {
1063         // TODO This doesn't work if we're showing multiple segments at once
1064         if ((uint32_t)segment_id != current_segment_)
1065                 return;
1066
1067         // Set zero location if the Key_View_TriggerIsZeroTime setting is set and
1068         // if this is the first trigger for this segment.
1069         GlobalSettings settings;
1070         bool trigger_is_zero_time = settings.value(GlobalSettings::Key_View_TriggerIsZeroTime).toBool();
1071
1072         size_t trigger_count = session_.get_triggers(current_segment_).size();
1073
1074         if (trigger_is_zero_time && trigger_count == 1)
1075                 set_zero_position(location);
1076
1077         trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
1078 }
1079
1080 void View::get_scroll_layout(double &length, Timestamp &offset) const
1081 {
1082         const pair<Timestamp, Timestamp> extents = get_time_extents();
1083         length = ((extents.second - extents.first) / scale_).convert_to<double>();
1084         offset = offset_ / scale_;
1085 }
1086
1087 void View::set_zoom(double scale, int offset)
1088 {
1089         // Reset the "always zoom to fit" feature as the user changed the zoom
1090         always_zoom_to_fit_ = false;
1091         always_zoom_to_fit_changed(false);
1092
1093         const Timestamp cursor_offset = offset_ + scale_ * offset;
1094         const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
1095         const Timestamp new_offset = cursor_offset - new_scale * offset;
1096         set_scale_offset(new_scale.convert_to<double>(), new_offset);
1097 }
1098
1099 void View::calculate_tick_spacing()
1100 {
1101         const double SpacingIncrement = 10.0f;
1102         const double MinValueSpacing = 40.0f;
1103
1104         // Figure out the highest numeric value visible on a label
1105         const QSize areaSize = viewport_->size();
1106         const Timestamp max_time = max(fabs(offset_),
1107                 fabs(offset_ + scale_ * areaSize.width()));
1108
1109         double min_width = SpacingIncrement;
1110         double label_width, tick_period_width;
1111
1112         QFontMetrics m(QApplication::font());
1113
1114         // Copies of the member variables with the same name, used in the calculation
1115         // and written back afterwards, so that we don't emit signals all the time
1116         // during the calculation.
1117         pv::util::Timestamp tick_period = tick_period_;
1118         pv::util::SIPrefix tick_prefix = tick_prefix_;
1119         unsigned tick_precision = tick_precision_;
1120
1121         do {
1122                 const double min_period = scale_ * min_width;
1123
1124                 const int order = (int)floorf(log10f(min_period));
1125                 const pv::util::Timestamp order_decimal =
1126                         pow(pv::util::Timestamp(10), order);
1127
1128                 // Allow for a margin of error so that a scale unit of 1 can be used.
1129                 // Otherwise, for a SU of 1 the tick period will almost always be below
1130                 // the min_period by a small amount - and thus skipped in favor of 2.
1131                 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
1132                 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
1133                 double tp_with_margin;
1134                 unsigned int unit = 0;
1135
1136                 do {
1137                         tp_with_margin = order_decimal.convert_to<double>() *
1138                                 (ScaleUnits[unit++] + tp_margin);
1139                 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
1140
1141                 minor_tick_count_ = (unit == 2) ? 4 : 5;
1142                 tick_period = order_decimal * ScaleUnits[unit - 1];
1143                 tick_prefix = static_cast<pv::util::SIPrefix>(
1144                         (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
1145
1146                 // Precision is the number of fractional digits required, not
1147                 // taking the prefix into account (and it must never be negative)
1148                 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
1149
1150                 tick_period_width = (tick_period / scale_).convert_to<double>();
1151
1152                 const QString label_text = Ruler::format_time_with_distance(
1153                         tick_period, max_time, tick_prefix, time_unit_, tick_precision);
1154
1155                 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
1156                         Qt::AlignLeft | Qt::AlignTop, label_text).width() +
1157                                 MinValueSpacing;
1158
1159                 min_width += SpacingIncrement;
1160         } while (tick_period_width < label_width);
1161
1162         set_tick_period(tick_period);
1163         set_tick_prefix(tick_prefix);
1164         set_tick_precision(tick_precision);
1165 }
1166
1167 void View::adjust_top_margin()
1168 {
1169         assert(viewport_);
1170
1171         const QSize areaSize = viewport_->size();
1172
1173         const pair<int, int> extents = v_extents();
1174         const int top_margin = owner_visual_v_offset() + extents.first;
1175         const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
1176
1177         // Do we have empty space at the top while the last trace goes out of screen?
1178         if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
1179                 const int trace_height = extents.second - extents.first;
1180
1181                 // Center everything vertically if there is enough space
1182                 if (areaSize.height() >= trace_height)
1183                         set_v_offset(extents.first -
1184                                 ((areaSize.height() - trace_height) / 2));
1185                 else
1186                         // Remove the top margin to make as many traces fit on screen as possible
1187                         set_v_offset(extents.first);
1188         }
1189 }
1190
1191 void View::update_scroll()
1192 {
1193         assert(viewport_);
1194         QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
1195         QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
1196
1197         const QSize areaSize = viewport_->size();
1198
1199         // Set the horizontal scroll bar
1200         double length = 0;
1201         Timestamp offset;
1202         get_scroll_layout(length, offset);
1203         length = max(length - areaSize.width(), 0.0);
1204
1205         int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
1206
1207         hscrollbar->setPageStep(areaSize.width() / 2);
1208         hscrollbar->setSingleStep(major_tick_distance);
1209
1210         updating_scroll_ = true;
1211
1212         if (length < MaxScrollValue) {
1213                 hscrollbar->setRange(0, length);
1214                 hscrollbar->setSliderPosition(offset.convert_to<double>());
1215         } else {
1216                 hscrollbar->setRange(0, MaxScrollValue);
1217                 hscrollbar->setSliderPosition(
1218                         (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
1219         }
1220
1221         updating_scroll_ = false;
1222
1223         // Set the vertical scrollbar
1224         vscrollbar->setPageStep(areaSize.height());
1225         vscrollbar->setSingleStep(areaSize.height() / 8);
1226
1227         const pair<int, int> extents = v_extents();
1228
1229         // Don't change the scrollbar range if there are no traces
1230         if (extents.first != extents.second)
1231                 vscrollbar->setRange(extents.first - areaSize.height(),
1232                         extents.second);
1233
1234         if (scroll_needs_defaults_) {
1235                 set_scroll_default();
1236                 scroll_needs_defaults_ = false;
1237         }
1238 }
1239
1240 void View::reset_scroll()
1241 {
1242         scrollarea_->verticalScrollBar()->setRange(0, 0);
1243 }
1244
1245 void View::set_scroll_default()
1246 {
1247         assert(viewport_);
1248
1249         const QSize areaSize = viewport_->size();
1250
1251         const pair<int, int> extents = v_extents();
1252         const int trace_height = extents.second - extents.first;
1253
1254         // Do all traces fit in the view?
1255         if (areaSize.height() >= trace_height)
1256                 // Center all traces vertically
1257                 set_v_offset(extents.first -
1258                         ((areaSize.height() - trace_height) / 2));
1259         else
1260                 // Put the first trace at the top, letting the bottom ones overflow
1261                 set_v_offset(extents.first);
1262 }
1263
1264 void View::determine_if_header_was_shrunk()
1265 {
1266         const int header_pane_width =
1267                 splitter_->sizes().front();  // clazy:exclude=detaching-temporary
1268
1269         // Allow for a slight margin of error so that we also accept
1270         // slight differences when e.g. a label name change increased
1271         // the overall width
1272         header_was_shrunk_ = (header_pane_width < (header_width() - 10));
1273 }
1274
1275 void View::resize_header_to_fit()
1276 {
1277         // Setting the maximum width of the header widget doesn't work as
1278         // expected because the splitter would allow the user to make the
1279         // pane wider than that, creating empty space as a result.
1280         // To make this work, we stricly enforce the maximum width by
1281         // expanding the header unless the user shrunk it on purpose.
1282         // As we're then setting the width of the header pane, we set the
1283         // splitter to the maximum allowed position.
1284
1285         int splitter_area_width = 0;
1286         for (int w : splitter_->sizes())  // clazy:exclude=range-loop
1287                 splitter_area_width += w;
1288
1289         // Make sure the header has enough horizontal space to show all labels fully
1290         QList<int> pane_sizes;
1291         pane_sizes.push_back(header_->extended_size_hint().width());
1292         pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
1293         splitter_->setSizes(pane_sizes);
1294 }
1295
1296 void View::update_layout()
1297 {
1298         update_scroll();
1299 }
1300
1301 TraceTreeItemOwner* View::find_prevalent_trace_group(
1302         const shared_ptr<sigrok::ChannelGroup> &group,
1303         const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1304                 &signal_map)
1305 {
1306         assert(group);
1307
1308         unordered_set<TraceTreeItemOwner*> owners;
1309         vector<TraceTreeItemOwner*> owner_list;
1310
1311         // Make a set and a list of all the owners
1312         for (const auto& channel : group->channels()) {
1313                 for (auto& entry : signal_map) {
1314                         if (entry.first->channel() == channel) {
1315                                 TraceTreeItemOwner *const o = (entry.second)->owner();
1316                                 owner_list.push_back(o);
1317                                 owners.insert(o);
1318                         }
1319                 }
1320         }
1321
1322         // Iterate through the list of owners, and find the most prevalent
1323         size_t max_prevalence = 0;
1324         TraceTreeItemOwner *prevalent_owner = nullptr;
1325         for (TraceTreeItemOwner *owner : owners) {
1326                 const size_t prevalence = count_if(
1327                         owner_list.begin(), owner_list.end(),
1328                         [&](TraceTreeItemOwner *o) { return o == owner; });
1329                 if (prevalence > max_prevalence) {
1330                         max_prevalence = prevalence;
1331                         prevalent_owner = owner;
1332                 }
1333         }
1334
1335         return prevalent_owner;
1336 }
1337
1338 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
1339         const vector< shared_ptr<sigrok::Channel> > &channels,
1340         const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1341                 &signal_map,
1342         set< shared_ptr<Trace> > &add_list)
1343 {
1344         vector< shared_ptr<Trace> > filtered_traces;
1345
1346         for (const auto& channel : channels) {
1347                 for (auto& entry : signal_map) {
1348                         if (entry.first->channel() == channel) {
1349                                 shared_ptr<Trace> trace = entry.second;
1350                                 const auto list_iter = add_list.find(trace);
1351                                 if (list_iter == add_list.end())
1352                                         continue;
1353
1354                                 filtered_traces.push_back(trace);
1355                                 add_list.erase(list_iter);
1356                         }
1357                 }
1358         }
1359
1360         return filtered_traces;
1361 }
1362
1363 void View::determine_time_unit()
1364 {
1365         // Check whether we know the sample rate and hence can use time as the unit
1366         if (time_unit_ == util::TimeUnit::Samples) {
1367                 // Check all signals but...
1368                 for (const shared_ptr<Signal>& signal : signals_) {
1369                         const shared_ptr<SignalData> data = signal->data();
1370
1371                         // ...only check first segment of each
1372                         const vector< shared_ptr<Segment> > segments = data->segments();
1373                         if (!segments.empty())
1374                                 if (segments[0]->samplerate()) {
1375                                         set_time_unit(util::TimeUnit::Time);
1376                                         break;
1377                                 }
1378                 }
1379         }
1380 }
1381
1382 bool View::eventFilter(QObject *object, QEvent *event)
1383 {
1384         const QEvent::Type type = event->type();
1385         if (type == QEvent::MouseMove) {
1386
1387                 if (object)
1388                         hover_widget_ = qobject_cast<QWidget*>(object);
1389
1390                 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
1391                 if (object == viewport_)
1392                         hover_point_ = mouse_event->pos();
1393                 else if (object == ruler_)
1394                         hover_point_ = mouse_event->pos();
1395                 else if (object == header_)
1396                         hover_point_ = QPoint(0, mouse_event->y());
1397                 else
1398                         hover_point_ = QPoint(-1, -1);
1399
1400                 update_hover_point();
1401
1402         } else if (type == QEvent::Leave) {
1403                 hover_point_ = QPoint(-1, -1);
1404                 update_hover_point();
1405         } else if (type == QEvent::Show) {
1406
1407                 // This is somewhat of a hack, unfortunately. We cannot use
1408                 // set_v_offset() from within restore_settings() as the view
1409                 // at that point is neither visible nor properly sized.
1410                 // This is the least intrusive workaround I could come up
1411                 // with: set the vertical offset (or scroll defaults) when
1412                 // the view is shown, which happens after all widgets were
1413                 // resized to their final sizes.
1414                 update_layout();
1415
1416                 if (settings_restored_)
1417                         determine_if_header_was_shrunk();
1418                 else
1419                         resize_header_to_fit();
1420
1421                 if (scroll_needs_defaults_) {
1422                         set_scroll_default();
1423                         scroll_needs_defaults_ = false;
1424                 }
1425
1426                 if (saved_v_offset_) {
1427                         set_v_offset(saved_v_offset_);
1428                         saved_v_offset_ = 0;
1429                 }
1430         }
1431
1432         return QObject::eventFilter(object, event);
1433 }
1434
1435 void View::contextMenuEvent(QContextMenuEvent *event)
1436 {
1437         QPoint pos = event->pos() - QPoint(0, ruler_->sizeHint().height());
1438
1439         const shared_ptr<ViewItem> r = viewport_->get_mouse_over_item(pos);
1440         if (!r)
1441                 return;
1442
1443         QMenu *menu = r->create_view_context_menu(this, pos);
1444         if (menu)
1445                 menu->popup(event->globalPos());
1446 }
1447
1448 void View::resizeEvent(QResizeEvent* event)
1449 {
1450         // Only adjust the top margin if we shrunk vertically
1451         if (event->size().height() < event->oldSize().height())
1452                 adjust_top_margin();
1453
1454         update_layout();
1455 }
1456
1457 void View::update_hover_point()
1458 {
1459         // Determine signal that the mouse cursor is hovering over
1460         signal_under_mouse_cursor_.reset();
1461         if (hover_widget_ == this) {
1462                 for (const shared_ptr<Signal>& s : signals_) {
1463                         const pair<int, int> extents = s->v_extents();
1464                         const int top = s->get_visual_y() + extents.first;
1465                         const int btm = s->get_visual_y() + extents.second;
1466                         if ((hover_point_.y() >= top) && (hover_point_.y() <= btm)
1467                                 && s->base()->enabled())
1468                                 signal_under_mouse_cursor_ = s;
1469                 }
1470         }
1471
1472         // Update all trace tree items
1473         const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1474                 list_by_type<TraceTreeItem>());
1475         for (const shared_ptr<TraceTreeItem>& r : trace_tree_items)
1476                 r->hover_point_changed(hover_point_);
1477
1478         // Notify any other listeners
1479         hover_point_changed(hover_widget_, hover_point_);
1480 }
1481
1482 void View::row_item_appearance_changed(bool label, bool content)
1483 {
1484         if (label)
1485                 header_->update();
1486         if (content)
1487                 viewport_->update();
1488 }
1489
1490 void View::time_item_appearance_changed(bool label, bool content)
1491 {
1492         if (label) {
1493                 ruler_->update();
1494
1495                 // Make sure the header pane width is updated, too
1496                 update_layout();
1497         }
1498
1499         if (content)
1500                 viewport_->update();
1501 }
1502
1503 void View::extents_changed(bool horz, bool vert)
1504 {
1505         sticky_events_ |=
1506                 (horz ? TraceTreeItemHExtentsChanged : 0) |
1507                 (vert ? TraceTreeItemVExtentsChanged : 0);
1508
1509         lazy_event_handler_.stop();
1510         lazy_event_handler_.start();
1511 }
1512
1513 void View::on_signal_name_changed()
1514 {
1515         if (!header_was_shrunk_)
1516                 resize_header_to_fit();
1517 }
1518
1519 void View::on_splitter_moved()
1520 {
1521         // The header can only shrink when the splitter is moved manually
1522         determine_if_header_was_shrunk();
1523
1524         if (!header_was_shrunk_)
1525                 resize_header_to_fit();
1526 }
1527
1528 void View::on_zoom_in_shortcut_triggered()
1529 {
1530         zoom(1);
1531 }
1532
1533 void View::on_zoom_out_shortcut_triggered()
1534 {
1535         zoom(-1);
1536 }
1537
1538 void View::on_scroll_to_start_shortcut_triggered()
1539 {
1540         set_h_offset(0);
1541 }
1542
1543 void View::on_scroll_to_end_shortcut_triggered()
1544 {
1545         set_h_offset(get_h_scrollbar_maximum());
1546 }
1547
1548 void View::h_scroll_value_changed(int value)
1549 {
1550         if (updating_scroll_)
1551                 return;
1552
1553         // Disable sticky scrolling when user moves the horizontal scroll bar
1554         // during a running acquisition
1555         if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1556                 sticky_scrolling_ = false;
1557                 sticky_scrolling_changed(false);
1558         }
1559
1560         const int range = scrollarea_->horizontalScrollBar()->maximum();
1561         if (range < MaxScrollValue)
1562                 set_offset(scale_ * value);
1563         else {
1564                 double length = 0;
1565                 Timestamp offset;
1566                 get_scroll_layout(length, offset);
1567                 set_offset(scale_ * length * value / MaxScrollValue);
1568         }
1569
1570         ruler_->update();
1571         viewport_->update();
1572 }
1573
1574 void View::v_scroll_value_changed()
1575 {
1576         header_->update();
1577         viewport_->update();
1578 }
1579
1580 void View::signals_changed()
1581 {
1582         using sigrok::Channel;
1583
1584         vector< shared_ptr<Channel> > channels;
1585         shared_ptr<sigrok::Device> sr_dev;
1586         bool signals_added_or_removed = false;
1587
1588         // Do we need to set the vertical scrollbar to its default position later?
1589         // We do if there are no traces, i.e. the scroll bar has no range set
1590         bool reset_scrollbar =
1591                 (scrollarea_->verticalScrollBar()->minimum() ==
1592                         scrollarea_->verticalScrollBar()->maximum());
1593
1594         if (!session_.device()) {
1595                 reset_scroll();
1596                 signals_.clear();
1597         } else {
1598                 sr_dev = session_.device()->device();
1599                 assert(sr_dev);
1600                 channels = sr_dev->channels();
1601         }
1602
1603         vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1604
1605         // Make a list of traces that are being added, and a list of traces
1606         // that are being removed
1607         const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1608         const set<shared_ptr<Trace>> prev_traces(
1609                 prev_trace_list.begin(), prev_trace_list.end());
1610
1611         set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1612
1613 #ifdef ENABLE_DECODE
1614         traces.insert(decode_traces_.begin(), decode_traces_.end());
1615 #endif
1616
1617         set< shared_ptr<Trace> > add_traces;
1618         set_difference(traces.begin(), traces.end(),
1619                 prev_traces.begin(), prev_traces.end(),
1620                 inserter(add_traces, add_traces.begin()));
1621
1622         set< shared_ptr<Trace> > remove_traces;
1623         set_difference(prev_traces.begin(), prev_traces.end(),
1624                 traces.begin(), traces.end(),
1625                 inserter(remove_traces, remove_traces.begin()));
1626
1627         // Make a look-up table of sigrok Channels to pulseview Signals
1628         unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1629                 signal_map;
1630         for (const shared_ptr<Signal>& sig : signals_)
1631                 signal_map[sig->base()] = sig;
1632
1633         // Populate channel groups
1634         if (sr_dev)
1635                 for (auto& entry : sr_dev->channel_groups()) {
1636                         const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1637
1638                         if (group->channels().size() <= 1)
1639                                 continue;
1640
1641                         // Find best trace group to add to
1642                         TraceTreeItemOwner *owner = find_prevalent_trace_group(
1643                                 group, signal_map);
1644
1645                         // If there is no trace group, create one
1646                         shared_ptr<TraceGroup> new_trace_group;
1647                         if (!owner) {
1648                                 new_trace_group.reset(new TraceGroup());
1649                                 owner = new_trace_group.get();
1650                         }
1651
1652                         // Extract traces for the trace group, removing them from
1653                         // the add list
1654                         const vector< shared_ptr<Trace> > new_traces_in_group =
1655                                 extract_new_traces_for_channels(group->channels(),
1656                                         signal_map, add_traces);
1657
1658                         // Add the traces to the group
1659                         const pair<int, int> prev_v_extents = owner->v_extents();
1660                         int offset = prev_v_extents.second - prev_v_extents.first;
1661                         for (const shared_ptr<Trace>& trace : new_traces_in_group) {
1662                                 assert(trace);
1663                                 owner->add_child_item(trace);
1664
1665                                 const pair<int, int> extents = trace->v_extents();
1666                                 if (trace->enabled())
1667                                         offset += -extents.first;
1668                                 trace->force_to_v_offset(offset);
1669                                 if (trace->enabled())
1670                                         offset += extents.second;
1671                         }
1672
1673                         if (new_trace_group) {
1674                                 // Assign proper vertical offsets to each channel in the group
1675                                 new_trace_group->restack_items();
1676
1677                                 // If this is a new group, enqueue it in the new top level
1678                                 // items list
1679                                 if (!new_traces_in_group.empty())
1680                                         new_top_level_items.push_back(new_trace_group);
1681                         }
1682                 }
1683
1684         // Enqueue the remaining logic channels in a group
1685         vector< shared_ptr<Channel> > logic_channels;
1686         copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1687                 [](const shared_ptr<Channel>& c) {
1688                         return c->type() == sigrok::ChannelType::LOGIC; });
1689
1690         const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1691                 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1692
1693         if (non_grouped_logic_signals.size() > 0) {
1694                 const shared_ptr<TraceGroup> non_grouped_trace_group(
1695                         make_shared<TraceGroup>());
1696                 for (const shared_ptr<Trace>& trace : non_grouped_logic_signals)
1697                         non_grouped_trace_group->add_child_item(trace);
1698
1699                 non_grouped_trace_group->restack_items();
1700                 new_top_level_items.push_back(non_grouped_trace_group);
1701         }
1702
1703         // Enqueue the remaining channels as free ungrouped traces
1704         const vector< shared_ptr<Trace> > new_top_level_signals =
1705                 extract_new_traces_for_channels(channels, signal_map, add_traces);
1706         new_top_level_items.insert(new_top_level_items.end(),
1707                 new_top_level_signals.begin(), new_top_level_signals.end());
1708
1709         // Enqueue any remaining traces i.e. decode traces
1710         new_top_level_items.insert(new_top_level_items.end(),
1711                 add_traces.begin(), add_traces.end());
1712
1713         // Remove any removed traces
1714         for (const shared_ptr<Trace>& trace : remove_traces) {
1715                 TraceTreeItemOwner *const owner = trace->owner();
1716                 assert(owner);
1717                 owner->remove_child_item(trace);
1718                 signals_added_or_removed = true;
1719         }
1720
1721         // Remove any empty trace groups
1722         for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1723                 if (group->child_items().size() == 0) {
1724                         remove_child_item(group);
1725                         group.reset();
1726                 }
1727
1728         // Add and position the pending top levels items
1729         int offset = v_extents().second;
1730         for (auto item : new_top_level_items) {
1731                 add_child_item(item);
1732
1733                 // Position the item after the last item or at the top if there is none
1734                 const pair<int, int> extents = item->v_extents();
1735
1736                 if (item->enabled())
1737                         offset += -extents.first;
1738
1739                 item->force_to_v_offset(offset);
1740
1741                 if (item->enabled())
1742                         offset += extents.second;
1743                 signals_added_or_removed = true;
1744         }
1745
1746
1747         if (signals_added_or_removed && !header_was_shrunk_)
1748                 resize_header_to_fit();
1749
1750         update_layout();
1751
1752         header_->update();
1753         viewport_->update();
1754
1755         if (reset_scrollbar)
1756                 set_scroll_default();
1757 }
1758
1759 void View::capture_state_updated(int state)
1760 {
1761         GlobalSettings settings;
1762
1763         if (state == Session::Running) {
1764                 set_time_unit(util::TimeUnit::Samples);
1765
1766                 trigger_markers_.clear();
1767                 set_zero_position(0);
1768
1769                 scale_at_acq_start_ = scale_;
1770                 offset_at_acq_start_ = offset_;
1771
1772                 // Activate "always zoom to fit" if the setting is enabled and we're
1773                 // the main view of this session (other trace views may be used for
1774                 // zooming and we don't want to mess them up)
1775                 bool state = settings.value(GlobalSettings::Key_View_ZoomToFitDuringAcq).toBool();
1776                 if (is_main_view_ && state) {
1777                         always_zoom_to_fit_ = true;
1778                         always_zoom_to_fit_changed(always_zoom_to_fit_);
1779                 }
1780
1781                 // Enable sticky scrolling if the setting is enabled
1782                 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1783
1784                 // Reset all traces to segment 0
1785                 current_segment_ = 0;
1786                 set_current_segment(current_segment_);
1787         }
1788
1789         if (state == Session::Stopped) {
1790                 // After acquisition has stopped we need to re-calculate the ticks once
1791                 // as it's otherwise done when the user pans or zooms, which is too late
1792                 calculate_tick_spacing();
1793
1794                 // Reset "always zoom to fit", the acquisition has stopped
1795                 if (always_zoom_to_fit_) {
1796                         // Perform a final zoom-to-fit before disabling
1797                         zoom_fit(always_zoom_to_fit_);
1798                         always_zoom_to_fit_ = false;
1799                         always_zoom_to_fit_changed(always_zoom_to_fit_);
1800                 }
1801
1802                 bool zoom_to_fit_after_acq =
1803                         settings.value(GlobalSettings::Key_View_ZoomToFitAfterAcq).toBool();
1804
1805                 // Only perform zoom-to-fit if the user hasn't altered the viewport and
1806                 // we didn't restore settings in the meanwhile
1807                 if (zoom_to_fit_after_acq &&
1808                         !suppress_zoom_to_fit_after_acq_ &&
1809                         (scale_ == scale_at_acq_start_) &&
1810                         (offset_ == offset_at_acq_start_))
1811                         zoom_fit(false);  // We're stopped, so the GUI state doesn't matter
1812
1813                 suppress_zoom_to_fit_after_acq_ = false;
1814         }
1815 }
1816
1817 void View::on_new_segment(int new_segment_id)
1818 {
1819         on_segment_changed(new_segment_id);
1820 }
1821
1822 void View::on_segment_completed(int segment_id)
1823 {
1824         on_segment_changed(segment_id);
1825 }
1826
1827 void View::on_segment_changed(int segment)
1828 {
1829         switch (segment_display_mode_) {
1830         case Trace::ShowLastSegmentOnly:
1831         case Trace::ShowSingleSegmentOnly:
1832                 set_current_segment(segment);
1833                 break;
1834
1835         case Trace::ShowLastCompleteSegmentOnly:
1836                 // Only update if all segments are complete
1837                 if (session_.all_segments_complete(segment))
1838                         set_current_segment(segment);
1839                 break;
1840
1841         case Trace::ShowAllSegments:
1842         case Trace::ShowAccumulatedIntensity:
1843         default:
1844                 break;
1845         }
1846 }
1847
1848 void View::on_settingViewTriggerIsZeroTime_changed(const QVariant new_value)
1849 {
1850         if (new_value.toBool()) {
1851                 // The first trigger for this segment is used as the zero position
1852                 vector<util::Timestamp> triggers = session_.get_triggers(current_segment_);
1853                 if (triggers.size() > 0)
1854                         set_zero_position(triggers.front());
1855         } else
1856                 reset_zero_position();
1857 }
1858
1859 void View::perform_delayed_view_update()
1860 {
1861         if (always_zoom_to_fit_) {
1862                 zoom_fit(true);
1863         } else if (sticky_scrolling_) {
1864                 // Make right side of the view sticky
1865                 double length = 0;
1866                 Timestamp offset;
1867                 get_scroll_layout(length, offset);
1868
1869                 const QSize areaSize = viewport_->size();
1870                 length = max(length - areaSize.width(), 0.0);
1871
1872                 set_offset(scale_ * length);
1873         }
1874
1875         determine_time_unit();
1876         update_scroll();
1877         ruler_->update();
1878         viewport_->update();
1879 }
1880
1881 void View::process_sticky_events()
1882 {
1883         if (sticky_events_ & TraceTreeItemHExtentsChanged)
1884                 update_layout();
1885         if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1886                 restack_all_trace_tree_items();
1887                 update_scroll();
1888         }
1889
1890         // Clear the sticky events
1891         sticky_events_ = 0;
1892 }
1893
1894 } // namespace trace
1895 } // namespace views
1896 } // namespace pv