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