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