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