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"
67 CustomFilterProxyModel::CustomFilterProxyModel(QObject* parent) :
68 QSortFilterProxyModel(parent)
72 bool CustomFilterProxyModel::filterAcceptsRow(int sourceRow,
73 const QModelIndex &sourceParent) const
76 assert(sourceModel() != nullptr);
78 const QModelIndex ann_start_sample_idx = sourceModel()->index(sourceRow, 0);
79 const uint64_t ann_start_sample =
80 sourceModel()->data(ann_start_sample_idx, Qt::DisplayRole).toULongLong();
82 const QModelIndex ann_end_sample_idx = sourceModel()->index(sourceRow, 6);
83 const uint64_t ann_end_sample =
84 sourceModel()->data(ann_end_sample_idx, Qt::DisplayRole).toULongLong();
86 // We consider all annotations as visible that either
87 // a) begin to the left of the range and end within the range or
88 // b) begin and end within the range or
89 // c) begin within the range and end to the right of the range
90 // ...which is equivalent to the negation of "begins and ends outside the range"
92 const bool left_of_range = (ann_end_sample < range_start_sample_);
93 const bool right_of_range = (ann_start_sample > range_end_sample_);
94 const bool entirely_outside_of_range = left_of_range || right_of_range;
96 return !entirely_outside_of_range;
99 void CustomFilterProxyModel::set_sample_range(uint64_t start_sample,
102 range_start_sample_ = start_sample;
103 range_end_sample_ = end_sample;
109 QSize CustomTableView::minimumSizeHint() const
111 QSize size(QTableView::sizeHint());
114 for (int i = 0; i < horizontalHeader()->count(); i++)
115 if (!horizontalHeader()->isSectionHidden(i))
116 width += horizontalHeader()->sectionSize(i);
118 size.setWidth(width + (horizontalHeader()->count() * 1));
123 QSize CustomTableView::sizeHint() const
125 return minimumSizeHint();
129 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
130 ViewBase(session, is_main_view, parent),
132 // Note: Place defaults in View::reset_view_state(), not here
134 decoder_selector_(new QComboBox()),
135 hide_hidden_cb_(new QCheckBox()),
136 view_mode_selector_(new QComboBox()),
137 save_button_(new QToolButton()),
138 save_action_(new QAction(this)),
139 table_view_(new CustomTableView()),
140 model_(new AnnotationCollectionModel(this)),
141 filter_proxy_model_(new CustomFilterProxyModel(this)),
144 QVBoxLayout *root_layout = new QVBoxLayout(this);
145 root_layout->setContentsMargins(0, 0, 0, 0);
146 root_layout->addWidget(table_view_);
149 QToolBar* toolbar = new QToolBar();
150 toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
151 parent->addToolBar(toolbar);
154 toolbar->addWidget(new QLabel(tr("Decoder:")));
155 toolbar->addWidget(decoder_selector_);
156 toolbar->addSeparator();
157 toolbar->addWidget(save_button_);
158 toolbar->addSeparator();
159 toolbar->addWidget(view_mode_selector_);
160 toolbar->addSeparator();
161 toolbar->addWidget(hide_hidden_cb_);
163 connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
164 this, SLOT(on_selected_decoder_changed(int)));
165 connect(view_mode_selector_, SIGNAL(currentIndexChanged(int)),
166 this, SLOT(on_view_mode_changed(int)));
167 connect(hide_hidden_cb_, SIGNAL(toggled(bool)),
168 this, SLOT(on_hide_hidden_changed(bool)));
171 decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
173 for (int i = 0; i < ViewModeCount; i++)
174 view_mode_selector_->addItem(ViewModeNames[i], QVariant::fromValue(i));
176 hide_hidden_cb_->setText(tr("Hide Hidden Rows/Classes"));
177 hide_hidden_cb_->setChecked(true);
180 save_action_->setText(tr("&Save..."));
181 save_action_->setIcon(QIcon::fromTheme("document-save-as",
182 QIcon(":/icons/document-save-as.png")));
183 save_action_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
184 connect(save_action_, SIGNAL(triggered(bool)),
185 this, SLOT(on_actionSave_triggered()));
187 QMenu *save_menu = new QMenu();
188 connect(save_menu, SIGNAL(triggered(QAction*)),
189 this, SLOT(on_actionSave_triggered(QAction*)));
191 for (int i = 0; i < SaveTypeCount; i++) {
192 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
193 action->setData(QVariant::fromValue(i));
196 save_button_->setMenu(save_menu);
197 save_button_->setDefaultAction(save_action_);
198 save_button_->setPopupMode(QToolButton::MenuButtonPopup);
200 // Set up the models and the table view
201 filter_proxy_model_->setSourceModel(model_);
202 table_view_->setModel(filter_proxy_model_);
204 table_view_->setSelectionBehavior(QAbstractItemView::SelectRows);
205 table_view_->setSelectionMode(QAbstractItemView::ContiguousSelection);
206 table_view_->setSortingEnabled(true);
207 table_view_->sortByColumn(0, Qt::AscendingOrder);
209 for (uint8_t i = model_->first_hidden_column(); i < model_->columnCount(); i++)
210 table_view_->setColumnHidden(i, true);
212 const int font_height = QFontMetrics(QApplication::font()).height();
213 table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
214 table_view_->verticalHeader()->setVisible(false);
216 table_view_->horizontalHeader()->setStretchLastSection(true);
217 table_view_->horizontalHeader()->setCascadingSectionResizes(true);
218 table_view_->horizontalHeader()->setSectionsMovable(true);
219 table_view_->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
221 table_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
222 parent->setSizePolicy(table_view_->sizePolicy());
224 connect(table_view_, SIGNAL(clicked(const QModelIndex&)),
225 this, SLOT(on_table_item_clicked(const QModelIndex&)));
226 connect(table_view_, SIGNAL(doubleClicked(const QModelIndex&)),
227 this, SLOT(on_table_item_double_clicked(const QModelIndex&)));
228 connect(table_view_->horizontalHeader(), SIGNAL(customContextMenuRequested(const QPoint&)),
229 this, SLOT(on_table_header_requested(const QPoint&)));
231 // Set up metadata event handler
232 session_.metadata_obj_manager()->add_observer(this);
239 session_.metadata_obj_manager()->remove_observer(this);
242 ViewType View::get_type() const
244 return ViewTypeTabularDecoder;
247 void View::reset_view_state()
249 ViewBase::reset_view_state();
251 decoder_selector_->clear();
254 void View::clear_decode_signals()
256 ViewBase::clear_decode_signals();
262 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
264 ViewBase::add_decode_signal(signal);
266 connect(signal.get(), SIGNAL(name_changed(const QString&)),
267 this, SLOT(on_signal_name_changed(const QString&)));
269 // Note: At time of initial creation, decode signals have no decoders so we
270 // need to watch for decoder stacking events
272 connect(signal.get(), SIGNAL(decoder_stacked(void*)),
273 this, SLOT(on_decoder_stacked(void*)));
274 connect(signal.get(), SIGNAL(decoder_removed(void*)),
275 this, SLOT(on_decoder_removed(void*)));
277 // Add the top-level decoder provided by an already-existing signal
278 auto stack = signal->decoder_stack();
279 if (!stack.empty()) {
280 shared_ptr<Decoder>& dec = stack.at(0);
281 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)dec.get()));
285 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
287 // Remove all decoders provided by this signal
288 for (const shared_ptr<Decoder>& dec : signal->decoder_stack()) {
289 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
292 decoder_selector_->removeItem(index);
295 ViewBase::remove_decode_signal(signal);
297 if (signal.get() == signal_) {
304 void View::save_settings(QSettings &settings) const
306 ViewBase::save_settings(settings);
308 settings.setValue("view_mode", view_mode_selector_->currentIndex());
309 settings.setValue("hide_hidden", hide_hidden_cb_->isChecked());
312 void View::restore_settings(QSettings &settings)
314 ViewBase::restore_settings(settings);
316 if (settings.contains("view_mode"))
317 view_mode_selector_->setCurrentIndex(settings.value("view_mode").toInt());
319 if (settings.contains("hide_hidden"))
320 hide_hidden_cb_->setChecked(settings.value("hide_hidden").toBool());
323 void View::reset_data()
329 void View::update_data()
331 model_->set_signal_and_segment(signal_, current_segment_);
334 void View::save_data_as_csv(unsigned int save_type) const
336 // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
344 const bool save_all = !table_view_->selectionModel()->hasSelection();
346 GlobalSettings settings;
347 const QString dir = settings.value("MainWindow/SaveDirectory").toString();
349 const QString file_name = QFileDialog::getSaveFileName(
350 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
352 if (file_name.isEmpty())
355 QFile file(file_name);
356 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
357 QTextStream out_stream(&file);
360 table_view_->selectAll();
362 // Write out header columns in visual order, not logical order
363 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
364 int column = table_view_->horizontalHeader()->logicalIndex(i);
366 if (table_view_->horizontalHeader()->isSectionHidden(column))
369 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
371 if (save_type == SaveTypeCSVEscaped)
374 out_stream << '"' << title << '"';
376 if (i < (table_view_->horizontalHeader()->count() - 1))
379 out_stream << '\r' << '\n';
382 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
384 for (int i = 0; i < selected_rows.size(); i++) {
385 const int row = selected_rows.at(i).row();
387 // Write out columns in visual order, not logical order
388 for (int c = 0; c < table_view_->horizontalHeader()->count(); c++) {
389 const int column = table_view_->horizontalHeader()->logicalIndex(c);
391 if (table_view_->horizontalHeader()->isSectionHidden(column))
394 const QModelIndex idx = model_->index(row, column);
395 QString s = model_->data(idx, Qt::DisplayRole).toString();
397 if (save_type == SaveTypeCSVEscaped)
398 out_stream << s.replace(",", "\\,");
400 out_stream << '"' << s.replace("\"", "\"\"") << '"';
402 if (c < (table_view_->horizontalHeader()->count() - 1))
406 out_stream << '\r' << '\n';
409 if (out_stream.status() == QTextStream::Ok) {
411 table_view_->clearSelection();
417 QMessageBox msg(parent_);
418 msg.setText(tr("Error") + "\n\n" + tr("File %1 could not be written to.").arg(file_name));
419 msg.setStandardButtons(QMessageBox::Ok);
420 msg.setIcon(QMessageBox::Warning);
424 void View::on_selected_decoder_changed(int index)
427 disconnect(signal_, SIGNAL(color_changed(QColor)));
428 disconnect(signal_, SIGNAL(new_annotations()));
429 disconnect(signal_, SIGNAL(decode_reset()));
434 decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
436 // Find the signal that contains the selected decoder
437 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
438 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
439 if (decoder_ == dec.get())
443 connect(signal_, SIGNAL(color_changed(QColor)), this, SLOT(on_signal_color_changed(QColor)));
444 connect(signal_, SIGNAL(new_annotations()), this, SLOT(on_new_annotations()));
445 connect(signal_, SIGNAL(decode_reset()), this, SLOT(on_decoder_reset()));
451 void View::on_hide_hidden_changed(bool checked)
453 model_->set_hide_hidden(checked);
455 // Force repaint, otherwise the new selection isn't shown for some reason
456 table_view_->viewport()->update();
459 void View::on_view_mode_changed(int index)
461 if (index == ViewModeVisible) {
462 MetadataObject *md_obj =
463 session_.metadata_obj_manager()->find_object_by_type(MetadataObjMainViewRange);
466 int64_t start_sample = md_obj->value(MetadataValueStartSample).toLongLong();
467 int64_t end_sample = md_obj->value(MetadataValueEndSample).toLongLong();
469 filter_proxy_model_->set_sample_range(max((int64_t)0, start_sample),
470 max((int64_t)0, end_sample));
472 // Force repaint, otherwise the new selection may not show immediately
473 // table_view_->viewport()->update();
475 // Use the data model directly
476 table_view_->setModel(model_);
479 if (index == ViewModeLatest)
480 table_view_->scrollTo(
481 filter_proxy_model_->mapFromSource(model_->index(model_->rowCount() - 1, 0)),
482 QAbstractItemView::PositionAtBottom);
485 void View::on_signal_name_changed(const QString &name)
489 SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
492 DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
495 // Update the top-level decoder provided by this signal
496 auto stack = signal->decoder_stack();
497 if (!stack.empty()) {
498 shared_ptr<Decoder>& dec = stack.at(0);
499 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
502 decoder_selector_->setItemText(index, signal->name());
506 void View::on_signal_color_changed(const QColor &color)
510 table_view_->update();
513 void View::on_new_annotations()
515 if (view_mode_selector_->currentIndex() == ViewModeLatest) {
517 table_view_->scrollTo(model_->index(model_->rowCount() - 1, 0),
518 QAbstractItemView::PositionAtBottom);
520 if (!delayed_view_updater_.isActive())
521 delayed_view_updater_.start();
525 void View::on_decoder_reset()
527 // Invalidate the model's data connection immediately - otherwise we
528 // will use a stale pointer in model_->index() when called from the table view
529 model_->set_signal_and_segment(signal_, current_segment_);
532 void View::on_decoder_stacked(void* decoder)
534 Decoder* d = static_cast<Decoder*>(decoder);
536 // Find the signal that contains the selected decoder
537 DecodeSignal* signal = nullptr;
539 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
540 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
546 const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
547 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
550 // Add the decoder to the list
551 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
555 void View::on_decoder_removed(void* decoder)
557 Decoder* d = static_cast<Decoder*>(decoder);
559 // Remove the decoder from the list
560 int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
563 decoder_selector_->removeItem(index);
566 void View::on_actionSave_triggered(QAction* action)
568 int save_type = SaveTypeCSVQuoted;
571 save_type = action->data().toInt();
573 save_data_as_csv(save_type);
576 void View::on_table_item_clicked(const QModelIndex& index)
580 // Force repaint, otherwise the new selection isn't shown for some reason
581 table_view_->viewport()->update();
584 void View::on_table_item_double_clicked(const QModelIndex& index)
586 const Annotation* ann = static_cast<const Annotation*>(index.internalPointer());
588 shared_ptr<views::ViewBase> main_view = session_.main_view();
590 main_view->focus_on_range(ann->start_sample(), ann->end_sample());
593 void View::on_table_header_requested(const QPoint& pos)
595 QMenu* menu = new QMenu(this);
597 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
598 int column = table_view_->horizontalHeader()->logicalIndex(i);
600 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
601 QAction* action = new QAction(title, this);
603 action->setCheckable(true);
604 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
605 action->setData(column);
607 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
609 menu->addAction(action);
612 menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
615 void View::on_table_header_toggled(bool checked)
617 QAction* action = qobject_cast<QAction*>(QObject::sender());
620 const int column = action->data().toInt();
622 table_view_->horizontalHeader()->setSectionHidden(column, !checked);
625 void View::on_metadata_object_changed(MetadataObject* obj,
626 MetadataValueType value_type)
628 // Check if we need to update the model's data range. We only work on the
629 // end sample value because the start sample value is updated first and
630 // we don't want to update the model twice
632 if ((view_mode_selector_->currentIndex() == ViewModeVisible) &&
633 (obj->type() == MetadataObjMainViewRange) &&
634 (value_type == MetadataValueEndSample)) {
636 int64_t start_sample = obj->value(MetadataValueStartSample).toLongLong();
637 int64_t end_sample = obj->value(MetadataValueEndSample).toLongLong();
639 filter_proxy_model_->set_sample_range(max((int64_t)0, start_sample),
640 max((int64_t)0, end_sample));
643 if (obj->type() == MetadataObjMousePos) {
644 QModelIndex first_visible_idx =
645 filter_proxy_model_->mapToSource(filter_proxy_model_->index(0, 0));
646 QModelIndex last_visible_idx =
647 filter_proxy_model_->mapToSource(filter_proxy_model_->index(filter_proxy_model_->rowCount() - 1, 0));
649 if (first_visible_idx.isValid()) {
650 const QModelIndex first_highlighted_idx =
651 model_->update_highlighted_rows(first_visible_idx, last_visible_idx,
652 obj->value(MetadataValueStartSample).toLongLong());
654 if (view_mode_selector_->currentIndex() == ViewModeVisible) {
655 const QModelIndex idx = filter_proxy_model_->mapFromSource(first_highlighted_idx);
656 table_view_->scrollTo(idx, QAbstractItemView::EnsureVisible);
662 void View::perform_delayed_view_update()
668 } // namespace tabular_decoder