]> sigrok.org Git - pulseview.git/blob - pv/views/decoder_binary/view.cpp
Session: Fix issue #67 by improving error handling
[pulseview.git] / pv / views / decoder_binary / view.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2019 Soeren Apel <soeren@apelpie.net>
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 #include <climits>
21
22 #include <QByteArray>
23 #include <QDebug>
24 #include <QFileDialog>
25 #include <QLabel>
26 #include <QMenu>
27 #include <QMessageBox>
28 #include <QToolBar>
29 #include <QVBoxLayout>
30
31 #include <libsigrokdecode/libsigrokdecode.h>
32
33 #include "view.hpp"
34 #include "QHexView.hpp"
35
36 #include "pv/globalsettings.hpp"
37 #include "pv/session.hpp"
38 #include "pv/util.hpp"
39 #include "pv/data/decode/decoder.hpp"
40
41 using pv::data::DecodeSignal;
42 using pv::data::SignalBase;
43 using pv::data::decode::Decoder;
44 using pv::util::Timestamp;
45
46 using std::shared_ptr;
47
48 namespace pv {
49 namespace views {
50 namespace decoder_binary {
51
52 const char* SaveTypeNames[SaveTypeCount] = {
53         "Binary",
54         "Hex Dump, plain",
55         "Hex Dump, with offset",
56         "Hex Dump, canonical"
57 };
58
59
60 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
61         ViewBase(session, is_main_view, parent),
62
63         // Note: Place defaults in View::reset_view_state(), not here
64         parent_(parent),
65         decoder_selector_(new QComboBox()),
66         format_selector_(new QComboBox()),
67         class_selector_(new QComboBox()),
68         stacked_widget_(new QStackedWidget()),
69         hex_view_(new QHexView()),
70         save_button_(new QToolButton()),
71         save_action_(new QAction(this)),
72         signal_(nullptr)
73 {
74         QVBoxLayout *root_layout = new QVBoxLayout(this);
75         root_layout->setContentsMargins(0, 0, 0, 0);
76
77         // Create toolbar
78         QToolBar* toolbar = new QToolBar();
79         toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
80         parent->addToolBar(toolbar);
81
82         // Populate toolbar
83         toolbar->addWidget(new QLabel(tr("Decoder:")));
84         toolbar->addWidget(decoder_selector_);
85         toolbar->addWidget(class_selector_);
86         toolbar->addSeparator();
87         toolbar->addWidget(new QLabel(tr("Show data as")));
88         toolbar->addWidget(format_selector_);
89         toolbar->addSeparator();
90         toolbar->addWidget(save_button_);
91
92         // Add format types
93         format_selector_->addItem(tr("Hexdump"), QVariant(QString("text/hexdump")));
94
95         // Add widget stack
96         root_layout->addWidget(stacked_widget_);
97         stacked_widget_->addWidget(hex_view_);
98         stacked_widget_->setCurrentIndex(0);
99
100         connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
101                 this, SLOT(on_selected_decoder_changed(int)));
102         connect(class_selector_, SIGNAL(currentIndexChanged(int)),
103                 this, SLOT(on_selected_class_changed(int)));
104
105         // Configure widgets
106         decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
107         class_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
108
109         // Configure actions
110         save_action_->setText(tr("&Save..."));
111         save_action_->setIcon(QIcon::fromTheme("document-save-as",
112                 QIcon(":/icons/document-save-as.png")));
113         save_action_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
114         connect(save_action_, SIGNAL(triggered(bool)),
115                 this, SLOT(on_actionSave_triggered()));
116
117         QMenu *save_menu = new QMenu();
118         connect(save_menu, SIGNAL(triggered(QAction*)),
119                 this, SLOT(on_actionSave_triggered(QAction*)));
120
121         for (int i = 0; i < SaveTypeCount; i++) {
122                 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
123                 action->setData(QVariant::fromValue(i));
124         }
125
126         save_button_->setMenu(save_menu);
127         save_button_->setDefaultAction(save_action_);
128         save_button_->setPopupMode(QToolButton::MenuButtonPopup);
129
130         parent->setSizePolicy(hex_view_->sizePolicy()); // TODO Must be updated when selected widget changes
131
132         // Set up metadata event handler
133         session_.metadata_obj_manager()->add_observer(this);
134
135         reset_view_state();
136 }
137
138 View::~View()
139 {
140         session_.metadata_obj_manager()->remove_observer(this);
141 }
142
143 ViewType View::get_type() const
144 {
145         return ViewTypeDecoderBinary;
146 }
147
148 void View::reset_view_state()
149 {
150         ViewBase::reset_view_state();
151
152         decoder_selector_->clear();
153         class_selector_->clear();
154         format_selector_->setCurrentIndex(0);
155         save_button_->setEnabled(false);
156
157         hex_view_->clear();
158 }
159
160 void View::clear_decode_signals()
161 {
162         ViewBase::clear_decode_signals();
163
164         reset_data();
165         reset_view_state();
166 }
167
168 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
169 {
170         ViewBase::add_decode_signal(signal);
171
172         connect(signal.get(), SIGNAL(name_changed(const QString&)),
173                 this, SLOT(on_signal_name_changed(const QString&)));
174         connect(signal.get(), SIGNAL(decoder_stacked(void*)),
175                 this, SLOT(on_decoder_stacked(void*)));
176         connect(signal.get(), SIGNAL(decoder_removed(void*)),
177                 this, SLOT(on_decoder_removed(void*)));
178
179         // Add all decoders provided by this signal
180         auto stack = signal->decoder_stack();
181         if (stack.size() > 1) {
182                 for (const shared_ptr<Decoder>& dec : stack)
183                         // Only add the decoder if it has binary output
184                         if (dec->get_binary_class_count() > 0) {
185                                 QString title = QString("%1 (%2)").arg(signal->name(), dec->name());
186                                 decoder_selector_->addItem(title, QVariant::fromValue((void*)dec.get()));
187                         }
188         } else
189                 if (!stack.empty()) {
190                         shared_ptr<Decoder>& dec = stack.at(0);
191                         if (dec->get_binary_class_count() > 0)
192                                 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)dec.get()));
193                 }
194 }
195
196 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
197 {
198         // Remove all decoders provided by this signal
199         for (const shared_ptr<Decoder>& dec : signal->decoder_stack()) {
200                 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
201
202                 if (index != -1)
203                         decoder_selector_->removeItem(index);
204         }
205
206         ViewBase::remove_decode_signal(signal);
207
208         if (signal.get() == signal_) {
209                 reset_data();
210                 update_data();
211                 reset_view_state();
212         }
213 }
214
215 void View::save_settings(QSettings &settings) const
216 {
217         ViewBase::save_settings(settings);
218 }
219
220 void View::restore_settings(QSettings &settings)
221 {
222         // Note: It is assumed that this function is only called once,
223         // immediately after restoring a previous session.
224         ViewBase::restore_settings(settings);
225 }
226
227 void View::reset_data()
228 {
229         signal_ = nullptr;
230         decoder_ = nullptr;
231         bin_class_id_ = 0;
232         binary_data_exists_ = false;
233
234         hex_view_->clear();
235 }
236
237 void View::update_data()
238 {
239         if (!signal_)
240                 return;
241
242         const DecodeBinaryClass* bin_class =
243                 signal_->get_binary_data_class(current_segment_, decoder_, bin_class_id_);
244
245         hex_view_->set_data(bin_class);
246
247         if (!binary_data_exists_)
248                 return;
249
250         if (!save_button_->isEnabled())
251                 save_button_->setEnabled(true);
252 }
253
254 void View::save_data() const
255 {
256         assert(decoder_);
257         assert(signal_);
258
259         if (!signal_)
260                 return;
261
262         GlobalSettings settings;
263         const QString dir = settings.value("MainWindow/SaveDirectory").toString();
264
265         const QString file_name = QFileDialog::getSaveFileName(
266                 parent_, tr("Save Binary Data"), dir, tr("Binary Data Files (*.bin);;All Files (*)"));
267
268         if (file_name.isEmpty())
269                 return;
270
271         QFile file(file_name);
272         if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
273                 pair<size_t, size_t> selection = hex_view_->get_selection();
274
275                 vector<uint8_t> data;
276                 data.resize(selection.second - selection.first + 1);
277
278                 signal_->get_merged_binary_data_chunks_by_offset(current_segment_, decoder_,
279                         bin_class_id_, selection.first, selection.second, &data);
280
281                 int64_t bytes_written = file.write((const char*)data.data(), data.size());
282
283                 if ((bytes_written == -1) || ((uint64_t)bytes_written != data.size())) {
284                         QMessageBox msg(parent_);
285                         msg.setText(tr("Error") + "\n\n" + tr("File %1 could not be written to.").arg(file_name));
286                         msg.setStandardButtons(QMessageBox::Ok);
287                         msg.setIcon(QMessageBox::Warning);
288                         msg.exec();
289                         return;
290                 }
291         }
292 }
293
294 void View::save_data_as_hex_dump(bool with_offset, bool with_ascii) const
295 {
296         assert(decoder_);
297         assert(signal_);
298
299         if (!signal_)
300                 return;
301
302         GlobalSettings settings;
303         const QString dir = settings.value("MainWindow/SaveDirectory").toString();
304
305         const QString file_name = QFileDialog::getSaveFileName(
306                 parent_, tr("Save Binary Data"), dir, tr("Hex Dumps (*.txt);;All Files (*)"));
307
308         if (file_name.isEmpty())
309                 return;
310
311         QFile file(file_name);
312         if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text)) {
313                 pair<size_t, size_t> selection = hex_view_->get_selection();
314
315                 vector<uint8_t> data;
316                 data.resize(selection.second - selection.first + 1);
317
318                 signal_->get_merged_binary_data_chunks_by_offset(current_segment_, decoder_,
319                         bin_class_id_, selection.first, selection.second, &data);
320
321                 QTextStream out_stream(&file);
322
323                 uint64_t offset = selection.first;
324                 uint64_t n = hex_view_->get_bytes_per_line();
325                 QString s;
326
327                 while (offset < selection.second) {
328                         size_t end = std::min((uint64_t)(selection.second), offset + n);
329                         offset = hex_view_->create_hex_line(offset, end, &s, with_offset, with_ascii);
330 #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
331                         out_stream << s << Qt::endl;
332 #else
333                         out_stream << s << endl;
334 #endif
335                 }
336
337 #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
338                 out_stream << Qt::endl;
339 #else
340                 out_stream << endl;
341 #endif
342
343                 if (out_stream.status() != QTextStream::Ok) {
344                         QMessageBox msg(parent_);
345                         msg.setText(tr("Error") + "\n\n" + tr("File %1 could not be written to.").arg(file_name));
346                         msg.setStandardButtons(QMessageBox::Ok);
347                         msg.setIcon(QMessageBox::Warning);
348                         msg.exec();
349                         return;
350                 }
351         }
352 }
353
354 void View::on_selected_decoder_changed(int index)
355 {
356         if (signal_)
357                 disconnect(signal_, SIGNAL(new_binary_data(unsigned int, void*, unsigned int)));
358
359         reset_data();
360
361         decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
362
363         // Find the signal that contains the selected decoder
364         for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
365                 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
366                         if (decoder_ == dec.get())
367                                 signal_ = ds.get();
368
369         class_selector_->clear();
370
371         if (signal_) {
372                 // Populate binary class selector
373                 uint32_t bin_classes = decoder_->get_binary_class_count();
374                 for (uint32_t i = 0; i < bin_classes; i++) {
375                         const data::decode::DecodeBinaryClassInfo* class_info = decoder_->get_binary_class(i);
376                         class_selector_->addItem(class_info->description, QVariant::fromValue(i));
377                 }
378
379                 connect(signal_, SIGNAL(new_binary_data(unsigned int, void*, unsigned int)),
380                         this, SLOT(on_new_binary_data(unsigned int, void*, unsigned int)));
381         }
382
383         update_data();
384 }
385
386 void View::on_selected_class_changed(int index)
387 {
388         bin_class_id_ = class_selector_->itemData(index).value<uint32_t>();
389
390         binary_data_exists_ = (signal_) ?
391                 signal_->get_binary_data_chunk_count(current_segment_, decoder_, bin_class_id_) :
392                 false;
393
394         update_data();
395 }
396
397 void View::on_signal_name_changed(const QString &name)
398 {
399         (void)name;
400
401         SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
402         assert(sb);
403
404         DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
405         assert(signal);
406
407         // Update all decoder entries provided by this signal
408         auto stack = signal->decoder_stack();
409         if (stack.size() > 1) {
410                 for (const shared_ptr<Decoder>& dec : stack) {
411                         QString title = QString("%1 (%2)").arg(signal->name(), dec->name());
412                         int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
413
414                         if (index != -1)
415                                 decoder_selector_->setItemText(index, title);
416                 }
417         } else
418                 if (!stack.empty()) {
419                         shared_ptr<Decoder>& dec = stack.at(0);
420                         int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
421
422                         if (index != -1)
423                                 decoder_selector_->setItemText(index, signal->name());
424                 }
425 }
426
427 void View::on_new_binary_data(unsigned int segment_id, void* decoder, unsigned int bin_class_id)
428 {
429         if ((segment_id == current_segment_) && (decoder == decoder_) && (bin_class_id == bin_class_id_))
430                 if (!delayed_view_updater_.isActive())
431                         delayed_view_updater_.start();
432 }
433
434 void View::on_decoder_stacked(void* decoder)
435 {
436         // TODO This doesn't change existing entries for the same signal - but it should as the naming scheme may change
437
438         Decoder* d = static_cast<Decoder*>(decoder);
439
440         // Only add the decoder if it has binary output
441         if (d->get_binary_class_count() == 0)
442                 return;
443
444         // Find the signal that contains the selected decoder
445         DecodeSignal* signal = nullptr;
446
447         for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
448                 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
449                         if (d == dec.get())
450                                 signal = ds.get();
451
452         assert(signal);
453
454         // Add the decoder to the list
455         QString title = QString("%1 (%2)").arg(signal->name(), d->name());
456         decoder_selector_->addItem(title, QVariant::fromValue((void*)d));
457 }
458
459 void View::on_decoder_removed(void* decoder)
460 {
461         Decoder* d = static_cast<Decoder*>(decoder);
462
463         // Remove the decoder from the list
464         int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
465
466         if (index != -1)
467                 decoder_selector_->removeItem(index);
468 }
469
470 void View::on_actionSave_triggered(QAction* action)
471 {
472         int save_type = SaveTypeBinary;
473         if (action)
474                 save_type = action->data().toInt();
475
476         switch (save_type)
477         {
478         case SaveTypeBinary: save_data(); break;
479         case SaveTypeHexDumpPlain: save_data_as_hex_dump(false, false); break;
480         case SaveTypeHexDumpWithOffset: save_data_as_hex_dump(true, false); break;
481         case SaveTypeHexDumpComplete: save_data_as_hex_dump(true, true); break;
482         }
483 }
484
485 void View::on_metadata_object_changed(MetadataObject* obj,
486         MetadataValueType value_type)
487 {
488         // Check if we need to update the model's data range. We only work on the
489         // end sample value because the start sample value is updated first and
490         // we need both
491         if ((obj->type() == MetadataObjMainViewRange) &&
492                 (value_type == MetadataValueEndSample)) {
493
494                 int64_t start_sample = obj->value(MetadataValueStartSample).toLongLong();
495                 int64_t end_sample = obj->value(MetadataValueEndSample).toLongLong();
496
497                 hex_view_->set_visible_sample_range(start_sample, end_sample);
498         }
499
500         if (obj->type() == MetadataObjMousePos)
501                 hex_view_->set_highlighted_data_sample(obj->value(MetadataValueStartSample).toLongLong());
502 }
503
504 void View::perform_delayed_view_update()
505 {
506         if (signal_ && !binary_data_exists_)
507                 if (signal_->get_binary_data_chunk_count(current_segment_, decoder_, bin_class_id_))
508                         binary_data_exists_ = true;
509
510         update_data();
511 }
512
513
514 } // namespace decoder_binary
515 } // namespace views
516 } // namespace pv