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