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