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