]> sigrok.org Git - pulseview.git/blob - pv/toolbars/mainbar.cpp
Fix #1038 by catching invalid cursor ranges
[pulseview.git] / pv / toolbars / mainbar.cpp
1 /*
2  * This file is part of the PulseView project.
3  *
4  * Copyright (C) 2012-2015 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, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <extdef.h>
21
22 #include <algorithm>
23 #include <cassert>
24
25 #include <QAction>
26 #include <QDebug>
27 #include <QFileDialog>
28 #include <QHelpEvent>
29 #include <QMenu>
30 #include <QMessageBox>
31 #include <QSettings>
32 #include <QToolTip>
33
34 #include "mainbar.hpp"
35
36 #include <boost/algorithm/string/join.hpp>
37
38 #include <pv/data/decodesignal.hpp>
39 #include <pv/devicemanager.hpp>
40 #include <pv/devices/hardwaredevice.hpp>
41 #include <pv/devices/inputfile.hpp>
42 #include <pv/devices/sessionfile.hpp>
43 #include <pv/dialogs/connect.hpp>
44 #include <pv/dialogs/inputoutputoptions.hpp>
45 #include <pv/dialogs/storeprogress.hpp>
46 #include <pv/mainwindow.hpp>
47 #include <pv/popups/channels.hpp>
48 #include <pv/popups/deviceoptions.hpp>
49 #include <pv/util.hpp>
50 #include <pv/views/trace/view.hpp>
51 #include <pv/widgets/exportmenu.hpp>
52 #include <pv/widgets/importmenu.hpp>
53 #ifdef ENABLE_DECODE
54 #include <pv/widgets/decodermenu.hpp>
55 #endif
56
57 #include <libsigrokcxx/libsigrokcxx.hpp>
58
59 using std::back_inserter;
60 using std::copy;
61 using std::list;
62 using std::make_pair;
63 using std::map;
64 using std::max;
65 using std::min;
66 using std::pair;
67 using std::set;
68 using std::shared_ptr;
69 using std::string;
70 using std::vector;
71
72 using sigrok::Capability;
73 using sigrok::ConfigKey;
74 using sigrok::Error;
75 using sigrok::InputFormat;
76 using sigrok::OutputFormat;
77
78 using boost::algorithm::join;
79
80 namespace pv {
81 namespace toolbars {
82
83 const uint64_t MainBar::MinSampleCount = 100ULL;
84 const uint64_t MainBar::MaxSampleCount = 1000000000000ULL;
85 const uint64_t MainBar::DefaultSampleCount = 1000000;
86
87 const char *MainBar::SettingOpenDirectory = "MainWindow/OpenDirectory";
88 const char *MainBar::SettingSaveDirectory = "MainWindow/SaveDirectory";
89
90 MainBar::MainBar(Session &session, QWidget *parent,
91                 pv::views::trace::View *view) :
92         StandardBar(session, parent, view, false),
93         action_new_view_(new QAction(this)),
94         action_open_(new QAction(this)),
95         action_save_as_(new QAction(this)),
96         action_save_selection_as_(new QAction(this)),
97         action_connect_(new QAction(this)),
98         open_button_(new QToolButton()),
99         save_button_(new QToolButton()),
100         device_selector_(parent, session.device_manager(),
101                 action_connect_),
102         configure_button_(this),
103         configure_button_action_(nullptr),
104         channels_button_(this),
105         channels_button_action_(nullptr),
106         sample_count_(" samples", this),
107         sample_rate_("Hz", this),
108         updating_sample_rate_(false),
109         updating_sample_count_(false),
110         sample_count_supported_(false)
111 #ifdef ENABLE_DECODE
112         , add_decoder_button_(new QToolButton()),
113         menu_decoders_add_(new pv::widgets::DecoderMenu(this, true))
114 #endif
115 {
116         setObjectName(QString::fromUtf8("MainBar"));
117
118         setContextMenuPolicy(Qt::PreventContextMenu);
119
120         // Actions
121         action_new_view_->setText(tr("New &View"));
122         action_new_view_->setIcon(QIcon::fromTheme("window-new",
123                 QIcon(":/icons/window-new.png")));
124         connect(action_new_view_, SIGNAL(triggered(bool)),
125                 this, SLOT(on_actionNewView_triggered()));
126
127         action_open_->setText(tr("&Open..."));
128         action_open_->setIcon(QIcon::fromTheme("document-open",
129                 QIcon(":/icons/document-open.png")));
130         action_open_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O));
131         connect(action_open_, SIGNAL(triggered(bool)),
132                 this, SLOT(on_actionOpen_triggered()));
133
134         action_save_as_->setText(tr("&Save As..."));
135         action_save_as_->setIcon(QIcon::fromTheme("document-save-as",
136                 QIcon(":/icons/document-save-as.png")));
137         action_save_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
138         connect(action_save_as_, SIGNAL(triggered(bool)),
139                 this, SLOT(on_actionSaveAs_triggered()));
140
141         action_save_selection_as_->setText(tr("Save Selected &Range As..."));
142         action_save_selection_as_->setIcon(QIcon::fromTheme("document-save-as",
143                 QIcon(":/icons/document-save-as.png")));
144         action_save_selection_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
145         connect(action_save_selection_as_, SIGNAL(triggered(bool)),
146                 this, SLOT(on_actionSaveSelectionAs_triggered()));
147
148         widgets::ExportMenu *menu_file_export = new widgets::ExportMenu(this,
149                 session.device_manager().context());
150         menu_file_export->setTitle(tr("&Export"));
151         connect(menu_file_export,
152                 SIGNAL(format_selected(shared_ptr<sigrok::OutputFormat>)),
153                 this, SLOT(export_file(shared_ptr<sigrok::OutputFormat>)));
154
155         widgets::ImportMenu *menu_file_import = new widgets::ImportMenu(this,
156                 session.device_manager().context());
157         menu_file_import->setTitle(tr("&Import"));
158         connect(menu_file_import,
159                 SIGNAL(format_selected(shared_ptr<sigrok::InputFormat>)),
160                 this, SLOT(import_file(shared_ptr<sigrok::InputFormat>)));
161
162         action_connect_->setText(tr("&Connect to Device..."));
163         connect(action_connect_, SIGNAL(triggered(bool)),
164                 this, SLOT(on_actionConnect_triggered()));
165
166         // Open button
167         widgets::ImportMenu *import_menu = new widgets::ImportMenu(this,
168                 session.device_manager().context(), action_open_);
169         connect(import_menu,
170                 SIGNAL(format_selected(shared_ptr<sigrok::InputFormat>)),
171                 this,
172                 SLOT(import_file(shared_ptr<sigrok::InputFormat>)));
173
174         open_button_->setMenu(import_menu);
175         open_button_->setDefaultAction(action_open_);
176         open_button_->setPopupMode(QToolButton::MenuButtonPopup);
177
178         // Save button
179         vector<QAction *> open_actions;
180         open_actions.push_back(action_save_as_);
181         open_actions.push_back(action_save_selection_as_);
182
183         widgets::ExportMenu *export_menu = new widgets::ExportMenu(this,
184                 session.device_manager().context(),
185                 open_actions);
186         connect(export_menu,
187                 SIGNAL(format_selected(shared_ptr<sigrok::OutputFormat>)),
188                 this,
189                 SLOT(export_file(shared_ptr<sigrok::OutputFormat>)));
190
191         save_button_->setMenu(export_menu);
192         save_button_->setDefaultAction(action_save_as_);
193         save_button_->setPopupMode(QToolButton::MenuButtonPopup);
194
195         // Device selector menu
196         connect(&device_selector_, SIGNAL(device_selected()),
197                 this, SLOT(on_device_selected()));
198
199         // Setup the decoder button
200 #ifdef ENABLE_DECODE
201         menu_decoders_add_->setTitle(tr("&Add"));
202         connect(menu_decoders_add_, SIGNAL(decoder_selected(srd_decoder*)),
203                 this, SLOT(add_decoder(srd_decoder*)));
204
205         add_decoder_button_->setIcon(QIcon(":/icons/add-decoder.svg"));
206         add_decoder_button_->setPopupMode(QToolButton::InstantPopup);
207         add_decoder_button_->setMenu(menu_decoders_add_);
208         add_decoder_button_->setToolTip(tr("Add low-level, non-stacked protocol decoder"));
209 #endif
210
211         connect(&sample_count_, SIGNAL(value_changed()),
212                 this, SLOT(on_sample_count_changed()));
213         connect(&sample_rate_, SIGNAL(value_changed()),
214                 this, SLOT(on_sample_rate_changed()));
215
216         sample_count_.show_min_max_step(0, UINT64_MAX, 1);
217
218         set_capture_state(pv::Session::Stopped);
219
220         configure_button_.setToolTip(tr("Configure Device"));
221         configure_button_.setIcon(QIcon::fromTheme("preferences-system",
222                 QIcon(":/icons/preferences-system.png")));
223
224         channels_button_.setToolTip(tr("Configure Channels"));
225         channels_button_.setIcon(QIcon(":/icons/channels.svg"));
226
227         add_toolbar_widgets();
228
229         sample_count_.installEventFilter(this);
230         sample_rate_.installEventFilter(this);
231
232         // Setup session_ events
233         connect(&session_, SIGNAL(capture_state_changed(int)),
234                 this, SLOT(on_capture_state_changed(int)));
235         connect(&session, SIGNAL(device_changed()),
236                 this, SLOT(on_device_changed()));
237
238         update_device_list();
239 }
240
241 void MainBar::update_device_list()
242 {
243         DeviceManager &mgr = session_.device_manager();
244         shared_ptr<devices::Device> selected_device = session_.device();
245         list< shared_ptr<devices::Device> > devs;
246
247         copy(mgr.devices().begin(), mgr.devices().end(), back_inserter(devs));
248
249         if (std::find(devs.begin(), devs.end(), selected_device) == devs.end())
250                 devs.push_back(selected_device);
251
252         device_selector_.set_device_list(devs, selected_device);
253         update_device_config_widgets();
254 }
255
256 void MainBar::set_capture_state(pv::Session::capture_state state)
257 {
258         bool ui_enabled = (state == pv::Session::Stopped) ? true : false;
259
260         device_selector_.setEnabled(ui_enabled);
261         configure_button_.setEnabled(ui_enabled);
262         channels_button_.setEnabled(ui_enabled);
263         sample_count_.setEnabled(ui_enabled);
264         sample_rate_.setEnabled(ui_enabled);
265 }
266
267 void MainBar::reset_device_selector()
268 {
269         device_selector_.reset();
270 }
271
272 QAction* MainBar::action_open() const
273 {
274         return action_open_;
275 }
276
277 QAction* MainBar::action_save_as() const
278 {
279         return action_save_as_;
280 }
281
282 QAction* MainBar::action_save_selection_as() const
283 {
284         return action_save_selection_as_;
285 }
286
287 QAction* MainBar::action_connect() const
288 {
289         return action_connect_;
290 }
291
292 void MainBar::update_sample_rate_selector()
293 {
294         Glib::VariantContainerBase gvar_dict;
295         GVariant *gvar_list;
296         const uint64_t *elements = nullptr;
297         gsize num_elements;
298         map< const ConfigKey*, set<Capability> > keys;
299
300         if (updating_sample_rate_) {
301                 sample_rate_.show_none();
302                 return;
303         }
304
305         const shared_ptr<devices::Device> device =
306                 device_selector_.selected_device();
307         if (!device)
308                 return;
309
310         assert(!updating_sample_rate_);
311         updating_sample_rate_ = true;
312
313         const shared_ptr<sigrok::Device> sr_dev = device->device();
314
315         if (sr_dev->config_check(ConfigKey::SAMPLERATE, Capability::LIST)) {
316                 gvar_dict = sr_dev->config_list(ConfigKey::SAMPLERATE);
317         } else {
318                 sample_rate_.show_none();
319                 updating_sample_rate_ = false;
320                 return;
321         }
322
323         if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
324                         "samplerate-steps", G_VARIANT_TYPE("at")))) {
325                 elements = (const uint64_t *)g_variant_get_fixed_array(
326                                 gvar_list, &num_elements, sizeof(uint64_t));
327
328                 const uint64_t min = elements[0];
329                 const uint64_t max = elements[1];
330                 const uint64_t step = elements[2];
331
332                 g_variant_unref(gvar_list);
333
334                 assert(min > 0);
335                 assert(max > 0);
336                 assert(max > min);
337                 assert(step > 0);
338
339                 if (step == 1)
340                         sample_rate_.show_125_list(min, max);
341                 else {
342                         // When the step is not 1, we cam't make a 1-2-5-10
343                         // list of sample rates, because we may not be able to
344                         // make round numbers. Therefore in this case, show a
345                         // spin box.
346                         sample_rate_.show_min_max_step(min, max, step);
347                 }
348         } else if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
349                         "samplerates", G_VARIANT_TYPE("at")))) {
350                 elements = (const uint64_t *)g_variant_get_fixed_array(
351                                 gvar_list, &num_elements, sizeof(uint64_t));
352                 sample_rate_.show_list(elements, num_elements);
353                 g_variant_unref(gvar_list);
354         }
355         updating_sample_rate_ = false;
356
357         update_sample_rate_selector_value();
358 }
359
360 void MainBar::update_sample_rate_selector_value()
361 {
362         if (updating_sample_rate_)
363                 return;
364
365         const shared_ptr<devices::Device> device =
366                 device_selector_.selected_device();
367         if (!device)
368                 return;
369
370         try {
371                 auto gvar = device->device()->config_get(ConfigKey::SAMPLERATE);
372                 uint64_t samplerate =
373                         Glib::VariantBase::cast_dynamic<Glib::Variant<guint64>>(gvar).get();
374                 assert(!updating_sample_rate_);
375                 updating_sample_rate_ = true;
376                 sample_rate_.set_value(samplerate);
377                 updating_sample_rate_ = false;
378         } catch (Error error) {
379                 qDebug() << "WARNING: Failed to get value of sample rate";
380                 return;
381         }
382 }
383
384 void MainBar::update_sample_count_selector()
385 {
386         if (updating_sample_count_)
387                 return;
388
389         const shared_ptr<devices::Device> device =
390                 device_selector_.selected_device();
391         if (!device)
392                 return;
393
394         const shared_ptr<sigrok::Device> sr_dev = device->device();
395
396         assert(!updating_sample_count_);
397         updating_sample_count_ = true;
398
399         if (!sample_count_supported_) {
400                 sample_count_.show_none();
401                 updating_sample_count_ = false;
402                 return;
403         }
404
405         uint64_t sample_count = sample_count_.value();
406         uint64_t min_sample_count = 0;
407         uint64_t max_sample_count = MaxSampleCount;
408         bool default_count_set = false;
409
410         if (sample_count == 0) {
411                 sample_count = DefaultSampleCount;
412                 default_count_set = true;
413         }
414
415         if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::LIST)) {
416                 auto gvar = sr_dev->config_list(ConfigKey::LIMIT_SAMPLES);
417                 if (gvar.gobj())
418                         g_variant_get(gvar.gobj(), "(tt)",
419                                 &min_sample_count, &max_sample_count);
420         }
421
422         min_sample_count = min(max(min_sample_count, MinSampleCount),
423                 max_sample_count);
424
425         sample_count_.show_125_list(min_sample_count, max_sample_count);
426
427         if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::GET)) {
428                 auto gvar = sr_dev->config_get(ConfigKey::LIMIT_SAMPLES);
429                 sample_count = g_variant_get_uint64(gvar.gobj());
430                 if (sample_count == 0) {
431                         sample_count = DefaultSampleCount;
432                         default_count_set = true;
433                 }
434                 sample_count = min(max(sample_count, MinSampleCount),
435                         max_sample_count);
436         }
437
438         sample_count_.set_value(sample_count);
439
440         updating_sample_count_ = false;
441
442         // If we show the default rate then make sure the device uses the same
443         if (default_count_set)
444                 commit_sample_count();
445 }
446
447 void MainBar::update_device_config_widgets()
448 {
449         using namespace pv::popups;
450
451         const shared_ptr<devices::Device> device =
452                 device_selector_.selected_device();
453
454         // Hide the widgets if no device is selected
455         channels_button_action_->setVisible(!!device);
456         if (!device) {
457                 configure_button_action_->setVisible(false);
458                 sample_count_.show_none();
459                 sample_rate_.show_none();
460                 return;
461         }
462
463         const shared_ptr<sigrok::Device> sr_dev = device->device();
464         if (!sr_dev)
465                 return;
466
467         // Update the configure popup
468         DeviceOptions *const opts = new DeviceOptions(sr_dev, this);
469         configure_button_action_->setVisible(
470                 !opts->binding().properties().empty());
471         configure_button_.set_popup(opts);
472
473         // Update the channels popup
474         Channels *const channels = new Channels(session_, this);
475         channels_button_.set_popup(channels);
476
477         // Update supported options.
478         sample_count_supported_ = false;
479
480         if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::SET))
481                 sample_count_supported_ = true;
482
483         // Add notification of reconfigure events
484         disconnect(this, SLOT(on_config_changed()));
485         connect(&opts->binding(), SIGNAL(config_changed()),
486                 this, SLOT(on_config_changed()));
487
488         // Update sweep timing widgets.
489         update_sample_count_selector();
490         update_sample_rate_selector();
491 }
492
493 void MainBar::commit_sample_rate()
494 {
495         uint64_t sample_rate = 0;
496
497         const shared_ptr<devices::Device> device =
498                 device_selector_.selected_device();
499         if (!device)
500                 return;
501
502         const shared_ptr<sigrok::Device> sr_dev = device->device();
503
504         sample_rate = sample_rate_.value();
505         if (sample_rate == 0)
506                 return;
507
508         try {
509                 sr_dev->config_set(ConfigKey::SAMPLERATE,
510                         Glib::Variant<guint64>::create(sample_rate));
511                 update_sample_rate_selector();
512         } catch (Error error) {
513                 qDebug() << "Failed to configure samplerate.";
514                 return;
515         }
516
517         // Devices with built-in memory might impose limits on certain
518         // configurations, so let's check what sample count the driver
519         // lets us use now.
520         update_sample_count_selector();
521 }
522
523 void MainBar::commit_sample_count()
524 {
525         uint64_t sample_count = 0;
526
527         const shared_ptr<devices::Device> device =
528                 device_selector_.selected_device();
529         if (!device)
530                 return;
531
532         const shared_ptr<sigrok::Device> sr_dev = device->device();
533
534         sample_count = sample_count_.value();
535         if (sample_count_supported_) {
536                 try {
537                         sr_dev->config_set(ConfigKey::LIMIT_SAMPLES,
538                                 Glib::Variant<guint64>::create(sample_count));
539                         update_sample_count_selector();
540                 } catch (Error error) {
541                         qDebug() << "Failed to configure sample count.";
542                         return;
543                 }
544         }
545
546         // Devices with built-in memory might impose limits on certain
547         // configurations, so let's check what sample rate the driver
548         // lets us use now.
549         update_sample_rate_selector();
550 }
551
552 void MainBar::session_error(const QString text, const QString info_text)
553 {
554         QMetaObject::invokeMethod(this, "show_session_error",
555                 Qt::QueuedConnection, Q_ARG(QString, text),
556                 Q_ARG(QString, info_text));
557 }
558
559 void MainBar::show_session_error(const QString text, const QString info_text)
560 {
561         QMessageBox msg(this);
562         msg.setText(text);
563         msg.setInformativeText(info_text);
564         msg.setStandardButtons(QMessageBox::Ok);
565         msg.setIcon(QMessageBox::Warning);
566         msg.exec();
567 }
568
569 void MainBar::add_decoder(srd_decoder *decoder)
570 {
571 #ifdef ENABLE_DECODE
572         assert(decoder);
573         shared_ptr<data::DecodeSignal> signal = session_.add_decode_signal();
574         if (signal)
575                 signal->stack_decoder(decoder);
576 #else
577         (void)decoder;
578 #endif
579 }
580
581 void MainBar::export_file(shared_ptr<OutputFormat> format, bool selection_only)
582 {
583         using pv::dialogs::StoreProgress;
584
585         // Stop any currently running capture session
586         session_.stop_capture();
587
588         QSettings settings;
589         const QString dir = settings.value(SettingSaveDirectory).toString();
590
591         pair<uint64_t, uint64_t> sample_range;
592
593         // Selection only? Verify that the cursors are active and fetch their values
594         if (selection_only) {
595                 views::trace::View *trace_view =
596                         qobject_cast<views::trace::View*>(session_.main_view().get());
597
598                 if (!trace_view->cursors()->enabled()) {
599                         show_session_error(tr("Missing Cursors"), tr("You need to set the " \
600                                         "cursors before you can save the data enclosed by them " \
601                                         "to a session file (e.g. using the Show Cursors button)."));
602                         return;
603                 }
604
605                 const double samplerate = session_.get_samplerate();
606
607                 const pv::util::Timestamp& start_time = trace_view->cursors()->first()->time();
608                 const pv::util::Timestamp& end_time = trace_view->cursors()->second()->time();
609
610                 const uint64_t start_sample = (uint64_t)max(
611                         (double)0, start_time.convert_to<double>() * samplerate);
612                 const uint64_t end_sample = (uint64_t)max(
613                         (double)0, end_time.convert_to<double>() * samplerate);
614
615                 if ((start_sample == 0) && (end_sample == 0)) {
616                         // Both cursors are negative and were clamped to 0
617                         show_session_error(tr("Invalid Range"), tr("The cursors don't " \
618                                         "define a valid range of samples."));
619                         return;
620                 }
621
622                 sample_range = make_pair(start_sample, end_sample);
623         } else {
624                 sample_range = make_pair(0, 0);
625         }
626
627         // Construct the filter
628         const vector<string> exts = format->extensions();
629         QString filter = tr("%1 files ").arg(
630                 QString::fromStdString(format->description()));
631
632         if (exts.empty())
633                 filter += "(*)";
634         else
635                 filter += QString("(*.%1);;%2 (*)").arg(
636                         QString::fromStdString(join(exts, ", *.")),
637                         tr("All Files"));
638
639         // Show the file dialog
640         const QString file_name = QFileDialog::getSaveFileName(
641                 this, tr("Save File"), dir, filter);
642
643         if (file_name.isEmpty())
644                 return;
645
646         const QString abs_path = QFileInfo(file_name).absolutePath();
647         settings.setValue(SettingSaveDirectory, abs_path);
648
649         // Show the options dialog
650         map<string, Glib::VariantBase> options;
651         if (!format->options().empty()) {
652                 dialogs::InputOutputOptions dlg(
653                         tr("Export %1").arg(QString::fromStdString(
654                                 format->description())),
655                         format->options(), this);
656                 if (!dlg.exec())
657                         return;
658                 options = dlg.options();
659         }
660
661         if (!selection_only)
662                 session_.set_name(QFileInfo(file_name).fileName());
663
664         StoreProgress *dlg = new StoreProgress(file_name, format, options,
665                 sample_range, session_, this);
666         dlg->run();
667 }
668
669 void MainBar::import_file(shared_ptr<InputFormat> format)
670 {
671         assert(format);
672
673         QSettings settings;
674         const QString dir = settings.value(SettingOpenDirectory).toString();
675
676         // Construct the filter
677         const vector<string> exts = format->extensions();
678         const QString filter_exts = exts.empty() ? "" : QString::fromStdString("%1 (%2)").arg(
679                 tr("%1 files").arg(QString::fromStdString(format->description())),
680                 QString::fromStdString("*.%1").arg(QString::fromStdString(join(exts, " *."))));
681         const QString filter_all = QString::fromStdString("%1 (%2)").arg(
682                 tr("All Files"), QString::fromStdString("*"));
683         const QString filter = QString::fromStdString("%1%2%3").arg(
684                 exts.empty() ? "" : filter_exts,
685                 exts.empty() ? "" : ";;",
686                 filter_all);
687
688         // Show the file dialog
689         const QString file_name = QFileDialog::getOpenFileName(
690                 this, tr("Import File"), dir, filter);
691
692         if (file_name.isEmpty())
693                 return;
694
695         // Show the options dialog
696         map<string, Glib::VariantBase> options;
697         if (!format->options().empty()) {
698                 dialogs::InputOutputOptions dlg(
699                         tr("Import %1").arg(QString::fromStdString(
700                                 format->description())),
701                         format->options(), this);
702                 if (!dlg.exec())
703                         return;
704                 options = dlg.options();
705         }
706
707         session_.load_file(file_name, format, options);
708
709         const QString abs_path = QFileInfo(file_name).absolutePath();
710         settings.setValue(SettingOpenDirectory, abs_path);
711 }
712
713 void MainBar::on_device_selected()
714 {
715         shared_ptr<devices::Device> device = device_selector_.selected_device();
716         if (!device) {
717                 reset_device_selector();
718                 return;
719         }
720
721         session_.select_device(device);
722 }
723
724 void MainBar::on_device_changed()
725 {
726         update_device_list();
727         update_device_config_widgets();
728 }
729
730 void MainBar::on_capture_state_changed(int state)
731 {
732         set_capture_state((pv::Session::capture_state)state);
733 }
734
735 void MainBar::on_sample_count_changed()
736 {
737         if (!updating_sample_count_)
738                 commit_sample_count();
739 }
740
741 void MainBar::on_sample_rate_changed()
742 {
743         if (!updating_sample_rate_)
744                 commit_sample_rate();
745 }
746
747 void MainBar::on_config_changed()
748 {
749         commit_sample_count();
750         commit_sample_rate();
751 }
752
753 void MainBar::on_actionNewView_triggered()
754 {
755         new_view(&session_);
756 }
757
758 void MainBar::on_actionOpen_triggered()
759 {
760         QSettings settings;
761         const QString dir = settings.value(SettingOpenDirectory).toString();
762
763         // Show the dialog
764         const QString file_name = QFileDialog::getOpenFileName(
765                 this, tr("Open File"), dir, tr(
766                         "sigrok Sessions (*.sr);;"
767                         "All Files (*)"));
768
769         if (!file_name.isEmpty()) {
770                 session_.load_file(file_name);
771
772                 const QString abs_path = QFileInfo(file_name).absolutePath();
773                 settings.setValue(SettingOpenDirectory, abs_path);
774         }
775 }
776
777 void MainBar::on_actionSaveAs_triggered()
778 {
779         export_file(session_.device_manager().context()->output_formats()["srzip"]);
780 }
781
782 void MainBar::on_actionSaveSelectionAs_triggered()
783 {
784         export_file(session_.device_manager().context()->output_formats()["srzip"], true);
785 }
786
787 void MainBar::on_actionConnect_triggered()
788 {
789         // Stop any currently running capture session
790         session_.stop_capture();
791
792         dialogs::Connect dlg(this, session_.device_manager());
793
794         // If the user selected a device, select it in the device list. Select the
795         // current device otherwise.
796         if (dlg.exec())
797                 session_.select_device(dlg.get_selected_device());
798
799         update_device_list();
800 }
801
802 void MainBar::add_toolbar_widgets()
803 {
804         addAction(action_new_view_);
805         addSeparator();
806         addWidget(open_button_);
807         addWidget(save_button_);
808         addSeparator();
809
810         StandardBar::add_toolbar_widgets();
811
812         addWidget(&device_selector_);
813         configure_button_action_ = addWidget(&configure_button_);
814         channels_button_action_ = addWidget(&channels_button_);
815         addWidget(&sample_count_);
816         addWidget(&sample_rate_);
817 #ifdef ENABLE_DECODE
818         addSeparator();
819         addWidget(add_decoder_button_);
820 #endif
821 }
822
823 bool MainBar::eventFilter(QObject *watched, QEvent *event)
824 {
825         if (sample_count_supported_ && (watched == &sample_count_ ||
826                         watched == &sample_rate_) &&
827                         (event->type() == QEvent::ToolTip)) {
828                 auto sec = pv::util::Timestamp(sample_count_.value()) / sample_rate_.value();
829                 QHelpEvent *help_event = static_cast<QHelpEvent*>(event);
830
831                 QString str = tr("Total sampling time: %1").arg(
832                         pv::util::format_time_si(sec, pv::util::SIPrefix::unspecified, 0, "s", false));
833                 QToolTip::showText(help_event->globalPos(), str);
834
835                 return true;
836         }
837
838         return false;
839 }
840
841 } // namespace toolbars
842 } // namespace pv