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