Trace View: Move ruler time conversion from View to Ruler
[pulseview.git] / pv / views / trace / view.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #ifdef ENABLE_DECODE
21 #include <libsigrokdecode/libsigrokdecode.h>
22 #endif
23
24 #include <extdef.h>
25
26 #include <algorithm>
27 #include <cassert>
28 #include <climits>
29 #include <cmath>
30 #include <iostream>
31 #include <iterator>
32 #include <unordered_set>
33
34 #include <boost/archive/text_iarchive.hpp>
35 #include <boost/archive/text_oarchive.hpp>
36 #include <boost/serialization/serialization.hpp>
37
38 #include <QApplication>
39 #include <QEvent>
40 #include <QFontMetrics>
41 #include <QMenu>
42 #include <QMouseEvent>
43 #include <QScrollBar>
44 #include <QVBoxLayout>
45
46 #include <libsigrokcxx/libsigrokcxx.hpp>
47
48 #include "analogsignal.hpp"
49 #include "header.hpp"
50 #include "logicsignal.hpp"
51 #include "ruler.hpp"
52 #include "signal.hpp"
53 #include "tracegroup.hpp"
54 #include "triggermarker.hpp"
55 #include "view.hpp"
56 #include "viewport.hpp"
57
58 #include "pv/data/logic.hpp"
59 #include "pv/data/logicsegment.hpp"
60 #include "pv/devices/device.hpp"
61 #include "pv/globalsettings.hpp"
62 #include "pv/session.hpp"
63 #include "pv/util.hpp"
64
65 #ifdef ENABLE_DECODE
66 #include "decodetrace.hpp"
67 #endif
68
69 using pv::data::SignalData;
70 using pv::data::Segment;
71 using pv::util::TimeUnit;
72 using pv::util::Timestamp;
73
74 using std::back_inserter;
75 using std::copy_if;
76 using std::count_if;
77 using std::inserter;
78 using std::max;
79 using std::make_pair;
80 using std::make_shared;
81 using std::min;
82 using std::numeric_limits;
83 using std::pair;
84 using std::set;
85 using std::set_difference;
86 using std::shared_ptr;
87 using std::stringstream;
88 using std::unordered_map;
89 using std::unordered_set;
90 using std::vector;
91
92 namespace pv {
93 namespace views {
94 namespace trace {
95
96 const Timestamp View::MaxScale("1e9");
97 const Timestamp View::MinScale("1e-12");
98
99 const int View::MaxScrollValue = INT_MAX / 2;
100
101 const int View::ScaleUnits[3] = {1, 2, 5};
102
103
104 CustomScrollArea::CustomScrollArea(QWidget *parent) :
105         QAbstractScrollArea(parent)
106 {
107 }
108
109 bool CustomScrollArea::viewportEvent(QEvent *event)
110 {
111         switch (event->type()) {
112         case QEvent::Paint:
113         case QEvent::MouseButtonPress:
114         case QEvent::MouseButtonRelease:
115         case QEvent::MouseButtonDblClick:
116         case QEvent::MouseMove:
117         case QEvent::Wheel:
118         case QEvent::TouchBegin:
119         case QEvent::TouchUpdate:
120         case QEvent::TouchEnd:
121                 return false;
122         default:
123                 return QAbstractScrollArea::viewportEvent(event);
124         }
125 }
126
127 View::View(Session &session, bool is_main_view, QWidget *parent) :
128         ViewBase(session, is_main_view, parent),
129
130         // Note: Place defaults in View::reset_view_state(), not here
131         splitter_(new QSplitter()),
132         header_was_shrunk_(false),  // The splitter remains unchanged after a reset, so this goes here
133         sticky_scrolling_(false)  // Default setting is set in MainWindow::setup_ui()
134 {
135         QVBoxLayout *root_layout = new QVBoxLayout(this);
136         root_layout->setContentsMargins(0, 0, 0, 0);
137         root_layout->addWidget(splitter_);
138
139         viewport_ = new Viewport(*this);
140         scrollarea_ = new CustomScrollArea(splitter_);
141         scrollarea_->setViewport(viewport_);
142         scrollarea_->setFrameShape(QFrame::NoFrame);
143
144         ruler_ = new Ruler(*this);
145
146         header_ = new Header(*this);
147         header_->setMinimumWidth(10);  // So that the arrow tips show at least
148
149         // We put the header into a simple layout so that we can add the top margin,
150         // allowing us to make it line up with the bottom of the ruler
151         QWidget *header_container = new QWidget();
152         header_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
153         QVBoxLayout *header_layout = new QVBoxLayout(header_container);
154         header_layout->setContentsMargins(0, ruler_->sizeHint().height(), 0, 0);
155         header_layout->addWidget(header_);
156
157         // To let the ruler and scrollarea be on the same split pane, we need a layout
158         QWidget *trace_container = new QWidget();
159         trace_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
160         QVBoxLayout *trace_layout = new QVBoxLayout(trace_container);
161         trace_layout->setSpacing(0);  // We don't want space between the ruler and scrollarea
162         trace_layout->setContentsMargins(0, 0, 0, 0);
163         trace_layout->addWidget(ruler_);
164         trace_layout->addWidget(scrollarea_);
165
166         splitter_->addWidget(header_container);
167         splitter_->addWidget(trace_container);
168         splitter_->setHandleWidth(1);  // Don't show a visible rubber band
169         splitter_->setCollapsible(0, false);  // Prevent the header from collapsing
170         splitter_->setCollapsible(1, false);  // Prevent the traces from collapsing
171         splitter_->setStretchFactor(0, 0);  // Prevent the panes from being resized
172         splitter_->setStretchFactor(1, 1);  // when the entire view is resized
173         splitter_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
174
175         viewport_->installEventFilter(this);
176         ruler_->installEventFilter(this);
177         header_->installEventFilter(this);
178
179         // Set up settings and event handlers
180         GlobalSettings settings;
181         colored_bg_ = settings.value(GlobalSettings::Key_View_ColoredBG).toBool();
182         snap_distance_ = settings.value(GlobalSettings::Key_View_SnapDistance).toInt();
183
184         GlobalSettings::add_change_handler(this);
185
186         connect(scrollarea_->horizontalScrollBar(), SIGNAL(valueChanged(int)),
187                 this, SLOT(h_scroll_value_changed(int)));
188         connect(scrollarea_->verticalScrollBar(), SIGNAL(valueChanged(int)),
189                 this, SLOT(v_scroll_value_changed()));
190
191         connect(header_, SIGNAL(selection_changed()),
192                 ruler_, SLOT(clear_selection()));
193         connect(ruler_, SIGNAL(selection_changed()),
194                 header_, SLOT(clear_selection()));
195
196         connect(header_, SIGNAL(selection_changed()),
197                 this, SIGNAL(selection_changed()));
198         connect(ruler_, SIGNAL(selection_changed()),
199                 this, SIGNAL(selection_changed()));
200
201         connect(splitter_, SIGNAL(splitterMoved(int, int)),
202                 this, SLOT(on_splitter_moved()));
203
204         connect(&lazy_event_handler_, SIGNAL(timeout()),
205                 this, SLOT(process_sticky_events()));
206         lazy_event_handler_.setSingleShot(true);
207
208         // Trigger the initial event manually. The default device has signals
209         // which were created before this object came into being
210         signals_changed();
211
212         // make sure the transparent widgets are on the top
213         ruler_->raise();
214         header_->raise();
215
216         reset_view_state();
217 }
218
219 View::~View()
220 {
221         GlobalSettings::remove_change_handler(this);
222 }
223
224 void View::reset_view_state()
225 {
226         ViewBase::reset_view_state();
227
228         segment_display_mode_ = Trace::ShowLastSegmentOnly;
229         segment_selectable_ = false;
230         scale_ = 1e-3;
231         offset_ = 0;
232         ruler_offset_ = 0;
233         updating_scroll_ = false;
234         settings_restored_ = false;
235         always_zoom_to_fit_ = false;
236         tick_period_ = 0;
237         tick_prefix_ = pv::util::SIPrefix::yocto;
238         tick_precision_ = 0;
239         time_unit_ = util::TimeUnit::Time;
240         show_cursors_ = false;
241         cursors_ = make_shared<CursorPair>(*this);
242         next_flag_text_ = 'A';
243         trigger_markers_.clear();
244         hover_widget_ = nullptr;
245         hover_point_ = QPoint(-1, -1);
246         scroll_needs_defaults_ = true;
247         saved_v_offset_ = 0;
248         scale_at_acq_start_ = 0;
249         offset_at_acq_start_ = 0;
250         suppress_zoom_to_fit_after_acq_ = false;
251
252         show_cursors_ = false;
253         cursor_state_changed(show_cursors_);
254         flags_.clear();
255
256         // Update the zoom state
257         calculate_tick_spacing();
258
259         // Make sure the standard bar's segment selector is in sync
260         set_segment_display_mode(segment_display_mode_);
261 }
262
263 Session& View::session()
264 {
265         return session_;
266 }
267
268 const Session& View::session() const
269 {
270         return session_;
271 }
272
273 unordered_set< shared_ptr<Signal> > View::signals() const
274 {
275         return signals_;
276 }
277
278 void View::clear_signals()
279 {
280         ViewBase::clear_signalbases();
281         signals_.clear();
282 }
283
284 void View::add_signal(const shared_ptr<Signal> signal)
285 {
286         ViewBase::add_signalbase(signal->base());
287         signals_.insert(signal);
288
289         signal->set_segment_display_mode(segment_display_mode_);
290         signal->set_current_segment(current_segment_);
291
292         connect(signal->base().get(), SIGNAL(name_changed(const QString&)),
293                 this, SLOT(on_signal_name_changed()));
294 }
295
296 #ifdef ENABLE_DECODE
297 void View::clear_decode_signals()
298 {
299         decode_traces_.clear();
300 }
301
302 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
303 {
304         shared_ptr<DecodeTrace> d(
305                 new DecodeTrace(session_, signal, decode_traces_.size()));
306         decode_traces_.push_back(d);
307
308         d->set_segment_display_mode(segment_display_mode_);
309         d->set_current_segment(current_segment_);
310
311         connect(signal.get(), SIGNAL(name_changed(const QString&)),
312                 this, SLOT(on_signal_name_changed()));
313 }
314
315 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
316 {
317         for (auto i = decode_traces_.begin(); i != decode_traces_.end(); i++)
318                 if ((*i)->base() == signal) {
319                         decode_traces_.erase(i);
320                         signals_changed();
321                         return;
322                 }
323 }
324 #endif
325
326 shared_ptr<Signal> View::get_signal_under_mouse_cursor() const
327 {
328         return signal_under_mouse_cursor_;
329 }
330
331 View* View::view()
332 {
333         return this;
334 }
335
336 const View* View::view() const
337 {
338         return this;
339 }
340
341 Viewport* View::viewport()
342 {
343         return viewport_;
344 }
345
346 const Viewport* View::viewport() const
347 {
348         return viewport_;
349 }
350
351 const Ruler* View::ruler() const
352 {
353         return ruler_;
354 }
355
356 void View::save_settings(QSettings &settings) const
357 {
358         settings.setValue("scale", scale_);
359         settings.setValue("v_offset",
360                 scrollarea_->verticalScrollBar()->sliderPosition());
361
362         settings.setValue("splitter_state", splitter_->saveState());
363         settings.setValue("segment_display_mode", segment_display_mode_);
364
365         {
366                 stringstream ss;
367                 boost::archive::text_oarchive oa(ss);
368                 oa << boost::serialization::make_nvp("offset", offset_);
369                 settings.setValue("offset", QString::fromStdString(ss.str()));
370         }
371
372         for (const shared_ptr<Signal>& signal : signals_) {
373                 settings.beginGroup(signal->base()->internal_name());
374                 signal->save_settings(settings);
375                 settings.endGroup();
376         }
377 }
378
379 void View::restore_settings(QSettings &settings)
380 {
381         // Note: It is assumed that this function is only called once,
382         // immediately after restoring a previous session.
383
384         if (settings.contains("scale"))
385                 set_scale(settings.value("scale").toDouble());
386
387         if (settings.contains("offset")) {
388                 util::Timestamp offset;
389                 stringstream ss;
390                 ss << settings.value("offset").toString().toStdString();
391
392                 try {
393                         boost::archive::text_iarchive ia(ss);
394                         ia >> boost::serialization::make_nvp("offset", offset);
395                         // This also updates ruler_offset_
396                         set_offset(offset);
397                 } catch (boost::archive::archive_exception&) {
398                         qDebug() << "Could not restore the view offset";
399                 }
400         }
401
402         if (settings.contains("splitter_state"))
403                 splitter_->restoreState(settings.value("splitter_state").toByteArray());
404
405         if (settings.contains("segment_display_mode"))
406                 set_segment_display_mode(
407                         (Trace::SegmentDisplayMode)(settings.value("segment_display_mode").toInt()));
408
409         for (shared_ptr<Signal> signal : signals_) {
410                 settings.beginGroup(signal->base()->internal_name());
411                 signal->restore_settings(settings);
412                 settings.endGroup();
413         }
414
415         if (settings.contains("v_offset")) {
416                 saved_v_offset_ = settings.value("v_offset").toInt();
417                 set_v_offset(saved_v_offset_);
418                 scroll_needs_defaults_ = false;
419                 // Note: see eventFilter() for additional information
420         }
421
422         settings_restored_ = true;
423         suppress_zoom_to_fit_after_acq_ = true;
424
425         // Update the ruler so that it uses the new scale
426         calculate_tick_spacing();
427 }
428
429 vector< shared_ptr<TimeItem> > View::time_items() const
430 {
431         const vector<shared_ptr<Flag>> f(flags());
432         vector<shared_ptr<TimeItem>> items(f.begin(), f.end());
433
434         if (cursors_) {
435                 items.push_back(cursors_);
436                 items.push_back(cursors_->first());
437                 items.push_back(cursors_->second());
438         }
439
440         for (auto& trigger_marker : trigger_markers_)
441                 items.push_back(trigger_marker);
442
443         return items;
444 }
445
446 double View::scale() const
447 {
448         return scale_;
449 }
450
451 void View::set_scale(double scale)
452 {
453         if (scale_ != scale) {
454                 scale_ = scale;
455                 scale_changed();
456         }
457 }
458
459 void View::set_offset(const pv::util::Timestamp& offset, bool force_update)
460 {
461         if ((offset_ != offset) || force_update) {
462                 offset_ = offset;
463                 ruler_offset_ = offset_ + zero_offset_;
464                 offset_changed();
465         }
466 }
467
468 const Timestamp& View::offset() const
469 {
470         return offset_;
471 }
472
473 const Timestamp& View::ruler_offset() const
474 {
475         return ruler_offset_;
476 }
477
478 void View::set_zero_position(const pv::util::Timestamp& position)
479 {
480         zero_offset_ = -position;
481
482         // Force an immediate update of the offsets
483         set_offset(offset_, true);
484         ruler_->update();
485 }
486
487 void View::reset_zero_position()
488 {
489         zero_offset_ = 0;
490
491         // Force an immediate update of the offsets
492         set_offset(offset_, true);
493         ruler_->update();
494 }
495
496 pv::util::Timestamp View::zero_offset() const
497 {
498         return zero_offset_;
499 }
500
501 int View::owner_visual_v_offset() const
502 {
503         return -scrollarea_->verticalScrollBar()->sliderPosition();
504 }
505
506 void View::set_v_offset(int offset)
507 {
508         scrollarea_->verticalScrollBar()->setSliderPosition(offset);
509         header_->update();
510         viewport_->update();
511 }
512
513 unsigned int View::depth() const
514 {
515         return 0;
516 }
517
518 uint32_t View::current_segment() const
519 {
520         return current_segment_;
521 }
522
523 pv::util::SIPrefix View::tick_prefix() const
524 {
525         return tick_prefix_;
526 }
527
528 void View::set_tick_prefix(pv::util::SIPrefix tick_prefix)
529 {
530         if (tick_prefix_ != tick_prefix) {
531                 tick_prefix_ = tick_prefix;
532                 tick_prefix_changed();
533         }
534 }
535
536 unsigned int View::tick_precision() const
537 {
538         return tick_precision_;
539 }
540
541 void View::set_tick_precision(unsigned tick_precision)
542 {
543         if (tick_precision_ != tick_precision) {
544                 tick_precision_ = tick_precision;
545                 tick_precision_changed();
546         }
547 }
548
549 const pv::util::Timestamp& View::tick_period() const
550 {
551         return tick_period_;
552 }
553
554 unsigned int View::minor_tick_count() const
555 {
556         return minor_tick_count_;
557 }
558
559 void View::set_tick_period(const pv::util::Timestamp& tick_period)
560 {
561         if (tick_period_ != tick_period) {
562                 tick_period_ = tick_period;
563                 tick_period_changed();
564         }
565 }
566
567 TimeUnit View::time_unit() const
568 {
569         return time_unit_;
570 }
571
572 void View::set_time_unit(pv::util::TimeUnit time_unit)
573 {
574         if (time_unit_ != time_unit) {
575                 time_unit_ = time_unit;
576                 time_unit_changed();
577         }
578 }
579
580 void View::set_current_segment(uint32_t segment_id)
581 {
582         current_segment_ = segment_id;
583
584         for (const shared_ptr<Signal>& signal : signals_)
585                 signal->set_current_segment(current_segment_);
586 #ifdef ENABLE_DECODE
587         for (shared_ptr<DecodeTrace>& dt : decode_traces_)
588                 dt->set_current_segment(current_segment_);
589 #endif
590
591         vector<util::Timestamp> triggers = session_.get_triggers(current_segment_);
592
593         trigger_markers_.clear();
594         for (util::Timestamp timestamp : triggers)
595                 trigger_markers_.push_back(make_shared<TriggerMarker>(*this, timestamp));
596
597         // When enabled, the first trigger for this segment is used as the zero position
598         GlobalSettings settings;
599         bool trigger_is_zero_time = settings.value(GlobalSettings::Key_View_TriggerIsZeroTime).toBool();
600
601         if (trigger_is_zero_time && (triggers.size() > 0))
602                 set_zero_position(triggers.front());
603
604         viewport_->update();
605
606         segment_changed(segment_id);
607 }
608
609 bool View::segment_is_selectable() const
610 {
611         return segment_selectable_;
612 }
613
614 Trace::SegmentDisplayMode View::segment_display_mode() const
615 {
616         return segment_display_mode_;
617 }
618
619 void View::set_segment_display_mode(Trace::SegmentDisplayMode mode)
620 {
621         segment_display_mode_ = mode;
622
623         for (const shared_ptr<Signal>& signal : signals_)
624                 signal->set_segment_display_mode(mode);
625
626         uint32_t last_segment = session_.get_segment_count() - 1;
627
628         switch (mode) {
629         case Trace::ShowLastSegmentOnly:
630                 if (current_segment_ != last_segment)
631                         set_current_segment(last_segment);
632                 break;
633
634         case Trace::ShowLastCompleteSegmentOnly:
635                 // Do nothing if we only have one segment so far
636                 if (last_segment > 0) {
637                         // If the last segment isn't complete, the previous one must be
638                         uint32_t segment_id =
639                                 (session_.all_segments_complete(last_segment)) ?
640                                 last_segment : last_segment - 1;
641
642                         if (current_segment_ != segment_id)
643                                 set_current_segment(segment_id);
644                 }
645                 break;
646
647         case Trace::ShowSingleSegmentOnly:
648         case Trace::ShowAllSegments:
649         case Trace::ShowAccumulatedIntensity:
650         default:
651                 // Current segment remains as-is
652                 break;
653         }
654
655         segment_selectable_ = true;
656
657         if ((mode == Trace::ShowAllSegments) || (mode == Trace::ShowAccumulatedIntensity))
658                 segment_selectable_ = false;
659
660         viewport_->update();
661
662         segment_display_mode_changed((int)mode, segment_selectable_);
663 }
664
665 void View::zoom(double steps)
666 {
667         zoom(steps, viewport_->width() / 2);
668 }
669
670 void View::zoom(double steps, int offset)
671 {
672         set_zoom(scale_ * pow(3.0 / 2.0, -steps), offset);
673 }
674
675 void View::zoom_fit(bool gui_state)
676 {
677         // Act as one-shot when stopped, toggle along with the GUI otherwise
678         if (session_.get_capture_state() == Session::Stopped) {
679                 always_zoom_to_fit_ = false;
680                 always_zoom_to_fit_changed(false);
681         } else {
682                 always_zoom_to_fit_ = gui_state;
683                 always_zoom_to_fit_changed(gui_state);
684         }
685
686         const pair<Timestamp, Timestamp> extents = get_time_extents();
687         const Timestamp delta = extents.second - extents.first;
688         if (delta < Timestamp("1e-12"))
689                 return;
690
691         assert(viewport_);
692         const int w = viewport_->width();
693         if (w <= 0)
694                 return;
695
696         const Timestamp scale = max(min(delta / w, MaxScale), MinScale);
697         set_scale_offset(scale.convert_to<double>(), extents.first);
698 }
699
700 void View::set_scale_offset(double scale, const Timestamp& offset)
701 {
702         // Disable sticky scrolling / always zoom to fit when acquisition runs
703         // and user drags the viewport
704         if ((scale_ == scale) && (offset_ != offset) &&
705                         (session_.get_capture_state() == Session::Running)) {
706
707                 if (sticky_scrolling_) {
708                         sticky_scrolling_ = false;
709                         sticky_scrolling_changed(false);
710                 }
711
712                 if (always_zoom_to_fit_) {
713                         always_zoom_to_fit_ = false;
714                         always_zoom_to_fit_changed(false);
715                 }
716         }
717
718         set_scale(scale);
719         set_offset(offset);
720
721         calculate_tick_spacing();
722
723         update_scroll();
724         ruler_->update();
725         viewport_->update();
726 }
727
728 set< shared_ptr<SignalData> > View::get_visible_data() const
729 {
730         // Make a set of all the visible data objects
731         set< shared_ptr<SignalData> > visible_data;
732         for (const shared_ptr<Signal>& sig : signals_)
733                 if (sig->enabled())
734                         visible_data.insert(sig->data());
735
736         return visible_data;
737 }
738
739 pair<Timestamp, Timestamp> View::get_time_extents() const
740 {
741         boost::optional<Timestamp> left_time, right_time;
742         const set< shared_ptr<SignalData> > visible_data = get_visible_data();
743         for (const shared_ptr<SignalData>& d : visible_data) {
744                 const vector< shared_ptr<Segment> > segments = d->segments();
745                 for (const shared_ptr<Segment>& s : segments) {
746                         double samplerate = s->samplerate();
747                         samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
748
749                         const Timestamp start_time = s->start_time();
750                         left_time = left_time ?
751                                 min(*left_time, start_time) :
752                                                 start_time;
753                         right_time = right_time ?
754                                 max(*right_time, start_time + d->max_sample_count() / samplerate) :
755                                                  start_time + d->max_sample_count() / samplerate;
756                 }
757         }
758
759         if (!left_time || !right_time)
760                 return make_pair(0, 0);
761
762         assert(*left_time < *right_time);
763         return make_pair(*left_time, *right_time);
764 }
765
766 void View::enable_show_sampling_points(bool state)
767 {
768         (void)state;
769
770         viewport_->update();
771 }
772
773 void View::enable_show_analog_minor_grid(bool state)
774 {
775         (void)state;
776
777         viewport_->update();
778 }
779
780 void View::enable_colored_bg(bool state)
781 {
782         colored_bg_ = state;
783         viewport_->update();
784 }
785
786 bool View::colored_bg() const
787 {
788         return colored_bg_;
789 }
790
791 bool View::cursors_shown() const
792 {
793         return show_cursors_;
794 }
795
796 void View::show_cursors(bool show)
797 {
798         if (show_cursors_ != show) {
799                 show_cursors_ = show;
800
801                 cursor_state_changed(show);
802                 ruler_->update();
803                 viewport_->update();
804         }
805 }
806
807 void View::set_cursors(pv::util::Timestamp& first, pv::util::Timestamp& second)
808 {
809         assert(cursors_);
810
811         cursors_->first()->set_time(first);
812         cursors_->second()->set_time(second);
813
814         ruler_->update();
815         viewport_->update();
816 }
817
818 void View::centre_cursors()
819 {
820         assert(cursors_);
821
822         const double time_width = scale_ * viewport_->width();
823         cursors_->first()->set_time(offset_ + time_width * 0.4);
824         cursors_->second()->set_time(offset_ + time_width * 0.6);
825
826         ruler_->update();
827         viewport_->update();
828 }
829
830 shared_ptr<CursorPair> View::cursors() const
831 {
832         return cursors_;
833 }
834
835 void View::add_flag(const Timestamp& time)
836 {
837         flags_.push_back(make_shared<Flag>(*this, time,
838                 QString("%1").arg(next_flag_text_)));
839
840         next_flag_text_ = (next_flag_text_ >= 'Z') ? 'A' :
841                 (next_flag_text_ + 1);
842
843         time_item_appearance_changed(true, true);
844 }
845
846 void View::remove_flag(shared_ptr<Flag> flag)
847 {
848         flags_.remove(flag);
849         time_item_appearance_changed(true, true);
850 }
851
852 vector< shared_ptr<Flag> > View::flags() const
853 {
854         vector< shared_ptr<Flag> > flags(flags_.begin(), flags_.end());
855         stable_sort(flags.begin(), flags.end(),
856                 [](const shared_ptr<Flag> &a, const shared_ptr<Flag> &b) {
857                         return a->time() < b->time();
858                 });
859
860         return flags;
861 }
862
863 const QPoint& View::hover_point() const
864 {
865         return hover_point_;
866 }
867
868 const QWidget* View::hover_widget() const
869 {
870         return hover_widget_;
871 }
872
873 int64_t View::get_nearest_level_change(const QPoint &p)
874 {
875         // Is snapping disabled?
876         if (snap_distance_ == 0)
877                 return -1;
878
879         struct entry_t {
880                 entry_t(shared_ptr<Signal> s) :
881                         signal(s), delta(numeric_limits<int64_t>::max()), sample(-1), is_dense(false) {}
882                 shared_ptr<Signal> signal;
883                 int64_t delta;
884                 int64_t sample;
885                 bool is_dense;
886         };
887
888         vector<entry_t> list;
889
890         // Create list of signals to consider
891         if (signal_under_mouse_cursor_)
892                 list.emplace_back(signal_under_mouse_cursor_);
893         else
894                 for (shared_ptr<Signal> s : signals_) {
895                         if (!s->enabled())
896                                 continue;
897
898                         list.emplace_back(s);
899                 }
900
901         // Get data for listed signals
902         for (entry_t &e : list) {
903                 // Calculate sample number from cursor position
904                 const double samples_per_pixel = e.signal->base()->get_samplerate() * scale();
905                 const int64_t x_offset = offset().convert_to<double>() / scale();
906                 const int64_t sample_num = max(((x_offset + p.x()) * samples_per_pixel), 0.0);
907
908                 vector<data::LogicSegment::EdgePair> edges =
909                         e.signal->get_nearest_level_changes(sample_num);
910
911                 if (edges.empty())
912                         continue;
913
914                 // Check first edge
915                 const int64_t first_sample_delta = abs(sample_num - edges.front().first);
916                 const int64_t first_delta = first_sample_delta / samples_per_pixel;
917                 e.delta = first_delta;
918                 e.sample = edges.front().first;
919
920                 // Check second edge if available
921                 if (edges.size() == 2) {
922                         // Note: -1 because this is usually the right edge and sample points are left-aligned
923                         const int64_t second_sample_delta = abs(sample_num - edges.back().first - 1);
924                         const int64_t second_delta = second_sample_delta / samples_per_pixel;
925
926                         // If both edges are too close, we mark this signal as being dense
927                         if ((first_delta + second_delta) <= snap_distance_)
928                                 e.is_dense = true;
929
930                         if (second_delta < first_delta) {
931                                 e.delta = second_delta;
932                                 e.sample = edges.back().first;
933                         }
934                 }
935         }
936
937         // Look for the best match: non-dense first, then dense
938         entry_t *match = nullptr;
939
940         for (entry_t &e : list) {
941                 if (e.delta > snap_distance_ || e.is_dense)
942                         continue;
943
944                 if (match) {
945                         if (e.delta < match->delta)
946                                 match = &e;
947                 } else
948                         match = &e;
949         }
950
951         if (!match) {
952                 for (entry_t &e : list) {
953                         if (!e.is_dense)
954                                 continue;
955
956                         if (match) {
957                                 if (e.delta < match->delta)
958                                         match = &e;
959                         } else
960                                 match = &e;
961                 }
962         }
963
964         if (match) {
965                 // Somewhat ugly hack to make TimeItem::drag_by() work
966                 signal_under_mouse_cursor_ = match->signal;
967
968                 return match->sample;
969         }
970
971         return -1;
972 }
973
974 void View::restack_all_trace_tree_items()
975 {
976         // Make a list of owners that is sorted from deepest first
977         const vector<shared_ptr<TraceTreeItem>> items(
978                 list_by_type<TraceTreeItem>());
979         set< TraceTreeItemOwner* > owners;
980         for (const auto &r : items)
981                 owners.insert(r->owner());
982         vector< TraceTreeItemOwner* > sorted_owners(owners.begin(), owners.end());
983         sort(sorted_owners.begin(), sorted_owners.end(),
984                 [](const TraceTreeItemOwner* a, const TraceTreeItemOwner *b) {
985                         return a->depth() > b->depth(); });
986
987         // Restack the items recursively
988         for (auto &o : sorted_owners)
989                 o->restack_items();
990
991         // Animate the items to their destination
992         for (const auto &i : items)
993                 i->animate_to_layout_v_offset();
994 }
995
996 int View::header_width() const
997 {
998          return header_->extended_size_hint().width();
999 }
1000
1001 void View::on_setting_changed(const QString &key, const QVariant &value)
1002 {
1003         if (key == GlobalSettings::Key_View_TriggerIsZeroTime)
1004                 on_settingViewTriggerIsZeroTime_changed(value);
1005
1006         if (key == GlobalSettings::Key_View_SnapDistance) {
1007                 GlobalSettings settings;
1008                 snap_distance_ = settings.value(GlobalSettings::Key_View_SnapDistance).toInt();
1009         }
1010 }
1011
1012 void View::trigger_event(int segment_id, util::Timestamp location)
1013 {
1014         // TODO This doesn't work if we're showing multiple segments at once
1015         if ((uint32_t)segment_id != current_segment_)
1016                 return;
1017
1018         // Set zero location if the Key_View_TriggerIsZeroTime setting is set and
1019         // if this is the first trigger for this segment.
1020         GlobalSettings settings;
1021         bool trigger_is_zero_time = settings.value(GlobalSettings::Key_View_TriggerIsZeroTime).toBool();
1022
1023         size_t trigger_count = session_.get_triggers(current_segment_).size();
1024
1025         if (trigger_is_zero_time && trigger_count == 1)
1026                 set_zero_position(location);
1027
1028         trigger_markers_.push_back(make_shared<TriggerMarker>(*this, location));
1029 }
1030
1031 void View::get_scroll_layout(double &length, Timestamp &offset) const
1032 {
1033         const pair<Timestamp, Timestamp> extents = get_time_extents();
1034         length = ((extents.second - extents.first) / scale_).convert_to<double>();
1035         offset = offset_ / scale_;
1036 }
1037
1038 void View::set_zoom(double scale, int offset)
1039 {
1040         // Reset the "always zoom to fit" feature as the user changed the zoom
1041         always_zoom_to_fit_ = false;
1042         always_zoom_to_fit_changed(false);
1043
1044         const Timestamp cursor_offset = offset_ + scale_ * offset;
1045         const Timestamp new_scale = max(min(Timestamp(scale), MaxScale), MinScale);
1046         const Timestamp new_offset = cursor_offset - new_scale * offset;
1047         set_scale_offset(new_scale.convert_to<double>(), new_offset);
1048 }
1049
1050 void View::calculate_tick_spacing()
1051 {
1052         const double SpacingIncrement = 10.0f;
1053         const double MinValueSpacing = 40.0f;
1054
1055         // Figure out the highest numeric value visible on a label
1056         const QSize areaSize = viewport_->size();
1057         const Timestamp max_time = max(fabs(offset_),
1058                 fabs(offset_ + scale_ * areaSize.width()));
1059
1060         double min_width = SpacingIncrement;
1061         double label_width, tick_period_width;
1062
1063         QFontMetrics m(QApplication::font());
1064
1065         // Copies of the member variables with the same name, used in the calculation
1066         // and written back afterwards, so that we don't emit signals all the time
1067         // during the calculation.
1068         pv::util::Timestamp tick_period = tick_period_;
1069         pv::util::SIPrefix tick_prefix = tick_prefix_;
1070         unsigned tick_precision = tick_precision_;
1071
1072         do {
1073                 const double min_period = scale_ * min_width;
1074
1075                 const int order = (int)floorf(log10f(min_period));
1076                 const pv::util::Timestamp order_decimal =
1077                         pow(pv::util::Timestamp(10), order);
1078
1079                 // Allow for a margin of error so that a scale unit of 1 can be used.
1080                 // Otherwise, for a SU of 1 the tick period will almost always be below
1081                 // the min_period by a small amount - and thus skipped in favor of 2.
1082                 // Note: margin assumes that SU[0] and SU[1] contain the smallest values
1083                 double tp_margin = (ScaleUnits[0] + ScaleUnits[1]) / 2.0;
1084                 double tp_with_margin;
1085                 unsigned int unit = 0;
1086
1087                 do {
1088                         tp_with_margin = order_decimal.convert_to<double>() *
1089                                 (ScaleUnits[unit++] + tp_margin);
1090                 } while (tp_with_margin < min_period && unit < countof(ScaleUnits));
1091
1092                 minor_tick_count_ = (unit == 2) ? 4 : 5;
1093                 tick_period = order_decimal * ScaleUnits[unit - 1];
1094                 tick_prefix = static_cast<pv::util::SIPrefix>(
1095                         (order - pv::util::exponent(pv::util::SIPrefix::yocto)) / 3);
1096
1097                 // Precision is the number of fractional digits required, not
1098                 // taking the prefix into account (and it must never be negative)
1099                 tick_precision = max(ceil(log10(1 / tick_period)).convert_to<int>(), 0);
1100
1101                 tick_period_width = (tick_period / scale_).convert_to<double>();
1102
1103                 const QString label_text = Ruler::format_time_with_distance(
1104                         tick_period, max_time, tick_prefix, time_unit_, tick_precision);
1105
1106                 label_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
1107                         Qt::AlignLeft | Qt::AlignTop, label_text).width() +
1108                                 MinValueSpacing;
1109
1110                 min_width += SpacingIncrement;
1111         } while (tick_period_width < label_width);
1112
1113         set_tick_period(tick_period);
1114         set_tick_prefix(tick_prefix);
1115         set_tick_precision(tick_precision);
1116 }
1117
1118 void View::adjust_top_margin()
1119 {
1120         assert(viewport_);
1121
1122         const QSize areaSize = viewport_->size();
1123
1124         const pair<int, int> extents = v_extents();
1125         const int top_margin = owner_visual_v_offset() + extents.first;
1126         const int trace_bottom = owner_visual_v_offset() + extents.first + extents.second;
1127
1128         // Do we have empty space at the top while the last trace goes out of screen?
1129         if ((top_margin > 0) && (trace_bottom > areaSize.height())) {
1130                 const int trace_height = extents.second - extents.first;
1131
1132                 // Center everything vertically if there is enough space
1133                 if (areaSize.height() >= trace_height)
1134                         set_v_offset(extents.first -
1135                                 ((areaSize.height() - trace_height) / 2));
1136                 else
1137                         // Remove the top margin to make as many traces fit on screen as possible
1138                         set_v_offset(extents.first);
1139         }
1140 }
1141
1142 void View::update_scroll()
1143 {
1144         assert(viewport_);
1145         QScrollBar *hscrollbar = scrollarea_->horizontalScrollBar();
1146         QScrollBar *vscrollbar = scrollarea_->verticalScrollBar();
1147
1148         const QSize areaSize = viewport_->size();
1149
1150         // Set the horizontal scroll bar
1151         double length = 0;
1152         Timestamp offset;
1153         get_scroll_layout(length, offset);
1154         length = max(length - areaSize.width(), 0.0);
1155
1156         int major_tick_distance = (tick_period_ / scale_).convert_to<int>();
1157
1158         hscrollbar->setPageStep(areaSize.width() / 2);
1159         hscrollbar->setSingleStep(major_tick_distance);
1160
1161         updating_scroll_ = true;
1162
1163         if (length < MaxScrollValue) {
1164                 hscrollbar->setRange(0, length);
1165                 hscrollbar->setSliderPosition(offset.convert_to<double>());
1166         } else {
1167                 hscrollbar->setRange(0, MaxScrollValue);
1168                 hscrollbar->setSliderPosition(
1169                         (offset_ * MaxScrollValue / (scale_ * length)).convert_to<double>());
1170         }
1171
1172         updating_scroll_ = false;
1173
1174         // Set the vertical scrollbar
1175         vscrollbar->setPageStep(areaSize.height());
1176         vscrollbar->setSingleStep(areaSize.height() / 8);
1177
1178         const pair<int, int> extents = v_extents();
1179
1180         // Don't change the scrollbar range if there are no traces
1181         if (extents.first != extents.second)
1182                 vscrollbar->setRange(extents.first - areaSize.height(),
1183                         extents.second);
1184
1185         if (scroll_needs_defaults_) {
1186                 set_scroll_default();
1187                 scroll_needs_defaults_ = false;
1188         }
1189 }
1190
1191 void View::reset_scroll()
1192 {
1193         scrollarea_->verticalScrollBar()->setRange(0, 0);
1194 }
1195
1196 void View::set_scroll_default()
1197 {
1198         assert(viewport_);
1199
1200         const QSize areaSize = viewport_->size();
1201
1202         const pair<int, int> extents = v_extents();
1203         const int trace_height = extents.second - extents.first;
1204
1205         // Do all traces fit in the view?
1206         if (areaSize.height() >= trace_height)
1207                 // Center all traces vertically
1208                 set_v_offset(extents.first -
1209                         ((areaSize.height() - trace_height) / 2));
1210         else
1211                 // Put the first trace at the top, letting the bottom ones overflow
1212                 set_v_offset(extents.first);
1213 }
1214
1215 void View::determine_if_header_was_shrunk()
1216 {
1217         const int header_pane_width =
1218                 splitter_->sizes().front();  // clazy:exclude=detaching-temporary
1219
1220         // Allow for a slight margin of error so that we also accept
1221         // slight differences when e.g. a label name change increased
1222         // the overall width
1223         header_was_shrunk_ = (header_pane_width < (header_width() - 10));
1224 }
1225
1226 void View::resize_header_to_fit()
1227 {
1228         // Setting the maximum width of the header widget doesn't work as
1229         // expected because the splitter would allow the user to make the
1230         // pane wider than that, creating empty space as a result.
1231         // To make this work, we stricly enforce the maximum width by
1232         // expanding the header unless the user shrunk it on purpose.
1233         // As we're then setting the width of the header pane, we set the
1234         // splitter to the maximum allowed position.
1235
1236         int splitter_area_width = 0;
1237         for (int w : splitter_->sizes())  // clazy:exclude=range-loop
1238                 splitter_area_width += w;
1239
1240         // Make sure the header has enough horizontal space to show all labels fully
1241         QList<int> pane_sizes;
1242         pane_sizes.push_back(header_->extended_size_hint().width());
1243         pane_sizes.push_back(splitter_area_width - header_->extended_size_hint().width());
1244         splitter_->setSizes(pane_sizes);
1245 }
1246
1247 void View::update_layout()
1248 {
1249         update_scroll();
1250 }
1251
1252 TraceTreeItemOwner* View::find_prevalent_trace_group(
1253         const shared_ptr<sigrok::ChannelGroup> &group,
1254         const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1255                 &signal_map)
1256 {
1257         assert(group);
1258
1259         unordered_set<TraceTreeItemOwner*> owners;
1260         vector<TraceTreeItemOwner*> owner_list;
1261
1262         // Make a set and a list of all the owners
1263         for (const auto& channel : group->channels()) {
1264                 for (auto& entry : signal_map) {
1265                         if (entry.first->channel() == channel) {
1266                                 TraceTreeItemOwner *const o = (entry.second)->owner();
1267                                 owner_list.push_back(o);
1268                                 owners.insert(o);
1269                         }
1270                 }
1271         }
1272
1273         // Iterate through the list of owners, and find the most prevalent
1274         size_t max_prevalence = 0;
1275         TraceTreeItemOwner *prevalent_owner = nullptr;
1276         for (TraceTreeItemOwner *owner : owners) {
1277                 const size_t prevalence = count_if(
1278                         owner_list.begin(), owner_list.end(),
1279                         [&](TraceTreeItemOwner *o) { return o == owner; });
1280                 if (prevalence > max_prevalence) {
1281                         max_prevalence = prevalence;
1282                         prevalent_owner = owner;
1283                 }
1284         }
1285
1286         return prevalent_owner;
1287 }
1288
1289 vector< shared_ptr<Trace> > View::extract_new_traces_for_channels(
1290         const vector< shared_ptr<sigrok::Channel> > &channels,
1291         const unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1292                 &signal_map,
1293         set< shared_ptr<Trace> > &add_list)
1294 {
1295         vector< shared_ptr<Trace> > filtered_traces;
1296
1297         for (const auto& channel : channels) {
1298                 for (auto& entry : signal_map) {
1299                         if (entry.first->channel() == channel) {
1300                                 shared_ptr<Trace> trace = entry.second;
1301                                 const auto list_iter = add_list.find(trace);
1302                                 if (list_iter == add_list.end())
1303                                         continue;
1304
1305                                 filtered_traces.push_back(trace);
1306                                 add_list.erase(list_iter);
1307                         }
1308                 }
1309         }
1310
1311         return filtered_traces;
1312 }
1313
1314 void View::determine_time_unit()
1315 {
1316         // Check whether we know the sample rate and hence can use time as the unit
1317         if (time_unit_ == util::TimeUnit::Samples) {
1318                 // Check all signals but...
1319                 for (const shared_ptr<Signal>& signal : signals_) {
1320                         const shared_ptr<SignalData> data = signal->data();
1321
1322                         // ...only check first segment of each
1323                         const vector< shared_ptr<Segment> > segments = data->segments();
1324                         if (!segments.empty())
1325                                 if (segments[0]->samplerate()) {
1326                                         set_time_unit(util::TimeUnit::Time);
1327                                         break;
1328                                 }
1329                 }
1330         }
1331 }
1332
1333 bool View::eventFilter(QObject *object, QEvent *event)
1334 {
1335         const QEvent::Type type = event->type();
1336         if (type == QEvent::MouseMove) {
1337
1338                 if (object)
1339                         hover_widget_ = qobject_cast<QWidget*>(object);
1340
1341                 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
1342                 if (object == viewport_)
1343                         hover_point_ = mouse_event->pos();
1344                 else if (object == ruler_)
1345                         hover_point_ = mouse_event->pos();
1346                 else if (object == header_)
1347                         hover_point_ = QPoint(0, mouse_event->y());
1348                 else
1349                         hover_point_ = QPoint(-1, -1);
1350
1351                 update_hover_point();
1352
1353         } else if (type == QEvent::Leave) {
1354                 hover_point_ = QPoint(-1, -1);
1355                 update_hover_point();
1356         } else if (type == QEvent::Show) {
1357
1358                 // This is somewhat of a hack, unfortunately. We cannot use
1359                 // set_v_offset() from within restore_settings() as the view
1360                 // at that point is neither visible nor properly sized.
1361                 // This is the least intrusive workaround I could come up
1362                 // with: set the vertical offset (or scroll defaults) when
1363                 // the view is shown, which happens after all widgets were
1364                 // resized to their final sizes.
1365                 update_layout();
1366
1367                 if (settings_restored_)
1368                         determine_if_header_was_shrunk();
1369                 else
1370                         resize_header_to_fit();
1371
1372                 if (scroll_needs_defaults_) {
1373                         set_scroll_default();
1374                         scroll_needs_defaults_ = false;
1375                 }
1376
1377                 if (saved_v_offset_) {
1378                         set_v_offset(saved_v_offset_);
1379                         saved_v_offset_ = 0;
1380                 }
1381         }
1382
1383         return QObject::eventFilter(object, event);
1384 }
1385
1386 void View::contextMenuEvent(QContextMenuEvent *event)
1387 {
1388         QPoint pos = event->pos() - QPoint(0, ruler_->sizeHint().height());
1389
1390         const shared_ptr<ViewItem> r = viewport_->get_mouse_over_item(pos);
1391         if (!r)
1392                 return;
1393
1394         QMenu *menu = r->create_view_context_menu(this, pos);
1395         if (menu)
1396                 menu->popup(event->globalPos());
1397 }
1398
1399 void View::resizeEvent(QResizeEvent* event)
1400 {
1401         // Only adjust the top margin if we shrunk vertically
1402         if (event->size().height() < event->oldSize().height())
1403                 adjust_top_margin();
1404
1405         update_layout();
1406 }
1407
1408 void View::update_hover_point()
1409 {
1410         // Determine signal that the mouse cursor is hovering over
1411         signal_under_mouse_cursor_.reset();
1412         if (hover_widget_ == this) {
1413                 for (const shared_ptr<Signal>& s : signals_) {
1414                         const pair<int, int> extents = s->v_extents();
1415                         const int top = s->get_visual_y() + extents.first;
1416                         const int btm = s->get_visual_y() + extents.second;
1417                         if ((hover_point_.y() >= top) && (hover_point_.y() <= btm)
1418                                 && s->base()->enabled())
1419                                 signal_under_mouse_cursor_ = s;
1420                 }
1421         }
1422
1423         // Update all trace tree items
1424         const vector<shared_ptr<TraceTreeItem>> trace_tree_items(
1425                 list_by_type<TraceTreeItem>());
1426         for (const shared_ptr<TraceTreeItem>& r : trace_tree_items)
1427                 r->hover_point_changed(hover_point_);
1428
1429         // Notify any other listeners
1430         hover_point_changed(hover_widget_, hover_point_);
1431 }
1432
1433 void View::row_item_appearance_changed(bool label, bool content)
1434 {
1435         if (label)
1436                 header_->update();
1437         if (content)
1438                 viewport_->update();
1439 }
1440
1441 void View::time_item_appearance_changed(bool label, bool content)
1442 {
1443         if (label) {
1444                 ruler_->update();
1445
1446                 // Make sure the header pane width is updated, too
1447                 update_layout();
1448         }
1449
1450         if (content)
1451                 viewport_->update();
1452 }
1453
1454 void View::extents_changed(bool horz, bool vert)
1455 {
1456         sticky_events_ |=
1457                 (horz ? TraceTreeItemHExtentsChanged : 0) |
1458                 (vert ? TraceTreeItemVExtentsChanged : 0);
1459
1460         lazy_event_handler_.stop();
1461         lazy_event_handler_.start();
1462 }
1463
1464 void View::on_signal_name_changed()
1465 {
1466         if (!header_was_shrunk_)
1467                 resize_header_to_fit();
1468 }
1469
1470 void View::on_splitter_moved()
1471 {
1472         // The header can only shrink when the splitter is moved manually
1473         determine_if_header_was_shrunk();
1474
1475         if (!header_was_shrunk_)
1476                 resize_header_to_fit();
1477 }
1478
1479 void View::h_scroll_value_changed(int value)
1480 {
1481         if (updating_scroll_)
1482                 return;
1483
1484         // Disable sticky scrolling when user moves the horizontal scroll bar
1485         // during a running acquisition
1486         if (sticky_scrolling_ && (session_.get_capture_state() == Session::Running)) {
1487                 sticky_scrolling_ = false;
1488                 sticky_scrolling_changed(false);
1489         }
1490
1491         const int range = scrollarea_->horizontalScrollBar()->maximum();
1492         if (range < MaxScrollValue)
1493                 set_offset(scale_ * value);
1494         else {
1495                 double length = 0;
1496                 Timestamp offset;
1497                 get_scroll_layout(length, offset);
1498                 set_offset(scale_ * length * value / MaxScrollValue);
1499         }
1500
1501         ruler_->update();
1502         viewport_->update();
1503 }
1504
1505 void View::v_scroll_value_changed()
1506 {
1507         header_->update();
1508         viewport_->update();
1509 }
1510
1511 void View::signals_changed()
1512 {
1513         using sigrok::Channel;
1514
1515         vector< shared_ptr<Channel> > channels;
1516         shared_ptr<sigrok::Device> sr_dev;
1517         bool signals_added_or_removed = false;
1518
1519         // Do we need to set the vertical scrollbar to its default position later?
1520         // We do if there are no traces, i.e. the scroll bar has no range set
1521         bool reset_scrollbar =
1522                 (scrollarea_->verticalScrollBar()->minimum() ==
1523                         scrollarea_->verticalScrollBar()->maximum());
1524
1525         if (!session_.device()) {
1526                 reset_scroll();
1527                 signals_.clear();
1528         } else {
1529                 sr_dev = session_.device()->device();
1530                 assert(sr_dev);
1531                 channels = sr_dev->channels();
1532         }
1533
1534         vector< shared_ptr<TraceTreeItem> > new_top_level_items;
1535
1536         // Make a list of traces that are being added, and a list of traces
1537         // that are being removed
1538         const vector<shared_ptr<Trace>> prev_trace_list = list_by_type<Trace>();
1539         const set<shared_ptr<Trace>> prev_traces(
1540                 prev_trace_list.begin(), prev_trace_list.end());
1541
1542         set< shared_ptr<Trace> > traces(signals_.begin(), signals_.end());
1543
1544 #ifdef ENABLE_DECODE
1545         traces.insert(decode_traces_.begin(), decode_traces_.end());
1546 #endif
1547
1548         set< shared_ptr<Trace> > add_traces;
1549         set_difference(traces.begin(), traces.end(),
1550                 prev_traces.begin(), prev_traces.end(),
1551                 inserter(add_traces, add_traces.begin()));
1552
1553         set< shared_ptr<Trace> > remove_traces;
1554         set_difference(prev_traces.begin(), prev_traces.end(),
1555                 traces.begin(), traces.end(),
1556                 inserter(remove_traces, remove_traces.begin()));
1557
1558         // Make a look-up table of sigrok Channels to pulseview Signals
1559         unordered_map<shared_ptr<data::SignalBase>, shared_ptr<Signal> >
1560                 signal_map;
1561         for (const shared_ptr<Signal>& sig : signals_)
1562                 signal_map[sig->base()] = sig;
1563
1564         // Populate channel groups
1565         if (sr_dev)
1566                 for (auto& entry : sr_dev->channel_groups()) {
1567                         const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
1568
1569                         if (group->channels().size() <= 1)
1570                                 continue;
1571
1572                         // Find best trace group to add to
1573                         TraceTreeItemOwner *owner = find_prevalent_trace_group(
1574                                 group, signal_map);
1575
1576                         // If there is no trace group, create one
1577                         shared_ptr<TraceGroup> new_trace_group;
1578                         if (!owner) {
1579                                 new_trace_group.reset(new TraceGroup());
1580                                 owner = new_trace_group.get();
1581                         }
1582
1583                         // Extract traces for the trace group, removing them from
1584                         // the add list
1585                         const vector< shared_ptr<Trace> > new_traces_in_group =
1586                                 extract_new_traces_for_channels(group->channels(),
1587                                         signal_map, add_traces);
1588
1589                         // Add the traces to the group
1590                         const pair<int, int> prev_v_extents = owner->v_extents();
1591                         int offset = prev_v_extents.second - prev_v_extents.first;
1592                         for (const shared_ptr<Trace>& trace : new_traces_in_group) {
1593                                 assert(trace);
1594                                 owner->add_child_item(trace);
1595
1596                                 const pair<int, int> extents = trace->v_extents();
1597                                 if (trace->enabled())
1598                                         offset += -extents.first;
1599                                 trace->force_to_v_offset(offset);
1600                                 if (trace->enabled())
1601                                         offset += extents.second;
1602                         }
1603
1604                         if (new_trace_group) {
1605                                 // Assign proper vertical offsets to each channel in the group
1606                                 new_trace_group->restack_items();
1607
1608                                 // If this is a new group, enqueue it in the new top level
1609                                 // items list
1610                                 if (!new_traces_in_group.empty())
1611                                         new_top_level_items.push_back(new_trace_group);
1612                         }
1613                 }
1614
1615         // Enqueue the remaining logic channels in a group
1616         vector< shared_ptr<Channel> > logic_channels;
1617         copy_if(channels.begin(), channels.end(), back_inserter(logic_channels),
1618                 [](const shared_ptr<Channel>& c) {
1619                         return c->type() == sigrok::ChannelType::LOGIC; });
1620
1621         const vector< shared_ptr<Trace> > non_grouped_logic_signals =
1622                 extract_new_traces_for_channels(logic_channels, signal_map, add_traces);
1623
1624         if (non_grouped_logic_signals.size() > 0) {
1625                 const shared_ptr<TraceGroup> non_grouped_trace_group(
1626                         make_shared<TraceGroup>());
1627                 for (const shared_ptr<Trace>& trace : non_grouped_logic_signals)
1628                         non_grouped_trace_group->add_child_item(trace);
1629
1630                 non_grouped_trace_group->restack_items();
1631                 new_top_level_items.push_back(non_grouped_trace_group);
1632         }
1633
1634         // Enqueue the remaining channels as free ungrouped traces
1635         const vector< shared_ptr<Trace> > new_top_level_signals =
1636                 extract_new_traces_for_channels(channels, signal_map, add_traces);
1637         new_top_level_items.insert(new_top_level_items.end(),
1638                 new_top_level_signals.begin(), new_top_level_signals.end());
1639
1640         // Enqueue any remaining traces i.e. decode traces
1641         new_top_level_items.insert(new_top_level_items.end(),
1642                 add_traces.begin(), add_traces.end());
1643
1644         // Remove any removed traces
1645         for (const shared_ptr<Trace>& trace : remove_traces) {
1646                 TraceTreeItemOwner *const owner = trace->owner();
1647                 assert(owner);
1648                 owner->remove_child_item(trace);
1649                 signals_added_or_removed = true;
1650         }
1651
1652         // Remove any empty trace groups
1653         for (shared_ptr<TraceGroup> group : list_by_type<TraceGroup>())
1654                 if (group->child_items().size() == 0) {
1655                         remove_child_item(group);
1656                         group.reset();
1657                 }
1658
1659         // Add and position the pending top levels items
1660         int offset = v_extents().second;
1661         for (auto item : new_top_level_items) {
1662                 add_child_item(item);
1663
1664                 // Position the item after the last item or at the top if there is none
1665                 const pair<int, int> extents = item->v_extents();
1666
1667                 if (item->enabled())
1668                         offset += -extents.first;
1669
1670                 item->force_to_v_offset(offset);
1671
1672                 if (item->enabled())
1673                         offset += extents.second;
1674                 signals_added_or_removed = true;
1675         }
1676
1677
1678         if (signals_added_or_removed && !header_was_shrunk_)
1679                 resize_header_to_fit();
1680
1681         update_layout();
1682
1683         header_->update();
1684         viewport_->update();
1685
1686         if (reset_scrollbar)
1687                 set_scroll_default();
1688 }
1689
1690 void View::capture_state_updated(int state)
1691 {
1692         GlobalSettings settings;
1693
1694         if (state == Session::Running) {
1695                 set_time_unit(util::TimeUnit::Samples);
1696
1697                 trigger_markers_.clear();
1698                 set_zero_position(0);
1699
1700                 scale_at_acq_start_ = scale_;
1701                 offset_at_acq_start_ = offset_;
1702
1703                 // Activate "always zoom to fit" if the setting is enabled and we're
1704                 // the main view of this session (other trace views may be used for
1705                 // zooming and we don't want to mess them up)
1706                 bool state = settings.value(GlobalSettings::Key_View_ZoomToFitDuringAcq).toBool();
1707                 if (is_main_view_ && state) {
1708                         always_zoom_to_fit_ = true;
1709                         always_zoom_to_fit_changed(always_zoom_to_fit_);
1710                 }
1711
1712                 // Enable sticky scrolling if the setting is enabled
1713                 sticky_scrolling_ = settings.value(GlobalSettings::Key_View_StickyScrolling).toBool();
1714
1715                 // Reset all traces to segment 0
1716                 current_segment_ = 0;
1717                 set_current_segment(current_segment_);
1718         }
1719
1720         if (state == Session::Stopped) {
1721                 // After acquisition has stopped we need to re-calculate the ticks once
1722                 // as it's otherwise done when the user pans or zooms, which is too late
1723                 calculate_tick_spacing();
1724
1725                 // Reset "always zoom to fit", the acquisition has stopped
1726                 if (always_zoom_to_fit_) {
1727                         // Perform a final zoom-to-fit before disabling
1728                         zoom_fit(always_zoom_to_fit_);
1729                         always_zoom_to_fit_ = false;
1730                         always_zoom_to_fit_changed(always_zoom_to_fit_);
1731                 }
1732
1733                 bool zoom_to_fit_after_acq =
1734                         settings.value(GlobalSettings::Key_View_ZoomToFitAfterAcq).toBool();
1735
1736                 // Only perform zoom-to-fit if the user hasn't altered the viewport and
1737                 // we didn't restore settings in the meanwhile
1738                 if (zoom_to_fit_after_acq &&
1739                         !suppress_zoom_to_fit_after_acq_ &&
1740                         (scale_ == scale_at_acq_start_) &&
1741                         (offset_ == offset_at_acq_start_))
1742                         zoom_fit(false);  // We're stopped, so the GUI state doesn't matter
1743
1744                 suppress_zoom_to_fit_after_acq_ = false;
1745         }
1746 }
1747
1748 void View::on_new_segment(int new_segment_id)
1749 {
1750         on_segment_changed(new_segment_id);
1751 }
1752
1753 void View::on_segment_completed(int segment_id)
1754 {
1755         on_segment_changed(segment_id);
1756 }
1757
1758 void View::on_segment_changed(int segment)
1759 {
1760         switch (segment_display_mode_) {
1761         case Trace::ShowLastSegmentOnly:
1762         case Trace::ShowSingleSegmentOnly:
1763                 set_current_segment(segment);
1764                 break;
1765
1766         case Trace::ShowLastCompleteSegmentOnly:
1767                 // Only update if all segments are complete
1768                 if (session_.all_segments_complete(segment))
1769                         set_current_segment(segment);
1770                 break;
1771
1772         case Trace::ShowAllSegments:
1773         case Trace::ShowAccumulatedIntensity:
1774         default:
1775                 break;
1776         }
1777 }
1778
1779 void View::on_settingViewTriggerIsZeroTime_changed(const QVariant new_value)
1780 {
1781         if (new_value.toBool()) {
1782                 // The first trigger for this segment is used as the zero position
1783                 vector<util::Timestamp> triggers = session_.get_triggers(current_segment_);
1784                 if (triggers.size() > 0)
1785                         set_zero_position(triggers.front());
1786         } else
1787                 reset_zero_position();
1788 }
1789
1790 void View::perform_delayed_view_update()
1791 {
1792         if (always_zoom_to_fit_) {
1793                 zoom_fit(true);
1794         } else if (sticky_scrolling_) {
1795                 // Make right side of the view sticky
1796                 double length = 0;
1797                 Timestamp offset;
1798                 get_scroll_layout(length, offset);
1799
1800                 const QSize areaSize = viewport_->size();
1801                 length = max(length - areaSize.width(), 0.0);
1802
1803                 set_offset(scale_ * length);
1804         }
1805
1806         determine_time_unit();
1807         update_scroll();
1808         ruler_->update();
1809         viewport_->update();
1810 }
1811
1812 void View::process_sticky_events()
1813 {
1814         if (sticky_events_ & TraceTreeItemHExtentsChanged)
1815                 update_layout();
1816         if (sticky_events_ & TraceTreeItemVExtentsChanged) {
1817                 restack_all_trace_tree_items();
1818                 update_scroll();
1819         }
1820
1821         // Clear the sticky events
1822         sticky_events_ = 0;
1823 }
1824
1825 } // namespace trace
1826 } // namespace views
1827 } // namespace pv