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