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, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
28 #include <QFileDialog>
31 #include <QMessageBox>
35 #include "mainbar.hpp"
37 #include <boost/algorithm/string/join.hpp>
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>
54 #include <pv/widgets/decodermenu.hpp>
57 #include <libsigrokcxx/libsigrokcxx.hpp>
59 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(std::shared_ptr<sigrok::OutputFormat>)),
150 this, SLOT(export_file(std::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(std::shared_ptr<sigrok::InputFormat>)),
157 this, SLOT(import_file(std::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(std::shared_ptr<sigrok::InputFormat>)),
169 SLOT(import_file(std::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(std::shared_ptr<sigrok::OutputFormat>)),
186 SLOT(export_file(std::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::fromTheme("add-decoder",
203 QIcon(":/icons/add-decoder.svg")));
204 add_decoder_button_->setPopupMode(QToolButton::InstantPopup);
205 add_decoder_button_->setMenu(menu_decoders_add_);
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_.setIcon(QIcon::fromTheme("configure",
218 QIcon(":/icons/configure.png")));
220 channels_button_.setIcon(QIcon::fromTheme("channels",
221 QIcon(":/icons/channels.svg")));
223 add_toolbar_widgets();
225 sample_count_.installEventFilter(this);
226 sample_rate_.installEventFilter(this);
228 // Setup session_ events
229 connect(&session_, SIGNAL(capture_state_changed(int)),
230 this, SLOT(on_capture_state_changed(int)));
231 connect(&session, SIGNAL(device_changed()),
232 this, SLOT(on_device_changed()));
234 update_device_list();
237 void MainBar::update_device_list()
239 DeviceManager &mgr = session_.device_manager();
240 shared_ptr<devices::Device> selected_device = session_.device();
241 list< shared_ptr<devices::Device> > devs;
243 copy(mgr.devices().begin(), mgr.devices().end(), back_inserter(devs));
245 if (std::find(devs.begin(), devs.end(), selected_device) == devs.end())
246 devs.push_back(selected_device);
248 device_selector_.set_device_list(devs, selected_device);
249 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*, std::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;
406 if (sample_count == 0)
407 sample_count = DefaultSampleCount;
409 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::LIST)) {
410 auto gvar = sr_dev->config_list(ConfigKey::LIMIT_SAMPLES);
412 g_variant_get(gvar.gobj(), "(tt)",
413 &min_sample_count, &max_sample_count);
416 min_sample_count = min(max(min_sample_count, MinSampleCount),
419 sample_count_.show_125_list(
420 min_sample_count, max_sample_count);
422 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::GET)) {
423 auto gvar = sr_dev->config_get(ConfigKey::LIMIT_SAMPLES);
424 sample_count = g_variant_get_uint64(gvar.gobj());
425 if (sample_count == 0)
426 sample_count = DefaultSampleCount;
427 sample_count = min(max(sample_count, MinSampleCount),
431 sample_count_.set_value(sample_count);
433 updating_sample_count_ = false;
436 void MainBar::update_device_config_widgets()
438 using namespace pv::popups;
440 const shared_ptr<devices::Device> device =
441 device_selector_.selected_device();
443 // Hide the widgets if no device is selected
444 channels_button_action_->setVisible(!!device);
446 configure_button_action_->setVisible(false);
447 sample_count_.show_none();
448 sample_rate_.show_none();
452 const shared_ptr<sigrok::Device> sr_dev = device->device();
456 // Update the configure popup
457 DeviceOptions *const opts = new DeviceOptions(sr_dev, this);
458 configure_button_action_->setVisible(
459 !opts->binding().properties().empty());
460 configure_button_.set_popup(opts);
462 // Update the channels popup
463 Channels *const channels = new Channels(session_, this);
464 channels_button_.set_popup(channels);
466 // Update supported options.
467 sample_count_supported_ = false;
469 if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::SET))
470 sample_count_supported_ = true;
472 if (sr_dev->config_check(ConfigKey::LIMIT_FRAMES, Capability::SET)) {
473 sr_dev->config_set(ConfigKey::LIMIT_FRAMES,
474 Glib::Variant<guint64>::create(1));
478 // Add notification of reconfigure events
479 disconnect(this, SLOT(on_config_changed()));
480 connect(&opts->binding(), SIGNAL(config_changed()),
481 this, SLOT(on_config_changed()));
483 // Update sweep timing widgets.
484 update_sample_count_selector();
485 update_sample_rate_selector();
488 void MainBar::commit_sample_rate()
490 uint64_t sample_rate = 0;
492 const shared_ptr<devices::Device> device =
493 device_selector_.selected_device();
497 const shared_ptr<sigrok::Device> sr_dev = device->device();
499 sample_rate = sample_rate_.value();
500 if (sample_rate == 0)
504 sr_dev->config_set(ConfigKey::SAMPLERATE,
505 Glib::Variant<guint64>::create(sample_rate));
506 update_sample_rate_selector();
507 } catch (Error error) {
508 qDebug() << "Failed to configure samplerate.";
512 // Devices with built-in memory might impose limits on certain
513 // configurations, so let's check what sample count the driver
515 update_sample_count_selector();
518 void MainBar::commit_sample_count()
520 uint64_t sample_count = 0;
522 const shared_ptr<devices::Device> device =
523 device_selector_.selected_device();
527 const shared_ptr<sigrok::Device> sr_dev = device->device();
529 sample_count = sample_count_.value();
530 if (sample_count_supported_) {
532 sr_dev->config_set(ConfigKey::LIMIT_SAMPLES,
533 Glib::Variant<guint64>::create(sample_count));
534 update_sample_count_selector();
535 } catch (Error error) {
536 qDebug() << "Failed to configure sample count.";
541 // Devices with built-in memory might impose limits on certain
542 // configurations, so let's check what sample rate the driver
544 update_sample_rate_selector();
547 void MainBar::session_error(const QString text, const QString info_text)
549 QMetaObject::invokeMethod(this, "show_session_error",
550 Qt::QueuedConnection, Q_ARG(QString, text),
551 Q_ARG(QString, info_text));
554 void MainBar::show_session_error(const QString text, const QString info_text)
556 QMessageBox msg(this);
558 msg.setInformativeText(info_text);
559 msg.setStandardButtons(QMessageBox::Ok);
560 msg.setIcon(QMessageBox::Warning);
564 void MainBar::add_decoder(srd_decoder *decoder)
568 session_.add_decoder(decoder);
574 void MainBar::export_file(shared_ptr<OutputFormat> format,
577 using pv::dialogs::StoreProgress;
579 // Stop any currently running capture session
580 session_.stop_capture();
583 const QString dir = settings.value(SettingSaveDirectory).toString();
585 std::pair<uint64_t, uint64_t> sample_range;
587 // Selection only? Verify that the cursors are active and fetch their values
588 if (selection_only) {
589 views::TraceView::View *trace_view =
590 qobject_cast<views::TraceView::View*>(session_.main_view().get());
592 if (!trace_view->cursors()->enabled()) {
593 show_session_error(tr("Missing Cursors"), tr("You need to set the " \
594 "cursors before you can save the data enclosed by them " \
595 "to a session file (e.g. using ALT-V - Show Cursors)."));
599 const double samplerate = session_.get_samplerate();
601 const pv::util::Timestamp& start_time = trace_view->cursors()->first()->time();
602 const pv::util::Timestamp& end_time = trace_view->cursors()->second()->time();
604 const uint64_t start_sample =
605 std::max((double)0, start_time.convert_to<double>() * samplerate);
606 const uint64_t end_sample = end_time.convert_to<double>() * samplerate;
608 sample_range = std::make_pair(start_sample, end_sample);
610 sample_range = std::make_pair(0, 0);
613 // Construct the filter
614 const vector<string> exts = format->extensions();
615 QString filter = tr("%1 files ").arg(
616 QString::fromStdString(format->description()));
621 filter += QString("(*.%1);;%2 (*.*)").arg(
622 QString::fromStdString(join(exts, ", *.")),
625 // Show the file dialog
626 const QString file_name = QFileDialog::getSaveFileName(
627 this, tr("Save File"), dir, filter);
629 if (file_name.isEmpty())
632 const QString abs_path = QFileInfo(file_name).absolutePath();
633 settings.setValue(SettingSaveDirectory, abs_path);
635 // Show the options dialog
636 map<string, Glib::VariantBase> options;
637 if (!format->options().empty()) {
638 dialogs::InputOutputOptions dlg(
639 tr("Export %1").arg(QString::fromStdString(
640 format->description())),
641 format->options(), this);
644 options = dlg.options();
648 session_.set_name(QFileInfo(file_name).fileName());
650 StoreProgress *dlg = new StoreProgress(file_name, format, options,
651 sample_range, session_, this);
655 void MainBar::import_file(shared_ptr<InputFormat> format)
660 const QString dir = settings.value(SettingOpenDirectory).toString();
662 // Construct the filter
663 const vector<string> exts = format->extensions();
664 const QString filter = exts.empty() ? "" :
665 tr("%1 files (*.%2)").arg(
666 QString::fromStdString(format->description()),
667 QString::fromStdString(join(exts, ", *.")));
669 // Show the file dialog
670 const QString file_name = QFileDialog::getOpenFileName(
671 this, tr("Import File"), dir, tr(
672 "%1 files (*.*);;All Files (*.*)").arg(
673 QString::fromStdString(format->description())));
675 if (file_name.isEmpty())
678 // Show the options dialog
679 map<string, Glib::VariantBase> options;
680 if (!format->options().empty()) {
681 dialogs::InputOutputOptions dlg(
682 tr("Import %1").arg(QString::fromStdString(
683 format->description())),
684 format->options(), this);
687 options = dlg.options();
690 session_.load_file(file_name, format, options);
692 const QString abs_path = QFileInfo(file_name).absolutePath();
693 settings.setValue(SettingOpenDirectory, abs_path);
696 void MainBar::on_device_selected()
698 shared_ptr<devices::Device> device = device_selector_.selected_device();
700 reset_device_selector();
704 session_.select_device(device);
707 void MainBar::on_device_changed()
709 update_device_list();
710 update_device_config_widgets();
713 void MainBar::on_capture_state_changed(int state)
715 set_capture_state((pv::Session::capture_state)state);
718 void MainBar::on_sample_count_changed()
720 if (!updating_sample_count_)
721 commit_sample_count();
724 void MainBar::on_sample_rate_changed()
726 if (!updating_sample_rate_)
727 commit_sample_rate();
730 void MainBar::on_config_changed()
732 commit_sample_count();
733 commit_sample_rate();
736 void MainBar::on_actionNewView_triggered()
741 void MainBar::on_actionOpen_triggered()
744 const QString dir = settings.value(SettingOpenDirectory).toString();
747 const QString file_name = QFileDialog::getOpenFileName(
748 this, tr("Open File"), dir, tr(
749 "Sigrok Sessions (*.sr);;"
752 if (!file_name.isEmpty()) {
753 session_.load_file(file_name);
755 const QString abs_path = QFileInfo(file_name).absolutePath();
756 settings.setValue(SettingOpenDirectory, abs_path);
760 void MainBar::on_actionSaveAs_triggered()
762 export_file(session_.device_manager().context()->output_formats()["srzip"]);
765 void MainBar::on_actionSaveSelectionAs_triggered()
767 export_file(session_.device_manager().context()->output_formats()["srzip"], true);
770 void MainBar::on_actionConnect_triggered()
772 // Stop any currently running capture session
773 session_.stop_capture();
775 dialogs::Connect dlg(this, session_.device_manager());
777 // If the user selected a device, select it in the device list. Select the
778 // current device otherwise.
780 session_.select_device(dlg.get_selected_device());
782 update_device_list();
785 void MainBar::add_toolbar_widgets()
787 addAction(action_new_view_);
789 addWidget(open_button_);
790 addWidget(save_button_);
793 StandardBar::add_toolbar_widgets();
795 addWidget(&device_selector_);
796 configure_button_action_ = addWidget(&configure_button_);
797 channels_button_action_ = addWidget(&channels_button_);
798 addWidget(&sample_count_);
799 addWidget(&sample_rate_);
802 addWidget(add_decoder_button_);
806 bool MainBar::eventFilter(QObject *watched, QEvent *event)
808 if (sample_count_supported_ && (watched == &sample_count_ ||
809 watched == &sample_rate_) &&
810 (event->type() == QEvent::ToolTip)) {
811 auto sec = pv::util::Timestamp(sample_count_.value()) / sample_rate_.value();
812 QHelpEvent *help_event = static_cast<QHelpEvent*>(event);
814 QString str = tr("Total sampling time: %1").arg(
815 pv::util::format_time_si(sec, pv::util::SIPrefix::unspecified, 0, "s", false));
816 QToolTip::showText(help_event->globalPos(), str);
824 } // namespace toolbars