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