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