e41734a101e62e580e3e3e61aed7e39e11feb820
[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::shared_ptr;
49
50 namespace pv {
51 namespace views {
52 namespace tabular_decoder {
53
54 const char* SaveTypeNames[SaveTypeCount] = {
55         "CSV, commas escaped",
56         "CSV, fields quoted"
57 };
58
59 QSize QCustomTableView::minimumSizeHint() const
60 {
61         QSize size(QTableView::sizeHint());
62
63         int width = 0;
64         for (int i = 0; i < horizontalHeader()->count(); i++)
65                 if (!horizontalHeader()->isSectionHidden(i))
66                         width += horizontalHeader()->sectionSize(i);
67
68         size.setWidth(width + (horizontalHeader()->count() * 1));
69
70         return size;
71 }
72
73 QSize QCustomTableView::sizeHint() const
74 {
75         return minimumSizeHint();
76 }
77
78
79 View::View(Session &session, bool is_main_view, QMainWindow *parent) :
80         ViewBase(session, is_main_view, parent),
81
82         // Note: Place defaults in View::reset_view_state(), not here
83         parent_(parent),
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()),
89         signal_(nullptr)
90 {
91         QVBoxLayout *root_layout = new QVBoxLayout(this);
92         root_layout->setContentsMargins(0, 0, 0, 0);
93         root_layout->addWidget(table_view_);
94
95         // Create toolbar
96         QToolBar* toolbar = new QToolBar();
97         toolbar->setContextMenuPolicy(Qt::PreventContextMenu);
98         parent->addToolBar(toolbar);
99
100         // Populate toolbar
101         toolbar->addWidget(new QLabel(tr("Decoder:")));
102         toolbar->addWidget(decoder_selector_);
103         toolbar->addSeparator();
104         toolbar->addWidget(save_button_);
105
106         connect(decoder_selector_, SIGNAL(currentIndexChanged(int)),
107                 this, SLOT(on_selected_decoder_changed(int)));
108
109         // Configure widgets
110         decoder_selector_->setSizeAdjustPolicy(QComboBox::AdjustToContents);
111
112         // Configure actions
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()));
119
120         QMenu *save_menu = new QMenu();
121         connect(save_menu, SIGNAL(triggered(QAction*)),
122                 this, SLOT(on_actionSave_triggered(QAction*)));
123
124         for (int i = 0; i < SaveTypeCount; i++) {
125                 QAction *const action = save_menu->addAction(tr(SaveTypeNames[i]));
126                 action->setData(qVariantFromValue(i));
127         }
128
129         save_button_->setMenu(save_menu);
130         save_button_->setDefaultAction(save_action_);
131         save_button_->setPopupMode(QToolButton::MenuButtonPopup);
132
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);
139
140         const int font_height = QFontMetrics(QApplication::font()).height();
141         table_view_->verticalHeader()->setDefaultSectionSize((font_height * 5) / 4);
142         table_view_->verticalHeader()->setVisible(false);
143
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);
148
149         table_view_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
150         parent->setSizePolicy(table_view_->sizePolicy());
151
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&)));
158
159         reset_view_state();
160 }
161
162 ViewType View::get_type() const
163 {
164         return ViewTypeTabularDecoder;
165 }
166
167 void View::reset_view_state()
168 {
169         ViewBase::reset_view_state();
170
171         decoder_selector_->clear();
172 }
173
174 void View::clear_decode_signals()
175 {
176         ViewBase::clear_decode_signals();
177
178         reset_data();
179         reset_view_state();
180 }
181
182 void View::add_decode_signal(shared_ptr<data::DecodeSignal> signal)
183 {
184         ViewBase::add_decode_signal(signal);
185
186         connect(signal.get(), SIGNAL(name_changed(const QString&)),
187                 this, SLOT(on_signal_name_changed(const QString&)));
188
189         // Note: At time of initial creation, decode signals have no decoders so we
190         // need to watch for decoder stacking events
191
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*)));
196
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()));
202         }
203 }
204
205 void View::remove_decode_signal(shared_ptr<data::DecodeSignal> signal)
206 {
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()));
210
211                 if (index != -1)
212                         decoder_selector_->removeItem(index);
213         }
214
215         ViewBase::remove_decode_signal(signal);
216
217         if (signal.get() == signal_) {
218                 reset_data();
219                 update_data();
220                 reset_view_state();
221         }
222 }
223
224 void View::save_settings(QSettings &settings) const
225 {
226         ViewBase::save_settings(settings);
227 }
228
229 void View::restore_settings(QSettings &settings)
230 {
231         // Note: It is assumed that this function is only called once,
232         // immediately after restoring a previous session.
233         ViewBase::restore_settings(settings);
234 }
235
236 void View::reset_data()
237 {
238         signal_ = nullptr;
239         decoder_ = nullptr;
240 }
241
242 void View::update_data()
243 {
244         model_->set_signal_and_segment(signal_, current_segment_);
245 }
246
247 void View::save_data_as_csv(unsigned int save_type) const
248 {
249         // Note: We try to follow RFC 4180 (https://tools.ietf.org/html/rfc4180)
250
251         assert(decoder_);
252         assert(signal_);
253
254         if (!signal_)
255                 return;
256
257         const bool save_all = !table_view_->selectionModel()->hasSelection();
258
259         GlobalSettings settings;
260         const QString dir = settings.value("MainWindow/SaveDirectory").toString();
261
262         const QString file_name = QFileDialog::getSaveFileName(
263                 parent_, tr("Save Annotations as CSV"), dir, tr("CSV Files (*.csv);;Text Files (*.txt);;All Files (*)"));
264
265         if (file_name.isEmpty())
266                 return;
267
268         QFile file(file_name);
269         if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
270                 QTextStream out_stream(&file);
271
272                 if (save_all)
273                         table_view_->selectAll();
274
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);
278
279                         if (table_view_->horizontalHeader()->isSectionHidden(column))
280                                 continue;
281
282                         const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
283
284                         if (save_type == SaveTypeCSVEscaped)
285                                 out_stream << title;
286                         else
287                                 out_stream << '"' << title << '"';
288
289                         if (i < (table_view_->horizontalHeader()->count() - 1))
290                                 out_stream << ",";
291                 }
292                 out_stream << '\r' << '\n';
293
294
295                 QModelIndexList selected_rows = table_view_->selectionModel()->selectedRows();
296
297                 for (int i = 0; i < selected_rows.size(); i++) {
298                         const int row = selected_rows.at(i).row();
299
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);
303
304                                 if (table_view_->horizontalHeader()->isSectionHidden(column))
305                                         continue;
306
307                                 const QModelIndex idx = model_->index(row, column, QModelIndex());
308                                 QString s = model_->data(idx, Qt::DisplayRole).toString();
309
310                                 if (save_type == SaveTypeCSVEscaped)
311                                         out_stream << s.replace(",", "\\,");
312                                 else
313                                         out_stream << '"' << s.replace("\"", "\"\"") << '"';
314
315                                 if (c < (table_view_->horizontalHeader()->count() - 1))
316                                         out_stream << ",";
317                         }
318
319                         out_stream << '\r' << '\n';
320                 }
321
322                 if (out_stream.status() == QTextStream::Ok) {
323                         if (save_all)
324                                 table_view_->clearSelection();
325
326                         return;
327                 }
328         }
329
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);
334         msg.exec();
335 }
336
337 void View::on_selected_decoder_changed(int index)
338 {
339         if (signal_) {
340                 disconnect(signal_, SIGNAL(color_changed(QColor)));
341                 disconnect(signal_, SIGNAL(new_annotations()));
342                 disconnect(signal_, SIGNAL(decode_reset()));
343         }
344
345         reset_data();
346
347         decoder_ = (Decoder*)decoder_selector_->itemData(index).value<void*>();
348
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())
353                                 signal_ = ds.get();
354
355         if (signal_) {
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()));
359         }
360
361         update_data();
362 }
363
364 void View::on_signal_name_changed(const QString &name)
365 {
366         (void)name;
367
368         SignalBase* sb = qobject_cast<SignalBase*>(QObject::sender());
369         assert(sb);
370
371         DecodeSignal* signal = dynamic_cast<DecodeSignal*>(sb);
372         assert(signal);
373
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()));
379
380                 if (index != -1)
381                         decoder_selector_->setItemText(index, signal->name());
382         }
383 }
384
385 void View::on_signal_color_changed(const QColor &color)
386 {
387         (void)color;
388
389         table_view_->update();
390 }
391
392 void View::on_new_annotations()
393 {
394         if (!delayed_view_updater_.isActive())
395                 delayed_view_updater_.start();
396 }
397
398 void View::on_decoder_reset()
399 {
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_);
403 }
404
405 void View::on_decoder_stacked(void* decoder)
406 {
407         Decoder* d = static_cast<Decoder*>(decoder);
408
409         // Find the signal that contains the selected decoder
410         DecodeSignal* signal = nullptr;
411
412         for (const shared_ptr<DecodeSignal>& ds : decode_signals_)
413                 for (const shared_ptr<Decoder>& dec : ds->decoder_stack())
414                         if (d == dec.get())
415                                 signal = ds.get();
416
417         assert(signal);
418
419         const shared_ptr<Decoder>& dec = signal->decoder_stack().at(0);
420         int index = decoder_selector_->findData(QVariant::fromValue((void*)dec.get()));
421
422         if (index == -1) {
423                 // Add the decoder to the list
424                 decoder_selector_->addItem(signal->name(), QVariant::fromValue((void*)d));
425         }
426 }
427
428 void View::on_decoder_removed(void* decoder)
429 {
430         Decoder* d = static_cast<Decoder*>(decoder);
431
432         // Remove the decoder from the list
433         int index = decoder_selector_->findData(QVariant::fromValue((void*)d));
434
435         if (index != -1)
436                 decoder_selector_->removeItem(index);
437 }
438
439 void View::on_actionSave_triggered(QAction* action)
440 {
441         int save_type = SaveTypeCSVQuoted;
442
443         if (action)
444                 save_type = action->data().toInt();
445
446         save_data_as_csv(save_type);
447 }
448
449 void View::on_table_item_clicked(const QModelIndex& index)
450 {
451         (void)index;
452
453         // Force repaint, otherwise the new selection isn't shown for some reason
454         table_view_->viewport()->update();
455 }
456
457 void View::on_table_item_double_clicked(const QModelIndex& index)
458 {
459         const Annotation* ann = static_cast<const Annotation*>(index.internalPointer());
460
461         shared_ptr<views::ViewBase> main_view = session_.main_view();
462
463         main_view->focus_on_range(ann->start_sample(), ann->end_sample());
464 }
465
466 void View::on_table_header_requested(const QPoint& pos)
467 {
468         QMenu* menu = new QMenu(this);
469
470         for (int i = 0; i < table_view_->horizontalHeader()->count(); i++) {
471                 int column = table_view_->horizontalHeader()->logicalIndex(i);
472
473                 const QString title = model_->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
474                 QAction* action = new QAction(title, this);
475
476                 action->setCheckable(true);
477                 action->setChecked(!table_view_->horizontalHeader()->isSectionHidden(column));
478                 action->setData(column);
479
480                 connect(action, SIGNAL(toggled(bool)), this, SLOT(on_table_header_toggled(bool)));
481
482                 menu->addAction(action);
483         }
484
485         menu->popup(table_view_->horizontalHeader()->viewport()->mapToGlobal(pos));
486 }
487
488 void View::on_table_header_toggled(bool checked)
489 {
490         QAction* action = qobject_cast<QAction*>(QObject::sender());
491         assert(action);
492
493         const int column = action->data().toInt();
494
495         table_view_->horizontalHeader()->setSectionHidden(column, !checked);
496 }
497
498 void View::perform_delayed_view_update()
499 {
500         update_data();
501 }
502
503
504 } // namespace tabular_decoder
505 } // namespace views
506 } // namespace pv