]> sigrok.org Git - pulseview.git/blob - pv/views/tabular_decoder/view.cpp
Replace deprecated qVariantFromValue
[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 QSize QCustomTableView::minimumSizeHint() const
67 {
68         QSize size(QTableView::sizeHint());
69
70         int width = 0;
71         for (int i = 0; i < horizontalHeader()->count(); i++)
72                 if (!horizontalHeader()->isSectionHidden(i))
73                         width += horizontalHeader()->sectionSize(i);
74
75         size.setWidth(width + (horizontalHeader()->count() * 1));
76
77         return size;
78 }
79
80 QSize QCustomTableView::sizeHint() const
81 {
82         return minimumSizeHint();
83 }
84
85
86 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
87         ViewBase(session, is_main_view, parent),
88
89         // Note: Place defaults in View::reset_view_state(), not here
90         parent_(parent),
91         decoder_selector_(new QComboBox()),
92         hide_hidden_cb_(new QCheckBox()),
93         view_mode_selector_(new QComboBox()),
94         save_button_(new QToolButton()),
95         save_action_(new QAction(this)),
96         table_view_(new QCustomTableView()),
97         model_(new AnnotationCollectionModel()),
98         signal_(nullptr)
99 {
100         QVBoxLayout *root_layout = new QVBoxLayout(this);
101         root_layout->setContentsMargins(0, 0, 0, 0);
102         root_layout->addWidget(table_view_);
103
104         // Create toolbar
105         QToolBar* toolbar = new QToolBar();
106         toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
107         parent->addToolBar(toolbar);
108
109         // Populate toolbar
110         toolbar->addWidget(new QLabel(tr("Decoder:")));
111         toolbar->addWidget(decoder_selector_);
112         toolbar->addSeparator();
113         toolbar->addWidget(save_button_);
114         toolbar->addSeparator();
115         toolbar->addWidget(view_mode_selector_);
116         toolbar->addSeparator();
117         toolbar->addWidget(hide_hidden_cb_);
118
119         connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
120                 this, SLOT(on_selected_decoder_changed(int)));
121         connect(view_mode_selector_, SIGNAL(currentIndexChanged(int)),
122                 this, SLOT(on_view_mode_changed(int)));
123         connect(hide_hidden_cb_, SIGNAL(toggled(bool)),
124                 this, SLOT(on_hide_hidden_changed(bool)));
125
126         // Configure widgets
127         decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
128
129         for (int i = 0; i < ViewModeCount; i++)
130                 view_mode_selector_->addItem(ViewModeNames[i], QVariant::fromValue(i));
131
132         hide_hidden_cb_->setText(tr("Hide Hidden Rows/Classes"));
133         hide_hidden_cb_->setChecked(true);
134
135         // Configure actions
136         save_action_->setText(tr("&Save..."));
137         save_action_->setIcon(QIcon::fromTheme("document-save-as",
138                 QIcon(":/icons/document-save-as.png")));
139         save_action_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
140         connect(save_action_, SIGNAL(triggered(bool)),
141                 this, SLOT(on_actionSave_triggered()));
142
143         QMenu *save_menu = new QMenu();
144         connect(save_menu, SIGNAL(triggered(QAction*)),
145                 this, SLOT(on_actionSave_triggered(QAction*)));
146
147         for (int i = 0; i < SaveTypeCount; i++) {
148                 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
149                 action->setData(QVariant::fromValue(i));
150         }
151
152         save_button_->setMenu(save_menu);
153         save_button_->setDefaultAction(save_action_);
154         save_button_->setPopupMode(QToolButton::MenuButtonPopup);
155
156         // Set up the table view
157         table_view_->setModel(model_);
158         table_view_->setSelectionBehavior(QAbstractItemView::SelectRows);
159         table_view_->setSelectionMode(QAbstractItemView::ContiguousSelection);
160         table_view_->setSortingEnabled(false);
161         table_view_->sortByColumn(0, Qt::AscendingOrder);
162
163         const int font_height = QFontMetrics(QApplication::font()).height();
164         table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
165         table_view_->verticalHeader()->setVisible(false);
166
167         table_view_->horizontalHeader()->setStretchLastSection(true);
168         table_view_->horizontalHeader()->setCascadingSectionResizes(true);
169         table_view_->horizontalHeader()->setSectionsMovable(true);
170         table_view_->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
171
172         table_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
173         parent->setSizePolicy(table_view_->sizePolicy());
174
175         connect(table_view_, SIGNAL(clicked(const QModelIndex&)),
176                 this, SLOT(on_table_item_clicked(const QModelIndex&)));
177         connect(table_view_, SIGNAL(doubleClicked(const QModelIndex&)),
178                 this, SLOT(on_table_item_double_clicked(const QModelIndex&)));
179         connect(table_view_->horizontalHeader(), SIGNAL(customContextMenuRequested(const QPoint&)),
180                 this, SLOT(on_table_header_requested(const QPoint&)));
181
182         // Set up metadata event handler
183         session_.metadata_obj_manager()->add_observer(this);
184
185         reset_view_state();
186 }
187
188 View::~View()
189 {
190         session_.metadata_obj_manager()->remove_observer(this);
191 }
192
193 ViewType View::get_type() const
194 {
195         return ViewTypeTabularDecoder;
196 }
197
198 void View::reset_view_state()
199 {
200         ViewBase::reset_view_state();
201
202         decoder_selector_->clear();
203 }
204
205 void View::clear_decode_signals()
206 {
207         ViewBase::clear_decode_signals();
208
209         reset_data();
210         reset_view_state();
211 }
212
213 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
214 {
215         ViewBase::add_decode_signal(signal);
216
217         connect(signal.get(), SIGNAL(name_changed(const QString&)),
218                 this, SLOT(on_signal_name_changed(const QString&)));
219
220         // Note: At time of initial creation, decode signals have no decoders so we
221         // need to watch for decoder stacking events
222
223         connect(signal.get(), SIGNAL(decoder_stacked(void*)),
224                 this, SLOT(on_decoder_stacked(void*)));
225         connect(signal.get(), SIGNAL(decoder_removed(void*)),
226                 this, SLOT(on_decoder_removed(void*)));
227
228         // Add the top-level decoder provided by an already-existing signal
229         auto stack = signal->decoder_stack();
230         if (!stack.empty()) {
231                 shared_ptr<Decoder>& dec = stack.at(0);
232                 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)dec.get()));
233         }
234 }
235
236 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
237 {
238         // Remove all decoders provided by this signal
239         for (const shared_ptr<Decoder>& dec : signal->decoder_stack()) {
240                 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
241
242                 if (index != -1)
243                         decoder_selector_->removeItem(index);
244         }
245
246         ViewBase::remove_decode_signal(signal);
247
248         if (signal.get() == signal_) {
249                 reset_data();
250                 update_data();
251                 reset_view_state();
252         }
253 }
254
255 void View::save_settings(QSettings &settings) const
256 {
257         ViewBase::save_settings(settings);
258
259         settings.setValue("view_mode", view_mode_selector_->currentIndex());
260         settings.setValue("hide_hidden", hide_hidden_cb_->isChecked());
261 }
262
263 void View::restore_settings(QSettings &settings)
264 {
265         ViewBase::restore_settings(settings);
266
267         if (settings.contains("view_mode"))
268                 view_mode_selector_->setCurrentIndex(settings.value("view_mode").toInt());
269
270         if (settings.contains("hide_hidden"))
271                 hide_hidden_cb_->setChecked(settings.value("hide_hidden").toBool());
272 }
273
274 void View::reset_data()
275 {
276         signal_ = nullptr;
277         decoder_ = nullptr;
278 }
279
280 void View::update_data()
281 {
282         model_->set_signal_and_segment(signal_, current_segment_);
283 }
284
285 void View::save_data_as_csv(unsigned int save_type) const
286 {
287         // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
288
289         assert(decoder_);
290         assert(signal_);
291
292         if (!signal_)
293                 return;
294
295         const bool save_all = !table_view_->selectionModel()->hasSelection();
296
297         GlobalSettings settings;
298         const QString dir = settings.value("MainWindow/SaveDirectory").toString();
299
300         const QString file_name = QFileDialog::getSaveFileName(
301                 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
302
303         if (file_name.isEmpty())
304                 return;
305
306         QFile file(file_name);
307         if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
308                 QTextStream out_stream(&file);
309
310                 if (save_all)
311                         table_view_->selectAll();
312
313                 // Write out header columns in visual order, not logical order
314                 for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
315                         int column = table_view_->horizontalHeader()->logicalIndex(i);
316
317                         if (table_view_->horizontalHeader()->isSectionHidden(column))
318                                 continue;
319
320                         const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
321
322                         if (save_type == SaveTypeCSVEscaped)
323                                 out_stream << title;
324                         else
325                                 out_stream << '"' << title << '"';
326
327                         if (i < (table_view_->horizontalHeader()->count() - 1))
328                                 out_stream << ",";
329                 }
330                 out_stream << '\r' << '\n';
331
332
333                 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
334
335                 for (int i = 0; i < selected_rows.size(); i++) {
336                         const int row = selected_rows.at(i).row();
337
338                         // Write out columns in visual order, not logical order
339                         for (int c = 0; c < table_view_->horizontalHeader()->count(); c++) {
340                                 const int column = table_view_->horizontalHeader()->logicalIndex(c);
341
342                                 if (table_view_->horizontalHeader()->isSectionHidden(column))
343                                         continue;
344
345                                 const QModelIndex idx = model_->index(row, column);
346                                 QString s = model_->data(idx, Qt::DisplayRole).toString();
347
348                                 if (save_type == SaveTypeCSVEscaped)
349                                         out_stream << s.replace(",", "\\,");
350                                 else
351                                         out_stream << '"' << s.replace("\"", "\"\"") << '"';
352
353                                 if (c < (table_view_->horizontalHeader()->count() - 1))
354                                         out_stream << ",";
355                         }
356
357                         out_stream << '\r' << '\n';
358                 }
359
360                 if (out_stream.status() == QTextStream::Ok) {
361                         if (save_all)
362                                 table_view_->clearSelection();
363
364                         return;
365                 }
366         }
367
368         QMessageBox msg(parent_);
369         msg.setText(tr("Error") + "\n\n" + tr("File %1 could not be written to.").arg(file_name));
370         msg.setStandardButtons(QMessageBox::Ok);
371         msg.setIcon(QMessageBox::Warning);
372         msg.exec();
373 }
374
375 void View::on_selected_decoder_changed(int index)
376 {
377         if (signal_) {
378                 disconnect(signal_, SIGNAL(color_changed(QColor)));
379                 disconnect(signal_, SIGNAL(new_annotations()));
380                 disconnect(signal_, SIGNAL(decode_reset()));
381         }
382
383         reset_data();
384
385         decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
386
387         // Find the signal that contains the selected decoder
388         for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
389                 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
390                         if (decoder_ == dec.get())
391                                 signal_ = ds.get();
392
393         if (signal_) {
394                 connect(signal_, SIGNAL(color_changed(QColor)), this, SLOT(on_signal_color_changed(QColor)));
395                 connect(signal_, SIGNAL(new_annotations()), this, SLOT(on_new_annotations()));
396                 connect(signal_, SIGNAL(decode_reset()), this, SLOT(on_decoder_reset()));
397         }
398
399         update_data();
400 }
401
402 void View::on_hide_hidden_changed(bool checked)
403 {
404         model_->set_hide_hidden(checked);
405
406         // Force repaint, otherwise the new selection isn't shown for some reason
407         table_view_->viewport()->update();
408 }
409
410 void View::on_view_mode_changed(int index)
411 {
412         if (index == ViewModeVisible) {
413                 MetadataObject *md_obj =
414                         session_.metadata_obj_manager()->find_object_by_type(MetadataObjMainViewRange);
415                 assert(md_obj);
416
417                 int64_t start_sample = md_obj->value(MetadataValueStartSample).toLongLong();
418                 int64_t end_sample = md_obj->value(MetadataValueEndSample).toLongLong();
419
420                 model_->set_sample_range(max((int64_t)0, start_sample),
421                         max((int64_t)0, end_sample));
422         } else {
423                 // Reset the model's data range
424                 model_->set_sample_range(0, 0);
425         }
426
427         if (index == ViewModeLatest)
428                 table_view_->scrollTo(model_->index(model_->rowCount() - 1, 0),
429                         QAbstractItemView::PositionAtBottom);
430 }
431
432 void View::on_signal_name_changed(const QString &name)
433 {
434         (void)name;
435
436         SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
437         assert(sb);
438
439         DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
440         assert(signal);
441
442         // Update the top-level decoder provided by this signal
443         auto stack = signal->decoder_stack();
444         if (!stack.empty()) {
445                 shared_ptr<Decoder>& dec = stack.at(0);
446                 int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
447
448                 if (index != -1)
449                         decoder_selector_->setItemText(index, signal->name());
450         }
451 }
452
453 void View::on_signal_color_changed(const QColor &color)
454 {
455         (void)color;
456
457         table_view_->update();
458 }
459
460 void View::on_new_annotations()
461 {
462         if (view_mode_selector_->currentIndex() == ViewModeLatest) {
463                 update_data();
464                 table_view_->scrollTo(model_->index(model_->rowCount() - 1, 0),
465                         QAbstractItemView::PositionAtBottom);
466         } else {
467                 if (!delayed_view_updater_.isActive())
468                         delayed_view_updater_.start();
469         }
470 }
471
472 void View::on_decoder_reset()
473 {
474         // Invalidate the model's data connection immediately - otherwise we
475         // will use a stale pointer in model_->index() when called from the table view
476         model_->set_signal_and_segment(signal_, current_segment_);
477 }
478
479 void View::on_decoder_stacked(void* decoder)
480 {
481         Decoder* d = static_cast<Decoder*>(decoder);
482
483         // Find the signal that contains the selected decoder
484         DecodeSignal* signal = nullptr;
485
486         for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
487                 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
488                         if (d == dec.get())
489                                 signal = ds.get();
490
491         assert(signal);
492
493         const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
494         int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
495
496         if (index == -1) {
497                 // Add the decoder to the list
498                 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
499         }
500 }
501
502 void View::on_decoder_removed(void* decoder)
503 {
504         Decoder* d = static_cast<Decoder*>(decoder);
505
506         // Remove the decoder from the list
507         int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
508
509         if (index != -1)
510                 decoder_selector_->removeItem(index);
511 }
512
513 void View::on_actionSave_triggered(QAction* action)
514 {
515         int save_type = SaveTypeCSVQuoted;
516
517         if (action)
518                 save_type = action->data().toInt();
519
520         save_data_as_csv(save_type);
521 }
522
523 void View::on_table_item_clicked(const QModelIndex& index)
524 {
525         (void)index;
526
527         // Force repaint, otherwise the new selection isn't shown for some reason
528         table_view_->viewport()->update();
529 }
530
531 void View::on_table_item_double_clicked(const QModelIndex& index)
532 {
533         const Annotation* ann = static_cast<const Annotation*>(index.internalPointer());
534
535         shared_ptr<views::ViewBase> main_view = session_.main_view();
536
537         main_view->focus_on_range(ann->start_sample(), ann->end_sample());
538 }
539
540 void View::on_table_header_requested(const QPoint& pos)
541 {
542         QMenu* menu = new QMenu(this);
543
544         for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
545                 int column = table_view_->horizontalHeader()->logicalIndex(i);
546
547                 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
548                 QAction* action = new QAction(title, this);
549
550                 action->setCheckable(true);
551                 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
552                 action->setData(column);
553
554                 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
555
556                 menu->addAction(action);
557         }
558
559         menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
560 }
561
562 void View::on_table_header_toggled(bool checked)
563 {
564         QAction* action = qobject_cast<QAction*>(QObject::sender());
565         assert(action);
566
567         const int column = action->data().toInt();
568
569         table_view_->horizontalHeader()->setSectionHidden(column, !checked);
570 }
571
572 void View::on_metadata_object_changed(MetadataObject* obj,
573         MetadataValueType value_type)
574 {
575         // Check if we need to update the model's data range. We only work on the
576         // end sample value because the start sample value is updated first and
577         // we don't want to update the model twice
578
579         if ((view_mode_selector_->currentIndex() == ViewModeVisible) &&
580                 (obj->type() == MetadataObjMainViewRange) &&
581                 (value_type == MetadataValueEndSample)) {
582
583                 int64_t start_sample = obj->value(MetadataValueStartSample).toLongLong();
584                 int64_t end_sample = obj->value(MetadataValueEndSample).toLongLong();
585
586                 model_->set_sample_range(max((int64_t)0, start_sample),
587                         max((int64_t)0, end_sample));
588         }
589
590         if (obj->type() == MetadataObjMousePos) {
591                 QModelIndex first_visual_idx = table_view_->indexAt(table_view_->rect().topLeft());
592                 QModelIndex last_visual_idx = table_view_->indexAt(table_view_->rect().bottomLeft());
593
594                 model_->update_highlighted_rows(first_visual_idx, last_visual_idx,
595                         obj->value(MetadataValueStartSample).toLongLong());
596         }
597 }
598
599 void View::perform_delayed_view_update()
600 {
601         update_data();
602 }
603
604
605 } // namespace tabular_decoder
606 } // namespace views
607 } // namespace pv