2 * This file is part of the PulseView project.
4 * Copyright (C) 2012-2015 Joel Holdsworth <joel@airwebreathe.org.uk>
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.
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.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
27 #include <QFileDialog>
30 #include <QMessageBox>
34 #include "mainbar.hpp"
36 #include <boost/algorithm/string/join.hpp>
38 #include <pv/devicemanager.hpp>
39 #include <pv/devices/hardwaredevice.hpp>
40 #include <pv/devices/inputfile.hpp>
41 #include <pv/devices/sessionfile.hpp>
42 #include <pv/dialogs/connect.hpp>
43 #include <pv/dialogs/inputoutputoptions.hpp>
44 #include <pv/dialogs/storeprogress.hpp>
45 #include <pv/mainwindow.hpp>
46 #include <pv/popups/channels.hpp>
47 #include <pv/popups/deviceoptions.hpp>
48 #include <pv/util.hpp>
49 #include <pv/view/view.hpp>
50 #include <pv/widgets/exportmenu.hpp>
51 #include <pv/widgets/importmenu.hpp>
53 #include <pv/widgets/decodermenu.hpp>
56 #include <libsigrokcxx/libsigrokcxx.hpp>
58 using std::back_inserter;
67 using std::shared_ptr;
71 using sigrok::Capability;
72 using sigrok::ConfigKey;
74 using sigrok::InputFormat;
75 using sigrok::OutputFormat;
77 using boost::algorithm::join;
82 const uint64_t MainBar::MinSampleCount = 100ULL;
83 const uint64_t MainBar::MaxSampleCount = 1000000000000ULL;
84 const uint64_t MainBar::DefaultSampleCount = 1000000;
86 const char *MainBar::SettingOpenDirectory = "MainWindow/OpenDirectory";
87 const char *MainBar::SettingSaveDirectory = "MainWindow/SaveDirectory";
89 MainBar::MainBar(Session &session, QWidget *parent,
90 pv::views::TraceView::View *view) :
91 StandardBar(session, parent, view, false),
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 open_button_(new QToolButton()),
98 save_button_(new QToolButton()),
99 device_selector_(parent, session.device_manager(),
101 configure_button_(this),
102 configure_button_action_(nullptr),
103 channels_button_(this),
104 channels_button_action_(nullptr),
105 sample_count_(" samples", this),
106 sample_rate_("Hz", this),
107 updating_sample_rate_(false),
108 updating_sample_count_(false),
109 sample_count_supported_(false)
111 , add_decoder_button_(new QToolButton()),
112 menu_decoders_add_(new pv::widgets::DecoderMenu(this, true))
115 setObjectName(QString::fromUtf8("MainBar"));
118 action_new_view_->setText(tr("New &View"));
119 action_new_view_->setIcon(QIcon::fromTheme("window-new",
120 QIcon(":/icons/window-new.png")));
121 connect(action_new_view_, SIGNAL(triggered(bool)),
122 this, SLOT(on_actionNewView_triggered()));
124 action_open_->setText(tr("&Open..."));
125 action_open_->setIcon(QIcon::fromTheme("document-open",
126 QIcon(":/icons/document-open.png")));
127 action_open_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O));
128 connect(action_open_, SIGNAL(triggered(bool)),
129 this, SLOT(on_actionOpen_triggered()));
131 action_save_as_->setText(tr("&Save As..."));
132 action_save_as_->setIcon(QIcon::fromTheme("document-save-as",
133 QIcon(":/icons/document-save-as.png")));
134 action_save_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
135 connect(action_save_as_, SIGNAL(triggered(bool)),
136 this, SLOT(on_actionSaveAs_triggered()));
138 action_save_selection_as_->setText(tr("Save Selected &Range As..."));
139 action_save_selection_as_->setIcon(QIcon::fromTheme("document-save-as",
140 QIcon(":/icons/document-save-as.png")));
141 action_save_selection_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
142 connect(action_save_selection_as_, SIGNAL(triggered(bool)),
143 this, SLOT(on_actionSaveSelectionAs_triggered()));
145 widgets::ExportMenu *menu_file_export = new widgets::ExportMenu(this,
146 session.device_manager().context());
147 menu_file_export->setTitle(tr("&Export"));
148 connect(menu_file_export,
149 SIGNAL(format_selected(shared_ptr<sigrok::OutputFormat>)),
150 this, SLOT(export_file(shared_ptr<sigrok::OutputFormat>)));
152 widgets::ImportMenu *menu_file_import = new widgets::ImportMenu(this,
153 session.device_manager().context());
154 menu_file_import->setTitle(tr("&Import"));
155 connect(menu_file_import,
156 SIGNAL(format_selected(shared_ptr<sigrok::InputFormat>)),
157 this, SLOT(import_file(shared_ptr<sigrok::InputFormat>)));
159 action_connect_->setText(tr("&Connect to Device..."));
160 connect(action_connect_, SIGNAL(triggered(bool)),
161 this, SLOT(on_actionConnect_triggered()));
164 widgets::ImportMenu *import_menu = new widgets::ImportMenu(this,
165 session.device_manager().context(), action_open_);
167 SIGNAL(format_selected(shared_ptr<sigrok::InputFormat>)),
169 SLOT(import_file(shared_ptr<sigrok::InputFormat>)));
171 open_button_->setMenu(import_menu);
172 open_button_->setDefaultAction(action_open_);
173 open_button_->setPopupMode(QToolButton::MenuButtonPopup);
176 vector<QAction *> open_actions;
177 open_actions.push_back(action_save_as_);
178 open_actions.push_back(action_save_selection_as_);
180 widgets::ExportMenu *export_menu = new widgets::ExportMenu(this,
181 session.device_manager().context(),
184 SIGNAL(format_selected(shared_ptr<sigrok::OutputFormat>)),
186 SLOT(export_file(shared_ptr<sigrok::OutputFormat>)));
188 save_button_->setMenu(export_menu);
189 save_button_->setDefaultAction(action_save_as_);
190 save_button_->setPopupMode(QToolButton::MenuButtonPopup);
192 // Device selector menu
193 connect(&device_selector_, SIGNAL(device_selected()),
194 this, SLOT(on_device_selected()));
196 // Setup the decoder button
198 menu_decoders_add_->setTitle(tr("&Add"));
199 connect(menu_decoders_add_, SIGNAL(decoder_selected(srd_decoder*)),
200 this, SLOT(add_decoder(srd_decoder*)));
202 add_decoder_button_->setIcon(QIcon(":/icons/add-decoder.svg"));
203 add_decoder_button_->setPopupMode(QToolButton::InstantPopup);
204 add_decoder_button_->setMenu(menu_decoders_add_);
205 add_decoder_button_->setToolTip(tr("Add low-level, non-stacked protocol decoder"));
208 connect(&sample_count_, SIGNAL(value_changed()),
209 this, SLOT(on_sample_count_changed()));
210 connect(&sample_rate_, SIGNAL(value_changed()),
211 this, SLOT(on_sample_rate_changed()));
213 sample_count_.show_min_max_step(0, UINT64_MAX, 1);
215 set_capture_state(pv::Session::Stopped);
217 configure_button_.setToolTip(tr("Configure Device"));
218 configure_button_.setIcon(QIcon::fromTheme("preferences-system",
219 QIcon(":/icons/preferences-system.png")));
221 channels_button_.setToolTip(tr("Configure Channels"));
222 channels_button_.setIcon(QIcon(":/icons/channels.svg"));
224 add_toolbar_widgets();
226 sample_count_.installEventFilter(this);
227 sample_rate_.installEventFilter(this);
229 // Setup session_ events
230 connect(&session_, SIGNAL(capture_state_changed(int)),
231 this, SLOT(on_capture_state_changed(int)));
232 connect(&session, SIGNAL(device_changed()),
233 this, SLOT(on_device_changed()));
235 update_device_list();
238 void MainBar::update_device_list()
240 DeviceManager &mgr = session_.device_manager();
241 shared_ptr<devices::Device> selected_device = session_.device();
242 list< shared_ptr<devices::Device> > devs;
244 copy(mgr.devices().begin(), mgr.devices().end(), back_inserter(devs));
246 if (std::find(devs.begin(), devs.end(), selected_device) == devs.end())
247 devs.push_back(selected_device);
249 device_selector_.set_device_list(devs, selected_device);
250 update_device_config_widgets();
253 void MainBar::set_capture_state(pv::Session::capture_state state)
255 bool ui_enabled = (state == pv::Session::Stopped) ? true : false;
257 device_selector_.setEnabled(ui_enabled);
258 configure_button_.setEnabled(ui_enabled);
259 channels_button_.setEnabled(ui_enabled);
260 sample_count_.setEnabled(ui_enabled);
261 sample_rate_.setEnabled(ui_enabled);
264 void MainBar::reset_device_selector()
266 device_selector_.reset();
269 QAction* MainBar::action_open() const
274 QAction* MainBar::action_save_as() const
276 return action_save_as_;
279 QAction* MainBar::action_save_selection_as() const
281 return action_save_selection_as_;
284 QAction* MainBar::action_connect() const
286 return action_connect_;
289 void MainBar::update_sample_rate_selector()
291 Glib::VariantContainerBase gvar_dict;
293 const uint64_t *elements = nullptr;
295 map< const ConfigKey*, set<Capability> > keys;
297 if (updating_sample_rate_) {
298 sample_rate_.show_none();
302 const shared_ptr<devices::Device> device =
303 device_selector_.selected_device();
307 assert(!updating_sample_rate_);
308 updating_sample_rate_ = true;
310 const shared_ptr<sigrok::Device> sr_dev = device->device();
312 if (sr_dev->config_check(ConfigKey::SAMPLERATE, Capability::LIST)) {
313 gvar_dict = sr_dev->config_list(ConfigKey::SAMPLERATE);
315 sample_rate_.show_none();
316 updating_sample_rate_ = false;
320 if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
321 "samplerate-steps", G_VARIANT_TYPE("at")))) {
322 elements = (const uint64_t *)g_variant_get_fixed_array(
323 gvar_list, &num_elements, sizeof(uint64_t));
325 const uint64_t min = elements[0];
326 const uint64_t max = elements[1];
327 const uint64_t step = elements[2];
329 g_variant_unref(gvar_list);
337 sample_rate_.show_125_list(min, max);
339 // When the step is not 1, we cam't make a 1-2-5-10
340 // list of sample rates, because we may not be able to
341 // make round numbers. Therefore in this case, show a
343 sample_rate_.show_min_max_step(min, max, step);
345 } else if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
346 "samplerates", G_VARIANT_TYPE("at")))) {
347 elements = (const uint64_t *)g_variant_get_fixed_array(
348 gvar_list, &num_elements, sizeof(uint64_t));
349 sample_rate_.show_list(elements, num_elements);
350 g_variant_unref(gvar_list);
352 updating_sample_rate_ = false;
354 update_sample_rate_selector_value();
357 void MainBar::update_sample_rate_selector_value()
359 if (updating_sample_rate_)
362 const shared_ptr<devices::Device> device =
363 device_selector_.selected_device();
368 auto gvar = device->device()->config_get(ConfigKey::SAMPLERATE);
369 uint64_t samplerate =
370 Glib::VariantBase::cast_dynamic<Glib::Variant<guint64>>(gvar).get();
371 assert(!updating_sample_rate_);
372 updating_sample_rate_ = true;
373 sample_rate_.set_value(samplerate);
374 updating_sample_rate_ = false;
375 } catch (Error error) {
376 qDebug() << "WARNING: Failed to get value of sample rate";
381 void MainBar::update_sample_count_selector()
383 if (updating_sample_count_)
386 const shared_ptr<devices::Device> device =
387 device_selector_.selected_device();
391 const shared_ptr<sigrok::Device> sr_dev = device->device();
393 assert(!updating_sample_count_);
394 updating_sample_count_ = true;
396 if (!sample_count_supported_) {
397 sample_count_.show_none();
398 updating_sample_count_ = false;
402 uint64_t sample_count = sample_count_.value();
403 uint64_t min_sample_count = 0;
404 uint64_t max_sample_count = MaxSampleCount;
405 bool default_count_set = false;
407 if (sample_count == 0) {
408 sample_count = DefaultSampleCount;
409 default_count_set = true;
412 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::LIST)) {
413 auto gvar = sr_dev->config_list(ConfigKey::LIMIT_SAMPLES);
415 g_variant_get(gvar.gobj(), "(tt)",
416 &min_sample_count, &max_sample_count);
419 min_sample_count = min(max(min_sample_count, MinSampleCount),
422 sample_count_.show_125_list(min_sample_count, max_sample_count);
424 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::GET)) {
425 auto gvar = sr_dev->config_get(ConfigKey::LIMIT_SAMPLES);
426 sample_count = g_variant_get_uint64(gvar.gobj());
427 if (sample_count == 0) {
428 sample_count = DefaultSampleCount;
429 default_count_set = true;
431 sample_count = min(max(sample_count, MinSampleCount),
435 sample_count_.set_value(sample_count);
437 updating_sample_count_ = false;
439 // If we show the default rate then make sure the device uses the same
440 if (default_count_set)
441 commit_sample_count();
444 void MainBar::update_device_config_widgets()
446 using namespace pv::popups;
448 const shared_ptr<devices::Device> device =
449 device_selector_.selected_device();
451 // Hide the widgets if no device is selected
452 channels_button_action_->setVisible(!!device);
454 configure_button_action_->setVisible(false);
455 sample_count_.show_none();
456 sample_rate_.show_none();
460 const shared_ptr<sigrok::Device> sr_dev = device->device();
464 // Update the configure popup
465 DeviceOptions *const opts = new DeviceOptions(sr_dev, this);
466 configure_button_action_->setVisible(
467 !opts->binding().properties().empty());
468 configure_button_.set_popup(opts);
470 // Update the channels popup
471 Channels *const channels = new Channels(session_, this);
472 channels_button_.set_popup(channels);
474 // Update supported options.
475 sample_count_supported_ = false;
477 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::SET))
478 sample_count_supported_ = true;
480 if (sr_dev->config_check(ConfigKey::LIMIT_FRAMES, Capability::SET)) {
481 sr_dev->config_set(ConfigKey::LIMIT_FRAMES,
482 Glib::Variant<guint64>::create(1));
486 // Add notification of reconfigure events
487 disconnect(this, SLOT(on_config_changed()));
488 connect(&opts->binding(), SIGNAL(config_changed()),
489 this, SLOT(on_config_changed()));
491 // Update sweep timing widgets.
492 update_sample_count_selector();
493 update_sample_rate_selector();
496 void MainBar::commit_sample_rate()
498 uint64_t sample_rate = 0;
500 const shared_ptr<devices::Device> device =
501 device_selector_.selected_device();
505 const shared_ptr<sigrok::Device> sr_dev = device->device();
507 sample_rate = sample_rate_.value();
508 if (sample_rate == 0)
512 sr_dev->config_set(ConfigKey::SAMPLERATE,
513 Glib::Variant<guint64>::create(sample_rate));
514 update_sample_rate_selector();
515 } catch (Error error) {
516 qDebug() << "Failed to configure samplerate.";
520 // Devices with built-in memory might impose limits on certain
521 // configurations, so let's check what sample count the driver
523 update_sample_count_selector();
526 void MainBar::commit_sample_count()
528 uint64_t sample_count = 0;
530 const shared_ptr<devices::Device> device =
531 device_selector_.selected_device();
535 const shared_ptr<sigrok::Device> sr_dev = device->device();
537 sample_count = sample_count_.value();
538 if (sample_count_supported_) {
540 sr_dev->config_set(ConfigKey::LIMIT_SAMPLES,
541 Glib::Variant<guint64>::create(sample_count));
542 update_sample_count_selector();
543 } catch (Error error) {
544 qDebug() << "Failed to configure sample count.";
549 // Devices with built-in memory might impose limits on certain
550 // configurations, so let's check what sample rate the driver
552 update_sample_rate_selector();
555 void MainBar::session_error(const QString text, const QString info_text)
557 QMetaObject::invokeMethod(this, "show_session_error",
558 Qt::QueuedConnection, Q_ARG(QString, text),
559 Q_ARG(QString, info_text));
562 void MainBar::show_session_error(const QString text, const QString info_text)
564 QMessageBox msg(this);
566 msg.setInformativeText(info_text);
567 msg.setStandardButtons(QMessageBox::Ok);
568 msg.setIcon(QMessageBox::Warning);
572 void MainBar::add_decoder(srd_decoder *decoder)
576 session_.add_decoder(decoder);
582 void MainBar::export_file(shared_ptr<OutputFormat> format, bool selection_only)
584 using pv::dialogs::StoreProgress;
586 // Stop any currently running capture session
587 session_.stop_capture();
590 const QString dir = settings.value(SettingSaveDirectory).toString();
592 pair<uint64_t, uint64_t> sample_range;
594 // Selection only? Verify that the cursors are active and fetch their values
595 if (selection_only) {
596 views::TraceView::View *trace_view =
597 qobject_cast<views::TraceView::View*>(session_.main_view().get());
599 if (!trace_view->cursors()->enabled()) {
600 show_session_error(tr("Missing Cursors"), tr("You need to set the " \
601 "cursors before you can save the data enclosed by them " \
602 "to a session file (e.g. using the Show Cursors button)."));
606 const double samplerate = session_.get_samplerate();
608 const pv::util::Timestamp& start_time = trace_view->cursors()->first()->time();
609 const pv::util::Timestamp& end_time = trace_view->cursors()->second()->time();
611 const uint64_t start_sample = (uint64_t)max(
612 (double)0, start_time.convert_to<double>() * samplerate);
613 const uint64_t end_sample = (uint64_t)max(
614 (double)0, end_time.convert_to<double>() * samplerate);
616 sample_range = make_pair(start_sample, end_sample);
618 sample_range = make_pair(0, 0);
621 // Construct the filter
622 const vector<string> exts = format->extensions();
623 QString filter = tr("%1 files ").arg(
624 QString::fromStdString(format->description()));
629 filter += QString("(*.%1);;%2 (*.*)").arg(
630 QString::fromStdString(join(exts, ", *.")),
633 // Show the file dialog
634 const QString file_name = QFileDialog::getSaveFileName(
635 this, tr("Save File"), dir, filter);
637 if (file_name.isEmpty())
640 const QString abs_path = QFileInfo(file_name).absolutePath();
641 settings.setValue(SettingSaveDirectory, abs_path);
643 // Show the options dialog
644 map<string, Glib::VariantBase> options;
645 if (!format->options().empty()) {
646 dialogs::InputOutputOptions dlg(
647 tr("Export %1").arg(QString::fromStdString(
648 format->description())),
649 format->options(), this);
652 options = dlg.options();
656 session_.set_name(QFileInfo(file_name).fileName());
658 StoreProgress *dlg = new StoreProgress(file_name, format, options,
659 sample_range, session_, this);
663 void MainBar::import_file(shared_ptr<InputFormat> format)
668 const QString dir = settings.value(SettingOpenDirectory).toString();
670 // Construct the filter
671 const vector<string> exts = format->extensions();
672 const QString filter = exts.empty() ? "" :
673 tr("%1 files (*.%2)").arg(
674 QString::fromStdString(format->description()),
675 QString::fromStdString(join(exts, ", *.")));
677 // Show the file dialog
678 const QString file_name = QFileDialog::getOpenFileName(
679 this, tr("Import File"), dir, tr(
680 "%1 files (*.*);;All Files (*.*)").arg(
681 QString::fromStdString(format->description())));
683 if (file_name.isEmpty())
686 // Show the options dialog
687 map<string, Glib::VariantBase> options;
688 if (!format->options().empty()) {
689 dialogs::InputOutputOptions dlg(
690 tr("Import %1").arg(QString::fromStdString(
691 format->description())),
692 format->options(), this);
695 options = dlg.options();
698 session_.load_file(file_name, format, options);
700 const QString abs_path = QFileInfo(file_name).absolutePath();
701 settings.setValue(SettingOpenDirectory, abs_path);
704 void MainBar::on_device_selected()
706 shared_ptr<devices::Device> device = device_selector_.selected_device();
708 reset_device_selector();
712 session_.select_device(device);
715 void MainBar::on_device_changed()
717 update_device_list();
718 update_device_config_widgets();
721 void MainBar::on_capture_state_changed(int state)
723 set_capture_state((pv::Session::capture_state)state);
726 void MainBar::on_sample_count_changed()
728 if (!updating_sample_count_)
729 commit_sample_count();
732 void MainBar::on_sample_rate_changed()
734 if (!updating_sample_rate_)
735 commit_sample_rate();
738 void MainBar::on_config_changed()
740 commit_sample_count();
741 commit_sample_rate();
744 void MainBar::on_actionNewView_triggered()
749 void MainBar::on_actionOpen_triggered()
752 const QString dir = settings.value(SettingOpenDirectory).toString();
755 const QString file_name = QFileDialog::getOpenFileName(
756 this, tr("Open File"), dir, tr(
757 "Sigrok Sessions (*.sr);;"
760 if (!file_name.isEmpty()) {
761 session_.load_file(file_name);
763 const QString abs_path = QFileInfo(file_name).absolutePath();
764 settings.setValue(SettingOpenDirectory, abs_path);
768 void MainBar::on_actionSaveAs_triggered()
770 export_file(session_.device_manager().context()->output_formats()["srzip"]);
773 void MainBar::on_actionSaveSelectionAs_triggered()
775 export_file(session_.device_manager().context()->output_formats()["srzip"], true);
778 void MainBar::on_actionConnect_triggered()
780 // Stop any currently running capture session
781 session_.stop_capture();
783 dialogs::Connect dlg(this, session_.device_manager());
785 // If the user selected a device, select it in the device list. Select the
786 // current device otherwise.
788 session_.select_device(dlg.get_selected_device());
790 update_device_list();
793 void MainBar::add_toolbar_widgets()
795 addAction(action_new_view_);
797 addWidget(open_button_);
798 addWidget(save_button_);
801 StandardBar::add_toolbar_widgets();
803 addWidget(&device_selector_);
804 configure_button_action_ = addWidget(&configure_button_);
805 channels_button_action_ = addWidget(&channels_button_);
806 addWidget(&sample_count_);
807 addWidget(&sample_rate_);
810 addWidget(add_decoder_button_);
814 bool MainBar::eventFilter(QObject *watched, QEvent *event)
816 if (sample_count_supported_ && (watched == &sample_count_ ||
817 watched == &sample_rate_) &&
818 (event->type() == QEvent::ToolTip)) {
819 auto sec = pv::util::Timestamp(sample_count_.value()) / sample_rate_.value();
820 QHelpEvent *help_event = static_cast<QHelpEvent*>(event);
822 QString str = tr("Total sampling time: %1").arg(
823 pv::util::format_time_si(sec, pv::util::SIPrefix::unspecified, 0, "s", false));
824 QToolTip::showText(help_event->globalPos(), str);
832 } // namespace toolbars