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