DecodeTrace: Reset cached trace properties when decoder stack resets
[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         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         // Update the ruler so that it uses the new scale
361         calculate_tick_spacing();
362 }
363
364 vector< shared_ptr<TimeItem> > View::time_items() const
365 {
366         const vector<shared_ptr<Flag>> f(flags());
367         vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
368         items.push_back(cursors_);
369         items.push_back(cursors_->first());
370         items.push_back(cursors_->second());
371
372         for (auto trigger_marker : trigger_markers_)
373                 items.push_back(trigger_marker);
374
375         return items;
376 }
377
378 double View::scale() const
379 {
380         return scale_;
381 }
382
383 void View::set_scale(double scale)
384 {
385         if (scale_ != scale) {
386                 scale_ = scale;
387                 scale_changed();
388         }
389 }
390
391 const Timestamp& View::offset() const
392 {
393         return offset_;
394 }
395
396 void View::set_offset(const pv::util::Timestamp& offset)
397 {
398         if (offset_ != offset) {
399                 offset_ = offset;
400                 offset_changed();
401         }
402 }
403
404 int View::owner_visual_v_offset() const
405 {
406         return -scrollarea_->verticalScrollBar()->sliderPosition();
407 }
408
409 void View::set_v_offset(int offset)
410 {
411         scrollarea_->verticalScrollBar()->setSliderPosition(offset);
412         header_->update();
413         viewport_->update();
414 }
415
416 unsigned int View::depth() const
417 {
418         return 0;
419 }
420
421 pv::util::SIPrefix View::tick_prefix() const
422 {
423         return tick_prefix_;
424 }
425
426 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
427 {
428         if (tick_prefix_ != tick_prefix) {
429                 tick_prefix_ = tick_prefix;
430                 tick_prefix_changed();
431         }
432 }
433
434 unsigned int View::tick_precision() const
435 {
436         return tick_precision_;
437 }
438
439 void View::set_tick_precision(unsigned tick_precision)
440 {
441         if (tick_precision_ != tick_precision) {
442                 tick_precision_ = tick_precision;
443                 tick_precision_changed();
444         }
445 }
446
447 const pv::util::Timestamp& View::tick_period() const
448 {
449         return tick_period_;
450 }
451
452 void View::set_tick_period(const pv::util::Timestamp& tick_period)
453 {
454         if (tick_period_ != tick_period) {
455                 tick_period_ = tick_period;
456                 tick_period_changed();
457         }
458 }
459
460 TimeUnit View::time_unit() const
461 {
462         return time_unit_;
463 }
464
465 void View::set_time_unit(pv::util::TimeUnit time_unit)
466 {
467         if (time_unit_ != time_unit) {
468                 time_unit_ = time_unit;
469                 time_unit_changed();
470         }
471 }
472
473 void View::zoom(double steps)
474 {
475         zoom(steps, viewport_->width() / 2);
476 }
477
478 void View::zoom(double steps, int offset)
479 {
480         set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
481 }
482
483 void View::zoom_fit(bool gui_state)
484 {
485         // Act as one-shot when stopped, toggle along with the GUI otherwise
486         if (session_.get_capture_state() == Session::Stopped) {
487                 always_zoom_to_fit_ = false;
488                 always_zoom_to_fit_changed(false);
489         } else {
490                 always_zoom_to_fit_ = gui_state;
491                 always_zoom_to_fit_changed(gui_state);
492         }
493
494         const pair<Timestamp, Timestamp> extents = get_time_extents();
495         const Timestamp delta = extents.second - extents.first;
496         if (delta < Timestamp("1e-12"))
497                 return;
498
499         assert(viewport_);
500         const int w = viewport_->width();
501         if (w <= 0)
502                 return;
503
504         const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
505         set_scale_offset(scale.convert_to<double>(), extents.first);
506 }
507
508 void View::zoom_one_to_one()
509 {
510         using pv::data::SignalData;
511
512         // Make a set of all the visible data objects
513         set< shared_ptr<SignalData> > visible_data = get_visible_data();
514         if (visible_data.empty())
515                 return;
516
517         assert(viewport_);
518         const int w = viewport_->width();
519         if (w <= 0)
520                 return;
521
522         set_zoom(1.0 / session_.get_samplerate(), w / 2);
523 }
524
525 void View::set_scale_offset(double scale, const Timestamp& offset)
526 {
527         // Disable sticky scrolling / always zoom to fit when acquisition runs
528         // and user drags the viewport
529         if ((scale_ == scale) && (offset_ != offset) &&
530                         (session_.get_capture_state() == Session::Running)) {
531
532                 if (sticky_scrolling_) {
533                         sticky_scrolling_ = false;
534                         sticky_scrolling_changed(false);
535                 }
536
537                 if (always_zoom_to_fit_) {
538                         always_zoom_to_fit_ = false;
539                         always_zoom_to_fit_changed(false);
540                 }
541         }
542
543         set_scale(scale);
544         set_offset(offset);
545
546         calculate_tick_spacing();
547
548         update_scroll();
549         ruler_->update();
550         viewport_->update();
551 }
552
553 set< shared_ptr<SignalData> > View::get_visible_data() const
554 {
555         // Make a set of all the visible data objects
556         set< shared_ptr<SignalData> > visible_data;
557         for (const shared_ptr<Signal> sig : signals_)
558                 if (sig->enabled())
559                         visible_data.insert(sig->data());
560
561         return visible_data;
562 }
563
564 pair<Timestamp, Timestamp> View::get_time_extents() const
565 {
566         boost::optional<Timestamp> left_time, right_time;
567         const set< shared_ptr<SignalData> > visible_data = get_visible_data();
568         for (const shared_ptr<SignalData> d : visible_data) {
569                 const vector< shared_ptr<Segment> > segments = d->segments();
570                 for (const shared_ptr<Segment> &s : segments) {
571                         double samplerate = s->samplerate();
572                         samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
573
574                         const Timestamp start_time = s->start_time();
575                         left_time = left_time ?
576                                 min(*left_time, start_time) :
577                                                 start_time;
578                         right_time = right_time ?
579                                 max(*right_time, start_time + d->max_sample_count() / samplerate) :
580                                                  start_time + d->max_sample_count() / samplerate;
581                 }
582         }
583
584         if (!left_time || !right_time)
585                 return make_pair(0, 0);
586
587         assert(*left_time < *right_time);
588         return make_pair(*left_time, *right_time);
589 }
590
591 void View::enable_show_sampling_points(bool state)
592 {
593         (void)state;
594
595         viewport_->update();
596 }
597
598 void View::enable_show_analog_minor_grid(bool state)
599 {
600         (void)state;
601
602         viewport_->update();
603 }
604
605 void View::enable_coloured_bg(bool state)
606 {
607         coloured_bg_ = state;
608         viewport_->update();
609 }
610
611 bool View::coloured_bg() const
612 {
613         return coloured_bg_;
614 }
615
616 bool View::cursors_shown() const
617 {
618         return show_cursors_;
619 }
620
621 void View::show_cursors(bool show)
622 {
623         show_cursors_ = show;
624         ruler_->update();
625         viewport_->update();
626 }
627
628 void View::centre_cursors()
629 {
630         const double time_width = scale_ * viewport_->width();
631         cursors_->first()->set_time(offset_ + time_width * 0.4);
632         cursors_->second()->set_time(offset_ + time_width * 0.6);
633         ruler_->update();
634         viewport_->update();
635 }
636
637 shared_ptr<CursorPair> View::cursors() const
638 {
639         return cursors_;
640 }
641
642 void View::add_flag(const Timestamp& time)
643 {
644         flags_.push_back(make_shared<Flag>(*this, time,
645                 QString("%1").arg(next_flag_text_)));
646
647         next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
648                 (next_flag_text_ + 1);
649
650         time_item_appearance_changed(true, true);
651 }
652
653 void View::remove_flag(shared_ptr<Flag> flag)
654 {
655         flags_.remove(flag);
656         time_item_appearance_changed(true, true);
657 }
658
659 vector< shared_ptr<Flag> > View::flags() const
660 {
661         vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
662         stable_sort(flags.begin(), flags.end(),
663                 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
664                         return a->time() < b->time();
665                 });
666
667         return flags;
668 }
669
670 const QPoint& View::hover_point() const
671 {
672         return hover_point_;
673 }
674
675 void View::restack_all_trace_tree_items()
676 {
677         // Make a list of owners that is sorted from deepest first
678         const vector<shared_ptr<TraceTreeItem>> items(
679                 list_by_type<TraceTreeItem>());
680         set< TraceTreeItemOwner* > owners;
681         for (const auto &r : items)
682                 owners.insert(r->owner());
683         vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
684         sort(sorted_owners.begin(), sorted_owners.end(),
685                 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
686                         return a->depth() > b->depth(); });
687
688         // Restack the items recursively
689         for (auto &o : sorted_owners)
690                 o->restack_items();
691
692         // Animate the items to their destination
693         for (const auto &i : items)
694                 i->animate_to_layout_v_offset();
695 }
696
697 void View::trigger_event(util::Timestamp location)
698 {
699         trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
700 }
701
702 void View::get_scroll_layout(double &length, Timestamp &offset) const
703 {
704         const pair<Timestamp, Timestamp> extents = get_time_extents();
705         length = ((extents.second - extents.first) / scale_).convert_to<double>();
706         offset = offset_ / scale_;
707 }
708
709 void View::set_zoom(double scale, int offset)
710 {
711         // Reset the "always zoom to fit" feature as the user changed the zoom
712         always_zoom_to_fit_ = false;
713         always_zoom_to_fit_changed(false);
714
715         const Timestamp cursor_offset = offset_ + scale_ * offset;
716         const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
717         const Timestamp new_offset = cursor_offset - new_scale * offset;
718         set_scale_offset(new_scale.convert_to<double>(), new_offset);
719 }
720
721 void View::calculate_tick_spacing()
722 {
723         const double SpacingIncrement = 10.0f;
724         const double MinValueSpacing = 40.0f;
725
726         // Figure out the highest numeric value visible on a label
727         const QSize areaSize = viewport_->size();
728         const Timestamp max_time = max(fabs(offset_),
729                 fabs(offset_ + scale_ * areaSize.width()));
730
731         double min_width = SpacingIncrement;
732         double label_width, tick_period_width;
733
734         QFontMetrics m(QApplication::font());
735
736         // Copies of the member variables with the same name, used in the calculation
737         // and written back afterwards, so that we don't emit signals all the time
738         // during the calculation.
739         pv::util::Timestamp tick_period = tick_period_;
740         pv::util::SIPrefix tick_prefix = tick_prefix_;
741         unsigned tick_precision = tick_precision_;
742
743         do {
744                 const double min_period = scale_ * min_width;
745
746                 const int order = (int)floorf(log10f(min_period));
747                 const pv::util::Timestamp order_decimal =
748                         pow(pv::util::Timestamp(10), order);
749
750                 // Allow for a margin of error so that a scale unit of 1 can be used.
751                 // Otherwise, for a SU of 1 the tick period will almost always be below
752                 // the min_period by a small amount - and thus skipped in favor of 2.
753                 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
754                 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
755                 double tp_with_margin;
756                 unsigned int unit = 0;
757
758                 do {
759                         tp_with_margin = order_decimal.convert_to<double>() *
760                                 (ScaleUnits[unit++] + tp_margin);
761                 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
762
763                 tick_period = order_decimal * ScaleUnits[unit - 1];
764                 tick_prefix = static_cast<pv::util::SIPrefix>(
765                         (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
766
767                 // Precision is the number of fractional digits required, not
768                 // taking the prefix into account (and it must never be negative)
769                 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
770
771                 tick_period_width = (tick_period / scale_).convert_to<double>();
772
773                 const QString label_text = Ruler::format_time_with_distance(
774                         tick_period, max_time, tick_prefix, time_unit_, tick_precision);
775
776                 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
777                         Qt::AlignLeft | Qt::AlignTop, label_text).width() +
778                                 MinValueSpacing;
779
780                 min_width += SpacingIncrement;
781         } while (tick_period_width < label_width);
782
783         set_tick_period(tick_period);
784         set_tick_prefix(tick_prefix);
785         set_tick_precision(tick_precision);
786 }
787
788 void View::adjust_top_margin()
789 {
790         assert(viewport_);
791
792         const QSize areaSize = viewport_->size();
793
794         const pair<int, int> extents = v_extents();
795         const int top_margin = owner_visual_v_offset() + extents.first;
796         const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
797
798         // Do we have empty space at the top while the last trace goes out of screen?
799         if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
800                 const int trace_height = extents.second - extents.first;
801
802                 // Center everything vertically if there is enough space
803                 if (areaSize.height() >= trace_height)
804                         set_v_offset(extents.first -
805                                 ((areaSize.height() - trace_height) / 2));
806                 else
807                         // Remove the top margin to make as many traces fit on screen as possible
808                         set_v_offset(extents.first);
809         }
810 }
811
812 void View::update_scroll()
813 {
814         assert(viewport_);
815         QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
816         QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
817
818         const QSize areaSize = viewport_->size();
819
820         // Set the horizontal scroll bar
821         double length = 0;
822         Timestamp offset;
823         get_scroll_layout(length, offset);
824         length = max(length - areaSize.width(), 0.0);
825
826         int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
827
828         hscrollbar->setPageStep(areaSize.width() / 2);
829         hscrollbar->setSingleStep(major_tick_distance);
830
831         updating_scroll_ = true;
832
833         if (length < MaxScrollValue) {
834                 hscrollbar->setRange(0, length);
835                 hscrollbar->setSliderPosition(offset.convert_to<double>());
836         } else {
837                 hscrollbar->setRange(0, MaxScrollValue);
838                 hscrollbar->setSliderPosition(
839                         (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
840         }
841
842         updating_scroll_ = false;
843
844         // Set the vertical scrollbar
845         vscrollbar->setPageStep(areaSize.height());
846         vscrollbar->setSingleStep(areaSize.height() / 8);
847
848         const pair<int, int> extents = v_extents();
849
850         // Don't change the scrollbar range if there are no traces
851         if (extents.first != extents.second)
852                 vscrollbar->setRange(extents.first - areaSize.height(),
853                         extents.second);
854
855         if (scroll_needs_defaults_)
856                 set_scroll_default();
857 }
858
859 void View::reset_scroll()
860 {
861         scrollarea_->verticalScrollBar()->setRange(0, 0);
862 }
863
864 void View::set_scroll_default()
865 {
866         assert(viewport_);
867
868         const QSize areaSize = viewport_->size();
869
870         const pair<int, int> extents = v_extents();
871         const int trace_height = extents.second - extents.first;
872
873         // Do all traces fit in the view?
874         if (areaSize.height() >= trace_height)
875                 // Center all traces vertically
876                 set_v_offset(extents.first -
877                         ((areaSize.height() - trace_height) / 2));
878         else
879                 // Put the first trace at the top, letting the bottom ones overflow
880                 set_v_offset(extents.first);
881 }
882
883 bool View::header_was_shrunk() const
884 {
885         const int header_pane_width = splitter_->sizes().front();
886         const int header_width = header_->extended_size_hint().width();
887
888         // Allow for a slight margin of error so that we also accept
889         // slight differences when e.g. a label name change increased
890         // the overall width
891         return (header_pane_width < (header_width - 10));
892 }
893
894 void View::expand_header_to_fit()
895 {
896         int splitter_area_width = 0;
897         for (int w : splitter_->sizes())
898                 splitter_area_width += w;
899
900         // Make sure the header has enough horizontal space to show all labels fully
901         QList<int> pane_sizes;
902         pane_sizes.push_back(header_->extended_size_hint().width());
903         pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
904         splitter_->setSizes(pane_sizes);
905 }
906
907 void View::update_layout()
908 {
909         update_scroll();
910 }
911
912 TraceTreeItemOwner* View::find_prevalent_trace_group(
913         const shared_ptr<sigrok::ChannelGroup> &group,
914         const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
915                 &signal_map)
916 {
917         assert(group);
918
919         unordered_set<TraceTreeItemOwner*> owners;
920         vector<TraceTreeItemOwner*> owner_list;
921
922         // Make a set and a list of all the owners
923         for (const auto &channel : group->channels()) {
924                 for (auto entry : signal_map) {
925                         if (entry.first->channel() == channel) {
926                                 TraceTreeItemOwner *const o = (entry.second)->owner();
927                                 owner_list.push_back(o);
928                                 owners.insert(o);
929                         }
930                 }
931         }
932
933         // Iterate through the list of owners, and find the most prevalent
934         size_t max_prevalence = 0;
935         TraceTreeItemOwner *prevalent_owner = nullptr;
936         for (TraceTreeItemOwner *owner : owners) {
937                 const size_t prevalence = count_if(
938                         owner_list.begin(), owner_list.end(),
939                         [&](TraceTreeItemOwner *o) { return o == owner; });
940                 if (prevalence > max_prevalence) {
941                         max_prevalence = prevalence;
942                         prevalent_owner = owner;
943                 }
944         }
945
946         return prevalent_owner;
947 }
948
949 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
950         const vector< shared_ptr<sigrok::Channel> > &channels,
951         const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
952                 &signal_map,
953         set< shared_ptr<Trace> > &add_list)
954 {
955         vector< shared_ptr<Trace> > filtered_traces;
956
957         for (const auto &channel : channels) {
958                 for (auto entry : signal_map) {
959                         if (entry.first->channel() == channel) {
960                                 shared_ptr<Trace> trace = entry.second;
961                                 const auto list_iter = add_list.find(trace);
962                                 if (list_iter == add_list.end())
963                                         continue;
964
965                                 filtered_traces.push_back(trace);
966                                 add_list.erase(list_iter);
967                         }
968                 }
969         }
970
971         return filtered_traces;
972 }
973
974 void View::determine_time_unit()
975 {
976         // Check whether we know the sample rate and hence can use time as the unit
977         if (time_unit_ == util::TimeUnit::Samples) {
978                 // Check all signals but...
979                 for (const shared_ptr<Signal> signal : signals_) {
980                         const shared_ptr<SignalData> data = signal->data();
981
982                         // ...only check first segment of each
983                         const vector< shared_ptr<Segment> > segments = data->segments();
984                         if (!segments.empty())
985                                 if (segments[0]->samplerate()) {
986                                         set_time_unit(util::TimeUnit::Time);
987                                         break;
988                                 }
989                 }
990         }
991 }
992
993 bool View::eventFilter(QObject *object, QEvent *event)
994 {
995         const QEvent::Type type = event->type();
996         if (type == QEvent::MouseMove) {
997
998                 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
999                 if (object == viewport_)
1000                         hover_point_ = mouse_event->pos();
1001                 else if (object == ruler_)
1002                         hover_point_ = QPoint(mouse_event->x(), 0);
1003                 else if (object == header_)
1004                         hover_point_ = QPoint(0, mouse_event->y());
1005                 else
1006                         hover_point_ = QPoint(-1, -1);
1007
1008                 update_hover_point();
1009
1010         } else if (type == QEvent::Leave) {
1011                 hover_point_ = QPoint(-1, -1);
1012                 update_hover_point();
1013         } else if (type == QEvent::Show) {
1014
1015                 // This is somewhat of a hack, unfortunately. We cannot use
1016                 // set_v_offset() from within restore_settings() as the view
1017                 // at that point is neither visible nor properly sized.
1018                 // This is the least intrusive workaround I could come up
1019                 // with: set the vertical offset (or scroll defaults) when
1020                 // the view is shown, which happens after all widgets were
1021                 // resized to their final sizes.
1022                 update_layout();
1023
1024                 if (!settings_restored_)
1025                         expand_header_to_fit();
1026
1027                 if (scroll_needs_defaults_) {
1028                         set_scroll_default();
1029                         scroll_needs_defaults_ = false;
1030                 }
1031
1032                 if (saved_v_offset_) {
1033                         set_v_offset(saved_v_offset_);
1034                         saved_v_offset_ = 0;
1035                 }
1036         }
1037
1038         return QObject::eventFilter(object, event);
1039 }
1040
1041 void View::resizeEvent(QResizeEvent* event)
1042 {
1043         // Only adjust the top margin if we shrunk vertically
1044         if (event->size().height() < event->oldSize().height())
1045                 adjust_top_margin();
1046
1047         update_layout();
1048 }
1049
1050 void View::update_hover_point()
1051 {
1052         const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1053                 list_by_type<TraceTreeItem>());
1054         for (shared_ptr<TraceTreeItem> r : trace_tree_items)
1055                 r->hover_point_changed(hover_point_);
1056
1057         hover_point_changed(hover_point_);
1058 }
1059
1060 void View::row_item_appearance_changed(bool label, bool content)
1061 {
1062         if (label)
1063                 header_->update();
1064         if (content)
1065                 viewport_->update();
1066 }
1067
1068 void View::time_item_appearance_changed(bool label, bool content)
1069 {
1070         if (label) {
1071                 ruler_->update();
1072
1073                 // Make sure the header pane width is updated, too
1074                 update_layout();
1075         }
1076
1077         if (content)
1078                 viewport_->update();
1079 }
1080
1081 void View::extents_changed(bool horz, bool vert)
1082 {
1083         sticky_events_ |=
1084                 (horz ? TraceTreeItemHExtentsChanged : 0) |
1085                 (vert ? TraceTreeItemVExtentsChanged : 0);
1086
1087         lazy_event_handler_.start();
1088 }
1089
1090 void View::on_splitter_moved()
1091 {
1092         // Setting the maximum width of the header widget doesn't work as
1093         // expected because the splitter would allow the user to make the
1094         // pane wider than that, creating empty space as a result.
1095         // To make this work, we stricly enforce the maximum width by
1096         // expanding the header unless the user shrunk it on purpose.
1097         // As we're then setting the width of the header pane, we set the
1098         // splitter to the maximum allowed position.
1099         if (!header_was_shrunk())
1100                 expand_header_to_fit();
1101 }
1102
1103 void View::h_scroll_value_changed(int value)
1104 {
1105         if (updating_scroll_)
1106                 return;
1107
1108         // Disable sticky scrolling when user moves the horizontal scroll bar
1109         // during a running acquisition
1110         if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1111                 sticky_scrolling_ = false;
1112                 sticky_scrolling_changed(false);
1113         }
1114
1115         const int range = scrollarea_->horizontalScrollBar()->maximum();
1116         if (range < MaxScrollValue)
1117                 set_offset(scale_ * value);
1118         else {
1119                 double length = 0;
1120                 Timestamp offset;
1121                 get_scroll_layout(length, offset);
1122                 set_offset(scale_ * length * value / MaxScrollValue);
1123         }
1124
1125         ruler_->update();
1126         viewport_->update();
1127 }
1128
1129 void View::v_scroll_value_changed()
1130 {
1131         header_->update();
1132         viewport_->update();
1133 }
1134
1135 void View::signals_changed()
1136 {
1137         using sigrok::Channel;
1138
1139         vector< shared_ptr<Channel> > channels;
1140         shared_ptr<sigrok::Device> sr_dev;
1141
1142         // Do we need to set the vertical scrollbar to its default position later?
1143         // We do if there are no traces, i.e. the scroll bar has no range set
1144         bool reset_scrollbar =
1145                 (scrollarea_->verticalScrollBar()->minimum() ==
1146                         scrollarea_->verticalScrollBar()->maximum());
1147
1148         if (!session_.device()) {
1149                 reset_scroll();
1150                 signals_.clear();
1151         } else {
1152                 sr_dev = session_.device()->device();
1153                 assert(sr_dev);
1154                 channels = sr_dev->channels();
1155         }
1156
1157         vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1158
1159         // Make a list of traces that are being added, and a list of traces
1160         // that are being removed
1161         const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1162         const set<shared_ptr<Trace>> prev_traces(
1163                 prev_trace_list.begin(), prev_trace_list.end());
1164
1165         set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1166
1167 #ifdef ENABLE_DECODE
1168         traces.insert(decode_traces_.begin(), decode_traces_.end());
1169 #endif
1170
1171         set< shared_ptr<Trace> > add_traces;
1172         set_difference(traces.begin(), traces.end(),
1173                 prev_traces.begin(), prev_traces.end(),
1174                 inserter(add_traces, add_traces.begin()));
1175
1176         set< shared_ptr<Trace> > remove_traces;
1177         set_difference(prev_traces.begin(), prev_traces.end(),
1178                 traces.begin(), traces.end(),
1179                 inserter(remove_traces, remove_traces.begin()));
1180
1181         // Make a look-up table of sigrok Channels to pulseview Signals
1182         unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1183                 signal_map;
1184         for (const shared_ptr<Signal> &sig : signals_)
1185                 signal_map[sig->base()] = sig;
1186
1187         // Populate channel groups
1188         if (sr_dev)
1189                 for (auto entry : sr_dev->channel_groups()) {
1190                         const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1191
1192                         if (group->channels().size() <= 1)
1193                                 continue;
1194
1195                         // Find best trace group to add to
1196                         TraceTreeItemOwner *owner = find_prevalent_trace_group(
1197                                 group, signal_map);
1198
1199                         // If there is no trace group, create one
1200                         shared_ptr<TraceGroup> new_trace_group;
1201                         if (!owner) {
1202                                 new_trace_group.reset(new TraceGroup());
1203                                 owner = new_trace_group.get();
1204                         }
1205
1206                         // Extract traces for the trace group, removing them from
1207                         // the add list
1208                         const vector< shared_ptr<Trace> > new_traces_in_group =
1209                                 extract_new_traces_for_channels(group->channels(),
1210                                         signal_map, add_traces);
1211
1212                         // Add the traces to the group
1213                         const pair<int, int> prev_v_extents = owner->v_extents();
1214                         int offset = prev_v_extents.second - prev_v_extents.first;
1215                         for (shared_ptr<Trace> trace : new_traces_in_group) {
1216                                 assert(trace);
1217                                 owner->add_child_item(trace);
1218
1219                                 const pair<int, int> extents = trace->v_extents();
1220                                 if (trace->enabled())
1221                                         offset += -extents.first;
1222                                 trace->force_to_v_offset(offset);
1223                                 if (trace->enabled())
1224                                         offset += extents.second;
1225                         }
1226
1227                         if (new_trace_group) {
1228                                 // Assign proper vertical offsets to each channel in the group
1229                                 new_trace_group->restack_items();
1230
1231                                 // If this is a new group, enqueue it in the new top level
1232                                 // items list
1233                                 if (!new_traces_in_group.empty())
1234                                         new_top_level_items.push_back(new_trace_group);
1235                         }
1236                 }
1237
1238         // Enqueue the remaining logic channels in a group
1239         vector< shared_ptr<Channel> > logic_channels;
1240         copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1241                 [](const shared_ptr<Channel>& c) {
1242                         return c->type() == sigrok::ChannelType::LOGIC; });
1243
1244         const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1245                 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1246
1247         if (non_grouped_logic_signals.size() > 0) {
1248                 const shared_ptr<TraceGroup> non_grouped_trace_group(
1249                         make_shared<TraceGroup>());
1250                 for (shared_ptr<Trace> trace : non_grouped_logic_signals)
1251                         non_grouped_trace_group->add_child_item(trace);
1252
1253                 non_grouped_trace_group->restack_items();
1254                 new_top_level_items.push_back(non_grouped_trace_group);
1255         }
1256
1257         // Enqueue the remaining channels as free ungrouped traces
1258         const vector< shared_ptr<Trace> > new_top_level_signals =
1259                 extract_new_traces_for_channels(channels, signal_map, add_traces);
1260         new_top_level_items.insert(new_top_level_items.end(),
1261                 new_top_level_signals.begin(), new_top_level_signals.end());
1262
1263         // Enqueue any remaining traces i.e. decode traces
1264         new_top_level_items.insert(new_top_level_items.end(),
1265                 add_traces.begin(), add_traces.end());
1266
1267         // Remove any removed traces
1268         for (shared_ptr<Trace> trace : remove_traces) {
1269                 TraceTreeItemOwner *const owner = trace->owner();
1270                 assert(owner);
1271                 owner->remove_child_item(trace);
1272         }
1273
1274         // Remove any empty trace groups
1275         for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1276                 if (group->child_items().size() == 0) {
1277                         remove_child_item(group);
1278                         group.reset();
1279                 }
1280
1281         // Add and position the pending top levels items
1282         int offset = v_extents().second;
1283         for (auto item : new_top_level_items) {
1284                 add_child_item(item);
1285
1286                 // Position the item after the last item or at the top if there is none
1287                 const pair<int, int> extents = item->v_extents();
1288
1289                 if (item->enabled())
1290                         offset += -extents.first;
1291
1292                 item->force_to_v_offset(offset);
1293
1294                 if (item->enabled())
1295                         offset += extents.second;
1296         }
1297
1298
1299         if (!new_top_level_items.empty())
1300                 // Expand the header pane because the header should become fully
1301                 // visible when new signals are added
1302                 expand_header_to_fit();
1303
1304         update_layout();
1305
1306         header_->update();
1307         viewport_->update();
1308
1309         if (reset_scrollbar)
1310                 set_scroll_default();
1311 }
1312
1313 void View::capture_state_updated(int state)
1314 {
1315         GlobalSettings settings;
1316
1317         if (state == Session::Running) {
1318                 set_time_unit(util::TimeUnit::Samples);
1319
1320                 trigger_markers_.clear();
1321
1322                 scale_at_acq_start_ = scale_;
1323                 offset_at_acq_start_ = offset_;
1324
1325                 // Activate "always zoom to fit" if the setting is enabled and we're
1326                 // the main view of this session (other trace views may be used for
1327                 // zooming and we don't want to mess them up)
1328                 bool state = settings.value(GlobalSettings::Key_View_ZoomToFitDuringAcq).toBool();
1329                 if (is_main_view_ && state) {
1330                         always_zoom_to_fit_ = true;
1331                         always_zoom_to_fit_changed(always_zoom_to_fit_);
1332                 }
1333
1334                 // Enable sticky scrolling if the setting is enabled
1335                 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1336         }
1337
1338         if (state == Session::Stopped) {
1339                 // After acquisition has stopped we need to re-calculate the ticks once
1340                 // as it's otherwise done when the user pans or zooms, which is too late
1341                 calculate_tick_spacing();
1342
1343                 // Reset "always zoom to fit", the acquisition has stopped
1344                 if (always_zoom_to_fit_) {
1345                         // Perform a final zoom-to-fit before disabling
1346                         zoom_fit(always_zoom_to_fit_);
1347                         always_zoom_to_fit_ = false;
1348                         always_zoom_to_fit_changed(always_zoom_to_fit_);
1349                 }
1350
1351                 bool zoom_to_fit_after_acq =
1352                         settings.value(GlobalSettings::Key_View_ZoomToFitAfterAcq).toBool();
1353
1354                 // Only perform zoom-to-fit if the user hasn't altered the viewport and
1355                 // we didn't restore settings in the meanwhile
1356                 if (zoom_to_fit_after_acq &&
1357                         !suppress_zoom_to_fit_after_acq_ &&
1358                         (scale_ == scale_at_acq_start_) &&
1359                         (offset_ == offset_at_acq_start_))
1360                         zoom_fit(false);  // We're stopped, so the GUI state doesn't matter
1361
1362                 suppress_zoom_to_fit_after_acq_ = false;
1363         }
1364 }
1365
1366 void View::on_segment_changed(int segment)
1367 {
1368         current_segment_ = segment - 1;
1369
1370         for (shared_ptr<Signal> signal : signals_)
1371                 signal->set_current_segment(current_segment_);
1372
1373         viewport_->update();
1374 }
1375
1376 void View::perform_delayed_view_update()
1377 {
1378         if (always_zoom_to_fit_) {
1379                 zoom_fit(true);
1380         } else if (sticky_scrolling_) {
1381                 // Make right side of the view sticky
1382                 double length = 0;
1383                 Timestamp offset;
1384                 get_scroll_layout(length, offset);
1385
1386                 const QSize areaSize = viewport_->size();
1387                 length = max(length - areaSize.width(), 0.0);
1388
1389                 set_offset(scale_ * length);
1390         }
1391
1392         determine_time_unit();
1393         update_scroll();
1394         ruler_->update();
1395         viewport_->update();
1396 }
1397
1398 void View::process_sticky_events()
1399 {
1400         if (sticky_events_ & TraceTreeItemHExtentsChanged)
1401                 update_layout();
1402         if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1403                 restack_all_trace_tree_items();
1404                 update_scroll();
1405         }
1406
1407         // Clear the sticky events
1408         sticky_events_ = 0;
1409 }
1410
1411 } // namespace trace
1412 } // namespace views
1413 } // namespace pv