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;
48 using std::shared_ptr;
52 namespace tabular_decoder {
54 const char* SaveTypeNames[SaveTypeCount] = {
55 "CSV, commas escaped",
59 const char* ViewModeNames[ViewModeCount] = {
61 "Show all and focus on newest"
62 // "Show visible in main view"
65 QSize QCustomTableView::minimumSizeHint() const
67 QSize size(QTableView::sizeHint());
70 for (int i = 0; i < horizontalHeader()->count(); i++)
71 if (!horizontalHeader()->isSectionHidden(i))
72 width += horizontalHeader()->sectionSize(i);
74 size.setWidth(width + (horizontalHeader()->count() * 1));
79 QSize QCustomTableView::sizeHint() const
81 return minimumSizeHint();
85 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
86 ViewBase(session, is_main_view, parent),
88 // Note: Place defaults in View::reset_view_state(), not here
90 decoder_selector_(new QComboBox()),
91 hide_hidden_cb_(new QCheckBox()),
92 view_mode_selector_(new QComboBox()),
93 save_button_(new QToolButton()),
94 save_action_(new QAction(this)),
95 table_view_(new QCustomTableView()),
96 model_(new AnnotationCollectionModel()),
99 QVBoxLayout *root_layout = new QVBoxLayout(this);
100 root_layout->setContentsMargins(0, 0, 0, 0);
101 root_layout->addWidget(table_view_);
104 QToolBar* toolbar = new QToolBar();
105 toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
106 parent->addToolBar(toolbar);
109 toolbar->addWidget(new QLabel(tr("Decoder:")));
110 toolbar->addWidget(decoder_selector_);
111 toolbar->addSeparator();
112 toolbar->addWidget(save_button_);
113 toolbar->addSeparator();
114 toolbar->addWidget(view_mode_selector_);
115 toolbar->addSeparator();
116 toolbar->addWidget(hide_hidden_cb_);
118 connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
119 this, SLOT(on_selected_decoder_changed(int)));
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)));
126 decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
128 for (int i = 0; i < ViewModeCount; i++)
129 view_mode_selector_->addItem(ViewModeNames[i], QVariant::fromValue(i));
131 hide_hidden_cb_->setText(tr("Hide Hidden Rows/Classes"));
132 hide_hidden_cb_->setChecked(true);
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()));
142 QMenu *save_menu = new QMenu();
143 connect(save_menu, SIGNAL(triggered(QAction*)),
144 this, SLOT(on_actionSave_triggered(QAction*)));
146 for (int i = 0; i < SaveTypeCount; i++) {
147 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
148 action->setData(qVariantFromValue(i));
151 save_button_->setMenu(save_menu);
152 save_button_->setDefaultAction(save_action_);
153 save_button_->setPopupMode(QToolButton::MenuButtonPopup);
155 // Set up the table view
156 table_view_->setModel(model_);
157 table_view_->setSelectionBehavior(QAbstractItemView::SelectRows);
158 table_view_->setSelectionMode(QAbstractItemView::ContiguousSelection);
159 table_view_->setSortingEnabled(true);
160 table_view_->sortByColumn(0, Qt::AscendingOrder);
162 const int font_height = QFontMetrics(QApplication::font()).height();
163 table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
164 table_view_->verticalHeader()->setVisible(false);
166 table_view_->horizontalHeader()->setStretchLastSection(true);
167 table_view_->horizontalHeader()->setCascadingSectionResizes(true);
168 table_view_->horizontalHeader()->setSectionsMovable(true);
169 table_view_->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
171 table_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
172 parent->setSizePolicy(table_view_->sizePolicy());
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&)));
184 ViewType View::get_type() const
186 return ViewTypeTabularDecoder;
189 void View::reset_view_state()
191 ViewBase::reset_view_state();
193 decoder_selector_->clear();
196 void View::clear_decode_signals()
198 ViewBase::clear_decode_signals();
204 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
206 ViewBase::add_decode_signal(signal);
208 connect(signal.get(), SIGNAL(name_changed(const QString&)),
209 this, SLOT(on_signal_name_changed(const QString&)));
211 // Note: At time of initial creation, decode signals have no decoders so we
212 // need to watch for decoder stacking events
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*)));
219 // Add the top-level decoder provided by an already-existing signal
220 auto stack = signal->decoder_stack();
221 if (!stack.empty()) {
222 shared_ptr<Decoder>& dec = stack.at(0);
223 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)dec.get()));
227 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
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()));
234 decoder_selector_->removeItem(index);
237 ViewBase::remove_decode_signal(signal);
239 if (signal.get() == signal_) {
246 void View::save_settings(QSettings &settings) const
248 ViewBase::save_settings(settings);
250 settings.setValue("view_mode", view_mode_selector_->currentIndex());
251 settings.setValue("hide_hidden", hide_hidden_cb_->isChecked());
254 void View::restore_settings(QSettings &settings)
256 ViewBase::restore_settings(settings);
258 if (settings.contains("view_mode"))
259 view_mode_selector_->setCurrentIndex(settings.value("view_mode").toInt());
261 if (settings.contains("hide_hidden"))
262 hide_hidden_cb_->setChecked(settings.value("hide_hidden").toBool());
265 void View::reset_data()
271 void View::update_data()
273 model_->set_signal_and_segment(signal_, current_segment_);
276 void View::save_data_as_csv(unsigned int save_type) const
278 // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
286 const bool save_all = !table_view_->selectionModel()->hasSelection();
288 GlobalSettings settings;
289 const QString dir = settings.value("MainWindow/SaveDirectory").toString();
291 const QString file_name = QFileDialog::getSaveFileName(
292 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
294 if (file_name.isEmpty())
297 QFile file(file_name);
298 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
299 QTextStream out_stream(&file);
302 table_view_->selectAll();
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);
308 if (table_view_->horizontalHeader()->isSectionHidden(column))
311 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
313 if (save_type == SaveTypeCSVEscaped)
316 out_stream << '"' << title << '"';
318 if (i < (table_view_->horizontalHeader()->count() - 1))
321 out_stream << '\r' << '\n';
324 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
326 for (int i = 0; i < selected_rows.size(); i++) {
327 const int row = selected_rows.at(i).row();
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);
333 if (table_view_->horizontalHeader()->isSectionHidden(column))
336 const QModelIndex idx = model_->index(row, column);
337 QString s = model_->data(idx, Qt::DisplayRole).toString();
339 if (save_type == SaveTypeCSVEscaped)
340 out_stream << s.replace(",", "\\,");
342 out_stream << '"' << s.replace("\"", "\"\"") << '"';
344 if (c < (table_view_->horizontalHeader()->count() - 1))
348 out_stream << '\r' << '\n';
351 if (out_stream.status() == QTextStream::Ok) {
353 table_view_->clearSelection();
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);
366 void View::on_selected_decoder_changed(int index)
369 disconnect(signal_, SIGNAL(color_changed(QColor)));
370 disconnect(signal_, SIGNAL(new_annotations()));
371 disconnect(signal_, SIGNAL(decode_reset()));
376 decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
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())
385 connect(signal_, SIGNAL(color_changed(QColor)), this, SLOT(on_signal_color_changed(QColor)));
386 connect(signal_, SIGNAL(new_annotations()), this, SLOT(on_new_annotations()));
387 connect(signal_, SIGNAL(decode_reset()), this, SLOT(on_decoder_reset()));
393 void View::on_hide_hidden_changed(bool checked)
395 model_->set_hide_hidden(checked);
397 // Force repaint, otherwise the new selection isn't shown for some reason
398 table_view_->viewport()->update();
401 void View::on_view_mode_changed(int index)
406 void View::on_signal_name_changed(const QString &name)
410 SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
413 DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
416 // Update the top-level decoder provided by this signal
417 auto stack = signal->decoder_stack();
418 if (!stack.empty()) {
419 shared_ptr<Decoder>& dec = stack.at(0);
420 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
423 decoder_selector_->setItemText(index, signal->name());
427 void View::on_signal_color_changed(const QColor &color)
431 table_view_->update();
434 void View::on_new_annotations()
436 if (view_mode_selector_->currentIndex() == ViewModeLatest) {
438 table_view_->scrollTo(model_->index(model_->rowCount() - 1, 0),
439 QAbstractItemView::PositionAtBottom);
441 if (!delayed_view_updater_.isActive())
442 delayed_view_updater_.start();
446 void View::on_decoder_reset()
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_);
453 void View::on_decoder_stacked(void* decoder)
455 Decoder* d = static_cast<Decoder*>(decoder);
457 // Find the signal that contains the selected decoder
458 DecodeSignal* signal = nullptr;
460 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
461 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
467 const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
468 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
471 // Add the decoder to the list
472 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
476 void View::on_decoder_removed(void* decoder)
478 Decoder* d = static_cast<Decoder*>(decoder);
480 // Remove the decoder from the list
481 int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
484 decoder_selector_->removeItem(index);
487 void View::on_actionSave_triggered(QAction* action)
489 int save_type = SaveTypeCSVQuoted;
492 save_type = action->data().toInt();
494 save_data_as_csv(save_type);
497 void View::on_table_item_clicked(const QModelIndex& index)
501 // Force repaint, otherwise the new selection isn't shown for some reason
502 table_view_->viewport()->update();
505 void View::on_table_item_double_clicked(const QModelIndex& index)
507 const Annotation* ann = static_cast<const Annotation*>(index.internalPointer());
509 shared_ptr<views::ViewBase> main_view = session_.main_view();
511 main_view->focus_on_range(ann->start_sample(), ann->end_sample());
514 void View::on_table_header_requested(const QPoint& pos)
516 QMenu* menu = new QMenu(this);
518 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
519 int column = table_view_->horizontalHeader()->logicalIndex(i);
521 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
522 QAction* action = new QAction(title, this);
524 action->setCheckable(true);
525 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
526 action->setData(column);
528 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
530 menu->addAction(action);
533 menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
536 void View::on_table_header_toggled(bool checked)
538 QAction* action = qobject_cast<QAction*>(QObject::sender());
541 const int column = action->data().toInt();
543 table_view_->horizontalHeader()->setSectionHidden(column, !checked);
546 void View::perform_delayed_view_update()
552 } // namespace tabular_decoder