]> sigrok.org Git - pulseview.git/blob - pv/toolbars/mainbar.cpp
0adb6c9250c3bd17ca45c4e8da4d28466a97a7c1
[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::pair;
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, MainWindow &main_window) :
91         QToolBar("Sampling Bar", &main_window),
92         action_open_(new QAction(this)),
93         action_save_as_(new QAction(this)),
94         action_save_selection_as_(new QAction(this)),
95         action_connect_(new QAction(this)),
96         action_view_zoom_in_(new QAction(this)),
97         action_view_zoom_out_(new QAction(this)),
98         action_view_zoom_fit_(new QAction(this)),
99         action_view_zoom_one_to_one_(new QAction(this)),
100         action_view_show_cursors_(new QAction(this)),
101         session_(session),
102         device_selector_(&main_window, session.device_manager(),
103                 action_connect_),
104         configure_button_(this),
105         configure_button_action_(nullptr),
106         channels_button_(this),
107         channels_button_action_(nullptr),
108         sample_count_(" samples", this),
109         sample_rate_("Hz", this),
110         updating_sample_rate_(false),
111         updating_sample_count_(false),
112         sample_count_supported_(false),
113         icon_red_(":/icons/status-red.svg"),
114         icon_green_(":/icons/status-green.svg"),
115         icon_grey_(":/icons/status-grey.svg"),
116         run_stop_button_(this),
117         run_stop_button_action_(nullptr),
118         menu_button_(this)
119 #ifdef ENABLE_DECODE
120         , menu_decoders_add_(new pv::widgets::DecoderMenu(this, true))
121 #endif
122 {
123         setObjectName(QString::fromUtf8("MainBar"));
124
125         setMovable(false);
126         setFloatable(false);
127         setContextMenuPolicy(Qt::PreventContextMenu);
128
129         // Actions
130         action_open_->setText(tr("&Open..."));
131         action_open_->setIcon(QIcon::fromTheme("document-open",
132                 QIcon(":/icons/document-open.png")));
133         action_open_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O));
134         connect(action_open_, SIGNAL(triggered(bool)),
135                 this, SLOT(on_actionOpen_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         widgets::ExportMenu *menu_file_export = new widgets::ExportMenu(this,
152                 session.device_manager().context());
153         menu_file_export->setTitle(tr("&Export"));
154         connect(menu_file_export,
155                 SIGNAL(format_selected(std::shared_ptr<sigrok::OutputFormat>)),
156                 this, SLOT(export_file(std::shared_ptr<sigrok::OutputFormat>)));
157
158         widgets::ImportMenu *menu_file_import = new widgets::ImportMenu(this,
159                 session.device_manager().context());
160         menu_file_import->setTitle(tr("&Import"));
161         connect(menu_file_import,
162                 SIGNAL(format_selected(std::shared_ptr<sigrok::InputFormat>)),
163                 this, SLOT(import_file(std::shared_ptr<sigrok::InputFormat>)));
164
165         action_connect_->setText(tr("&Connect to Device..."));
166         connect(action_connect_, SIGNAL(triggered(bool)),
167                 this, SLOT(on_actionConnect_triggered()));
168
169         action_view_zoom_in_->setText(tr("Zoom &In"));
170         action_view_zoom_in_->setIcon(QIcon::fromTheme("zoom-in",
171                 QIcon(":/icons/zoom-in.png")));
172         // simply using Qt::Key_Plus shows no + in the menu
173         action_view_zoom_in_->setShortcut(QKeySequence::ZoomIn);
174         connect(action_view_zoom_in_, SIGNAL(triggered(bool)),
175                 this, SLOT(on_actionViewZoomIn_triggered()));
176
177         action_view_zoom_out_->setText(tr("Zoom &Out"));
178         action_view_zoom_out_->setIcon(QIcon::fromTheme("zoom-out",
179                 QIcon(":/icons/zoom-out.png")));
180         action_view_zoom_out_->setShortcut(QKeySequence::ZoomOut);
181         connect(action_view_zoom_out_, SIGNAL(triggered(bool)),
182                 this, SLOT(on_actionViewZoomOut_triggered()));
183
184         action_view_zoom_fit_->setCheckable(true);
185         action_view_zoom_fit_->setText(tr("Zoom to &Fit"));
186         action_view_zoom_fit_->setIcon(QIcon::fromTheme("zoom-fit",
187                 QIcon(":/icons/zoom-fit.png")));
188         action_view_zoom_fit_->setShortcut(QKeySequence(Qt::Key_F));
189         connect(action_view_zoom_fit_, SIGNAL(triggered(bool)),
190                 this, SLOT(on_actionViewZoomFit_triggered()));
191
192         action_view_zoom_one_to_one_->setText(tr("Zoom to O&ne-to-One"));
193         action_view_zoom_one_to_one_->setIcon(QIcon::fromTheme("zoom-original",
194                 QIcon(":/icons/zoom-original.png")));
195         action_view_zoom_one_to_one_->setShortcut(QKeySequence(Qt::Key_O));
196         connect(action_view_zoom_one_to_one_, SIGNAL(triggered(bool)),
197                 this, SLOT(on_actionViewZoomOneToOne_triggered()));
198
199         action_view_show_cursors_->setCheckable(true);
200         action_view_show_cursors_->setIcon(QIcon::fromTheme("show-cursors",
201                 QIcon(":/icons/show-cursors.svg")));
202         action_view_show_cursors_->setShortcut(QKeySequence(Qt::Key_C));
203         connect(action_view_show_cursors_, SIGNAL(triggered(bool)),
204                 this, SLOT(on_actionViewShowCursors_triggered()));
205         action_view_show_cursors_->setText(tr("Show &Cursors"));
206
207         // Open button
208         QToolButton *const open_button = new QToolButton(this);
209
210         widgets::ImportMenu *import_menu = new widgets::ImportMenu(this,
211                 session.device_manager().context(), action_open_);
212         connect(import_menu,
213                 SIGNAL(format_selected(std::shared_ptr<sigrok::InputFormat>)),
214                 this,
215                 SLOT(import_file(std::shared_ptr<sigrok::InputFormat>)));
216
217         open_button->setMenu(import_menu);
218         open_button->setDefaultAction(action_open_);
219         open_button->setPopupMode(QToolButton::MenuButtonPopup);
220
221         // Save button
222         QToolButton *const save_button = new QToolButton(this);
223
224         vector<QAction *> open_actions;
225         open_actions.push_back(action_save_as_);
226         open_actions.push_back(action_save_selection_as_);
227
228         widgets::ExportMenu *export_menu = new widgets::ExportMenu(this,
229                 session.device_manager().context(),
230                 open_actions);
231         connect(export_menu,
232                 SIGNAL(format_selected(std::shared_ptr<sigrok::OutputFormat>)),
233                 this,
234                 SLOT(export_file(std::shared_ptr<sigrok::OutputFormat>)));
235
236         save_button->setMenu(export_menu);
237         save_button->setDefaultAction(action_save_as_);
238         save_button->setPopupMode(QToolButton::MenuButtonPopup);
239
240         // Device selector menu
241         connect(&device_selector_, SIGNAL(device_selected()),
242                 this, SLOT(on_device_selected()));
243
244         // Setup the decoder button
245 #ifdef ENABLE_DECODE
246         menu_decoders_add_->setTitle(tr("&Add"));
247         connect(menu_decoders_add_, SIGNAL(decoder_selected(srd_decoder*)),
248                 this, SLOT(add_decoder(srd_decoder*)));
249
250         QToolButton *add_decoder_button = new QToolButton(this);
251         add_decoder_button->setIcon(QIcon::fromTheme("add-decoder",
252                 QIcon(":/icons/add-decoder.svg")));
253         add_decoder_button->setPopupMode(QToolButton::InstantPopup);
254         add_decoder_button->setMenu(menu_decoders_add_);
255 #endif
256
257         // Setup the toolbar
258         addWidget(open_button);
259         addWidget(save_button);
260         addSeparator();
261         addAction(action_view_zoom_in_);
262         addAction(action_view_zoom_out_);
263         addAction(action_view_zoom_fit_);
264         addAction(action_view_zoom_one_to_one_);
265         addSeparator();
266         addAction(action_view_show_cursors_);
267         addSeparator();
268
269         connect(&run_stop_button_, SIGNAL(clicked()),
270                 this, SLOT(on_run_stop()));
271         connect(&sample_count_, SIGNAL(value_changed()),
272                 this, SLOT(on_sample_count_changed()));
273         connect(&sample_rate_, SIGNAL(value_changed()),
274                 this, SLOT(on_sample_rate_changed()));
275
276         sample_count_.show_min_max_step(0, UINT64_MAX, 1);
277
278         set_capture_state(pv::Session::Stopped);
279
280         configure_button_.setIcon(QIcon::fromTheme("configure",
281                 QIcon(":/icons/configure.png")));
282
283         channels_button_.setIcon(QIcon::fromTheme("channels",
284                 QIcon(":/icons/channels.svg")));
285
286         run_stop_button_.setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
287
288         addWidget(&device_selector_);
289         configure_button_action_ = addWidget(&configure_button_);
290         channels_button_action_ = addWidget(&channels_button_);
291         addWidget(&sample_count_);
292         addWidget(&sample_rate_);
293         run_stop_button_action_ = addWidget(&run_stop_button_);
294 #ifdef ENABLE_DECODE
295         addSeparator();
296         addWidget(add_decoder_button);
297 #endif
298
299         QWidget *const spacer = new QWidget();
300         spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
301         addWidget(spacer);
302
303         addWidget(&menu_button_);
304
305         sample_count_.installEventFilter(this);
306         sample_rate_.installEventFilter(this);
307
308         // Setup session_ events
309         connect(&session_, SIGNAL(capture_state_changed(int)),
310                 this, SLOT(capture_state_changed(int)));
311         connect(&session, SIGNAL(device_changed()),
312                 this, SLOT(on_device_changed()));
313
314         update_device_list();
315 }
316
317 Session &MainBar::session(void) const
318 {
319         return session_;
320 }
321
322 void MainBar::update_device_list()
323 {
324         DeviceManager &mgr = session_.device_manager();
325         shared_ptr<devices::Device> selected_device = session_.device();
326         list< shared_ptr<devices::Device> > devs;
327
328         copy(mgr.devices().begin(), mgr.devices().end(), back_inserter(devs));
329
330         if (std::find(devs.begin(), devs.end(), selected_device) == devs.end())
331                 devs.push_back(selected_device);
332
333         device_selector_.set_device_list(devs, selected_device);
334         update_device_config_widgets();
335 }
336
337
338 void MainBar::set_capture_state(pv::Session::capture_state state)
339 {
340         const QIcon *icons[] = {&icon_grey_, &icon_red_, &icon_green_};
341         run_stop_button_.setIcon(*icons[state]);
342         run_stop_button_.setText((state == pv::Session::Stopped) ?
343                 tr("Run") : tr("Stop"));
344         run_stop_button_.setShortcut(QKeySequence(Qt::Key_Space));
345
346         bool ui_enabled = (state == pv::Session::Stopped) ? true : false;
347
348         device_selector_.setEnabled(ui_enabled);
349         configure_button_.setEnabled(ui_enabled);
350         channels_button_.setEnabled(ui_enabled);
351         sample_count_.setEnabled(ui_enabled);
352         sample_rate_.setEnabled(ui_enabled);
353 }
354
355 void MainBar::reset_device_selector()
356 {
357         device_selector_.reset();
358 }
359
360 void MainBar::select_device(shared_ptr<devices::Device> device)
361 {
362         try {
363                 if (device)
364                         session_.set_device(device);
365                 else
366                         session_.set_default_device();
367         } catch (const QString &e) {
368                 QMessageBox msg(this);
369                 msg.setText(e);
370                 msg.setInformativeText(tr("Failed to Select Device"));
371                 msg.setStandardButtons(QMessageBox::Ok);
372                 msg.setIcon(QMessageBox::Warning);
373                 msg.exec();
374         }
375 }
376
377 void MainBar::load_init_file(const std::string &file_name,
378         const std::string &format)
379 {
380         shared_ptr<InputFormat> input_format;
381
382         DeviceManager& device_manager = session_.device_manager();
383
384         if (!format.empty()) {
385                 const map<string, shared_ptr<InputFormat> > formats =
386                         device_manager.context()->input_formats();
387                 const auto iter = find_if(formats.begin(), formats.end(),
388                         [&](const pair<string, shared_ptr<InputFormat> > f) {
389                                 return f.first == format; });
390                 if (iter == formats.end()) {
391                         cerr << "Unexpected input format: " << format << endl;
392                         return;
393                 }
394
395                 input_format = (*iter).second;
396         }
397
398         load_file(QString::fromStdString(file_name), input_format);
399 }
400
401 QAction* MainBar::action_open() const
402 {
403         return action_open_;
404 }
405
406 QAction* MainBar::action_save_as() const
407 {
408         return action_save_as_;
409 }
410
411 QAction* MainBar::action_save_selection_as() const
412 {
413         return action_save_selection_as_;
414 }
415
416 QAction* MainBar::action_connect() const
417 {
418         return action_connect_;
419 }
420
421 QAction* MainBar::action_view_zoom_in() const
422 {
423         return action_view_zoom_in_;
424 }
425
426 QAction* MainBar::action_view_zoom_out() const
427 {
428         return action_view_zoom_out_;
429 }
430
431 QAction* MainBar::action_view_zoom_fit() const
432 {
433         return action_view_zoom_fit_;
434 }
435
436 QAction* MainBar::action_view_zoom_one_to_one() const
437 {
438         return action_view_zoom_one_to_one_;
439 }
440
441 QAction* MainBar::action_view_show_cursors() const
442 {
443         return action_view_show_cursors_;
444 }
445
446 void MainBar::run_stop()
447 {
448         switch (session_.get_capture_state()) {
449         case Session::Stopped:
450                 session_.start_capture([&](QString message) {
451                         session_error("Capture failed", message); });
452                 break;
453         case Session::AwaitingTrigger:
454         case Session::Running:
455                 session_.stop_capture();
456                 break;
457         }
458 }
459
460 void MainBar::load_file(QString file_name,
461         std::shared_ptr<sigrok::InputFormat> format,
462         const std::map<std::string, Glib::VariantBase> &options)
463 {
464         DeviceManager& device_manager = session_.device_manager();
465
466         const QString errorMessage(
467                 QString("Failed to load file %1").arg(file_name));
468
469         try {
470                 if (format)
471                         session_.set_device(shared_ptr<devices::Device>(
472                                 new devices::InputFile(
473                                         device_manager.context(),
474                                         file_name.toStdString(),
475                                         format, options)));
476                 else
477                         session_.set_device(shared_ptr<devices::Device>(
478                                 new devices::SessionFile(
479                                         device_manager.context(),
480                                         file_name.toStdString())));
481         } catch (Error e) {
482                 show_session_error(tr("Failed to load ") + file_name, e.what());
483                 session_.set_default_device();
484                 update_device_list();
485                 return;
486         }
487
488         session_.set_name(QFileInfo(file_name).fileName());
489
490         update_device_list();
491
492         session_.start_capture([&, errorMessage](QString infoMessage) {
493                 session_error(errorMessage, infoMessage); });
494 }
495
496 void MainBar::update_sample_rate_selector()
497 {
498         Glib::VariantContainerBase gvar_dict;
499         GVariant *gvar_list;
500         const uint64_t *elements = nullptr;
501         gsize num_elements;
502         map< const ConfigKey*, std::set<Capability> > keys;
503
504         if (updating_sample_rate_) {
505                 sample_rate_.show_none();
506                 return;
507         }
508
509         const shared_ptr<devices::Device> device =
510                 device_selector_.selected_device();
511         if (!device)
512                 return;
513
514         assert(!updating_sample_rate_);
515         updating_sample_rate_ = true;
516
517         const shared_ptr<sigrok::Device> sr_dev = device->device();
518
519         if (sr_dev->config_check(ConfigKey::SAMPLERATE, Capability::LIST)) {
520                 gvar_dict = sr_dev->config_list(ConfigKey::SAMPLERATE);
521         } else {
522                 sample_rate_.show_none();
523                 updating_sample_rate_ = false;
524                 return;
525         }
526
527         if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
528                         "samplerate-steps", G_VARIANT_TYPE("at")))) {
529                 elements = (const uint64_t *)g_variant_get_fixed_array(
530                                 gvar_list, &num_elements, sizeof(uint64_t));
531
532                 const uint64_t min = elements[0];
533                 const uint64_t max = elements[1];
534                 const uint64_t step = elements[2];
535
536                 g_variant_unref(gvar_list);
537
538                 assert(min > 0);
539                 assert(max > 0);
540                 assert(max > min);
541                 assert(step > 0);
542
543                 if (step == 1)
544                         sample_rate_.show_125_list(min, max);
545                 else {
546                         // When the step is not 1, we cam't make a 1-2-5-10
547                         // list of sample rates, because we may not be able to
548                         // make round numbers. Therefore in this case, show a
549                         // spin box.
550                         sample_rate_.show_min_max_step(min, max, step);
551                 }
552         } else if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
553                         "samplerates", G_VARIANT_TYPE("at")))) {
554                 elements = (const uint64_t *)g_variant_get_fixed_array(
555                                 gvar_list, &num_elements, sizeof(uint64_t));
556                 sample_rate_.show_list(elements, num_elements);
557                 g_variant_unref(gvar_list);
558         }
559         updating_sample_rate_ = false;
560
561         update_sample_rate_selector_value();
562 }
563
564 void MainBar::update_sample_rate_selector_value()
565 {
566         if (updating_sample_rate_)
567                 return;
568
569         const shared_ptr<devices::Device> device =
570                 device_selector_.selected_device();
571         if (!device)
572                 return;
573
574         try {
575                 auto gvar = device->device()->config_get(ConfigKey::SAMPLERATE);
576                 uint64_t samplerate =
577                         Glib::VariantBase::cast_dynamic<Glib::Variant<guint64>>(gvar).get();
578                 assert(!updating_sample_rate_);
579                 updating_sample_rate_ = true;
580                 sample_rate_.set_value(samplerate);
581                 updating_sample_rate_ = false;
582         } catch (Error error) {
583                 qDebug() << "WARNING: Failed to get value of sample rate";
584                 return;
585         }
586 }
587
588 void MainBar::update_sample_count_selector()
589 {
590         if (updating_sample_count_)
591                 return;
592
593         const shared_ptr<devices::Device> device =
594                 device_selector_.selected_device();
595         if (!device)
596                 return;
597
598         const shared_ptr<sigrok::Device> sr_dev = device->device();
599
600         assert(!updating_sample_count_);
601         updating_sample_count_ = true;
602
603         if (!sample_count_supported_) {
604                 sample_count_.show_none();
605                 updating_sample_count_ = false;
606                 return;
607         }
608
609         uint64_t sample_count = sample_count_.value();
610         uint64_t min_sample_count = 0;
611         uint64_t max_sample_count = MaxSampleCount;
612
613         if (sample_count == 0)
614                 sample_count = DefaultSampleCount;
615
616         if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::LIST)) {
617                 auto gvar = sr_dev->config_list(ConfigKey::LIMIT_SAMPLES);
618                 if (gvar.gobj())
619                         g_variant_get(gvar.gobj(), "(tt)",
620                                 &min_sample_count, &max_sample_count);
621         }
622
623         min_sample_count = min(max(min_sample_count, MinSampleCount),
624                 max_sample_count);
625
626         sample_count_.show_125_list(
627                 min_sample_count, max_sample_count);
628
629         if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::GET)) {
630                 auto gvar = sr_dev->config_get(ConfigKey::LIMIT_SAMPLES);
631                 sample_count = g_variant_get_uint64(gvar.gobj());
632                 if (sample_count == 0)
633                         sample_count = DefaultSampleCount;
634                 sample_count = min(max(sample_count, MinSampleCount),
635                         max_sample_count);
636         }
637
638         sample_count_.set_value(sample_count);
639
640         updating_sample_count_ = false;
641 }
642
643 void MainBar::update_device_config_widgets()
644 {
645         using namespace pv::popups;
646
647         const shared_ptr<devices::Device> device =
648                 device_selector_.selected_device();
649
650         // Hide the widgets if no device is selected
651         channels_button_action_->setVisible(!!device);
652         run_stop_button_action_->setVisible(!!device);
653         if (!device) {
654                 configure_button_action_->setVisible(false);
655                 sample_count_.show_none();
656                 sample_rate_.show_none();
657                 return;
658         }
659
660         const shared_ptr<sigrok::Device> sr_dev = device->device();
661         if (!sr_dev)
662                 return;
663
664         // Update the configure popup
665         DeviceOptions *const opts = new DeviceOptions(sr_dev, this);
666         configure_button_action_->setVisible(
667                 !opts->binding().properties().empty());
668         configure_button_.set_popup(opts);
669
670         // Update the channels popup
671         Channels *const channels = new Channels(session_, this);
672         channels_button_.set_popup(channels);
673
674         // Update supported options.
675         sample_count_supported_ = false;
676
677         if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::SET))
678                 sample_count_supported_ = true;
679
680         if (sr_dev->config_check(ConfigKey::LIMIT_FRAMES, Capability::SET)) {
681                 sr_dev->config_set(ConfigKey::LIMIT_FRAMES,
682                         Glib::Variant<guint64>::create(1));
683                         on_config_changed();
684         }
685
686         // Add notification of reconfigure events
687         disconnect(this, SLOT(on_config_changed()));
688         connect(&opts->binding(), SIGNAL(config_changed()),
689                 this, SLOT(on_config_changed()));
690
691         // Update sweep timing widgets.
692         update_sample_count_selector();
693         update_sample_rate_selector();
694 }
695
696 void MainBar::commit_sample_rate()
697 {
698         uint64_t sample_rate = 0;
699
700         const shared_ptr<devices::Device> device =
701                 device_selector_.selected_device();
702         if (!device)
703                 return;
704
705         const shared_ptr<sigrok::Device> sr_dev = device->device();
706
707         sample_rate = sample_rate_.value();
708         if (sample_rate == 0)
709                 return;
710
711         try {
712                 sr_dev->config_set(ConfigKey::SAMPLERATE,
713                         Glib::Variant<guint64>::create(sample_rate));
714                 update_sample_rate_selector();
715         } catch (Error error) {
716                 qDebug() << "Failed to configure samplerate.";
717                 return;
718         }
719
720         // Devices with built-in memory might impose limits on certain
721         // configurations, so let's check what sample count the driver
722         // lets us use now.
723         update_sample_count_selector();
724 }
725
726 void MainBar::commit_sample_count()
727 {
728         uint64_t sample_count = 0;
729
730         const shared_ptr<devices::Device> device =
731                 device_selector_.selected_device();
732         if (!device)
733                 return;
734
735         const shared_ptr<sigrok::Device> sr_dev = device->device();
736
737         sample_count = sample_count_.value();
738         if (sample_count_supported_) {
739                 try {
740                         sr_dev->config_set(ConfigKey::LIMIT_SAMPLES,
741                                 Glib::Variant<guint64>::create(sample_count));
742                         update_sample_count_selector();
743                 } catch (Error error) {
744                         qDebug() << "Failed to configure sample count.";
745                         return;
746                 }
747         }
748
749         // Devices with built-in memory might impose limits on certain
750         // configurations, so let's check what sample rate the driver
751         // lets us use now.
752         update_sample_rate_selector();
753 }
754
755 void MainBar::session_error(const QString text, const QString info_text)
756 {
757         QMetaObject::invokeMethod(this, "show_session_error",
758                 Qt::QueuedConnection, Q_ARG(QString, text),
759                 Q_ARG(QString, info_text));
760 }
761
762 void MainBar::show_session_error(const QString text, const QString info_text)
763 {
764         QMessageBox msg(this);
765         msg.setText(text);
766         msg.setInformativeText(info_text);
767         msg.setStandardButtons(QMessageBox::Ok);
768         msg.setIcon(QMessageBox::Warning);
769         msg.exec();
770 }
771
772 void MainBar::capture_state_changed(int state)
773 {
774         set_capture_state((pv::Session::capture_state)state);
775 }
776
777 void MainBar::add_decoder(srd_decoder *decoder)
778 {
779 #ifdef ENABLE_DECODE
780         assert(decoder);
781         session_.add_decoder(decoder);
782 #else
783         (void)decoder;
784 #endif
785 }
786
787 void MainBar::export_file(shared_ptr<OutputFormat> format,
788         bool selection_only)
789 {
790         using pv::dialogs::StoreProgress;
791
792         // Stop any currently running capture session
793         session_.stop_capture();
794
795         QSettings settings;
796         const QString dir = settings.value(SettingSaveDirectory).toString();
797
798         std::pair<uint64_t, uint64_t> sample_range;
799
800         // Selection only? Verify that the cursors are active and fetch their values
801         if (selection_only) {
802                 if (!session_.main_view()->cursors()->enabled()) {
803                         show_session_error(tr("Missing Cursors"), tr("You need to set the " \
804                                         "cursors before you can save the data enclosed by them " \
805                                         "to a session file (e.g. using ALT-V - Show Cursors)."));
806                         return;
807                 }
808
809                 const double samplerate = session_.get_samplerate();
810
811                 const pv::util::Timestamp& start_time = session_.main_view()->cursors()->first()->time();
812                 const pv::util::Timestamp& end_time = session_.main_view()->cursors()->second()->time();
813
814                 const uint64_t start_sample =
815                         std::max((double)0, start_time.convert_to<double>() * samplerate);
816                 const uint64_t end_sample = end_time.convert_to<double>() * samplerate;
817
818                 sample_range = std::make_pair(start_sample, end_sample);
819         } else {
820                 sample_range = std::make_pair(0, 0);
821         }
822
823         // Construct the filter
824         const vector<string> exts = format->extensions();
825         QString filter = tr("%1 files ").arg(
826                 QString::fromStdString(format->description()));
827
828         if (exts.empty())
829                 filter += "(*.*)";
830         else
831                 filter += QString("(*.%1);;%2 (*.*)").arg(
832                         QString::fromStdString(join(exts, ", *.")),
833                         tr("All Files"));
834
835         // Show the file dialog
836         const QString file_name = QFileDialog::getSaveFileName(
837                 this, tr("Save File"), dir, filter);
838
839         if (file_name.isEmpty())
840                 return;
841
842         const QString abs_path = QFileInfo(file_name).absolutePath();
843         settings.setValue(SettingSaveDirectory, abs_path);
844
845         // Show the options dialog
846         map<string, Glib::VariantBase> options;
847         if (!format->options().empty()) {
848                 dialogs::InputOutputOptions dlg(
849                         tr("Export %1").arg(QString::fromStdString(
850                                 format->description())),
851                         format->options(), this);
852                 if (!dlg.exec())
853                         return;
854                 options = dlg.options();
855         }
856
857         session_.set_name(QFileInfo(file_name).fileName());
858
859         StoreProgress *dlg = new StoreProgress(file_name, format, options,
860                 sample_range, session_, this);
861         dlg->run();
862 }
863
864 void MainBar::import_file(shared_ptr<InputFormat> format)
865 {
866         assert(format);
867
868         QSettings settings;
869         const QString dir = settings.value(SettingOpenDirectory).toString();
870
871         // Construct the filter
872         const vector<string> exts = format->extensions();
873         const QString filter = exts.empty() ? "" :
874                 tr("%1 files (*.%2)").arg(
875                         QString::fromStdString(format->description()),
876                         QString::fromStdString(join(exts, ", *.")));
877
878         // Show the file dialog
879         const QString file_name = QFileDialog::getOpenFileName(
880                 this, tr("Import File"), dir, tr(
881                         "%1 files (*.*);;All Files (*.*)").arg(
882                         QString::fromStdString(format->description())));
883
884         if (file_name.isEmpty())
885                 return;
886
887         // Show the options dialog
888         map<string, Glib::VariantBase> options;
889         if (!format->options().empty()) {
890                 dialogs::InputOutputOptions dlg(
891                         tr("Import %1").arg(QString::fromStdString(
892                                 format->description())),
893                         format->options(), this);
894                 if (!dlg.exec())
895                         return;
896                 options = dlg.options();
897         }
898
899         load_file(file_name, format, options);
900
901         const QString abs_path = QFileInfo(file_name).absolutePath();
902         settings.setValue(SettingOpenDirectory, abs_path);
903 }
904
905 void MainBar::on_device_selected()
906 {
907         shared_ptr<devices::Device> device = device_selector_.selected_device();
908         if (!device) {
909                 reset_device_selector();
910                 return;
911         }
912
913         select_device(device);
914 }
915
916 void MainBar::on_device_changed()
917 {
918         update_device_list();
919         update_device_config_widgets();
920 }
921
922 void MainBar::on_sample_count_changed()
923 {
924         if (!updating_sample_count_)
925                 commit_sample_count();
926 }
927
928 void MainBar::on_sample_rate_changed()
929 {
930         if (!updating_sample_rate_)
931                 commit_sample_rate();
932 }
933
934 void MainBar::on_run_stop()
935 {
936         commit_sample_count();
937         commit_sample_rate();   
938         run_stop();
939 }
940
941 void MainBar::on_config_changed()
942 {
943         commit_sample_count();
944         commit_sample_rate();   
945 }
946
947 void MainBar::on_actionOpen_triggered()
948 {
949         QSettings settings;
950         const QString dir = settings.value(SettingOpenDirectory).toString();
951
952         // Show the dialog
953         const QString file_name = QFileDialog::getOpenFileName(
954                 this, tr("Open File"), dir, tr(
955                         "Sigrok Sessions (*.sr);;"
956                         "All Files (*.*)"));
957
958         if (!file_name.isEmpty()) {
959                 load_file(file_name);
960
961                 const QString abs_path = QFileInfo(file_name).absolutePath();
962                 settings.setValue(SettingOpenDirectory, abs_path);
963         }
964 }
965
966 void MainBar::on_actionSaveAs_triggered()
967 {
968         export_file(session_.device_manager().context()->output_formats()["srzip"]);
969 }
970
971 void MainBar::on_actionSaveSelectionAs_triggered()
972 {
973         export_file(session_.device_manager().context()->output_formats()["srzip"], true);
974 }
975
976 void MainBar::on_actionConnect_triggered()
977 {
978         // Stop any currently running capture session
979         session_.stop_capture();
980
981         dialogs::Connect dlg(this, session_.device_manager());
982
983         // If the user selected a device, select it in the device list. Select the
984         // current device otherwise.
985         if (dlg.exec())
986                 select_device(dlg.get_selected_device());
987
988         update_device_list();
989 }
990
991 void MainBar::on_actionViewZoomIn_triggered()
992 {
993         session_.main_view()->zoom(1);
994 }
995
996 void MainBar::on_actionViewZoomOut_triggered()
997 {
998         session_.main_view()->zoom(-1);
999 }
1000
1001 void MainBar::on_actionViewZoomFit_triggered()
1002 {
1003         session_.main_view()->zoom_fit(action_view_zoom_fit_->isChecked());
1004 }
1005
1006 void MainBar::on_actionViewZoomOneToOne_triggered()
1007 {
1008         session_.main_view()->zoom_one_to_one();
1009 }
1010
1011 void MainBar::on_actionViewShowCursors_triggered()
1012 {
1013         const bool show = !session_.main_view()->cursors_shown();
1014         if (show)
1015                 session_.main_view()->centre_cursors();
1016
1017         session_.main_view()->show_cursors(show);
1018 }
1019
1020 void MainBar::on_always_zoom_to_fit_changed(bool state)
1021 {
1022         action_view_zoom_fit_->setChecked(state);
1023 }
1024
1025 bool MainBar::eventFilter(QObject *watched, QEvent *event)
1026 {
1027         if (sample_count_supported_ && (watched == &sample_count_ ||
1028                         watched == &sample_rate_) &&
1029                         (event->type() == QEvent::ToolTip)) {
1030                 auto sec = pv::util::Timestamp(sample_count_.value()) / sample_rate_.value();
1031                 QHelpEvent *help_event = static_cast<QHelpEvent*>(event);
1032
1033                 QString str = tr("Total sampling time: %1").arg(
1034                         pv::util::format_time_si(sec, pv::util::SIPrefix::unspecified, 0, "s", false));
1035                 QToolTip::showText(help_event->globalPos(), str);
1036
1037                 return true;
1038         }
1039
1040         return false;
1041 }
1042
1043 } // namespace toolbars
1044 } // namespace pv