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