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