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/views/trace/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::trace::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"));
117 setContextMenuPolicy(Qt::PreventContextMenu);
120 action_new_view_->setText(tr("New &View"));
121 action_new_view_->setIcon(QIcon::fromTheme("window-new",
122 QIcon(":/icons/window-new.png")));
123 connect(action_new_view_, SIGNAL(triggered(bool)),
124 this, SLOT(on_actionNewView_triggered()));
126 action_open_->setText(tr("&Open..."));
127 action_open_->setIcon(QIcon::fromTheme("document-open",
128 QIcon(":/icons/document-open.png")));
129 action_open_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O));
130 connect(action_open_, SIGNAL(triggered(bool)),
131 this, SLOT(on_actionOpen_triggered()));
133 action_save_as_->setText(tr("&Save As..."));
134 action_save_as_->setIcon(QIcon::fromTheme("document-save-as",
135 QIcon(":/icons/document-save-as.png")));
136 action_save_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
137 connect(action_save_as_, SIGNAL(triggered(bool)),
138 this, SLOT(on_actionSaveAs_triggered()));
140 action_save_selection_as_->setText(tr("Save Selected &Range As..."));
141 action_save_selection_as_->setIcon(QIcon::fromTheme("document-save-as",
142 QIcon(":/icons/document-save-as.png")));
143 action_save_selection_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
144 connect(action_save_selection_as_, SIGNAL(triggered(bool)),
145 this, SLOT(on_actionSaveSelectionAs_triggered()));
147 widgets::ExportMenu *menu_file_export = new widgets::ExportMenu(this,
148 session.device_manager().context());
149 menu_file_export->setTitle(tr("&Export"));
150 connect(menu_file_export,
151 SIGNAL(format_selected(shared_ptr<sigrok::OutputFormat>)),
152 this, SLOT(export_file(shared_ptr<sigrok::OutputFormat>)));
154 widgets::ImportMenu *menu_file_import = new widgets::ImportMenu(this,
155 session.device_manager().context());
156 menu_file_import->setTitle(tr("&Import"));
157 connect(menu_file_import,
158 SIGNAL(format_selected(shared_ptr<sigrok::InputFormat>)),
159 this, SLOT(import_file(shared_ptr<sigrok::InputFormat>)));
161 action_connect_->setText(tr("&Connect to Device..."));
162 connect(action_connect_, SIGNAL(triggered(bool)),
163 this, SLOT(on_actionConnect_triggered()));
166 widgets::ImportMenu *import_menu = new widgets::ImportMenu(this,
167 session.device_manager().context(), action_open_);
169 SIGNAL(format_selected(shared_ptr<sigrok::InputFormat>)),
171 SLOT(import_file(shared_ptr<sigrok::InputFormat>)));
173 open_button_->setMenu(import_menu);
174 open_button_->setDefaultAction(action_open_);
175 open_button_->setPopupMode(QToolButton::MenuButtonPopup);
178 vector<QAction *> open_actions;
179 open_actions.push_back(action_save_as_);
180 open_actions.push_back(action_save_selection_as_);
182 widgets::ExportMenu *export_menu = new widgets::ExportMenu(this,
183 session.device_manager().context(),
186 SIGNAL(format_selected(shared_ptr<sigrok::OutputFormat>)),
188 SLOT(export_file(shared_ptr<sigrok::OutputFormat>)));
190 save_button_->setMenu(export_menu);
191 save_button_->setDefaultAction(action_save_as_);
192 save_button_->setPopupMode(QToolButton::MenuButtonPopup);
194 // Device selector menu
195 connect(&device_selector_, SIGNAL(device_selected()),
196 this, SLOT(on_device_selected()));
198 // Setup the decoder button
200 menu_decoders_add_->setTitle(tr("&Add"));
201 connect(menu_decoders_add_, SIGNAL(decoder_selected(srd_decoder*)),
202 this, SLOT(add_decoder(srd_decoder*)));
204 add_decoder_button_->setIcon(QIcon(":/icons/add-decoder.svg"));
205 add_decoder_button_->setPopupMode(QToolButton::InstantPopup);
206 add_decoder_button_->setMenu(menu_decoders_add_);
207 add_decoder_button_->setToolTip(tr("Add low-level, non-stacked protocol decoder"));
210 connect(&sample_count_, SIGNAL(value_changed()),
211 this, SLOT(on_sample_count_changed()));
212 connect(&sample_rate_, SIGNAL(value_changed()),
213 this, SLOT(on_sample_rate_changed()));
215 sample_count_.show_min_max_step(0, UINT64_MAX, 1);
217 set_capture_state(pv::Session::Stopped);
219 configure_button_.setToolTip(tr("Configure Device"));
220 configure_button_.setIcon(QIcon::fromTheme("preferences-system",
221 QIcon(":/icons/preferences-system.png")));
223 channels_button_.setToolTip(tr("Configure Channels"));
224 channels_button_.setIcon(QIcon(":/icons/channels.svg"));
226 add_toolbar_widgets();
228 sample_count_.installEventFilter(this);
229 sample_rate_.installEventFilter(this);
231 // Setup session_ events
232 connect(&session_, SIGNAL(capture_state_changed(int)),
233 this, SLOT(on_capture_state_changed(int)));
234 connect(&session, SIGNAL(device_changed()),
235 this, SLOT(on_device_changed()));
237 update_device_list();
240 void MainBar::update_device_list()
242 DeviceManager &mgr = session_.device_manager();
243 shared_ptr<devices::Device> selected_device = session_.device();
244 list< shared_ptr<devices::Device> > devs;
246 copy(mgr.devices().begin(), mgr.devices().end(), back_inserter(devs));
248 if (std::find(devs.begin(), devs.end(), selected_device) == devs.end())
249 devs.push_back(selected_device);
251 device_selector_.set_device_list(devs, selected_device);
252 update_device_config_widgets();
255 void MainBar::set_capture_state(pv::Session::capture_state state)
257 bool ui_enabled = (state == pv::Session::Stopped) ? true : false;
259 device_selector_.setEnabled(ui_enabled);
260 configure_button_.setEnabled(ui_enabled);
261 channels_button_.setEnabled(ui_enabled);
262 sample_count_.setEnabled(ui_enabled);
263 sample_rate_.setEnabled(ui_enabled);
266 void MainBar::reset_device_selector()
268 device_selector_.reset();
271 QAction* MainBar::action_open() const
276 QAction* MainBar::action_save_as() const
278 return action_save_as_;
281 QAction* MainBar::action_save_selection_as() const
283 return action_save_selection_as_;
286 QAction* MainBar::action_connect() const
288 return action_connect_;
291 void MainBar::update_sample_rate_selector()
293 Glib::VariantContainerBase gvar_dict;
295 const uint64_t *elements = nullptr;
297 map< const ConfigKey*, set<Capability> > keys;
299 if (updating_sample_rate_) {
300 sample_rate_.show_none();
304 const shared_ptr<devices::Device> device =
305 device_selector_.selected_device();
309 assert(!updating_sample_rate_);
310 updating_sample_rate_ = true;
312 const shared_ptr<sigrok::Device> sr_dev = device->device();
314 if (sr_dev->config_check(ConfigKey::SAMPLERATE, Capability::LIST)) {
315 gvar_dict = sr_dev->config_list(ConfigKey::SAMPLERATE);
317 sample_rate_.show_none();
318 updating_sample_rate_ = false;
322 if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
323 "samplerate-steps", G_VARIANT_TYPE("at")))) {
324 elements = (const uint64_t *)g_variant_get_fixed_array(
325 gvar_list, &num_elements, sizeof(uint64_t));
327 const uint64_t min = elements[0];
328 const uint64_t max = elements[1];
329 const uint64_t step = elements[2];
331 g_variant_unref(gvar_list);
339 sample_rate_.show_125_list(min, max);
341 // When the step is not 1, we cam't make a 1-2-5-10
342 // list of sample rates, because we may not be able to
343 // make round numbers. Therefore in this case, show a
345 sample_rate_.show_min_max_step(min, max, step);
347 } else if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
348 "samplerates", G_VARIANT_TYPE("at")))) {
349 elements = (const uint64_t *)g_variant_get_fixed_array(
350 gvar_list, &num_elements, sizeof(uint64_t));
351 sample_rate_.show_list(elements, num_elements);
352 g_variant_unref(gvar_list);
354 updating_sample_rate_ = false;
356 update_sample_rate_selector_value();
359 void MainBar::update_sample_rate_selector_value()
361 if (updating_sample_rate_)
364 const shared_ptr<devices::Device> device =
365 device_selector_.selected_device();
370 auto gvar = device->device()->config_get(ConfigKey::SAMPLERATE);
371 uint64_t samplerate =
372 Glib::VariantBase::cast_dynamic<Glib::Variant<guint64>>(gvar).get();
373 assert(!updating_sample_rate_);
374 updating_sample_rate_ = true;
375 sample_rate_.set_value(samplerate);
376 updating_sample_rate_ = false;
377 } catch (Error error) {
378 qDebug() << "WARNING: Failed to get value of sample rate";
383 void MainBar::update_sample_count_selector()
385 if (updating_sample_count_)
388 const shared_ptr<devices::Device> device =
389 device_selector_.selected_device();
393 const shared_ptr<sigrok::Device> sr_dev = device->device();
395 assert(!updating_sample_count_);
396 updating_sample_count_ = true;
398 if (!sample_count_supported_) {
399 sample_count_.show_none();
400 updating_sample_count_ = false;
404 uint64_t sample_count = sample_count_.value();
405 uint64_t min_sample_count = 0;
406 uint64_t max_sample_count = MaxSampleCount;
407 bool default_count_set = false;
409 if (sample_count == 0) {
410 sample_count = DefaultSampleCount;
411 default_count_set = true;
414 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::LIST)) {
415 auto gvar = sr_dev->config_list(ConfigKey::LIMIT_SAMPLES);
417 g_variant_get(gvar.gobj(), "(tt)",
418 &min_sample_count, &max_sample_count);
421 min_sample_count = min(max(min_sample_count, MinSampleCount),
424 sample_count_.show_125_list(min_sample_count, max_sample_count);
426 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::GET)) {
427 auto gvar = sr_dev->config_get(ConfigKey::LIMIT_SAMPLES);
428 sample_count = g_variant_get_uint64(gvar.gobj());
429 if (sample_count == 0) {
430 sample_count = DefaultSampleCount;
431 default_count_set = true;
433 sample_count = min(max(sample_count, MinSampleCount),
437 sample_count_.set_value(sample_count);
439 updating_sample_count_ = false;
441 // If we show the default rate then make sure the device uses the same
442 if (default_count_set)
443 commit_sample_count();
446 void MainBar::update_device_config_widgets()
448 using namespace pv::popups;
450 const shared_ptr<devices::Device> device =
451 device_selector_.selected_device();
453 // Hide the widgets if no device is selected
454 channels_button_action_->setVisible(!!device);
456 configure_button_action_->setVisible(false);
457 sample_count_.show_none();
458 sample_rate_.show_none();
462 const shared_ptr<sigrok::Device> sr_dev = device->device();
466 // Update the configure popup
467 DeviceOptions *const opts = new DeviceOptions(sr_dev, this);
468 configure_button_action_->setVisible(
469 !opts->binding().properties().empty());
470 configure_button_.set_popup(opts);
472 // Update the channels popup
473 Channels *const channels = new Channels(session_, this);
474 channels_button_.set_popup(channels);
476 // Update supported options.
477 sample_count_supported_ = false;
479 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::SET))
480 sample_count_supported_ = true;
482 if (sr_dev->config_check(ConfigKey::LIMIT_FRAMES, Capability::SET)) {
483 sr_dev->config_set(ConfigKey::LIMIT_FRAMES,
484 Glib::Variant<guint64>::create(1));
488 // Add notification of reconfigure events
489 disconnect(this, SLOT(on_config_changed()));
490 connect(&opts->binding(), SIGNAL(config_changed()),
491 this, SLOT(on_config_changed()));
493 // Update sweep timing widgets.
494 update_sample_count_selector();
495 update_sample_rate_selector();
498 void MainBar::commit_sample_rate()
500 uint64_t sample_rate = 0;
502 const shared_ptr<devices::Device> device =
503 device_selector_.selected_device();
507 const shared_ptr<sigrok::Device> sr_dev = device->device();
509 sample_rate = sample_rate_.value();
510 if (sample_rate == 0)
514 sr_dev->config_set(ConfigKey::SAMPLERATE,
515 Glib::Variant<guint64>::create(sample_rate));
516 update_sample_rate_selector();
517 } catch (Error error) {
518 qDebug() << "Failed to configure samplerate.";
522 // Devices with built-in memory might impose limits on certain
523 // configurations, so let's check what sample count the driver
525 update_sample_count_selector();
528 void MainBar::commit_sample_count()
530 uint64_t sample_count = 0;
532 const shared_ptr<devices::Device> device =
533 device_selector_.selected_device();
537 const shared_ptr<sigrok::Device> sr_dev = device->device();
539 sample_count = sample_count_.value();
540 if (sample_count_supported_) {
542 sr_dev->config_set(ConfigKey::LIMIT_SAMPLES,
543 Glib::Variant<guint64>::create(sample_count));
544 update_sample_count_selector();
545 } catch (Error error) {
546 qDebug() << "Failed to configure sample count.";
551 // Devices with built-in memory might impose limits on certain
552 // configurations, so let's check what sample rate the driver
554 update_sample_rate_selector();
557 void MainBar::session_error(const QString text, const QString info_text)
559 QMetaObject::invokeMethod(this, "show_session_error",
560 Qt::QueuedConnection, Q_ARG(QString, text),
561 Q_ARG(QString, info_text));
564 void MainBar::show_session_error(const QString text, const QString info_text)
566 QMessageBox msg(this);
568 msg.setInformativeText(info_text);
569 msg.setStandardButtons(QMessageBox::Ok);
570 msg.setIcon(QMessageBox::Warning);
574 void MainBar::add_decoder(srd_decoder *decoder)
578 session_.add_decoder(decoder);
584 void MainBar::export_file(shared_ptr<OutputFormat> format, bool selection_only)
586 using pv::dialogs::StoreProgress;
588 // Stop any currently running capture session
589 session_.stop_capture();
592 const QString dir = settings.value(SettingSaveDirectory).toString();
594 pair<uint64_t, uint64_t> sample_range;
596 // Selection only? Verify that the cursors are active and fetch their values
597 if (selection_only) {
598 views::trace::View *trace_view =
599 qobject_cast<views::trace::View*>(session_.main_view().get());
601 if (!trace_view->cursors()->enabled()) {
602 show_session_error(tr("Missing Cursors"), tr("You need to set the " \
603 "cursors before you can save the data enclosed by them " \
604 "to a session file (e.g. using the Show Cursors button)."));
608 const double samplerate = session_.get_samplerate();
610 const pv::util::Timestamp& start_time = trace_view->cursors()->first()->time();
611 const pv::util::Timestamp& end_time = trace_view->cursors()->second()->time();
613 const uint64_t start_sample = (uint64_t)max(
614 (double)0, start_time.convert_to<double>() * samplerate);
615 const uint64_t end_sample = (uint64_t)max(
616 (double)0, end_time.convert_to<double>() * samplerate);
618 sample_range = make_pair(start_sample, end_sample);
620 sample_range = make_pair(0, 0);
623 // Construct the filter
624 const vector<string> exts = format->extensions();
625 QString filter = tr("%1 files ").arg(
626 QString::fromStdString(format->description()));
631 filter += QString("(*.%1);;%2 (*)").arg(
632 QString::fromStdString(join(exts, ", *.")),
635 // Show the file dialog
636 const QString file_name = QFileDialog::getSaveFileName(
637 this, tr("Save File"), dir, filter);
639 if (file_name.isEmpty())
642 const QString abs_path = QFileInfo(file_name).absolutePath();
643 settings.setValue(SettingSaveDirectory, abs_path);
645 // Show the options dialog
646 map<string, Glib::VariantBase> options;
647 if (!format->options().empty()) {
648 dialogs::InputOutputOptions dlg(
649 tr("Export %1").arg(QString::fromStdString(
650 format->description())),
651 format->options(), this);
654 options = dlg.options();
658 session_.set_name(QFileInfo(file_name).fileName());
660 StoreProgress *dlg = new StoreProgress(file_name, format, options,
661 sample_range, session_, this);
665 void MainBar::import_file(shared_ptr<InputFormat> format)
670 const QString dir = settings.value(SettingOpenDirectory).toString();
672 // Construct the filter
673 const vector<string> exts = format->extensions();
674 const QString filter = exts.empty() ? "" :
675 tr("%1 files (*.%2)").arg(
676 QString::fromStdString(format->description()),
677 QString::fromStdString(join(exts, ", *.")));
679 // Show the file dialog
680 const QString file_name = QFileDialog::getOpenFileName(
681 this, tr("Import File"), dir, tr(
682 "%1 files (*);;All Files (*)").arg(
683 QString::fromStdString(format->description())));
685 if (file_name.isEmpty())
688 // Show the options dialog
689 map<string, Glib::VariantBase> options;
690 if (!format->options().empty()) {
691 dialogs::InputOutputOptions dlg(
692 tr("Import %1").arg(QString::fromStdString(
693 format->description())),
694 format->options(), this);
697 options = dlg.options();
700 session_.load_file(file_name, format, options);
702 const QString abs_path = QFileInfo(file_name).absolutePath();
703 settings.setValue(SettingOpenDirectory, abs_path);
706 void MainBar::on_device_selected()
708 shared_ptr<devices::Device> device = device_selector_.selected_device();
710 reset_device_selector();
714 session_.select_device(device);
717 void MainBar::on_device_changed()
719 update_device_list();
720 update_device_config_widgets();
723 void MainBar::on_capture_state_changed(int state)
725 set_capture_state((pv::Session::capture_state)state);
728 void MainBar::on_sample_count_changed()
730 if (!updating_sample_count_)
731 commit_sample_count();
734 void MainBar::on_sample_rate_changed()
736 if (!updating_sample_rate_)
737 commit_sample_rate();
740 void MainBar::on_config_changed()
742 commit_sample_count();
743 commit_sample_rate();
746 void MainBar::on_actionNewView_triggered()
751 void MainBar::on_actionOpen_triggered()
754 const QString dir = settings.value(SettingOpenDirectory).toString();
757 const QString file_name = QFileDialog::getOpenFileName(
758 this, tr("Open File"), dir, tr(
759 "sigrok Sessions (*.sr);;"
762 if (!file_name.isEmpty()) {
763 session_.load_file(file_name);
765 const QString abs_path = QFileInfo(file_name).absolutePath();
766 settings.setValue(SettingOpenDirectory, abs_path);
770 void MainBar::on_actionSaveAs_triggered()
772 export_file(session_.device_manager().context()->output_formats()["srzip"]);
775 void MainBar::on_actionSaveSelectionAs_triggered()
777 export_file(session_.device_manager().context()->output_formats()["srzip"], true);
780 void MainBar::on_actionConnect_triggered()
782 // Stop any currently running capture session
783 session_.stop_capture();
785 dialogs::Connect dlg(this, session_.device_manager());
787 // If the user selected a device, select it in the device list. Select the
788 // current device otherwise.
790 session_.select_device(dlg.get_selected_device());
792 update_device_list();
795 void MainBar::add_toolbar_widgets()
797 addAction(action_new_view_);
799 addWidget(open_button_);
800 addWidget(save_button_);
803 StandardBar::add_toolbar_widgets();
805 addWidget(&device_selector_);
806 configure_button_action_ = addWidget(&configure_button_);
807 channels_button_action_ = addWidget(&channels_button_);
808 addWidget(&sample_count_);
809 addWidget(&sample_rate_);
812 addWidget(add_decoder_button_);
816 bool MainBar::eventFilter(QObject *watched, QEvent *event)
818 if (sample_count_supported_ && (watched == &sample_count_ ||
819 watched == &sample_rate_) &&
820 (event->type() == QEvent::ToolTip)) {
821 auto sec = pv::util::Timestamp(sample_count_.value()) / sample_rate_.value();
822 QHelpEvent *help_event = static_cast<QHelpEvent*>(event);
824 QString str = tr("Total sampling time: %1").arg(
825 pv::util::format_time_si(sec, pv::util::SIPrefix::unspecified, 0, "s", false));
826 QToolTip::showText(help_event->globalPos(), str);
834 } // namespace toolbars