Settings: About: alpha-sort list of protocol decoders
[pulseview.git] / pv / view / 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 <QHBoxLayout>
42 #include <QMouseEvent>
43 #include <QScrollBar>
44
45 #include <libsigrokcxx/libsigrokcxx.hpp>
46
47 #include "analogsignal.hpp"
48 #include "header.hpp"
49 #include "logicsignal.hpp"
50 #include "ruler.hpp"
51 #include "signal.hpp"
52 #include "tracegroup.hpp"
53 #include "triggermarker.hpp"
54 #include "view.hpp"
55 #include "viewport.hpp"
56
57 #include "pv/data/logic.hpp"
58 #include "pv/data/logicsegment.hpp"
59 #include "pv/devices/device.hpp"
60 #include "pv/globalsettings.hpp"
61 #include "pv/session.hpp"
62 #include "pv/util.hpp"
63
64 #ifdef ENABLE_DECODE
65 #include "decodetrace.hpp"
66 #endif
67
68 using pv::data::SignalData;
69 using pv::data::Segment;
70 using pv::util::TimeUnit;
71 using pv::util::Timestamp;
72
73 using std::back_inserter;
74 using std::copy_if;
75 using std::count_if;
76 using std::dynamic_pointer_cast;
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::pair;
83 using std::set;
84 using std::set_difference;
85 using std::shared_ptr;
86 using std::stringstream;
87 using std::unordered_map;
88 using std::unordered_set;
89 using std::vector;
90
91 namespace pv {
92 namespace views {
93 namespace TraceView {
94
95 const Timestamp View::MaxScale("1e9");
96 const Timestamp View::MinScale("1e-12");
97
98 const int View::MaxScrollValue = INT_MAX / 2;
99 const int View::MaxViewAutoUpdateRate = 25; // No more than 25 Hz with sticky scrolling
100
101 const int View::ScaleUnits[3] = {1, 2, 5};
102
103
104 CustomAbstractScrollArea::CustomAbstractScrollArea(QWidget *parent) :
105         QAbstractScrollArea(parent)
106 {
107 }
108
109 void CustomAbstractScrollArea::setViewportMargins(int left, int top, int right, int bottom)
110 {
111         QAbstractScrollArea::setViewportMargins(left, top, right, bottom);
112 }
113
114 bool CustomAbstractScrollArea::viewportEvent(QEvent *event)
115 {
116         switch (event->type()) {
117         case QEvent::Paint:
118         case QEvent::MouseButtonPress:
119         case QEvent::MouseButtonRelease:
120         case QEvent::MouseButtonDblClick:
121         case QEvent::MouseMove:
122         case QEvent::Wheel:
123         case QEvent::TouchBegin:
124         case QEvent::TouchUpdate:
125         case QEvent::TouchEnd:
126                 return false;
127         default:
128                 return QAbstractScrollArea::viewportEvent(event);
129         }
130 }
131
132 View::View(Session &session, bool is_main_view, QWidget *parent) :
133         ViewBase(session, is_main_view, parent),
134         viewport_(new Viewport(*this)),
135         ruler_(new Ruler(*this)),
136         header_(new Header(*this)),
137         scrollarea_(this),
138         scale_(1e-3),
139         offset_(0),
140         updating_scroll_(false),
141         sticky_scrolling_(false), // Default setting is set in MainWindow::setup_ui()
142         always_zoom_to_fit_(false),
143         tick_period_(0),
144         tick_prefix_(pv::util::SIPrefix::yocto),
145         tick_precision_(0),
146         time_unit_(util::TimeUnit::Time),
147         show_cursors_(false),
148         cursors_(new CursorPair(*this)),
149         next_flag_text_('A'),
150         trigger_markers_(),
151         hover_point_(-1, -1),
152         scroll_needs_defaults_(false),
153         saved_v_offset_(0),
154         size_finalized_(false)
155 {
156         GlobalSettings settings;
157         coloured_bg_ = settings.value(GlobalSettings::Key_View_ColouredBG).toBool();
158
159         connect(scrollarea_.horizontalScrollBar(), SIGNAL(valueChanged(int)),
160                 this, SLOT(h_scroll_value_changed(int)));
161         connect(scrollarea_.verticalScrollBar(), SIGNAL(valueChanged(int)),
162                 this, SLOT(v_scroll_value_changed()));
163
164         connect(header_, SIGNAL(selection_changed()),
165                 ruler_, SLOT(clear_selection()));
166         connect(ruler_, SIGNAL(selection_changed()),
167                 header_, SLOT(clear_selection()));
168
169         connect(header_, SIGNAL(selection_changed()),
170                 this, SIGNAL(selection_changed()));
171         connect(ruler_, SIGNAL(selection_changed()),
172                 this, SIGNAL(selection_changed()));
173
174         connect(this, SIGNAL(hover_point_changed()),
175                 this, SLOT(on_hover_point_changed()));
176
177         connect(&lazy_event_handler_, SIGNAL(timeout()),
178                 this, SLOT(process_sticky_events()));
179         lazy_event_handler_.setSingleShot(true);
180
181         connect(&delayed_view_updater_, SIGNAL(timeout()),
182                 this, SLOT(perform_delayed_view_update()));
183         delayed_view_updater_.setSingleShot(true);
184         delayed_view_updater_.setInterval(1000 / MaxViewAutoUpdateRate);
185
186         /* To let the scroll area fill up the parent QWidget (this), we need a layout */
187         QHBoxLayout *layout = new QHBoxLayout(this);
188         setLayout(layout);
189         layout->setContentsMargins(0, 0, 0, 0);
190         layout->addWidget(&scrollarea_);
191
192         scrollarea_.setViewport(viewport_);
193
194         viewport_->installEventFilter(this);
195         ruler_->installEventFilter(this);
196         header_->installEventFilter(this);
197
198         // Trigger the initial event manually. The default device has signals
199         // which were created before this object came into being
200         signals_changed();
201
202         // make sure the transparent widgets are on the top
203         ruler_->raise();
204         header_->raise();
205
206         // Update the zoom state
207         calculate_tick_spacing();
208 }
209
210 Session& View::session()
211 {
212         return session_;
213 }
214
215 const Session& View::session() const
216 {
217         return session_;
218 }
219
220 unordered_set< shared_ptr<Signal> > View::signals() const
221 {
222         return signals_;
223 }
224
225 void View::clear_signals()
226 {
227         signals_.clear();
228 }
229
230 void View::add_signal(const shared_ptr<Signal> signal)
231 {
232         signals_.insert(signal);
233 }
234
235 #ifdef ENABLE_DECODE
236 void View::clear_decode_signals()
237 {
238         decode_traces_.clear();
239 }
240
241 void View::add_decode_signal(shared_ptr<data::SignalBase> signalbase)
242 {
243         shared_ptr<DecodeTrace> d(
244                 new DecodeTrace(session_, signalbase, decode_traces_.size()));
245         decode_traces_.push_back(d);
246 }
247
248 void View::remove_decode_signal(shared_ptr<data::SignalBase> signalbase)
249 {
250         for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
251                 if ((*i)->base() == signalbase) {
252                         decode_traces_.erase(i);
253                         signals_changed();
254                         return;
255                 }
256 }
257 #endif
258
259 View* View::view()
260 {
261         return this;
262 }
263
264 const View* View::view() const
265 {
266         return this;
267 }
268
269 Viewport* View::viewport()
270 {
271         return viewport_;
272 }
273
274 const Viewport* View::viewport() const
275 {
276         return viewport_;
277 }
278
279 void View::save_settings(QSettings &settings) const
280 {
281         settings.setValue("scale", scale_);
282         settings.setValue("v_offset",
283                 scrollarea_.verticalScrollBar()->sliderPosition());
284
285         stringstream ss;
286         boost::archive::text_oarchive oa(ss);
287         oa << boost::serialization::make_nvp("offset", offset_);
288         settings.setValue("offset", QString::fromStdString(ss.str()));
289
290         for (shared_ptr<Signal> signal : signals_) {
291                 settings.beginGroup(signal->base()->internal_name());
292                 signal->save_settings(settings);
293                 settings.endGroup();
294         }
295 }
296
297 void View::restore_settings(QSettings &settings)
298 {
299         // Note: It is assumed that this function is only called once,
300         // immediately after restoring a previous session.
301
302         if (settings.contains("scale"))
303                 set_scale(settings.value("scale").toDouble());
304
305         if (settings.contains("offset")) {
306                 util::Timestamp offset;
307                 stringstream ss;
308                 ss << settings.value("offset").toString().toStdString();
309
310                 boost::archive::text_iarchive ia(ss);
311                 ia >> boost::serialization::make_nvp("offset", offset);
312
313                 set_offset(offset);
314         }
315
316         for (shared_ptr<Signal> signal : signals_) {
317                 settings.beginGroup(signal->base()->internal_name());
318                 signal->restore_settings(settings);
319                 settings.endGroup();
320         }
321
322         if (settings.contains("v_offset")) {
323                 saved_v_offset_ = settings.value("v_offset").toInt();
324                 set_v_offset(saved_v_offset_);
325                 scroll_needs_defaults_ = false;
326                 // Note: see resizeEvent() for additional information
327         }
328 }
329
330 vector< shared_ptr<TimeItem> > View::time_items() const
331 {
332         const vector<shared_ptr<Flag>> f(flags());
333         vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
334         items.push_back(cursors_);
335         items.push_back(cursors_->first());
336         items.push_back(cursors_->second());
337
338         for (auto trigger_marker : trigger_markers_)
339                 items.push_back(trigger_marker);
340
341         return items;
342 }
343
344 double View::scale() const
345 {
346         return scale_;
347 }
348
349 void View::set_scale(double scale)
350 {
351         if (scale_ != scale) {
352                 scale_ = scale;
353                 Q_EMIT scale_changed();
354         }
355 }
356
357 const Timestamp& View::offset() const
358 {
359         return offset_;
360 }
361
362 void View::set_offset(const pv::util::Timestamp& offset)
363 {
364         if (offset_ != offset) {
365                 offset_ = offset;
366                 Q_EMIT offset_changed();
367         }
368 }
369
370 int View::owner_visual_v_offset() const
371 {
372         return -scrollarea_.verticalScrollBar()->sliderPosition();
373 }
374
375 void View::set_v_offset(int offset)
376 {
377         scrollarea_.verticalScrollBar()->setSliderPosition(offset);
378         header_->update();
379         viewport_->update();
380 }
381
382 unsigned int View::depth() const
383 {
384         return 0;
385 }
386
387 pv::util::SIPrefix View::tick_prefix() const
388 {
389         return tick_prefix_;
390 }
391
392 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
393 {
394         if (tick_prefix_ != tick_prefix) {
395                 tick_prefix_ = tick_prefix;
396                 Q_EMIT tick_prefix_changed();
397         }
398 }
399
400 unsigned int View::tick_precision() const
401 {
402         return tick_precision_;
403 }
404
405 void View::set_tick_precision(unsigned tick_precision)
406 {
407         if (tick_precision_ != tick_precision) {
408                 tick_precision_ = tick_precision;
409                 Q_EMIT tick_precision_changed();
410         }
411 }
412
413 const pv::util::Timestamp& View::tick_period() const
414 {
415         return tick_period_;
416 }
417
418 void View::set_tick_period(const pv::util::Timestamp& tick_period)
419 {
420         if (tick_period_ != tick_period) {
421                 tick_period_ = tick_period;
422                 Q_EMIT tick_period_changed();
423         }
424 }
425
426 TimeUnit View::time_unit() const
427 {
428         return time_unit_;
429 }
430
431 void View::set_time_unit(pv::util::TimeUnit time_unit)
432 {
433         if (time_unit_ != time_unit) {
434                 time_unit_ = time_unit;
435                 Q_EMIT time_unit_changed();
436         }
437 }
438
439 void View::zoom(double steps)
440 {
441         zoom(steps, viewport_->width() / 2);
442 }
443
444 void View::zoom(double steps, int offset)
445 {
446         set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
447 }
448
449 void View::zoom_fit(bool gui_state)
450 {
451         // Act as one-shot when stopped, toggle along with the GUI otherwise
452         if (session_.get_capture_state() == Session::Stopped) {
453                 always_zoom_to_fit_ = false;
454                 always_zoom_to_fit_changed(false);
455         } else {
456                 always_zoom_to_fit_ = gui_state;
457                 always_zoom_to_fit_changed(gui_state);
458         }
459
460         const pair<Timestamp, Timestamp> extents = get_time_extents();
461         const Timestamp delta = extents.second - extents.first;
462         if (delta < Timestamp("1e-12"))
463                 return;
464
465         assert(viewport_);
466         const int w = viewport_->width();
467         if (w <= 0)
468                 return;
469
470         const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
471         set_scale_offset(scale.convert_to<double>(), extents.first);
472 }
473
474 void View::zoom_one_to_one()
475 {
476         using pv::data::SignalData;
477
478         // Make a set of all the visible data objects
479         set< shared_ptr<SignalData> > visible_data = get_visible_data();
480         if (visible_data.empty())
481                 return;
482
483         assert(viewport_);
484         const int w = viewport_->width();
485         if (w <= 0)
486                 return;
487
488         set_zoom(1.0 / session_.get_samplerate(), w / 2);
489 }
490
491 void View::set_scale_offset(double scale, const Timestamp& offset)
492 {
493         // Disable sticky scrolling / always zoom to fit when acquisition runs
494         // and user drags the viewport
495         if ((scale_ == scale) && (offset_ != offset) &&
496                         (session_.get_capture_state() == Session::Running)) {
497
498                 if (sticky_scrolling_) {
499                         sticky_scrolling_ = false;
500                         sticky_scrolling_changed(false);
501                 }
502
503                 if (always_zoom_to_fit_) {
504                         always_zoom_to_fit_ = false;
505                         always_zoom_to_fit_changed(false);
506                 }
507         }
508
509         set_scale(scale);
510         set_offset(offset);
511
512         calculate_tick_spacing();
513
514         update_scroll();
515         ruler_->update();
516         viewport_->update();
517 }
518
519 set< shared_ptr<SignalData> > View::get_visible_data() const
520 {
521         // Make a set of all the visible data objects
522         set< shared_ptr<SignalData> > visible_data;
523         for (const shared_ptr<Signal> sig : signals_)
524                 if (sig->enabled())
525                         visible_data.insert(sig->data());
526
527         return visible_data;
528 }
529
530 pair<Timestamp, Timestamp> View::get_time_extents() const
531 {
532         boost::optional<Timestamp> left_time, right_time;
533         const set< shared_ptr<SignalData> > visible_data = get_visible_data();
534         for (const shared_ptr<SignalData> d : visible_data) {
535                 const vector< shared_ptr<Segment> > segments = d->segments();
536                 for (const shared_ptr<Segment> &s : segments) {
537                         double samplerate = s->samplerate();
538                         samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
539
540                         const Timestamp start_time = s->start_time();
541                         left_time = left_time ?
542                                 min(*left_time, start_time) :
543                                                 start_time;
544                         right_time = right_time ?
545                                 max(*right_time, start_time + d->max_sample_count() / samplerate) :
546                                                  start_time + d->max_sample_count() / samplerate;
547                 }
548         }
549
550         if (!left_time || !right_time)
551                 return make_pair(0, 0);
552
553         assert(*left_time < *right_time);
554         return make_pair(*left_time, *right_time);
555 }
556
557 void View::enable_show_sampling_points(bool state)
558 {
559         (void)state;
560
561         viewport_->update();
562 }
563
564 void View::enable_show_analog_minor_grid(bool state)
565 {
566         (void)state;
567
568         viewport_->update();
569 }
570
571 void View::enable_coloured_bg(bool state)
572 {
573         const vector<shared_ptr<TraceTreeItem>> items(
574                 list_by_type<TraceTreeItem>());
575
576         for (shared_ptr<TraceTreeItem> i : items) {
577                 // Can't cast to Trace because it's abstract, so we need to
578                 // check for any derived classes individually
579
580                 shared_ptr<AnalogSignal> a = dynamic_pointer_cast<AnalogSignal>(i);
581                 if (a)
582                         a->set_coloured_bg(state);
583
584                 shared_ptr<LogicSignal> l = dynamic_pointer_cast<LogicSignal>(i);
585                 if (l)
586                         l->set_coloured_bg(state);
587
588 #ifdef ENABLE_DECODE
589                 shared_ptr<DecodeTrace> d = dynamic_pointer_cast<DecodeTrace>(i);
590                 if (d)
591                         d->set_coloured_bg(state);
592 #endif
593         }
594
595         viewport_->update();
596 }
597
598 bool View::cursors_shown() const
599 {
600         return show_cursors_;
601 }
602
603 void View::show_cursors(bool show)
604 {
605         show_cursors_ = show;
606         ruler_->update();
607         viewport_->update();
608 }
609
610 void View::centre_cursors()
611 {
612         const double time_width = scale_ * viewport_->width();
613         cursors_->first()->set_time(offset_ + time_width * 0.4);
614         cursors_->second()->set_time(offset_ + time_width * 0.6);
615         ruler_->update();
616         viewport_->update();
617 }
618
619 shared_ptr<CursorPair> View::cursors() const
620 {
621         return cursors_;
622 }
623
624 void View::add_flag(const Timestamp& time)
625 {
626         flags_.push_back(make_shared<Flag>(*this, time,
627                 QString("%1").arg(next_flag_text_)));
628
629         next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
630                 (next_flag_text_ + 1);
631
632         time_item_appearance_changed(true, true);
633 }
634
635 void View::remove_flag(shared_ptr<Flag> flag)
636 {
637         flags_.remove(flag);
638         time_item_appearance_changed(true, true);
639 }
640
641 vector< shared_ptr<Flag> > View::flags() const
642 {
643         vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
644         stable_sort(flags.begin(), flags.end(),
645                 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
646                         return a->time() < b->time();
647                 });
648
649         return flags;
650 }
651
652 const QPoint& View::hover_point() const
653 {
654         return hover_point_;
655 }
656
657 void View::restack_all_trace_tree_items()
658 {
659         // Make a list of owners that is sorted from deepest first
660         const vector<shared_ptr<TraceTreeItem>> items(
661                 list_by_type<TraceTreeItem>());
662         set< TraceTreeItemOwner* > owners;
663         for (const auto &r : items)
664                 owners.insert(r->owner());
665         vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
666         sort(sorted_owners.begin(), sorted_owners.end(),
667                 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
668                         return a->depth() > b->depth(); });
669
670         // Restack the items recursively
671         for (auto &o : sorted_owners)
672                 o->restack_items();
673
674         // Re-assign background colors
675         bool next_bgcolour_state = false;
676
677         for (auto &o : sorted_owners)
678                 next_bgcolour_state = o->reassign_bgcolour_states(next_bgcolour_state);
679
680         // Animate the items to their destination
681         for (const auto &i : items)
682                 i->animate_to_layout_v_offset();
683 }
684
685 void View::trigger_event(util::Timestamp location)
686 {
687         trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
688 }
689
690 void View::get_scroll_layout(double &length, Timestamp &offset) const
691 {
692         const pair<Timestamp, Timestamp> extents = get_time_extents();
693         length = ((extents.second - extents.first) / scale_).convert_to<double>();
694         offset = offset_ / scale_;
695 }
696
697 void View::set_zoom(double scale, int offset)
698 {
699         // Reset the "always zoom to fit" feature as the user changed the zoom
700         always_zoom_to_fit_ = false;
701         always_zoom_to_fit_changed(false);
702
703         const Timestamp cursor_offset = offset_ + scale_ * offset;
704         const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
705         const Timestamp new_offset = cursor_offset - new_scale * offset;
706         set_scale_offset(new_scale.convert_to<double>(), new_offset);
707 }
708
709 void View::calculate_tick_spacing()
710 {
711         const double SpacingIncrement = 10.0f;
712         const double MinValueSpacing = 40.0f;
713
714         // Figure out the highest numeric value visible on a label
715         const QSize areaSize = viewport_->size();
716         const Timestamp max_time = max(fabs(offset_),
717                 fabs(offset_ + scale_ * areaSize.width()));
718
719         double min_width = SpacingIncrement;
720         double label_width, tick_period_width;
721
722         QFontMetrics m(QApplication::font());
723
724         // Copies of the member variables with the same name, used in the calculation
725         // and written back afterwards, so that we don't emit signals all the time
726         // during the calculation.
727         pv::util::Timestamp tick_period = tick_period_;
728         pv::util::SIPrefix tick_prefix = tick_prefix_;
729         unsigned tick_precision = tick_precision_;
730
731         do {
732                 const double min_period = scale_ * min_width;
733
734                 const int order = (int)floorf(log10f(min_period));
735                 const pv::util::Timestamp order_decimal =
736                         pow(pv::util::Timestamp(10), order);
737
738                 // Allow for a margin of error so that a scale unit of 1 can be used.
739                 // Otherwise, for a SU of 1 the tick period will almost always be below
740                 // the min_period by a small amount - and thus skipped in favor of 2.
741                 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
742                 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
743                 double tp_with_margin;
744                 unsigned int unit = 0;
745
746                 do {
747                         tp_with_margin = order_decimal.convert_to<double>() *
748                                 (ScaleUnits[unit++] + tp_margin);
749                 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
750
751                 tick_period = order_decimal * ScaleUnits[unit - 1];
752                 tick_prefix = static_cast<pv::util::SIPrefix>(
753                         (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
754
755                 // Precision is the number of fractional digits required, not
756                 // taking the prefix into account (and it must never be negative)
757                 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
758
759                 tick_period_width = (tick_period / scale_).convert_to<double>();
760
761                 const QString label_text = Ruler::format_time_with_distance(
762                         tick_period, max_time, tick_prefix, time_unit_, tick_precision);
763
764                 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
765                         Qt::AlignLeft | Qt::AlignTop, label_text).width() +
766                                 MinValueSpacing;
767
768                 min_width += SpacingIncrement;
769         } while (tick_period_width < label_width);
770
771         set_tick_period(tick_period);
772         set_tick_prefix(tick_prefix);
773         set_tick_precision(tick_precision);
774 }
775
776 void View::update_scroll()
777 {
778         assert(viewport_);
779         QScrollBar *hscrollbar = scrollarea_.horizontalScrollBar();
780         QScrollBar *vscrollbar = scrollarea_.verticalScrollBar();
781
782         const QSize areaSize = viewport_->size();
783
784         // Set the horizontal scroll bar
785         double length = 0;
786         Timestamp offset;
787         get_scroll_layout(length, offset);
788         length = max(length - areaSize.width(), 0.0);
789
790         int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
791
792         hscrollbar->setPageStep(areaSize.width() / 2);
793         hscrollbar->setSingleStep(major_tick_distance);
794
795         updating_scroll_ = true;
796
797         if (length < MaxScrollValue) {
798                 hscrollbar->setRange(0, length);
799                 hscrollbar->setSliderPosition(offset.convert_to<double>());
800         } else {
801                 hscrollbar->setRange(0, MaxScrollValue);
802                 hscrollbar->setSliderPosition(
803                         (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
804         }
805
806         updating_scroll_ = false;
807
808         // Set the vertical scrollbar
809         vscrollbar->setPageStep(areaSize.height());
810         vscrollbar->setSingleStep(areaSize.height() / 8);
811
812         const pair<int, int> extents = v_extents();
813
814         // Don't change the scrollbar range if there are no traces
815         if (extents.first != extents.second)
816                 vscrollbar->setRange(extents.first - areaSize.height(),
817                         extents.second);
818
819         if (scroll_needs_defaults_)
820                 set_scroll_default();
821 }
822
823 void View::reset_scroll()
824 {
825         scrollarea_.verticalScrollBar()->setRange(0, 0);
826 }
827
828 void View::set_scroll_default()
829 {
830         assert(viewport_);
831
832         const QSize areaSize = viewport_->size();
833
834         const pair<int, int> extents = v_extents();
835         const int trace_height = extents.second - extents.first;
836
837         // Do all traces fit in the view?
838         if (areaSize.height() >= trace_height)
839                 // Center all traces vertically
840                 set_v_offset(extents.first -
841                         ((areaSize.height() - trace_height) / 2));
842         else
843                 // Put the first trace at the top, letting the bottom ones overflow
844                 set_v_offset(extents.first);
845
846         // If we're not sure whether setting the defaults worked as
847         // the window wasn't set up entirely yet, we want to be called
848         // again later to make sure
849         scroll_needs_defaults_ = !size_finalized_;
850 }
851
852 void View::update_layout()
853 {
854         scrollarea_.setViewportMargins(
855                 header_->sizeHint().width() - Header::BaselineOffset,
856                 ruler_->sizeHint().height(), 0, 0);
857         ruler_->setGeometry(viewport_->x(), 0,
858                 viewport_->width(), ruler_->extended_size_hint().height());
859         header_->setGeometry(0, viewport_->y(),
860                 header_->extended_size_hint().width(), viewport_->height());
861         update_scroll();
862 }
863
864 TraceTreeItemOwner* View::find_prevalent_trace_group(
865         const shared_ptr<sigrok::ChannelGroup> &group,
866         const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
867                 &signal_map)
868 {
869         assert(group);
870
871         unordered_set<TraceTreeItemOwner*> owners;
872         vector<TraceTreeItemOwner*> owner_list;
873
874         // Make a set and a list of all the owners
875         for (const auto &channel : group->channels()) {
876                 for (auto entry : signal_map) {
877                         if (entry.first->channel() == channel) {
878                                 TraceTreeItemOwner *const o = (entry.second)->owner();
879                                 owner_list.push_back(o);
880                                 owners.insert(o);
881                         }
882                 }
883         }
884
885         // Iterate through the list of owners, and find the most prevalent
886         size_t max_prevalence = 0;
887         TraceTreeItemOwner *prevalent_owner = nullptr;
888         for (TraceTreeItemOwner *owner : owners) {
889                 const size_t prevalence = count_if(
890                         owner_list.begin(), owner_list.end(),
891                         [&](TraceTreeItemOwner *o) { return o == owner; });
892                 if (prevalence > max_prevalence) {
893                         max_prevalence = prevalence;
894                         prevalent_owner = owner;
895                 }
896         }
897
898         return prevalent_owner;
899 }
900
901 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
902         const vector< shared_ptr<sigrok::Channel> > &channels,
903         const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
904                 &signal_map,
905         set< shared_ptr<Trace> > &add_list)
906 {
907         vector< shared_ptr<Trace> > filtered_traces;
908
909         for (const auto &channel : channels) {
910                 for (auto entry : signal_map) {
911                         if (entry.first->channel() == channel) {
912                                 shared_ptr<Trace> trace = entry.second;
913                                 const auto list_iter = add_list.find(trace);
914                                 if (list_iter == add_list.end())
915                                         continue;
916
917                                 filtered_traces.push_back(trace);
918                                 add_list.erase(list_iter);
919                         }
920                 }
921         }
922
923         return filtered_traces;
924 }
925
926 void View::determine_time_unit()
927 {
928         // Check whether we know the sample rate and hence can use time as the unit
929         if (time_unit_ == util::TimeUnit::Samples) {
930                 // Check all signals but...
931                 for (const shared_ptr<Signal> signal : signals_) {
932                         const shared_ptr<SignalData> data = signal->data();
933
934                         // ...only check first segment of each
935                         const vector< shared_ptr<Segment> > segments = data->segments();
936                         if (!segments.empty())
937                                 if (segments[0]->samplerate()) {
938                                         set_time_unit(util::TimeUnit::Time);
939                                         break;
940                                 }
941                 }
942         }
943 }
944
945 bool View::eventFilter(QObject *object, QEvent *event)
946 {
947         const QEvent::Type type = event->type();
948         if (type == QEvent::MouseMove) {
949
950                 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
951                 if (object == viewport_)
952                         hover_point_ = mouse_event->pos();
953                 else if (object == ruler_)
954                         hover_point_ = QPoint(mouse_event->x(), 0);
955                 else if (object == header_)
956                         hover_point_ = QPoint(0, mouse_event->y());
957                 else
958                         hover_point_ = QPoint(-1, -1);
959
960                 hover_point_changed();
961
962         } else if (type == QEvent::Leave) {
963                 hover_point_ = QPoint(-1, -1);
964                 hover_point_changed();
965         }
966
967         return QObject::eventFilter(object, event);
968 }
969
970 void View::resizeEvent(QResizeEvent*)
971 {
972         update_layout();
973
974         // This is somewhat of a hack, unfortunately. We cannot use
975         // set_v_offset() from within restore_settings() as the view
976         // at that point is neither visible nor properly sized.
977         // This is the least intrusive workaround I could come up
978         // with: set the vertical offset (or scroll defaults) when
979         // the view is visible and resized to its final size.
980         // Resize events that are sent when the view is not visible
981         // must be ignored as they have wrong sizes, potentially
982         // preventing the v offset from being set successfully.
983
984         if (isVisible())
985                 size_finalized_ = true;
986
987         if (size_finalized_ && saved_v_offset_) {
988                 set_v_offset(saved_v_offset_);
989                 saved_v_offset_ = 0;
990         }
991
992         if (size_finalized_ && scroll_needs_defaults_)
993                 set_scroll_default();
994 }
995
996 void View::row_item_appearance_changed(bool label, bool content)
997 {
998         if (label)
999                 header_->update();
1000         if (content)
1001                 viewport_->update();
1002 }
1003
1004 void View::time_item_appearance_changed(bool label, bool content)
1005 {
1006         if (label)
1007                 ruler_->update();
1008         if (content)
1009                 viewport_->update();
1010 }
1011
1012 void View::extents_changed(bool horz, bool vert)
1013 {
1014         sticky_events_ |=
1015                 (horz ? TraceTreeItemHExtentsChanged : 0) |
1016                 (vert ? TraceTreeItemVExtentsChanged : 0);
1017         lazy_event_handler_.start();
1018 }
1019
1020 void View::h_scroll_value_changed(int value)
1021 {
1022         if (updating_scroll_)
1023                 return;
1024
1025         // Disable sticky scrolling when user moves the horizontal scroll bar
1026         // during a running acquisition
1027         if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1028                 sticky_scrolling_ = false;
1029                 sticky_scrolling_changed(false);
1030         }
1031
1032         const int range = scrollarea_.horizontalScrollBar()->maximum();
1033         if (range < MaxScrollValue)
1034                 set_offset(scale_ * value);
1035         else {
1036                 double length = 0;
1037                 Timestamp offset;
1038                 get_scroll_layout(length, offset);
1039                 set_offset(scale_ * length * value / MaxScrollValue);
1040         }
1041
1042         ruler_->update();
1043         viewport_->update();
1044 }
1045
1046 void View::v_scroll_value_changed()
1047 {
1048         header_->update();
1049         viewport_->update();
1050 }
1051
1052 void View::signals_changed()
1053 {
1054         using sigrok::Channel;
1055
1056         vector< shared_ptr<Channel> > channels;
1057         shared_ptr<sigrok::Device> sr_dev;
1058
1059         // Do we need to set the vertical scrollbar to its default position later?
1060         // We do if there are no traces, i.e. the scroll bar has no range set
1061         bool reset_scrollbar =
1062                 (scrollarea_.verticalScrollBar()->minimum() ==
1063                         scrollarea_.verticalScrollBar()->maximum());
1064
1065         if (!session_.device()) {
1066                 reset_scroll();
1067                 signals_.clear();
1068         } else {
1069                 sr_dev = session_.device()->device();
1070                 assert(sr_dev);
1071                 channels = sr_dev->channels();
1072         }
1073
1074         vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1075
1076         // Make a list of traces that are being added, and a list of traces
1077         // that are being removed
1078         const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1079         const set<shared_ptr<Trace>> prev_traces(
1080                 prev_trace_list.begin(), prev_trace_list.end());
1081
1082         set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1083
1084 #ifdef ENABLE_DECODE
1085         traces.insert(decode_traces_.begin(), decode_traces_.end());
1086 #endif
1087
1088         set< shared_ptr<Trace> > add_traces;
1089         set_difference(traces.begin(), traces.end(),
1090                 prev_traces.begin(), prev_traces.end(),
1091                 inserter(add_traces, add_traces.begin()));
1092
1093         set< shared_ptr<Trace> > remove_traces;
1094         set_difference(prev_traces.begin(), prev_traces.end(),
1095                 traces.begin(), traces.end(),
1096                 inserter(remove_traces, remove_traces.begin()));
1097
1098         // Make a look-up table of sigrok Channels to pulseview Signals
1099         unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1100                 signal_map;
1101         for (const shared_ptr<Signal> &sig : signals_)
1102                 signal_map[sig->base()] = sig;
1103
1104         // Populate channel groups
1105         if (sr_dev)
1106                 for (auto entry : sr_dev->channel_groups()) {
1107                         const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1108
1109                         if (group->channels().size() <= 1)
1110                                 continue;
1111
1112                         // Find best trace group to add to
1113                         TraceTreeItemOwner *owner = find_prevalent_trace_group(
1114                                 group, signal_map);
1115
1116                         // If there is no trace group, create one
1117                         shared_ptr<TraceGroup> new_trace_group;
1118                         if (!owner) {
1119                                 new_trace_group.reset(new TraceGroup());
1120                                 owner = new_trace_group.get();
1121                         }
1122
1123                         // Extract traces for the trace group, removing them from
1124                         // the add list
1125                         const vector< shared_ptr<Trace> > new_traces_in_group =
1126                                 extract_new_traces_for_channels(group->channels(),
1127                                         signal_map, add_traces);
1128
1129                         // Add the traces to the group
1130                         const pair<int, int> prev_v_extents = owner->v_extents();
1131                         int offset = prev_v_extents.second - prev_v_extents.first;
1132                         for (shared_ptr<Trace> trace : new_traces_in_group) {
1133                                 assert(trace);
1134                                 owner->add_child_item(trace);
1135
1136                                 const pair<int, int> extents = trace->v_extents();
1137                                 if (trace->enabled())
1138                                         offset += -extents.first;
1139                                 trace->force_to_v_offset(offset);
1140                                 if (trace->enabled())
1141                                         offset += extents.second;
1142                         }
1143
1144                         if (new_trace_group) {
1145                                 // Assign proper vertical offsets to each channel in the group
1146                                 new_trace_group->restack_items();
1147
1148                                 // If this is a new group, enqueue it in the new top level
1149                                 // items list
1150                                 if (!new_traces_in_group.empty())
1151                                         new_top_level_items.push_back(new_trace_group);
1152                         }
1153                 }
1154
1155         // Enqueue the remaining logic channels in a group
1156         vector< shared_ptr<Channel> > logic_channels;
1157         copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1158                 [](const shared_ptr<Channel>& c) {
1159                         return c->type() == sigrok::ChannelType::LOGIC; });
1160
1161         const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1162                 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1163
1164         if (non_grouped_logic_signals.size() > 0) {
1165                 const shared_ptr<TraceGroup> non_grouped_trace_group(
1166                         make_shared<TraceGroup>());
1167                 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1168                         non_grouped_trace_group->add_child_item(trace);
1169
1170                 non_grouped_trace_group->restack_items();
1171                 new_top_level_items.push_back(non_grouped_trace_group);
1172         }
1173
1174         // Enqueue the remaining channels as free ungrouped traces
1175         const vector< shared_ptr<Trace> > new_top_level_signals =
1176                 extract_new_traces_for_channels(channels, signal_map, add_traces);
1177         new_top_level_items.insert(new_top_level_items.end(),
1178                 new_top_level_signals.begin(), new_top_level_signals.end());
1179
1180         // Enqueue any remaining traces i.e. decode traces
1181         new_top_level_items.insert(new_top_level_items.end(),
1182                 add_traces.begin(), add_traces.end());
1183
1184         // Remove any removed traces
1185         for (shared_ptr<Trace> trace : remove_traces) {
1186                 TraceTreeItemOwner *const owner = trace->owner();
1187                 assert(owner);
1188                 owner->remove_child_item(trace);
1189         }
1190
1191         // Remove any empty trace groups
1192         for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1193                 if (group->child_items().size() == 0) {
1194                         remove_child_item(group);
1195                         group.reset();
1196                 }
1197
1198         // Add and position the pending top levels items
1199         int offset = v_extents().second;
1200         for (auto item : new_top_level_items) {
1201                 add_child_item(item);
1202
1203                 // Position the item after the last item or at the top if there is none
1204                 const pair<int, int> extents = item->v_extents();
1205
1206                 if (item->enabled())
1207                         offset += -extents.first;
1208
1209                 item->force_to_v_offset(offset);
1210
1211                 if (item->enabled())
1212                         offset += extents.second;
1213         }
1214
1215         update_layout();
1216
1217         header_->update();
1218         viewport_->update();
1219
1220         if (reset_scrollbar)
1221                 set_scroll_default();
1222 }
1223
1224 void View::capture_state_updated(int state)
1225 {
1226         if (state == Session::Running) {
1227                 set_time_unit(util::TimeUnit::Samples);
1228
1229                 trigger_markers_.clear();
1230
1231                 // Activate "always zoom to fit" if the setting is enabled and we're
1232                 // the main view of this session (other trace views may be used for
1233                 // zooming and we don't want to mess them up)
1234                 GlobalSettings settings;
1235                 bool state = settings.value(GlobalSettings::Key_View_AlwaysZoomToFit).toBool();
1236                 if (is_main_view_ && state) {
1237                         always_zoom_to_fit_ = true;
1238                         always_zoom_to_fit_changed(always_zoom_to_fit_);
1239                 }
1240
1241                 // Enable sticky scrolling if the setting is enabled
1242                 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1243         }
1244
1245         if (state == Session::Stopped) {
1246                 // After acquisition has stopped we need to re-calculate the ticks once
1247                 // as it's otherwise done when the user pans or zooms, which is too late
1248                 calculate_tick_spacing();
1249
1250                 // Reset "always zoom to fit", the acquisition has stopped
1251                 if (always_zoom_to_fit_) {
1252                         // Perform a final zoom-to-fit before disabling
1253                         zoom_fit(always_zoom_to_fit_);
1254                         always_zoom_to_fit_ = false;
1255                         always_zoom_to_fit_changed(always_zoom_to_fit_);
1256                 }
1257         }
1258 }
1259
1260 void View::data_updated()
1261 {
1262         if (always_zoom_to_fit_ || sticky_scrolling_) {
1263                 if (!delayed_view_updater_.isActive())
1264                         delayed_view_updater_.start();
1265         } else {
1266                 determine_time_unit();
1267                 update_scroll();
1268                 ruler_->update();
1269                 viewport_->update();
1270         }
1271 }
1272
1273 void View::perform_delayed_view_update()
1274 {
1275         if (always_zoom_to_fit_) {
1276                 zoom_fit(true);
1277         } else if (sticky_scrolling_) {
1278                 // Make right side of the view sticky
1279                 double length = 0;
1280                 Timestamp offset;
1281                 get_scroll_layout(length, offset);
1282
1283                 const QSize areaSize = viewport_->size();
1284                 length = max(length - areaSize.width(), 0.0);
1285
1286                 set_offset(scale_ * length);
1287         }
1288
1289         determine_time_unit();
1290         update_scroll();
1291         ruler_->update();
1292         viewport_->update();
1293 }
1294
1295 void View::process_sticky_events()
1296 {
1297         if (sticky_events_ & TraceTreeItemHExtentsChanged)
1298                 update_layout();
1299         if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1300                 restack_all_trace_tree_items();
1301                 update_scroll();
1302         }
1303
1304         // Clear the sticky events
1305         sticky_events_ = 0;
1306 }
1307
1308 void View::on_hover_point_changed()
1309 {
1310         const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1311                 list_by_type<TraceTreeItem>());
1312         for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1313                 r->hover_point_changed();
1314 }
1315
1316 } // namespace TraceView
1317 } // namespace views
1318 } // namespace pv