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