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