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