Implement annotation export for all rows
[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 <climits>
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 <QComboBox>
35 #include <QFileDialog>
36 #include <QFormLayout>
37 #include <QLabel>
38 #include <QMenu>
39 #include <QMessageBox>
40 #include <QPushButton>
41 #include <QTextStream>
42 #include <QToolTip>
43
44 #include "decodetrace.hpp"
45 #include "view.hpp"
46 #include "viewport.hpp"
47
48 #include <pv/globalsettings.hpp>
49 #include <pv/session.hpp>
50 #include <pv/strnatcmp.hpp>
51 #include <pv/data/decodesignal.hpp>
52 #include <pv/data/decode/annotation.hpp>
53 #include <pv/data/decode/decoder.hpp>
54 #include <pv/data/logic.hpp>
55 #include <pv/data/logicsegment.hpp>
56 #include <pv/widgets/decodergroupbox.hpp>
57 #include <pv/widgets/decodermenu.hpp>
58
59 using std::abs;
60 using std::make_pair;
61 using std::max;
62 using std::min;
63 using std::out_of_range;
64 using std::pair;
65 using std::shared_ptr;
66 using std::tie;
67 using std::vector;
68
69 using pv::data::decode::Annotation;
70 using pv::data::decode::Row;
71 using pv::data::DecodeChannel;
72 using pv::data::DecodeSignal;
73
74 namespace pv {
75 namespace views {
76 namespace trace {
77
78
79 #define DECODETRACE_COLOR_SATURATION (180) /* 0-255 */
80 #define DECODETRACE_COLOR_VALUE (170) /* 0-255 */
81
82 const QColor DecodeTrace::ErrorBgColor = QColor(0xEF, 0x29, 0x29);
83 const QColor DecodeTrace::NoDecodeColor = QColor(0x88, 0x8A, 0x85);
84
85 const int DecodeTrace::ArrowSize = 4;
86 const double DecodeTrace::EndCapWidth = 5;
87 const int DecodeTrace::RowTitleMargin = 10;
88 const int DecodeTrace::DrawPadding = 100;
89
90 const int DecodeTrace::MaxTraceUpdateRate = 1; // No more than 1 Hz
91
92 DecodeTrace::DecodeTrace(pv::Session &session,
93         shared_ptr<data::SignalBase> signalbase, int index) :
94         Trace(signalbase),
95         session_(session),
96         row_height_(0),
97         max_visible_rows_(0),
98         delete_mapper_(this),
99         show_hide_mapper_(this)
100 {
101         decode_signal_ = dynamic_pointer_cast<data::DecodeSignal>(base_);
102
103         // Determine shortest string we want to see displayed in full
104         QFontMetrics m(QApplication::font());
105         min_useful_label_width_ = m.width("XX"); // e.g. two hex characters
106
107         // For the base color, we want to start at a very different color for
108         // every decoder stack, so multiply the index with a number that is
109         // rather close to 180 degrees of the color circle but not a dividend of 360
110         // Note: The offset equals the color of the first annotation
111         QColor color;
112         const int h = (120 + 160 * index) % 360;
113         const int s = DECODETRACE_COLOR_SATURATION;
114         const int v = DECODETRACE_COLOR_VALUE;
115         color.setHsv(h, s, v);
116         base_->set_color(color);
117
118         connect(decode_signal_.get(), SIGNAL(new_annotations()),
119                 this, SLOT(on_new_annotations()));
120         connect(decode_signal_.get(), SIGNAL(decode_reset()),
121                 this, SLOT(on_decode_reset()));
122         connect(decode_signal_.get(), SIGNAL(decode_finished()),
123                 this, SLOT(on_decode_finished()));
124         connect(decode_signal_.get(), SIGNAL(channels_updated()),
125                 this, SLOT(on_channels_updated()));
126
127         connect(&delete_mapper_, SIGNAL(mapped(int)),
128                 this, SLOT(on_delete_decoder(int)));
129         connect(&show_hide_mapper_, SIGNAL(mapped(int)),
130                 this, SLOT(on_show_hide_decoder(int)));
131
132         connect(&delayed_trace_updater_, SIGNAL(timeout()),
133                 this, SLOT(on_delayed_trace_update()));
134         delayed_trace_updater_.setSingleShot(true);
135         delayed_trace_updater_.setInterval(1000 / MaxTraceUpdateRate);
136 }
137
138 bool DecodeTrace::enabled() const
139 {
140         return true;
141 }
142
143 shared_ptr<data::SignalBase> DecodeTrace::base() const
144 {
145         return base_;
146 }
147
148 pair<int, int> DecodeTrace::v_extents() const
149 {
150         const int row_height = (ViewItemPaintParams::text_height() * 6) / 4;
151
152         // Make an empty decode trace appear symmetrical
153         const int row_count = max(1, max_visible_rows_);
154
155         return make_pair(-row_height, row_height * row_count);
156 }
157
158 void DecodeTrace::paint_back(QPainter &p, ViewItemPaintParams &pp)
159 {
160         Trace::paint_back(p, pp);
161         paint_axis(p, pp, get_visual_y());
162 }
163
164 void DecodeTrace::paint_mid(QPainter &p, ViewItemPaintParams &pp)
165 {
166         const int text_height = ViewItemPaintParams::text_height();
167         row_height_ = (text_height * 6) / 4;
168         const int annotation_height = (text_height * 5) / 4;
169
170         // Set default pen to allow for text width calculation
171         p.setPen(Qt::black);
172
173         // Iterate through the rows
174         int y = get_visual_y();
175         pair<uint64_t, uint64_t> sample_range = get_sample_range(pp.left(), pp.right());
176
177         // Just because the view says we see a certain sample range it
178         // doesn't mean we have this many decoded samples, too, so crop
179         // the range to what has been decoded already
180         sample_range.second = min((int64_t)sample_range.second,
181                 decode_signal_->get_decoded_sample_count(current_segment_, false));
182
183         const vector<Row> rows = decode_signal_->visible_rows();
184
185         visible_rows_.clear();
186         for (const Row& row : rows) {
187                 // Cache the row title widths
188                 int row_title_width;
189                 try {
190                         row_title_width = row_title_widths_.at(row);
191                 } catch (out_of_range&) {
192                         const int w = p.boundingRect(QRectF(), 0, row.title()).width() +
193                                 RowTitleMargin;
194                         row_title_widths_[row] = w;
195                         row_title_width = w;
196                 }
197
198                 vector<Annotation> annotations;
199                 decode_signal_->get_annotation_subset(annotations, row,
200                         current_segment_, sample_range.first, sample_range.second);
201                 if (!annotations.empty()) {
202                         draw_annotations(annotations, p, annotation_height, pp, y,
203                                 get_row_color(row.index()), row_title_width);
204                         y += row_height_;
205                         visible_rows_.push_back(row);
206                 }
207         }
208
209         draw_unresolved_period(p, annotation_height, pp.left(), pp.right());
210
211         if ((int)visible_rows_.size() > max_visible_rows_) {
212                 max_visible_rows_ = (int)visible_rows_.size();
213
214                 // Call order is important, otherwise the lazy event handler won't work
215                 owner_->extents_changed(false, true);
216                 owner_->row_item_appearance_changed(false, true);
217         }
218
219         const QString err = decode_signal_->error_message();
220         if (!err.isEmpty())
221                 draw_error(p, err, pp);
222 }
223
224 void DecodeTrace::paint_fore(QPainter &p, ViewItemPaintParams &pp)
225 {
226         assert(row_height_);
227
228         for (size_t i = 0; i < visible_rows_.size(); i++) {
229                 const int y = i * row_height_ + get_visual_y();
230
231                 p.setPen(QPen(Qt::NoPen));
232                 p.setBrush(QApplication::palette().brush(QPalette::WindowText));
233
234                 if (i != 0) {
235                         const QPointF points[] = {
236                                 QPointF(pp.left(), y - ArrowSize),
237                                 QPointF(pp.left() + ArrowSize, y),
238                                 QPointF(pp.left(), y + ArrowSize)
239                         };
240                         p.drawPolygon(points, countof(points));
241                 }
242
243                 const QRect r(pp.left() + ArrowSize * 2, y - row_height_ / 2,
244                         pp.right() - pp.left(), row_height_);
245                 const QString h(visible_rows_[i].title());
246                 const int f = Qt::AlignLeft | Qt::AlignVCenter |
247                         Qt::TextDontClip;
248
249                 // Draw the outline
250                 p.setPen(QApplication::palette().color(QPalette::Base));
251                 for (int dx = -1; dx <= 1; dx++)
252                         for (int dy = -1; dy <= 1; dy++)
253                                 if (dx != 0 && dy != 0)
254                                         p.drawText(r.translated(dx, dy), f, h);
255
256                 // Draw the text
257                 p.setPen(QApplication::palette().color(QPalette::WindowText));
258                 p.drawText(r, f, h);
259         }
260
261         if (show_hover_marker_)
262                 paint_hover_marker(p);
263 }
264
265 void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form)
266 {
267         using pv::data::decode::Decoder;
268
269         assert(form);
270
271         // Add the standard options
272         Trace::populate_popup_form(parent, form);
273
274         // Add the decoder options
275         bindings_.clear();
276         channel_id_map_.clear();
277         init_state_map_.clear();
278         decoder_forms_.clear();
279
280         const vector< shared_ptr<Decoder> > &stack = decode_signal_->decoder_stack();
281
282         if (stack.empty()) {
283                 QLabel *const l = new QLabel(
284                         tr("<p><i>No decoders in the stack</i></p>"));
285                 l->setAlignment(Qt::AlignCenter);
286                 form->addRow(l);
287         } else {
288                 auto iter = stack.cbegin();
289                 for (int i = 0; i < (int)stack.size(); i++, iter++) {
290                         shared_ptr<Decoder> dec(*iter);
291                         create_decoder_form(i, dec, parent, form);
292                 }
293
294                 form->addRow(new QLabel(
295                         tr("<i>* Required channels</i>"), parent));
296         }
297
298         // Add stacking button
299         pv::widgets::DecoderMenu *const decoder_menu =
300                 new pv::widgets::DecoderMenu(parent);
301         connect(decoder_menu, SIGNAL(decoder_selected(srd_decoder*)),
302                 this, SLOT(on_stack_decoder(srd_decoder*)));
303
304         QPushButton *const stack_button =
305                 new QPushButton(tr("Stack Decoder"), parent);
306         stack_button->setMenu(decoder_menu);
307         stack_button->setToolTip(tr("Stack a higher-level decoder on top of this one"));
308
309         QHBoxLayout *stack_button_box = new QHBoxLayout;
310         stack_button_box->addWidget(stack_button, 0, Qt::AlignRight);
311         form->addRow(stack_button_box);
312 }
313
314 QMenu* DecodeTrace::create_header_context_menu(QWidget *parent)
315 {
316         QMenu *const menu = Trace::create_header_context_menu(parent);
317
318         menu->addSeparator();
319
320         QAction *const del = new QAction(tr("Delete"), this);
321         del->setShortcuts(QKeySequence::Delete);
322         connect(del, SIGNAL(triggered()), this, SLOT(on_delete()));
323         menu->addAction(del);
324
325         return menu;
326 }
327
328 QMenu* DecodeTrace::create_view_context_menu(QWidget *parent, QPoint &click_pos)
329 {
330         try {
331                 selected_row_ = &visible_rows_[get_row_at_point(click_pos)];
332         } catch (out_of_range&) {
333                 selected_row_ = nullptr;
334         }
335
336         const pair<uint64_t, uint64_t> sample_range =
337                 get_sample_range(click_pos.x(), click_pos.x() + 1);
338         selected_samplepos_ = sample_range.first;
339
340         QMenu *const menu = new QMenu(parent);
341
342         QAction *const export_all_rows =
343                         new QAction(tr("Export all annotations"), this);
344         export_all_rows->setIcon(QIcon::fromTheme("document-save-as",
345                 QIcon(":/icons/document-save-as.png")));
346         connect(export_all_rows, SIGNAL(triggered()), this, SLOT(on_export_all_rows()));
347         menu->addAction(export_all_rows);
348
349         QAction *const export_row =
350                         new QAction(tr("Export all annotations for this row"), this);
351         export_row->setIcon(QIcon::fromTheme("document-save-as",
352                 QIcon(":/icons/document-save-as.png")));
353         connect(export_row, SIGNAL(triggered()), this, SLOT(on_export_row()));
354         menu->addAction(export_row);
355
356         menu->addSeparator();
357
358         QAction *const export_all_rows_from_here =
359                 new QAction(tr("Export all annotations, starting here"), this);
360         export_all_rows_from_here->setIcon(QIcon::fromTheme("document-save-as",
361                 QIcon(":/icons/document-save-as.png")));
362         connect(export_all_rows_from_here, SIGNAL(triggered()), this, SLOT(on_export_all_rows_from_here()));
363         menu->addAction(export_all_rows_from_here);
364
365         QAction *const export_row_from_here =
366                 new QAction(tr("Export annotations for this row, starting here"), this);
367         export_row_from_here->setIcon(QIcon::fromTheme("document-save-as",
368                 QIcon(":/icons/document-save-as.png")));
369         connect(export_row_from_here, SIGNAL(triggered()), this, SLOT(on_export_row_from_here()));
370         menu->addAction(export_row_from_here);
371
372         return menu;
373 }
374
375 void DecodeTrace::draw_annotations(vector<pv::data::decode::Annotation> annotations,
376                 QPainter &p, int h, const ViewItemPaintParams &pp, int y,
377                 QColor row_color, int row_title_width)
378 {
379         using namespace pv::data::decode;
380
381         Annotation::Class block_class = 0;
382         bool block_class_uniform = true;
383         qreal block_start = 0;
384         int block_ann_count = 0;
385
386         const Annotation *prev_ann;
387         qreal prev_end = INT_MIN;
388
389         qreal a_end;
390
391         double samples_per_pixel, pixels_offset;
392         tie(pixels_offset, samples_per_pixel) =
393                 get_pixels_offset_samples_per_pixel();
394
395         // Sort the annotations by start sample so that decoders
396         // can't confuse us by creating annotations out of order
397         stable_sort(annotations.begin(), annotations.end(),
398                 [](const Annotation &a, const Annotation &b) {
399                         return a.start_sample() < b.start_sample(); });
400
401         // Gather all annotations that form a visual "block" and draw them as such
402         for (const Annotation &a : annotations) {
403
404                 const qreal abs_a_start = a.start_sample() / samples_per_pixel;
405                 const qreal abs_a_end   = a.end_sample() / samples_per_pixel;
406
407                 const qreal a_start = abs_a_start - pixels_offset;
408                 a_end = abs_a_end - pixels_offset;
409
410                 const qreal a_width = a_end - a_start;
411                 const qreal delta = a_end - prev_end;
412
413                 bool a_is_separate = false;
414
415                 // Annotation wider than the threshold for a useful label width?
416                 if (a_width >= min_useful_label_width_) {
417                         for (const QString &ann_text : a.annotations()) {
418                                 const qreal w = p.boundingRect(QRectF(), 0, ann_text).width();
419                                 // Annotation wide enough to fit a label? Don't put it in a block then
420                                 if (w <= a_width) {
421                                         a_is_separate = true;
422                                         break;
423                                 }
424                         }
425                 }
426
427                 // Were the previous and this annotation more than a pixel apart?
428                 if ((abs(delta) > 1) || a_is_separate) {
429                         // Block was broken, draw annotations that form the current block
430                         if (block_ann_count == 1)
431                                 draw_annotation(*prev_ann, p, h, pp, y, row_color,
432                                         row_title_width);
433                         else if (block_ann_count > 0)
434                                 draw_annotation_block(block_start, prev_end, block_class,
435                                         block_class_uniform, p, h, y, row_color);
436
437                         block_ann_count = 0;
438                 }
439
440                 if (a_is_separate) {
441                         draw_annotation(a, p, h, pp, y, row_color, row_title_width);
442                         // Next annotation must start a new block. delta will be > 1
443                         // because we set prev_end to INT_MIN but that's okay since
444                         // block_ann_count will be 0 and nothing will be drawn
445                         prev_end = INT_MIN;
446                         block_ann_count = 0;
447                 } else {
448                         prev_end = a_end;
449                         prev_ann = &a;
450
451                         if (block_ann_count == 0) {
452                                 block_start = a_start;
453                                 block_class = a.ann_class();
454                                 block_class_uniform = true;
455                         } else
456                                 if (a.ann_class() != block_class)
457                                         block_class_uniform = false;
458
459                         block_ann_count++;
460                 }
461         }
462
463         if (block_ann_count == 1)
464                 draw_annotation(*prev_ann, p, h, pp, y, row_color, row_title_width);
465         else if (block_ann_count > 0)
466                 draw_annotation_block(block_start, prev_end, block_class,
467                         block_class_uniform, p, h, y, row_color);
468 }
469
470 void DecodeTrace::draw_annotation(const pv::data::decode::Annotation &a,
471         QPainter &p, int h, const ViewItemPaintParams &pp, int y,
472         QColor row_color, int row_title_width) const
473 {
474         double samples_per_pixel, pixels_offset;
475         tie(pixels_offset, samples_per_pixel) =
476                 get_pixels_offset_samples_per_pixel();
477
478         const double start = a.start_sample() / samples_per_pixel -
479                 pixels_offset;
480         const double end = a.end_sample() / samples_per_pixel - pixels_offset;
481
482         QColor color = get_annotation_color(row_color, a.ann_class());
483         p.setPen(color.darker());
484         p.setBrush(color);
485
486         if (start > pp.right() + DrawPadding || end < pp.left() - DrawPadding)
487                 return;
488
489         if (a.start_sample() == a.end_sample())
490                 draw_instant(a, p, h, start, y);
491         else
492                 draw_range(a, p, h, start, end, y, pp, row_title_width);
493 }
494
495 void DecodeTrace::draw_annotation_block(qreal start, qreal end,
496         Annotation::Class ann_class, bool use_ann_format, QPainter &p, int h,
497         int y, QColor row_color) const
498 {
499         const double top = y + .5 - h / 2;
500         const double bottom = y + .5 + h / 2;
501
502         const QRectF rect(start, top, end - start, bottom - top);
503         const int r = h / 4;
504
505         p.setPen(QPen(Qt::NoPen));
506         p.setBrush(Qt::white);
507         p.drawRoundedRect(rect, r, r);
508
509         // If all annotations in this block are of the same type, we can use the
510         // one format that all of these annotations have. Otherwise, we should use
511         // a neutral color (i.e. gray)
512         if (use_ann_format) {
513                 const QColor color = get_annotation_color(row_color, ann_class);
514                 p.setPen(color.darker());
515                 p.setBrush(QBrush(color, Qt::Dense4Pattern));
516         } else {
517                 p.setPen(Qt::gray);
518                 p.setBrush(QBrush(Qt::gray, Qt::Dense4Pattern));
519         }
520
521         p.drawRoundedRect(rect, r, r);
522 }
523
524 void DecodeTrace::draw_instant(const pv::data::decode::Annotation &a, QPainter &p,
525         int h, qreal x, int y) const
526 {
527         const QString text = a.annotations().empty() ?
528                 QString() : a.annotations().back();
529         const qreal w = min((qreal)p.boundingRect(QRectF(), 0, text).width(),
530                 0.0) + h;
531         const QRectF rect(x - w / 2, y - h / 2, w, h);
532
533         p.drawRoundedRect(rect, h / 2, h / 2);
534
535         p.setPen(Qt::black);
536         p.drawText(rect, Qt::AlignCenter | Qt::AlignVCenter, text);
537 }
538
539 void DecodeTrace::draw_range(const pv::data::decode::Annotation &a, QPainter &p,
540         int h, qreal start, qreal end, int y, const ViewItemPaintParams &pp,
541         int row_title_width) const
542 {
543         const qreal top = y + .5 - h / 2;
544         const qreal bottom = y + .5 + h / 2;
545         const vector<QString> annotations = a.annotations();
546
547         // If the two ends are within 1 pixel, draw a vertical line
548         if (start + 1.0 > end) {
549                 p.drawLine(QPointF(start, top), QPointF(start, bottom));
550                 return;
551         }
552
553         const qreal cap_width = min((end - start) / 4, EndCapWidth);
554
555         QPointF pts[] = {
556                 QPointF(start, y + .5f),
557                 QPointF(start + cap_width, top),
558                 QPointF(end - cap_width, top),
559                 QPointF(end, y + .5f),
560                 QPointF(end - cap_width, bottom),
561                 QPointF(start + cap_width, bottom)
562         };
563
564         p.drawConvexPolygon(pts, countof(pts));
565
566         if (annotations.empty())
567                 return;
568
569         const int ann_start = start + cap_width;
570         const int ann_end = end - cap_width;
571
572         const int real_start = max(ann_start, pp.left() + row_title_width);
573         const int real_end = min(ann_end, pp.right());
574         const int real_width = real_end - real_start;
575
576         QRectF rect(real_start, y - h / 2, real_width, h);
577         if (rect.width() <= 4)
578                 return;
579
580         p.setPen(Qt::black);
581
582         // Try to find an annotation that will fit
583         QString best_annotation;
584         int best_width = 0;
585
586         for (const QString &a : annotations) {
587                 const int w = p.boundingRect(QRectF(), 0, a).width();
588                 if (w <= rect.width() && w > best_width)
589                         best_annotation = a, best_width = w;
590         }
591
592         if (best_annotation.isEmpty())
593                 best_annotation = annotations.back();
594
595         // If not ellide the last in the list
596         p.drawText(rect, Qt::AlignCenter, p.fontMetrics().elidedText(
597                 best_annotation, Qt::ElideRight, rect.width()));
598 }
599
600 void DecodeTrace::draw_error(QPainter &p, const QString &message,
601         const ViewItemPaintParams &pp)
602 {
603         const int y = get_visual_y();
604
605         double samples_per_pixel, pixels_offset;
606         tie(pixels_offset, samples_per_pixel) = get_pixels_offset_samples_per_pixel();
607
608         p.setPen(ErrorBgColor.darker());
609         p.setBrush(ErrorBgColor);
610
611         const QRectF bounding_rect = QRectF(pp.left(), INT_MIN / 2 + y, pp.right(), INT_MAX);
612
613         const QRectF text_rect = p.boundingRect(bounding_rect, Qt::AlignCenter, message);
614         const qreal r = text_rect.height() / 4;
615
616         p.drawRoundedRect(text_rect.adjusted(-r, -r, r, r), r, r, Qt::AbsoluteSize);
617
618         p.setPen(Qt::black);
619         p.drawText(text_rect, message);
620 }
621
622 void DecodeTrace::draw_unresolved_period(QPainter &p, int h, int left, int right) const
623 {
624         using namespace pv::data;
625         using pv::data::decode::Decoder;
626
627         double samples_per_pixel, pixels_offset;
628
629         const int64_t sample_count = decode_signal_->get_working_sample_count(current_segment_);
630         if (sample_count == 0)
631                 return;
632
633         const int64_t samples_decoded = decode_signal_->get_decoded_sample_count(current_segment_, true);
634         if (sample_count == samples_decoded)
635                 return;
636
637         const int y = get_visual_y();
638
639         tie(pixels_offset, samples_per_pixel) = get_pixels_offset_samples_per_pixel();
640
641         const double start = max(samples_decoded /
642                 samples_per_pixel - pixels_offset, left - 1.0);
643         const double end = min(sample_count / samples_per_pixel -
644                 pixels_offset, right + 1.0);
645         const QRectF no_decode_rect(start, y - (h / 2) - 0.5, end - start, h);
646
647         p.setPen(QPen(Qt::NoPen));
648         p.setBrush(Qt::white);
649         p.drawRect(no_decode_rect);
650
651         p.setPen(NoDecodeColor);
652         p.setBrush(QBrush(NoDecodeColor, Qt::Dense6Pattern));
653         p.drawRect(no_decode_rect);
654 }
655
656 pair<double, double> DecodeTrace::get_pixels_offset_samples_per_pixel() const
657 {
658         assert(owner_);
659
660         const View *view = owner_->view();
661         assert(view);
662
663         const double scale = view->scale();
664         assert(scale > 0);
665
666         const double pixels_offset =
667                 ((view->offset() - decode_signal_->start_time()) / scale).convert_to<double>();
668
669         double samplerate = decode_signal_->samplerate();
670
671         // Show sample rate as 1Hz when it is unknown
672         if (samplerate == 0.0)
673                 samplerate = 1.0;
674
675         return make_pair(pixels_offset, samplerate * scale);
676 }
677
678 pair<uint64_t, uint64_t> DecodeTrace::get_sample_range(
679         int x_start, int x_end) const
680 {
681         double samples_per_pixel, pixels_offset;
682         tie(pixels_offset, samples_per_pixel) =
683                 get_pixels_offset_samples_per_pixel();
684
685         const uint64_t start = (uint64_t)max(
686                 (x_start + pixels_offset) * samples_per_pixel, 0.0);
687         const uint64_t end = (uint64_t)max(
688                 (x_end + pixels_offset) * samples_per_pixel, 0.0);
689
690         return make_pair(start, end);
691 }
692
693 QColor DecodeTrace::get_row_color(int row_index) const
694 {
695         // For each row color, use the base color hue and add an offset that's
696         // not a dividend of 360
697
698         QColor color;
699         const int h = (base_->color().toHsv().hue() + 20 * row_index) % 360;
700         const int s = DECODETRACE_COLOR_SATURATION;
701         const int v = DECODETRACE_COLOR_VALUE;
702         color.setHsl(h, s, v);
703
704         return color;
705 }
706
707 QColor DecodeTrace::get_annotation_color(QColor row_color, int annotation_index) const
708 {
709         // For each row color, use the base color hue and add an offset that's
710         // not a dividend of 360 and not a multiple of the row offset
711
712         QColor color(row_color);
713         const int h = (color.toHsv().hue() + 55 * annotation_index) % 360;
714         const int s = DECODETRACE_COLOR_SATURATION;
715         const int v = DECODETRACE_COLOR_VALUE;
716         color.setHsl(h, s, v);
717
718         return color;
719 }
720
721 int DecodeTrace::get_row_at_point(const QPoint &point)
722 {
723         if (!row_height_)
724                 return -1;
725
726         const int y = (point.y() - get_visual_y() + row_height_ / 2);
727
728         /* Integer divison of (x-1)/x would yield 0, so we check for this. */
729         if (y < 0)
730                 return -1;
731
732         const int row = y / row_height_;
733
734         if (row >= (int)visible_rows_.size())
735                 return -1;
736
737         return row;
738 }
739
740 const QString DecodeTrace::get_annotation_at_point(const QPoint &point)
741 {
742         using namespace pv::data::decode;
743
744         if (!enabled())
745                 return QString();
746
747         const pair<uint64_t, uint64_t> sample_range =
748                 get_sample_range(point.x(), point.x() + 1);
749         const int row = get_row_at_point(point);
750         if (row < 0)
751                 return QString();
752
753         vector<Annotation> annotations;
754
755         decode_signal_->get_annotation_subset(annotations, visible_rows_[row],
756                 current_segment_, sample_range.first, sample_range.second);
757
758         return (annotations.empty()) ?
759                 QString() : annotations[0].annotations().front();
760 }
761
762 void DecodeTrace::hover_point_changed(const QPoint &hp)
763 {
764         Trace::hover_point_changed(hp);
765
766         assert(owner_);
767
768         const View *const view = owner_->view();
769         assert(view);
770
771         if (hp.x() == 0) {
772                 QToolTip::hideText();
773                 return;
774         }
775
776         QString ann = get_annotation_at_point(hp);
777
778         assert(view);
779
780         if (!row_height_ || ann.isEmpty()) {
781                 QToolTip::hideText();
782                 return;
783         }
784
785         const int hover_row = get_row_at_point(hp);
786
787         QFontMetrics m(QToolTip::font());
788         const QRect text_size = m.boundingRect(QRect(), 0, ann);
789
790         // This is OS-specific and unfortunately we can't query it, so
791         // use an approximation to at least try to minimize the error.
792         const int padding = 8;
793
794         // Make sure the tool tip doesn't overlap with the mouse cursor.
795         // If it did, the tool tip would constantly hide and re-appear.
796         // We also push it up by one row so that it appears above the
797         // decode trace, not below.
798         QPoint p = hp;
799         p.setX(hp.x() - (text_size.width() / 2) - padding);
800
801         p.setY(get_visual_y() - (row_height_ / 2) +
802                 (hover_row * row_height_) -
803                 row_height_ - text_size.height() - padding);
804
805         QToolTip::showText(view->viewport()->mapToGlobal(p), ann);
806 }
807
808 void DecodeTrace::create_decoder_form(int index,
809         shared_ptr<data::decode::Decoder> &dec, QWidget *parent,
810         QFormLayout *form)
811 {
812         GlobalSettings settings;
813
814         assert(dec);
815         const srd_decoder *const decoder = dec->decoder();
816         assert(decoder);
817
818         const bool decoder_deletable = index > 0;
819
820         pv::widgets::DecoderGroupBox *const group =
821                 new pv::widgets::DecoderGroupBox(
822                         QString::fromUtf8(decoder->name),
823                         tr("%1:\n%2").arg(QString::fromUtf8(decoder->longname),
824                                 QString::fromUtf8(decoder->desc)),
825                         nullptr, decoder_deletable);
826         group->set_decoder_visible(dec->shown());
827
828         if (decoder_deletable) {
829                 delete_mapper_.setMapping(group, index);
830                 connect(group, SIGNAL(delete_decoder()), &delete_mapper_, SLOT(map()));
831         }
832
833         show_hide_mapper_.setMapping(group, index);
834         connect(group, SIGNAL(show_hide_decoder()),
835                 &show_hide_mapper_, SLOT(map()));
836
837         QFormLayout *const decoder_form = new QFormLayout;
838         group->add_layout(decoder_form);
839
840         const vector<DecodeChannel> channels = decode_signal_->get_channels();
841
842         // Add the channels
843         for (DecodeChannel ch : channels) {
844                 // Ignore channels not part of the decoder we create the form for
845                 if (ch.decoder_ != dec)
846                         continue;
847
848                 QComboBox *const combo = create_channel_selector(parent, &ch);
849                 QComboBox *const combo_init_state = create_channel_selector_init_state(parent, &ch);
850
851                 channel_id_map_[combo] = ch.id;
852                 init_state_map_[combo_init_state] = ch.id;
853
854                 connect(combo, SIGNAL(currentIndexChanged(int)),
855                         this, SLOT(on_channel_selected(int)));
856                 connect(combo_init_state, SIGNAL(currentIndexChanged(int)),
857                         this, SLOT(on_init_state_changed(int)));
858
859                 QHBoxLayout *const hlayout = new QHBoxLayout;
860                 hlayout->addWidget(combo);
861                 hlayout->addWidget(combo_init_state);
862
863                 if (!settings.value(GlobalSettings::Key_Dec_InitialStateConfigurable).toBool())
864                         combo_init_state->hide();
865
866                 const QString required_flag = ch.is_optional ? QString() : QString("*");
867                 decoder_form->addRow(tr("<b>%1</b> (%2) %3")
868                         .arg(ch.name, ch.desc, required_flag), hlayout);
869         }
870
871         // Add the options
872         shared_ptr<binding::Decoder> binding(
873                 new binding::Decoder(decode_signal_, dec));
874         binding->add_properties_to_form(decoder_form, true);
875
876         bindings_.push_back(binding);
877
878         form->addRow(group);
879         decoder_forms_.push_back(group);
880 }
881
882 QComboBox* DecodeTrace::create_channel_selector(QWidget *parent, const DecodeChannel *ch)
883 {
884         const auto sigs(session_.signalbases());
885
886         // Sort signals in natural order
887         vector< shared_ptr<data::SignalBase> > sig_list(sigs.begin(), sigs.end());
888         sort(sig_list.begin(), sig_list.end(),
889                 [](const shared_ptr<data::SignalBase> &a,
890                 const shared_ptr<data::SignalBase> &b) {
891                         return strnatcasecmp(a->name().toStdString(),
892                                 b->name().toStdString()) < 0; });
893
894         QComboBox *selector = new QComboBox(parent);
895
896         selector->addItem("-", qVariantFromValue((void*)nullptr));
897
898         if (!ch->assigned_signal)
899                 selector->setCurrentIndex(0);
900
901         for (const shared_ptr<data::SignalBase> &b : sig_list) {
902                 assert(b);
903                 if (b->logic_data() && b->enabled()) {
904                         selector->addItem(b->name(),
905                                 qVariantFromValue((void*)b.get()));
906
907                         if (ch->assigned_signal == b.get())
908                                 selector->setCurrentIndex(selector->count() - 1);
909                 }
910         }
911
912         return selector;
913 }
914
915 QComboBox* DecodeTrace::create_channel_selector_init_state(QWidget *parent,
916         const DecodeChannel *ch)
917 {
918         QComboBox *selector = new QComboBox(parent);
919
920         selector->addItem("0", qVariantFromValue((int)SRD_INITIAL_PIN_LOW));
921         selector->addItem("1", qVariantFromValue((int)SRD_INITIAL_PIN_HIGH));
922         selector->addItem("X", qVariantFromValue((int)SRD_INITIAL_PIN_SAME_AS_SAMPLE0));
923
924         selector->setCurrentIndex(ch->initial_pin_state);
925
926         selector->setToolTip("Initial (assumed) pin value before the first sample");
927
928         return selector;
929 }
930
931 void DecodeTrace::export_annotations(vector<Annotation> *annotations) const
932 {
933         using namespace pv::data::decode;
934
935         GlobalSettings settings;
936         const QString dir = settings.value("MainWindow/SaveDirectory").toString();
937
938         const QString file_name = QFileDialog::getSaveFileName(
939                 owner_->view(), tr("Export annotations"), dir, tr("Text Files (*.txt);;All Files (*)"));
940
941         if (file_name.isEmpty())
942                 return;
943
944         QString format = settings.value(GlobalSettings::Key_Dec_ExportFormat).toString();
945         const QString quote = format.contains("%q") ? "\"" : "";
946         format = format.remove("%q");
947
948         QFile file(file_name);
949         if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
950                 QTextStream out_stream(&file);
951
952                 for (Annotation &ann : *annotations) {
953                         const QString sample_range = QString("%1-%2") \
954                                 .arg(QString::number(ann.start_sample()), QString::number(ann.end_sample()));
955
956                         const QString class_name = quote + ann.row()->class_name() + quote;
957
958                         QString all_ann_text;
959                         for (const QString &s : ann.annotations())
960                                 all_ann_text = all_ann_text + quote + s + quote + ",";
961                         all_ann_text.chop(1);
962
963                         const QString first_ann_text = quote + ann.annotations().front() + quote;
964
965                         QString out_text = format;
966                         out_text = out_text.replace("%s", sample_range);
967                         out_text = out_text.replace("%d",
968                                 quote + QString::fromUtf8(ann.row()->decoder()->name) + quote);
969                         out_text = out_text.replace("%c", class_name);
970                         out_text = out_text.replace("%1", first_ann_text);
971                         out_text = out_text.replace("%a", all_ann_text);
972                         out_stream << out_text << '\n';
973                 }
974
975                 if (out_stream.status() == QTextStream::Ok)
976                         return;
977         }
978
979         QMessageBox msg(owner_->view());
980         msg.setText(tr("Error"));
981         msg.setInformativeText(tr("File %1 could not be written to.").arg(file_name));
982         msg.setStandardButtons(QMessageBox::Ok);
983         msg.setIcon(QMessageBox::Warning);
984         msg.exec();
985 }
986
987 void DecodeTrace::on_new_annotations()
988 {
989         if (!delayed_trace_updater_.isActive())
990                 delayed_trace_updater_.start();
991 }
992
993 void DecodeTrace::on_delayed_trace_update()
994 {
995         if (owner_)
996                 owner_->row_item_appearance_changed(false, true);
997 }
998
999 void DecodeTrace::on_decode_reset()
1000 {
1001         visible_rows_.clear();
1002         max_visible_rows_ = 0;
1003
1004         if (owner_)
1005                 owner_->row_item_appearance_changed(false, true);
1006 }
1007
1008 void DecodeTrace::on_decode_finished()
1009 {
1010         if (owner_)
1011                 owner_->row_item_appearance_changed(false, true);
1012 }
1013
1014 void DecodeTrace::delete_pressed()
1015 {
1016         on_delete();
1017 }
1018
1019 void DecodeTrace::on_delete()
1020 {
1021         session_.remove_decode_signal(decode_signal_);
1022 }
1023
1024 void DecodeTrace::on_channel_selected(int)
1025 {
1026         QComboBox *cb = qobject_cast<QComboBox*>(QObject::sender());
1027
1028         // Determine signal that was selected
1029         const data::SignalBase *signal =
1030                 (data::SignalBase*)cb->itemData(cb->currentIndex()).value<void*>();
1031
1032         // Determine decode channel ID this combo box is the channel selector for
1033         const uint16_t id = channel_id_map_.at(cb);
1034
1035         decode_signal_->assign_signal(id, signal);
1036 }
1037
1038 void DecodeTrace::on_channels_updated()
1039 {
1040         if (owner_)
1041                 owner_->row_item_appearance_changed(false, true);
1042 }
1043
1044 void DecodeTrace::on_init_state_changed(int)
1045 {
1046         QComboBox *cb = qobject_cast<QComboBox*>(QObject::sender());
1047
1048         // Determine inital pin state that was selected
1049         int init_state = cb->itemData(cb->currentIndex()).value<int>();
1050
1051         // Determine decode channel ID this combo box is the channel selector for
1052         const uint16_t id = init_state_map_.at(cb);
1053
1054         decode_signal_->set_initial_pin_state(id, init_state);
1055 }
1056
1057 void DecodeTrace::on_stack_decoder(srd_decoder *decoder)
1058 {
1059         decode_signal_->stack_decoder(decoder);
1060
1061         create_popup_form();
1062 }
1063
1064 void DecodeTrace::on_delete_decoder(int index)
1065 {
1066         decode_signal_->remove_decoder(index);
1067
1068         // Force re-calculation of the trace height, see paint_mid()
1069         max_visible_rows_ = 0;
1070         owner_->extents_changed(false, true);
1071
1072         // Update the popup
1073         create_popup_form();
1074 }
1075
1076 void DecodeTrace::on_show_hide_decoder(int index)
1077 {
1078         const bool state = decode_signal_->toggle_decoder_visibility(index);
1079
1080         assert(index < (int)decoder_forms_.size());
1081         decoder_forms_[index]->set_decoder_visible(state);
1082
1083         if (!state) {
1084                 // Force re-calculation of the trace height, see paint_mid()
1085                 max_visible_rows_ = 0;
1086                 owner_->extents_changed(false, true);
1087         }
1088
1089         if (owner_)
1090                 owner_->row_item_appearance_changed(false, true);
1091 }
1092
1093 void DecodeTrace::on_export_row()
1094 {
1095         selected_samplepos_ = 0;
1096         on_export_row_from_here();
1097 }
1098
1099 void DecodeTrace::on_export_all_rows()
1100 {
1101         selected_samplepos_ = 0;
1102         on_export_all_rows_from_here();
1103 }
1104
1105 void DecodeTrace::on_export_row_from_here()
1106 {
1107         using namespace pv::data::decode;
1108
1109         if (!selected_row_)
1110                 return;
1111
1112         vector<Annotation> *annotations = new vector<Annotation>();
1113
1114         decode_signal_->get_annotation_subset(*annotations, *selected_row_,
1115                 current_segment_, selected_samplepos_, ULLONG_MAX);
1116
1117         if (annotations->empty())
1118                 return;
1119
1120         export_annotations(annotations);
1121         delete annotations;
1122 }
1123
1124 void DecodeTrace::on_export_all_rows_from_here()
1125 {
1126         using namespace pv::data::decode;
1127
1128         vector<Annotation> *annotations = new vector<Annotation>();
1129
1130         decode_signal_->get_annotation_subset(*annotations, current_segment_,
1131                 selected_samplepos_, ULLONG_MAX);
1132
1133         if (!annotations->empty())
1134                 export_annotations(annotations);
1135
1136         delete annotations;
1137 }
1138
1139 } // namespace trace
1140 } // namespace views
1141 } // namespace pv