]> sigrok.org Git - pulseview.git/blame_incremental - pv/views/trace/decodetrace.cpp
Session: Fix issue #67 by improving error handling
[pulseview.git] / pv / views / trace / decodetrace.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include <libsigrokdecode/libsigrokdecode.h>
21
22#include <limits>
23#include <mutex>
24#include <tuple>
25
26#include <extdef.h>
27
28#include <boost/functional/hash.hpp>
29
30#include <QAction>
31#include <QApplication>
32#include <QClipboard>
33#include <QCheckBox>
34#include <QComboBox>
35#include <QDebug>
36#include <QFileDialog>
37#include <QFormLayout>
38#include <QLabel>
39#include <QMenu>
40#include <QMessageBox>
41#include <QPushButton>
42#include <QTextStream>
43#include <QToolTip>
44
45#include "decodetrace.hpp"
46#include "view.hpp"
47#include "viewport.hpp"
48
49#include <pv/globalsettings.hpp>
50#include <pv/session.hpp>
51#include <pv/strnatcmp.hpp>
52#include <pv/data/decodesignal.hpp>
53#include <pv/data/decode/annotation.hpp>
54#include <pv/data/decode/decoder.hpp>
55#include <pv/data/logic.hpp>
56#include <pv/data/logicsegment.hpp>
57#include <pv/widgets/decodergroupbox.hpp>
58#include <pv/widgets/decodermenu.hpp>
59#include <pv/widgets/flowlayout.hpp>
60
61using std::abs;
62using std::find_if;
63using std::lock_guard;
64using std::make_pair;
65using std::max;
66using std::min;
67using std::numeric_limits;
68using std::pair;
69using std::shared_ptr;
70using std::tie;
71using std::vector;
72
73using pv::data::decode::Annotation;
74using pv::data::decode::AnnotationClass;
75using pv::data::decode::Row;
76using pv::data::decode::DecodeChannel;
77using pv::data::DecodeSignal;
78
79namespace pv {
80namespace views {
81namespace trace {
82
83const QColor DecodeTrace::NoDecodeColor = QColor(0x88, 0x8A, 0x85);
84const QColor DecodeTrace::ExpandMarkerWarnColor = QColor(0xFF, 0xA5, 0x00); // QColorConstants::Svg::orange
85const QColor DecodeTrace::ExpandMarkerHiddenColor = QColor(0x69, 0x69, 0x69); // QColorConstants::Svg::dimgray
86const uint8_t DecodeTrace::ExpansionAreaHeaderAlpha = 10 * 255 / 100;
87const uint8_t DecodeTrace::ExpansionAreaAlpha = 5 * 255 / 100;
88
89const int DecodeTrace::ArrowSize = 6;
90const double DecodeTrace::EndCapWidth = 5;
91const int DecodeTrace::RowTitleMargin = 7;
92const int DecodeTrace::DrawPadding = 100;
93
94const int DecodeTrace::MaxTraceUpdateRate = 1; // No more than 1 Hz
95const int DecodeTrace::AnimationDurationInTicks = 7;
96const int DecodeTrace::HiddenRowHideDelay = 1000; // 1 second
97
98/**
99 * Helper function for forceUpdate()
100 */
101void invalidateLayout(QLayout* layout)
102{
103 // Recompute the given layout and all its child layouts recursively
104 for (int i = 0; i < layout->count(); i++) {
105 QLayoutItem *item = layout->itemAt(i);
106
107 if (item->layout())
108 invalidateLayout(item->layout());
109 else
110 item->invalidate();
111 }
112
113 layout->invalidate();
114 layout->activate();
115}
116
117void forceUpdate(QWidget* widget)
118{
119 // Update all child widgets recursively
120 for (QObject* child : widget->children())
121 if (child->isWidgetType())
122 forceUpdate((QWidget*)child);
123
124 // Invalidate the layout of the widget itself
125 if (widget->layout())
126 invalidateLayout(widget->layout());
127}
128
129
130ContainerWidget::ContainerWidget(QWidget *parent) :
131 QWidget(parent)
132{
133}
134
135void ContainerWidget::resizeEvent(QResizeEvent* event)
136{
137 QWidget::resizeEvent(event);
138
139 widgetResized(this);
140}
141
142
143DecodeTrace::DecodeTrace(pv::Session &session,
144 shared_ptr<data::SignalBase> signalbase, int index) :
145 Trace(signalbase),
146 session_(session),
147 show_hidden_rows_(false),
148 delete_mapper_(this),
149 show_hide_mapper_(this),
150 row_show_hide_mapper_(this)
151{
152 decode_signal_ = dynamic_pointer_cast<data::DecodeSignal>(base_);
153
154 GlobalSettings settings;
155 always_show_all_rows_ = settings.value(GlobalSettings::Key_Dec_AlwaysShowAllRows).toBool();
156
157 GlobalSettings::add_change_handler(this);
158
159 // Determine shortest string we want to see displayed in full
160 QFontMetrics m(QApplication::font());
161 // e.g. two hex characters
162 min_useful_label_width_ = util::text_width(m, "XX");
163
164 default_row_height_ = (ViewItemPaintParams::text_height() * 6) / 4;
165 annotation_height_ = (ViewItemPaintParams::text_height() * 5) / 4;
166
167 // For the base color, we want to start at a very different color for
168 // every decoder stack, so multiply the index with a number that is
169 // rather close to 180 degrees of the color circle but not a dividend of 360
170 // Note: The offset equals the color of the first annotation
171 QColor color;
172 const int h = (120 + 160 * index) % 360;
173 const int s = DECODE_COLOR_SATURATION;
174 const int v = DECODE_COLOR_VALUE;
175 color.setHsv(h, s, v);
176 base_->set_color(color);
177
178 connect(decode_signal_.get(), SIGNAL(color_changed(QColor)),
179 this, SLOT(on_color_changed(QColor)));
180
181 connect(decode_signal_.get(), SIGNAL(new_annotations()),
182 this, SLOT(on_new_annotations()));
183 connect(decode_signal_.get(), SIGNAL(decode_reset()),
184 this, SLOT(on_decode_reset()));
185 connect(decode_signal_.get(), SIGNAL(decode_finished()),
186 this, SLOT(on_decode_finished()));
187 connect(decode_signal_.get(), SIGNAL(channels_updated()),
188 this, SLOT(on_channels_updated()));
189
190 connect(&delete_mapper_, SIGNAL(mapped(int)),
191 this, SLOT(on_delete_decoder(int)));
192 connect(&show_hide_mapper_, SIGNAL(mapped(int)),
193 this, SLOT(on_show_hide_decoder(int)));
194 connect(&row_show_hide_mapper_, SIGNAL(mapped(int)),
195 this, SLOT(on_show_hide_row(int)));
196 connect(&class_show_hide_mapper_, SIGNAL(mapped(QWidget*)),
197 this, SLOT(on_show_hide_class(QWidget*)));
198
199 connect(&delayed_trace_updater_, SIGNAL(timeout()),
200 this, SLOT(on_delayed_trace_update()));
201 delayed_trace_updater_.setSingleShot(true);
202 delayed_trace_updater_.setInterval(1000 / MaxTraceUpdateRate);
203
204 connect(&animation_timer_, SIGNAL(timeout()),
205 this, SLOT(on_animation_timer()));
206 animation_timer_.setInterval(1000 / 50);
207
208 connect(&delayed_hidden_row_hider_, SIGNAL(timeout()),
209 this, SLOT(on_hide_hidden_rows()));
210 delayed_hidden_row_hider_.setSingleShot(true);
211 delayed_hidden_row_hider_.setInterval(HiddenRowHideDelay);
212
213 default_marker_shape_ << QPoint(0, -ArrowSize);
214 default_marker_shape_ << QPoint(ArrowSize, 0);
215 default_marker_shape_ << QPoint(0, ArrowSize);
216}
217
218DecodeTrace::~DecodeTrace()
219{
220 GlobalSettings::remove_change_handler(this);
221
222 for (DecodeTraceRow& r : rows_) {
223 for (QCheckBox* cb : r.selectors)
224 delete cb;
225
226 delete r.selector_container;
227 delete r.header_container;
228 delete r.container;
229 }
230}
231
232bool DecodeTrace::enabled() const
233{
234 return true;
235}
236
237shared_ptr<data::SignalBase> DecodeTrace::base() const
238{
239 return base_;
240}
241
242void DecodeTrace::set_owner(TraceTreeItemOwner *owner)
243{
244 Trace::set_owner(owner);
245
246 // The owner is set in trace::View::signals_changed(), which is a slot.
247 // So after this trace was added to the view, we won't have an owner
248 // that we need to initialize in update_rows(). Once we do, we call it
249 // from on_decode_reset().
250 on_decode_reset();
251}
252
253pair<int, int> DecodeTrace::v_extents() const
254{
255 // Make an empty decode trace appear symmetrical
256 if (visible_rows_ == 0)
257 return make_pair(-default_row_height_, default_row_height_);
258
259 unsigned int height = 0;
260 for (const DecodeTraceRow& r : rows_)
261 if (r.currently_visible)
262 height += r.height;
263
264 return make_pair(-default_row_height_, height);
265}
266
267void DecodeTrace::paint_back(QPainter &p, ViewItemPaintParams &pp)
268{
269 Trace::paint_back(p, pp);
270 paint_axis(p, pp, get_visual_y());
271}
272
273void DecodeTrace::paint_mid(QPainter &p, ViewItemPaintParams &pp)
274{
275 lock_guard<mutex> lock(row_modification_mutex_);
276 unsigned int visible_rows;
277
278#if DECODETRACE_SHOW_RENDER_TIME
279 render_time_.restart();
280#endif
281
282 // Set default pen to allow for text width calculation
283 p.setPen(Qt::black);
284
285 pair<uint64_t, uint64_t> sample_range = get_view_sample_range(pp.left(), pp.right());
286
287 // Just because the view says we see a certain sample range it
288 // doesn't mean we have this many decoded samples, too, so crop
289 // the range to what has been decoded already
290 sample_range.second = min((int64_t)sample_range.second,
291 decode_signal_->get_decoded_sample_count(current_segment_, false));
292
293 visible_rows = 0;
294 int y = get_visual_y();
295
296 for (DecodeTraceRow& r : rows_) {
297 // If the row is hidden, we don't want to fetch annotations
298 assert(r.decode_row);
299 assert(r.decode_row->decoder());
300 if ((!r.decode_row->decoder()->visible()) ||
301 ((!r.decode_row->visible() && (!show_hidden_rows_) && (!r.expanding) && (!r.expanded) && (!r.collapsing)))) {
302 r.currently_visible = false;
303 continue;
304 }
305
306 deque<const Annotation*> annotations;
307 decode_signal_->get_annotation_subset(annotations, r.decode_row,
308 current_segment_, sample_range.first, sample_range.second);
309
310 // Show row if there are visible annotations, when user wants to see
311 // all rows that have annotations somewhere and this one is one of them
312 // or when the row has at least one hidden annotation class
313 r.currently_visible = !annotations.empty();
314 if (!r.currently_visible) {
315 size_t ann_count = decode_signal_->get_annotation_count(r.decode_row, current_segment_);
316 r.currently_visible = ((always_show_all_rows_ || r.has_hidden_classes) &&
317 (ann_count > 0)) || r.expanded;
318 }
319
320 if (r.currently_visible) {
321 draw_annotations(annotations, p, pp, y, r);
322 y += r.height;
323 visible_rows++;
324 }
325 }
326
327 draw_unresolved_period(p, pp.left(), pp.right());
328
329 if (visible_rows != visible_rows_) {
330 visible_rows_ = visible_rows;
331
332 // Call order is important, otherwise the lazy event handler won't work
333 owner_->extents_changed(false, true);
334 owner_->row_item_appearance_changed(false, true);
335 }
336
337 const QString err = base_->get_error_message();
338 if (!err.isEmpty())
339 paint_error(p, pp);
340
341#if DECODETRACE_SHOW_RENDER_TIME
342 qDebug() << "Rendering" << base_->name() << "took" << render_time_.elapsed() << "ms";
343#endif
344}
345
346void DecodeTrace::paint_fore(QPainter &p, ViewItemPaintParams &pp)
347{
348 unsigned int y = get_visual_y();
349
350 update_expanded_rows();
351
352 for (const DecodeTraceRow& r : rows_) {
353 if (!r.currently_visible)
354 continue;
355
356 p.setPen(QPen(Qt::NoPen));
357
358 if (r.expand_marker_highlighted)
359 p.setBrush(QApplication::palette().brush(QPalette::Highlight));
360 else if (!r.decode_row->visible())
361 p.setBrush(ExpandMarkerHiddenColor);
362 else if (r.has_hidden_classes)
363 p.setBrush(ExpandMarkerWarnColor);
364 else
365 p.setBrush(QApplication::palette().brush(QPalette::WindowText));
366
367 // Draw expansion marker
368 QPolygon marker(r.expand_marker_shape);
369 marker.translate(pp.left(), y);
370 p.drawPolygon(marker);
371
372 p.setBrush(QApplication::palette().brush(QPalette::WindowText));
373
374 const QRect text_rect(pp.left() + ArrowSize * 2, y - r.height / 2,
375 pp.right() - pp.left(), r.height);
376 const QString h(r.decode_row->title());
377 const int f = Qt::AlignLeft | Qt::AlignVCenter |
378 Qt::TextDontClip;
379
380 // Draw the outline
381 p.setPen(QApplication::palette().color(QPalette::Base));
382 for (int dx = -1; dx <= 1; dx++)
383 for (int dy = -1; dy <= 1; dy++)
384 if (dx != 0 && dy != 0)
385 p.drawText(text_rect.translated(dx, dy), f, h);
386
387 // Draw the text
388 if (!r.decode_row->visible())
389 p.setPen(ExpandMarkerHiddenColor);
390 else
391 p.setPen(QApplication::palette().color(QPalette::WindowText));
392
393 p.drawText(text_rect, f, h);
394
395 y += r.height;
396 }
397
398 if (show_hover_marker_)
399 paint_hover_marker(p);
400}
401
402void DecodeTrace::update_stack_button()
403{
404 const vector< shared_ptr<Decoder> > &stack = decode_signal_->decoder_stack();
405
406 // Only show decoders in the menu that can be stacked onto the last one in the stack
407 if (!stack.empty()) {
408 const srd_decoder* d = stack.back()->get_srd_decoder();
409
410 if (d->outputs) {
411 pv::widgets::DecoderMenu *const decoder_menu =
412 new pv::widgets::DecoderMenu(stack_button_, (const char*)(d->outputs->data));
413 connect(decoder_menu, SIGNAL(decoder_selected(srd_decoder*)),
414 this, SLOT(on_stack_decoder(srd_decoder*)));
415
416 decoder_menu->setStyleSheet("QMenu { menu-scrollable: 1; }");
417
418 stack_button_->setMenu(decoder_menu);
419 stack_button_->show();
420 return;
421 }
422 }
423
424 // No decoders available for stacking
425 stack_button_->setMenu(nullptr);
426 stack_button_->hide();
427}
428
429void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form)
430{
431 assert(form);
432
433 // Add the standard options
434 Trace::populate_popup_form(parent, form);
435
436 // Add the decoder options
437 bindings_.clear();
438 channel_id_map_.clear();
439 init_state_map_.clear();
440 decoder_forms_.clear();
441
442 const vector< shared_ptr<Decoder> > &stack = decode_signal_->decoder_stack();
443
444 if (stack.empty()) {
445 QLabel *const l = new QLabel(
446 tr("<p><i>No decoders in the stack</i></p>"));
447 l->setAlignment(Qt::AlignCenter);
448 form->addRow(l);
449 } else {
450 auto iter = stack.cbegin();
451 for (int i = 0; i < (int)stack.size(); i++, iter++) {
452 shared_ptr<Decoder> dec(*iter);
453 create_decoder_form(i, dec, parent, form);
454 }
455
456 form->addRow(new QLabel(
457 tr("<i>* Required channels</i>"), parent));
458 }
459
460 // Add stacking button
461 stack_button_ = new QPushButton(tr("Stack Decoder"), parent);
462 stack_button_->setToolTip(tr("Stack a higher-level decoder on top of this one"));
463 update_stack_button();
464
465 QHBoxLayout *stack_button_box = new QHBoxLayout;
466 stack_button_box->addWidget(stack_button_, 0, Qt::AlignRight);
467 form->addRow(stack_button_box);
468}
469
470QMenu* DecodeTrace::create_header_context_menu(QWidget *parent)
471{
472 QMenu *const menu = Trace::create_header_context_menu(parent);
473
474 menu->addSeparator();
475
476 QAction *const del = new QAction(tr("Delete"), this);
477 del->setShortcuts(QKeySequence::Delete);
478 connect(del, SIGNAL(triggered()), this, SLOT(on_delete()));
479 menu->addAction(del);
480
481 return menu;
482}
483
484QMenu* DecodeTrace::create_view_context_menu(QWidget *parent, QPoint &click_pos)
485{
486 // Get entries from default menu before adding our own
487 QMenu *const menu = new QMenu(parent);
488
489 QMenu* default_menu = Trace::create_view_context_menu(parent, click_pos);
490 if (default_menu) {
491 for (QAction *action : default_menu->actions()) { // clazy:exclude=range-loop
492 menu->addAction(action);
493 if (action->parent() == default_menu)
494 action->setParent(menu);
495 }
496 delete default_menu;
497
498 // Add separator if needed
499 if (menu->actions().length() > 0)
500 menu->addSeparator();
501 }
502
503 selected_row_ = nullptr;
504 const DecodeTraceRow* r = get_row_at_point(click_pos);
505 if (r)
506 selected_row_ = r->decode_row;
507
508 const View *const view = owner_->view();
509 assert(view);
510 QPoint pos = view->viewport()->mapFrom(parent, click_pos);
511
512 // Default sample range is "from here"
513 const pair<uint64_t, uint64_t> sample_range = get_view_sample_range(pos.x(), pos.x() + 1);
514 selected_sample_range_ = make_pair(sample_range.first, numeric_limits<uint64_t>::max());
515
516 if (decode_signal_->is_paused()) {
517 QAction *const resume =
518 new QAction(tr("Resume decoding"), this);
519 resume->setIcon(QIcon::fromTheme("media-playback-start",
520 QIcon(":/icons/media-playback-start.png")));
521 connect(resume, SIGNAL(triggered()), this, SLOT(on_pause_decode()));
522 menu->addAction(resume);
523 } else {
524 QAction *const pause =
525 new QAction(tr("Pause decoding"), this);
526 pause->setIcon(QIcon::fromTheme("media-playback-pause",
527 QIcon(":/icons/media-playback-pause.png")));
528 connect(pause, SIGNAL(triggered()), this, SLOT(on_pause_decode()));
529 menu->addAction(pause);
530 }
531
532 QAction *const copy_annotation_to_clipboard =
533 new QAction(tr("Copy annotation text to clipboard"), this);
534 copy_annotation_to_clipboard->setIcon(QIcon::fromTheme("edit-paste",
535 QIcon(":/icons/edit-paste.svg")));
536 connect(copy_annotation_to_clipboard, SIGNAL(triggered()), this, SLOT(on_copy_annotation_to_clipboard()));
537 menu->addAction(copy_annotation_to_clipboard);
538
539 menu->addSeparator();
540
541 QAction *const export_all_rows =
542 new QAction(tr("Export all annotations"), this);
543 export_all_rows->setIcon(QIcon::fromTheme("document-save-as",
544 QIcon(":/icons/document-save-as.png")));
545 connect(export_all_rows, SIGNAL(triggered()), this, SLOT(on_export_all_rows()));
546 menu->addAction(export_all_rows);
547
548 QAction *const export_row =
549 new QAction(tr("Export all annotations for this row"), this);
550 export_row->setIcon(QIcon::fromTheme("document-save-as",
551 QIcon(":/icons/document-save-as.png")));
552 connect(export_row, SIGNAL(triggered()), this, SLOT(on_export_row()));
553 menu->addAction(export_row);
554
555 menu->addSeparator();
556
557 QAction *const export_all_rows_from_here =
558 new QAction(tr("Export all annotations, starting here"), this);
559 export_all_rows_from_here->setIcon(QIcon::fromTheme("document-save-as",
560 QIcon(":/icons/document-save-as.png")));
561 connect(export_all_rows_from_here, SIGNAL(triggered()), this, SLOT(on_export_all_rows_from_here()));
562 menu->addAction(export_all_rows_from_here);
563
564 QAction *const export_row_from_here =
565 new QAction(tr("Export annotations for this row, starting here"), this);
566 export_row_from_here->setIcon(QIcon::fromTheme("document-save-as",
567 QIcon(":/icons/document-save-as.png")));
568 connect(export_row_from_here, SIGNAL(triggered()), this, SLOT(on_export_row_from_here()));
569 menu->addAction(export_row_from_here);
570
571 menu->addSeparator();
572
573 QAction *const export_all_rows_with_cursor =
574 new QAction(tr("Export all annotations within cursor range"), this);
575 export_all_rows_with_cursor->setIcon(QIcon::fromTheme("document-save-as",
576 QIcon(":/icons/document-save-as.png")));
577 connect(export_all_rows_with_cursor, SIGNAL(triggered()), this, SLOT(on_export_all_rows_with_cursor()));
578 menu->addAction(export_all_rows_with_cursor);
579
580 QAction *const export_row_with_cursor =
581 new QAction(tr("Export annotations for this row within cursor range"), this);
582 export_row_with_cursor->setIcon(QIcon::fromTheme("document-save-as",
583 QIcon(":/icons/document-save-as.png")));
584 connect(export_row_with_cursor, SIGNAL(triggered()), this, SLOT(on_export_row_with_cursor()));
585 menu->addAction(export_row_with_cursor);
586
587 if (!view->cursors()->enabled()) {
588 export_all_rows_with_cursor->setEnabled(false);
589 export_row_with_cursor->setEnabled(false);
590 }
591
592 return menu;
593}
594
595void DecodeTrace::delete_pressed()
596{
597 on_delete();
598}
599
600void DecodeTrace::hover_point_changed(const QPoint &hp)
601{
602 Trace::hover_point_changed(hp);
603
604 assert(owner_);
605
606 DecodeTraceRow* hover_row = get_row_at_point(hp);
607
608 // Row expansion marker handling
609 for (DecodeTraceRow& r : rows_)
610 r.expand_marker_highlighted = false;
611
612 if (hover_row) {
613 const pair<int, int> extents = v_extents();
614 const int trace_top = get_visual_y() + extents.first;
615 const int trace_btm = get_visual_y() + extents.second;
616
617 if ((hp.x() > 0) && (hp.x() < (int)(ArrowSize + 3 + hover_row->title_width)) &&
618 (hp.y() > trace_top) && (hp.y() < trace_btm)) {
619
620 hover_row->expand_marker_highlighted = true;
621 show_hidden_rows_ = true;
622 delayed_hidden_row_hider_.start();
623 }
624 }
625
626 // Tooltip handling
627 if (hp.x() > 0) {
628 QString ann = get_annotation_at_point(hp);
629
630 if (!ann.isEmpty()) {
631 QFontMetrics m(QToolTip::font());
632 const QRect text_size = m.boundingRect(QRect(), 0, ann);
633
634 // This is OS-specific and unfortunately we can't query it, so
635 // use an approximation to at least try to minimize the error.
636 const int padding = default_row_height_ + 8;
637
638 // Make sure the tool tip doesn't overlap with the mouse cursor.
639 // If it did, the tool tip would constantly hide and re-appear.
640 // We also push it up by one row so that it appears above the
641 // decode trace, not below.
642 QPoint p = hp;
643 p.setX(hp.x() - (text_size.width() / 2) - padding);
644
645 p.setY(get_row_y(hover_row) - default_row_height_ -
646 text_size.height() - padding);
647
648 const View *const view = owner_->view();
649 assert(view);
650 QToolTip::showText(view->viewport()->mapToGlobal(p), ann);
651
652 } else
653 QToolTip::hideText();
654
655 } else
656 QToolTip::hideText();
657}
658
659void DecodeTrace::mouse_left_press_event(const QMouseEvent* event)
660{
661 // Update container widths which depend on the scrollarea's current width
662 update_expanded_rows();
663
664 // Handle row expansion marker
665 for (DecodeTraceRow& r : rows_) {
666 if (!r.expand_marker_highlighted)
667 continue;
668
669 unsigned int y = get_row_y(&r);
670 if ((event->x() > 0) && (event->x() <= (int)(ArrowSize + 3 + r.title_width)) &&
671 (event->y() > (int)(y - (default_row_height_ / 2))) &&
672 (event->y() <= (int)(y + (default_row_height_ / 2)))) {
673
674 if (r.expanded) {
675 r.collapsing = true;
676 r.expanded = false;
677 r.anim_shape = ArrowSize;
678 } else {
679 r.expanding = true;
680 r.anim_shape = 0;
681
682 // Force geometry update of the widget container to get
683 // an up-to-date height (which also depends on the width)
684 forceUpdate(r.container);
685
686 r.container->setVisible(true);
687 r.expanded_height = 2 * default_row_height_ + r.container->sizeHint().height();
688 }
689
690 r.animation_step = 0;
691 r.anim_height = r.height;
692
693 animation_timer_.start();
694 }
695 }
696}
697
698void DecodeTrace::draw_annotations(deque<const Annotation*>& annotations,
699 QPainter &p, const ViewItemPaintParams &pp, int y, const DecodeTraceRow& row)
700{
701 uint32_t block_class = 0;
702 bool block_class_uniform = true;
703 qreal block_start = 0;
704 int block_ann_count = 0;
705
706 const Annotation* prev_ann;
707 qreal prev_end = INT_MIN;
708
709 qreal a_end;
710
711 double samples_per_pixel, pixels_offset;
712 tie(pixels_offset, samples_per_pixel) =
713 get_pixels_offset_samples_per_pixel();
714
715 // Gather all annotations that form a visual "block" and draw them as such
716 for (const Annotation* a : annotations) {
717
718 const qreal abs_a_start = a->start_sample() / samples_per_pixel;
719 const qreal abs_a_end = a->end_sample() / samples_per_pixel;
720
721 const qreal a_start = abs_a_start - pixels_offset;
722 a_end = abs_a_end - pixels_offset;
723
724 const qreal a_width = a_end - a_start;
725 const qreal delta = a_end - prev_end;
726
727 bool a_is_separate = false;
728
729 // Annotation wider than the threshold for a useful label width?
730 if (a_width >= min_useful_label_width_) {
731 for (const QString &ann_text : *(a->annotations())) {
732 const qreal w = p.boundingRect(QRectF(), 0, ann_text).width();
733 // Annotation wide enough to fit a label? Don't put it in a block then
734 if (w <= a_width) {
735 a_is_separate = true;
736 break;
737 }
738 }
739 }
740
741 // Were the previous and this annotation more than a pixel apart?
742 if ((abs(delta) > 1) || a_is_separate) {
743 // Block was broken, draw annotations that form the current block
744 if (block_ann_count == 1)
745 draw_annotation(prev_ann, p, pp, y, row);
746 else if (block_ann_count > 0)
747 draw_annotation_block(block_start, prev_end, block_class,
748 block_class_uniform, p, y, row);
749
750 block_ann_count = 0;
751 }
752
753 if (a_is_separate) {
754 draw_annotation(a, p, pp, y, row);
755 // Next annotation must start a new block. delta will be > 1
756 // because we set prev_end to INT_MIN but that's okay since
757 // block_ann_count will be 0 and nothing will be drawn
758 prev_end = INT_MIN;
759 block_ann_count = 0;
760 } else {
761 prev_end = a_end;
762 prev_ann = a;
763
764 if (block_ann_count == 0) {
765 block_start = a_start;
766 block_class = a->ann_class_id();
767 block_class_uniform = true;
768 } else
769 if (a->ann_class_id() != block_class)
770 block_class_uniform = false;
771
772 block_ann_count++;
773 }
774 }
775
776 if (block_ann_count == 1)
777 draw_annotation(prev_ann, p, pp, y, row);
778 else if (block_ann_count > 0)
779 draw_annotation_block(block_start, prev_end, block_class,
780 block_class_uniform, p, y, row);
781}
782
783void DecodeTrace::draw_annotation(const Annotation* a, QPainter &p,
784 const ViewItemPaintParams &pp, int y, const DecodeTraceRow& row) const
785{
786 double samples_per_pixel, pixels_offset;
787 tie(pixels_offset, samples_per_pixel) =
788 get_pixels_offset_samples_per_pixel();
789
790 const double start = a->start_sample() / samples_per_pixel - pixels_offset;
791 const double end = a->end_sample() / samples_per_pixel - pixels_offset;
792
793 p.setPen(a->dark_color());
794 p.setBrush(a->color());
795
796 if ((start > (pp.right() + DrawPadding)) || (end < (pp.left() - DrawPadding)))
797 return;
798
799 if (a->start_sample() == a->end_sample())
800 draw_instant(a, p, start, y);
801 else
802 draw_range(a, p, start, end, y, pp, row.title_width);
803}
804
805void DecodeTrace::draw_annotation_block(qreal start, qreal end,
806 uint32_t ann_class, bool use_ann_format, QPainter &p, int y,
807 const DecodeTraceRow& row) const
808{
809 const double top = y + .5 - annotation_height_ / 2;
810 const double bottom = y + .5 + annotation_height_ / 2;
811 const double width = end - start;
812
813 // If all annotations in this block are of the same type, we can use the
814 // one format that all of these annotations have. Otherwise, we should use
815 // a neutral color (i.e. gray)
816 if (use_ann_format) {
817 p.setPen(row.decode_row->get_dark_class_color(ann_class));
818 p.setBrush(QBrush(row.decode_row->get_class_color(ann_class), Qt::Dense4Pattern));
819 } else {
820 p.setPen(QColor(Qt::darkGray));
821 p.setBrush(QBrush(Qt::gray, Qt::Dense4Pattern));
822 }
823
824 if (width <= 1)
825 p.drawLine(QPointF(start, top), QPointF(start, bottom));
826 else {
827 const QRectF rect(start, top, width, bottom - top);
828 const int r = annotation_height_ / 4;
829 p.drawRoundedRect(rect, r, r);
830 }
831}
832
833void DecodeTrace::draw_instant(const Annotation* a, QPainter &p, qreal x, int y) const
834{
835 const QString text = a->annotations()->empty() ?
836 QString() : a->annotations()->back();
837 const qreal w = min((qreal)p.boundingRect(QRectF(), 0, text).width(),
838 0.0) + annotation_height_;
839 const QRectF rect(x - w / 2, y - annotation_height_ / 2, w, annotation_height_);
840
841 p.drawRoundedRect(rect, annotation_height_ / 2, annotation_height_ / 2);
842
843 p.setPen(Qt::black);
844 p.drawText(rect, Qt::AlignCenter | Qt::AlignVCenter, text);
845}
846
847void DecodeTrace::draw_range(const Annotation* a, QPainter &p,
848 qreal start, qreal end, int y, const ViewItemPaintParams &pp,
849 int row_title_width) const
850{
851 const qreal top = y + .5 - annotation_height_ / 2;
852 const qreal bottom = y + .5 + annotation_height_ / 2;
853 const vector<QString>* annotations = a->annotations();
854
855 // If the two ends are within 1 pixel, draw a vertical line
856 if (start + 1.0 > end) {
857 p.drawLine(QPointF(start, top), QPointF(start, bottom));
858 return;
859 }
860
861 const qreal cap_width = min((end - start) / 4, EndCapWidth);
862
863 QPointF pts[] = {
864 QPointF(start, y + .5f),
865 QPointF(start + cap_width, top),
866 QPointF(end - cap_width, top),
867 QPointF(end, y + .5f),
868 QPointF(end - cap_width, bottom),
869 QPointF(start + cap_width, bottom)
870 };
871
872 p.drawConvexPolygon(pts, countof(pts));
873
874 if (annotations->empty())
875 return;
876
877 const int ann_start = start + cap_width;
878 const int ann_end = end - cap_width;
879
880 const int real_start = max(ann_start, pp.left() + ArrowSize + row_title_width);
881 const int real_end = min(ann_end, pp.right());
882 const int real_width = real_end - real_start;
883
884 QRectF rect(real_start, y - annotation_height_ / 2, real_width, annotation_height_);
885 if (rect.width() <= 4)
886 return;
887
888 p.setPen(Qt::black);
889
890 // Try to find an annotation that will fit
891 QString best_annotation;
892 int best_width = 0;
893
894 for (const QString &s : *annotations) {
895 const int w = p.boundingRect(QRectF(), 0, s).width();
896 if (w <= rect.width() && w > best_width)
897 best_annotation = s, best_width = w;
898 }
899
900 if (best_annotation.isEmpty())
901 best_annotation = annotations->back();
902
903 // If not ellide the last in the list
904 p.drawText(rect, Qt::AlignCenter, p.fontMetrics().elidedText(
905 best_annotation, Qt::ElideRight, rect.width()));
906}
907
908void DecodeTrace::draw_unresolved_period(QPainter &p, int left, int right) const
909{
910 double samples_per_pixel, pixels_offset;
911
912 const int64_t sample_count = decode_signal_->get_working_sample_count(current_segment_);
913 if (sample_count == 0)
914 return;
915
916 const int64_t samples_decoded = decode_signal_->get_decoded_sample_count(current_segment_, true);
917 if (sample_count == samples_decoded)
918 return;
919
920 const int y = get_visual_y();
921
922 tie(pixels_offset, samples_per_pixel) = get_pixels_offset_samples_per_pixel();
923
924 const double start = max(samples_decoded /
925 samples_per_pixel - pixels_offset, left - 1.0);
926 const double end = min(sample_count / samples_per_pixel -
927 pixels_offset, right + 1.0);
928 const QRectF no_decode_rect(start, y - (annotation_height_ / 2) - 0.5,
929 end - start, annotation_height_);
930
931 p.setPen(QPen(Qt::NoPen));
932 p.setBrush(Qt::white);
933 p.drawRect(no_decode_rect);
934
935 p.setPen(NoDecodeColor);
936 p.setBrush(QBrush(NoDecodeColor, Qt::Dense6Pattern));
937 p.drawRect(no_decode_rect);
938}
939
940pair<double, double> DecodeTrace::get_pixels_offset_samples_per_pixel() const
941{
942 assert(owner_);
943
944 const View *view = owner_->view();
945 assert(view);
946
947 const double scale = view->scale();
948 assert(scale > 0);
949
950 const double pixels_offset =
951 ((view->offset() - decode_signal_->start_time()) / scale).convert_to<double>();
952
953 double samplerate = decode_signal_->get_samplerate();
954
955 // Show sample rate as 1Hz when it is unknown
956 if (samplerate == 0.0)
957 samplerate = 1.0;
958
959 return make_pair(pixels_offset, samplerate * scale);
960}
961
962pair<uint64_t, uint64_t> DecodeTrace::get_view_sample_range(
963 int x_start, int x_end) const
964{
965 double samples_per_pixel, pixels_offset;
966 tie(pixels_offset, samples_per_pixel) =
967 get_pixels_offset_samples_per_pixel();
968
969 const uint64_t start = (uint64_t)max(
970 (x_start + pixels_offset) * samples_per_pixel, 0.0);
971 const uint64_t end = (uint64_t)max(
972 (x_end + pixels_offset) * samples_per_pixel, 0.0);
973
974 return make_pair(start, end);
975}
976
977unsigned int DecodeTrace::get_row_y(const DecodeTraceRow* row) const
978{
979 assert(row);
980
981 unsigned int y = get_visual_y();
982
983 for (const DecodeTraceRow& r : rows_) {
984 if (!r.currently_visible)
985 continue;
986
987 if (row->decode_row == r.decode_row)
988 break;
989 else
990 y += r.height;
991 }
992
993 return y;
994}
995
996DecodeTraceRow* DecodeTrace::get_row_at_point(const QPoint &point)
997{
998 int y = get_visual_y() - (default_row_height_ / 2);
999
1000 for (DecodeTraceRow& r : rows_) {
1001 if (!r.currently_visible)
1002 continue;
1003
1004 if ((point.y() >= y) && (point.y() < (int)(y + r.height)))
1005 return &r;
1006
1007 y += r.height;
1008 }
1009
1010 return nullptr;
1011}
1012
1013const QString DecodeTrace::get_annotation_at_point(const QPoint &point)
1014{
1015 if (!enabled())
1016 return QString();
1017
1018 const pair<uint64_t, uint64_t> sample_range =
1019 get_view_sample_range(point.x(), point.x() + 1);
1020 const DecodeTraceRow* r = get_row_at_point(point);
1021
1022 if (!r)
1023 return QString();
1024
1025 if (point.y() > (int)(get_row_y(r) + (annotation_height_ / 2)))
1026 return QString();
1027
1028 deque<const Annotation*> annotations;
1029
1030 decode_signal_->get_annotation_subset(annotations, r->decode_row,
1031 current_segment_, sample_range.first, sample_range.second);
1032
1033 const Annotation* a = annotations.empty() ? nullptr : annotations[0];
1034
1035 // Create a string of the format "CLASS: VALUE"
1036 QString s;
1037 if (a) {
1038 if (!a->ann_class_description().isEmpty())
1039 s = a->ann_class_description() + ": ";
1040 s += a->annotations()->front();
1041 }
1042
1043 return s;
1044}
1045
1046void DecodeTrace::create_decoder_form(int index, shared_ptr<Decoder> &dec,
1047 QWidget *parent, QFormLayout *form)
1048{
1049 GlobalSettings settings;
1050
1051 assert(dec);
1052 const srd_decoder *const decoder = dec->get_srd_decoder();
1053 assert(decoder);
1054
1055 const bool decoder_deletable = index > 0;
1056
1057 pv::widgets::DecoderGroupBox *const group =
1058 new pv::widgets::DecoderGroupBox(
1059 QString::fromUtf8(decoder->name),
1060 tr("%1:\n%2").arg(QString::fromUtf8(decoder->longname),
1061 QString::fromUtf8(decoder->desc)),
1062 nullptr, decoder_deletable);
1063 group->set_decoder_visible(dec->visible());
1064
1065 if (decoder_deletable) {
1066 delete_mapper_.setMapping(group, index);
1067 connect(group, SIGNAL(delete_decoder()), &delete_mapper_, SLOT(map()));
1068 }
1069
1070 show_hide_mapper_.setMapping(group, index);
1071 connect(group, SIGNAL(show_hide_decoder()),
1072 &show_hide_mapper_, SLOT(map()));
1073
1074 QFormLayout *const decoder_form = new QFormLayout;
1075 group->add_layout(decoder_form);
1076
1077 const vector<DecodeChannel> channels = decode_signal_->get_channels();
1078
1079 // Add the channels
1080 for (const DecodeChannel& ch : channels) {
1081 // Ignore channels not part of the decoder we create the form for
1082 if (ch.decoder_ != dec)
1083 continue;
1084
1085 QComboBox *const combo = create_channel_selector(parent, &ch);
1086 QComboBox *const combo_init_state = create_channel_selector_init_state(parent, &ch);
1087
1088 channel_id_map_[combo] = ch.id;
1089 init_state_map_[combo_init_state] = ch.id;
1090
1091 connect(combo, SIGNAL(currentIndexChanged(int)),
1092 this, SLOT(on_channel_selected(int)));
1093 connect(combo_init_state, SIGNAL(currentIndexChanged(int)),
1094 this, SLOT(on_init_state_changed(int)));
1095
1096 QHBoxLayout *const hlayout = new QHBoxLayout;
1097 hlayout->addWidget(combo);
1098 hlayout->addWidget(combo_init_state);
1099
1100 if (!settings.value(GlobalSettings::Key_Dec_InitialStateConfigurable).toBool())
1101 combo_init_state->hide();
1102
1103 const QString required_flag = ch.is_optional ? QString() : QString("*");
1104 decoder_form->addRow(tr("<b>%1</b> (%2) %3")
1105 .arg(ch.name, ch.desc, required_flag), hlayout);
1106 }
1107
1108 // Add the options
1109 shared_ptr<binding::Decoder> binding(
1110 new binding::Decoder(decode_signal_, dec));
1111 binding->add_properties_to_form(decoder_form, true);
1112
1113 bindings_.push_back(binding);
1114
1115 form->addRow(group);
1116 decoder_forms_.push_back(group);
1117}
1118
1119QComboBox* DecodeTrace::create_channel_selector(QWidget *parent, const DecodeChannel *ch)
1120{
1121 const auto sigs(session_.signalbases());
1122
1123 // Sort signals in natural order
1124 vector< shared_ptr<data::SignalBase> > sig_list(sigs.begin(), sigs.end());
1125 sort(sig_list.begin(), sig_list.end(),
1126 [](const shared_ptr<data::SignalBase> &a,
1127 const shared_ptr<data::SignalBase> &b) {
1128 return strnatcasecmp(a->name().toStdString(),
1129 b->name().toStdString()) < 0; });
1130
1131 QComboBox *selector = new QComboBox(parent);
1132
1133 selector->addItem("-", QVariant::fromValue((void*)nullptr));
1134
1135 if (!ch->assigned_signal)
1136 selector->setCurrentIndex(0);
1137
1138 for (const shared_ptr<data::SignalBase> &b : sig_list) {
1139 assert(b);
1140 if (b->logic_data() && b->enabled()) {
1141 selector->addItem(b->name(), QVariant::fromValue(b));
1142
1143 if (ch->assigned_signal == b)
1144 selector->setCurrentIndex(selector->count() - 1);
1145 }
1146 }
1147
1148 return selector;
1149}
1150
1151QComboBox* DecodeTrace::create_channel_selector_init_state(QWidget *parent,
1152 const DecodeChannel *ch)
1153{
1154 QComboBox *selector = new QComboBox(parent);
1155
1156 selector->addItem("0", QVariant::fromValue((int)SRD_INITIAL_PIN_LOW));
1157 selector->addItem("1", QVariant::fromValue((int)SRD_INITIAL_PIN_HIGH));
1158 selector->addItem("X", QVariant::fromValue((int)SRD_INITIAL_PIN_SAME_AS_SAMPLE0));
1159
1160 selector->setCurrentIndex(ch->initial_pin_state);
1161
1162 selector->setToolTip("Initial (assumed) pin value before the first sample");
1163
1164 return selector;
1165}
1166
1167void DecodeTrace::export_annotations(deque<const Annotation*>& annotations) const
1168{
1169 GlobalSettings settings;
1170 const QString dir = settings.value("MainWindow/SaveDirectory").toString();
1171
1172 const QString file_name = QFileDialog::getSaveFileName(
1173 owner_->view(), tr("Export annotations"), dir, tr("Text Files (*.txt);;All Files (*)"));
1174
1175 if (file_name.isEmpty())
1176 return;
1177
1178 QString format = settings.value(GlobalSettings::Key_Dec_ExportFormat).toString();
1179 const QString quote = format.contains("%q") ? "\"" : "";
1180 format = format.remove("%q");
1181
1182 const bool has_sample_range = format.contains("%s");
1183 const bool has_row_name = format.contains("%r");
1184 const bool has_dec_name = format.contains("%d");
1185 const bool has_class_name = format.contains("%c");
1186 const bool has_first_ann_text = format.contains("%1");
1187 const bool has_all_ann_text = format.contains("%a");
1188
1189 QFile file(file_name);
1190 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
1191 QTextStream out_stream(&file);
1192
1193 for (const Annotation* ann : annotations) {
1194 QString out_text = format;
1195
1196 if (has_sample_range) {
1197 const QString sample_range = QString("%1-%2") \
1198 .arg(QString::number(ann->start_sample()), QString::number(ann->end_sample()));
1199 out_text = out_text.replace("%s", sample_range);
1200 }
1201
1202 if (has_dec_name)
1203 out_text = out_text.replace("%d",
1204 quote + QString::fromUtf8(ann->row()->decoder()->name()) + quote);
1205
1206 if (has_row_name) {
1207 const QString row_name = quote + ann->row()->description() + quote;
1208 out_text = out_text.replace("%r", row_name);
1209 }
1210
1211 if (has_class_name) {
1212 const QString class_name = quote + ann->ann_class_name() + quote;
1213 out_text = out_text.replace("%c", class_name);
1214 }
1215
1216 if (has_first_ann_text) {
1217 const QString first_ann_text = quote + ann->annotations()->front() + quote;
1218 out_text = out_text.replace("%1", first_ann_text);
1219 }
1220
1221 if (has_all_ann_text) {
1222 QString all_ann_text;
1223 for (const QString &s : *(ann->annotations()))
1224 all_ann_text = all_ann_text + quote + s + quote + ",";
1225 all_ann_text.chop(1);
1226
1227 out_text = out_text.replace("%a", all_ann_text);
1228 }
1229
1230 out_stream << out_text << '\n';
1231 }
1232
1233 if (out_stream.status() == QTextStream::Ok)
1234 return;
1235 }
1236
1237 QMessageBox msg(owner_->view());
1238 msg.setText(tr("Error") + "\n\n" + tr("File %1 could not be written to.").arg(file_name));
1239 msg.setStandardButtons(QMessageBox::Ok);
1240 msg.setIcon(QMessageBox::Warning);
1241 msg.exec();
1242}
1243
1244void DecodeTrace::initialize_row_widgets(DecodeTraceRow* r, unsigned int row_id)
1245{
1246 // Set colors and fixed widths
1247 QFontMetrics m(QApplication::font());
1248
1249 QPalette header_palette = owner_->view()->palette();
1250 QPalette selector_palette = owner_->view()->palette();
1251
1252 if (GlobalSettings::current_theme_is_dark()) {
1253 header_palette.setColor(QPalette::Background,
1254 QColor(255, 255, 255, ExpansionAreaHeaderAlpha));
1255 selector_palette.setColor(QPalette::Background,
1256 QColor(255, 255, 255, ExpansionAreaAlpha));
1257 } else {
1258 header_palette.setColor(QPalette::Background,
1259 QColor(0, 0, 0, ExpansionAreaHeaderAlpha));
1260 selector_palette.setColor(QPalette::Background,
1261 QColor(0, 0, 0, ExpansionAreaAlpha));
1262 }
1263
1264 const int w = m.boundingRect(r->decode_row->title()).width() + RowTitleMargin;
1265 r->title_width = w;
1266
1267 // Set up top-level container
1268 connect(r->container, SIGNAL(widgetResized(QWidget*)),
1269 this, SLOT(on_row_container_resized(QWidget*)));
1270
1271 QVBoxLayout* vlayout = new QVBoxLayout();
1272 r->container->setLayout(vlayout);
1273
1274 // Add header container
1275 vlayout->addWidget(r->header_container);
1276 vlayout->setContentsMargins(0, 0, 0, 0);
1277 vlayout->setSpacing(0);
1278 QHBoxLayout* header_container_layout = new QHBoxLayout();
1279 r->header_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
1280 r->header_container->setMinimumSize(0, default_row_height_);
1281 r->header_container->setLayout(header_container_layout);
1282 r->header_container->layout()->setContentsMargins(10, 2, 10, 2);
1283
1284 r->header_container->setAutoFillBackground(true);
1285 r->header_container->setPalette(header_palette);
1286
1287 // Add widgets inside the header container
1288 QCheckBox* cb = new QCheckBox();
1289 r->row_visibility_checkbox = cb;
1290 header_container_layout->addWidget(cb);
1291 cb->setText(tr("Show this row"));
1292 cb->setChecked(r->decode_row->visible());
1293
1294 row_show_hide_mapper_.setMapping(cb, row_id);
1295 connect(cb, SIGNAL(stateChanged(int)),
1296 &row_show_hide_mapper_, SLOT(map()));
1297
1298 QPushButton* btn = new QPushButton();
1299 header_container_layout->addWidget(btn);
1300 btn->setFlat(true);
1301 btn->setStyleSheet(":hover { background-color: palette(button); color: palette(button-text); border:0; }");
1302 btn->setText(tr("Show All"));
1303 btn->setProperty("decode_trace_row_ptr", QVariant::fromValue((void*)r));
1304 connect(btn, SIGNAL(clicked(bool)), this, SLOT(on_show_all_classes()));
1305
1306 btn = new QPushButton();
1307 header_container_layout->addWidget(btn);
1308 btn->setFlat(true);
1309 btn->setStyleSheet(":hover { background-color: palette(button); color: palette(button-text); border:0; }");
1310 btn->setText(tr("Hide All"));
1311 btn->setProperty("decode_trace_row_ptr", QVariant::fromValue((void*)r));
1312 connect(btn, SIGNAL(clicked(bool)), this, SLOT(on_hide_all_classes()));
1313
1314 header_container_layout->addStretch(); // To left-align the header widgets
1315
1316 // Add selector container
1317 vlayout->addWidget(r->selector_container);
1318 r->selector_container->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
1319 r->selector_container->setLayout(new FlowLayout(r->selector_container));
1320
1321 r->selector_container->setAutoFillBackground(true);
1322 r->selector_container->setPalette(selector_palette);
1323
1324 // Add all classes that can be toggled
1325 vector<AnnotationClass*> ann_classes = r->decode_row->ann_classes();
1326
1327 for (const AnnotationClass* ann_class : ann_classes) {
1328 cb = new QCheckBox();
1329 cb->setText(tr(ann_class->description));
1330 cb->setChecked(ann_class->visible());
1331
1332 int dim = ViewItemPaintParams::text_height() - 2;
1333 QPixmap pixmap(dim, dim);
1334 pixmap.fill(r->decode_row->get_class_color(ann_class->id));
1335 cb->setIcon(pixmap);
1336
1337 r->selector_container->layout()->addWidget(cb);
1338 r->selectors.push_back(cb);
1339
1340 cb->setProperty("ann_class_ptr", QVariant::fromValue((void*)ann_class));
1341 cb->setProperty("decode_trace_row_ptr", QVariant::fromValue((void*)r));
1342
1343 class_show_hide_mapper_.setMapping(cb, cb);
1344 connect(cb, SIGNAL(stateChanged(int)),
1345 &class_show_hide_mapper_, SLOT(map()));
1346 }
1347}
1348
1349void DecodeTrace::update_rows()
1350{
1351 if (!owner_)
1352 return;
1353
1354 lock_guard<mutex> lock(row_modification_mutex_);
1355
1356 for (DecodeTraceRow& r : rows_)
1357 r.exists = false;
1358
1359 unsigned int row_id = 0;
1360 for (Row* decode_row : decode_signal_->get_rows()) {
1361 // Find row in our list
1362 auto r_it = find_if(rows_.begin(), rows_.end(),
1363 [&](DecodeTraceRow& r){ return r.decode_row == decode_row; });
1364
1365 DecodeTraceRow* r = nullptr;
1366 if (r_it == rows_.end()) {
1367 // Row doesn't exist yet, create and append it
1368 DecodeTraceRow nr;
1369 nr.decode_row = decode_row;
1370 nr.decode_row->set_base_color(base_->color());
1371 nr.height = default_row_height_;
1372 nr.expanded_height = default_row_height_;
1373 nr.currently_visible = false;
1374 nr.has_hidden_classes = decode_row->has_hidden_classes();
1375 nr.expand_marker_highlighted = false;
1376 nr.expanding = false;
1377 nr.expanded = false;
1378 nr.collapsing = false;
1379 nr.expand_marker_shape = default_marker_shape_;
1380 nr.container = new ContainerWidget(owner_->view()->scrollarea());
1381 nr.header_container = new QWidget(nr.container);
1382 nr.selector_container = new QWidget(nr.container);
1383
1384 rows_.push_back(nr);
1385 r = &rows_.back();
1386 initialize_row_widgets(r, row_id);
1387 } else
1388 r = &(*r_it);
1389
1390 r->exists = true;
1391 row_id++;
1392 }
1393
1394 // If there's only one row, it must not be hidden or else it can't be un-hidden
1395 if (row_id == 1)
1396 rows_.front().row_visibility_checkbox->setEnabled(false);
1397
1398 // Remove any rows that no longer exist, obeying that iterators are invalidated
1399 bool any_exists;
1400 do {
1401 any_exists = false;
1402
1403 for (unsigned int i = 0; i < rows_.size(); i++)
1404 if (!rows_[i].exists) {
1405 delete rows_[i].row_visibility_checkbox;
1406
1407 for (QCheckBox* cb : rows_[i].selectors)
1408 delete cb;
1409
1410 delete rows_[i].selector_container;
1411 delete rows_[i].header_container;
1412 delete rows_[i].container;
1413
1414 rows_.erase(rows_.begin() + i);
1415 any_exists = true;
1416 break;
1417 }
1418 } while (any_exists);
1419}
1420
1421void DecodeTrace::set_row_expanded(DecodeTraceRow* r)
1422{
1423 r->height = r->expanded_height;
1424 r->expanding = false;
1425 r->expanded = true;
1426
1427 // For details on this, see on_animation_timer()
1428 r->expand_marker_shape.setPoint(0, 0, 0);
1429 r->expand_marker_shape.setPoint(1, ArrowSize, ArrowSize);
1430 r->expand_marker_shape.setPoint(2, 2*ArrowSize, 0);
1431
1432 r->container->resize(owner_->view()->viewport()->width() - r->container->pos().x(),
1433 r->height - 2 * default_row_height_);
1434}
1435
1436void DecodeTrace::set_row_collapsed(DecodeTraceRow* r)
1437{
1438 r->height = default_row_height_;
1439 r->collapsing = false;
1440 r->expanded = false;
1441 r->expand_marker_shape = default_marker_shape_;
1442 r->container->setVisible(false);
1443
1444 r->container->resize(owner_->view()->viewport()->width() - r->container->pos().x(),
1445 r->height - 2 * default_row_height_);
1446}
1447
1448void DecodeTrace::update_expanded_rows()
1449{
1450 for (DecodeTraceRow& r : rows_) {
1451 if (r.expanding || r.expanded)
1452 r.expanded_height = 2 * default_row_height_ + r.container->sizeHint().height();
1453
1454 if (r.expanded)
1455 r.height = r.expanded_height;
1456
1457 int x = 2 * ArrowSize;
1458 int y = get_row_y(&r) + default_row_height_;
1459 // Only update the position if it actually changes
1460 if ((x != r.container->pos().x()) || (y != r.container->pos().y()))
1461 r.container->move(x, y);
1462
1463 int w = owner_->view()->viewport()->width() - x;
1464 int h = r.height - 2 * default_row_height_;
1465 // Only update the dimension if they actually change
1466 if ((w != r.container->sizeHint().width()) || (h != r.container->sizeHint().height()))
1467 r.container->resize(w, h);
1468 }
1469}
1470
1471void DecodeTrace::on_setting_changed(const QString &key, const QVariant &value)
1472{
1473 Trace::on_setting_changed(key, value);
1474
1475 if (key == GlobalSettings::Key_Dec_AlwaysShowAllRows)
1476 always_show_all_rows_ = value.toBool();
1477}
1478
1479void DecodeTrace::on_color_changed(const QColor &color)
1480{
1481 for (DecodeTraceRow& r : rows_)
1482 r.decode_row->set_base_color(color);
1483
1484 if (owner_)
1485 owner_->row_item_appearance_changed(false, true);
1486}
1487
1488void DecodeTrace::on_new_annotations()
1489{
1490 if (!delayed_trace_updater_.isActive())
1491 delayed_trace_updater_.start();
1492}
1493
1494void DecodeTrace::on_delayed_trace_update()
1495{
1496 if (owner_)
1497 owner_->row_item_appearance_changed(false, true);
1498}
1499
1500void DecodeTrace::on_decode_reset()
1501{
1502 update_rows();
1503
1504 if (owner_)
1505 owner_->row_item_appearance_changed(false, true);
1506}
1507
1508void DecodeTrace::on_decode_finished()
1509{
1510 if (owner_)
1511 owner_->row_item_appearance_changed(false, true);
1512}
1513
1514void DecodeTrace::on_pause_decode()
1515{
1516 if (decode_signal_->is_paused())
1517 decode_signal_->resume_decode();
1518 else
1519 decode_signal_->pause_decode();
1520}
1521
1522void DecodeTrace::on_delete()
1523{
1524 session_.remove_decode_signal(decode_signal_);
1525}
1526
1527void DecodeTrace::on_channel_selected(int)
1528{
1529 QComboBox *cb = qobject_cast<QComboBox*>(QObject::sender());
1530
1531 // Determine signal that was selected
1532 shared_ptr<data::SignalBase> signal =
1533 cb->itemData(cb->currentIndex()).value<shared_ptr<data::SignalBase>>();
1534
1535 // Determine decode channel ID this combo box is the channel selector for
1536 const uint16_t id = channel_id_map_.at(cb);
1537
1538 decode_signal_->assign_signal(id, signal);
1539}
1540
1541void DecodeTrace::on_channels_updated()
1542{
1543 if (owner_)
1544 owner_->row_item_appearance_changed(false, true);
1545}
1546
1547void DecodeTrace::on_init_state_changed(int)
1548{
1549 QComboBox *cb = qobject_cast<QComboBox*>(QObject::sender());
1550
1551 // Determine inital pin state that was selected
1552 int init_state = cb->itemData(cb->currentIndex()).value<int>();
1553
1554 // Determine decode channel ID this combo box is the channel selector for
1555 const uint16_t id = init_state_map_.at(cb);
1556
1557 decode_signal_->set_initial_pin_state(id, init_state);
1558}
1559
1560void DecodeTrace::on_stack_decoder(srd_decoder *decoder)
1561{
1562 decode_signal_->stack_decoder(decoder);
1563 update_rows();
1564
1565 create_popup_form();
1566}
1567
1568void DecodeTrace::on_delete_decoder(int index)
1569{
1570 decode_signal_->remove_decoder(index);
1571 update_rows();
1572
1573 owner_->extents_changed(false, true);
1574
1575 create_popup_form();
1576}
1577
1578void DecodeTrace::on_show_hide_decoder(int index)
1579{
1580 const bool state = decode_signal_->toggle_decoder_visibility(index);
1581
1582 assert(index < (int)decoder_forms_.size());
1583 decoder_forms_[index]->set_decoder_visible(state);
1584
1585 if (!state)
1586 owner_->extents_changed(false, true);
1587
1588 owner_->row_item_appearance_changed(false, true);
1589}
1590
1591void DecodeTrace::on_show_hide_row(int row_id)
1592{
1593 if (row_id >= (int)rows_.size())
1594 return;
1595
1596 rows_[row_id].decode_row->set_visible(!rows_[row_id].decode_row->visible());
1597
1598 if (!rows_[row_id].decode_row->visible())
1599 set_row_collapsed(&rows_[row_id]);
1600
1601 owner_->extents_changed(false, true);
1602 owner_->row_item_appearance_changed(false, true);
1603}
1604
1605void DecodeTrace::on_show_hide_class(QWidget* sender)
1606{
1607 void* ann_class_ptr = sender->property("ann_class_ptr").value<void*>();
1608 assert(ann_class_ptr);
1609 AnnotationClass* ann_class = (AnnotationClass*)ann_class_ptr;
1610
1611 ann_class->set_visible(!ann_class->visible());
1612
1613 void* row_ptr = sender->property("decode_trace_row_ptr").value<void*>();
1614 assert(row_ptr);
1615 DecodeTraceRow* row = (DecodeTraceRow*)row_ptr;
1616
1617 row->has_hidden_classes = row->decode_row->has_hidden_classes();
1618
1619 owner_->row_item_appearance_changed(false, true);
1620}
1621
1622void DecodeTrace::on_show_all_classes()
1623{
1624 void* row_ptr = QObject::sender()->property("decode_trace_row_ptr").value<void*>();
1625 assert(row_ptr);
1626 DecodeTraceRow* row = (DecodeTraceRow*)row_ptr;
1627
1628 for (QCheckBox* cb : row->selectors)
1629 cb->setChecked(true);
1630
1631 row->has_hidden_classes = false;
1632
1633 owner_->row_item_appearance_changed(false, true);
1634}
1635
1636void DecodeTrace::on_hide_all_classes()
1637{
1638 void* row_ptr = QObject::sender()->property("decode_trace_row_ptr").value<void*>();
1639 assert(row_ptr);
1640 DecodeTraceRow* row = (DecodeTraceRow*)row_ptr;
1641
1642 for (QCheckBox* cb : row->selectors)
1643 cb->setChecked(false);
1644
1645 row->has_hidden_classes = true;
1646
1647 owner_->row_item_appearance_changed(false, true);
1648}
1649
1650void DecodeTrace::on_row_container_resized(QWidget* sender)
1651{
1652 sender->update();
1653
1654 owner_->extents_changed(false, true);
1655 owner_->row_item_appearance_changed(false, true);
1656}
1657
1658void DecodeTrace::on_copy_annotation_to_clipboard()
1659{
1660 if (!selected_row_)
1661 return;
1662
1663 deque<const Annotation*> annotations;
1664
1665 decode_signal_->get_annotation_subset(annotations, selected_row_,
1666 current_segment_, selected_sample_range_.first, selected_sample_range_.first);
1667
1668 if (annotations.empty())
1669 return;
1670
1671 QClipboard *clipboard = QApplication::clipboard();
1672 clipboard->setText(annotations.front()->annotations()->front(), QClipboard::Clipboard);
1673
1674 if (clipboard->supportsSelection())
1675 clipboard->setText(annotations.front()->annotations()->front(), QClipboard::Selection);
1676}
1677
1678void DecodeTrace::on_export_row()
1679{
1680 selected_sample_range_ = make_pair(0, numeric_limits<uint64_t>::max());
1681 on_export_row_from_here();
1682}
1683
1684void DecodeTrace::on_export_all_rows()
1685{
1686 selected_sample_range_ = make_pair(0, numeric_limits<uint64_t>::max());
1687 on_export_all_rows_from_here();
1688}
1689
1690void DecodeTrace::on_export_row_with_cursor()
1691{
1692 const View *view = owner_->view();
1693 assert(view);
1694
1695 if (!view->cursors()->enabled())
1696 return;
1697
1698 const double samplerate = session_.get_samplerate();
1699
1700 const pv::util::Timestamp& start_time = view->cursors()->first()->time();
1701 const pv::util::Timestamp& end_time = view->cursors()->second()->time();
1702
1703 const uint64_t start_sample = (uint64_t)max(
1704 0.0, start_time.convert_to<double>() * samplerate);
1705 const uint64_t end_sample = (uint64_t)max(
1706 0.0, end_time.convert_to<double>() * samplerate);
1707
1708 // Are both cursors negative and thus were clamped to 0?
1709 if ((start_sample == 0) && (end_sample == 0))
1710 return;
1711
1712 selected_sample_range_ = make_pair(start_sample, end_sample);
1713 on_export_row_from_here();
1714}
1715
1716void DecodeTrace::on_export_all_rows_with_cursor()
1717{
1718 const View *view = owner_->view();
1719 assert(view);
1720
1721 if (!view->cursors()->enabled())
1722 return;
1723
1724 const double samplerate = session_.get_samplerate();
1725
1726 const pv::util::Timestamp& start_time = view->cursors()->first()->time();
1727 const pv::util::Timestamp& end_time = view->cursors()->second()->time();
1728
1729 const uint64_t start_sample = (uint64_t)max(
1730 0.0, start_time.convert_to<double>() * samplerate);
1731 const uint64_t end_sample = (uint64_t)max(
1732 0.0, end_time.convert_to<double>() * samplerate);
1733
1734 // Are both cursors negative and thus were clamped to 0?
1735 if ((start_sample == 0) && (end_sample == 0))
1736 return;
1737
1738 selected_sample_range_ = make_pair(start_sample, end_sample);
1739 on_export_all_rows_from_here();
1740}
1741
1742void DecodeTrace::on_export_row_from_here()
1743{
1744 if (!selected_row_)
1745 return;
1746
1747 deque<const Annotation*> annotations;
1748
1749 decode_signal_->get_annotation_subset(annotations, selected_row_,
1750 current_segment_, selected_sample_range_.first, selected_sample_range_.second);
1751
1752 if (annotations.empty())
1753 return;
1754
1755 export_annotations(annotations);
1756}
1757
1758void DecodeTrace::on_export_all_rows_from_here()
1759{
1760 deque<const Annotation*> annotations;
1761
1762 decode_signal_->get_annotation_subset(annotations, current_segment_,
1763 selected_sample_range_.first, selected_sample_range_.second);
1764
1765 if (!annotations.empty())
1766 export_annotations(annotations);
1767}
1768
1769void DecodeTrace::on_animation_timer()
1770{
1771 bool animation_finished = true;
1772
1773 for (DecodeTraceRow& r : rows_) {
1774 if (!(r.expanding || r.collapsing))
1775 continue;
1776
1777 unsigned int height_delta = r.expanded_height - default_row_height_;
1778
1779 if (r.expanding) {
1780 if (r.height < r.expanded_height) {
1781 r.anim_height += height_delta / (float)AnimationDurationInTicks;
1782 r.height = min((int)r.anim_height, (int)r.expanded_height);
1783 r.anim_shape += ArrowSize / (float)AnimationDurationInTicks;
1784 animation_finished = false;
1785 } else
1786 set_row_expanded(&r);
1787 }
1788
1789 if (r.collapsing) {
1790 if (r.height > default_row_height_) {
1791 r.anim_height -= height_delta / (float)AnimationDurationInTicks;
1792 r.height = max((int)r.anim_height, (int)0);
1793 r.anim_shape -= ArrowSize / (float)AnimationDurationInTicks;
1794 animation_finished = false;
1795 } else
1796 set_row_collapsed(&r);
1797 }
1798
1799 // The expansion marker shape switches between
1800 // 0/-A, A/0, 0/A (default state; anim_shape=0) and
1801 // 0/ 0, A/A, 2A/0 (expanded state; anim_shape=ArrowSize)
1802
1803 r.expand_marker_shape.setPoint(0, 0, -ArrowSize + r.anim_shape);
1804 r.expand_marker_shape.setPoint(1, ArrowSize, r.anim_shape);
1805 r.expand_marker_shape.setPoint(2, 2*r.anim_shape, ArrowSize - r.anim_shape);
1806 }
1807
1808 if (animation_finished)
1809 animation_timer_.stop();
1810
1811 owner_->extents_changed(false, true);
1812 owner_->row_item_appearance_changed(false, true);
1813}
1814
1815void DecodeTrace::on_hide_hidden_rows()
1816{
1817 // Make all hidden traces invisible again unless the user is hovering over a row name
1818 bool any_highlighted = false;
1819
1820 for (DecodeTraceRow& r : rows_)
1821 if (r.expand_marker_highlighted)
1822 any_highlighted = true;
1823
1824 if (!any_highlighted) {
1825 show_hidden_rows_ = false;
1826
1827 owner_->extents_changed(false, true);
1828 owner_->row_item_appearance_changed(false, true);
1829 }
1830}
1831
1832} // namespace trace
1833} // namespace views
1834} // namespace pv