]> sigrok.org Git - pulseview.git/blame - pv/views/tabular_decoder/view.cpp
TabularDecView: Implement saving as CSV
[pulseview.git] / pv / views / tabular_decoder / view.cpp
CommitLineData
24d69d27
SA
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2020 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
f54e68b0 22#include <QApplication>
24d69d27
SA
23#include <QDebug>
24#include <QFileDialog>
f54e68b0
SA
25#include <QFontMetrics>
26#include <QHeaderView>
24d69d27
SA
27#include <QLabel>
28#include <QMenu>
29#include <QMessageBox>
30#include <QToolBar>
31#include <QVBoxLayout>
32
33#include <libsigrokdecode/libsigrokdecode.h>
34
35#include "view.hpp"
36
37#include "pv/globalsettings.hpp"
9a35b05d 38#include "pv/session.hpp"
24d69d27
SA
39#include "pv/util.hpp"
40#include "pv/data/decode/decoder.hpp"
41
42using pv::data::DecodeSignal;
43using pv::data::SignalBase;
44using pv::data::decode::Decoder;
45using pv::util::Timestamp;
46
f54e68b0 47using std::make_shared;
24d69d27
SA
48using std::shared_ptr;
49
50namespace pv {
51namespace views {
52namespace tabular_decoder {
53
be0f5903
SA
54const char* SaveTypeNames[SaveTypeCount] = {
55 "CSV, commas escaped",
56 "CSV, fields quoted"
57};
58
f54e68b0
SA
59QSize QCustomTableView::minimumSizeHint() const
60{
61 QSize size(QTableView::sizeHint());
62
63 int width = 0;
64 for (int i = 0; i < horizontalHeader()->count(); i++)
65 if (!horizontalHeader()->isSectionHidden(i))
88a25978 66 width += horizontalHeader()->sectionSize(i);
f54e68b0
SA
67
68 size.setWidth(width + (horizontalHeader()->count() * 1));
69
70 return size;
71}
72
73QSize QCustomTableView::sizeHint() const
74{
75 return minimumSizeHint();
76}
77
24d69d27
SA
78
79View::View(Session &session, bool is_main_view, QMainWindow *parent) :
80 ViewBase(session, is_main_view, parent),
81
82 // Note: Place defaults in View::reset_view_state(), not here
83 parent_(parent),
84 decoder_selector_(new QComboBox()),
85 save_button_(new QToolButton()),
86 save_action_(new QAction(this)),
f54e68b0 87 table_view_(new QCustomTableView()),
24d69d27 88 model_(new AnnotationCollectionModel()),
f54e68b0
SA
89 signal_(nullptr),
90 updating_data_(false)
24d69d27
SA
91{
92 QVBoxLayout *root_layout = new QVBoxLayout(this);
93 root_layout->setContentsMargins(0, 0, 0, 0);
94 root_layout->addWidget(table_view_);
95
96 // Create toolbar
97 QToolBar* toolbar = new QToolBar();
98 toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
99 parent->addToolBar(toolbar);
100
101 // Populate toolbar
102 toolbar->addWidget(new QLabel(tr("Decoder:")));
103 toolbar->addWidget(decoder_selector_);
104 toolbar->addSeparator();
105 toolbar->addWidget(save_button_);
106
107 connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
108 this, SLOT(on_selected_decoder_changed(int)));
109
110 // Configure widgets
111 decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
112
113 // Configure actions
114 save_action_->setText(tr("&Save..."));
115 save_action_->setIcon(QIcon::fromTheme("document-save-as",
116 QIcon(":/icons/document-save-as.png")));
117 save_action_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
118 connect(save_action_, SIGNAL(triggered(bool)),
119 this, SLOT(on_actionSave_triggered()));
120
121 QMenu *save_menu = new QMenu();
122 connect(save_menu, SIGNAL(triggered(QAction*)),
123 this, SLOT(on_actionSave_triggered(QAction*)));
124
be0f5903
SA
125 for (int i = 0; i < SaveTypeCount; i++) {
126 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
127 action->setData(qVariantFromValue(i));
128 }
129
24d69d27
SA
130 save_button_->setMenu(save_menu);
131 save_button_->setDefaultAction(save_action_);
132 save_button_->setPopupMode(QToolButton::MenuButtonPopup);
133
134 // Set up the table view
135 table_view_->setModel(model_);
9a35b05d 136 table_view_->setSelectionBehavior(QAbstractItemView::SelectRows);
be0f5903 137 table_view_->setSelectionMode(QAbstractItemView::ContiguousSelection);
24d69d27
SA
138 table_view_->setSortingEnabled(true);
139 table_view_->sortByColumn(0, Qt::AscendingOrder);
140
f54e68b0
SA
141 const int font_height = QFontMetrics(QApplication::font()).height();
142 table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
143
88a25978
SA
144 table_view_->horizontalHeader()->setStretchLastSection(true);
145 table_view_->horizontalHeader()->setCascadingSectionResizes(true);
146 table_view_->horizontalHeader()->setSectionsMovable(true);
9a35b05d 147 table_view_->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
f54e68b0
SA
148
149 table_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
150 parent->setSizePolicy(table_view_->sizePolicy());
151
9a35b05d
SA
152 connect(table_view_, SIGNAL(clicked(const QModelIndex&)),
153 this, SLOT(on_table_item_clicked(const QModelIndex&)));
154 connect(table_view_, SIGNAL(doubleClicked(const QModelIndex&)),
155 this, SLOT(on_table_item_double_clicked(const QModelIndex&)));
156 connect(table_view_->horizontalHeader(), SIGNAL(customContextMenuRequested(const QPoint&)),
157 this, SLOT(on_table_header_requested(const QPoint&)));
158
24d69d27
SA
159 reset_view_state();
160}
161
162ViewType View::get_type() const
163{
164 return ViewTypeTabularDecoder;
165}
166
167void View::reset_view_state()
168{
169 ViewBase::reset_view_state();
170
171 decoder_selector_->clear();
172}
173
174void View::clear_decode_signals()
175{
176 ViewBase::clear_decode_signals();
177
178 reset_data();
179 reset_view_state();
180}
181
182void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
183{
184 ViewBase::add_decode_signal(signal);
185
186 connect(signal.get(), SIGNAL(name_changed(const QString&)),
187 this, SLOT(on_signal_name_changed(const QString&)));
88a25978
SA
188
189 // Note: At time of initial creation, decode signals have no decoders so we
190 // need to watch for decoder stacking events
191
24d69d27
SA
192 connect(signal.get(), SIGNAL(decoder_stacked(void*)),
193 this, SLOT(on_decoder_stacked(void*)));
194 connect(signal.get(), SIGNAL(decoder_removed(void*)),
195 this, SLOT(on_decoder_removed(void*)));
196
88a25978 197 // Add the top-level decoder provided by an already-existing signal
24d69d27 198 auto stack = signal->decoder_stack();
f54e68b0
SA
199 if (!stack.empty()) {
200 shared_ptr<Decoder>& dec = stack.at(0);
201 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)dec.get()));
202 }
24d69d27
SA
203}
204
205void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
206{
207 // Remove all decoders provided by this signal
208 for (const shared_ptr<Decoder>& dec : signal->decoder_stack()) {
209 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
210
211 if (index != -1)
212 decoder_selector_->removeItem(index);
213 }
214
215 ViewBase::remove_decode_signal(signal);
216
217 if (signal.get() == signal_) {
218 reset_data();
219 update_data();
220 reset_view_state();
221 }
222}
223
224void View::save_settings(QSettings &settings) const
225{
226 ViewBase::save_settings(settings);
227}
228
229void View::restore_settings(QSettings &settings)
230{
231 // Note: It is assumed that this function is only called once,
232 // immediately after restoring a previous session.
233 ViewBase::restore_settings(settings);
234}
235
236void View::reset_data()
237{
238 signal_ = nullptr;
239 decoder_ = nullptr;
240}
241
242void View::update_data()
243{
f54e68b0
SA
244 if (updating_data_) {
245 if (!delayed_view_updater_.isActive())
246 delayed_view_updater_.start();
247 return;
248 }
249
250 updating_data_ = true;
251
252 table_view_->setRootIndex(model_->index(1, 0, QModelIndex()));
253 model_->set_signal_and_segment(signal_, current_segment_);
254
255 updating_data_ = false;
24d69d27
SA
256}
257
be0f5903 258void View::save_data_as_csv(unsigned int save_type) const
24d69d27 259{
be0f5903
SA
260 // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
261
24d69d27
SA
262 assert(decoder_);
263 assert(signal_);
264
265 if (!signal_)
266 return;
267
be0f5903
SA
268 const bool save_all = !table_view_->selectionModel()->hasSelection();
269
270 GlobalSettings settings;
24d69d27
SA
271 const QString dir = settings.value("MainWindow/SaveDirectory").toString();
272
273 const QString file_name = QFileDialog::getSaveFileName(
be0f5903 274 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
24d69d27
SA
275
276 if (file_name.isEmpty())
277 return;
278
279 QFile file(file_name);
280 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
be0f5903
SA
281 QTextStream out_stream(&file);
282
283 if (save_all)
284 table_view_->selectAll();
285
286 // Write out header columns in visual order, not logical order
287 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
288 int column = table_view_->horizontalHeader()->logicalIndex(i);
289
290 if (table_view_->horizontalHeader()->isSectionHidden(column))
291 continue;
292
293 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
294
295 if (save_type == SaveTypeCSVEscaped)
296 out_stream << title;
297 else
298 out_stream << '"' << title << '"';
299
300 if (i < (table_view_->horizontalHeader()->count() - 1))
301 out_stream << ",";
302 }
303 out_stream << '\r' << '\n';
24d69d27 304
24d69d27 305
be0f5903 306 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
24d69d27 307
be0f5903
SA
308 for (int i = 0; i < selected_rows.size(); i++) {
309 const int row = selected_rows.at(i).row();
310
311 // Write out columns in visual order, not logical order
312 for (int c = 0; c < table_view_->horizontalHeader()->count(); c++) {
313 const int column = table_view_->horizontalHeader()->logicalIndex(c);
314
315 if (table_view_->horizontalHeader()->isSectionHidden(column))
316 continue;
317
318 const QModelIndex idx = model_->index(row, column, QModelIndex());
319 QString s = model_->data(idx, Qt::DisplayRole).toString();
320
321 if (save_type == SaveTypeCSVEscaped)
322 out_stream << s.replace(",", "\\,");
323 else
324 out_stream << '"' << s.replace("\"", "\"\"") << '"';
325
326 if (c < (table_view_->horizontalHeader()->count() - 1))
327 out_stream << ",";
328 }
329
330 out_stream << '\r' << '\n';
331 }
332
333 if (out_stream.status() == QTextStream::Ok) {
334 if (save_all)
335 table_view_->clearSelection();
24d69d27 336
24d69d27
SA
337 return;
338 }
be0f5903
SA
339 }
340
341 QMessageBox msg(parent_);
342 msg.setText(tr("Error") + "\n\n" + tr("File %1 could not be written to.").arg(file_name));
343 msg.setStandardButtons(QMessageBox::Ok);
344 msg.setIcon(QMessageBox::Warning);
345 msg.exec();
24d69d27
SA
346}
347
348void View::on_selected_decoder_changed(int index)
349{
02c87df7 350 if (signal_) {
85125b0f 351 disconnect(signal_, SIGNAL(color_changed(QColor)));
24d69d27 352 disconnect(signal_, SIGNAL(new_annotations()));
02c87df7
SA
353 disconnect(signal_, SIGNAL(decode_reset()));
354 }
24d69d27
SA
355
356 reset_data();
357
358 decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
359
360 // Find the signal that contains the selected decoder
361 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
362 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
363 if (decoder_ == dec.get())
364 signal_ = ds.get();
365
02c87df7 366 if (signal_) {
88a25978 367 connect(signal_, SIGNAL(color_changed(QColor)), this, SLOT(on_signal_color_changed(QColor)));
24d69d27 368 connect(signal_, SIGNAL(new_annotations()), this, SLOT(on_new_annotations()));
02c87df7
SA
369 connect(signal_, SIGNAL(decode_reset()), this, SLOT(on_decoder_reset()));
370 }
24d69d27
SA
371
372 update_data();
373}
374
375void View::on_signal_name_changed(const QString &name)
376{
377 (void)name;
378
379 SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
380 assert(sb);
381
382 DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
383 assert(signal);
384
f54e68b0 385 // Update the top-level decoder provided by this signal
24d69d27 386 auto stack = signal->decoder_stack();
f54e68b0
SA
387 if (!stack.empty()) {
388 shared_ptr<Decoder>& dec = stack.at(0);
389 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
24d69d27 390
f54e68b0
SA
391 if (index != -1)
392 decoder_selector_->setItemText(index, signal->name());
393 }
24d69d27
SA
394}
395
88a25978
SA
396void View::on_signal_color_changed(const QColor &color)
397{
398 (void)color;
399
400 table_view_->update();
401}
402
24d69d27
SA
403void View::on_new_annotations()
404{
405 if (!delayed_view_updater_.isActive())
406 delayed_view_updater_.start();
407}
408
02c87df7
SA
409void View::on_decoder_reset()
410{
411 // Invalidate the model's data connection immediately - otherwise we
412 // will use a stale pointer in model_->index() when called from the table view
413 model_->set_signal_and_segment(signal_, current_segment_);
414}
415
24d69d27
SA
416void View::on_decoder_stacked(void* decoder)
417{
24d69d27
SA
418 Decoder* d = static_cast<Decoder*>(decoder);
419
420 // Find the signal that contains the selected decoder
421 DecodeSignal* signal = nullptr;
422
423 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
424 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
425 if (d == dec.get())
426 signal = ds.get();
427
428 assert(signal);
429
88a25978
SA
430 const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
431 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
432
433 if (index == -1) {
434 // Add the decoder to the list
85125b0f 435 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
88a25978 436 }
24d69d27
SA
437}
438
439void View::on_decoder_removed(void* decoder)
440{
441 Decoder* d = static_cast<Decoder*>(decoder);
442
443 // Remove the decoder from the list
444 int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
445
446 if (index != -1)
447 decoder_selector_->removeItem(index);
448}
449
450void View::on_actionSave_triggered(QAction* action)
451{
be0f5903
SA
452 int save_type = SaveTypeCSVQuoted;
453
454 if (action)
455 save_type = action->data().toInt();
24d69d27 456
be0f5903 457 save_data_as_csv(save_type);
24d69d27
SA
458}
459
9a35b05d
SA
460void View::on_table_item_clicked(const QModelIndex& index)
461{
462 (void)index;
463
464 // Force repaint, otherwise the new selection isn't shown for some reason
465 table_view_->viewport()->update();
466}
467
468void View::on_table_item_double_clicked(const QModelIndex& index)
469{
470 const Annotation* ann = static_cast<const Annotation*>(index.internalPointer());
471
472 shared_ptr<views::ViewBase> main_view = session_.main_view();
473
474 main_view->focus_on_range(ann->start_sample(), ann->end_sample());
475}
476
477void View::on_table_header_requested(const QPoint& pos)
478{
479 QMenu* menu = new QMenu(this);
480
481 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
482 int column = table_view_->horizontalHeader()->logicalIndex(i);
483
484 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
485 QAction* action = new QAction(title, this);
486
487 action->setCheckable(true);
488 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
489 action->setData(column);
490
491 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
492
493 menu->addAction(action);
494 }
495
496 menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
497}
498
499void View::on_table_header_toggled(bool checked)
500{
501 QAction* action = qobject_cast<QAction*>(QObject::sender());
502 assert(action);
503
504 const int column = action->data().toInt();
505
506 table_view_->horizontalHeader()->setSectionHidden(column, !checked);
507}
508
24d69d27
SA
509void View::perform_delayed_view_update()
510{
511 update_data();
512}
513
514
515} // namespace tabular_decoder
516} // namespace views
517} // namespace pv