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