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/deviceoptions.hpp>
47 #include <pv/popups/channels.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;
69 using std::shared_ptr;
73 using sigrok::Capability;
74 using sigrok::ConfigKey;
76 using sigrok::InputFormat;
77 using sigrok::OutputFormat;
79 using boost::algorithm::join;
84 const uint64_t MainBar::MinSampleCount = 100ULL;
85 const uint64_t MainBar::MaxSampleCount = 1000000000000ULL;
86 const uint64_t MainBar::DefaultSampleCount = 1000000;
88 const char *MainBar::SettingOpenDirectory = "MainWindow/OpenDirectory";
89 const char *MainBar::SettingSaveDirectory = "MainWindow/SaveDirectory";
91 MainBar::MainBar(Session &session, QWidget *parent,
92 pv::views::TraceView::View *view) :
93 StandardBar(session, parent, view, false),
94 action_new_view_(new QAction(this)),
95 action_open_(new QAction(this)),
96 action_save_as_(new QAction(this)),
97 action_save_selection_as_(new QAction(this)),
98 action_connect_(new QAction(this)),
99 open_button_(new QToolButton()),
100 save_button_(new QToolButton()),
101 device_selector_(parent, session.device_manager(),
103 configure_button_(this),
104 configure_button_action_(nullptr),
105 channels_button_(this),
106 channels_button_action_(nullptr),
107 sample_count_(" samples", this),
108 sample_rate_("Hz", this),
109 updating_sample_rate_(false),
110 updating_sample_count_(false),
111 sample_count_supported_(false)
113 , add_decoder_button_(new QToolButton()),
114 menu_decoders_add_(new pv::widgets::DecoderMenu(this, true))
117 setObjectName(QString::fromUtf8("MainBar"));
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::fromTheme("add-decoder",
205 QIcon(":/icons/add-decoder.svg")));
206 add_decoder_button_->setPopupMode(QToolButton::InstantPopup);
207 add_decoder_button_->setMenu(menu_decoders_add_);
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("configure",
221 QIcon(":/icons/configure.png")));
223 channels_button_.setToolTip(tr("Configure Channels"));
224 channels_button_.setIcon(QIcon::fromTheme("channels",
225 QIcon(":/icons/channels.svg")));
227 add_toolbar_widgets();
229 sample_count_.installEventFilter(this);
230 sample_rate_.installEventFilter(this);
232 // Setup session_ events
233 connect(&session_, SIGNAL(capture_state_changed(int)),
234 this, SLOT(on_capture_state_changed(int)));
235 connect(&session, SIGNAL(device_changed()),
236 this, SLOT(on_device_changed()));
238 update_device_list();
241 void MainBar::update_device_list()
243 DeviceManager &mgr = session_.device_manager();
244 shared_ptr<devices::Device> selected_device = session_.device();
245 list< shared_ptr<devices::Device> > devs;
247 copy(mgr.devices().begin(), mgr.devices().end(), back_inserter(devs));
249 if (std::find(devs.begin(), devs.end(), selected_device) == devs.end())
250 devs.push_back(selected_device);
252 device_selector_.set_device_list(devs, selected_device);
253 update_device_config_widgets();
256 void MainBar::set_capture_state(pv::Session::capture_state state)
258 bool ui_enabled = (state == pv::Session::Stopped) ? true : false;
260 device_selector_.setEnabled(ui_enabled);
261 configure_button_.setEnabled(ui_enabled);
262 channels_button_.setEnabled(ui_enabled);
263 sample_count_.setEnabled(ui_enabled);
264 sample_rate_.setEnabled(ui_enabled);
267 void MainBar::reset_device_selector()
269 device_selector_.reset();
272 QAction* MainBar::action_open() const
277 QAction* MainBar::action_save_as() const
279 return action_save_as_;
282 QAction* MainBar::action_save_selection_as() const
284 return action_save_selection_as_;
287 QAction* MainBar::action_connect() const
289 return action_connect_;
292 void MainBar::update_sample_rate_selector()
294 Glib::VariantContainerBase gvar_dict;
296 const uint64_t *elements = nullptr;
298 map< const ConfigKey*, set<Capability> > keys;
300 if (updating_sample_rate_) {
301 sample_rate_.show_none();
305 const shared_ptr<devices::Device> device =
306 device_selector_.selected_device();
310 assert(!updating_sample_rate_);
311 updating_sample_rate_ = true;
313 const shared_ptr<sigrok::Device> sr_dev = device->device();
315 if (sr_dev->config_check(ConfigKey::SAMPLERATE, Capability::LIST)) {
316 gvar_dict = sr_dev->config_list(ConfigKey::SAMPLERATE);
318 sample_rate_.show_none();
319 updating_sample_rate_ = false;
323 if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
324 "samplerate-steps", G_VARIANT_TYPE("at")))) {
325 elements = (const uint64_t *)g_variant_get_fixed_array(
326 gvar_list, &num_elements, sizeof(uint64_t));
328 const uint64_t min = elements[0];
329 const uint64_t max = elements[1];
330 const uint64_t step = elements[2];
332 g_variant_unref(gvar_list);
340 sample_rate_.show_125_list(min, max);
342 // When the step is not 1, we cam't make a 1-2-5-10
343 // list of sample rates, because we may not be able to
344 // make round numbers. Therefore in this case, show a
346 sample_rate_.show_min_max_step(min, max, step);
348 } else if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
349 "samplerates", G_VARIANT_TYPE("at")))) {
350 elements = (const uint64_t *)g_variant_get_fixed_array(
351 gvar_list, &num_elements, sizeof(uint64_t));
352 sample_rate_.show_list(elements, num_elements);
353 g_variant_unref(gvar_list);
355 updating_sample_rate_ = false;
357 update_sample_rate_selector_value();
360 void MainBar::update_sample_rate_selector_value()
362 if (updating_sample_rate_)
365 const shared_ptr<devices::Device> device =
366 device_selector_.selected_device();
371 auto gvar = device->device()->config_get(ConfigKey::SAMPLERATE);
372 uint64_t samplerate =
373 Glib::VariantBase::cast_dynamic<Glib::Variant<guint64>>(gvar).get();
374 assert(!updating_sample_rate_);
375 updating_sample_rate_ = true;
376 sample_rate_.set_value(samplerate);
377 updating_sample_rate_ = false;
378 } catch (Error error) {
379 qDebug() << "WARNING: Failed to get value of sample rate";
384 void MainBar::update_sample_count_selector()
386 if (updating_sample_count_)
389 const shared_ptr<devices::Device> device =
390 device_selector_.selected_device();
394 const shared_ptr<sigrok::Device> sr_dev = device->device();
396 assert(!updating_sample_count_);
397 updating_sample_count_ = true;
399 if (!sample_count_supported_) {
400 sample_count_.show_none();
401 updating_sample_count_ = false;
405 uint64_t sample_count = sample_count_.value();
406 uint64_t min_sample_count = 0;
407 uint64_t max_sample_count = MaxSampleCount;
408 bool default_count_set = false;
410 if (sample_count == 0) {
411 sample_count = DefaultSampleCount;
412 default_count_set = true;
415 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::LIST)) {
416 auto gvar = sr_dev->config_list(ConfigKey::LIMIT_SAMPLES);
418 g_variant_get(gvar.gobj(), "(tt)",
419 &min_sample_count, &max_sample_count);
422 min_sample_count = min(max(min_sample_count, MinSampleCount),
425 sample_count_.show_125_list(
426 min_sample_count, max_sample_count);
428 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::GET)) {
429 auto gvar = sr_dev->config_get(ConfigKey::LIMIT_SAMPLES);
430 sample_count = g_variant_get_uint64(gvar.gobj());
431 if (sample_count == 0) {
432 sample_count = DefaultSampleCount;
433 default_count_set = true;
435 sample_count = min(max(sample_count, MinSampleCount),
439 sample_count_.set_value(sample_count);
441 updating_sample_count_ = false;
443 // If we show the default rate then make sure the device uses the same
444 if (default_count_set)
445 commit_sample_count();
448 void MainBar::update_device_config_widgets()
450 using namespace pv::popups;
452 const shared_ptr<devices::Device> device =
453 device_selector_.selected_device();
455 // Hide the widgets if no device is selected
456 channels_button_action_->setVisible(!!device);
458 configure_button_action_->setVisible(false);
459 sample_count_.show_none();
460 sample_rate_.show_none();
464 const shared_ptr<sigrok::Device> sr_dev = device->device();
468 // Update the configure popup
469 DeviceOptions *const opts = new DeviceOptions(sr_dev, this);
470 configure_button_action_->setVisible(
471 !opts->binding().properties().empty());
472 configure_button_.set_popup(opts);
474 // Update the channels popup
475 Channels *const channels = new Channels(session_, this);
476 channels_button_.set_popup(channels);
478 // Update supported options.
479 sample_count_supported_ = false;
481 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::SET))
482 sample_count_supported_ = true;
484 if (sr_dev->config_check(ConfigKey::LIMIT_FRAMES, Capability::SET)) {
485 sr_dev->config_set(ConfigKey::LIMIT_FRAMES,
486 Glib::Variant<guint64>::create(1));
490 // Add notification of reconfigure events
491 disconnect(this, SLOT(on_config_changed()));
492 connect(&opts->binding(), SIGNAL(config_changed()),
493 this, SLOT(on_config_changed()));
495 // Update sweep timing widgets.
496 update_sample_count_selector();
497 update_sample_rate_selector();
500 void MainBar::commit_sample_rate()
502 uint64_t sample_rate = 0;
504 const shared_ptr<devices::Device> device =
505 device_selector_.selected_device();
509 const shared_ptr<sigrok::Device> sr_dev = device->device();
511 sample_rate = sample_rate_.value();
512 if (sample_rate == 0)
516 sr_dev->config_set(ConfigKey::SAMPLERATE,
517 Glib::Variant<guint64>::create(sample_rate));
518 update_sample_rate_selector();
519 } catch (Error error) {
520 qDebug() << "Failed to configure samplerate.";
524 // Devices with built-in memory might impose limits on certain
525 // configurations, so let's check what sample count the driver
527 update_sample_count_selector();
530 void MainBar::commit_sample_count()
532 uint64_t sample_count = 0;
534 const shared_ptr<devices::Device> device =
535 device_selector_.selected_device();
539 const shared_ptr<sigrok::Device> sr_dev = device->device();
541 sample_count = sample_count_.value();
542 if (sample_count_supported_) {
544 sr_dev->config_set(ConfigKey::LIMIT_SAMPLES,
545 Glib::Variant<guint64>::create(sample_count));
546 update_sample_count_selector();
547 } catch (Error error) {
548 qDebug() << "Failed to configure sample count.";
553 // Devices with built-in memory might impose limits on certain
554 // configurations, so let's check what sample rate the driver
556 update_sample_rate_selector();
559 void MainBar::session_error(const QString text, const QString info_text)
561 QMetaObject::invokeMethod(this, "show_session_error",
562 Qt::QueuedConnection, Q_ARG(QString, text),
563 Q_ARG(QString, info_text));
566 void MainBar::show_session_error(const QString text, const QString info_text)
568 QMessageBox msg(this);
570 msg.setInformativeText(info_text);
571 msg.setStandardButtons(QMessageBox::Ok);
572 msg.setIcon(QMessageBox::Warning);
576 void MainBar::add_decoder(srd_decoder *decoder)
580 session_.add_decoder(decoder);
586 void MainBar::export_file(shared_ptr<OutputFormat> format,
589 using pv::dialogs::StoreProgress;
591 // Stop any currently running capture session
592 session_.stop_capture();
595 const QString dir = settings.value(SettingSaveDirectory).toString();
597 pair<uint64_t, uint64_t> sample_range;
599 // Selection only? Verify that the cursors are active and fetch their values
600 if (selection_only) {
601 views::TraceView::View *trace_view =
602 qobject_cast<views::TraceView::View*>(session_.main_view().get());
604 if (!trace_view->cursors()->enabled()) {
605 show_session_error(tr("Missing Cursors"), tr("You need to set the " \
606 "cursors before you can save the data enclosed by them " \
607 "to a session file (e.g. using ALT-V - Show Cursors)."));
611 const double samplerate = session_.get_samplerate();
613 const pv::util::Timestamp& start_time = trace_view->cursors()->first()->time();
614 const pv::util::Timestamp& end_time = trace_view->cursors()->second()->time();
616 const uint64_t start_sample = (uint64_t)max(
617 (double)0, start_time.convert_to<double>() * samplerate);
618 const uint64_t end_sample = (uint64_t)max(
619 (double)0, end_time.convert_to<double>() * samplerate);
621 sample_range = make_pair(start_sample, end_sample);
623 sample_range = make_pair(0, 0);
626 // Construct the filter
627 const vector<string> exts = format->extensions();
628 QString filter = tr("%1 files ").arg(
629 QString::fromStdString(format->description()));
634 filter += QString("(*.%1);;%2 (*.*)").arg(
635 QString::fromStdString(join(exts, ", *.")),
638 // Show the file dialog
639 const QString file_name = QFileDialog::getSaveFileName(
640 this, tr("Save File"), dir, filter);
642 if (file_name.isEmpty())
645 const QString abs_path = QFileInfo(file_name).absolutePath();
646 settings.setValue(SettingSaveDirectory, abs_path);
648 // Show the options dialog
649 map<string, Glib::VariantBase> options;
650 if (!format->options().empty()) {
651 dialogs::InputOutputOptions dlg(
652 tr("Export %1").arg(QString::fromStdString(
653 format->description())),
654 format->options(), this);
657 options = dlg.options();
661 session_.set_name(QFileInfo(file_name).fileName());
663 StoreProgress *dlg = new StoreProgress(file_name, format, options,
664 sample_range, session_, this);
668 void MainBar::import_file(shared_ptr<InputFormat> format)
673 const QString dir = settings.value(SettingOpenDirectory).toString();
675 // Construct the filter
676 const vector<string> exts = format->extensions();
677 const QString filter = exts.empty() ? "" :
678 tr("%1 files (*.%2)").arg(
679 QString::fromStdString(format->description()),
680 QString::fromStdString(join(exts, ", *.")));
682 // Show the file dialog
683 const QString file_name = QFileDialog::getOpenFileName(
684 this, tr("Import File"), dir, tr(
685 "%1 files (*.*);;All Files (*.*)").arg(
686 QString::fromStdString(format->description())));
688 if (file_name.isEmpty())
691 // Show the options dialog
692 map<string, Glib::VariantBase> options;
693 if (!format->options().empty()) {
694 dialogs::InputOutputOptions dlg(
695 tr("Import %1").arg(QString::fromStdString(
696 format->description())),
697 format->options(), this);
700 options = dlg.options();
703 session_.load_file(file_name, format, options);
705 const QString abs_path = QFileInfo(file_name).absolutePath();
706 settings.setValue(SettingOpenDirectory, abs_path);
709 void MainBar::on_device_selected()
711 shared_ptr<devices::Device> device = device_selector_.selected_device();
713 reset_device_selector();
717 session_.select_device(device);
720 void MainBar::on_device_changed()
722 update_device_list();
723 update_device_config_widgets();
726 void MainBar::on_capture_state_changed(int state)
728 set_capture_state((pv::Session::capture_state)state);
731 void MainBar::on_sample_count_changed()
733 if (!updating_sample_count_)
734 commit_sample_count();
737 void MainBar::on_sample_rate_changed()
739 if (!updating_sample_rate_)
740 commit_sample_rate();
743 void MainBar::on_config_changed()
745 commit_sample_count();
746 commit_sample_rate();
749 void MainBar::on_actionNewView_triggered()
754 void MainBar::on_actionOpen_triggered()
757 const QString dir = settings.value(SettingOpenDirectory).toString();
760 const QString file_name = QFileDialog::getOpenFileName(
761 this, tr("Open File"), dir, tr(
762 "Sigrok Sessions (*.sr);;"
765 if (!file_name.isEmpty()) {
766 session_.load_file(file_name);
768 const QString abs_path = QFileInfo(file_name).absolutePath();
769 settings.setValue(SettingOpenDirectory, abs_path);
773 void MainBar::on_actionSaveAs_triggered()
775 export_file(session_.device_manager().context()->output_formats()["srzip"]);
778 void MainBar::on_actionSaveSelectionAs_triggered()
780 export_file(session_.device_manager().context()->output_formats()["srzip"], true);
783 void MainBar::on_actionConnect_triggered()
785 // Stop any currently running capture session
786 session_.stop_capture();
788 dialogs::Connect dlg(this, session_.device_manager());
790 // If the user selected a device, select it in the device list. Select the
791 // current device otherwise.
793 session_.select_device(dlg.get_selected_device());
795 update_device_list();
798 void MainBar::add_toolbar_widgets()
800 addAction(action_new_view_);
802 addWidget(open_button_);
803 addWidget(save_button_);
806 StandardBar::add_toolbar_widgets();
808 addWidget(&device_selector_);
809 configure_button_action_ = addWidget(&configure_button_);
810 channels_button_action_ = addWidget(&channels_button_);
811 addWidget(&sample_count_);
812 addWidget(&sample_rate_);
815 addWidget(add_decoder_button_);
819 bool MainBar::eventFilter(QObject *watched, QEvent *event)
821 if (sample_count_supported_ && (watched == &sample_count_ ||
822 watched == &sample_rate_) &&
823 (event->type() == QEvent::ToolTip)) {
824 auto sec = pv::util::Timestamp(sample_count_.value()) / sample_rate_.value();
825 QHelpEvent *help_event = static_cast<QHelpEvent*>(event);
827 QString str = tr("Total sampling time: %1").arg(
828 pv::util::format_time_si(sec, pv::util::SIPrefix::unspecified, 0, "s", false));
829 QToolTip::showText(help_event->globalPos(), str);
837 } // namespace toolbars