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