2 * This file is part of the PulseView project.
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
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.
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.
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/>.
21 #include <libsigrokdecode/libsigrokdecode.h>
30 #include <boost/functional/hash.hpp>
33 #include <QApplication>
36 #include <QFileDialog>
37 #include <QFormLayout>
40 #include <QMessageBox>
41 #include <QPushButton>
42 #include <QTextStream>
45 #include "decodetrace.hpp"
47 #include "viewport.hpp"
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>
62 using std::lock_guard;
66 using std::numeric_limits;
67 using std::out_of_range;
69 using std::shared_ptr;
73 using pv::data::decode::Annotation;
74 using pv::data::decode::Row;
75 using pv::data::decode::DecodeChannel;
76 using pv::data::DecodeSignal;
83 #define DECODETRACE_COLOR_SATURATION (180) /* 0-255 */
84 #define DECODETRACE_COLOR_VALUE (170) /* 0-255 */
86 const QColor DecodeTrace::ErrorBgColor = QColor(0xEF, 0x29, 0x29);
87 const QColor DecodeTrace::NoDecodeColor = QColor(0x88, 0x8A, 0x85);
89 const int DecodeTrace::ArrowSize = 6;
90 const double DecodeTrace::EndCapWidth = 5;
91 const int DecodeTrace::RowTitleMargin = 7;
92 const int DecodeTrace::DrawPadding = 100;
94 const int DecodeTrace::MaxTraceUpdateRate = 1; // No more than 1 Hz
95 const unsigned int DecodeTrace::AnimationDurationInTicks = 7;
97 DecodeTrace::DecodeTrace(pv::Session &session,
98 shared_ptr<data::SignalBase> signalbase, int index) :
101 max_visible_rows_(0),
102 delete_mapper_(this),
103 show_hide_mapper_(this)
105 decode_signal_ = dynamic_pointer_cast<data::DecodeSignal>(base_);
107 GlobalSettings settings;
108 always_show_all_rows_ = settings.value(GlobalSettings::Key_Dec_AlwaysShowAllRows).toBool();
110 GlobalSettings::add_change_handler(this);
112 // Determine shortest string we want to see displayed in full
113 QFontMetrics m(QApplication::font());
114 min_useful_label_width_ = m.width("XX"); // e.g. two hex characters
116 default_row_height_ = (ViewItemPaintParams::text_height() * 6) / 4;
117 annotation_height_ = (ViewItemPaintParams::text_height() * 5) / 4;
119 // For the base color, we want to start at a very different color for
120 // every decoder stack, so multiply the index with a number that is
121 // rather close to 180 degrees of the color circle but not a dividend of 360
122 // Note: The offset equals the color of the first annotation
124 const int h = (120 + 160 * index) % 360;
125 const int s = DECODETRACE_COLOR_SATURATION;
126 const int v = DECODETRACE_COLOR_VALUE;
127 color.setHsv(h, s, v);
128 base_->set_color(color);
130 connect(decode_signal_.get(), SIGNAL(new_annotations()),
131 this, SLOT(on_new_annotations()));
132 connect(decode_signal_.get(), SIGNAL(decode_reset()),
133 this, SLOT(on_decode_reset()));
134 connect(decode_signal_.get(), SIGNAL(decode_finished()),
135 this, SLOT(on_decode_finished()));
136 connect(decode_signal_.get(), SIGNAL(channels_updated()),
137 this, SLOT(on_channels_updated()));
139 connect(&delete_mapper_, SIGNAL(mapped(int)),
140 this, SLOT(on_delete_decoder(int)));
141 connect(&show_hide_mapper_, SIGNAL(mapped(int)),
142 this, SLOT(on_show_hide_decoder(int)));
144 connect(&delayed_trace_updater_, SIGNAL(timeout()),
145 this, SLOT(on_delayed_trace_update()));
146 delayed_trace_updater_.setSingleShot(true);
147 delayed_trace_updater_.setInterval(1000 / MaxTraceUpdateRate);
149 connect(&animation_timer_, SIGNAL(timeout()),
150 this, SLOT(on_animation_timer()));
151 animation_timer_.setInterval(1000 / 50);
153 default_marker_shape_ << QPoint(0, -ArrowSize);
154 default_marker_shape_ << QPoint(ArrowSize, 0);
155 default_marker_shape_ << QPoint(0, ArrowSize);
158 DecodeTrace::~DecodeTrace()
160 GlobalSettings::remove_change_handler(this);
162 for (RowData& r : rows_)
166 bool DecodeTrace::enabled() const
171 shared_ptr<data::SignalBase> DecodeTrace::base() const
176 pair<int, int> DecodeTrace::v_extents() const
178 // Make an empty decode trace appear symmetrical
179 if (max_visible_rows_ == 0)
180 return make_pair(-default_row_height_, default_row_height_);
182 unsigned int height = 0;
183 for (const RowData& r : rows_)
184 if (r.currently_visible)
187 return make_pair(-default_row_height_, height);
190 void DecodeTrace::paint_back(QPainter &p, ViewItemPaintParams &pp)
192 Trace::paint_back(p, pp);
193 paint_axis(p, pp, get_visual_y());
196 void DecodeTrace::paint_mid(QPainter &p, ViewItemPaintParams &pp)
198 lock_guard<mutex> lock(row_modification_mutex_);
200 // Set default pen to allow for text width calculation
203 pair<uint64_t, uint64_t> sample_range = get_view_sample_range(pp.left(), pp.right());
205 // Just because the view says we see a certain sample range it
206 // doesn't mean we have this many decoded samples, too, so crop
207 // the range to what has been decoded already
208 sample_range.second = min((int64_t)sample_range.second,
209 decode_signal_->get_decoded_sample_count(current_segment_, false));
211 for (RowData& r : rows_)
212 r.currently_visible = false;
214 int y = get_visual_y();
216 for (RowData& r : rows_) {
217 // If an entire decoder is hidden, we don't want to fetch annotations
218 if (!r.decode_row.decoder()->shown()) {
219 r.currently_visible = false;
223 vector<Annotation> annotations;
224 decode_signal_->get_annotation_subset(annotations, r.decode_row,
225 current_segment_, sample_range.first, sample_range.second);
227 // Show row if there are visible annotations or when user wants to see
228 // all rows that have annotations somewhere and this one is one of them
229 size_t ann_count = decode_signal_->get_annotation_count(r.decode_row, current_segment_);
230 r.currently_visible = !annotations.empty() || (always_show_all_rows_ && (ann_count > 0));
232 if (r.currently_visible) {
233 draw_annotations(annotations, p, annotation_height_, pp, y,
234 get_row_color(r.decode_row.index()), r.title_width);
240 draw_unresolved_period(p, annotation_height_, pp.left(), pp.right());
242 if (visible_rows_ > max_visible_rows_) {
243 max_visible_rows_ = visible_rows_;
245 // Call order is important, otherwise the lazy event handler won't work
246 owner_->extents_changed(false, true);
247 owner_->row_item_appearance_changed(false, true);
250 const QString err = decode_signal_->error_message();
252 draw_error(p, err, pp);
255 void DecodeTrace::paint_fore(QPainter &p, ViewItemPaintParams &pp)
257 unsigned int y = get_visual_y();
259 for (const RowData& r : rows_) {
260 if (!r.currently_visible)
263 p.setPen(QPen(Qt::NoPen));
265 if (r.expand_marker_highlighted)
266 p.setBrush(QApplication::palette().brush(QPalette::Highlight));
268 p.setBrush(QApplication::palette().brush(QPalette::WindowText));
270 // Draw expansion marker
271 QPolygon marker(r.expand_marker_shape);
272 marker.translate(pp.left(), y);
273 p.drawPolygon(marker);
275 p.setBrush(QApplication::palette().brush(QPalette::WindowText));
277 const QRect text_rect(pp.left() + ArrowSize * 2, y - r.height / 2,
278 pp.right() - pp.left(), r.height);
279 const QString h(r.decode_row.title());
280 const int f = Qt::AlignLeft | Qt::AlignVCenter |
284 p.setPen(QApplication::palette().color(QPalette::Base));
285 for (int dx = -1; dx <= 1; dx++)
286 for (int dy = -1; dy <= 1; dy++)
287 if (dx != 0 && dy != 0)
288 p.drawText(text_rect.translated(dx, dy), f, h);
291 p.setPen(QApplication::palette().color(QPalette::WindowText));
292 p.drawText(text_rect, f, h);
297 if (show_hover_marker_)
298 paint_hover_marker(p);
301 void DecodeTrace::update_stack_button()
303 const vector< shared_ptr<data::decode::Decoder> > &stack = decode_signal_->decoder_stack();
305 // Only show decoders in the menu that can be stacked onto the last one in the stack
306 if (!stack.empty()) {
307 const srd_decoder* d = stack.back()->decoder();
310 pv::widgets::DecoderMenu *const decoder_menu =
311 new pv::widgets::DecoderMenu(stack_button_, (const char*)(d->outputs->data));
312 connect(decoder_menu, SIGNAL(decoder_selected(srd_decoder*)),
313 this, SLOT(on_stack_decoder(srd_decoder*)));
315 decoder_menu->setStyleSheet("QMenu { menu-scrollable: 1; }");
317 stack_button_->setMenu(decoder_menu);
318 stack_button_->show();
323 // No decoders available for stacking
324 stack_button_->setMenu(nullptr);
325 stack_button_->hide();
328 void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form)
330 using pv::data::decode::Decoder;
334 // Add the standard options
335 Trace::populate_popup_form(parent, form);
337 // Add the decoder options
339 channel_id_map_.clear();
340 init_state_map_.clear();
341 decoder_forms_.clear();
343 const vector< shared_ptr<Decoder> > &stack = decode_signal_->decoder_stack();
346 QLabel *const l = new QLabel(
347 tr("<p><i>No decoders in the stack</i></p>"));
348 l->setAlignment(Qt::AlignCenter);
351 auto iter = stack.cbegin();
352 for (int i = 0; i < (int)stack.size(); i++, iter++) {
353 shared_ptr<Decoder> dec(*iter);
354 create_decoder_form(i, dec, parent, form);
357 form->addRow(new QLabel(
358 tr("<i>* Required channels</i>"), parent));
361 // Add stacking button
362 stack_button_ = new QPushButton(tr("Stack Decoder"), parent);
363 stack_button_->setToolTip(tr("Stack a higher-level decoder on top of this one"));
364 update_stack_button();
366 QHBoxLayout *stack_button_box = new QHBoxLayout;
367 stack_button_box->addWidget(stack_button_, 0, Qt::AlignRight);
368 form->addRow(stack_button_box);
371 QMenu* DecodeTrace::create_header_context_menu(QWidget *parent)
373 QMenu *const menu = Trace::create_header_context_menu(parent);
375 menu->addSeparator();
377 QAction *const del = new QAction(tr("Delete"), this);
378 del->setShortcuts(QKeySequence::Delete);
379 connect(del, SIGNAL(triggered()), this, SLOT(on_delete()));
380 menu->addAction(del);
385 QMenu* DecodeTrace::create_view_context_menu(QWidget *parent, QPoint &click_pos)
387 // Get entries from default menu before adding our own
388 QMenu *const menu = new QMenu(parent);
390 QMenu* default_menu = Trace::create_view_context_menu(parent, click_pos);
392 for (QAction *action : default_menu->actions()) { // clazy:exclude=range-loop
393 menu->addAction(action);
394 if (action->parent() == default_menu)
395 action->setParent(menu);
399 // Add separator if needed
400 if (menu->actions().length() > 0)
401 menu->addSeparator();
404 selected_row_ = nullptr;
405 const RowData* r = get_row_at_point(click_pos);
407 selected_row_ = &(r->decode_row);
409 const View *const view = owner_->view();
411 QPoint pos = view->viewport()->mapFrom(parent, click_pos);
413 // Default sample range is "from here"
414 const pair<uint64_t, uint64_t> sample_range = get_view_sample_range(pos.x(), pos.x() + 1);
415 selected_sample_range_ = make_pair(sample_range.first, numeric_limits<uint64_t>::max());
417 if (decode_signal_->is_paused()) {
418 QAction *const resume =
419 new QAction(tr("Resume decoding"), this);
420 resume->setIcon(QIcon::fromTheme("media-playback-start",
421 QIcon(":/icons/media-playback-start.png")));
422 connect(resume, SIGNAL(triggered()), this, SLOT(on_pause_decode()));
423 menu->addAction(resume);
425 QAction *const pause =
426 new QAction(tr("Pause decoding"), this);
427 pause->setIcon(QIcon::fromTheme("media-playback-pause",
428 QIcon(":/icons/media-playback-pause.png")));
429 connect(pause, SIGNAL(triggered()), this, SLOT(on_pause_decode()));
430 menu->addAction(pause);
433 QAction *const copy_annotation_to_clipboard =
434 new QAction(tr("Copy annotation text to clipboard"), this);
435 copy_annotation_to_clipboard->setIcon(QIcon::fromTheme("edit-paste",
436 QIcon(":/icons/edit-paste.svg")));
437 connect(copy_annotation_to_clipboard, SIGNAL(triggered()), this, SLOT(on_copy_annotation_to_clipboard()));
438 menu->addAction(copy_annotation_to_clipboard);
440 menu->addSeparator();
442 QAction *const export_all_rows =
443 new QAction(tr("Export all annotations"), this);
444 export_all_rows->setIcon(QIcon::fromTheme("document-save-as",
445 QIcon(":/icons/document-save-as.png")));
446 connect(export_all_rows, SIGNAL(triggered()), this, SLOT(on_export_all_rows()));
447 menu->addAction(export_all_rows);
449 QAction *const export_row =
450 new QAction(tr("Export all annotations for this row"), this);
451 export_row->setIcon(QIcon::fromTheme("document-save-as",
452 QIcon(":/icons/document-save-as.png")));
453 connect(export_row, SIGNAL(triggered()), this, SLOT(on_export_row()));
454 menu->addAction(export_row);
456 menu->addSeparator();
458 QAction *const export_all_rows_from_here =
459 new QAction(tr("Export all annotations, starting here"), this);
460 export_all_rows_from_here->setIcon(QIcon::fromTheme("document-save-as",
461 QIcon(":/icons/document-save-as.png")));
462 connect(export_all_rows_from_here, SIGNAL(triggered()), this, SLOT(on_export_all_rows_from_here()));
463 menu->addAction(export_all_rows_from_here);
465 QAction *const export_row_from_here =
466 new QAction(tr("Export annotations for this row, starting here"), this);
467 export_row_from_here->setIcon(QIcon::fromTheme("document-save-as",
468 QIcon(":/icons/document-save-as.png")));
469 connect(export_row_from_here, SIGNAL(triggered()), this, SLOT(on_export_row_from_here()));
470 menu->addAction(export_row_from_here);
472 menu->addSeparator();
474 QAction *const export_all_rows_with_cursor =
475 new QAction(tr("Export all annotations within cursor range"), this);
476 export_all_rows_with_cursor->setIcon(QIcon::fromTheme("document-save-as",
477 QIcon(":/icons/document-save-as.png")));
478 connect(export_all_rows_with_cursor, SIGNAL(triggered()), this, SLOT(on_export_all_rows_with_cursor()));
479 menu->addAction(export_all_rows_with_cursor);
481 QAction *const export_row_with_cursor =
482 new QAction(tr("Export annotations for this row within cursor range"), this);
483 export_row_with_cursor->setIcon(QIcon::fromTheme("document-save-as",
484 QIcon(":/icons/document-save-as.png")));
485 connect(export_row_with_cursor, SIGNAL(triggered()), this, SLOT(on_export_row_with_cursor()));
486 menu->addAction(export_row_with_cursor);
488 if (!view->cursors()->enabled()) {
489 export_all_rows_with_cursor->setEnabled(false);
490 export_row_with_cursor->setEnabled(false);
496 void DecodeTrace::delete_pressed()
501 void DecodeTrace::hover_point_changed(const QPoint &hp)
503 Trace::hover_point_changed(hp);
507 RowData* hover_row = get_row_at_point(hp);
509 // Row expansion marker handling
510 for (RowData& r : rows_)
511 r.expand_marker_highlighted = false;
514 int row_y = get_row_y(hover_row);
515 if ((hp.x() > 0) && (hp.x() < 2 * ArrowSize) &&
516 (hp.y() > (int)(row_y - ArrowSize)) && (hp.y() < (int)(row_y + ArrowSize)))
517 hover_row->expand_marker_highlighted = true;
522 QString ann = get_annotation_at_point(hp);
524 if (!ann.isEmpty()) {
525 QFontMetrics m(QToolTip::font());
526 const QRect text_size = m.boundingRect(QRect(), 0, ann);
528 // This is OS-specific and unfortunately we can't query it, so
529 // use an approximation to at least try to minimize the error.
530 const int padding = default_row_height_ + 8;
532 // Make sure the tool tip doesn't overlap with the mouse cursor.
533 // If it did, the tool tip would constantly hide and re-appear.
534 // We also push it up by one row so that it appears above the
535 // decode trace, not below.
537 p.setX(hp.x() - (text_size.width() / 2) - padding);
539 p.setY(get_row_y(hover_row) - default_row_height_ -
540 text_size.height() - padding);
542 const View *const view = owner_->view();
544 QToolTip::showText(view->viewport()->mapToGlobal(p), ann);
547 QToolTip::hideText();
550 QToolTip::hideText();
553 void DecodeTrace::mouse_left_press_event(const QMouseEvent* event)
555 // Handle row expansion marker
556 for (RowData& r : rows_) {
557 if (!r.expand_marker_highlighted)
560 unsigned int y = get_row_y(&r);
561 if ((event->x() > 0) && (event->x() <= (int)(ArrowSize + 3)) &&
562 (event->y() > (int)(y - (default_row_height_ / 2))) &&
563 (event->y() <= (int)(y + (default_row_height_ / 2)))) {
568 r.anim_shape = ArrowSize;
572 r.container->setVisible(true);
575 r.animation_step = 0;
576 r.anim_height = r.height;
578 r.container->move(2 * ArrowSize,
579 get_row_y(&r) + default_row_height_);
581 animation_timer_.start();
586 void DecodeTrace::draw_annotations(vector<pv::data::decode::Annotation> annotations,
587 QPainter &p, int h, const ViewItemPaintParams &pp, int y,
588 QColor row_color, int row_title_width)
590 using namespace pv::data::decode;
592 Annotation::Class block_class = 0;
593 bool block_class_uniform = true;
594 qreal block_start = 0;
595 int block_ann_count = 0;
597 const Annotation *prev_ann;
598 qreal prev_end = INT_MIN;
602 double samples_per_pixel, pixels_offset;
603 tie(pixels_offset, samples_per_pixel) =
604 get_pixels_offset_samples_per_pixel();
606 // Sort the annotations by start sample so that decoders
607 // can't confuse us by creating annotations out of order
608 stable_sort(annotations.begin(), annotations.end(),
609 [](const Annotation &a, const Annotation &b) {
610 return a.start_sample() < b.start_sample(); });
612 // Gather all annotations that form a visual "block" and draw them as such
613 for (const Annotation &a : annotations) {
615 const qreal abs_a_start = a.start_sample() / samples_per_pixel;
616 const qreal abs_a_end = a.end_sample() / samples_per_pixel;
618 const qreal a_start = abs_a_start - pixels_offset;
619 a_end = abs_a_end - pixels_offset;
621 const qreal a_width = a_end - a_start;
622 const qreal delta = a_end - prev_end;
624 bool a_is_separate = false;
626 // Annotation wider than the threshold for a useful label width?
627 if (a_width >= min_useful_label_width_) {
628 for (const QString &ann_text : a.annotations()) {
629 const qreal w = p.boundingRect(QRectF(), 0, ann_text).width();
630 // Annotation wide enough to fit a label? Don't put it in a block then
632 a_is_separate = true;
638 // Were the previous and this annotation more than a pixel apart?
639 if ((abs(delta) > 1) || a_is_separate) {
640 // Block was broken, draw annotations that form the current block
641 if (block_ann_count == 1)
642 draw_annotation(*prev_ann, p, h, pp, y, row_color,
644 else if (block_ann_count > 0)
645 draw_annotation_block(block_start, prev_end, block_class,
646 block_class_uniform, p, h, y, row_color);
652 draw_annotation(a, p, h, pp, y, row_color, row_title_width);
653 // Next annotation must start a new block. delta will be > 1
654 // because we set prev_end to INT_MIN but that's okay since
655 // block_ann_count will be 0 and nothing will be drawn
662 if (block_ann_count == 0) {
663 block_start = a_start;
664 block_class = a.ann_class();
665 block_class_uniform = true;
667 if (a.ann_class() != block_class)
668 block_class_uniform = false;
674 if (block_ann_count == 1)
675 draw_annotation(*prev_ann, p, h, pp, y, row_color, row_title_width);
676 else if (block_ann_count > 0)
677 draw_annotation_block(block_start, prev_end, block_class,
678 block_class_uniform, p, h, y, row_color);
681 void DecodeTrace::draw_annotation(const pv::data::decode::Annotation &a,
682 QPainter &p, int h, const ViewItemPaintParams &pp, int y,
683 QColor row_color, int row_title_width) const
685 double samples_per_pixel, pixels_offset;
686 tie(pixels_offset, samples_per_pixel) =
687 get_pixels_offset_samples_per_pixel();
689 const double start = a.start_sample() / samples_per_pixel -
691 const double end = a.end_sample() / samples_per_pixel - pixels_offset;
693 QColor color = get_annotation_color(row_color, a.ann_class());
694 p.setPen(color.darker());
697 if (start > pp.right() + DrawPadding || end < pp.left() - DrawPadding)
700 if (a.start_sample() == a.end_sample())
701 draw_instant(a, p, h, start, y);
703 draw_range(a, p, h, start, end, y, pp, row_title_width);
706 void DecodeTrace::draw_annotation_block(qreal start, qreal end,
707 Annotation::Class ann_class, bool use_ann_format, QPainter &p, int h,
708 int y, QColor row_color) const
710 const double top = y + .5 - h / 2;
711 const double bottom = y + .5 + h / 2;
713 const QRectF rect(start, top, end - start, bottom - top);
716 p.setPen(QPen(Qt::NoPen));
717 p.setBrush(Qt::white);
718 p.drawRoundedRect(rect, r, r);
720 // If all annotations in this block are of the same type, we can use the
721 // one format that all of these annotations have. Otherwise, we should use
722 // a neutral color (i.e. gray)
723 if (use_ann_format) {
724 const QColor color = get_annotation_color(row_color, ann_class);
725 p.setPen(color.darker());
726 p.setBrush(QBrush(color, Qt::Dense4Pattern));
729 p.setBrush(QBrush(Qt::gray, Qt::Dense4Pattern));
732 p.drawRoundedRect(rect, r, r);
735 void DecodeTrace::draw_instant(const pv::data::decode::Annotation &a, QPainter &p,
736 int h, qreal x, int y) const
738 const QString text = a.annotations().empty() ?
739 QString() : a.annotations().back();
740 const qreal w = min((qreal)p.boundingRect(QRectF(), 0, text).width(),
742 const QRectF rect(x - w / 2, y - h / 2, w, h);
744 p.drawRoundedRect(rect, h / 2, h / 2);
747 p.drawText(rect, Qt::AlignCenter | Qt::AlignVCenter, text);
750 void DecodeTrace::draw_range(const pv::data::decode::Annotation &a, QPainter &p,
751 int h, qreal start, qreal end, int y, const ViewItemPaintParams &pp,
752 int row_title_width) const
754 const qreal top = y + .5 - h / 2;
755 const qreal bottom = y + .5 + h / 2;
756 const vector<QString> annotations = a.annotations();
758 // If the two ends are within 1 pixel, draw a vertical line
759 if (start + 1.0 > end) {
760 p.drawLine(QPointF(start, top), QPointF(start, bottom));
764 const qreal cap_width = min((end - start) / 4, EndCapWidth);
767 QPointF(start, y + .5f),
768 QPointF(start + cap_width, top),
769 QPointF(end - cap_width, top),
770 QPointF(end, y + .5f),
771 QPointF(end - cap_width, bottom),
772 QPointF(start + cap_width, bottom)
775 p.drawConvexPolygon(pts, countof(pts));
777 if (annotations.empty())
780 const int ann_start = start + cap_width;
781 const int ann_end = end - cap_width;
783 const int real_start = max(ann_start, pp.left() + ArrowSize + row_title_width);
784 const int real_end = min(ann_end, pp.right());
785 const int real_width = real_end - real_start;
787 QRectF rect(real_start, y - h / 2, real_width, h);
788 if (rect.width() <= 4)
793 // Try to find an annotation that will fit
794 QString best_annotation;
797 for (const QString &a : annotations) {
798 const int w = p.boundingRect(QRectF(), 0, a).width();
799 if (w <= rect.width() && w > best_width)
800 best_annotation = a, best_width = w;
803 if (best_annotation.isEmpty())
804 best_annotation = annotations.back();
806 // If not ellide the last in the list
807 p.drawText(rect, Qt::AlignCenter, p.fontMetrics().elidedText(
808 best_annotation, Qt::ElideRight, rect.width()));
811 void DecodeTrace::draw_error(QPainter &p, const QString &message,
812 const ViewItemPaintParams &pp)
814 const int y = get_visual_y();
816 double samples_per_pixel, pixels_offset;
817 tie(pixels_offset, samples_per_pixel) = get_pixels_offset_samples_per_pixel();
819 p.setPen(ErrorBgColor.darker());
820 p.setBrush(ErrorBgColor);
822 const QRectF bounding_rect = QRectF(pp.left(), INT_MIN / 2 + y, pp.right(), INT_MAX);
824 const QRectF text_rect = p.boundingRect(bounding_rect, Qt::AlignCenter, message);
825 const qreal r = text_rect.height() / 4;
827 p.drawRoundedRect(text_rect.adjusted(-r, -r, r, r), r, r, Qt::AbsoluteSize);
830 p.drawText(text_rect, message);
833 void DecodeTrace::draw_unresolved_period(QPainter &p, int h, int left, int right) const
835 using namespace pv::data;
836 using pv::data::decode::Decoder;
838 double samples_per_pixel, pixels_offset;
840 const int64_t sample_count = decode_signal_->get_working_sample_count(current_segment_);
841 if (sample_count == 0)
844 const int64_t samples_decoded = decode_signal_->get_decoded_sample_count(current_segment_, true);
845 if (sample_count == samples_decoded)
848 const int y = get_visual_y();
850 tie(pixels_offset, samples_per_pixel) = get_pixels_offset_samples_per_pixel();
852 const double start = max(samples_decoded /
853 samples_per_pixel - pixels_offset, left - 1.0);
854 const double end = min(sample_count / samples_per_pixel -
855 pixels_offset, right + 1.0);
856 const QRectF no_decode_rect(start, y - (h / 2) - 0.5, end - start, h);
858 p.setPen(QPen(Qt::NoPen));
859 p.setBrush(Qt::white);
860 p.drawRect(no_decode_rect);
862 p.setPen(NoDecodeColor);
863 p.setBrush(QBrush(NoDecodeColor, Qt::Dense6Pattern));
864 p.drawRect(no_decode_rect);
867 pair<double, double> DecodeTrace::get_pixels_offset_samples_per_pixel() const
871 const View *view = owner_->view();
874 const double scale = view->scale();
877 const double pixels_offset =
878 ((view->offset() - decode_signal_->start_time()) / scale).convert_to<double>();
880 double samplerate = decode_signal_->samplerate();
882 // Show sample rate as 1Hz when it is unknown
883 if (samplerate == 0.0)
886 return make_pair(pixels_offset, samplerate * scale);
889 pair<uint64_t, uint64_t> DecodeTrace::get_view_sample_range(
890 int x_start, int x_end) const
892 double samples_per_pixel, pixels_offset;
893 tie(pixels_offset, samples_per_pixel) =
894 get_pixels_offset_samples_per_pixel();
896 const uint64_t start = (uint64_t)max(
897 (x_start + pixels_offset) * samples_per_pixel, 0.0);
898 const uint64_t end = (uint64_t)max(
899 (x_end + pixels_offset) * samples_per_pixel, 0.0);
901 return make_pair(start, end);
904 QColor DecodeTrace::get_row_color(int row_index) const
906 // For each row color, use the base color hue and add an offset that's
907 // not a dividend of 360
910 const int h = (base_->color().toHsv().hue() + 20 * row_index) % 360;
911 const int s = DECODETRACE_COLOR_SATURATION;
912 const int v = DECODETRACE_COLOR_VALUE;
913 color.setHsl(h, s, v);
918 QColor DecodeTrace::get_annotation_color(QColor row_color, int annotation_index) const
920 // For each row color, use the base color hue and add an offset that's
921 // not a dividend of 360 and not a multiple of the row offset
923 QColor color(row_color);
924 const int h = (color.toHsv().hue() + 55 * annotation_index) % 360;
925 const int s = DECODETRACE_COLOR_SATURATION;
926 const int v = DECODETRACE_COLOR_VALUE;
927 color.setHsl(h, s, v);
932 unsigned int DecodeTrace::get_row_y(const RowData* row) const
936 unsigned int y = get_visual_y();
938 for (const RowData& r : rows_) {
939 if (!r.currently_visible)
942 if (row->decode_row == r.decode_row)
951 RowData* DecodeTrace::get_row_at_point(const QPoint &point)
953 int y = get_visual_y() - (default_row_height_ / 2);
955 for (RowData& r : rows_) {
956 if (!r.currently_visible)
959 if ((point.y() >= y) && (point.y() < (int)(y + r.height)))
968 const QString DecodeTrace::get_annotation_at_point(const QPoint &point)
970 using namespace pv::data::decode;
975 const pair<uint64_t, uint64_t> sample_range =
976 get_view_sample_range(point.x(), point.x() + 1);
977 const RowData* r = get_row_at_point(point);
982 if (point.y() > (int)(get_row_y(r) + (annotation_height_ / 2)))
985 vector<Annotation> annotations;
987 decode_signal_->get_annotation_subset(annotations, r->decode_row,
988 current_segment_, sample_range.first, sample_range.second);
990 return (annotations.empty()) ?
991 QString() : annotations[0].annotations().front();
994 void DecodeTrace::create_decoder_form(int index,
995 shared_ptr<data::decode::Decoder> &dec, QWidget *parent,
998 GlobalSettings settings;
1001 const srd_decoder *const decoder = dec->decoder();
1004 const bool decoder_deletable = index > 0;
1006 pv::widgets::DecoderGroupBox *const group =
1007 new pv::widgets::DecoderGroupBox(
1008 QString::fromUtf8(decoder->name),
1009 tr("%1:\n%2").arg(QString::fromUtf8(decoder->longname),
1010 QString::fromUtf8(decoder->desc)),
1011 nullptr, decoder_deletable);
1012 group->set_decoder_visible(dec->shown());
1014 if (decoder_deletable) {
1015 delete_mapper_.setMapping(group, index);
1016 connect(group, SIGNAL(delete_decoder()), &delete_mapper_, SLOT(map()));
1019 show_hide_mapper_.setMapping(group, index);
1020 connect(group, SIGNAL(show_hide_decoder()),
1021 &show_hide_mapper_, SLOT(map()));
1023 QFormLayout *const decoder_form = new QFormLayout;
1024 group->add_layout(decoder_form);
1026 const vector<DecodeChannel> channels = decode_signal_->get_channels();
1029 for (const DecodeChannel& ch : channels) {
1030 // Ignore channels not part of the decoder we create the form for
1031 if (ch.decoder_ != dec)
1034 QComboBox *const combo = create_channel_selector(parent, &ch);
1035 QComboBox *const combo_init_state = create_channel_selector_init_state(parent, &ch);
1037 channel_id_map_[combo] = ch.id;
1038 init_state_map_[combo_init_state] = ch.id;
1040 connect(combo, SIGNAL(currentIndexChanged(int)),
1041 this, SLOT(on_channel_selected(int)));
1042 connect(combo_init_state, SIGNAL(currentIndexChanged(int)),
1043 this, SLOT(on_init_state_changed(int)));
1045 QHBoxLayout *const hlayout = new QHBoxLayout;
1046 hlayout->addWidget(combo);
1047 hlayout->addWidget(combo_init_state);
1049 if (!settings.value(GlobalSettings::Key_Dec_InitialStateConfigurable).toBool())
1050 combo_init_state->hide();
1052 const QString required_flag = ch.is_optional ? QString() : QString("*");
1053 decoder_form->addRow(tr("<b>%1</b> (%2) %3")
1054 .arg(ch.name, ch.desc, required_flag), hlayout);
1058 shared_ptr<binding::Decoder> binding(
1059 new binding::Decoder(decode_signal_, dec));
1060 binding->add_properties_to_form(decoder_form, true);
1062 bindings_.push_back(binding);
1064 form->addRow(group);
1065 decoder_forms_.push_back(group);
1068 QComboBox* DecodeTrace::create_channel_selector(QWidget *parent, const DecodeChannel *ch)
1070 const auto sigs(session_.signalbases());
1072 // Sort signals in natural order
1073 vector< shared_ptr<data::SignalBase> > sig_list(sigs.begin(), sigs.end());
1074 sort(sig_list.begin(), sig_list.end(),
1075 [](const shared_ptr<data::SignalBase> &a,
1076 const shared_ptr<data::SignalBase> &b) {
1077 return strnatcasecmp(a->name().toStdString(),
1078 b->name().toStdString()) < 0; });
1080 QComboBox *selector = new QComboBox(parent);
1082 selector->addItem("-", qVariantFromValue((void*)nullptr));
1084 if (!ch->assigned_signal)
1085 selector->setCurrentIndex(0);
1087 for (const shared_ptr<data::SignalBase> &b : sig_list) {
1089 if (b->logic_data() && b->enabled()) {
1090 selector->addItem(b->name(),
1091 qVariantFromValue((void*)b.get()));
1093 if (ch->assigned_signal == b.get())
1094 selector->setCurrentIndex(selector->count() - 1);
1101 QComboBox* DecodeTrace::create_channel_selector_init_state(QWidget *parent,
1102 const DecodeChannel *ch)
1104 QComboBox *selector = new QComboBox(parent);
1106 selector->addItem("0", qVariantFromValue((int)SRD_INITIAL_PIN_LOW));
1107 selector->addItem("1", qVariantFromValue((int)SRD_INITIAL_PIN_HIGH));
1108 selector->addItem("X", qVariantFromValue((int)SRD_INITIAL_PIN_SAME_AS_SAMPLE0));
1110 selector->setCurrentIndex(ch->initial_pin_state);
1112 selector->setToolTip("Initial (assumed) pin value before the first sample");
1117 void DecodeTrace::export_annotations(vector<Annotation> *annotations) const
1119 using namespace pv::data::decode;
1121 GlobalSettings settings;
1122 const QString dir = settings.value("MainWindow/SaveDirectory").toString();
1124 const QString file_name = QFileDialog::getSaveFileName(
1125 owner_->view(), tr("Export annotations"), dir, tr("Text Files (*.txt);;All Files (*)"));
1127 if (file_name.isEmpty())
1130 QString format = settings.value(GlobalSettings::Key_Dec_ExportFormat).toString();
1131 const QString quote = format.contains("%q") ? "\"" : "";
1132 format = format.remove("%q");
1134 QFile file(file_name);
1135 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
1136 QTextStream out_stream(&file);
1138 for (Annotation &ann : *annotations) {
1139 const QString sample_range = QString("%1-%2") \
1140 .arg(QString::number(ann.start_sample()), QString::number(ann.end_sample()));
1142 const QString class_name = quote + ann.row()->class_name() + quote;
1144 QString all_ann_text;
1145 for (const QString &s : ann.annotations())
1146 all_ann_text = all_ann_text + quote + s + quote + ",";
1147 all_ann_text.chop(1);
1149 const QString first_ann_text = quote + ann.annotations().front() + quote;
1151 QString out_text = format;
1152 out_text = out_text.replace("%s", sample_range);
1153 out_text = out_text.replace("%d",
1154 quote + QString::fromUtf8(ann.row()->decoder()->name()) + quote);
1155 out_text = out_text.replace("%c", class_name);
1156 out_text = out_text.replace("%1", first_ann_text);
1157 out_text = out_text.replace("%a", all_ann_text);
1158 out_stream << out_text << '\n';
1161 if (out_stream.status() == QTextStream::Ok)
1165 QMessageBox msg(owner_->view());
1166 msg.setText(tr("Error") + "\n\n" + tr("File %1 could not be written to.").arg(file_name));
1167 msg.setStandardButtons(QMessageBox::Ok);
1168 msg.setIcon(QMessageBox::Warning);
1172 void DecodeTrace::update_rows()
1174 lock_guard<mutex> lock(row_modification_mutex_);
1176 QFontMetrics m(QApplication::font());
1178 for (RowData& r : rows_)
1181 for (const Row& decode_row : decode_signal_->get_rows()) {
1182 // Find row in our list
1183 auto r_it = find_if(rows_.begin(), rows_.end(),
1184 [&](RowData& r){ return r.decode_row == decode_row; });
1186 RowData* r = nullptr;
1187 if (r_it == rows_.end()) {
1188 // Row doesn't exist yet, create and append it
1190 nr.decode_row = decode_row;
1191 nr.height = default_row_height_;
1192 nr.expanded_height = 5*default_row_height_;
1193 nr.currently_visible = false;
1194 nr.expand_marker_highlighted = false;
1195 nr.expanding = false;
1196 nr.expanded = false;
1197 nr.collapsing = false;
1198 nr.expand_marker_shape = default_marker_shape_;
1199 nr.container = new QWidget(owner_->view()->viewport());
1201 rows_.push_back(nr);
1208 const int w = m.boundingRect(r->decode_row.title()).width() + RowTitleMargin;
1211 r->container->resize(owner_->view()->viewport()->width() - r->container->pos().x(),
1212 r->expanded_height - 2 * default_row_height_);
1213 r->container->setVisible(false);
1216 // Remove any rows that no longer exist, obeying that iterators are invalidated
1221 for (unsigned int i = 0; i < rows_.size(); i++)
1222 if (!rows_[i].exists) {
1223 delete rows_[i].container;
1224 rows_.erase(rows_.begin() + i);
1228 } while (any_exists);
1231 void DecodeTrace::on_setting_changed(const QString &key, const QVariant &value)
1233 Trace::on_setting_changed(key, value);
1235 if (key == GlobalSettings::Key_Dec_AlwaysShowAllRows) {
1236 max_visible_rows_ = 0;
1237 always_show_all_rows_ = value.toBool();
1241 void DecodeTrace::on_new_annotations()
1243 if (!delayed_trace_updater_.isActive())
1244 delayed_trace_updater_.start();
1247 void DecodeTrace::on_delayed_trace_update()
1250 owner_->row_item_appearance_changed(false, true);
1253 void DecodeTrace::on_decode_reset()
1255 max_visible_rows_ = 0;
1259 owner_->row_item_appearance_changed(false, true);
1262 void DecodeTrace::on_decode_finished()
1265 owner_->row_item_appearance_changed(false, true);
1268 void DecodeTrace::on_pause_decode()
1270 if (decode_signal_->is_paused())
1271 decode_signal_->resume_decode();
1273 decode_signal_->pause_decode();
1276 void DecodeTrace::on_delete()
1278 session_.remove_decode_signal(decode_signal_);
1281 void DecodeTrace::on_channel_selected(int)
1283 QComboBox *cb = qobject_cast<QComboBox*>(QObject::sender());
1285 // Determine signal that was selected
1286 const data::SignalBase *signal =
1287 (data::SignalBase*)cb->itemData(cb->currentIndex()).value<void*>();
1289 // Determine decode channel ID this combo box is the channel selector for
1290 const uint16_t id = channel_id_map_.at(cb);
1292 decode_signal_->assign_signal(id, signal);
1295 void DecodeTrace::on_channels_updated()
1298 owner_->row_item_appearance_changed(false, true);
1301 void DecodeTrace::on_init_state_changed(int)
1303 QComboBox *cb = qobject_cast<QComboBox*>(QObject::sender());
1305 // Determine inital pin state that was selected
1306 int init_state = cb->itemData(cb->currentIndex()).value<int>();
1308 // Determine decode channel ID this combo box is the channel selector for
1309 const uint16_t id = init_state_map_.at(cb);
1311 decode_signal_->set_initial_pin_state(id, init_state);
1314 void DecodeTrace::on_stack_decoder(srd_decoder *decoder)
1316 decode_signal_->stack_decoder(decoder);
1319 create_popup_form();
1322 void DecodeTrace::on_delete_decoder(int index)
1324 decode_signal_->remove_decoder(index);
1327 // Force re-calculation of the trace height
1328 max_visible_rows_ = 0;
1329 owner_->extents_changed(false, true);
1331 create_popup_form();
1334 void DecodeTrace::on_show_hide_decoder(int index)
1336 const bool state = decode_signal_->toggle_decoder_visibility(index);
1338 assert(index < (int)decoder_forms_.size());
1339 decoder_forms_[index]->set_decoder_visible(state);
1342 // Force re-calculation of the trace height, see paint_mid()
1343 max_visible_rows_ = 0;
1344 owner_->extents_changed(false, true);
1348 owner_->row_item_appearance_changed(false, true);
1351 void DecodeTrace::on_copy_annotation_to_clipboard()
1353 using namespace pv::data::decode;
1358 vector<Annotation> *annotations = new vector<Annotation>();
1360 decode_signal_->get_annotation_subset(*annotations, *selected_row_,
1361 current_segment_, selected_sample_range_.first, selected_sample_range_.first);
1363 if (annotations->empty())
1366 QClipboard *clipboard = QApplication::clipboard();
1367 clipboard->setText(annotations->front().annotations().front(), QClipboard::Clipboard);
1369 if (clipboard->supportsSelection())
1370 clipboard->setText(annotations->front().annotations().front(), QClipboard::Selection);
1375 void DecodeTrace::on_export_row()
1377 selected_sample_range_ = make_pair(0, numeric_limits<uint64_t>::max());
1378 on_export_row_from_here();
1381 void DecodeTrace::on_export_all_rows()
1383 selected_sample_range_ = make_pair(0, numeric_limits<uint64_t>::max());
1384 on_export_all_rows_from_here();
1387 void DecodeTrace::on_export_row_with_cursor()
1389 const View *view = owner_->view();
1392 if (!view->cursors()->enabled())
1395 const double samplerate = session_.get_samplerate();
1397 const pv::util::Timestamp& start_time = view->cursors()->first()->time();
1398 const pv::util::Timestamp& end_time = view->cursors()->second()->time();
1400 const uint64_t start_sample = (uint64_t)max(
1401 0.0, start_time.convert_to<double>() * samplerate);
1402 const uint64_t end_sample = (uint64_t)max(
1403 0.0, end_time.convert_to<double>() * samplerate);
1405 // Are both cursors negative and thus were clamped to 0?
1406 if ((start_sample == 0) && (end_sample == 0))
1409 selected_sample_range_ = make_pair(start_sample, end_sample);
1410 on_export_row_from_here();
1413 void DecodeTrace::on_export_all_rows_with_cursor()
1415 const View *view = owner_->view();
1418 if (!view->cursors()->enabled())
1421 const double samplerate = session_.get_samplerate();
1423 const pv::util::Timestamp& start_time = view->cursors()->first()->time();
1424 const pv::util::Timestamp& end_time = view->cursors()->second()->time();
1426 const uint64_t start_sample = (uint64_t)max(
1427 0.0, start_time.convert_to<double>() * samplerate);
1428 const uint64_t end_sample = (uint64_t)max(
1429 0.0, end_time.convert_to<double>() * samplerate);
1431 // Are both cursors negative and thus were clamped to 0?
1432 if ((start_sample == 0) && (end_sample == 0))
1435 selected_sample_range_ = make_pair(start_sample, end_sample);
1436 on_export_all_rows_from_here();
1439 void DecodeTrace::on_export_row_from_here()
1441 using namespace pv::data::decode;
1446 vector<Annotation> *annotations = new vector<Annotation>();
1448 decode_signal_->get_annotation_subset(*annotations, *selected_row_,
1449 current_segment_, selected_sample_range_.first, selected_sample_range_.second);
1451 if (annotations->empty())
1454 export_annotations(annotations);
1458 void DecodeTrace::on_export_all_rows_from_here()
1460 using namespace pv::data::decode;
1462 vector<Annotation> *annotations = new vector<Annotation>();
1464 decode_signal_->get_annotation_subset(*annotations, current_segment_,
1465 selected_sample_range_.first, selected_sample_range_.second);
1467 if (!annotations->empty())
1468 export_annotations(annotations);
1473 void DecodeTrace::on_animation_timer()
1475 bool animation_finished = true;
1477 for (RowData& r : rows_) {
1478 if (!(r.expanding || r.collapsing))
1481 unsigned int height_delta = r.expanded_height - default_row_height_;
1484 if (r.height < r.expanded_height) {
1485 r.anim_height += height_delta / (float)AnimationDurationInTicks;
1486 r.height = r.anim_height;
1487 r.anim_shape += ArrowSize / (float)AnimationDurationInTicks;
1488 animation_finished = false;
1490 r.height = std::min(r.height, r.expanded_height);
1491 r.expanding = false;
1497 if (r.height > default_row_height_) {
1498 r.anim_height -= height_delta / (float)AnimationDurationInTicks;
1499 r.height = r.anim_height;
1500 r.anim_shape -= ArrowSize / (float)AnimationDurationInTicks;
1501 animation_finished = false;
1503 r.height = std::max(r.height, default_row_height_);
1504 r.collapsing = false;
1506 r.expand_marker_shape = default_marker_shape_;
1507 r.container->setVisible(false);
1511 // The expansion marker shape switches between
1512 // 0/-A, A/0, 0/A (default state; anim_shape=0) and
1513 // 0/ 0, A/A, 2A/0 (expanded state; anim_shape=ArrowSize)
1515 r.expand_marker_shape.setPoint(0, 0, -ArrowSize + r.anim_shape);
1516 r.expand_marker_shape.setPoint(1, ArrowSize, r.anim_shape);
1517 r.expand_marker_shape.setPoint(2, 2*r.anim_shape, ArrowSize - r.anim_shape);
1519 r.container->resize(owner_->view()->viewport()->width() - r.container->pos().x(),
1520 r.height - 2 * default_row_height_);
1523 if (animation_finished)
1524 animation_timer_.stop();
1527 owner_->row_item_appearance_changed(false, true);
1530 } // namespace trace
1531 } // namespace views