Header: Keep a shared_ptr of the clicked item
[pulseview.git] / pv / mainwindow.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
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, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include <cassert>
22
23 #ifdef ENABLE_DECODE
24 #include <libsigrokdecode/libsigrokdecode.h>
25 #endif
26
27 #include <algorithm>
28 #include <iterator>
29
30 #include <QAction>
31 #include <QApplication>
32 #include <QButtonGroup>
33 #include <QCloseEvent>
34 #include <QFileDialog>
35 #include <QMessageBox>
36 #include <QMenu>
37 #include <QMenuBar>
38 #include <QSettings>
39 #include <QStatusBar>
40 #include <QVBoxLayout>
41 #include <QWidget>
42
43 #include "mainwindow.h"
44
45 #include "devicemanager.h"
46 #include "dialogs/about.h"
47 #include "dialogs/connect.h"
48 #include "dialogs/storeprogress.h"
49 #include "toolbars/samplingbar.h"
50 #include "view/logicsignal.h"
51 #include "view/view.h"
52 #ifdef ENABLE_DECODE
53 #include "widgets/decodermenu.h"
54 #endif
55
56 #include <inttypes.h>
57 #include <stdint.h>
58 #include <stdarg.h>
59 #include <glib.h>
60 #include <libsigrok/libsigrok.hpp>
61
62 using std::list;
63 using std::map;
64 using std::pair;
65 using std::shared_ptr;
66 using std::string;
67
68 using sigrok::Device;
69 using sigrok::Error;
70 using sigrok::HardwareDevice;
71
72 namespace pv {
73
74 namespace view {
75 class SelectableItem;
76 }
77
78 const char *MainWindow::SettingOpenDirectory = "MainWindow/OpenDirectory";
79 const char *MainWindow::SettingSaveDirectory = "MainWindow/SaveDirectory";
80
81 MainWindow::MainWindow(DeviceManager &device_manager,
82         const char *open_file_name,
83         QWidget *parent) :
84         QMainWindow(parent),
85         _device_manager(device_manager),
86         _session(device_manager)
87 {
88         setup_ui();
89         restore_ui_settings();
90         if (open_file_name) {
91                 const QString s(QString::fromUtf8(open_file_name));
92                 QMetaObject::invokeMethod(this, "load_file",
93                         Qt::QueuedConnection,
94                         Q_ARG(QString, s));
95         }
96 }
97
98 void MainWindow::setup_ui()
99 {
100         setObjectName(QString::fromUtf8("MainWindow"));
101
102         // Set the window icon
103         QIcon icon;
104         icon.addFile(QString::fromUtf8(":/icons/sigrok-logo-notext.png"),
105                 QSize(), QIcon::Normal, QIcon::Off);
106         setWindowIcon(icon);
107
108         // Setup the central widget
109         _central_widget = new QWidget(this);
110         _vertical_layout = new QVBoxLayout(_central_widget);
111         _vertical_layout->setSpacing(6);
112         _vertical_layout->setContentsMargins(0, 0, 0, 0);
113         setCentralWidget(_central_widget);
114
115         _view = new pv::view::View(_session, this);
116
117         _vertical_layout->addWidget(_view);
118
119         // Setup the menu bar
120         QMenuBar *const menu_bar = new QMenuBar(this);
121         menu_bar->setGeometry(QRect(0, 0, 400, 25));
122
123         // File Menu
124         QMenu *const menu_file = new QMenu;
125         menu_file->setTitle(tr("&File"));
126
127         QAction *const action_open = new QAction(this);
128         action_open->setText(tr("&Open..."));
129         action_open->setIcon(QIcon::fromTheme("document-open",
130                 QIcon(":/icons/document-open.png")));
131         action_open->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O));
132         action_open->setObjectName(QString::fromUtf8("actionOpen"));
133         menu_file->addAction(action_open);
134
135         QAction *const action_save_as = new QAction(this);
136         action_save_as->setText(tr("&Save As..."));
137         action_save_as->setIcon(QIcon::fromTheme("document-save-as",
138                 QIcon(":/icons/document-save-as.png")));
139         action_save_as->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
140         action_save_as->setObjectName(QString::fromUtf8("actionSaveAs"));
141         menu_file->addAction(action_save_as);
142
143         menu_file->addSeparator();
144
145         QAction *const action_connect = new QAction(this);
146         action_connect->setText(tr("&Connect to Device..."));
147         action_connect->setObjectName(QString::fromUtf8("actionConnect"));
148         menu_file->addAction(action_connect);
149
150         menu_file->addSeparator();
151
152         QAction *action_quit = new QAction(this);
153         action_quit->setText(tr("&Quit"));
154         action_quit->setIcon(QIcon::fromTheme("application-exit",
155                 QIcon(":/icons/application-exit.png")));
156         action_quit->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
157         action_quit->setObjectName(QString::fromUtf8("actionQuit"));
158         menu_file->addAction(action_quit);
159
160         // View Menu
161         QMenu *menu_view = new QMenu;
162         menu_view->setTitle(tr("&View"));
163
164         QAction *const action_view_zoom_in = new QAction(this);
165         action_view_zoom_in->setText(tr("Zoom &In"));
166         action_view_zoom_in->setIcon(QIcon::fromTheme("zoom-in",
167                 QIcon(":/icons/zoom-in.png")));
168         // simply using Qt::Key_Plus shows no + in the menu
169         action_view_zoom_in->setShortcut(QKeySequence::ZoomIn);
170         action_view_zoom_in->setObjectName(
171                 QString::fromUtf8("actionViewZoomIn"));
172         menu_view->addAction(action_view_zoom_in);
173
174         QAction *const action_view_zoom_out = new QAction(this);
175         action_view_zoom_out->setText(tr("Zoom &Out"));
176         action_view_zoom_out->setIcon(QIcon::fromTheme("zoom-out",
177                 QIcon(":/icons/zoom-out.png")));
178         action_view_zoom_out->setShortcut(QKeySequence::ZoomOut);
179         action_view_zoom_out->setObjectName(
180                 QString::fromUtf8("actionViewZoomOut"));
181         menu_view->addAction(action_view_zoom_out);
182
183         QAction *const action_view_zoom_fit = new QAction(this);
184         action_view_zoom_fit->setText(tr("Zoom to &Fit"));
185         action_view_zoom_fit->setIcon(QIcon::fromTheme("zoom-fit",
186                 QIcon(":/icons/zoom-fit.png")));
187         action_view_zoom_fit->setShortcut(QKeySequence(Qt::Key_F));
188         action_view_zoom_fit->setObjectName(
189                 QString::fromUtf8("actionViewZoomFit"));
190         menu_view->addAction(action_view_zoom_fit);
191
192         QAction *const action_view_zoom_one_to_one = new QAction(this);
193         action_view_zoom_one_to_one->setText(tr("Zoom to &One-to-One"));
194         action_view_zoom_one_to_one->setIcon(QIcon::fromTheme("zoom-original",
195                 QIcon(":/icons/zoom-original.png")));
196         action_view_zoom_one_to_one->setShortcut(QKeySequence(Qt::Key_O));
197         action_view_zoom_one_to_one->setObjectName(
198                 QString::fromUtf8("actionViewZoomOneToOne"));
199         menu_view->addAction(action_view_zoom_one_to_one);
200
201         menu_view->addSeparator();
202
203         QAction *action_view_show_cursors = new QAction(this);
204         action_view_show_cursors->setCheckable(true);
205         action_view_show_cursors->setChecked(_view->cursors_shown());
206         action_view_show_cursors->setShortcut(QKeySequence(Qt::Key_C));
207         action_view_show_cursors->setObjectName(
208                 QString::fromUtf8("actionViewShowCursors"));
209         action_view_show_cursors->setText(tr("Show &Cursors"));
210         menu_view->addAction(action_view_show_cursors);
211
212         // Decoders Menu
213 #ifdef ENABLE_DECODE
214         QMenu *const menu_decoders = new QMenu;
215         menu_decoders->setTitle(tr("&Decoders"));
216
217         pv::widgets::DecoderMenu *const menu_decoders_add =
218                 new pv::widgets::DecoderMenu(menu_decoders, true);
219         menu_decoders_add->setTitle(tr("&Add"));
220         connect(menu_decoders_add, SIGNAL(decoder_selected(srd_decoder*)),
221                 this, SLOT(add_decoder(srd_decoder*)));
222
223         menu_decoders->addMenu(menu_decoders_add);
224 #endif
225
226         // Help Menu
227         QMenu *const menu_help = new QMenu;
228         menu_help->setTitle(tr("&Help"));
229
230         QAction *const action_about = new QAction(this);
231         action_about->setObjectName(QString::fromUtf8("actionAbout"));
232         action_about->setText(tr("&About..."));
233         menu_help->addAction(action_about);
234
235         menu_bar->addAction(menu_file->menuAction());
236         menu_bar->addAction(menu_view->menuAction());
237 #ifdef ENABLE_DECODE
238         menu_bar->addAction(menu_decoders->menuAction());
239 #endif
240         menu_bar->addAction(menu_help->menuAction());
241
242         setMenuBar(menu_bar);
243         QMetaObject::connectSlotsByName(this);
244
245         // Setup the toolbar
246         QToolBar *const toolbar = new QToolBar(tr("Main Toolbar"), this);
247         toolbar->setObjectName(QString::fromUtf8("MainToolbar"));
248         toolbar->addAction(action_open);
249         toolbar->addAction(action_save_as);
250         toolbar->addSeparator();
251         toolbar->addAction(action_view_zoom_in);
252         toolbar->addAction(action_view_zoom_out);
253         toolbar->addAction(action_view_zoom_fit);
254         toolbar->addAction(action_view_zoom_one_to_one);
255         addToolBar(toolbar);
256
257         // Setup the sampling bar
258         _sampling_bar = new toolbars::SamplingBar(_session, this);
259
260         // Populate the device list and select the initially selected device
261         update_device_list();
262
263         connect(_sampling_bar, SIGNAL(run_stop()), this,
264                 SLOT(run_stop()));
265         addToolBar(_sampling_bar);
266
267         // Set the title
268         setWindowTitle(tr("PulseView"));
269
270         // Setup _session events
271         connect(&_session, SIGNAL(capture_state_changed(int)), this,
272                 SLOT(capture_state_changed(int)));
273 }
274
275 void MainWindow::save_ui_settings()
276 {
277         QSettings settings;
278
279         map<string, string> dev_info;
280         list<string> key_list;
281
282         settings.beginGroup("MainWindow");
283         settings.setValue("state", saveState());
284         settings.setValue("geometry", saveGeometry());
285         settings.endGroup();
286
287         if (_session.device()) {
288                 settings.beginGroup("Device");
289                 key_list.push_back("vendor");
290                 key_list.push_back("model");
291                 key_list.push_back("version");
292                 key_list.push_back("serial_num");
293                 key_list.push_back("connection_id");
294
295                 dev_info = _device_manager.get_device_info(
296                         _session.device());
297
298                 for (string key : key_list) {
299
300                         if (dev_info.count(key))
301                                 settings.setValue(QString::fromUtf8(key.c_str()),
302                                                 QString::fromUtf8(dev_info.at(key).c_str()));
303                         else
304                                 settings.remove(QString::fromUtf8(key.c_str()));
305                 }
306
307                 settings.endGroup();
308         }
309 }
310
311 void MainWindow::restore_ui_settings()
312 {
313         QSettings settings;
314
315         shared_ptr<HardwareDevice> device;
316
317         map<string, string> dev_info;
318         list<string> key_list;
319         string value;
320
321         settings.beginGroup("MainWindow");
322
323         if (settings.contains("geometry")) {
324                 restoreGeometry(settings.value("geometry").toByteArray());
325                 restoreState(settings.value("state").toByteArray());
326         } else
327                 resize(1000, 720);
328
329         settings.endGroup();
330
331         // Re-select last used device if possible.
332         settings.beginGroup("Device");
333         key_list.push_back("vendor");
334         key_list.push_back("model");
335         key_list.push_back("version");
336         key_list.push_back("serial_num");
337         key_list.push_back("connection_id");
338
339         for (string key : key_list) {
340                 if (!settings.contains(QString::fromUtf8(key.c_str())))
341                         continue;
342
343                 value = settings.value(QString::fromUtf8(key.c_str())).toString().toStdString();
344
345                 if (value.size() > 0)
346                         dev_info.insert(std::make_pair(key, value));
347         }
348
349         device = _device_manager.find_device_from_info(dev_info);
350
351         if (device) {
352                 _session.set_device(device);
353                 update_device_list();
354         }
355
356         settings.endGroup();
357 }
358
359 void MainWindow::session_error(
360         const QString text, const QString info_text)
361 {
362         QMetaObject::invokeMethod(this, "show_session_error",
363                 Qt::QueuedConnection, Q_ARG(QString, text),
364                 Q_ARG(QString, info_text));
365 }
366
367 void MainWindow::update_device_list()
368 {
369         assert(_sampling_bar);
370
371         shared_ptr<Device> selected_device = _session.device();
372         list< shared_ptr<Device> > devices;
373
374         if (_device_manager.devices().size() == 0)
375                 return;
376
377         std::copy(_device_manager.devices().begin(),
378                 _device_manager.devices().end(), std::back_inserter(devices));
379
380         if (std::find(devices.begin(), devices.end(), selected_device) ==
381                 devices.end())
382                 devices.push_back(selected_device);
383         assert(selected_device);
384
385         list< pair< shared_ptr<Device>, string> > device_list;
386
387         for (auto device : devices)
388                 device_list.push_back(make_pair(
389                         device, _device_manager.get_display_name(device)));
390
391         _sampling_bar->set_device_list(device_list, selected_device);
392 }
393
394 void MainWindow::closeEvent(QCloseEvent *event)
395 {
396         save_ui_settings();
397         event->accept();
398 }
399
400 void MainWindow::load_file(QString file_name)
401 {
402         const QString errorMessage(
403                 QString("Failed to load file %1").arg(file_name));
404         const QString infoMessage;
405
406         try {
407                 _session.set_file(file_name.toStdString());
408         } catch(Error e) {
409                 show_session_error(tr("Failed to load ") + file_name, e.what());
410                 _session.set_default_device();
411                 update_device_list();
412                 return;
413         }
414
415         update_device_list();
416
417         _session.start_capture([&, errorMessage, infoMessage](QString) {
418                 session_error(errorMessage, infoMessage); });
419 }
420
421 void MainWindow::show_session_error(
422         const QString text, const QString info_text)
423 {
424         QMessageBox msg(this);
425         msg.setText(text);
426         msg.setInformativeText(info_text);
427         msg.setStandardButtons(QMessageBox::Ok);
428         msg.setIcon(QMessageBox::Warning);
429         msg.exec();
430 }
431
432 void MainWindow::on_actionOpen_triggered()
433 {
434         QSettings settings;
435         const QString dir = settings.value(SettingOpenDirectory).toString();
436
437         // Show the dialog
438         const QString file_name = QFileDialog::getOpenFileName(
439                 this, tr("Open File"), dir, tr(
440                         "Sigrok Sessions (*.sr);;"
441                         "All Files (*.*)"));
442
443         if (!file_name.isEmpty()) {
444                 load_file(file_name);
445
446                 const QString abs_path = QFileInfo(file_name).absolutePath();
447                 settings.setValue(SettingOpenDirectory, abs_path);
448         }
449 }
450
451 void MainWindow::on_actionSaveAs_triggered()
452 {
453         using pv::dialogs::StoreProgress;
454
455         // Stop any currently running capture session
456         _session.stop_capture();
457
458         QSettings settings;
459         const QString dir = settings.value(SettingSaveDirectory).toString();
460
461         // Show the dialog
462         const QString file_name = QFileDialog::getSaveFileName(
463                 this, tr("Save File"), dir, tr("Sigrok Sessions (*.sr)"));
464
465         if (file_name.isEmpty())
466                 return;
467
468         const QString abs_path = QFileInfo(file_name).absolutePath();
469         settings.setValue(SettingSaveDirectory, abs_path);
470
471         StoreProgress *dlg = new StoreProgress(file_name, _session, this);
472         dlg->run();
473 }
474
475 void MainWindow::on_actionConnect_triggered()
476 {
477         // Stop any currently running capture session
478         _session.stop_capture();
479
480         dialogs::Connect dlg(this, _device_manager);
481
482         // If the user selected a device, select it in the device list. Select the
483         // current device otherwise.
484         if (dlg.exec())
485                 _session.set_device(dlg.get_selected_device());
486
487         update_device_list();
488 }
489
490 void MainWindow::on_actionQuit_triggered()
491 {
492         close();
493 }
494
495 void MainWindow::on_actionViewZoomIn_triggered()
496 {
497         _view->zoom(1);
498 }
499
500 void MainWindow::on_actionViewZoomOut_triggered()
501 {
502         _view->zoom(-1);
503 }
504
505 void MainWindow::on_actionViewZoomFit_triggered()
506 {
507         _view->zoom_fit();
508 }
509
510 void MainWindow::on_actionViewZoomOneToOne_triggered()
511 {
512         _view->zoom_one_to_one();
513 }
514
515 void MainWindow::on_actionViewShowCursors_triggered()
516 {
517         assert(_view);
518
519         const bool show = !_view->cursors_shown();
520         if(show)
521                 _view->centre_cursors();
522
523         _view->show_cursors(show);
524 }
525
526 void MainWindow::on_actionAbout_triggered()
527 {
528         dialogs::About dlg(_device_manager.context(), this);
529         dlg.exec();
530 }
531
532 void MainWindow::add_decoder(srd_decoder *decoder)
533 {
534 #ifdef ENABLE_DECODE
535         assert(decoder);
536         _session.add_decoder(decoder);
537 #else
538         (void)decoder;
539 #endif
540 }
541
542 void MainWindow::run_stop()
543 {
544         switch(_session.get_capture_state()) {
545         case SigSession::Stopped:
546                 _session.start_capture([&](QString message) {
547                         session_error("Capture failed", message); });
548                 break;
549
550         case SigSession::AwaitingTrigger:
551         case SigSession::Running:
552                 _session.stop_capture();
553                 break;
554         }
555 }
556
557 void MainWindow::capture_state_changed(int state)
558 {
559         _sampling_bar->set_capture_state((pv::SigSession::capture_state)state);
560 }
561
562 } // namespace pv