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