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