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