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