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