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