StoreSession: Use DeviceManager to get context
[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 <boost/algorithm/string/join.hpp>
31
32 #include <QAction>
33 #include <QApplication>
34 #include <QButtonGroup>
35 #include <QCloseEvent>
36 #include <QFileDialog>
37 #include <QMessageBox>
38 #include <QMenu>
39 #include <QMenuBar>
40 #include <QSettings>
41 #include <QStatusBar>
42 #include <QVBoxLayout>
43 #include <QWidget>
44
45 #include "mainwindow.hpp"
46
47 #include "devicemanager.hpp"
48 #include "dialogs/about.hpp"
49 #include "dialogs/connect.hpp"
50 #include "dialogs/inputoutputoptions.hpp"
51 #include "dialogs/storeprogress.hpp"
52 #include "toolbars/mainbar.hpp"
53 #include "view/logicsignal.hpp"
54 #include "view/view.hpp"
55 #include "widgets/exportmenu.hpp"
56 #ifdef ENABLE_DECODE
57 #include "widgets/decodermenu.hpp"
58 #endif
59 #include "widgets/hidingmenubar.hpp"
60
61 #include <inttypes.h>
62 #include <stdint.h>
63 #include <stdarg.h>
64 #include <glib.h>
65 #include <libsigrokcxx/libsigrokcxx.hpp>
66
67 using std::list;
68 using std::map;
69 using std::shared_ptr;
70 using std::string;
71 using std::vector;
72
73 using boost::algorithm::join;
74
75 using sigrok::Device;
76 using sigrok::Error;
77 using sigrok::HardwareDevice;
78 using sigrok::OutputFormat;
79
80 namespace pv {
81
82 namespace view {
83 class ViewItem;
84 }
85
86 const char *MainWindow::SettingOpenDirectory = "MainWindow/OpenDirectory";
87 const char *MainWindow::SettingSaveDirectory = "MainWindow/SaveDirectory";
88
89 MainWindow::MainWindow(DeviceManager &device_manager,
90         const char *open_file_name,
91         QWidget *parent) :
92         QMainWindow(parent),
93         device_manager_(device_manager),
94         session_(device_manager),
95         action_open_(new QAction(this)),
96         action_save_as_(new QAction(this)),
97         action_connect_(new QAction(this)),
98         action_quit_(new QAction(this)),
99         action_view_zoom_in_(new QAction(this)),
100         action_view_zoom_out_(new QAction(this)),
101         action_view_zoom_fit_(new QAction(this)),
102         action_view_zoom_one_to_one_(new QAction(this)),
103         action_view_show_cursors_(new QAction(this)),
104         action_about_(new QAction(this))
105 #ifdef ENABLE_DECODE
106         , menu_decoders_add_(new pv::widgets::DecoderMenu(this, true))
107 #endif
108 {
109         setup_ui();
110         restore_ui_settings();
111         if (open_file_name) {
112                 const QString s(QString::fromUtf8(open_file_name));
113                 QMetaObject::invokeMethod(this, "load_file",
114                         Qt::QueuedConnection,
115                         Q_ARG(QString, s));
116         }
117 }
118
119 QAction* MainWindow::action_open() const
120 {
121         return action_open_;
122 }
123
124 QAction* MainWindow::action_save_as() const
125 {
126         return action_save_as_;
127 }
128
129 QAction* MainWindow::action_connect() const
130 {
131         return action_connect_;
132 }
133
134 QAction* MainWindow::action_quit() const
135 {
136         return action_quit_;
137 }
138
139 QAction* MainWindow::action_view_zoom_in() const
140 {
141         return action_view_zoom_in_;
142 }
143
144 QAction* MainWindow::action_view_zoom_out() const
145 {
146         return action_view_zoom_out_;
147 }
148
149 QAction* MainWindow::action_view_zoom_fit() const
150 {
151         return action_view_zoom_fit_;
152 }
153
154 QAction* MainWindow::action_view_zoom_one_to_one() const
155 {
156         return action_view_zoom_one_to_one_;
157 }
158
159 QAction* MainWindow::action_view_show_cursors() const
160 {
161         return action_view_show_cursors_;
162 }
163
164 QAction* MainWindow::action_about() const
165 {
166         return action_about_;
167 }
168
169 #ifdef ENABLE_DECODE
170 QMenu* MainWindow::menu_decoder_add() const
171 {
172         return menu_decoders_add_;
173 }
174 #endif
175
176 void MainWindow::run_stop()
177 {
178         switch(session_.get_capture_state()) {
179         case Session::Stopped:
180                 session_.start_capture([&](QString message) {
181                         session_error("Capture failed", message); });
182                 break;
183
184         case Session::AwaitingTrigger:
185         case Session::Running:
186                 session_.stop_capture();
187                 break;
188         }
189 }
190
191 void MainWindow::select_device(shared_ptr<Device> device)
192 {
193         try {
194                 session_.set_device(device);
195         } catch(const QString &e) {
196                 QMessageBox msg(this);
197                 msg.setText(e);
198                 msg.setInformativeText(tr("Failed to Select Device"));
199                 msg.setStandardButtons(QMessageBox::Ok);
200                 msg.setIcon(QMessageBox::Warning);
201                 msg.exec();
202         }
203 }
204
205 void MainWindow::export_file(shared_ptr<OutputFormat> format)
206 {
207         using pv::dialogs::StoreProgress;
208
209         // Stop any currently running capture session
210         session_.stop_capture();
211
212         QSettings settings;
213         const QString dir = settings.value(SettingSaveDirectory).toString();
214
215         // Construct the filter
216         const vector<string> exts = format->extensions();
217         QString filter = tr("%1 files ").arg(
218                 QString::fromStdString(format->description()));
219
220         if (exts.empty())
221                 filter += "(*.*)";
222         else
223                 filter += QString("(*.%1);;%2 (*.*)").arg(
224                         QString::fromStdString(join(exts, ", *."))).arg(
225                         tr("All Files"));
226
227         // Show the file dialog
228         const QString file_name = QFileDialog::getSaveFileName(
229                 this, tr("Save File"), dir, filter);
230
231         if (file_name.isEmpty())
232                 return;
233
234         const QString abs_path = QFileInfo(file_name).absolutePath();
235         settings.setValue(SettingSaveDirectory, abs_path);
236
237         // Show the options dialog
238         map<string, Glib::VariantBase> options;
239         if (!format->options().empty()) {
240                 dialogs::InputOutputOptions dlg(
241                         tr("Export %1").arg(QString::fromStdString(
242                                 format->description())),
243                         format->options(), this);
244                 if (!dlg.exec())
245                         return;
246                 options = dlg.options();
247         }
248
249         StoreProgress *dlg = new StoreProgress(file_name, format, options,
250                 session_, this);
251         dlg->run();
252 }
253
254 void MainWindow::setup_ui()
255 {
256         setObjectName(QString::fromUtf8("MainWindow"));
257
258         // Set the window icon
259         QIcon icon;
260         icon.addFile(QString(":/icons/sigrok-logo-notext.svg"));
261         setWindowIcon(icon);
262
263         // Setup the central widget
264         central_widget_ = new QWidget(this);
265         vertical_layout_ = new QVBoxLayout(central_widget_);
266         vertical_layout_->setSpacing(6);
267         vertical_layout_->setContentsMargins(0, 0, 0, 0);
268         setCentralWidget(central_widget_);
269
270         view_ = new pv::view::View(session_, this);
271
272         vertical_layout_->addWidget(view_);
273
274         // Setup the menu bar
275         pv::widgets::HidingMenuBar *const menu_bar =
276                 new pv::widgets::HidingMenuBar(this);
277
278         // File Menu
279         QMenu *const menu_file = new QMenu;
280         menu_file->setTitle(tr("&File"));
281
282         action_open_->setText(tr("&Open..."));
283         action_open_->setIcon(QIcon::fromTheme("document-open",
284                 QIcon(":/icons/document-open.png")));
285         action_open_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O));
286         action_open_->setObjectName(QString::fromUtf8("actionOpen"));
287         menu_file->addAction(action_open_);
288
289         action_save_as_->setText(tr("&Save As..."));
290         action_save_as_->setIcon(QIcon::fromTheme("document-save-as",
291                 QIcon(":/icons/document-save-as.png")));
292         action_save_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
293         action_save_as_->setObjectName(QString::fromUtf8("actionSaveAs"));
294         menu_file->addAction(action_save_as_);
295
296         menu_file->addSeparator();
297
298         widgets::ExportMenu *menu_file_export = new widgets::ExportMenu(this,
299                 device_manager_.context());
300         menu_file_export->setTitle(tr("&Export"));
301         connect(menu_file_export,
302                 SIGNAL(format_selected(std::shared_ptr<sigrok::OutputFormat>)),
303                 this, SLOT(export_file(std::shared_ptr<sigrok::OutputFormat>)));
304         menu_file->addAction(menu_file_export->menuAction());
305
306         menu_file->addSeparator();
307
308         action_connect_->setText(tr("&Connect to Device..."));
309         action_connect_->setObjectName(QString::fromUtf8("actionConnect"));
310         menu_file->addAction(action_connect_);
311
312         menu_file->addSeparator();
313
314         action_quit_->setText(tr("&Quit"));
315         action_quit_->setIcon(QIcon::fromTheme("application-exit",
316                 QIcon(":/icons/application-exit.png")));
317         action_quit_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
318         action_quit_->setObjectName(QString::fromUtf8("actionQuit"));
319         menu_file->addAction(action_quit_);
320
321         // View Menu
322         QMenu *menu_view = new QMenu;
323         menu_view->setTitle(tr("&View"));
324
325         action_view_zoom_in_->setText(tr("Zoom &In"));
326         action_view_zoom_in_->setIcon(QIcon::fromTheme("zoom-in",
327                 QIcon(":/icons/zoom-in.png")));
328         // simply using Qt::Key_Plus shows no + in the menu
329         action_view_zoom_in_->setShortcut(QKeySequence::ZoomIn);
330         action_view_zoom_in_->setObjectName(
331                 QString::fromUtf8("actionViewZoomIn"));
332         menu_view->addAction(action_view_zoom_in_);
333
334         action_view_zoom_out_->setText(tr("Zoom &Out"));
335         action_view_zoom_out_->setIcon(QIcon::fromTheme("zoom-out",
336                 QIcon(":/icons/zoom-out.png")));
337         action_view_zoom_out_->setShortcut(QKeySequence::ZoomOut);
338         action_view_zoom_out_->setObjectName(
339                 QString::fromUtf8("actionViewZoomOut"));
340         menu_view->addAction(action_view_zoom_out_);
341
342         action_view_zoom_fit_->setText(tr("Zoom to &Fit"));
343         action_view_zoom_fit_->setIcon(QIcon::fromTheme("zoom-fit",
344                 QIcon(":/icons/zoom-fit.png")));
345         action_view_zoom_fit_->setShortcut(QKeySequence(Qt::Key_F));
346         action_view_zoom_fit_->setObjectName(
347                 QString::fromUtf8("actionViewZoomFit"));
348         menu_view->addAction(action_view_zoom_fit_);
349
350         action_view_zoom_one_to_one_->setText(tr("Zoom to O&ne-to-One"));
351         action_view_zoom_one_to_one_->setIcon(QIcon::fromTheme("zoom-original",
352                 QIcon(":/icons/zoom-original.png")));
353         action_view_zoom_one_to_one_->setShortcut(QKeySequence(Qt::Key_O));
354         action_view_zoom_one_to_one_->setObjectName(
355                 QString::fromUtf8("actionViewZoomOneToOne"));
356         menu_view->addAction(action_view_zoom_one_to_one_);
357
358         menu_view->addSeparator();
359
360         action_view_show_cursors_->setCheckable(true);
361         action_view_show_cursors_->setChecked(view_->cursors_shown());
362         action_view_show_cursors_->setIcon(QIcon::fromTheme("show-cursors",
363                 QIcon(":/icons/show-cursors.svg")));
364         action_view_show_cursors_->setShortcut(QKeySequence(Qt::Key_C));
365         action_view_show_cursors_->setObjectName(
366                 QString::fromUtf8("actionViewShowCursors"));
367         action_view_show_cursors_->setText(tr("Show &Cursors"));
368         menu_view->addAction(action_view_show_cursors_);
369
370         // Decoders Menu
371 #ifdef ENABLE_DECODE
372         QMenu *const menu_decoders = new QMenu;
373         menu_decoders->setTitle(tr("&Decoders"));
374
375         menu_decoders_add_->setTitle(tr("&Add"));
376         connect(menu_decoders_add_, SIGNAL(decoder_selected(srd_decoder*)),
377                 this, SLOT(add_decoder(srd_decoder*)));
378
379         menu_decoders->addMenu(menu_decoders_add_);
380 #endif
381
382         // Help Menu
383         QMenu *const menu_help = new QMenu;
384         menu_help->setTitle(tr("&Help"));
385
386         action_about_->setObjectName(QString::fromUtf8("actionAbout"));
387         action_about_->setText(tr("&About..."));
388         menu_help->addAction(action_about_);
389
390         menu_bar->addAction(menu_file->menuAction());
391         menu_bar->addAction(menu_view->menuAction());
392 #ifdef ENABLE_DECODE
393         menu_bar->addAction(menu_decoders->menuAction());
394 #endif
395         menu_bar->addAction(menu_help->menuAction());
396
397         setMenuBar(menu_bar);
398         QMetaObject::connectSlotsByName(this);
399
400         // Setup the toolbar
401         main_bar_ = new toolbars::MainBar(session_, *this);
402
403         // Populate the device list and select the initially selected device
404         update_device_list();
405
406         addToolBar(main_bar_);
407
408         // Set the title
409         setWindowTitle(tr("PulseView"));
410
411         // Setup session_ events
412         connect(&session_, SIGNAL(capture_state_changed(int)), this,
413                 SLOT(capture_state_changed(int)));
414         connect(&session_, SIGNAL(device_selected()), this,
415                 SLOT(device_selected()));
416 }
417
418 void MainWindow::save_ui_settings()
419 {
420         QSettings settings;
421
422         map<string, string> dev_info;
423         list<string> key_list;
424
425         settings.beginGroup("MainWindow");
426         settings.setValue("state", saveState());
427         settings.setValue("geometry", saveGeometry());
428         settings.endGroup();
429
430         if (session_.device()) {
431                 settings.beginGroup("Device");
432                 key_list.push_back("vendor");
433                 key_list.push_back("model");
434                 key_list.push_back("version");
435                 key_list.push_back("serial_num");
436                 key_list.push_back("connection_id");
437
438                 dev_info = device_manager_.get_device_info(
439                         session_.device());
440
441                 for (string key : key_list) {
442
443                         if (dev_info.count(key))
444                                 settings.setValue(QString::fromUtf8(key.c_str()),
445                                                 QString::fromUtf8(dev_info.at(key).c_str()));
446                         else
447                                 settings.remove(QString::fromUtf8(key.c_str()));
448                 }
449
450                 settings.endGroup();
451         }
452 }
453
454 void MainWindow::restore_ui_settings()
455 {
456         QSettings settings;
457
458         shared_ptr<HardwareDevice> device;
459
460         map<string, string> dev_info;
461         list<string> key_list;
462         string value;
463
464         settings.beginGroup("MainWindow");
465
466         if (settings.contains("geometry")) {
467                 restoreGeometry(settings.value("geometry").toByteArray());
468                 restoreState(settings.value("state").toByteArray());
469         } else
470                 resize(1000, 720);
471
472         settings.endGroup();
473
474         // Re-select last used device if possible.
475         settings.beginGroup("Device");
476         key_list.push_back("vendor");
477         key_list.push_back("model");
478         key_list.push_back("version");
479         key_list.push_back("serial_num");
480         key_list.push_back("connection_id");
481
482         for (string key : key_list) {
483                 if (!settings.contains(QString::fromUtf8(key.c_str())))
484                         continue;
485
486                 value = settings.value(QString::fromUtf8(key.c_str())).toString().toStdString();
487
488                 if (value.size() > 0)
489                         dev_info.insert(std::make_pair(key, value));
490         }
491
492         device = device_manager_.find_device_from_info(dev_info);
493
494         if (device) {
495                 select_device(device);
496                 update_device_list();
497         }
498
499         settings.endGroup();
500 }
501
502 void MainWindow::session_error(
503         const QString text, const QString info_text)
504 {
505         QMetaObject::invokeMethod(this, "show_session_error",
506                 Qt::QueuedConnection, Q_ARG(QString, text),
507                 Q_ARG(QString, info_text));
508 }
509
510 void MainWindow::update_device_list()
511 {
512         main_bar_->update_device_list();
513 }
514
515 void MainWindow::closeEvent(QCloseEvent *event)
516 {
517         save_ui_settings();
518         event->accept();
519 }
520
521 void MainWindow::keyReleaseEvent(QKeyEvent *event)
522 {
523         if (event->key() == Qt::Key_Alt) {
524                 menuBar()->setHidden(!menuBar()->isHidden());
525                 menuBar()->setFocus();
526         }
527         QMainWindow::keyReleaseEvent(event);
528 }
529
530 void MainWindow::load_file(QString file_name)
531 {
532         const QString errorMessage(
533                 QString("Failed to load file %1").arg(file_name));
534         const QString infoMessage;
535
536         try {
537                 session_.set_session_file(file_name.toStdString());
538         } catch(Error e) {
539                 show_session_error(tr("Failed to load ") + file_name, e.what());
540                 session_.set_default_device();
541                 update_device_list();
542                 return;
543         }
544
545         update_device_list();
546
547         session_.start_capture([&, errorMessage, infoMessage](QString) {
548                 session_error(errorMessage, infoMessage); });
549 }
550
551 void MainWindow::show_session_error(
552         const QString text, const QString info_text)
553 {
554         QMessageBox msg(this);
555         msg.setText(text);
556         msg.setInformativeText(info_text);
557         msg.setStandardButtons(QMessageBox::Ok);
558         msg.setIcon(QMessageBox::Warning);
559         msg.exec();
560 }
561
562 void MainWindow::on_actionOpen_triggered()
563 {
564         QSettings settings;
565         const QString dir = settings.value(SettingOpenDirectory).toString();
566
567         // Show the dialog
568         const QString file_name = QFileDialog::getOpenFileName(
569                 this, tr("Open File"), dir, tr(
570                         "Sigrok Sessions (*.sr);;"
571                         "All Files (*.*)"));
572
573         if (!file_name.isEmpty()) {
574                 load_file(file_name);
575
576                 const QString abs_path = QFileInfo(file_name).absolutePath();
577                 settings.setValue(SettingOpenDirectory, abs_path);
578         }
579 }
580
581 void MainWindow::on_actionSaveAs_triggered()
582 {
583         export_file(device_manager_.context()->output_formats()["srzip"]);
584 }
585
586 void MainWindow::on_actionConnect_triggered()
587 {
588         // Stop any currently running capture session
589         session_.stop_capture();
590
591         dialogs::Connect dlg(this, device_manager_);
592
593         // If the user selected a device, select it in the device list. Select the
594         // current device otherwise.
595         if (dlg.exec())
596                 select_device(dlg.get_selected_device());
597
598         update_device_list();
599 }
600
601 void MainWindow::on_actionQuit_triggered()
602 {
603         close();
604 }
605
606 void MainWindow::on_actionViewZoomIn_triggered()
607 {
608         view_->zoom(1);
609 }
610
611 void MainWindow::on_actionViewZoomOut_triggered()
612 {
613         view_->zoom(-1);
614 }
615
616 void MainWindow::on_actionViewZoomFit_triggered()
617 {
618         view_->zoom_fit();
619 }
620
621 void MainWindow::on_actionViewZoomOneToOne_triggered()
622 {
623         view_->zoom_one_to_one();
624 }
625
626 void MainWindow::on_actionViewShowCursors_triggered()
627 {
628         assert(view_);
629
630         const bool show = !view_->cursors_shown();
631         if(show)
632                 view_->centre_cursors();
633
634         view_->show_cursors(show);
635 }
636
637 void MainWindow::on_actionAbout_triggered()
638 {
639         dialogs::About dlg(device_manager_.context(), this);
640         dlg.exec();
641 }
642
643 void MainWindow::add_decoder(srd_decoder *decoder)
644 {
645 #ifdef ENABLE_DECODE
646         assert(decoder);
647         session_.add_decoder(decoder);
648 #else
649         (void)decoder;
650 #endif
651 }
652
653 void MainWindow::capture_state_changed(int state)
654 {
655         main_bar_->set_capture_state((pv::Session::capture_state)state);
656 }
657
658 void MainWindow::device_selected()
659 {
660         // Set the title to include the device/file name
661         const shared_ptr<sigrok::Device> device = session_.device();
662         if (!device)
663                 return;
664
665         const string display_name = device_manager_.get_display_name(device);
666         setWindowTitle(tr("%1 - PulseView").arg(display_name.c_str()));
667 }
668
669 } // namespace pv