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