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