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