]> sigrok.org Git - pulseview.git/blob - pv/view/decodetrace.cpp
22d8f2dce06ceff5b0c46e8a185550ce52fc81ba
[pulseview.git] / pv / view / 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, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 extern "C" {
22 #include <libsigrokdecode/libsigrokdecode.h>
23 }
24
25 #include <extdef.h>
26
27 #include <boost/foreach.hpp>
28
29 #include <QAction>
30 #include <QApplication>
31 #include <QComboBox>
32 #include <QFormLayout>
33 #include <QLabel>
34 #include <QMenu>
35 #include <QPushButton>
36
37 #include "decodetrace.h"
38
39 #include <pv/sigsession.h>
40 #include <pv/data/decoderstack.h>
41 #include <pv/data/decode/decoder.h>
42 #include <pv/data/logic.h>
43 #include <pv/data/logicsnapshot.h>
44 #include <pv/data/decode/annotation.h>
45 #include <pv/view/logicsignal.h>
46 #include <pv/view/view.h>
47 #include <pv/widgets/decodergroupbox.h>
48 #include <pv/widgets/decodermenu.h>
49
50 using boost::dynamic_pointer_cast;
51 using boost::shared_ptr;
52 using std::list;
53 using std::max;
54 using std::map;
55 using std::min;
56 using std::vector;
57
58 namespace pv {
59 namespace view {
60
61 const QColor DecodeTrace::DecodeColours[4] = {
62         QColor(0xEF, 0x29, 0x29),       // Red
63         QColor(0xFC, 0xE9, 0x4F),       // Yellow
64         QColor(0x8A, 0xE2, 0x34),       // Green
65         QColor(0x72, 0x9F, 0xCF)        // Blue
66 };
67
68 const QColor DecodeTrace::ErrorBgColour = QColor(0xEF, 0x29, 0x29);
69 const QColor DecodeTrace::NoDecodeColour = QColor(0x88, 0x8A, 0x85);
70
71 const double DecodeTrace::EndCapWidth = 5;
72 const int DecodeTrace::DrawPadding = 100;
73
74 const QColor DecodeTrace::Colours[7] = {
75         QColor(0xFC, 0xE9, 0x4F),       // Light Butter
76         QColor(0xFC, 0xAF, 0x3E),       // Light Orange
77         QColor(0xE9, 0xB9, 0x6E),       // Light Chocolate
78         QColor(0x8A, 0xE2, 0x34),       // Light Green
79         QColor(0x72, 0x9F, 0xCF),       // Light Blue
80         QColor(0xAD, 0x7F, 0xA8),       // Light Plum
81         QColor(0xEF, 0x29, 0x29)        // Light Red
82 };
83
84 DecodeTrace::DecodeTrace(pv::SigSession &session,
85         boost::shared_ptr<pv::data::DecoderStack> decoder_stack, int index) :
86         Trace(session, QString::fromUtf8(
87                 decoder_stack->stack().front()->decoder()->name)),
88         _decoder_stack(decoder_stack),
89         _delete_mapper(this),
90         _show_hide_mapper(this)
91 {
92         assert(_decoder_stack);
93
94         _colour = DecodeColours[index % countof(DecodeColours)];
95
96         connect(_decoder_stack.get(), SIGNAL(new_decode_data()),
97                 this, SLOT(on_new_decode_data()));
98         connect(&_delete_mapper, SIGNAL(mapped(int)),
99                 this, SLOT(on_delete_decoder(int)));
100         connect(&_show_hide_mapper, SIGNAL(mapped(int)),
101                 this, SLOT(on_show_hide_decoder(int)));
102 }
103
104 bool DecodeTrace::enabled() const
105 {
106         return true;
107 }
108
109 const boost::shared_ptr<pv::data::DecoderStack>& DecodeTrace::decoder() const
110 {
111         return _decoder_stack;
112 }
113
114 void DecodeTrace::set_view(pv::view::View *view)
115 {
116         assert(view);
117         Trace::set_view(view);
118 }
119
120 void DecodeTrace::paint_back(QPainter &p, int left, int right)
121 {
122         Trace::paint_back(p, left, right);
123         paint_axis(p, get_y(), left, right);
124 }
125
126 void DecodeTrace::paint_mid(QPainter &p, int left, int right)
127 {
128         using namespace pv::data::decode;
129
130         const double scale = _view->scale();
131         assert(scale > 0);
132
133         double samplerate = _decoder_stack->samplerate();
134
135         // Show sample rate as 1Hz when it is unknown
136         if (samplerate == 0.0)
137                 samplerate = 1.0;
138
139         const double pixels_offset = (_view->offset() -
140                 _decoder_stack->get_start_time()) / scale;
141         const double samples_per_pixel = samplerate * scale;
142
143         const uint64_t start_sample = (uint64_t)max((left + pixels_offset) *
144                 samples_per_pixel, 0.0);
145         const uint64_t end_sample = (uint64_t)max((right + pixels_offset) *
146                 samples_per_pixel, 0.0);
147
148         QFontMetrics m(QApplication::font());
149         const int text_height =  m.boundingRect(QRect(), 0, "Tg").height();
150         const int annotation_height = (text_height * 5) / 4;
151         const int row_height = (text_height * 6) / 4;
152
153         assert(_decoder_stack);
154         const QString err = _decoder_stack->error_message();
155         if (!err.isEmpty())
156         {
157                 draw_error(p, err, left, right);
158                 draw_unresolved_period(p, annotation_height, left, right,
159                         samples_per_pixel, pixels_offset);
160                 return;
161         }
162
163         // Iterate through the rows
164         assert(_view);
165         int y = get_y();
166
167         assert(_decoder_stack);
168
169         const vector<Row> rows(_decoder_stack->get_visible_rows());
170         for (size_t i = 0; i < rows.size(); i++)
171         {
172                 const Row &row = rows[i];
173                 vector<Annotation> annotations;
174                 _decoder_stack->get_annotation_subset(annotations, row,
175                         start_sample, end_sample);
176                 if (!annotations.empty()) {
177                         BOOST_FOREACH(const Annotation &a, annotations)
178                                 draw_annotation(a, p, get_text_colour(),
179                                         annotation_height, left, right,
180                                         samples_per_pixel, pixels_offset, y, i);
181                         y += row_height;
182                 }
183         }
184
185         // Draw the hatching
186         draw_unresolved_period(p, annotation_height, left, right,
187                 samples_per_pixel, pixels_offset);
188 }
189
190 void DecodeTrace::populate_popup_form(QWidget *parent, QFormLayout *form)
191 {
192         using pv::data::decode::Decoder;
193
194         assert(form);
195         assert(parent);
196         assert(_decoder_stack);
197
198         // Add the standard options
199         Trace::populate_popup_form(parent, form);
200
201         // Add the decoder options
202         _bindings.clear();
203         _probe_selectors.clear();
204         _decoder_forms.clear();
205
206         const list< shared_ptr<Decoder> >& stack = _decoder_stack->stack();
207
208         if (stack.empty())
209         {
210                 QLabel *const l = new QLabel(
211                         tr("<p><i>No decoders in the stack</i></p>"));
212                 l->setAlignment(Qt::AlignCenter);
213                 form->addRow(l);
214         }
215         else
216         {
217                 list< shared_ptr<Decoder> >::const_iterator iter =
218                         stack.begin();
219                 for (int i = 0; i < (int)stack.size(); i++, iter++) {
220                         shared_ptr<Decoder> dec(*iter);
221                         create_decoder_form(i, dec, parent, form);
222                 }
223
224                 form->addRow(new QLabel(
225                         tr("<i>* Required Probes</i>"), parent));
226         }
227
228         // Add stacking button
229         pv::widgets::DecoderMenu *const decoder_menu =
230                 new pv::widgets::DecoderMenu(parent);
231         connect(decoder_menu, SIGNAL(decoder_selected(srd_decoder*)),
232                 this, SLOT(on_stack_decoder(srd_decoder*)));
233
234         QPushButton *const stack_button =
235                 new QPushButton(tr("Stack Decoder"), parent);
236         stack_button->setMenu(decoder_menu);
237
238         QHBoxLayout *stack_button_box = new QHBoxLayout;
239         stack_button_box->addWidget(stack_button, 0, Qt::AlignRight);
240         form->addRow(stack_button_box);
241 }
242
243 QMenu* DecodeTrace::create_context_menu(QWidget *parent)
244 {
245         QMenu *const menu = Trace::create_context_menu(parent);
246
247         menu->addSeparator();
248
249         QAction *const del = new QAction(tr("Delete"), this);
250         del->setShortcuts(QKeySequence::Delete);
251         connect(del, SIGNAL(triggered()), this, SLOT(on_delete()));
252         menu->addAction(del);
253
254         return menu;
255 }
256
257 void DecodeTrace::draw_annotation(const pv::data::decode::Annotation &a, QPainter &p,
258         QColor text_color, int h, int left, int right, double samples_per_pixel,
259         double pixels_offset, int y, unsigned int row_index) const
260 {
261         const double start = a.start_sample() / samples_per_pixel -
262                 pixels_offset;
263         const double end = a.end_sample() / samples_per_pixel -
264                 pixels_offset;
265         const QColor fill = Colours[((row_index * 2 + a.format()) *
266                 (countof(Colours) / 4 + 1)) % countof(Colours)];
267         const QColor outline(fill.darker());
268
269         if (start > right + DrawPadding || end < left - DrawPadding)
270                 return;
271
272         if (a.start_sample() == a.end_sample())
273                 draw_instant(a, p, fill, outline, text_color, h,
274                         start, y);
275         else
276                 draw_range(a, p, fill, outline, text_color, h,
277                         start, end, y);
278 }
279
280 void DecodeTrace::draw_instant(const pv::data::decode::Annotation &a, QPainter &p,
281         QColor fill, QColor outline, QColor text_color, int h, double x, int y) const
282 {
283         const QString text = a.annotations().empty() ?
284                 QString() : a.annotations().back();
285         const double w = min(p.boundingRect(QRectF(), 0, text).width(),
286                 0.0) + h;
287         const QRectF rect(x - w / 2, y - h / 2, w, h);
288
289         p.setPen(outline);
290         p.setBrush(fill);
291         p.drawRoundedRect(rect, h / 2, h / 2);
292
293         p.setPen(text_color);
294         p.drawText(rect, Qt::AlignCenter | Qt::AlignVCenter, text);
295 }
296
297 void DecodeTrace::draw_range(const pv::data::decode::Annotation &a, QPainter &p,
298         QColor fill, QColor outline, QColor text_color, int h, double start,
299         double end, int y) const
300 {
301         const double top = y + .5 - h / 2;
302         const double bottom = y + .5 + h / 2;
303         const vector<QString> annotations = a.annotations();
304
305         p.setPen(outline);
306         p.setBrush(fill);
307
308         // If the two ends are within 1 pixel, draw a vertical line
309         if (start + 1.0 > end)
310         {
311                 p.drawLine(QPointF(start, top), QPointF(start, bottom));
312                 return;
313         }
314
315         const double cap_width = min((end - start) / 4, EndCapWidth);
316
317         QPointF pts[] = {
318                 QPointF(start, y + .5f),
319                 QPointF(start + cap_width, top),
320                 QPointF(end - cap_width, top),
321                 QPointF(end, y + .5f),
322                 QPointF(end - cap_width, bottom),
323                 QPointF(start + cap_width, bottom)
324         };
325
326         p.drawConvexPolygon(pts, countof(pts));
327
328         if (annotations.empty())
329                 return;
330
331         QRectF rect(start + cap_width, y - h / 2,
332                 end - start - cap_width * 2, h);
333         p.setPen(text_color);
334
335         // Try to find an annotation that will fit
336         QString best_annotation;
337         int best_width = 0;
338
339         BOOST_FOREACH(const QString &a, annotations) {
340                 const int w = p.boundingRect(QRectF(), 0, a).width();
341                 if (w <= rect.width() && w > best_width)
342                         best_annotation = a, best_width = w;
343         }
344
345         if (best_annotation.isEmpty())
346                 best_annotation = annotations.back();
347
348         // If not ellide the last in the list
349         p.drawText(rect, Qt::AlignCenter, p.fontMetrics().elidedText(
350                 best_annotation, Qt::ElideRight, rect.width()));
351 }
352
353 void DecodeTrace::draw_error(QPainter &p, const QString &message,
354         int left, int right)
355 {
356         const int y = get_y();
357
358         p.setPen(ErrorBgColour.darker());
359         p.setBrush(ErrorBgColour);
360
361         const QRectF bounding_rect =
362                 QRectF(left, INT_MIN / 2 + y, right - left, INT_MAX);
363         const QRectF text_rect = p.boundingRect(bounding_rect,
364                 Qt::AlignCenter, message);
365         const float r = text_rect.height() / 4;
366
367         p.drawRoundedRect(text_rect.adjusted(-r, -r, r, r), r, r,
368                 Qt::AbsoluteSize);
369
370         p.setPen(get_text_colour());
371         p.drawText(text_rect, message);
372 }
373
374 void DecodeTrace::draw_unresolved_period(QPainter &p, int h, int left,
375         int right, double samples_per_pixel, double pixels_offset) 
376 {
377         using namespace pv::data;
378         using pv::data::decode::Decoder;
379
380         assert(_decoder_stack); 
381
382         shared_ptr<Logic> data;
383         shared_ptr<LogicSignal> logic_signal;
384
385         const list< shared_ptr<Decoder> > &stack = _decoder_stack->stack();
386
387         // We get the logic data of the first probe in the list.
388         // This works because we are currently assuming all
389         // LogicSignals have the same data/snapshot
390         BOOST_FOREACH (const shared_ptr<Decoder> &dec, stack)
391                 if (dec && !dec->probes().empty() &&
392                         ((logic_signal = (*dec->probes().begin()).second)) &&
393                         ((data = logic_signal->logic_data())))
394                         break;
395
396         if (!data || data->get_snapshots().empty())
397                 return;
398
399         const shared_ptr<LogicSnapshot> snapshot =
400                 data->get_snapshots().front();
401         assert(snapshot);
402         const int64_t sample_count = (int64_t)snapshot->get_sample_count();
403         if (sample_count == 0)
404                 return;
405
406         const int64_t samples_decoded = _decoder_stack->samples_decoded();
407         if (sample_count == samples_decoded)
408                 return;
409
410         const int y = get_y();
411         const double start = max(samples_decoded /
412                 samples_per_pixel - pixels_offset, left - 1.0);
413         const double end = min(sample_count / samples_per_pixel -
414                 pixels_offset, right + 1.0);
415         const QRectF no_decode_rect(start, y - h/2 + 0.5, end - start, h);
416
417         p.setPen(QPen(Qt::NoPen));
418         p.setBrush(Qt::white);
419         p.drawRect(no_decode_rect);
420
421         p.setPen(NoDecodeColour);
422         p.setBrush(QBrush(NoDecodeColour, Qt::Dense6Pattern));
423         p.drawRect(no_decode_rect);
424 }
425
426 void DecodeTrace::create_decoder_form(int index,
427         shared_ptr<data::decode::Decoder> &dec, QWidget *parent,
428         QFormLayout *form)
429 {
430         const GSList *probe;
431
432         assert(dec);
433         const srd_decoder *const decoder = dec->decoder();
434         assert(decoder);
435
436         pv::widgets::DecoderGroupBox *const group =
437                 new pv::widgets::DecoderGroupBox(
438                         QString::fromUtf8(decoder->name));
439         group->set_decoder_visible(dec->shown());
440
441         _delete_mapper.setMapping(group, index);
442         connect(group, SIGNAL(delete_decoder()), &_delete_mapper, SLOT(map()));
443
444         _show_hide_mapper.setMapping(group, index);
445         connect(group, SIGNAL(show_hide_decoder()),
446                 &_show_hide_mapper, SLOT(map()));
447
448         QFormLayout *const decoder_form = new QFormLayout;
449         group->add_layout(decoder_form);
450
451         // Add the mandatory probes
452         for(probe = decoder->probes; probe; probe = probe->next) {
453                 const struct srd_probe *const p =
454                         (struct srd_probe *)probe->data;
455                 QComboBox *const combo = create_probe_selector(parent, dec, p);
456                 connect(combo, SIGNAL(currentIndexChanged(int)),
457                         this, SLOT(on_probe_selected(int)));
458                 decoder_form->addRow(tr("<b>%1</b> (%2) *")
459                         .arg(p->name).arg(p->desc), combo);
460
461                 const ProbeSelector s = {combo, dec, p};
462                 _probe_selectors.push_back(s);
463         }
464
465         // Add the optional probes
466         for(probe = decoder->opt_probes; probe; probe = probe->next) {
467                 const struct srd_probe *const p =
468                         (struct srd_probe *)probe->data;
469                 QComboBox *const combo = create_probe_selector(parent, dec, p);
470                 connect(combo, SIGNAL(currentIndexChanged(int)),
471                         this, SLOT(on_probe_selected(int)));
472                 decoder_form->addRow(tr("<b>%1</b> (%2)")
473                         .arg(p->name).arg(p->desc), combo);
474
475                 const ProbeSelector s = {combo, dec, p};
476                 _probe_selectors.push_back(s);
477         }
478
479         // Add the options
480         shared_ptr<prop::binding::DecoderOptions> binding(
481                 new prop::binding::DecoderOptions(_decoder_stack, dec));
482         binding->add_properties_to_form(decoder_form, true);
483
484         _bindings.push_back(binding);
485
486         form->addRow(group);
487         _decoder_forms.push_back(group);
488 }
489
490 QComboBox* DecodeTrace::create_probe_selector(
491         QWidget *parent, const shared_ptr<data::decode::Decoder> &dec,
492         const srd_probe *const probe)
493 {
494         assert(dec);
495
496         const vector< shared_ptr<Signal> > sigs = _session.get_signals();
497
498         assert(_decoder_stack);
499         const map<const srd_probe*,
500                 shared_ptr<LogicSignal> >::const_iterator probe_iter =
501                 dec->probes().find(probe);
502
503         QComboBox *selector = new QComboBox(parent);
504
505         selector->addItem("-", qVariantFromValue((void*)NULL));
506
507         if (probe_iter == dec->probes().end())
508                 selector->setCurrentIndex(0);
509
510         for(size_t i = 0; i < sigs.size(); i++) {
511                 const shared_ptr<view::Signal> s(sigs[i]);
512                 assert(s);
513
514                 if (dynamic_pointer_cast<LogicSignal>(s) && s->enabled())
515                 {
516                         selector->addItem(s->get_name(),
517                                 qVariantFromValue((void*)s.get()));
518                         if ((*probe_iter).second == s)
519                                 selector->setCurrentIndex(i + 1);
520                 }
521         }
522
523         return selector;
524 }
525
526 void DecodeTrace::commit_decoder_probes(shared_ptr<data::decode::Decoder> &dec)
527 {
528         assert(dec);
529
530         map<const srd_probe*, shared_ptr<LogicSignal> > probe_map;
531         const vector< shared_ptr<Signal> > sigs = _session.get_signals();
532
533         BOOST_FOREACH(const ProbeSelector &s, _probe_selectors)
534         {
535                 if(s._decoder != dec)
536                         break;
537
538                 const LogicSignal *const selection =
539                         (LogicSignal*)s._combo->itemData(
540                                 s._combo->currentIndex()).value<void*>();
541
542                 BOOST_FOREACH(shared_ptr<Signal> sig, sigs)
543                         if(sig.get() == selection) {
544                                 probe_map[s._probe] =
545                                         dynamic_pointer_cast<LogicSignal>(sig);
546                                 break;
547                         }
548         }
549
550         dec->set_probes(probe_map);
551 }
552
553 void DecodeTrace::commit_probes()
554 {
555         assert(_decoder_stack);
556         BOOST_FOREACH(shared_ptr<data::decode::Decoder> dec,
557                 _decoder_stack->stack())
558                 commit_decoder_probes(dec);
559
560         _decoder_stack->begin_decode();
561 }
562
563 void DecodeTrace::on_new_decode_data()
564 {
565         if (_view)
566                 _view->update_viewport();
567 }
568
569 void DecodeTrace::delete_pressed()
570 {
571         on_delete();
572 }
573
574 void DecodeTrace::on_delete()
575 {
576         _session.remove_decode_signal(this);
577 }
578
579 void DecodeTrace::on_probe_selected(int)
580 {
581         commit_probes();
582 }
583
584 void DecodeTrace::on_stack_decoder(srd_decoder *decoder)
585 {
586         assert(decoder);
587         assert(_decoder_stack);
588         _decoder_stack->push(shared_ptr<data::decode::Decoder>(
589                 new data::decode::Decoder(decoder)));
590         _decoder_stack->begin_decode();
591
592         create_popup_form();
593 }
594
595 void DecodeTrace::on_delete_decoder(int index)
596 {
597         _decoder_stack->remove(index);
598
599         // Update the popup
600         create_popup_form();    
601
602         _decoder_stack->begin_decode();
603 }
604
605 void DecodeTrace::on_show_hide_decoder(int index)
606 {
607         using pv::data::decode::Decoder;
608
609         const list< shared_ptr<Decoder> > stack(_decoder_stack->stack());
610
611         // Find the decoder in the stack
612         list< shared_ptr<Decoder> >::const_iterator iter = stack.begin();
613         for(int i = 0; i < index; i++, iter++)
614                 assert(iter != stack.end());
615
616         shared_ptr<Decoder> dec = *iter;
617         assert(dec);
618
619         const bool show = !dec->shown();
620         dec->show(show);
621
622         assert(index < (int)_decoder_forms.size());
623         _decoder_forms[index]->set_decoder_visible(show);
624
625         _view->update_viewport();
626 }
627
628 } // namespace view
629 } // namespace pv