1ed6f95b18b1a0daedf3903291febfab099f8ed2
[pulseview.git] / pv / views / tabular_decoder / view.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2020 Soeren Apel <soeren@apelpie.net>
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 #include <climits>
21
22 #include <QApplication>
23 #include <QDebug>
24 #include <QFileDialog>
25 #include <QFontMetrics>
26 #include <QHeaderView>
27 #include <QLabel>
28 #include <QMenu>
29 #include <QMessageBox>
30 #include <QToolBar>
31 #include <QVBoxLayout>
32
33 #include <libsigrokdecode/libsigrokdecode.h>
34
35 #include "view.hpp"
36
37 #include "pv/globalsettings.hpp"
38 #include "pv/session.hpp"
39 #include "pv/util.hpp"
40 #include "pv/data/decode/decoder.hpp"
41
42 using pv::data::DecodeSignal;
43 using pv::data::SignalBase;
44 using pv::data::decode::Decoder;
45 using pv::util::Timestamp;
46
47 using std::make_shared;
48 using std::max;
49 using std::shared_ptr;
50
51 namespace pv {
52 namespace views {
53 namespace tabular_decoder {
54
55 const char* SaveTypeNames[SaveTypeCount] = {
56         "CSV, commas escaped",
57         "CSV, fields quoted"
58 };
59
60 const char* ViewModeNames[ViewModeCount] = {
61         "Show all",
62         "Show all and focus on newest",
63         "Show visible in main view"
64 };
65
66
67 CustomFilterProxyModel::CustomFilterProxyModel(QObject* parent) :
68         QSortFilterProxyModel(parent)
69 {
70 }
71
72 bool CustomFilterProxyModel::filterAcceptsRow(int sourceRow,
73         const QModelIndex &sourceParent) const
74 {
75         (void)sourceParent;
76         assert(sourceModel() != nullptr);
77
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();
81
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();
85
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"
91
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;
95
96         return !entirely_outside_of_range;
97 }
98
99 void CustomFilterProxyModel::set_sample_range(uint64_t start_sample,
100         uint64_t end_sample)
101 {
102         range_start_sample_ = start_sample;
103         range_end_sample_ = end_sample;
104
105         invalidateFilter();
106 }
107
108
109 QSize CustomTableView::minimumSizeHint() const
110 {
111         QSize size(QTableView::sizeHint());
112
113         int width = 0;
114         for (int i = 0; i < horizontalHeader()->count(); i++)
115                 if (!horizontalHeader()->isSectionHidden(i))
116                         width += horizontalHeader()->sectionSize(i);
117
118         size.setWidth(width + (horizontalHeader()->count() * 1));
119
120         return size;
121 }
122
123 QSize CustomTableView::sizeHint() const
124 {
125         return minimumSizeHint();
126 }
127
128
129 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
130         ViewBase(session, is_main_view, parent),
131
132         // Note: Place defaults in View::reset_view_state(), not here
133         parent_(parent),
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)),
142         signal_(nullptr)
143 {
144         QVBoxLayout *root_layout = new QVBoxLayout(this);
145         root_layout->setContentsMargins(0, 0, 0, 0);
146         root_layout->addWidget(table_view_);
147
148         // Create toolbar
149         QToolBar* toolbar = new QToolBar();
150         toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
151         parent->addToolBar(toolbar);
152
153         // Populate 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_);
162
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)));
169
170         // Configure widgets
171         decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
172
173         for (int i = 0; i < ViewModeCount; i++)
174                 view_mode_selector_->addItem(ViewModeNames[i], QVariant::fromValue(i));
175
176         hide_hidden_cb_->setText(tr("Hide Hidden Rows/Classes"));
177         hide_hidden_cb_->setChecked(true);
178
179         // Configure actions
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()));
186
187         QMenu *save_menu = new QMenu();
188         connect(save_menu, SIGNAL(triggered(QAction*)),
189                 this, SLOT(on_actionSave_triggered(QAction*)));
190
191         for (int i = 0; i < SaveTypeCount; i++) {
192                 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
193                 action->setData(QVariant::fromValue(i));
194         }
195
196         save_button_->setMenu(save_menu);
197         save_button_->setDefaultAction(save_action_);
198         save_button_->setPopupMode(QToolButton::MenuButtonPopup);
199
200         // Set up the models and the table view
201         filter_proxy_model_->setSourceModel(model_);
202         table_view_->setModel(filter_proxy_model_);
203
204         table_view_->setSelectionBehavior(QAbstractItemView::SelectRows);
205         table_view_->setSelectionMode(QAbstractItemView::ContiguousSelection);
206         table_view_->setSortingEnabled(true);
207         table_view_->sortByColumn(0, Qt::AscendingOrder);
208
209         for (uint8_t i = model_->first_hidden_column(); i < model_->columnCount(); i++)
210                 table_view_->setColumnHidden(i, true);
211
212         const int font_height = QFontMetrics(QApplication::font()).height();
213         table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
214         table_view_->verticalHeader()->setVisible(false);
215
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);
220
221         table_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
222         parent->setSizePolicy(table_view_->sizePolicy());
223
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&)));
230
231         // Set up metadata event handler
232         session_.metadata_obj_manager()->add_observer(this);
233
234         reset_view_state();
235 }
236
237 View::~View()
238 {
239         session_.metadata_obj_manager()->remove_observer(this);
240 }
241
242 ViewType View::get_type() const
243 {
244         return ViewTypeTabularDecoder;
245 }
246
247 void View::reset_view_state()
248 {
249         ViewBase::reset_view_state();
250
251         decoder_selector_->clear();
252 }
253
254 void View::clear_decode_signals()
255 {
256         ViewBase::clear_decode_signals();
257
258         reset_data();
259         reset_view_state();
260 }
261
262 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
263 {
264         ViewBase::add_decode_signal(signal);
265
266         connect(signal.get(), SIGNAL(name_changed(const QString&)),
267                 this, SLOT(on_signal_name_changed(const QString&)));
268
269         // Note: At time of initial creation, decode signals have no decoders so we
270         // need to watch for decoder stacking events
271
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*)));
276
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()));
282         }
283 }
284
285 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
286 {
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()));
290
291                 if (index != -1)
292                         decoder_selector_->removeItem(index);
293         }
294
295         ViewBase::remove_decode_signal(signal);
296
297         if (signal.get() == signal_) {
298                 reset_data();
299                 update_data();
300                 reset_view_state();
301         }
302 }
303
304 void View::save_settings(QSettings &settings) const
305 {
306         ViewBase::save_settings(settings);
307
308         settings.setValue("view_mode", view_mode_selector_->currentIndex());
309         settings.setValue("hide_hidden", hide_hidden_cb_->isChecked());
310 }
311
312 void View::restore_settings(QSettings &settings)
313 {
314         ViewBase::restore_settings(settings);
315
316         if (settings.contains("view_mode"))
317                 view_mode_selector_->setCurrentIndex(settings.value("view_mode").toInt());
318
319         if (settings.contains("hide_hidden"))
320                 hide_hidden_cb_->setChecked(settings.value("hide_hidden").toBool());
321 }
322
323 void View::reset_data()
324 {
325         signal_ = nullptr;
326         decoder_ = nullptr;
327 }
328
329 void View::update_data()
330 {
331         model_->set_signal_and_segment(signal_, current_segment_);
332 }
333
334 void View::save_data_as_csv(unsigned int save_type) const
335 {
336         // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
337
338         assert(decoder_);
339         assert(signal_);
340
341         if (!signal_)
342                 return;
343
344         const bool save_all = !table_view_->selectionModel()->hasSelection();
345
346         GlobalSettings settings;
347         const QString dir = settings.value("MainWindow/SaveDirectory").toString();
348
349         const QString file_name = QFileDialog::getSaveFileName(
350                 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
351
352         if (file_name.isEmpty())
353                 return;
354
355         QFile file(file_name);
356         if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
357                 QTextStream out_stream(&file);
358
359                 if (save_all)
360                         table_view_->selectAll();
361
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);
365
366                         if (table_view_->horizontalHeader()->isSectionHidden(column))
367                                 continue;
368
369                         const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
370
371                         if (save_type == SaveTypeCSVEscaped)
372                                 out_stream << title;
373                         else
374                                 out_stream << '"' << title << '"';
375
376                         if (i < (table_view_->horizontalHeader()->count() - 1))
377                                 out_stream << ",";
378                 }
379                 out_stream << '\r' << '\n';
380
381
382                 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
383
384                 for (int i = 0; i < selected_rows.size(); i++) {
385                         const int row = selected_rows.at(i).row();
386
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);
390
391                                 if (table_view_->horizontalHeader()->isSectionHidden(column))
392                                         continue;
393
394                                 const QModelIndex idx = model_->index(row, column);
395                                 QString s = model_->data(idx, Qt::DisplayRole).toString();
396
397                                 if (save_type == SaveTypeCSVEscaped)
398                                         out_stream << s.replace(",", "\\,");
399                                 else
400                                         out_stream << '"' << s.replace("\"", "\"\"") << '"';
401
402                                 if (c < (table_view_->horizontalHeader()->count() - 1))
403                                         out_stream << ",";
404                         }
405
406                         out_stream << '\r' << '\n';
407                 }
408
409                 if (out_stream.status() == QTextStream::Ok) {
410                         if (save_all)
411                                 table_view_->clearSelection();
412
413                         return;
414                 }
415         }
416
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);
421         msg.exec();
422 }
423
424 void View::on_selected_decoder_changed(int index)
425 {
426         if (signal_) {
427                 disconnect(signal_, SIGNAL(color_changed(QColor)));
428                 disconnect(signal_, SIGNAL(new_annotations()));
429                 disconnect(signal_, SIGNAL(decode_reset()));
430         }
431
432         reset_data();
433
434         decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
435
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())
440                                 signal_ = ds.get();
441
442         if (signal_) {
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()));
446         }
447
448         update_data();
449 }
450
451 void View::on_hide_hidden_changed(bool checked)
452 {
453         model_->set_hide_hidden(checked);
454
455         // Force repaint, otherwise the new selection isn't shown for some reason
456         table_view_->viewport()->update();
457 }
458
459 void View::on_view_mode_changed(int index)
460 {
461         if (index == ViewModeVisible) {
462                 MetadataObject *md_obj =
463                         session_.metadata_obj_manager()->find_object_by_type(MetadataObjMainViewRange);
464                 assert(md_obj);
465
466                 int64_t start_sample = md_obj->value(MetadataValueStartSample).toLongLong();
467                 int64_t end_sample = md_obj->value(MetadataValueEndSample).toLongLong();
468
469                 filter_proxy_model_->set_sample_range(max((int64_t)0, start_sample),
470                         max((int64_t)0, end_sample));
471
472                 // Force repaint, otherwise the new selection may not show immediately
473 //              table_view_->viewport()->update();
474         } else {
475                 // Use the data model directly
476                 table_view_->setModel(model_);
477         }
478
479         if (index == ViewModeLatest)
480                 table_view_->scrollTo(
481                         filter_proxy_model_->mapFromSource(model_->index(model_->rowCount() - 1, 0)),
482                         QAbstractItemView::PositionAtBottom);
483 }
484
485 void View::on_signal_name_changed(const QString &name)
486 {
487         (void)name;
488
489         SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
490         assert(sb);
491
492         DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
493         assert(signal);
494
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()));
500
501                 if (index != -1)
502                         decoder_selector_->setItemText(index, signal->name());
503         }
504 }
505
506 void View::on_signal_color_changed(const QColor &color)
507 {
508         (void)color;
509
510         table_view_->update();
511 }
512
513 void View::on_new_annotations()
514 {
515         if (view_mode_selector_->currentIndex() == ViewModeLatest) {
516                 update_data();
517                 table_view_->scrollTo(model_->index(model_->rowCount() - 1, 0),
518                         QAbstractItemView::PositionAtBottom);
519         } else {
520                 if (!delayed_view_updater_.isActive())
521                         delayed_view_updater_.start();
522         }
523 }
524
525 void View::on_decoder_reset()
526 {
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_);
530 }
531
532 void View::on_decoder_stacked(void* decoder)
533 {
534         Decoder* d = static_cast<Decoder*>(decoder);
535
536         // Find the signal that contains the selected decoder
537         DecodeSignal* signal = nullptr;
538
539         for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
540                 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
541                         if (d == dec.get())
542                                 signal = ds.get();
543
544         assert(signal);
545
546         const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
547         int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
548
549         if (index == -1) {
550                 // Add the decoder to the list
551                 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
552         }
553 }
554
555 void View::on_decoder_removed(void* decoder)
556 {
557         Decoder* d = static_cast<Decoder*>(decoder);
558
559         // Remove the decoder from the list
560         int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
561
562         if (index != -1)
563                 decoder_selector_->removeItem(index);
564 }
565
566 void View::on_actionSave_triggered(QAction* action)
567 {
568         int save_type = SaveTypeCSVQuoted;
569
570         if (action)
571                 save_type = action->data().toInt();
572
573         save_data_as_csv(save_type);
574 }
575
576 void View::on_table_item_clicked(const QModelIndex& index)
577 {
578         (void)index;
579
580         // Force repaint, otherwise the new selection isn't shown for some reason
581         table_view_->viewport()->update();
582 }
583
584 void View::on_table_item_double_clicked(const QModelIndex& index)
585 {
586         const Annotation* ann = static_cast<const Annotation*>(index.internalPointer());
587
588         shared_ptr<views::ViewBase> main_view = session_.main_view();
589
590         main_view->focus_on_range(ann->start_sample(), ann->end_sample());
591 }
592
593 void View::on_table_header_requested(const QPoint& pos)
594 {
595         QMenu* menu = new QMenu(this);
596
597         for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
598                 int column = table_view_->horizontalHeader()->logicalIndex(i);
599
600                 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
601                 QAction* action = new QAction(title, this);
602
603                 action->setCheckable(true);
604                 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
605                 action->setData(column);
606
607                 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
608
609                 menu->addAction(action);
610         }
611
612         menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
613 }
614
615 void View::on_table_header_toggled(bool checked)
616 {
617         QAction* action = qobject_cast<QAction*>(QObject::sender());
618         assert(action);
619
620         const int column = action->data().toInt();
621
622         table_view_->horizontalHeader()->setSectionHidden(column, !checked);
623 }
624
625 void View::on_metadata_object_changed(MetadataObject* obj,
626         MetadataValueType value_type)
627 {
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
631
632         if ((view_mode_selector_->currentIndex() == ViewModeVisible) &&
633                 (obj->type() == MetadataObjMainViewRange) &&
634                 (value_type == MetadataValueEndSample)) {
635
636                 int64_t start_sample = obj->value(MetadataValueStartSample).toLongLong();
637                 int64_t end_sample = obj->value(MetadataValueEndSample).toLongLong();
638
639                 filter_proxy_model_->set_sample_range(max((int64_t)0, start_sample),
640                         max((int64_t)0, end_sample));
641         }
642
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));
648
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());
653
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);
657                         }
658                 }
659         }
660 }
661
662 void View::perform_delayed_view_update()
663 {
664         update_data();
665 }
666
667
668 } // namespace tabular_decoder
669 } // namespace views
670 } // namespace pv