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