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