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