]> sigrok.org Git - pulseview.git/blob - pv/view/view.cpp
TimeMarker: Fixed position of set_time function
[pulseview.git] / pv / view / 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, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #ifdef ENABLE_DECODE
22 #include <libsigrokdecode/libsigrokdecode.h>
23 #endif
24
25 #include <extdef.h>
26
27 #include <cassert>
28 #include <climits>
29 #include <cmath>
30 #include <mutex>
31 #include <unordered_set>
32
33 #include <QApplication>
34 #include <QEvent>
35 #include <QFontMetrics>
36 #include <QMouseEvent>
37 #include <QScrollBar>
38
39 #include <libsigrok/libsigrok.hpp>
40
41 #include "cursorheader.hpp"
42 #include "decodetrace.hpp"
43 #include "header.hpp"
44 #include "logicsignal.hpp"
45 #include "ruler.hpp"
46 #include "signal.hpp"
47 #include "tracegroup.hpp"
48 #include "view.hpp"
49 #include "viewport.hpp"
50
51 #include "pv/session.hpp"
52 #include "pv/data/logic.hpp"
53 #include "pv/data/logicsegment.hpp"
54 #include "pv/util.hpp"
55
56 using boost::shared_lock;
57 using boost::shared_mutex;
58
59 using pv::data::SignalData;
60 using pv::data::Segment;
61 using pv::util::format_time;
62
63 using std::back_inserter;
64 using std::deque;
65 using std::dynamic_pointer_cast;
66 using std::list;
67 using std::lock_guard;
68 using std::max;
69 using std::make_pair;
70 using std::min;
71 using std::pair;
72 using std::set;
73 using std::shared_ptr;
74 using std::unordered_map;
75 using std::unordered_set;
76 using std::vector;
77 using std::weak_ptr;
78
79 namespace pv {
80 namespace view {
81
82 const double View::MaxScale = 1e9;
83 const double View::MinScale = 1e-15;
84
85 const int View::MaxScrollValue = INT_MAX / 2;
86
87 const int View::ScaleUnits[3] = {1, 2, 5};
88
89 const QColor View::CursorAreaColour(220, 231, 243);
90
91 const QSizeF View::LabelPadding(4, 0);
92
93 View::View(Session &session, QWidget *parent) :
94         QAbstractScrollArea(parent),
95         session_(session),
96         viewport_(new Viewport(*this)),
97         ruler_(new Ruler(*this)),
98         cursorheader_(new CursorHeader(*this)),
99         header_(new Header(*this)),
100         scale_(1e-6),
101         offset_(0),
102         v_offset_(0),
103         updating_scroll_(false),
104         tick_period_(0.0),
105         tick_prefix_(0),
106         show_cursors_(false),
107         cursors_(new CursorPair(*this)),
108         hover_point_(-1, -1)
109 {
110         connect(horizontalScrollBar(), SIGNAL(valueChanged(int)),
111                 this, SLOT(h_scroll_value_changed(int)));
112         connect(verticalScrollBar(), SIGNAL(valueChanged(int)),
113                 this, SLOT(v_scroll_value_changed(int)));
114
115         connect(&session_, SIGNAL(signals_changed()),
116                 this, SLOT(signals_changed()));
117         connect(&session_, SIGNAL(capture_state_changed(int)),
118                 this, SLOT(data_updated()));
119         connect(&session_, SIGNAL(data_received()),
120                 this, SLOT(data_updated()));
121         connect(&session_, SIGNAL(frame_ended()),
122                 this, SLOT(data_updated()));
123
124         connect(cursors_->first().get(), SIGNAL(time_changed()),
125                 this, SLOT(marker_time_changed()));
126         connect(cursors_->second().get(), SIGNAL(time_changed()),
127                 this, SLOT(marker_time_changed()));
128
129         connect(header_, SIGNAL(signals_moved()),
130                 this, SLOT(on_signals_moved()));
131
132         connect(header_, SIGNAL(selection_changed()),
133                 cursorheader_, SLOT(clear_selection()));
134         connect(cursorheader_, SIGNAL(selection_changed()),
135                 header_, SLOT(clear_selection()));
136
137         connect(header_, SIGNAL(selection_changed()),
138                 this, SIGNAL(selection_changed()));
139         connect(cursorheader_, SIGNAL(selection_changed()),
140                 this, SIGNAL(selection_changed()));
141
142         connect(this, SIGNAL(hover_point_changed()),
143                 this, SLOT(on_hover_point_changed()));
144
145         connect(&lazy_event_handler_, SIGNAL(timeout()),
146                 this, SLOT(process_sticky_events()));
147         lazy_event_handler_.setSingleShot(true);
148
149         setViewport(viewport_);
150
151         viewport_->installEventFilter(this);
152         ruler_->installEventFilter(this);
153         cursorheader_->installEventFilter(this);
154         header_->installEventFilter(this);
155
156         // Trigger the initial event manually. The default device has signals
157         // which were created before this object came into being
158         signals_changed();
159
160         // make sure the transparent widgets are on the top
161         cursorheader_->raise();
162         header_->raise();
163
164         // Update the zoom state
165         calculate_tick_spacing();
166 }
167
168 Session& View::session()
169 {
170         return session_;
171 }
172
173 const Session& View::session() const
174 {
175         return session_;
176 }
177
178 View* View::view()
179 {
180         return this;
181 }
182
183 const View* View::view() const
184 {
185         return this;
186 }
187
188 Viewport* View::viewport()
189 {
190         return viewport_;
191 }
192
193 const Viewport* View::viewport() const
194 {
195         return viewport_;
196 }
197
198 vector< shared_ptr<TimeItem> > View::time_items() const
199 {
200         vector< shared_ptr<TimeItem> > items;
201         items.push_back(cursors_);
202         items.push_back(cursors_->first());
203         items.push_back(cursors_->second());
204         return items;
205 }
206
207 double View::scale() const
208 {
209         return scale_;
210 }
211
212 double View::offset() const
213 {
214         return offset_;
215 }
216
217 int View::owner_visual_v_offset() const
218 {
219         return -v_offset_;
220 }
221
222 unsigned int View::depth() const
223 {
224         return 0;
225 }
226
227 unsigned int View::tick_prefix() const
228 {
229         return tick_prefix_;
230 }
231
232 double View::tick_period() const
233 {
234         return tick_period_;
235 }
236
237 void View::zoom(double steps)
238 {
239         zoom(steps, viewport_->width() / 2);
240 }
241
242 void View::zoom(double steps, int offset)
243 {
244         set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
245 }
246
247 void View::zoom_fit()
248 {
249         const pair<double, double> extents = get_time_extents();
250         const double delta = extents.second - extents.first;
251         if (delta < 1e-12)
252                 return;
253
254         assert(viewport_);
255         const int w = viewport_->width();
256         if (w <= 0)
257                 return;
258
259         const double scale = max(min(delta / w, MaxScale), MinScale);
260         set_scale_offset(scale, extents.first);
261 }
262
263 void View::zoom_one_to_one()
264 {
265         using pv::data::SignalData;
266
267         // Make a set of all the visible data objects
268         set< shared_ptr<SignalData> > visible_data = get_visible_data();
269         if (visible_data.empty())
270                 return;
271
272         double samplerate = 0.0;
273         for (const shared_ptr<SignalData> d : visible_data) {
274                 assert(d);
275                 const vector< shared_ptr<Segment> > segments =
276                         d->segments();
277                 for (const shared_ptr<Segment> &s : segments)
278                         samplerate = max(samplerate, s->samplerate());
279         }
280
281         if (samplerate == 0.0)
282                 return;
283
284         assert(viewport_);
285         const int w = viewport_->width();
286         if (w <= 0)
287                 return;
288
289         set_zoom(1.0 / samplerate, w / 2);
290 }
291
292 void View::set_scale_offset(double scale, double offset)
293 {
294         scale_ = scale;
295         offset_ = offset;
296
297         calculate_tick_spacing();
298
299         update_scroll();
300         ruler_->update();
301         cursorheader_->update();
302         viewport_->update();
303         scale_offset_changed();
304 }
305
306 set< shared_ptr<SignalData> > View::get_visible_data() const
307 {
308         shared_lock<shared_mutex> lock(session().signals_mutex());
309         const vector< shared_ptr<Signal> > &sigs(session().signals());
310
311         // Make a set of all the visible data objects
312         set< shared_ptr<SignalData> > visible_data;
313         for (const shared_ptr<Signal> sig : sigs)
314                 if (sig->enabled())
315                         visible_data.insert(sig->data());
316
317         return visible_data;
318 }
319
320 pair<double, double> View::get_time_extents() const
321 {
322         double left_time = DBL_MAX, right_time = DBL_MIN;
323         const set< shared_ptr<SignalData> > visible_data = get_visible_data();
324         for (const shared_ptr<SignalData> d : visible_data)
325         {
326                 const vector< shared_ptr<Segment> > segments =
327                         d->segments();
328                 for (const shared_ptr<Segment> &s : segments) {
329                         double samplerate = s->samplerate();
330                         samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
331
332                         const double start_time = s->start_time();
333                         left_time = min(left_time, start_time);
334                         right_time = max(right_time, start_time +
335                                 d->get_max_sample_count() / samplerate);
336                 }
337         }
338
339         if (left_time == DBL_MAX && right_time == DBL_MIN)
340                 return make_pair(0.0, 0.0);
341
342         assert(left_time < right_time);
343         return make_pair(left_time, right_time);
344 }
345
346 bool View::cursors_shown() const
347 {
348         return show_cursors_;
349 }
350
351 void View::show_cursors(bool show)
352 {
353         show_cursors_ = show;
354         cursorheader_->update();
355         viewport_->update();
356 }
357
358 void View::centre_cursors()
359 {
360         const double time_width = scale_ * viewport_->width();
361         cursors_->first()->set_time(offset_ + time_width * 0.4);
362         cursors_->second()->set_time(offset_ + time_width * 0.6);
363         cursorheader_->update();
364         viewport_->update();
365 }
366
367 std::shared_ptr<CursorPair> View::cursors() const
368 {
369         return cursors_;
370 }
371
372 const QPoint& View::hover_point() const
373 {
374         return hover_point_;
375 }
376
377 void View::update_viewport()
378 {
379         assert(viewport_);
380         viewport_->update();
381         header_->update();
382 }
383
384 void View::restack_all_row_items()
385 {
386         // Make a set of owners
387         unordered_set< RowItemOwner* > owners;
388         for (const auto &r : *this)
389                 owners.insert(r->owner());
390
391         // Make a list that is sorted from deepest first
392         vector< RowItemOwner* > sorted_owners(owners.begin(), owners.end());
393         sort(sorted_owners.begin(), sorted_owners.end(),
394                 [](const RowItemOwner* a, const RowItemOwner *b) {
395                         return a->depth() > b->depth(); });
396
397         // Restack the items recursively
398         for (auto &o : sorted_owners)
399                 o->restack_items();
400
401         // Animate the items to their destination
402         for (const auto &r : *this)
403                 r->animate_to_layout_v_offset();
404 }
405
406 void View::get_scroll_layout(double &length, double &offset) const
407 {
408         const pair<double, double> extents = get_time_extents();
409         length = (extents.second - extents.first) / scale_;
410         offset = offset_ / scale_;
411 }
412
413 void View::set_zoom(double scale, int offset)
414 {
415         const double cursor_offset = offset_ + scale_ * offset;
416         const double new_scale = max(min(scale, MaxScale), MinScale);
417         const double new_offset = cursor_offset - new_scale * offset;
418         set_scale_offset(new_scale, new_offset);
419 }
420
421 void View::calculate_tick_spacing()
422 {
423         const double SpacingIncrement = 32.0f;
424         const double MinValueSpacing = 32.0f;
425
426         double min_width = SpacingIncrement, typical_width;
427
428         QFontMetrics m(QApplication::font());
429
430         do {
431                 const double min_period = scale_ * min_width;
432
433                 const int order = (int)floorf(log10f(min_period));
434                 const double order_decimal = pow(10.0, order);
435
436                 unsigned int unit = 0;
437
438                 do {
439                         tick_period_ = order_decimal * ScaleUnits[unit++];
440                 } while (tick_period_ < min_period &&
441                         unit < countof(ScaleUnits));
442
443                 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
444
445                 typical_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
446                         Qt::AlignLeft | Qt::AlignTop,
447                         format_time(offset_, tick_prefix_)).width() +
448                                 MinValueSpacing;
449
450                 min_width += SpacingIncrement;
451
452         } while(typical_width > tick_period_ / scale_);
453 }
454
455 void View::update_scroll()
456 {
457         assert(viewport_);
458
459         const QSize areaSize = viewport_->size();
460
461         // Set the horizontal scroll bar
462         double length = 0, offset = 0;
463         get_scroll_layout(length, offset);
464         length = max(length - areaSize.width(), 0.0);
465
466         int major_tick_distance = tick_period_ / scale_;
467
468         horizontalScrollBar()->setPageStep(areaSize.width() / 2);
469         horizontalScrollBar()->setSingleStep(major_tick_distance);
470
471         updating_scroll_ = true;
472
473         if (length < MaxScrollValue) {
474                 horizontalScrollBar()->setRange(0, length);
475                 horizontalScrollBar()->setSliderPosition(offset);
476         } else {
477                 horizontalScrollBar()->setRange(0, MaxScrollValue);
478                 horizontalScrollBar()->setSliderPosition(
479                         offset_ * MaxScrollValue / (scale_ * length));
480         }
481
482         updating_scroll_ = false;
483
484         // Set the vertical scrollbar
485         verticalScrollBar()->setPageStep(areaSize.height());
486         verticalScrollBar()->setSingleStep(areaSize.height() / 8);
487
488         const pair<int, int> extents = v_extents();
489         verticalScrollBar()->setRange(extents.first - (areaSize.height() / 2),
490                 extents.second - (areaSize.height() / 2));
491 }
492
493 void View::update_layout()
494 {
495         setViewportMargins(
496                 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
497                 ruler_->sizeHint().height(), 0, 0);
498         ruler_->setGeometry(viewport_->x(), 0,
499                 viewport_->width(), viewport_->y());
500         cursorheader_->setGeometry(
501                 viewport_->x(),
502                 ruler_->sizeHint().height() - cursorheader_->sizeHint().height() / 2,
503                 viewport_->width(), cursorheader_->sizeHint().height());
504         header_->setGeometry(0, viewport_->y(),
505                 header_->sizeHint().width(), viewport_->height());
506         update_scroll();
507 }
508
509 void View::paint_label(QPainter &p, const QRect &rect, bool hover)
510 {
511         (void)p;
512         (void)rect;
513         (void)hover;
514 }
515
516 QRectF View::label_rect(const QRectF &rect)
517 {
518         (void)rect;
519         return QRectF();
520 }
521
522 bool View::add_channels_to_owner(
523         const vector< shared_ptr<sigrok::Channel> > &channels,
524         RowItemOwner *owner, int &offset,
525         unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
526                 &signal_map,
527         std::function<bool (shared_ptr<RowItem>)> filter_func)
528 {
529         bool any_added = false;
530
531         assert(owner);
532
533         for (const auto &channel : channels)
534         {
535                 const auto iter = signal_map.find(channel);
536                 if (iter == signal_map.end() ||
537                         (filter_func && !filter_func((*iter).second)))
538                         continue;
539
540                 shared_ptr<RowItem> row_item = (*iter).second;
541                 owner->add_child_item(row_item);
542                 apply_offset(row_item, offset);
543                 signal_map.erase(iter);
544
545                 any_added = true;
546         }
547
548         return any_added;
549 }
550
551 void View::apply_offset(shared_ptr<RowItem> row_item, int &offset) {
552         assert(row_item);
553         const pair<int, int> extents = row_item->v_extents();
554         if (row_item->enabled())
555                 offset += -extents.first;
556         row_item->force_to_v_offset(offset);
557         if (row_item->enabled())
558                 offset += extents.second;
559 }
560
561 bool View::eventFilter(QObject *object, QEvent *event)
562 {
563         const QEvent::Type type = event->type();
564         if (type == QEvent::MouseMove) {
565
566                 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
567                 if (object == viewport_)
568                         hover_point_ = mouse_event->pos();
569                 else if (object == ruler_ || object == cursorheader_)
570                         hover_point_ = QPoint(mouse_event->x(), 0);
571                 else if (object == header_)
572                         hover_point_ = QPoint(0, mouse_event->y());
573                 else
574                         hover_point_ = QPoint(-1, -1);
575
576                 hover_point_changed();
577
578         } else if (type == QEvent::Leave) {
579                 hover_point_ = QPoint(-1, -1);
580                 hover_point_changed();
581         }
582
583         return QObject::eventFilter(object, event);
584 }
585
586 bool View::viewportEvent(QEvent *e)
587 {
588         switch(e->type()) {
589         case QEvent::Paint:
590         case QEvent::MouseButtonPress:
591         case QEvent::MouseButtonRelease:
592         case QEvent::MouseButtonDblClick:
593         case QEvent::MouseMove:
594         case QEvent::Wheel:
595         case QEvent::TouchBegin:
596         case QEvent::TouchUpdate:
597         case QEvent::TouchEnd:
598                 return false;
599
600         default:
601                 return QAbstractScrollArea::viewportEvent(e);
602         }
603 }
604
605 void View::resizeEvent(QResizeEvent*)
606 {
607         update_layout();
608 }
609
610 void View::row_item_appearance_changed(bool label, bool content)
611 {
612         if (label)
613                 header_->update();
614         if (content)
615                 viewport_->update();
616 }
617
618 void View::extents_changed(bool horz, bool vert)
619 {
620         sticky_events_ |=
621                 (horz ? RowItemHExtentsChanged : 0) |
622                 (vert ? RowItemVExtentsChanged : 0);
623         lazy_event_handler_.start();
624 }
625
626 void View::h_scroll_value_changed(int value)
627 {
628         if (updating_scroll_)
629                 return;
630
631         const int range = horizontalScrollBar()->maximum();
632         if (range < MaxScrollValue)
633                 offset_ = scale_ * value;
634         else {
635                 double length = 0, offset;
636                 get_scroll_layout(length, offset);
637                 offset_ = scale_ * length * value / MaxScrollValue;
638         }
639
640         ruler_->update();
641         cursorheader_->update();
642         viewport_->update();
643 }
644
645 void View::v_scroll_value_changed(int value)
646 {
647         v_offset_ = value;
648         header_->update();
649         viewport_->update();
650 }
651
652 void View::signals_changed()
653 {
654         int offset = 0;
655
656         // Populate the traces
657         clear_child_items();
658
659         shared_ptr<sigrok::Device> device = session_.device();
660         assert(device);
661
662         // Collect a set of signals
663         unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
664                 signal_map;
665
666         shared_lock<shared_mutex> lock(session_.signals_mutex());
667         const vector< shared_ptr<Signal> > &sigs(session_.signals());
668
669         for (const shared_ptr<Signal> &sig : sigs)
670                 signal_map[sig->channel()] = sig;
671
672         // Populate channel groups
673         for (auto entry : device->channel_groups())
674         {
675                 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
676
677                 if (group->channels().size() <= 1)
678                         continue;
679
680                 shared_ptr<TraceGroup> trace_group(new TraceGroup());
681                 int child_offset = 0;
682                 if (add_channels_to_owner(group->channels(),
683                         trace_group.get(), child_offset, signal_map))
684                 {
685                         add_child_item(trace_group);
686                         apply_offset(trace_group, offset);
687                 }
688         }
689
690         // Add the remaining logic channels
691         shared_ptr<TraceGroup> logic_trace_group(new TraceGroup());
692         int child_offset = 0;
693
694         if (add_channels_to_owner(device->channels(),
695                 logic_trace_group.get(), child_offset, signal_map,
696                 [](shared_ptr<RowItem> r) -> bool {
697                         return dynamic_pointer_cast<LogicSignal>(r) != nullptr;
698                         }))
699
700         {
701                 add_child_item(logic_trace_group);
702                 apply_offset(logic_trace_group, offset);
703         }
704
705         // Add the remaining channels
706         add_channels_to_owner(device->channels(), this, offset, signal_map);
707         assert(signal_map.empty());
708
709         // Add decode signals
710 #ifdef ENABLE_DECODE
711         const vector< shared_ptr<DecodeTrace> > decode_sigs(
712                 session().get_decode_signals());
713         for (auto s : decode_sigs) {
714                 add_child_item(s);
715                 apply_offset(s, offset);
716         }
717 #endif
718
719         update_layout();
720 }
721
722 void View::data_updated()
723 {
724         // Update the scroll bars
725         update_scroll();
726
727         // Repaint the view
728         viewport_->update();
729 }
730
731 void View::marker_time_changed()
732 {
733         cursorheader_->update();
734         viewport_->update();
735 }
736
737 void View::on_signals_moved()
738 {
739         update_scroll();
740         signals_moved();
741 }
742
743 void View::process_sticky_events()
744 {
745         if (sticky_events_ & RowItemHExtentsChanged)
746                 update_layout();
747         if (sticky_events_ & RowItemVExtentsChanged)
748                 restack_all_row_items();
749
750         // Clear the sticky events
751         sticky_events_ = 0;
752 }
753
754 void View::on_hover_point_changed()
755 {
756         for (shared_ptr<RowItem> r : *this)
757                 r->hover_point_changed();
758 }
759
760 } // namespace view
761 } // namespace pv