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