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),
69 range_filtering_enabled_(false)
73 bool CustomFilterProxyModel::filterAcceptsRow(int sourceRow,
74 const QModelIndex &sourceParent) const
77 assert(sourceModel() != nullptr);
81 if (range_filtering_enabled_) {
82 const QModelIndex ann_start_sample_idx = sourceModel()->index(sourceRow, 0);
83 const uint64_t ann_start_sample =
84 sourceModel()->data(ann_start_sample_idx, Qt::DisplayRole).toULongLong();
86 const QModelIndex ann_end_sample_idx = sourceModel()->index(sourceRow, 6);
87 const uint64_t ann_end_sample =
88 sourceModel()->data(ann_end_sample_idx, Qt::DisplayRole).toULongLong();
90 // We consider all annotations as visible that either
91 // a) begin to the left of the range and end within the range or
92 // b) begin and end within the range or
93 // c) begin within the range and end to the right of the range
94 // ...which is equivalent to the negation of "begins and ends outside the range"
96 const bool left_of_range = (ann_end_sample < range_start_sample_);
97 const bool right_of_range = (ann_start_sample > range_end_sample_);
98 const bool entirely_outside_of_range = left_of_range || right_of_range;
100 result = !entirely_outside_of_range;
106 void CustomFilterProxyModel::set_sample_range(uint64_t start_sample,
109 range_start_sample_ = start_sample;
110 range_end_sample_ = end_sample;
115 void CustomFilterProxyModel::enable_range_filtering(bool value)
117 range_filtering_enabled_ = value;
123 QSize CustomTableView::minimumSizeHint() const
125 QSize size(QTableView::sizeHint());
128 for (int i = 0; i < horizontalHeader()->count(); i++)
129 if (!horizontalHeader()->isSectionHidden(i))
130 width += horizontalHeader()->sectionSize(i);
132 size.setWidth(width + (horizontalHeader()->count() * 1));
137 QSize CustomTableView::sizeHint() const
139 return minimumSizeHint();
142 void CustomTableView::keyPressEvent(QKeyEvent *event)
144 if ((event->key() == Qt::Key_Return) || (event->key() == Qt::Key_Enter))
145 activatedByKey(currentIndex());
147 QTableView::keyPressEvent(event);
151 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
152 ViewBase(session, is_main_view, parent),
154 // Note: Place defaults in View::reset_view_state(), not here
156 decoder_selector_(new QComboBox()),
157 hide_hidden_cb_(new QCheckBox()),
158 view_mode_selector_(new QComboBox()),
159 save_button_(new QToolButton()),
160 save_action_(new QAction(this)),
161 table_view_(new CustomTableView()),
162 model_(new AnnotationCollectionModel(this)),
163 filter_proxy_model_(new CustomFilterProxyModel(this)),
166 QVBoxLayout *root_layout = new QVBoxLayout(this);
167 root_layout->setContentsMargins(0, 0, 0, 0);
168 root_layout->addWidget(table_view_);
171 QToolBar* toolbar = new QToolBar();
172 toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
173 parent->addToolBar(toolbar);
176 toolbar->addWidget(new QLabel(tr("Decoder:")));
177 toolbar->addWidget(decoder_selector_);
178 toolbar->addSeparator();
179 toolbar->addWidget(save_button_);
180 toolbar->addSeparator();
181 toolbar->addWidget(view_mode_selector_);
182 toolbar->addSeparator();
183 toolbar->addWidget(hide_hidden_cb_);
185 connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
186 this, SLOT(on_selected_decoder_changed(int)));
187 connect(view_mode_selector_, SIGNAL(currentIndexChanged(int)),
188 this, SLOT(on_view_mode_changed(int)));
189 connect(hide_hidden_cb_, SIGNAL(toggled(bool)),
190 this, SLOT(on_hide_hidden_changed(bool)));
193 decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
195 for (int i = 0; i < ViewModeCount; i++)
196 view_mode_selector_->addItem(ViewModeNames[i], QVariant::fromValue(i));
198 hide_hidden_cb_->setText(tr("Hide Hidden Rows/Classes"));
199 hide_hidden_cb_->setChecked(true);
202 save_action_->setText(tr("&Save..."));
203 save_action_->setIcon(QIcon::fromTheme("document-save-as",
204 QIcon(":/icons/document-save-as.png")));
205 save_action_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
206 connect(save_action_, SIGNAL(triggered(bool)),
207 this, SLOT(on_actionSave_triggered()));
209 QMenu *save_menu = new QMenu();
210 connect(save_menu, SIGNAL(triggered(QAction*)),
211 this, SLOT(on_actionSave_triggered(QAction*)));
213 for (int i = 0; i < SaveTypeCount; i++) {
214 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
215 action->setData(QVariant::fromValue(i));
218 save_button_->setMenu(save_menu);
219 save_button_->setDefaultAction(save_action_);
220 save_button_->setPopupMode(QToolButton::MenuButtonPopup);
222 // Set up the models and the table view
223 filter_proxy_model_->setSourceModel(model_);
224 table_view_->setModel(filter_proxy_model_);
226 table_view_->setSelectionBehavior(QAbstractItemView::SelectRows);
227 table_view_->setSelectionMode(QAbstractItemView::ContiguousSelection);
228 table_view_->setSortingEnabled(true);
229 table_view_->sortByColumn(0, Qt::AscendingOrder);
231 for (uint8_t i = model_->first_hidden_column(); i < model_->columnCount(); i++)
232 table_view_->setColumnHidden(i, true);
234 const int font_height = QFontMetrics(QApplication::font()).height();
235 table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
236 table_view_->verticalHeader()->setVisible(false);
238 table_view_->horizontalHeader()->setStretchLastSection(true);
239 table_view_->horizontalHeader()->setCascadingSectionResizes(true);
240 table_view_->horizontalHeader()->setSectionsMovable(true);
241 table_view_->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
243 table_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
244 parent->setSizePolicy(table_view_->sizePolicy());
246 connect(table_view_, SIGNAL(clicked(const QModelIndex&)),
247 this, SLOT(on_table_item_clicked(const QModelIndex&)));
248 connect(table_view_, SIGNAL(doubleClicked(const QModelIndex&)),
249 this, SLOT(on_table_item_double_clicked(const QModelIndex&)));
250 connect(table_view_, SIGNAL(activatedByKey(const QModelIndex&)),
251 this, SLOT(on_table_item_double_clicked(const QModelIndex&)));
252 connect(table_view_->horizontalHeader(), SIGNAL(customContextMenuRequested(const QPoint&)),
253 this, SLOT(on_table_header_requested(const QPoint&)));
255 // Set up metadata event handler
256 session_.metadata_obj_manager()->add_observer(this);
263 session_.metadata_obj_manager()->remove_observer(this);
266 ViewType View::get_type() const
268 return ViewTypeTabularDecoder;
271 void View::reset_view_state()
273 ViewBase::reset_view_state();
275 decoder_selector_->clear();
278 void View::clear_decode_signals()
280 ViewBase::clear_decode_signals();
286 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
288 ViewBase::add_decode_signal(signal);
290 connect(signal.get(), SIGNAL(name_changed(const QString&)),
291 this, SLOT(on_signal_name_changed(const QString&)));
293 // Note: At time of initial creation, decode signals have no decoders so we
294 // need to watch for decoder stacking events
296 connect(signal.get(), SIGNAL(decoder_stacked(void*)),
297 this, SLOT(on_decoder_stacked(void*)));
298 connect(signal.get(), SIGNAL(decoder_removed(void*)),
299 this, SLOT(on_decoder_removed(void*)));
301 // Add the top-level decoder provided by an already-existing signal
302 auto stack = signal->decoder_stack();
303 if (!stack.empty()) {
304 shared_ptr<Decoder>& dec = stack.at(0);
305 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)dec.get()));
309 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
311 // Remove all decoders provided by this signal
312 for (const shared_ptr<Decoder>& dec : signal->decoder_stack()) {
313 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
316 decoder_selector_->removeItem(index);
319 ViewBase::remove_decode_signal(signal);
321 if (signal.get() == signal_) {
328 void View::save_settings(QSettings &settings) const
330 ViewBase::save_settings(settings);
332 settings.setValue("view_mode", view_mode_selector_->currentIndex());
333 settings.setValue("hide_hidden", hide_hidden_cb_->isChecked());
336 void View::restore_settings(QSettings &settings)
338 ViewBase::restore_settings(settings);
340 if (settings.contains("view_mode"))
341 view_mode_selector_->setCurrentIndex(settings.value("view_mode").toInt());
343 if (settings.contains("hide_hidden"))
344 hide_hidden_cb_->setChecked(settings.value("hide_hidden").toBool());
347 void View::reset_data()
353 void View::update_data()
355 model_->set_signal_and_segment(signal_, current_segment_);
358 void View::save_data_as_csv(unsigned int save_type) const
360 // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
368 const bool save_all = !table_view_->selectionModel()->hasSelection();
370 GlobalSettings settings;
371 const QString dir = settings.value("MainWindow/SaveDirectory").toString();
373 const QString file_name = QFileDialog::getSaveFileName(
374 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
376 if (file_name.isEmpty())
379 QFile file(file_name);
380 if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
381 QTextStream out_stream(&file);
384 table_view_->selectAll();
386 // Write out header columns in visual order, not logical order
387 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
388 int column = table_view_->horizontalHeader()->logicalIndex(i);
390 if (table_view_->horizontalHeader()->isSectionHidden(column))
393 const QString title = filter_proxy_model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
395 if (save_type == SaveTypeCSVEscaped)
398 out_stream << '"' << title << '"';
400 if (i < (table_view_->horizontalHeader()->count() - 1))
403 out_stream << '\r' << '\n';
406 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
408 for (int i = 0; i < selected_rows.size(); i++) {
409 const int row = selected_rows.at(i).row();
411 // Write out columns in visual order, not logical order
412 for (int c = 0; c < table_view_->horizontalHeader()->count(); c++) {
413 const int column = table_view_->horizontalHeader()->logicalIndex(c);
415 if (table_view_->horizontalHeader()->isSectionHidden(column))
418 const QModelIndex idx = filter_proxy_model_->index(row, column);
419 QString s = filter_proxy_model_->data(idx, Qt::DisplayRole).toString();
421 if (save_type == SaveTypeCSVEscaped)
422 out_stream << s.replace(",", "\\,");
424 out_stream << '"' << s.replace("\"", "\"\"") << '"';
426 if (c < (table_view_->horizontalHeader()->count() - 1))
430 out_stream << '\r' << '\n';
433 if (out_stream.status() == QTextStream::Ok) {
435 table_view_->clearSelection();
441 QMessageBox msg(parent_);
442 msg.setText(tr("Error") + "\n\n" + tr("File %1 could not be written to.").arg(file_name));
443 msg.setStandardButtons(QMessageBox::Ok);
444 msg.setIcon(QMessageBox::Warning);
448 void View::on_selected_decoder_changed(int index)
451 disconnect(signal_, SIGNAL(color_changed(QColor)));
452 disconnect(signal_, SIGNAL(new_annotations()));
453 disconnect(signal_, SIGNAL(decode_reset()));
458 decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
460 // Find the signal that contains the selected decoder
461 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
462 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
463 if (decoder_ == dec.get())
467 connect(signal_, SIGNAL(color_changed(QColor)), this, SLOT(on_signal_color_changed(QColor)));
468 connect(signal_, SIGNAL(new_annotations()), this, SLOT(on_new_annotations()));
469 connect(signal_, SIGNAL(decode_reset()), this, SLOT(on_decoder_reset()));
474 // Force repaint, otherwise the new selection isn't shown for some reason
475 table_view_->viewport()->update();
478 void View::on_hide_hidden_changed(bool checked)
480 model_->set_hide_hidden(checked);
482 // Force repaint, otherwise the new selection isn't shown for some reason
483 table_view_->viewport()->update();
486 void View::on_view_mode_changed(int index)
488 if (index == ViewModeAll)
489 filter_proxy_model_->enable_range_filtering(false);
491 if (index == ViewModeVisible) {
492 MetadataObject *md_obj =
493 session_.metadata_obj_manager()->find_object_by_type(MetadataObjMainViewRange);
496 int64_t start_sample = md_obj->value(MetadataValueStartSample).toLongLong();
497 int64_t end_sample = md_obj->value(MetadataValueEndSample).toLongLong();
499 filter_proxy_model_->enable_range_filtering(true);
500 filter_proxy_model_->set_sample_range(max((int64_t)0, start_sample),
501 max((int64_t)0, end_sample));
504 if (index == ViewModeLatest) {
505 filter_proxy_model_->enable_range_filtering(false);
507 table_view_->scrollTo(
508 filter_proxy_model_->mapFromSource(model_->index(model_->rowCount() - 1, 0)),
509 QAbstractItemView::PositionAtBottom);
513 void View::on_signal_name_changed(const QString &name)
517 SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
520 DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
523 // Update the top-level decoder provided by this signal
524 auto stack = signal->decoder_stack();
525 if (!stack.empty()) {
526 shared_ptr<Decoder>& dec = stack.at(0);
527 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
530 decoder_selector_->setItemText(index, signal->name());
534 void View::on_signal_color_changed(const QColor &color)
538 // Force immediate repaint, otherwise it's updated after the header popup is closed
539 table_view_->viewport()->update();
542 void View::on_new_annotations()
544 if (view_mode_selector_->currentIndex() == ViewModeLatest) {
546 table_view_->scrollTo(
547 filter_proxy_model_->index(filter_proxy_model_->rowCount() - 1, 0),
548 QAbstractItemView::PositionAtBottom);
550 if (!delayed_view_updater_.isActive())
551 delayed_view_updater_.start();
555 void View::on_decoder_reset()
557 // Invalidate the model's data connection immediately - otherwise we
558 // will use a stale pointer in model_->index() when called from the table view
559 model_->set_signal_and_segment(signal_, current_segment_);
562 void View::on_decoder_stacked(void* decoder)
564 Decoder* d = static_cast<Decoder*>(decoder);
566 // Find the signal that contains the selected decoder
567 DecodeSignal* signal = nullptr;
569 for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
570 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
576 const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
577 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
580 // Add the decoder to the list
581 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
585 void View::on_decoder_removed(void* decoder)
587 Decoder* d = static_cast<Decoder*>(decoder);
589 // Remove the decoder from the list
590 int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
593 decoder_selector_->removeItem(index);
596 void View::on_actionSave_triggered(QAction* action)
598 int save_type = SaveTypeCSVQuoted;
601 save_type = action->data().toInt();
603 save_data_as_csv(save_type);
606 void View::on_table_item_clicked(const QModelIndex& index)
610 // Force repaint, otherwise the new selection isn't shown for some reason
611 table_view_->viewport()->update();
614 void View::on_table_item_double_clicked(const QModelIndex& index)
616 const QModelIndex src_idx = filter_proxy_model_->mapToSource(index);
618 const Annotation* ann = static_cast<const Annotation*>(src_idx.internalPointer());
621 shared_ptr<views::ViewBase> main_view = session_.main_view();
623 main_view->focus_on_range(ann->start_sample(), ann->end_sample());
626 void View::on_table_header_requested(const QPoint& pos)
628 QMenu* menu = new QMenu(this);
630 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
631 int column = table_view_->horizontalHeader()->logicalIndex(i);
633 const QString title =
634 filter_proxy_model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
635 QAction* action = new QAction(title, this);
637 action->setCheckable(true);
638 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
639 action->setData(column);
641 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
643 menu->addAction(action);
646 menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
649 void View::on_table_header_toggled(bool checked)
651 QAction* action = qobject_cast<QAction*>(QObject::sender());
654 const int column = action->data().toInt();
656 table_view_->horizontalHeader()->setSectionHidden(column, !checked);
659 void View::on_metadata_object_changed(MetadataObject* obj,
660 MetadataValueType value_type)
662 // Check if we need to update the model's data range. We only work on the
663 // end sample value because the start sample value is updated first and
664 // we don't want to update the model twice
666 if ((view_mode_selector_->currentIndex() == ViewModeVisible) &&
667 (obj->type() == MetadataObjMainViewRange) &&
668 (value_type == MetadataValueEndSample)) {
670 int64_t start_sample = obj->value(MetadataValueStartSample).toLongLong();
671 int64_t end_sample = obj->value(MetadataValueEndSample).toLongLong();
673 filter_proxy_model_->set_sample_range(max((int64_t)0, start_sample),
674 max((int64_t)0, end_sample));
677 if (obj->type() == MetadataObjMousePos) {
678 QModelIndex first_visible_idx =
679 filter_proxy_model_->mapToSource(filter_proxy_model_->index(0, 0));
680 QModelIndex last_visible_idx =
681 filter_proxy_model_->mapToSource(filter_proxy_model_->index(filter_proxy_model_->rowCount() - 1, 0));
683 if (first_visible_idx.isValid()) {
684 const QModelIndex first_highlighted_idx =
685 model_->update_highlighted_rows(first_visible_idx, last_visible_idx,
686 obj->value(MetadataValueStartSample).toLongLong());
688 if (view_mode_selector_->currentIndex() == ViewModeVisible) {
689 const QModelIndex idx = filter_proxy_model_->mapFromSource(first_highlighted_idx);
690 table_view_->scrollTo(idx, QAbstractItemView::EnsureVisible);
693 // Force repaint, otherwise the table doesn't immediately update for some reason
694 table_view_->viewport()->update();
699 void View::perform_delayed_view_update()
705 } // namespace tabular_decoder