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