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