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