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