]> sigrok.org Git - pulseview.git/blob - pv/view/view.cpp
aac6333addd032c0adb85886c60f2fdf9b48a248
[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/logicsnapshot.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::Snapshot;
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_(*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 double View::scale() const
199 {
200         return scale_;
201 }
202
203 double View::offset() const
204 {
205         return offset_;
206 }
207
208 int View::owner_visual_v_offset() const
209 {
210         return -v_offset_;
211 }
212
213 unsigned int View::depth() const
214 {
215         return 0;
216 }
217
218 unsigned int View::tick_prefix() const
219 {
220         return tick_prefix_;
221 }
222
223 double View::tick_period() const
224 {
225         return tick_period_;
226 }
227
228 void View::zoom(double steps)
229 {
230         zoom(steps, viewport_->width() / 2);
231 }
232
233 void View::zoom(double steps, int offset)
234 {
235         set_zoom(scale_ * pow(3.0/2.0, -steps), offset);
236 }
237
238 void View::zoom_fit()
239 {
240         const pair<double, double> extents = get_time_extents();
241         const double delta = extents.second - extents.first;
242         if (delta < 1e-12)
243                 return;
244
245         assert(viewport_);
246         const int w = viewport_->width();
247         if (w <= 0)
248                 return;
249
250         const double scale = max(min(delta / w, MaxScale), MinScale);
251         set_scale_offset(scale, extents.first);
252 }
253
254 void View::zoom_one_to_one()
255 {
256         using pv::data::SignalData;
257
258         // Make a set of all the visible data objects
259         set< shared_ptr<SignalData> > visible_data = get_visible_data();
260         if (visible_data.empty())
261                 return;
262
263         double samplerate = 0.0;
264         for (const shared_ptr<SignalData> d : visible_data) {
265                 assert(d);
266                 samplerate = max(samplerate, d->samplerate());
267         }
268
269         if (samplerate == 0.0)
270                 return;
271
272         assert(viewport_);
273         const int w = viewport_->width();
274         if (w <= 0)
275                 return;
276
277         set_zoom(1.0 / samplerate, w / 2);
278 }
279
280 void View::set_scale_offset(double scale, double offset)
281 {
282         scale_ = scale;
283         offset_ = offset;
284
285         calculate_tick_spacing();
286
287         update_scroll();
288         ruler_->update();
289         cursorheader_->update();
290         viewport_->update();
291         scale_offset_changed();
292 }
293
294 set< shared_ptr<SignalData> > View::get_visible_data() const
295 {
296         shared_lock<shared_mutex> lock(session().signals_mutex());
297         const vector< shared_ptr<Signal> > &sigs(session().signals());
298
299         // Make a set of all the visible data objects
300         set< shared_ptr<SignalData> > visible_data;
301         for (const shared_ptr<Signal> sig : sigs)
302                 if (sig->enabled())
303                         visible_data.insert(sig->data());
304
305         return visible_data;
306 }
307
308 pair<double, double> View::get_time_extents() const
309 {
310         double left_time = DBL_MAX, right_time = DBL_MIN;
311         const set< shared_ptr<SignalData> > visible_data = get_visible_data();
312         for (const shared_ptr<SignalData> d : visible_data)
313         {
314                 double samplerate = d->samplerate();
315                 samplerate = (samplerate <= 0.0) ? 1.0 : samplerate;
316
317                 const vector< shared_ptr<Snapshot> > snapshots =
318                         d->snapshots();
319                 for (const shared_ptr<Snapshot> &s : snapshots) {
320                         const double start_time = s->start_time();
321                         left_time = min(left_time, start_time);
322                         right_time = max(right_time, start_time +
323                                 d->get_max_sample_count() / samplerate);
324                 }
325         }
326
327         if (left_time == DBL_MAX && right_time == DBL_MIN)
328                 return make_pair(0.0, 0.0);
329
330         assert(left_time < right_time);
331         return make_pair(left_time, right_time);
332 }
333
334 bool View::cursors_shown() const
335 {
336         return show_cursors_;
337 }
338
339 void View::show_cursors(bool show)
340 {
341         show_cursors_ = show;
342         cursorheader_->update();
343         viewport_->update();
344 }
345
346 void View::centre_cursors()
347 {
348         const double time_width = scale_ * viewport_->width();
349         cursors_.first()->set_time(offset_ + time_width * 0.4);
350         cursors_.second()->set_time(offset_ + time_width * 0.6);
351         cursorheader_->update();
352         viewport_->update();
353 }
354
355 CursorPair& View::cursors()
356 {
357         return cursors_;
358 }
359
360 const CursorPair& View::cursors() const
361 {
362         return cursors_;
363 }
364
365 const QPoint& View::hover_point() const
366 {
367         return hover_point_;
368 }
369
370 void View::update_viewport()
371 {
372         assert(viewport_);
373         viewport_->update();
374         header_->update();
375 }
376
377 void View::restack_all_row_items()
378 {
379         // Make a set of owners
380         unordered_set< RowItemOwner* > owners;
381         for (const auto &r : *this)
382                 owners.insert(r->owner());
383
384         // Make a list that is sorted from deepest first
385         vector< RowItemOwner* > sorted_owners(owners.begin(), owners.end());
386         sort(sorted_owners.begin(), sorted_owners.end(),
387                 [](const RowItemOwner* a, const RowItemOwner *b) {
388                         return a->depth() > b->depth(); });
389
390         // Restack the items recursively
391         for (auto &o : sorted_owners)
392                 o->restack_items();
393
394         // Animate the items to their destination
395         for (const auto &r : *this)
396                 r->animate_to_layout_v_offset();
397 }
398
399 void View::get_scroll_layout(double &length, double &offset) const
400 {
401         const pair<double, double> extents = get_time_extents();
402         length = (extents.second - extents.first) / scale_;
403         offset = offset_ / scale_;
404 }
405
406 void View::set_zoom(double scale, int offset)
407 {
408         const double cursor_offset = offset_ + scale_ * offset;
409         const double new_scale = max(min(scale, MaxScale), MinScale);
410         const double new_offset = cursor_offset - new_scale * offset;
411         set_scale_offset(new_scale, new_offset);
412 }
413
414 void View::calculate_tick_spacing()
415 {
416         const double SpacingIncrement = 32.0f;
417         const double MinValueSpacing = 32.0f;
418
419         double min_width = SpacingIncrement, typical_width;
420
421         QFontMetrics m(QApplication::font());
422
423         do {
424                 const double min_period = scale_ * min_width;
425
426                 const int order = (int)floorf(log10f(min_period));
427                 const double order_decimal = pow(10.0, order);
428
429                 unsigned int unit = 0;
430
431                 do {
432                         tick_period_ = order_decimal * ScaleUnits[unit++];
433                 } while (tick_period_ < min_period &&
434                         unit < countof(ScaleUnits));
435
436                 tick_prefix_ = (order - pv::util::FirstSIPrefixPower) / 3;
437
438                 typical_width = m.boundingRect(0, 0, INT_MAX, INT_MAX,
439                         Qt::AlignLeft | Qt::AlignTop,
440                         format_time(offset_, tick_prefix_)).width() +
441                                 MinValueSpacing;
442
443                 min_width += SpacingIncrement;
444
445         } while(typical_width > tick_period_ / scale_);
446 }
447
448 void View::update_scroll()
449 {
450         assert(viewport_);
451
452         const QSize areaSize = viewport_->size();
453
454         // Set the horizontal scroll bar
455         double length = 0, offset = 0;
456         get_scroll_layout(length, offset);
457         length = max(length - areaSize.width(), 0.0);
458
459         int major_tick_distance = tick_period_ / scale_;
460
461         horizontalScrollBar()->setPageStep(areaSize.width() / 2);
462         horizontalScrollBar()->setSingleStep(major_tick_distance);
463
464         updating_scroll_ = true;
465
466         if (length < MaxScrollValue) {
467                 horizontalScrollBar()->setRange(0, length);
468                 horizontalScrollBar()->setSliderPosition(offset);
469         } else {
470                 horizontalScrollBar()->setRange(0, MaxScrollValue);
471                 horizontalScrollBar()->setSliderPosition(
472                         offset_ * MaxScrollValue / (scale_ * length));
473         }
474
475         updating_scroll_ = false;
476
477         // Set the vertical scrollbar
478         verticalScrollBar()->setPageStep(areaSize.height());
479
480         const pair<int, int> extents = v_extents();
481         const int extra_scroll_height = (extents.second - extents.first) / 4;
482         verticalScrollBar()->setRange(extents.first - extra_scroll_height,
483                 extents.first + extra_scroll_height);
484 }
485
486 void View::update_layout()
487 {
488         setViewportMargins(
489                 header_->sizeHint().width() - pv::view::Header::BaselineOffset,
490                 ruler_->sizeHint().height(), 0, 0);
491         ruler_->setGeometry(viewport_->x(), 0,
492                 viewport_->width(), viewport_->y());
493         cursorheader_->setGeometry(
494                 viewport_->x(),
495                 ruler_->sizeHint().height() - cursorheader_->sizeHint().height() / 2,
496                 viewport_->width(), cursorheader_->sizeHint().height());
497         header_->setGeometry(0, viewport_->y(),
498                 header_->sizeHint().width(), viewport_->height());
499         update_scroll();
500 }
501
502 void View::paint_label(QPainter &p, int right, bool hover)
503 {
504         (void)p;
505         (void)right;
506         (void)hover;
507 }
508
509 QRectF View::label_rect(int right)
510 {
511         (void)right;
512         return QRectF();
513 }
514
515 bool View::add_channels_to_owner(
516         const vector< shared_ptr<sigrok::Channel> > &channels,
517         RowItemOwner *owner, int &offset,
518         unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
519                 &signal_map,
520         std::function<bool (shared_ptr<RowItem>)> filter_func)
521 {
522         bool any_added = false;
523
524         assert(owner);
525
526         for (const auto &channel : channels)
527         {
528                 const auto iter = signal_map.find(channel);
529                 if (iter == signal_map.end() ||
530                         (filter_func && !filter_func((*iter).second)))
531                         continue;
532
533                 shared_ptr<RowItem> row_item = (*iter).second;
534                 owner->add_child_item(row_item);
535                 apply_offset(row_item, offset);
536                 signal_map.erase(iter);
537
538                 any_added = true;
539         }
540
541         return any_added;
542 }
543
544 void View::apply_offset(shared_ptr<RowItem> row_item, int &offset) {
545         assert(row_item);
546         const pair<int, int> extents = row_item->v_extents();
547         if (row_item->enabled())
548                 offset += -extents.first;
549         row_item->force_to_v_offset(offset);
550         if (row_item->enabled())
551                 offset += extents.second;
552 }
553
554 bool View::eventFilter(QObject *object, QEvent *event)
555 {
556         const QEvent::Type type = event->type();
557         if (type == QEvent::MouseMove) {
558
559                 const QMouseEvent *const mouse_event = (QMouseEvent*)event;
560                 if (object == viewport_)
561                         hover_point_ = mouse_event->pos();
562                 else if (object == ruler_ || object == cursorheader_)
563                         hover_point_ = QPoint(mouse_event->x(), 0);
564                 else if (object == header_)
565                         hover_point_ = QPoint(0, mouse_event->y());
566                 else
567                         hover_point_ = QPoint(-1, -1);
568
569                 hover_point_changed();
570
571         } else if (type == QEvent::Leave) {
572                 hover_point_ = QPoint(-1, -1);
573                 hover_point_changed();
574         }
575
576         return QObject::eventFilter(object, event);
577 }
578
579 bool View::viewportEvent(QEvent *e)
580 {
581         switch(e->type()) {
582         case QEvent::Paint:
583         case QEvent::MouseButtonPress:
584         case QEvent::MouseButtonRelease:
585         case QEvent::MouseButtonDblClick:
586         case QEvent::MouseMove:
587         case QEvent::Wheel:
588         case QEvent::TouchBegin:
589         case QEvent::TouchUpdate:
590         case QEvent::TouchEnd:
591                 return false;
592
593         default:
594                 return QAbstractScrollArea::viewportEvent(e);
595         }
596 }
597
598 void View::resizeEvent(QResizeEvent*)
599 {
600         update_layout();
601 }
602
603 void View::appearance_changed(bool label, bool content)
604 {
605         if (label)
606                 header_->update();
607         if (content)
608                 viewport_->update();
609 }
610
611 void View::extents_changed(bool horz, bool vert)
612 {
613         sticky_events_ |=
614                 (horz ? SelectableItemHExtentsChanged : 0) |
615                 (vert ? SelectableItemVExtentsChanged : 0);
616         lazy_event_handler_.start();
617 }
618
619 void View::h_scroll_value_changed(int value)
620 {
621         if (updating_scroll_)
622                 return;
623
624         const int range = horizontalScrollBar()->maximum();
625         if (range < MaxScrollValue)
626                 offset_ = scale_ * value;
627         else {
628                 double length = 0, offset;
629                 get_scroll_layout(length, offset);
630                 offset_ = scale_ * length * value / MaxScrollValue;
631         }
632
633         ruler_->update();
634         cursorheader_->update();
635         viewport_->update();
636 }
637
638 void View::v_scroll_value_changed(int value)
639 {
640         v_offset_ = value;
641         header_->update();
642         viewport_->update();
643 }
644
645 void View::signals_changed()
646 {
647         int offset = 0;
648
649         // Populate the traces
650         clear_child_items();
651
652         shared_ptr<sigrok::Device> device = session_.device();
653         assert(device);
654
655         // Collect a set of signals
656         unordered_map<shared_ptr<sigrok::Channel>, shared_ptr<Signal> >
657                 signal_map;
658
659         shared_lock<shared_mutex> lock(session_.signals_mutex());
660         const vector< shared_ptr<Signal> > &sigs(session_.signals());
661
662         for (const shared_ptr<Signal> &sig : sigs)
663                 signal_map[sig->channel()] = sig;
664
665         // Populate channel groups
666         for (auto entry : device->channel_groups())
667         {
668                 const shared_ptr<sigrok::ChannelGroup> &group = entry.second;
669
670                 if (group->channels().size() <= 1)
671                         continue;
672
673                 shared_ptr<TraceGroup> trace_group(new TraceGroup());
674                 int child_offset = 0;
675                 if (add_channels_to_owner(group->channels(),
676                         trace_group.get(), child_offset, signal_map))
677                 {
678                         add_child_item(trace_group);
679                         apply_offset(trace_group, offset);
680                 }
681         }
682
683         // Add the remaining logic channels
684         shared_ptr<TraceGroup> logic_trace_group(new TraceGroup());
685         int child_offset = 0;
686
687         if (add_channels_to_owner(device->channels(),
688                 logic_trace_group.get(), child_offset, signal_map,
689                 [](shared_ptr<RowItem> r) -> bool {
690                         return dynamic_pointer_cast<LogicSignal>(r) != nullptr;
691                         }))
692
693         {
694                 add_child_item(logic_trace_group);
695                 apply_offset(logic_trace_group, offset);
696         }
697
698         // Add the remaining channels
699         add_channels_to_owner(device->channels(), this, offset, signal_map);
700         assert(signal_map.empty());
701
702         // Add decode signals
703 #ifdef ENABLE_DECODE
704         const vector< shared_ptr<DecodeTrace> > decode_sigs(
705                 session().get_decode_signals());
706         for (auto s : decode_sigs) {
707                 add_child_item(s);
708                 apply_offset(s, offset);
709         }
710 #endif
711
712         update_layout();
713 }
714
715 void View::data_updated()
716 {
717         // Update the scroll bars
718         update_scroll();
719
720         // Repaint the view
721         viewport_->update();
722 }
723
724 void View::marker_time_changed()
725 {
726         cursorheader_->update();
727         viewport_->update();
728 }
729
730 void View::on_signals_moved()
731 {
732         update_scroll();
733         signals_moved();
734 }
735
736 void View::process_sticky_events()
737 {
738         if (sticky_events_ & SelectableItemHExtentsChanged)
739                 update_layout();
740         if (sticky_events_ & SelectableItemVExtentsChanged)
741                 restack_all_row_items();
742
743         // Clear the sticky events
744         sticky_events_ = 0;
745 }
746
747 void View::on_hover_point_changed()
748 {
749         for (shared_ptr<RowItem> r : *this)
750                 r->hover_point_changed();
751 }
752
753 } // namespace view
754 } // namespace pv