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