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