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