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