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