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