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