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