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