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