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