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