2 * This file is part of the PulseView project.
4 * Copyright (C) 2020 Soeren Apel <soeren@apelpie.net>
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.
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.
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/>.
22 #include <QApplication>
24 #include <QFileDialog>
25 #include <QFontMetrics>
26 #include <QHeaderView>
29 #include <QMessageBox>
31 #include <QVBoxLayout>
33 #include <libsigrokdecode/libsigrokdecode.h>
37 #include "pv/globalsettings.hpp"
38 #include "pv/session.hpp"
39 #include "pv/util.hpp"
40 #include "pv/data/decode/decoder.hpp"
42 using pv::data::DecodeSignal;
43 using pv::data::SignalBase;
44 using pv::data::decode::Decoder;
45 using pv::util::Timestamp;
47 using std::make_shared;
49 using std::shared_ptr;
53 namespace tabular_decoder {
55 const char* SaveTypeNames[SaveTypeCount] = {
56 "CSV, commas escaped",
60 const char* ViewModeNames[ViewModeCount] = {
62 "Show all and focus on newest",
63 "Show visible in main view"
66 QSize QCustomTableView::minimumSizeHint() const
68 QSize size(QTableView::sizeHint());
71 for (int i = 0; i < horizontalHeader()->count(); i++)
72 if (!horizontalHeader()->isSectionHidden(i))
73 width += horizontalHeader()->sectionSize(i);
75 size.setWidth(width + (horizontalHeader()->count() * 1));
80 QSize QCustomTableView::sizeHint() const
82 return minimumSizeHint();
86 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
87 ViewBase(session, is_main_view, parent),
89 // Note: Place defaults in View::reset_view_state(), not here
91 decoder_selector_(new QComboBox()),
92 hide_hidden_cb_(new QCheckBox()),
93 view_mode_selector_(new QComboBox()),
94 save_button_(new QToolButton()),
95 save_action_(new QAction(this)),
96 table_view_(new QCustomTableView()),
97 model_(new AnnotationCollectionModel()),
100 QVBoxLayout *root_layout = new QVBoxLayout(this);
101 root_layout->setContentsMargins(0, 0, 0, 0);
102 root_layout->addWidget(table_view_);
105 QToolBar* toolbar = new QToolBar();
106 toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
107 parent->addToolBar(toolbar);
110 toolbar->addWidget(new QLabel(tr("Decoder:")));
111 toolbar->addWidget(decoder_selector_);
112 toolbar->addSeparator();
113 toolbar->addWidget(save_button_);
114 toolbar->addSeparator();
115 toolbar->addWidget(view_mode_selector_);
116 toolbar->addSeparator();
117 toolbar->addWidget(hide_hidden_cb_);
119 connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
120 this, SLOT(on_selected_decoder_changed(int)));
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)));
127 decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
129 for (int i = 0; i < ViewModeCount; i++)
130 view_mode_selector_->addItem(ViewModeNames[i], QVariant::fromValue(i));
132 hide_hidden_cb_->setText(tr("Hide Hidden Rows/Classes"));
133 hide_hidden_cb_->setChecked(true);
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()));
143 QMenu *save_menu = new QMenu();
144 connect(save_menu, SIGNAL(triggered(QAction*)),
145 this, SLOT(on_actionSave_triggered(QAction*)));
147 for (int i = 0; i < SaveTypeCount; i++) {
148 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
149 action->setData(qVariantFromValue(i));
152 save_button_->setMenu(save_menu);
153 save_button_->setDefaultAction(save_action_);
154 save_button_->setPopupMode(QToolButton::MenuButtonPopup);
156 // Set up the table view
157 table_view_->setModel(model_);
158 table_view_->setSelectionBehavior(QAbstractItemView::SelectRows);
159 table_view_->setSelectionMode(QAbstractItemView::ContiguousSelection);
160 table_view_->setSortingEnabled(true);
161 table_view_->sortByColumn(0, Qt::AscendingOrder);
163 const int font_height = QFontMetrics(QApplication::font()).height();
164 table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
165 table_view_->verticalHeader()->setVisible(false);
167 table_view_->horizontalHeader()->setStretchLastSection(true);
168 table_view_->horizontalHeader()->setCascadingSectionResizes(true);
169 table_view_->horizontalHeader()->setSectionsMovable(true);
170 table_view_->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
172 table_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
173 parent->setSizePolicy(table_view_->sizePolicy());
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&)));
182 // Set up metadata event handler
183 session_.metadata_obj_manager()->add_observer(this);
190 session_.metadata_obj_manager()->remove_observer(this);
193 ViewType View::get_type() const
195 return ViewTypeTabularDecoder;
198 void View::reset_view_state()
200 ViewBase::reset_view_state();
202 decoder_selector_->clear();
205 void View::clear_decode_signals()
207 ViewBase::clear_decode_signals();
213 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
215 ViewBase::add_decode_signal(signal);
217 connect(signal.get(), SIGNAL(name_changed(const QString&)),
218 this, SLOT(on_signal_name_changed(const QString&)));
220 // Note: At time of initial creation, decode signals have no decoders so we
221 // need to watch for decoder stacking events
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*)));
228 // Add the top-level decoder provided by an already-existing signal
229 auto stack = signal->decoder_stack();
230 if (!stack.empty()) {
231 shared_ptr<Decoder>& dec = stack.at(0);
232 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)dec.get()));
236 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
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()));
243 decoder_selector_->removeItem(index);
246 ViewBase::remove_decode_signal(signal);
248 if (signal.get() == signal_) {
255 void View::save_settings(QSettings &settings) const
257 ViewBase::save_settings(settings);
259 settings.setValue("view_mode", view_mode_selector_->currentIndex());
260 settings.setValue("hide_hidden", hide_hidden_cb_->isChecked());
263 void View::restore_settings(QSettings &settings)
265 ViewBase::restore_settings(settings);
267 if (settings.contains("view_mode"))
268 view_mode_selector_->setCurrentIndex(settings.value("view_mode").toInt());
270 if (settings.contains("hide_hidden"))
271 hide_hidden_cb_->setChecked(settings.value("hide_hidden").toBool());
274 void View::reset_data()
280 void View::update_data()
282 model_->set_signal_and_segment(signal_, current_segment_);
285 void View::save_data_as_csv(unsigned int save_type) const
287 // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
295 const bool save_all = !table_view_->selectionModel()->hasSelection();
297 GlobalSettings settings;
298 const QString dir = settings.value("MainWindow/SaveDirectory").toString();
300 const QString file_name = QFileDialog::getSaveFileName(
301 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
303 if (file_name.isEmpty())
306 QFile file(file_name);
307 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
308 QTextStream out_stream(&file);
311 table_view_->selectAll();
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);
317 if (table_view_->horizontalHeader()->isSectionHidden(column))
320 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
322 if (save_type == SaveTypeCSVEscaped)
325 out_stream << '"' << title << '"';
327 if (i < (table_view_->horizontalHeader()->count() - 1))
330 out_stream << '\r' << '\n';
333 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
335 for (int i = 0; i < selected_rows.size(); i++) {
336 const int row = selected_rows.at(i).row();
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);
342 if (table_view_->horizontalHeader()->isSectionHidden(column))
345 const QModelIndex idx = model_->index(row, column);
346 QString s = model_->data(idx, Qt::DisplayRole).toString();
348 if (save_type == SaveTypeCSVEscaped)
349 out_stream << s.replace(",", "\\,");
351 out_stream << '"' << s.replace("\"", "\"\"") << '"';
353 if (c < (table_view_->horizontalHeader()->count() - 1))
357 out_stream << '\r' << '\n';
360 if (out_stream.status() == QTextStream::Ok) {
362 table_view_->clearSelection();
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);
375 void View::on_selected_decoder_changed(int index)
378 disconnect(signal_, SIGNAL(color_changed(QColor)));
379 disconnect(signal_, SIGNAL(new_annotations()));
380 disconnect(signal_, SIGNAL(decode_reset()));
385 decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
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())
394 connect(signal_, SIGNAL(color_changed(QColor)), this, SLOT(on_signal_color_changed(QColor)));
395 connect(signal_, SIGNAL(new_annotations()), this, SLOT(on_new_annotations()));
396 connect(signal_, SIGNAL(decode_reset()), this, SLOT(on_decoder_reset()));
402 void View::on_hide_hidden_changed(bool checked)
404 model_->set_hide_hidden(checked);
406 // Force repaint, otherwise the new selection isn't shown for some reason
407 table_view_->viewport()->update();
410 void View::on_view_mode_changed(int index)
412 if (index == ViewModeVisible) {
413 MetadataObject *md_obj =
414 session_.metadata_obj_manager()->find_object_by_type(MetadataObjMainViewRange);
417 int64_t start_sample = md_obj->value(MetadataValueStartSample).toLongLong();
418 int64_t end_sample = md_obj->value(MetadataValueEndSample).toLongLong();
420 model_->set_sample_range(max((int64_t)0, start_sample),
421 max((int64_t)0, end_sample));
423 // Reset the model's data range
424 model_->set_sample_range(0, 0);
427 if (index == ViewModeLatest)
428 table_view_->scrollTo(model_->index(model_->rowCount() - 1, 0),
429 QAbstractItemView::PositionAtBottom);
432 void View::on_signal_name_changed(const QString &name)
436 SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
439 DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
442 // Update the top-level decoder provided by this signal
443 auto stack = signal->decoder_stack();
444 if (!stack.empty()) {
445 shared_ptr<Decoder>& dec = stack.at(0);
446 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
449 decoder_selector_->setItemText(index, signal->name());
453 void View::on_signal_color_changed(const QColor &color)
457 table_view_->update();
460 void View::on_new_annotations()
462 if (view_mode_selector_->currentIndex() == ViewModeLatest) {
464 table_view_->scrollTo(model_->index(model_->rowCount() - 1, 0),
465 QAbstractItemView::PositionAtBottom);
467 if (!delayed_view_updater_.isActive())
468 delayed_view_updater_.start();
472 void View::on_decoder_reset()
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_);
479 void View::on_decoder_stacked(void* decoder)
481 Decoder* d = static_cast<Decoder*>(decoder);
483 // Find the signal that contains the selected decoder
484 DecodeSignal* signal = nullptr;
486 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
487 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
493 const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
494 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
497 // Add the decoder to the list
498 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
502 void View::on_decoder_removed(void* decoder)
504 Decoder* d = static_cast<Decoder*>(decoder);
506 // Remove the decoder from the list
507 int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
510 decoder_selector_->removeItem(index);
513 void View::on_actionSave_triggered(QAction* action)
515 int save_type = SaveTypeCSVQuoted;
518 save_type = action->data().toInt();
520 save_data_as_csv(save_type);
523 void View::on_table_item_clicked(const QModelIndex& index)
527 // Force repaint, otherwise the new selection isn't shown for some reason
528 table_view_->viewport()->update();
531 void View::on_table_item_double_clicked(const QModelIndex& index)
533 const Annotation* ann = static_cast<const Annotation*>(index.internalPointer());
535 shared_ptr<views::ViewBase> main_view = session_.main_view();
537 main_view->focus_on_range(ann->start_sample(), ann->end_sample());
540 void View::on_table_header_requested(const QPoint& pos)
542 QMenu* menu = new QMenu(this);
544 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
545 int column = table_view_->horizontalHeader()->logicalIndex(i);
547 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
548 QAction* action = new QAction(title, this);
550 action->setCheckable(true);
551 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
552 action->setData(column);
554 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
556 menu->addAction(action);
559 menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
562 void View::on_table_header_toggled(bool checked)
564 QAction* action = qobject_cast<QAction*>(QObject::sender());
567 const int column = action->data().toInt();
569 table_view_->horizontalHeader()->setSectionHidden(column, !checked);
572 void View::on_metadata_object_changed(MetadataObject* obj,
573 MetadataValueType value_type)
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
579 if ((view_mode_selector_->currentIndex() == ViewModeVisible) &&
580 (obj->type() == MetadataObjMainViewRange) &&
581 (value_type == MetadataValueEndSample)) {
583 int64_t start_sample = obj->value(MetadataValueStartSample).toLongLong();
584 int64_t end_sample = obj->value(MetadataValueEndSample).toLongLong();
586 model_->set_sample_range(max((int64_t)0, start_sample),
587 max((int64_t)0, end_sample));
591 void View::perform_delayed_view_update()
597 } // namespace tabular_decoder