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 QSize QCustomTableView::minimumSizeHint() const
61 QSize size(QTableView::sizeHint());
64 for (int i = 0; i < horizontalHeader()->count(); i++)
65 if (!horizontalHeader()->isSectionHidden(i))
66 width += horizontalHeader()->sectionSize(i);
68 size.setWidth(width + (horizontalHeader()->count() * 1));
73 QSize QCustomTableView::sizeHint() const
75 return minimumSizeHint();
79 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
80 ViewBase(session, is_main_view, parent),
82 // Note: Place defaults in View::reset_view_state(), not here
84 decoder_selector_(new QComboBox()),
85 save_button_(new QToolButton()),
86 save_action_(new QAction(this)),
87 table_view_(new QCustomTableView()),
88 model_(new AnnotationCollectionModel()),
92 QVBoxLayout *root_layout = new QVBoxLayout(this);
93 root_layout->setContentsMargins(0, 0, 0, 0);
94 root_layout->addWidget(table_view_);
97 QToolBar* toolbar = new QToolBar();
98 toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
99 parent->addToolBar(toolbar);
102 toolbar->addWidget(new QLabel(tr("Decoder:")));
103 toolbar->addWidget(decoder_selector_);
104 toolbar->addSeparator();
105 toolbar->addWidget(save_button_);
107 connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
108 this, SLOT(on_selected_decoder_changed(int)));
111 decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
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()));
121 QMenu *save_menu = new QMenu();
122 connect(save_menu, SIGNAL(triggered(QAction*)),
123 this, SLOT(on_actionSave_triggered(QAction*)));
125 for (int i = 0; i < SaveTypeCount; i++) {
126 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
127 action->setData(qVariantFromValue(i));
130 save_button_->setMenu(save_menu);
131 save_button_->setDefaultAction(save_action_);
132 save_button_->setPopupMode(QToolButton::MenuButtonPopup);
134 // Set up the table view
135 table_view_->setModel(model_);
136 table_view_->setSelectionBehavior(QAbstractItemView::SelectRows);
137 table_view_->setSelectionMode(QAbstractItemView::ContiguousSelection);
138 table_view_->setSortingEnabled(true);
139 table_view_->sortByColumn(0, Qt::AscendingOrder);
141 const int font_height = QFontMetrics(QApplication::font()).height();
142 table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
144 table_view_->horizontalHeader()->setStretchLastSection(true);
145 table_view_->horizontalHeader()->setCascadingSectionResizes(true);
146 table_view_->horizontalHeader()->setSectionsMovable(true);
147 table_view_->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
149 table_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
150 parent->setSizePolicy(table_view_->sizePolicy());
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&)));
162 ViewType View::get_type() const
164 return ViewTypeTabularDecoder;
167 void View::reset_view_state()
169 ViewBase::reset_view_state();
171 decoder_selector_->clear();
174 void View::clear_decode_signals()
176 ViewBase::clear_decode_signals();
182 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
184 ViewBase::add_decode_signal(signal);
186 connect(signal.get(), SIGNAL(name_changed(const QString&)),
187 this, SLOT(on_signal_name_changed(const QString&)));
189 // Note: At time of initial creation, decode signals have no decoders so we
190 // need to watch for decoder stacking events
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*)));
197 // Add the top-level decoder provided by an already-existing signal
198 auto stack = signal->decoder_stack();
199 if (!stack.empty()) {
200 shared_ptr<Decoder>& dec = stack.at(0);
201 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)dec.get()));
205 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
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()));
212 decoder_selector_->removeItem(index);
215 ViewBase::remove_decode_signal(signal);
217 if (signal.get() == signal_) {
224 void View::save_settings(QSettings &settings) const
226 ViewBase::save_settings(settings);
229 void View::restore_settings(QSettings &settings)
231 // Note: It is assumed that this function is only called once,
232 // immediately after restoring a previous session.
233 ViewBase::restore_settings(settings);
236 void View::reset_data()
242 void View::update_data()
244 if (updating_data_) {
245 if (!delayed_view_updater_.isActive())
246 delayed_view_updater_.start();
250 updating_data_ = true;
252 table_view_->setRootIndex(model_->index(1, 0, QModelIndex()));
253 model_->set_signal_and_segment(signal_, current_segment_);
255 updating_data_ = false;
258 void View::save_data_as_csv(unsigned int save_type) const
260 // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
268 const bool save_all = !table_view_->selectionModel()->hasSelection();
270 GlobalSettings settings;
271 const QString dir = settings.value("MainWindow/SaveDirectory").toString();
273 const QString file_name = QFileDialog::getSaveFileName(
274 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
276 if (file_name.isEmpty())
279 QFile file(file_name);
280 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
281 QTextStream out_stream(&file);
284 table_view_->selectAll();
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);
290 if (table_view_->horizontalHeader()->isSectionHidden(column))
293 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
295 if (save_type == SaveTypeCSVEscaped)
298 out_stream << '"' << title << '"';
300 if (i < (table_view_->horizontalHeader()->count() - 1))
303 out_stream << '\r' << '\n';
306 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
308 for (int i = 0; i < selected_rows.size(); i++) {
309 const int row = selected_rows.at(i).row();
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);
315 if (table_view_->horizontalHeader()->isSectionHidden(column))
318 const QModelIndex idx = model_->index(row, column, QModelIndex());
319 QString s = model_->data(idx, Qt::DisplayRole).toString();
321 if (save_type == SaveTypeCSVEscaped)
322 out_stream << s.replace(",", "\\,");
324 out_stream << '"' << s.replace("\"", "\"\"") << '"';
326 if (c < (table_view_->horizontalHeader()->count() - 1))
330 out_stream << '\r' << '\n';
333 if (out_stream.status() == QTextStream::Ok) {
335 table_view_->clearSelection();
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);
348 void View::on_selected_decoder_changed(int index)
351 disconnect(signal_, SIGNAL(color_changed(QColor)));
352 disconnect(signal_, SIGNAL(new_annotations()));
353 disconnect(signal_, SIGNAL(decode_reset()));
358 decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
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())
367 connect(signal_, SIGNAL(color_changed(QColor)), this, SLOT(on_signal_color_changed(QColor)));
368 connect(signal_, SIGNAL(new_annotations()), this, SLOT(on_new_annotations()));
369 connect(signal_, SIGNAL(decode_reset()), this, SLOT(on_decoder_reset()));
375 void View::on_signal_name_changed(const QString &name)
379 SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
382 DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
385 // Update the top-level decoder provided by this signal
386 auto stack = signal->decoder_stack();
387 if (!stack.empty()) {
388 shared_ptr<Decoder>& dec = stack.at(0);
389 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
392 decoder_selector_->setItemText(index, signal->name());
396 void View::on_signal_color_changed(const QColor &color)
400 table_view_->update();
403 void View::on_new_annotations()
405 if (!delayed_view_updater_.isActive())
406 delayed_view_updater_.start();
409 void View::on_decoder_reset()
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_);
416 void View::on_decoder_stacked(void* decoder)
418 Decoder* d = static_cast<Decoder*>(decoder);
420 // Find the signal that contains the selected decoder
421 DecodeSignal* signal = nullptr;
423 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
424 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
430 const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
431 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
434 // Add the decoder to the list
435 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
439 void View::on_decoder_removed(void* decoder)
441 Decoder* d = static_cast<Decoder*>(decoder);
443 // Remove the decoder from the list
444 int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
447 decoder_selector_->removeItem(index);
450 void View::on_actionSave_triggered(QAction* action)
452 int save_type = SaveTypeCSVQuoted;
455 save_type = action->data().toInt();
457 save_data_as_csv(save_type);
460 void View::on_table_item_clicked(const QModelIndex& index)
464 // Force repaint, otherwise the new selection isn't shown for some reason
465 table_view_->viewport()->update();
468 void View::on_table_item_double_clicked(const QModelIndex& index)
470 const Annotation* ann = static_cast<const Annotation*>(index.internalPointer());
472 shared_ptr<views::ViewBase> main_view = session_.main_view();
474 main_view->focus_on_range(ann->start_sample(), ann->end_sample());
477 void View::on_table_header_requested(const QPoint& pos)
479 QMenu* menu = new QMenu(this);
481 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
482 int column = table_view_->horizontalHeader()->logicalIndex(i);
484 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
485 QAction* action = new QAction(title, this);
487 action->setCheckable(true);
488 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
489 action->setData(column);
491 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
493 menu->addAction(action);
496 menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
499 void View::on_table_header_toggled(bool checked)
501 QAction* action = qobject_cast<QAction*>(QObject::sender());
504 const int column = action->data().toInt();
506 table_view_->horizontalHeader()->setSectionHidden(column, !checked);
509 void View::perform_delayed_view_update()
515 } // namespace tabular_decoder