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