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