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()),
91 QVBoxLayout *root_layout = new QVBoxLayout(this);
92 root_layout->setContentsMargins(0, 0, 0, 0);
93 root_layout->addWidget(table_view_);
96 QToolBar* toolbar = new QToolBar();
97 toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
98 parent->addToolBar(toolbar);
101 toolbar->addWidget(new QLabel(tr("Decoder:")));
102 toolbar->addWidget(decoder_selector_);
103 toolbar->addSeparator();
104 toolbar->addWidget(save_button_);
106 connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
107 this, SLOT(on_selected_decoder_changed(int)));
110 decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
113 save_action_->setText(tr("&Save..."));
114 save_action_->setIcon(QIcon::fromTheme("document-save-as",
115 QIcon(":/icons/document-save-as.png")));
116 save_action_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
117 connect(save_action_, SIGNAL(triggered(bool)),
118 this, SLOT(on_actionSave_triggered()));
120 QMenu *save_menu = new QMenu();
121 connect(save_menu, SIGNAL(triggered(QAction*)),
122 this, SLOT(on_actionSave_triggered(QAction*)));
124 for (int i = 0; i < SaveTypeCount; i++) {
125 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
126 action->setData(qVariantFromValue(i));
129 save_button_->setMenu(save_menu);
130 save_button_->setDefaultAction(save_action_);
131 save_button_->setPopupMode(QToolButton::MenuButtonPopup);
133 // Set up the table view
134 table_view_->setModel(model_);
135 table_view_->setSelectionBehavior(QAbstractItemView::SelectRows);
136 table_view_->setSelectionMode(QAbstractItemView::ContiguousSelection);
137 table_view_->setSortingEnabled(true);
138 table_view_->sortByColumn(0, Qt::AscendingOrder);
140 const int font_height = QFontMetrics(QApplication::font()).height();
141 table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
142 table_view_->verticalHeader()->setVisible(false);
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 model_->set_signal_and_segment(signal_, current_segment_);
247 void View::save_data_as_csv(unsigned int save_type) const
249 // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
257 const bool save_all = !table_view_->selectionModel()->hasSelection();
259 GlobalSettings settings;
260 const QString dir = settings.value("MainWindow/SaveDirectory").toString();
262 const QString file_name = QFileDialog::getSaveFileName(
263 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
265 if (file_name.isEmpty())
268 QFile file(file_name);
269 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
270 QTextStream out_stream(&file);
273 table_view_->selectAll();
275 // Write out header columns in visual order, not logical order
276 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
277 int column = table_view_->horizontalHeader()->logicalIndex(i);
279 if (table_view_->horizontalHeader()->isSectionHidden(column))
282 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
284 if (save_type == SaveTypeCSVEscaped)
287 out_stream << '"' << title << '"';
289 if (i < (table_view_->horizontalHeader()->count() - 1))
292 out_stream << '\r' << '\n';
295 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
297 for (int i = 0; i < selected_rows.size(); i++) {
298 const int row = selected_rows.at(i).row();
300 // Write out columns in visual order, not logical order
301 for (int c = 0; c < table_view_->horizontalHeader()->count(); c++) {
302 const int column = table_view_->horizontalHeader()->logicalIndex(c);
304 if (table_view_->horizontalHeader()->isSectionHidden(column))
307 const QModelIndex idx = model_->index(row, column, QModelIndex());
308 QString s = model_->data(idx, Qt::DisplayRole).toString();
310 if (save_type == SaveTypeCSVEscaped)
311 out_stream << s.replace(",", "\\,");
313 out_stream << '"' << s.replace("\"", "\"\"") << '"';
315 if (c < (table_view_->horizontalHeader()->count() - 1))
319 out_stream << '\r' << '\n';
322 if (out_stream.status() == QTextStream::Ok) {
324 table_view_->clearSelection();
330 QMessageBox msg(parent_);
331 msg.setText(tr("Error") + "\n\n" + tr("File %1 could not be written to.").arg(file_name));
332 msg.setStandardButtons(QMessageBox::Ok);
333 msg.setIcon(QMessageBox::Warning);
337 void View::on_selected_decoder_changed(int index)
340 disconnect(signal_, SIGNAL(color_changed(QColor)));
341 disconnect(signal_, SIGNAL(new_annotations()));
342 disconnect(signal_, SIGNAL(decode_reset()));
347 decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
349 // Find the signal that contains the selected decoder
350 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
351 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
352 if (decoder_ == dec.get())
356 connect(signal_, SIGNAL(color_changed(QColor)), this, SLOT(on_signal_color_changed(QColor)));
357 connect(signal_, SIGNAL(new_annotations()), this, SLOT(on_new_annotations()));
358 connect(signal_, SIGNAL(decode_reset()), this, SLOT(on_decoder_reset()));
364 void View::on_signal_name_changed(const QString &name)
368 SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
371 DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
374 // Update the top-level decoder provided by this signal
375 auto stack = signal->decoder_stack();
376 if (!stack.empty()) {
377 shared_ptr<Decoder>& dec = stack.at(0);
378 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
381 decoder_selector_->setItemText(index, signal->name());
385 void View::on_signal_color_changed(const QColor &color)
389 table_view_->update();
392 void View::on_new_annotations()
394 if (!delayed_view_updater_.isActive())
395 delayed_view_updater_.start();
398 void View::on_decoder_reset()
400 // Invalidate the model's data connection immediately - otherwise we
401 // will use a stale pointer in model_->index() when called from the table view
402 model_->set_signal_and_segment(signal_, current_segment_);
405 void View::on_decoder_stacked(void* decoder)
407 Decoder* d = static_cast<Decoder*>(decoder);
409 // Find the signal that contains the selected decoder
410 DecodeSignal* signal = nullptr;
412 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
413 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
419 const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
420 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
423 // Add the decoder to the list
424 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
428 void View::on_decoder_removed(void* decoder)
430 Decoder* d = static_cast<Decoder*>(decoder);
432 // Remove the decoder from the list
433 int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
436 decoder_selector_->removeItem(index);
439 void View::on_actionSave_triggered(QAction* action)
441 int save_type = SaveTypeCSVQuoted;
444 save_type = action->data().toInt();
446 save_data_as_csv(save_type);
449 void View::on_table_item_clicked(const QModelIndex& index)
453 // Force repaint, otherwise the new selection isn't shown for some reason
454 table_view_->viewport()->update();
457 void View::on_table_item_double_clicked(const QModelIndex& index)
459 const Annotation* ann = static_cast<const Annotation*>(index.internalPointer());
461 shared_ptr<views::ViewBase> main_view = session_.main_view();
463 main_view->focus_on_range(ann->start_sample(), ann->end_sample());
466 void View::on_table_header_requested(const QPoint& pos)
468 QMenu* menu = new QMenu(this);
470 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
471 int column = table_view_->horizontalHeader()->logicalIndex(i);
473 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
474 QAction* action = new QAction(title, this);
476 action->setCheckable(true);
477 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
478 action->setData(column);
480 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
482 menu->addAction(action);
485 menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
488 void View::on_table_header_toggled(bool checked)
490 QAction* action = qobject_cast<QAction*>(QObject::sender());
493 const int column = action->data().toInt();
495 table_view_->horizontalHeader()->setSectionHidden(column, !checked);
498 void View::perform_delayed_view_update()
504 } // namespace tabular_decoder