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