Session: Improve session robustness
[pulseview.git] / pv / view / logicsignal.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 #include <extdef.h>
22
23 #include <cassert>
24 #include <cmath>
25
26 #include <algorithm>
27
28 #include <QApplication>
29 #include <QFormLayout>
30 #include <QToolBar>
31
32 #include "logicsignal.hpp"
33 #include "view.hpp"
34
35 #include <pv/session.hpp>
36 #include <pv/devicemanager.hpp>
37 #include <pv/devices/device.hpp>
38 #include <pv/data/logic.hpp>
39 #include <pv/data/logicsegment.hpp>
40 #include <pv/view/view.hpp>
41
42 #include <libsigrokcxx/libsigrokcxx.hpp>
43
44 using std::deque;
45 using std::max;
46 using std::make_pair;
47 using std::min;
48 using std::pair;
49 using std::shared_ptr;
50 using std::vector;
51
52 using sigrok::Channel;
53 using sigrok::ConfigKey;
54 using sigrok::Capability;
55 using sigrok::Error;
56 using sigrok::Trigger;
57 using sigrok::TriggerStage;
58 using sigrok::TriggerMatch;
59 using sigrok::TriggerMatchType;
60
61 namespace pv {
62 namespace view {
63
64 const float LogicSignal::Oversampling = 2.0f;
65
66 const QColor LogicSignal::EdgeColour(0x80, 0x80, 0x80);
67 const QColor LogicSignal::HighColour(0x00, 0xC0, 0x00);
68 const QColor LogicSignal::LowColour(0xC0, 0x00, 0x00);
69
70 const QColor LogicSignal::SignalColours[10] = {
71         QColor(0x16, 0x19, 0x1A),       // Black
72         QColor(0x8F, 0x52, 0x02),       // Brown
73         QColor(0xCC, 0x00, 0x00),       // Red
74         QColor(0xF5, 0x79, 0x00),       // Orange
75         QColor(0xED, 0xD4, 0x00),       // Yellow
76         QColor(0x73, 0xD2, 0x16),       // Green
77         QColor(0x34, 0x65, 0xA4),       // Blue
78         QColor(0x75, 0x50, 0x7B),       // Violet
79         QColor(0x88, 0x8A, 0x85),       // Grey
80         QColor(0xEE, 0xEE, 0xEC),       // White
81 };
82
83 QColor LogicSignal::TriggerMarkerBackgroundColour = QColor(0xED, 0xD4, 0x00);
84 const int LogicSignal::TriggerMarkerPadding = 2;
85 const char* LogicSignal::TriggerMarkerIcons[8] = {
86         nullptr,
87         ":/icons/trigger-marker-low.svg",
88         ":/icons/trigger-marker-high.svg",
89         ":/icons/trigger-marker-rising.svg",
90         ":/icons/trigger-marker-falling.svg",
91         ":/icons/trigger-marker-change.svg",
92         nullptr,
93         nullptr
94 };
95
96 QCache<QString, const QIcon> LogicSignal::icon_cache_;
97 QCache<QString, const QPixmap> LogicSignal::pixmap_cache_;
98
99 LogicSignal::LogicSignal(
100         pv::Session &session,
101         shared_ptr<devices::Device> device,
102         shared_ptr<Channel> channel,
103         shared_ptr<data::Logic> data) :
104         Signal(session, channel),
105         signal_height_(QFontMetrics(QApplication::font()).height() * 2),
106         device_(device),
107         data_(data),
108         trigger_none_(nullptr),
109         trigger_rising_(nullptr),
110         trigger_high_(nullptr),
111         trigger_falling_(nullptr),
112         trigger_low_(nullptr),
113         trigger_change_(nullptr)
114 {
115         shared_ptr<Trigger> trigger;
116
117         set_colour(SignalColours[channel->index() % countof(SignalColours)]);
118
119         /* Populate this channel's trigger setting with whatever we
120          * find in the current session trigger, if anything. */
121         trigger_match_ = nullptr;
122         if ((trigger = session_.session()->trigger()))
123                 for (auto stage : trigger->stages())
124                         for (auto match : stage->matches())
125                                 if (match->channel() == channel_)
126                                         trigger_match_ = match->type();
127 }
128
129 shared_ptr<pv::data::SignalData> LogicSignal::data() const
130 {
131         return data_;
132 }
133
134 shared_ptr<pv::data::Logic> LogicSignal::logic_data() const
135 {
136         return data_;
137 }
138
139 void LogicSignal::set_logic_data(std::shared_ptr<pv::data::Logic> data)
140 {
141         data_ = data;
142 }
143
144 std::pair<int, int> LogicSignal::v_extents() const
145 {
146         const int signal_margin =
147                 QFontMetrics(QApplication::font()).height() / 2;
148         return make_pair(-signal_height_ - signal_margin, signal_margin);
149 }
150
151 int LogicSignal::scale_handle_offset() const
152 {
153         return -signal_height_;
154 }
155
156 void LogicSignal::scale_handle_dragged(int offset)
157 {
158         const int font_height = QFontMetrics(QApplication::font()).height();
159         const int units = (-offset / font_height);
160         signal_height_ = ((units < 1) ? 1 : units) * font_height;
161 }
162
163 void LogicSignal::paint_mid(QPainter &p, const ViewItemPaintParams &pp)
164 {
165         QLineF *line;
166
167         vector< pair<int64_t, bool> > edges;
168
169         assert(channel_);
170         assert(data_);
171         assert(owner_);
172
173         const int y = get_visual_y();
174
175         if (!channel_->enabled())
176                 return;
177
178         const float high_offset = y - signal_height_ + 0.5f;
179         const float low_offset = y + 0.5f;
180
181         const deque< shared_ptr<pv::data::LogicSegment> > &segments =
182                 data_->logic_segments();
183         if (segments.empty())
184                 return;
185
186         const shared_ptr<pv::data::LogicSegment> &segment =
187                 segments.front();
188
189         double samplerate = segment->samplerate();
190
191         // Show sample rate as 1Hz when it is unknown
192         if (samplerate == 0.0)
193                 samplerate = 1.0;
194
195         const double pixels_offset = pp.pixels_offset();
196         const pv::util::Timestamp& start_time = segment->start_time();
197         const int64_t last_sample = segment->get_sample_count() - 1;
198         const double samples_per_pixel = samplerate * pp.scale();
199         const pv::util::Timestamp start = samplerate * (pp.offset() - start_time);
200         const pv::util::Timestamp end = start + samples_per_pixel * pp.width();
201
202         const int64_t start_sample = min(max(floor(start).convert_to<int64_t>(),
203                 (int64_t)0), last_sample);
204         const uint64_t end_sample = min(max(ceil(end).convert_to<int64_t>(),
205                 (int64_t)0), last_sample);
206
207         segment->get_subsampled_edges(edges, start_sample, end_sample,
208                 samples_per_pixel / Oversampling, channel_->index());
209         assert(edges.size() >= 2);
210
211         // Paint the edges
212         const unsigned int edge_count = edges.size() - 2;
213         QLineF *const edge_lines = new QLineF[edge_count];
214         line = edge_lines;
215
216         for (auto i = edges.cbegin() + 1; i != edges.cend() - 1; i++) {
217                 const float x = ((*i).first / samples_per_pixel -
218                         pixels_offset) + pp.left();
219                 *line++ = QLineF(x, high_offset, x, low_offset);
220         }
221
222         p.setPen(EdgeColour);
223         p.drawLines(edge_lines, edge_count);
224         delete[] edge_lines;
225
226         // Paint the caps
227         const unsigned int max_cap_line_count = edges.size();
228         QLineF *const cap_lines = new QLineF[max_cap_line_count];
229
230         p.setPen(HighColour);
231         paint_caps(p, cap_lines, edges, true, samples_per_pixel,
232                 pixels_offset, pp.left(), high_offset);
233         p.setPen(LowColour);
234         paint_caps(p, cap_lines, edges, false, samples_per_pixel,
235                 pixels_offset, pp.left(), low_offset);
236
237         delete[] cap_lines;
238 }
239
240 void LogicSignal::paint_fore(QPainter &p, const ViewItemPaintParams &pp)
241 {
242         // Draw the trigger marker
243         if (!trigger_match_ || !channel_->enabled())
244                 return;
245
246         const int y = get_visual_y();
247         const vector<int32_t> trig_types = get_trigger_types();
248         for (int32_t type_id : trig_types) {
249                 const TriggerMatchType *const type =
250                         TriggerMatchType::get(type_id);
251                 if (trigger_match_ != type || type_id < 0 ||
252                         (size_t)type_id >= countof(TriggerMarkerIcons) ||
253                         !TriggerMarkerIcons[type_id])
254                         continue;
255
256                 const QPixmap *const pixmap = get_pixmap(
257                         TriggerMarkerIcons[type_id]);
258                 if (!pixmap)
259                         continue;
260
261                 const float pad = TriggerMarkerPadding - 0.5f;
262                 const QSize size = pixmap->size();
263                 const QPoint point(
264                         pp.right() - size.width() - pad * 2,
265                         y - (signal_height_ + size.height()) / 2);
266
267                 p.setPen(QPen(TriggerMarkerBackgroundColour.darker()));
268                 p.setBrush(TriggerMarkerBackgroundColour);
269                 p.drawRoundedRect(QRectF(point, size).adjusted(
270                         -pad, -pad, pad, pad), pad, pad);
271                 p.drawPixmap(point, *pixmap);
272
273                 break;
274         }
275 }
276
277 void LogicSignal::paint_caps(QPainter &p, QLineF *const lines,
278         vector< pair<int64_t, bool> > &edges, bool level,
279         double samples_per_pixel, double pixels_offset, float x_offset,
280         float y_offset)
281 {
282         QLineF *line = lines;
283
284         for (auto i = edges.begin(); i != (edges.end() - 1); i++)
285                 if ((*i).second == level) {
286                         *line++ = QLineF(
287                                 ((*i).first / samples_per_pixel -
288                                         pixels_offset) + x_offset, y_offset,
289                                 ((*(i+1)).first / samples_per_pixel -
290                                         pixels_offset) + x_offset, y_offset);
291                 }
292
293         p.drawLines(lines, line - lines);
294 }
295
296 void LogicSignal::init_trigger_actions(QWidget *parent)
297 {
298         trigger_none_ = new QAction(*get_icon(":/icons/trigger-none.svg"),
299                 tr("No trigger"), parent);
300         trigger_none_->setCheckable(true);
301         connect(trigger_none_, SIGNAL(triggered()), this, SLOT(on_trigger()));
302
303         trigger_rising_ = new QAction(*get_icon(":/icons/trigger-rising.svg"),
304                 tr("Trigger on rising edge"), parent);
305         trigger_rising_->setCheckable(true);
306         connect(trigger_rising_, SIGNAL(triggered()), this, SLOT(on_trigger()));
307
308         trigger_high_ = new QAction(*get_icon(":/icons/trigger-high.svg"),
309                 tr("Trigger on high level"), parent);
310         trigger_high_->setCheckable(true);
311         connect(trigger_high_, SIGNAL(triggered()), this, SLOT(on_trigger()));
312
313         trigger_falling_ = new QAction(*get_icon(":/icons/trigger-falling.svg"),
314                 tr("Trigger on falling edge"), parent);
315         trigger_falling_->setCheckable(true);
316         connect(trigger_falling_, SIGNAL(triggered()), this, SLOT(on_trigger()));
317
318         trigger_low_ = new QAction(*get_icon(":/icons/trigger-low.svg"),
319                 tr("Trigger on low level"), parent);
320         trigger_low_->setCheckable(true);
321         connect(trigger_low_, SIGNAL(triggered()), this, SLOT(on_trigger()));
322
323         trigger_change_ = new QAction(*get_icon(":/icons/trigger-change.svg"),
324                 tr("Trigger on rising or falling edge"), parent);
325         trigger_change_->setCheckable(true);
326         connect(trigger_change_, SIGNAL(triggered()), this, SLOT(on_trigger()));
327 }
328
329 const vector<int32_t> LogicSignal::get_trigger_types() const
330 {
331         const auto sr_dev = device_->device();
332         if (sr_dev->config_check(ConfigKey::TRIGGER_MATCH, Capability::LIST)) {
333                 const Glib::VariantContainerBase gvar =
334                         sr_dev->config_list(ConfigKey::TRIGGER_MATCH);
335
336                 vector<int32_t> ttypes;
337
338                 for (unsigned int i = 0; i < gvar.get_n_children(); i++) {
339                         Glib::VariantBase tmp_vb;
340                         gvar.get_child(tmp_vb, i);
341
342                         Glib::Variant<int32_t> tmp_v =
343                                 Glib::VariantBase::cast_dynamic< Glib::Variant<int32_t> >(tmp_vb);
344
345                         ttypes.push_back(tmp_v.get());
346                 }
347
348                 return ttypes;
349         } else {
350                 return vector<int32_t>();
351         }
352 }
353
354 QAction* LogicSignal::action_from_trigger_type(const TriggerMatchType *type)
355 {
356         QAction *action;
357
358         action = trigger_none_;
359         if (type) {
360                 switch (type->id()) {
361                 case SR_TRIGGER_ZERO:
362                         action = trigger_low_;
363                         break;
364                 case SR_TRIGGER_ONE:
365                         action = trigger_high_;
366                         break;
367                 case SR_TRIGGER_RISING:
368                         action = trigger_rising_;
369                         break;
370                 case SR_TRIGGER_FALLING:
371                         action = trigger_falling_;
372                         break;
373                 case SR_TRIGGER_EDGE:
374                         action = trigger_change_;
375                         break;
376                 default:
377                         assert(0);
378                 }
379         }
380
381         return action;
382 }
383
384 const TriggerMatchType *LogicSignal::trigger_type_from_action(QAction *action)
385 {
386         if (action == trigger_low_)
387                 return TriggerMatchType::ZERO;
388         else if (action == trigger_high_)
389                 return TriggerMatchType::ONE;
390         else if (action == trigger_rising_)
391                 return TriggerMatchType::RISING;
392         else if (action == trigger_falling_)
393                 return TriggerMatchType::FALLING;
394         else if (action == trigger_change_)
395                 return TriggerMatchType::EDGE;
396         else
397                 return nullptr;
398 }
399
400 void LogicSignal::populate_popup_form(QWidget *parent, QFormLayout *form)
401 {
402         Signal::populate_popup_form(parent, form);
403
404         const vector<int32_t> trig_types = get_trigger_types();
405
406         if (!trig_types.empty()) {
407                 trigger_bar_ = new QToolBar(parent);
408                 init_trigger_actions(trigger_bar_);
409                 trigger_bar_->addAction(trigger_none_);
410                 trigger_none_->setChecked(!trigger_match_);
411
412                 for (auto type_id : trig_types) {
413                         const TriggerMatchType *const type =
414                                 TriggerMatchType::get(type_id);
415                         QAction *const action = action_from_trigger_type(type);
416                         trigger_bar_->addAction(action);
417                         action->setChecked(trigger_match_ == type);
418                 }
419                 form->addRow(tr("Trigger"), trigger_bar_);
420         }
421 }
422
423 void LogicSignal::modify_trigger()
424 {
425         auto trigger = session_.session()->trigger();
426         auto new_trigger = session_.device_manager().context()->create_trigger("pulseview");
427
428         if (trigger) {
429                 for (auto stage : trigger->stages()) {
430                         const auto &matches = stage->matches();
431                         if (std::none_of(matches.begin(), matches.end(),
432                             [&](shared_ptr<TriggerMatch> match) {
433                                         return match->channel() != channel_; }))
434                                 continue;
435
436                         auto new_stage = new_trigger->add_stage();
437                         for (auto match : stage->matches()) {
438                                 if (match->channel() == channel_)
439                                         continue;
440                                 new_stage->add_match(match->channel(), match->type());
441                         }
442                 }
443         }
444
445         if (trigger_match_) {
446                 // Until we can let the user decide how to group trigger matches
447                 // into stages, put all of the matches into a single stage --
448                 // most devices only support a single trigger stage.
449                 if (new_trigger->stages().empty())
450                         new_trigger->add_stage();
451
452                 new_trigger->stages().back()->add_match(channel_, trigger_match_);
453         }
454
455         session_.session()->set_trigger(
456                 new_trigger->stages().empty() ? nullptr : new_trigger);
457
458         if (owner_)
459                 owner_->row_item_appearance_changed(false, true);
460 }
461
462 const QIcon* LogicSignal::get_icon(const char *path)
463 {
464         if (!icon_cache_.contains(path)) {
465                 const QIcon *icon = new QIcon(path);
466                 icon_cache_.insert(path, icon);
467         }
468
469         return icon_cache_.take(path);
470 }
471
472 const QPixmap* LogicSignal::get_pixmap(const char *path)
473 {
474         if (!pixmap_cache_.contains(path)) {
475                 const QPixmap *pixmap = new QPixmap(path);
476                 pixmap_cache_.insert(path, pixmap);
477         }
478
479         return pixmap_cache_.take(path);
480 }
481
482 void LogicSignal::on_trigger()
483 {
484         QAction *action;
485
486         action_from_trigger_type(trigger_match_)->setChecked(false);
487
488         action = (QAction *)sender();
489         action->setChecked(true);
490         trigger_match_ = trigger_type_from_action(action);
491
492         modify_trigger();
493 }
494
495 } // namespace view
496 } // namespace pv