]> sigrok.org Git - pulseview.git/blob - pv/mainwindow.cpp
2558cb07692fe497e87d262fad574bc81ad70bfd
[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 "util.hpp"
49 #include "data/segment.hpp"
50 #include "devices/hardwaredevice.hpp"
51 #include "devices/inputfile.hpp"
52 #include "devices/sessionfile.hpp"
53 #include "dialogs/about.hpp"
54 #include "dialogs/connect.hpp"
55 #include "dialogs/inputoutputoptions.hpp"
56 #include "dialogs/storeprogress.hpp"
57 #include "toolbars/mainbar.hpp"
58 #include "view/logicsignal.hpp"
59 #include "view/view.hpp"
60 #include "widgets/exportmenu.hpp"
61 #include "widgets/importmenu.hpp"
62 #ifdef ENABLE_DECODE
63 #include "widgets/decodermenu.hpp"
64 #endif
65 #include "widgets/hidingmenubar.hpp"
66
67 #include <inttypes.h>
68 #include <stdint.h>
69 #include <stdarg.h>
70 #include <glib.h>
71 #include <libsigrokcxx/libsigrokcxx.hpp>
72
73 using std::cerr;
74 using std::endl;
75 using std::list;
76 using std::map;
77 using std::max;
78 using std::pair;
79 using std::shared_ptr;
80 using std::string;
81 using std::vector;
82
83 using boost::algorithm::join;
84
85 using sigrok::Error;
86 using sigrok::OutputFormat;
87 using sigrok::InputFormat;
88
89 namespace pv {
90
91 namespace view {
92 class ViewItem;
93 }
94
95 const char *MainWindow::SettingOpenDirectory = "MainWindow/OpenDirectory";
96 const char *MainWindow::SettingSaveDirectory = "MainWindow/SaveDirectory";
97
98 MainWindow::MainWindow(DeviceManager &device_manager,
99         string open_file_name, string open_file_format,
100         QWidget *parent) :
101         QMainWindow(parent),
102         device_manager_(device_manager),
103         session_(device_manager),
104         action_open_(new QAction(this)),
105         action_save_as_(new QAction(this)),
106         action_save_selection_as_(new QAction(this)),
107         action_connect_(new QAction(this)),
108         action_quit_(new QAction(this)),
109         action_view_zoom_in_(new QAction(this)),
110         action_view_zoom_out_(new QAction(this)),
111         action_view_zoom_fit_(new QAction(this)),
112         action_view_zoom_one_to_one_(new QAction(this)),
113         action_view_sticky_scrolling_(new QAction(this)),
114         action_view_coloured_bg_(new QAction(this)),
115         action_view_show_cursors_(new QAction(this)),
116         action_about_(new QAction(this))
117 #ifdef ENABLE_DECODE
118         , menu_decoders_add_(new pv::widgets::DecoderMenu(this, true))
119 #endif
120 {
121         qRegisterMetaType<util::Timestamp>("util::Timestamp");
122
123         setup_ui();
124         restore_ui_settings();
125         if (open_file_name.empty())
126                 select_init_device();
127         else
128                 load_init_file(open_file_name, open_file_format);
129 }
130
131 QAction* MainWindow::action_open() const
132 {
133         return action_open_;
134 }
135
136 QAction* MainWindow::action_save_as() const
137 {
138         return action_save_as_;
139 }
140
141 QAction* MainWindow::action_save_selection_as() const
142 {
143         return action_save_selection_as_;
144 }
145
146 QAction* MainWindow::action_connect() const
147 {
148         return action_connect_;
149 }
150
151 QAction* MainWindow::action_quit() const
152 {
153         return action_quit_;
154 }
155
156 QAction* MainWindow::action_view_zoom_in() const
157 {
158         return action_view_zoom_in_;
159 }
160
161 QAction* MainWindow::action_view_zoom_out() const
162 {
163         return action_view_zoom_out_;
164 }
165
166 QAction* MainWindow::action_view_zoom_fit() const
167 {
168         return action_view_zoom_fit_;
169 }
170
171 QAction* MainWindow::action_view_zoom_one_to_one() const
172 {
173         return action_view_zoom_one_to_one_;
174 }
175
176 QAction* MainWindow::action_view_sticky_scrolling() const
177 {
178         return action_view_sticky_scrolling_;
179 }
180
181 QAction* MainWindow::action_view_coloured_bg() const
182 {
183         return action_view_coloured_bg_;
184 }
185
186 QAction* MainWindow::action_view_show_cursors() const
187 {
188         return action_view_show_cursors_;
189 }
190
191 QAction* MainWindow::action_about() const
192 {
193         return action_about_;
194 }
195
196 #ifdef ENABLE_DECODE
197 QMenu* MainWindow::menu_decoder_add() const
198 {
199         return menu_decoders_add_;
200 }
201 #endif
202
203 void MainWindow::run_stop()
204 {
205         switch (session_.get_capture_state()) {
206         case Session::Stopped:
207                 session_.start_capture([&](QString message) {
208                         session_error("Capture failed", message); });
209                 break;
210         case Session::AwaitingTrigger:
211         case Session::Running:
212                 session_.stop_capture();
213                 break;
214         }
215 }
216
217 void MainWindow::select_device(shared_ptr<devices::Device> device)
218 {
219         try {
220                 if (device)
221                         session_.set_device(device);
222                 else
223                         session_.set_default_device();
224         } catch (const QString &e) {
225                 QMessageBox msg(this);
226                 msg.setText(e);
227                 msg.setInformativeText(tr("Failed to Select Device"));
228                 msg.setStandardButtons(QMessageBox::Ok);
229                 msg.setIcon(QMessageBox::Warning);
230                 msg.exec();
231         }
232 }
233
234 void MainWindow::export_file(shared_ptr<OutputFormat> format,
235         bool selection_only)
236 {
237         using pv::dialogs::StoreProgress;
238
239         // Stop any currently running capture session
240         session_.stop_capture();
241
242         QSettings settings;
243         const QString dir = settings.value(SettingSaveDirectory).toString();
244
245         std::pair<uint64_t, uint64_t> sample_range;
246
247         // Selection only? Verify that the cursors are active and fetch their values
248         if (selection_only) {
249                 if (!view_->cursors()->enabled()) {
250                         show_session_error(tr("Missing Cursors"), tr("You need to set the " \
251                                         "cursors before you can save the data enclosed by them " \
252                                         "to a session file (e.g. using ALT-V - Show Cursors)."));
253                         return;
254                 }
255
256                 const double samplerate = session_.get_samplerate();
257
258                 const pv::util::Timestamp& start_time = view_->cursors()->first()->time();
259                 const pv::util::Timestamp& end_time = view_->cursors()->second()->time();
260
261                 const uint64_t start_sample =
262                         std::max((double)0, start_time.convert_to<double>() * samplerate);
263                 const uint64_t end_sample = end_time.convert_to<double>() * samplerate;
264
265                 sample_range = std::make_pair(start_sample, end_sample);
266         } else {
267                 sample_range = std::make_pair(0, 0);
268         }
269
270         // Construct the filter
271         const vector<string> exts = format->extensions();
272         QString filter = tr("%1 files ").arg(
273                 QString::fromStdString(format->description()));
274
275         if (exts.empty())
276                 filter += "(*.*)";
277         else
278                 filter += QString("(*.%1);;%2 (*.*)").arg(
279                         QString::fromStdString(join(exts, ", *.")),
280                         tr("All Files"));
281
282         // Show the file dialog
283         const QString file_name = QFileDialog::getSaveFileName(
284                 this, tr("Save File"), dir, filter);
285
286         if (file_name.isEmpty())
287                 return;
288
289         const QString abs_path = QFileInfo(file_name).absolutePath();
290         settings.setValue(SettingSaveDirectory, abs_path);
291
292         // Show the options dialog
293         map<string, Glib::VariantBase> options;
294         if (!format->options().empty()) {
295                 dialogs::InputOutputOptions dlg(
296                         tr("Export %1").arg(QString::fromStdString(
297                                 format->description())),
298                         format->options(), this);
299                 if (!dlg.exec())
300                         return;
301                 options = dlg.options();
302         }
303
304         StoreProgress *dlg = new StoreProgress(file_name, format, options,
305                 sample_range, session_, this);
306         dlg->run();
307 }
308
309 void MainWindow::import_file(shared_ptr<InputFormat> format)
310 {
311         assert(format);
312
313         QSettings settings;
314         const QString dir = settings.value(SettingOpenDirectory).toString();
315
316         // Construct the filter
317         const vector<string> exts = format->extensions();
318         const QString filter = exts.empty() ? "" :
319                 tr("%1 files (*.%2)").arg(
320                         QString::fromStdString(format->description()),
321                         QString::fromStdString(join(exts, ", *.")));
322
323         // Show the file dialog
324         const QString file_name = QFileDialog::getOpenFileName(
325                 this, tr("Import File"), dir, tr(
326                         "%1 files (*.*);;All Files (*.*)").arg(
327                         QString::fromStdString(format->description())));
328
329         if (file_name.isEmpty())
330                 return;
331
332         // Show the options dialog
333         map<string, Glib::VariantBase> options;
334         if (!format->options().empty()) {
335                 dialogs::InputOutputOptions dlg(
336                         tr("Import %1").arg(QString::fromStdString(
337                                 format->description())),
338                         format->options(), this);
339                 if (!dlg.exec())
340                         return;
341                 options = dlg.options();
342         }
343
344         load_file(file_name, format, options);
345
346         const QString abs_path = QFileInfo(file_name).absolutePath();
347         settings.setValue(SettingOpenDirectory, abs_path);
348 }
349
350 void MainWindow::setup_ui()
351 {
352         setObjectName(QString::fromUtf8("MainWindow"));
353
354         // Set the window icon
355         QIcon icon;
356         icon.addFile(QString(":/icons/sigrok-logo-notext.svg"));
357         setWindowIcon(icon);
358
359         // Setup the central widget
360         central_widget_ = new QWidget(this);
361         vertical_layout_ = new QVBoxLayout(central_widget_);
362         vertical_layout_->setSpacing(6);
363         vertical_layout_->setContentsMargins(0, 0, 0, 0);
364         setCentralWidget(central_widget_);
365
366         view_ = new pv::view::View(session_, this);
367
368         vertical_layout_->addWidget(view_);
369
370         // Setup the menu bar
371         pv::widgets::HidingMenuBar *const menu_bar =
372                 new pv::widgets::HidingMenuBar(this);
373
374         // File Menu
375         QMenu *const menu_file = new QMenu;
376         menu_file->setTitle(tr("&File"));
377
378         action_open_->setText(tr("&Open..."));
379         action_open_->setIcon(QIcon::fromTheme("document-open",
380                 QIcon(":/icons/document-open.png")));
381         action_open_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O));
382         action_open_->setObjectName(QString::fromUtf8("actionOpen"));
383         menu_file->addAction(action_open_);
384
385         action_save_as_->setText(tr("&Save As..."));
386         action_save_as_->setIcon(QIcon::fromTheme("document-save-as",
387                 QIcon(":/icons/document-save-as.png")));
388         action_save_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
389         action_save_as_->setObjectName(QString::fromUtf8("actionSaveAs"));
390         menu_file->addAction(action_save_as_);
391
392         action_save_selection_as_->setText(tr("Save Selected &Range As..."));
393         action_save_selection_as_->setIcon(QIcon::fromTheme("document-save-as",
394                 QIcon(":/icons/document-save-as.png")));
395         action_save_selection_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
396         action_save_selection_as_->setObjectName(QString::fromUtf8("actionSaveSelectionAs"));
397         menu_file->addAction(action_save_selection_as_);
398
399         menu_file->addSeparator();
400
401         widgets::ExportMenu *menu_file_export = new widgets::ExportMenu(this,
402                 device_manager_.context());
403         menu_file_export->setTitle(tr("&Export"));
404         connect(menu_file_export,
405                 SIGNAL(format_selected(std::shared_ptr<sigrok::OutputFormat>)),
406                 this, SLOT(export_file(std::shared_ptr<sigrok::OutputFormat>)));
407         menu_file->addAction(menu_file_export->menuAction());
408
409         widgets::ImportMenu *menu_file_import = new widgets::ImportMenu(this,
410                 device_manager_.context());
411         menu_file_import->setTitle(tr("&Import"));
412         connect(menu_file_import,
413                 SIGNAL(format_selected(std::shared_ptr<sigrok::InputFormat>)),
414                 this, SLOT(import_file(std::shared_ptr<sigrok::InputFormat>)));
415         menu_file->addAction(menu_file_import->menuAction());
416
417         menu_file->addSeparator();
418
419         action_connect_->setText(tr("&Connect to Device..."));
420         action_connect_->setObjectName(QString::fromUtf8("actionConnect"));
421         menu_file->addAction(action_connect_);
422
423         menu_file->addSeparator();
424
425         action_quit_->setText(tr("&Quit"));
426         action_quit_->setIcon(QIcon::fromTheme("application-exit",
427                 QIcon(":/icons/application-exit.png")));
428         action_quit_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
429         action_quit_->setObjectName(QString::fromUtf8("actionQuit"));
430         menu_file->addAction(action_quit_);
431
432         // View Menu
433         QMenu *menu_view = new QMenu;
434         menu_view->setTitle(tr("&View"));
435
436         action_view_zoom_in_->setText(tr("Zoom &In"));
437         action_view_zoom_in_->setIcon(QIcon::fromTheme("zoom-in",
438                 QIcon(":/icons/zoom-in.png")));
439         // simply using Qt::Key_Plus shows no + in the menu
440         action_view_zoom_in_->setShortcut(QKeySequence::ZoomIn);
441         action_view_zoom_in_->setObjectName(
442                 QString::fromUtf8("actionViewZoomIn"));
443         menu_view->addAction(action_view_zoom_in_);
444
445         action_view_zoom_out_->setText(tr("Zoom &Out"));
446         action_view_zoom_out_->setIcon(QIcon::fromTheme("zoom-out",
447                 QIcon(":/icons/zoom-out.png")));
448         action_view_zoom_out_->setShortcut(QKeySequence::ZoomOut);
449         action_view_zoom_out_->setObjectName(
450                 QString::fromUtf8("actionViewZoomOut"));
451         menu_view->addAction(action_view_zoom_out_);
452
453         action_view_zoom_fit_->setCheckable(true);
454         action_view_zoom_fit_->setText(tr("Zoom to &Fit"));
455         action_view_zoom_fit_->setIcon(QIcon::fromTheme("zoom-fit",
456                 QIcon(":/icons/zoom-fit.png")));
457         action_view_zoom_fit_->setShortcut(QKeySequence(Qt::Key_F));
458         action_view_zoom_fit_->setObjectName(
459                 QString::fromUtf8("actionViewZoomFit"));
460         menu_view->addAction(action_view_zoom_fit_);
461
462         action_view_zoom_one_to_one_->setText(tr("Zoom to O&ne-to-One"));
463         action_view_zoom_one_to_one_->setIcon(QIcon::fromTheme("zoom-original",
464                 QIcon(":/icons/zoom-original.png")));
465         action_view_zoom_one_to_one_->setShortcut(QKeySequence(Qt::Key_O));
466         action_view_zoom_one_to_one_->setObjectName(
467                 QString::fromUtf8("actionViewZoomOneToOne"));
468         menu_view->addAction(action_view_zoom_one_to_one_);
469
470         menu_view->addSeparator();
471
472         action_view_sticky_scrolling_->setCheckable(true);
473         action_view_sticky_scrolling_->setChecked(true);
474         action_view_sticky_scrolling_->setShortcut(QKeySequence(Qt::Key_S));
475         action_view_sticky_scrolling_->setObjectName(
476                 QString::fromUtf8("actionViewStickyScrolling"));
477         action_view_sticky_scrolling_->setText(tr("&Sticky Scrolling"));
478         menu_view->addAction(action_view_sticky_scrolling_);
479
480         view_->enable_sticky_scrolling(action_view_sticky_scrolling_->isChecked());
481
482         menu_view->addSeparator();
483
484         action_view_coloured_bg_->setCheckable(true);
485         action_view_coloured_bg_->setChecked(true);
486         action_view_coloured_bg_->setShortcut(QKeySequence(Qt::Key_B));
487         action_view_coloured_bg_->setObjectName(
488                 QString::fromUtf8("actionViewColouredBg"));
489         action_view_coloured_bg_->setText(tr("Use &coloured backgrounds"));
490         menu_view->addAction(action_view_coloured_bg_);
491
492         view_->enable_coloured_bg(action_view_coloured_bg_->isChecked());
493
494         menu_view->addSeparator();
495
496         action_view_show_cursors_->setCheckable(true);
497         action_view_show_cursors_->setChecked(view_->cursors_shown());
498         action_view_show_cursors_->setIcon(QIcon::fromTheme("show-cursors",
499                 QIcon(":/icons/show-cursors.svg")));
500         action_view_show_cursors_->setShortcut(QKeySequence(Qt::Key_C));
501         action_view_show_cursors_->setObjectName(
502                 QString::fromUtf8("actionViewShowCursors"));
503         action_view_show_cursors_->setText(tr("Show &Cursors"));
504         menu_view->addAction(action_view_show_cursors_);
505
506         // Decoders Menu
507 #ifdef ENABLE_DECODE
508         QMenu *const menu_decoders = new QMenu;
509         menu_decoders->setTitle(tr("&Decoders"));
510
511         menu_decoders_add_->setTitle(tr("&Add"));
512         connect(menu_decoders_add_, SIGNAL(decoder_selected(srd_decoder*)),
513                 this, SLOT(add_decoder(srd_decoder*)));
514
515         menu_decoders->addMenu(menu_decoders_add_);
516 #endif
517
518         // Help Menu
519         QMenu *const menu_help = new QMenu;
520         menu_help->setTitle(tr("&Help"));
521
522         action_about_->setObjectName(QString::fromUtf8("actionAbout"));
523         action_about_->setText(tr("&About..."));
524         menu_help->addAction(action_about_);
525
526         menu_bar->addAction(menu_file->menuAction());
527         menu_bar->addAction(menu_view->menuAction());
528 #ifdef ENABLE_DECODE
529         menu_bar->addAction(menu_decoders->menuAction());
530 #endif
531         menu_bar->addAction(menu_help->menuAction());
532
533         setMenuBar(menu_bar);
534         QMetaObject::connectSlotsByName(this);
535
536         // Also add all actions to the main window for always-enabled hotkeys
537         for (QAction* action : menu_bar->actions())
538                 this->addAction(action);
539
540         // Setup the toolbar
541         main_bar_ = new toolbars::MainBar(session_, *this);
542
543         // Populate the device list and select the initially selected device
544         update_device_list();
545
546         addToolBar(main_bar_);
547
548         // Set the title
549         setWindowTitle(tr("PulseView"));
550
551         // Setup session_ events
552         connect(&session_, SIGNAL(capture_state_changed(int)), this,
553                 SLOT(capture_state_changed(int)));
554         connect(&session_, SIGNAL(device_selected()), this,
555                 SLOT(device_selected()));
556         connect(&session_, SIGNAL(trigger_event(util::Timestamp)), view_,
557                 SLOT(trigger_event(util::Timestamp)));
558
559         // Setup view_ events
560         connect(view_, SIGNAL(sticky_scrolling_changed(bool)), this,
561                 SLOT(sticky_scrolling_changed(bool)));
562         connect(view_, SIGNAL(always_zoom_to_fit_changed(bool)), this,
563                 SLOT(always_zoom_to_fit_changed(bool)));
564
565 }
566
567 void MainWindow::select_init_device()
568 {
569         QSettings settings;
570         map<string, string> dev_info;
571         list<string> key_list;
572         shared_ptr<devices::HardwareDevice> device;
573
574         // Re-select last used device if possible but only if it's not demo
575         settings.beginGroup("Device");
576         key_list.push_back("vendor");
577         key_list.push_back("model");
578         key_list.push_back("version");
579         key_list.push_back("serial_num");
580         key_list.push_back("connection_id");
581
582         for (string key : key_list) {
583                 const QString k = QString::fromStdString(key);
584                 if (!settings.contains(k))
585                         continue;
586
587                 const string value = settings.value(k).toString().toStdString();
588                 if (!value.empty())
589                         dev_info.insert(std::make_pair(key, value));
590         }
591
592         if (dev_info.count("model") > 0)
593                 if (dev_info.at("model").find("Demo device") == std::string::npos)
594                         device = device_manager_.find_device_from_info(dev_info);
595
596         // When we can't find a device similar to the one we used last
597         // time and there is at least one device aside from demo, use it
598         if (!device) {
599                 for (shared_ptr<devices::HardwareDevice> dev : device_manager_.devices()) {
600                         dev_info = device_manager_.get_device_info(dev);
601
602                         if (dev_info.count("model") > 0)
603                                 if (dev_info.at("model").find("Demo device") == std::string::npos) {
604                                         device = dev;
605                                         break;
606                                 }
607                 }
608         }
609
610         select_device(device);
611         update_device_list();
612
613         settings.endGroup();
614 }
615
616 void MainWindow::load_init_file(const std::string &file_name,
617         const std::string &format)
618 {
619         shared_ptr<InputFormat> input_format;
620
621         if (!format.empty()) {
622                 const map<string, shared_ptr<InputFormat> > formats =
623                         device_manager_.context()->input_formats();
624                 const auto iter = find_if(formats.begin(), formats.end(),
625                         [&](const pair<string, shared_ptr<InputFormat> > f) {
626                                 return f.first == format; });
627                 if (iter == formats.end()) {
628                         cerr << "Unexpected input format: " << format << endl;
629                         return;
630                 }
631
632                 input_format = (*iter).second;
633         }
634
635         load_file(QString::fromStdString(file_name), input_format);
636 }
637
638
639 void MainWindow::save_ui_settings()
640 {
641         QSettings settings;
642
643         map<string, string> dev_info;
644         list<string> key_list;
645
646         settings.beginGroup("MainWindow");
647         settings.setValue("state", saveState());
648         settings.setValue("geometry", saveGeometry());
649         settings.endGroup();
650
651         if (session_.device()) {
652                 settings.beginGroup("Device");
653                 key_list.push_back("vendor");
654                 key_list.push_back("model");
655                 key_list.push_back("version");
656                 key_list.push_back("serial_num");
657                 key_list.push_back("connection_id");
658
659                 dev_info = device_manager_.get_device_info(
660                         session_.device());
661
662                 for (string key : key_list) {
663                         if (dev_info.count(key))
664                                 settings.setValue(QString::fromUtf8(key.c_str()),
665                                                 QString::fromUtf8(dev_info.at(key).c_str()));
666                         else
667                                 settings.remove(QString::fromUtf8(key.c_str()));
668                 }
669
670                 settings.endGroup();
671         }
672 }
673
674 void MainWindow::restore_ui_settings()
675 {
676         QSettings settings;
677
678         settings.beginGroup("MainWindow");
679
680         if (settings.contains("geometry")) {
681                 restoreGeometry(settings.value("geometry").toByteArray());
682                 restoreState(settings.value("state").toByteArray());
683         } else
684                 resize(1000, 720);
685
686         settings.endGroup();
687 }
688
689 void MainWindow::session_error(
690         const QString text, const QString info_text)
691 {
692         QMetaObject::invokeMethod(this, "show_session_error",
693                 Qt::QueuedConnection, Q_ARG(QString, text),
694                 Q_ARG(QString, info_text));
695 }
696
697 void MainWindow::update_device_list()
698 {
699         main_bar_->update_device_list();
700 }
701
702 void MainWindow::load_file(QString file_name,
703         std::shared_ptr<sigrok::InputFormat> format,
704         const std::map<std::string, Glib::VariantBase> &options)
705 {
706         const QString errorMessage(
707                 QString("Failed to load file %1").arg(file_name));
708
709         try {
710                 if (format)
711                         session_.set_device(shared_ptr<devices::Device>(
712                                 new devices::InputFile(
713                                         device_manager_.context(),
714                                         file_name.toStdString(),
715                                         format, options)));
716                 else
717                         session_.set_device(shared_ptr<devices::Device>(
718                                 new devices::SessionFile(
719                                         device_manager_.context(),
720                                         file_name.toStdString())));
721         } catch (Error e) {
722                 show_session_error(tr("Failed to load ") + file_name, e.what());
723                 session_.set_default_device();
724                 update_device_list();
725                 return;
726         }
727
728         update_device_list();
729
730         session_.start_capture([&, errorMessage](QString infoMessage) {
731                 session_error(errorMessage, infoMessage); });
732 }
733
734 void MainWindow::closeEvent(QCloseEvent *event)
735 {
736         save_ui_settings();
737         event->accept();
738 }
739
740 void MainWindow::keyReleaseEvent(QKeyEvent *event)
741 {
742         if (event->key() == Qt::Key_Alt) {
743                 menuBar()->setHidden(!menuBar()->isHidden());
744                 menuBar()->setFocus();
745         }
746         QMainWindow::keyReleaseEvent(event);
747 }
748
749 void MainWindow::show_session_error(
750         const QString text, const QString info_text)
751 {
752         QMessageBox msg(this);
753         msg.setText(text);
754         msg.setInformativeText(info_text);
755         msg.setStandardButtons(QMessageBox::Ok);
756         msg.setIcon(QMessageBox::Warning);
757         msg.exec();
758 }
759
760 void MainWindow::on_actionOpen_triggered()
761 {
762         QSettings settings;
763         const QString dir = settings.value(SettingOpenDirectory).toString();
764
765         // Show the dialog
766         const QString file_name = QFileDialog::getOpenFileName(
767                 this, tr("Open File"), dir, tr(
768                         "Sigrok Sessions (*.sr);;"
769                         "All Files (*.*)"));
770
771         if (!file_name.isEmpty()) {
772                 load_file(file_name);
773
774                 const QString abs_path = QFileInfo(file_name).absolutePath();
775                 settings.setValue(SettingOpenDirectory, abs_path);
776         }
777 }
778
779 void MainWindow::on_actionSaveAs_triggered()
780 {
781         export_file(device_manager_.context()->output_formats()["srzip"]);
782 }
783
784 void MainWindow::on_actionSaveSelectionAs_triggered()
785 {
786         export_file(device_manager_.context()->output_formats()["srzip"], true);
787 }
788
789 void MainWindow::on_actionConnect_triggered()
790 {
791         // Stop any currently running capture session
792         session_.stop_capture();
793
794         dialogs::Connect dlg(this, device_manager_);
795
796         // If the user selected a device, select it in the device list. Select the
797         // current device otherwise.
798         if (dlg.exec())
799                 select_device(dlg.get_selected_device());
800
801         update_device_list();
802 }
803
804 void MainWindow::on_actionQuit_triggered()
805 {
806         close();
807 }
808
809 void MainWindow::on_actionViewZoomIn_triggered()
810 {
811         view_->zoom(1);
812 }
813
814 void MainWindow::on_actionViewZoomOut_triggered()
815 {
816         view_->zoom(-1);
817 }
818
819 void MainWindow::on_actionViewZoomFit_triggered()
820 {
821         view_->zoom_fit(action_view_zoom_fit_->isChecked());
822 }
823
824 void MainWindow::on_actionViewZoomOneToOne_triggered()
825 {
826         view_->zoom_one_to_one();
827 }
828
829 void MainWindow::on_actionViewStickyScrolling_triggered()
830 {
831         view_->enable_sticky_scrolling(action_view_sticky_scrolling_->isChecked());
832 }
833
834 void MainWindow::on_actionViewColouredBg_triggered()
835 {
836         view_->enable_coloured_bg(action_view_coloured_bg_->isChecked());
837 }
838
839 void MainWindow::on_actionViewShowCursors_triggered()
840 {
841         assert(view_);
842
843         const bool show = !view_->cursors_shown();
844         if (show)
845                 view_->centre_cursors();
846
847         view_->show_cursors(show);
848 }
849
850 void MainWindow::on_actionAbout_triggered()
851 {
852         dialogs::About dlg(device_manager_.context(), this);
853         dlg.exec();
854 }
855
856 void MainWindow::sticky_scrolling_changed(bool state)
857 {
858         action_view_sticky_scrolling_->setChecked(state);
859 }
860
861 void MainWindow::always_zoom_to_fit_changed(bool state)
862 {
863         action_view_zoom_fit_->setChecked(state);
864 }
865
866 void MainWindow::add_decoder(srd_decoder *decoder)
867 {
868 #ifdef ENABLE_DECODE
869         assert(decoder);
870         session_.add_decoder(decoder);
871 #else
872         (void)decoder;
873 #endif
874 }
875
876 void MainWindow::capture_state_changed(int state)
877 {
878         main_bar_->set_capture_state((pv::Session::capture_state)state);
879 }
880
881 void MainWindow::device_selected()
882 {
883         // Set the title to include the device/file name
884         const shared_ptr<devices::Device> device = session_.device();
885
886         if (!device) {
887                 main_bar_->reset_device_selector();
888                 return;
889         }
890
891         const string display_name = device->display_name(device_manager_);
892         setWindowTitle(tr("%1 - PulseView").arg(display_name.c_str()));
893 }
894
895 } // namespace pv