a2a20fb62a93aafe4956d0a6b52b4742099e7dfc
[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, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <extdef.h>
21
22 #include <algorithm>
23 #include <cassert>
24
25 #include <QAction>
26 #include <QDebug>
27 #include <QFileDialog>
28 #include <QHelpEvent>
29 #include <QMenu>
30 #include <QMessageBox>
31 #include <QSettings>
32 #include <QToolTip>
33
34 #include "mainbar.hpp"
35
36 #include <boost/algorithm/string/join.hpp>
37
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>
52 #ifdef ENABLE_DECODE
53 #include <pv/data/decodesignal.hpp>
54 #endif
55
56 #include <libsigrokcxx/libsigrokcxx.hpp>
57
58 using std::back_inserter;
59 using std::copy;
60 using std::list;
61 using std::make_pair;
62 using std::map;
63 using std::max;
64 using std::min;
65 using std::pair;
66 using std::set;
67 using std::shared_ptr;
68 using std::string;
69 using std::vector;
70
71 using sigrok::Capability;
72 using sigrok::ConfigKey;
73 using sigrok::Error;
74 using sigrok::InputFormat;
75 using sigrok::OutputFormat;
76
77 using boost::algorithm::join;
78
79 namespace pv {
80 namespace toolbars {
81
82 const uint64_t MainBar::MinSampleCount = 100ULL;
83 const uint64_t MainBar::MaxSampleCount = 1000000000000ULL;
84 const uint64_t MainBar::DefaultSampleCount = 1000000;
85
86 const char *MainBar::SettingOpenDirectory = "MainWindow/OpenDirectory";
87 const char *MainBar::SettingSaveDirectory = "MainWindow/SaveDirectory";
88
89 MainBar::MainBar(Session &session, QWidget *parent, pv::views::trace::View *view) :
90         StandardBar(session, parent, view, false),
91         action_new_view_(new QAction(this)),
92         action_open_(new QAction(this)),
93         action_save_(new QAction(this)),
94         action_save_as_(new QAction(this)),
95         action_save_selection_as_(new QAction(this)),
96         action_restore_setup_(new QAction(this)),
97         action_save_setup_(new QAction(this)),
98         action_connect_(new QAction(this)),
99         new_view_button_(new QToolButton()),
100         open_button_(new QToolButton()),
101         save_button_(new QToolButton()),
102         device_selector_(parent, session.device_manager(), action_connect_),
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)
112 #ifdef ENABLE_DECODE
113         , add_decoder_button_(new QToolButton())
114 #endif
115 {
116         setObjectName(QString::fromUtf8("MainBar"));
117
118         setContextMenuPolicy(Qt::PreventContextMenu);
119
120         // Actions
121         action_new_view_->setText(tr("New &View"));
122         action_new_view_->setIcon(QIcon::fromTheme("window-new",
123                 QIcon(":/icons/window-new.png")));
124         connect(action_new_view_, SIGNAL(triggered(bool)),
125                 this, SLOT(on_actionNewView_triggered()));
126
127         action_open_->setText(tr("&Open..."));
128         action_open_->setIcon(QIcon::fromTheme("document-open",
129                 QIcon(":/icons/document-open.png")));
130         action_open_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_O));
131         connect(action_open_, SIGNAL(triggered(bool)),
132                 this, SLOT(on_actionOpen_triggered()));
133
134         action_restore_setup_->setText(tr("Restore Session Setu&p..."));
135         connect(action_restore_setup_, SIGNAL(triggered(bool)),
136                 this, SLOT(on_actionRestoreSetup_triggered()));
137
138         action_save_->setText(tr("&Save..."));
139         action_save_->setIcon(QIcon::fromTheme("document-save-as",
140                 QIcon(":/icons/document-save-as.png")));
141         action_save_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_S));
142         connect(action_save_, SIGNAL(triggered(bool)),
143                 this, SLOT(on_actionSave_triggered()));
144
145         action_save_as_->setText(tr("Save &As..."));
146         action_save_as_->setIcon(QIcon::fromTheme("document-save-as",
147                 QIcon(":/icons/document-save-as.png")));
148         connect(action_save_as_, SIGNAL(triggered(bool)),
149                 this, SLOT(on_actionSaveAs_triggered()));
150
151         action_save_selection_as_->setText(tr("Save Selected &Range As..."));
152         action_save_selection_as_->setIcon(QIcon::fromTheme("document-save-as",
153                 QIcon(":/icons/document-save-as.png")));
154         action_save_selection_as_->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
155         connect(action_save_selection_as_, SIGNAL(triggered(bool)),
156                 this, SLOT(on_actionSaveSelectionAs_triggered()));
157
158         action_save_setup_->setText(tr("Save Session Setu&p..."));
159         connect(action_save_setup_, SIGNAL(triggered(bool)),
160                 this, SLOT(on_actionSaveSetup_triggered()));
161
162         widgets::ExportMenu *menu_file_export = new widgets::ExportMenu(this,
163                 session.device_manager().context());
164         menu_file_export->setTitle(tr("&Export"));
165         connect(menu_file_export, SIGNAL(format_selected(shared_ptr<sigrok::OutputFormat>)),
166                 this, SLOT(export_file(shared_ptr<sigrok::OutputFormat>)));
167
168         widgets::ImportMenu *menu_file_import = new widgets::ImportMenu(this,
169                 session.device_manager().context());
170         menu_file_import->setTitle(tr("&Import"));
171         connect(menu_file_import, SIGNAL(format_selected(shared_ptr<sigrok::InputFormat>)),
172                 this, SLOT(import_file(shared_ptr<sigrok::InputFormat>)));
173
174         action_connect_->setText(tr("&Connect to Device..."));
175         connect(action_connect_, SIGNAL(triggered(bool)),
176                 this, SLOT(on_actionConnect_triggered()));
177
178         // New view button
179         QMenu *menu_new_view = new QMenu();
180         connect(menu_new_view, SIGNAL(triggered(QAction*)),
181                 this, SLOT(on_actionNewView_triggered(QAction*)));
182
183         for (int i = 0; i < views::ViewTypeCount; i++) {
184                 QAction *const action = menu_new_view->addAction(tr(views::ViewTypeNames[i]));
185                 action->setData(QVariant::fromValue(i));
186         }
187
188         new_view_button_->setMenu(menu_new_view);
189         new_view_button_->setDefaultAction(action_new_view_);
190         new_view_button_->setPopupMode(QToolButton::MenuButtonPopup);
191
192         // Open button
193         vector<QAction*> open_actions;
194         open_actions.push_back(action_open_);
195         QAction* separator_o = new QAction(this);
196         separator_o->setSeparator(true);
197         open_actions.push_back(separator_o);
198         open_actions.push_back(action_restore_setup_);
199
200         widgets::ImportMenu *import_menu = new widgets::ImportMenu(this,
201                 session.device_manager().context(), open_actions);
202         connect(import_menu, SIGNAL(format_selected(shared_ptr<sigrok::InputFormat>)),
203                 this, SLOT(import_file(shared_ptr<sigrok::InputFormat>)));
204
205         open_button_->setMenu(import_menu);
206         open_button_->setDefaultAction(action_open_);
207         open_button_->setPopupMode(QToolButton::MenuButtonPopup);
208
209         // Save button
210         vector<QAction*> save_actions;
211         save_actions.push_back(action_save_);
212         save_actions.push_back(action_save_as_);
213         save_actions.push_back(action_save_selection_as_);
214         QAction* separator_s = new QAction(this);
215         separator_s->setSeparator(true);
216         save_actions.push_back(separator_s);
217         save_actions.push_back(action_save_setup_);
218
219         widgets::ExportMenu *export_menu = new widgets::ExportMenu(this,
220                 session.device_manager().context(), save_actions);
221         connect(export_menu, SIGNAL(format_selected(shared_ptr<sigrok::OutputFormat>)),
222                 this, SLOT(export_file(shared_ptr<sigrok::OutputFormat>)));
223
224         save_button_->setMenu(export_menu);
225         save_button_->setDefaultAction(action_save_);
226         save_button_->setPopupMode(QToolButton::MenuButtonPopup);
227
228         // Device selector menu
229         connect(&device_selector_, SIGNAL(device_selected()),
230                 this, SLOT(on_device_selected()));
231
232         // Setup the decoder button
233 #ifdef ENABLE_DECODE
234         add_decoder_button_->setIcon(QIcon(":/icons/add-decoder.svg"));
235         add_decoder_button_->setPopupMode(QToolButton::InstantPopup);
236         add_decoder_button_->setToolTip(tr("Add protocol decoder"));
237         add_decoder_button_->setShortcut(QKeySequence(Qt::Key_D));
238
239         connect(add_decoder_button_, SIGNAL(clicked()),
240                 this, SLOT(on_add_decoder_clicked()));
241 #endif
242
243         connect(&sample_count_, SIGNAL(value_changed()),
244                 this, SLOT(on_sample_count_changed()));
245         connect(&sample_rate_, SIGNAL(value_changed()),
246                 this, SLOT(on_sample_rate_changed()));
247
248         sample_count_.show_min_max_step(0, UINT64_MAX, 1);
249
250         set_capture_state(pv::Session::Stopped);
251
252         configure_button_.setToolTip(tr("Configure Device"));
253         configure_button_.setIcon(QIcon::fromTheme("preferences-system",
254                 QIcon(":/icons/preferences-system.png")));
255
256         channels_button_.setToolTip(tr("Configure Channels"));
257         channels_button_.setIcon(QIcon(":/icons/channels.svg"));
258
259         add_toolbar_widgets();
260
261         sample_count_.installEventFilter(this);
262         sample_rate_.installEventFilter(this);
263
264         // Setup session_ events
265         connect(&session_, SIGNAL(capture_state_changed(int)),
266                 this, SLOT(on_capture_state_changed(int)));
267         connect(&session, SIGNAL(device_changed()),
268                 this, SLOT(on_device_changed()));
269
270         update_device_list();
271 }
272
273 void MainBar::update_device_list()
274 {
275         DeviceManager &mgr = session_.device_manager();
276         shared_ptr<devices::Device> selected_device = session_.device();
277         list< shared_ptr<devices::Device> > devs;
278
279         copy(mgr.devices().begin(), mgr.devices().end(), back_inserter(devs));
280
281         if (std::find(devs.begin(), devs.end(), selected_device) == devs.end())
282                 devs.push_back(selected_device);
283
284         device_selector_.set_device_list(devs, selected_device);
285         update_device_config_widgets();
286 }
287
288 void MainBar::set_capture_state(pv::Session::capture_state state)
289 {
290         bool ui_enabled = (state == pv::Session::Stopped) ? true : false;
291
292         device_selector_.setEnabled(ui_enabled);
293         configure_button_.setEnabled(ui_enabled);
294         channels_button_.setEnabled(ui_enabled);
295         sample_count_.setEnabled(ui_enabled);
296         sample_rate_.setEnabled(ui_enabled);
297 }
298
299 void MainBar::reset_device_selector()
300 {
301         device_selector_.reset();
302 }
303
304 QAction* MainBar::action_open() const
305 {
306         return action_open_;
307 }
308
309 QAction* MainBar::action_save() const
310 {
311         return action_save_;
312 }
313
314 QAction* MainBar::action_save_as() const
315 {
316         return action_save_as_;
317 }
318
319 QAction* MainBar::action_save_selection_as() const
320 {
321         return action_save_selection_as_;
322 }
323
324 QAction* MainBar::action_connect() const
325 {
326         return action_connect_;
327 }
328
329 void MainBar::update_sample_rate_selector()
330 {
331         Glib::VariantContainerBase gvar_dict;
332         GVariant *gvar_list;
333         const uint64_t *elements = nullptr;
334         gsize num_elements;
335         map< const ConfigKey*, set<Capability> > keys;
336
337         if (updating_sample_rate_) {
338                 sample_rate_.show_none();
339                 return;
340         }
341
342         const shared_ptr<devices::Device> device = device_selector_.selected_device();
343         if (!device)
344                 return;
345
346         assert(!updating_sample_rate_);
347         updating_sample_rate_ = true;
348
349         const shared_ptr<sigrok::Device> sr_dev = device->device();
350
351         sample_rate_.allow_user_entered_values(false);
352         if (sr_dev->config_check(ConfigKey::EXTERNAL_CLOCK, Capability::GET)) {
353                 try {
354                         auto gvar = sr_dev->config_get(ConfigKey::EXTERNAL_CLOCK);
355                         if (gvar.gobj()) {
356                                 bool value = Glib::VariantBase::cast_dynamic<Glib::Variant<bool>>(
357                                         gvar).get();
358                                 sample_rate_.allow_user_entered_values(value);
359                         }
360                 } catch (Error& error) {
361                         // Do nothing
362                 }
363         }
364
365
366         if (sr_dev->config_check(ConfigKey::SAMPLERATE, Capability::LIST)) {
367                 try {
368                         gvar_dict = sr_dev->config_list(ConfigKey::SAMPLERATE);
369                 } catch (Error& error) {
370                         qDebug() << tr("Failed to get sample rate list:") << error.what();
371                 }
372         } else {
373                 sample_rate_.show_none();
374                 updating_sample_rate_ = false;
375                 return;
376         }
377
378         if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
379                         "samplerate-steps", G_VARIANT_TYPE("at")))) {
380                 elements = (const uint64_t *)g_variant_get_fixed_array(
381                         gvar_list, &num_elements, sizeof(uint64_t));
382
383                 const uint64_t min = elements[0];
384                 const uint64_t max = elements[1];
385                 const uint64_t step = elements[2];
386
387                 g_variant_unref(gvar_list);
388
389                 assert(min > 0);
390                 assert(max > 0);
391                 assert(max > min);
392                 assert(step > 0);
393
394                 if (step == 1)
395                         sample_rate_.show_125_list(min, max);
396                 else {
397                         // When the step is not 1, we cam't make a 1-2-5-10
398                         // list of sample rates, because we may not be able to
399                         // make round numbers. Therefore in this case, show a
400                         // spin box.
401                         sample_rate_.show_min_max_step(min, max, step);
402                 }
403         } else if ((gvar_list = g_variant_lookup_value(gvar_dict.gobj(),
404                         "samplerates", G_VARIANT_TYPE("at")))) {
405                 elements = (const uint64_t *)g_variant_get_fixed_array(
406                         gvar_list, &num_elements, sizeof(uint64_t));
407                 sample_rate_.show_list(elements, num_elements);
408                 g_variant_unref(gvar_list);
409         }
410         updating_sample_rate_ = false;
411
412         update_sample_rate_selector_value();
413 }
414
415 void MainBar::update_sample_rate_selector_value()
416 {
417         if (updating_sample_rate_)
418                 return;
419
420         const shared_ptr<devices::Device> device = device_selector_.selected_device();
421         if (!device)
422                 return;
423
424         try {
425                 auto gvar = device->device()->config_get(ConfigKey::SAMPLERATE);
426                 uint64_t samplerate =
427                         Glib::VariantBase::cast_dynamic<Glib::Variant<guint64>>(gvar).get();
428                 assert(!updating_sample_rate_);
429                 updating_sample_rate_ = true;
430                 sample_rate_.set_value(samplerate);
431                 updating_sample_rate_ = false;
432         } catch (Error& error) {
433                 qDebug() << tr("Failed to get sample rate:") << error.what();
434         }
435 }
436
437 void MainBar::update_sample_count_selector()
438 {
439         if (updating_sample_count_)
440                 return;
441
442         const shared_ptr<devices::Device> device = device_selector_.selected_device();
443         if (!device)
444                 return;
445
446         const shared_ptr<sigrok::Device> sr_dev = device->device();
447
448         assert(!updating_sample_count_);
449         updating_sample_count_ = true;
450
451         if (!sample_count_supported_) {
452                 sample_count_.show_none();
453                 updating_sample_count_ = false;
454                 return;
455         }
456
457         uint64_t sample_count = sample_count_.value();
458         uint64_t min_sample_count = 0;
459         uint64_t max_sample_count = MaxSampleCount;
460         bool default_count_set = false;
461
462         if (sample_count == 0) {
463                 sample_count = DefaultSampleCount;
464                 default_count_set = true;
465         }
466
467         if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::LIST)) {
468                 try {
469                         auto gvar = sr_dev->config_list(ConfigKey::LIMIT_SAMPLES);
470                         if (gvar.gobj())
471                                 g_variant_get(gvar.gobj(), "(tt)",
472                                         &min_sample_count, &max_sample_count);
473                 } catch (Error& error) {
474                         qDebug() << tr("Failed to get sample limit list:") << error.what();
475                 }
476         }
477
478         min_sample_count = min(max(min_sample_count, MinSampleCount),
479                 max_sample_count);
480
481         sample_count_.show_125_list(min_sample_count, max_sample_count);
482
483         if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::GET)) {
484                 auto gvar = sr_dev->config_get(ConfigKey::LIMIT_SAMPLES);
485                 sample_count = g_variant_get_uint64(gvar.gobj());
486                 if (sample_count == 0) {
487                         sample_count = DefaultSampleCount;
488                         default_count_set = true;
489                 }
490                 sample_count = min(max(sample_count, MinSampleCount),
491                         max_sample_count);
492         }
493
494         sample_count_.set_value(sample_count);
495
496         updating_sample_count_ = false;
497
498         // If we show the default rate then make sure the device uses the same
499         if (default_count_set)
500                 commit_sample_count();
501 }
502
503 void MainBar::update_device_config_widgets()
504 {
505         using namespace pv::popups;
506
507         const shared_ptr<devices::Device> device = device_selector_.selected_device();
508
509         // Hide the widgets if no device is selected
510         channels_button_action_->setVisible(!!device);
511         if (!device) {
512                 configure_button_action_->setVisible(false);
513                 sample_count_.show_none();
514                 sample_rate_.show_none();
515                 return;
516         }
517
518         const shared_ptr<sigrok::Device> sr_dev = device->device();
519         if (!sr_dev)
520                 return;
521
522         // Update the configure popup
523         DeviceOptions *const opts = new DeviceOptions(sr_dev, this);
524         configure_button_action_->setVisible(!opts->binding().properties().empty());
525         configure_button_.set_popup(opts);
526
527         // Update the channels popup
528         Channels *const channels = new Channels(session_, this);
529         channels_button_.set_popup(channels);
530
531         // Update supported options.
532         sample_count_supported_ = false;
533
534         if (sr_dev->config_check(ConfigKey::LIMIT_SAMPLES, Capability::SET))
535                 sample_count_supported_ = true;
536
537         // Add notification of reconfigure events
538         disconnect(this, SLOT(on_config_changed()));
539         connect(&opts->binding(), SIGNAL(config_changed()),
540                 this, SLOT(on_config_changed()));
541
542         // Update sweep timing widgets.
543         update_sample_count_selector();
544         update_sample_rate_selector();
545 }
546
547 void MainBar::commit_sample_rate()
548 {
549         uint64_t sample_rate = 0;
550
551         const shared_ptr<devices::Device> device = device_selector_.selected_device();
552         if (!device)
553                 return;
554
555         const shared_ptr<sigrok::Device> sr_dev = device->device();
556
557         sample_rate = sample_rate_.value();
558
559         try {
560                 sr_dev->config_set(ConfigKey::SAMPLERATE,
561                         Glib::Variant<guint64>::create(sample_rate));
562                 update_sample_rate_selector();
563         } catch (Error& error) {
564                 qDebug() << tr("Failed to configure samplerate:") << error.what();
565                 return;
566         }
567
568         // Devices with built-in memory might impose limits on certain
569         // configurations, so let's check what sample count the driver
570         // lets us use now.
571         update_sample_count_selector();
572 }
573
574 void MainBar::commit_sample_count()
575 {
576         uint64_t sample_count = 0;
577
578         const shared_ptr<devices::Device> device = device_selector_.selected_device();
579         if (!device)
580                 return;
581
582         const shared_ptr<sigrok::Device> sr_dev = device->device();
583
584         sample_count = sample_count_.value();
585         if (sample_count_supported_) {
586                 try {
587                         sr_dev->config_set(ConfigKey::LIMIT_SAMPLES,
588                                 Glib::Variant<guint64>::create(sample_count));
589                         update_sample_count_selector();
590                 } catch (Error& error) {
591                         qDebug() << tr("Failed to configure sample count:") << error.what();
592                         return;
593                 }
594         }
595
596         // Devices with built-in memory might impose limits on certain
597         // configurations, so let's check what sample rate the driver
598         // lets us use now.
599         update_sample_rate_selector();
600 }
601
602 void MainBar::show_session_error(const QString text, const QString info_text)
603 {
604         QMessageBox msg(this);
605         msg.setText(text + "\n\n" + info_text);
606         msg.setStandardButtons(QMessageBox::Ok);
607         msg.setIcon(QMessageBox::Warning);
608         msg.exec();
609 }
610
611 void MainBar::export_file(shared_ptr<OutputFormat> format, bool selection_only, QString path)
612 {
613         using pv::dialogs::StoreProgress;
614
615         // Stop any currently running capture session
616         session_.stop_capture();
617
618         QSettings settings;
619         const QString dir = settings.value(SettingSaveDirectory).toString();
620
621         pair<uint64_t, uint64_t> sample_range;
622
623         // Selection only? Verify that the cursors are active and fetch their values
624         if (selection_only) {
625                 views::trace::View *trace_view =
626                         qobject_cast<views::trace::View*>(session_.main_view().get());
627
628                 if (!trace_view->cursors()->enabled()) {
629                         show_session_error(tr("Missing Cursors"), tr("You need to set the " \
630                                 "cursors before you can save the data enclosed by them " \
631                                 "to a session file (e.g. using the Show Cursors button)."));
632                         return;
633                 }
634
635                 const double samplerate = session_.get_samplerate();
636
637                 const pv::util::Timestamp& start_time = trace_view->cursors()->first()->time();
638                 const pv::util::Timestamp& end_time = trace_view->cursors()->second()->time();
639
640                 const uint64_t start_sample = (uint64_t)max(
641                         0.0, start_time.convert_to<double>() * samplerate);
642                 const uint64_t end_sample = (uint64_t)max(
643                         0.0, end_time.convert_to<double>() * samplerate);
644
645                 if ((start_sample == 0) && (end_sample == 0)) {
646                         // Both cursors are negative and were clamped to 0
647                         show_session_error(tr("Invalid Range"), tr("The cursors don't " \
648                                 "define a valid range of samples."));
649                         return;
650                 }
651
652                 sample_range = make_pair(start_sample, end_sample);
653         } else {
654                 sample_range = make_pair(0, 0);
655         }
656
657         // Construct the filter
658         const vector<string> exts = format->extensions();
659         QString filter = tr("%1 files ").arg(
660                 QString::fromStdString(format->description()));
661
662         if (exts.empty())
663                 filter += "(*)";
664         else
665                 filter += QString("(*.%1);;%2 (*)").arg(
666                         QString::fromStdString(join(exts, ", *.")),
667                         tr("All Files"));
668
669         // Show the file dialog
670         const QString file_name = path.isEmpty() ?
671                 QFileDialog::getSaveFileName(this, tr("Save File"), dir, filter) :
672                 path;
673
674         if (file_name.isEmpty())
675                 return;
676
677         const QString abs_path = QFileInfo(file_name).absolutePath();
678         settings.setValue(SettingSaveDirectory, abs_path);
679
680         // Show the options dialog
681         map<string, Glib::VariantBase> options;
682         if (!format->options().empty()) {
683                 dialogs::InputOutputOptions dlg(
684                         tr("Export %1").arg(QString::fromStdString(
685                                 format->description())),
686                         format->options(), this);
687                 if (!dlg.exec())
688                         return;
689                 options = dlg.options();
690         }
691
692         if (!selection_only &&
693                         format == session_.device_manager().context()->output_formats()["srzip"])
694                 session_.set_path(file_name);
695
696         StoreProgress *dlg = new StoreProgress(file_name, format, options,
697                 sample_range, session_, this);
698         dlg->run();
699 }
700
701 void MainBar::import_file(shared_ptr<InputFormat> format)
702 {
703         assert(format);
704
705         QSettings settings;
706         const QString dir = settings.value(SettingOpenDirectory).toString();
707
708         // Construct the filter
709         const vector<string> exts = format->extensions();
710         const QString filter_exts = exts.empty() ? "" : QString::fromStdString("%1 (%2)").arg(
711                 tr("%1 files").arg(QString::fromStdString(format->description())),
712                 QString::fromStdString("*.%1").arg(QString::fromStdString(join(exts, " *."))));
713         const QString filter_all = QString::fromStdString("%1 (%2)").arg(
714                 tr("All Files"), QString::fromStdString("*"));
715         const QString filter = QString::fromStdString("%1%2%3").arg(
716                 exts.empty() ? "" : filter_exts,
717                 exts.empty() ? "" : ";;",
718                 filter_all);
719
720         // Show the file dialog
721         const QString file_name = QFileDialog::getOpenFileName(
722                 this, tr("Import File"), dir, filter);
723
724         if (file_name.isEmpty())
725                 return;
726
727         // Show the options dialog
728         map<string, Glib::VariantBase> options;
729         if (!format->options().empty()) {
730                 dialogs::InputOutputOptions dlg(
731                         tr("Import %1").arg(QString::fromStdString(
732                                 format->description())),
733                         format->options(), this);
734                 if (!dlg.exec())
735                         return;
736                 options = dlg.options();
737         }
738
739         session_.load_file(file_name, "", format, options);
740
741         const QString abs_path = QFileInfo(file_name).absolutePath();
742         settings.setValue(SettingOpenDirectory, abs_path);
743 }
744
745 void MainBar::on_device_selected()
746 {
747         shared_ptr<devices::Device> device = device_selector_.selected_device();
748
749         if (device)
750                 session_.select_device(device);
751         else
752                 reset_device_selector();
753 }
754
755 void MainBar::on_device_changed()
756 {
757         update_device_list();
758         update_device_config_widgets();
759 }
760
761 void MainBar::on_capture_state_changed(int state)
762 {
763         set_capture_state((pv::Session::capture_state)state);
764 }
765
766 void MainBar::on_sample_count_changed()
767 {
768         if (!updating_sample_count_)
769                 commit_sample_count();
770 }
771
772 void MainBar::on_sample_rate_changed()
773 {
774         if (!updating_sample_rate_)
775                 commit_sample_rate();
776 }
777
778 void MainBar::on_config_changed()
779 {
780         // We want to also call update_sample_rate_selector() here in case
781         // the user changed the SR_CONF_EXTERNAL_CLOCK option. However,
782         // commit_sample_rate() does this already, so we don't call it here
783
784         commit_sample_count();
785         commit_sample_rate();
786 }
787
788 void MainBar::on_actionNewView_triggered(QAction* action)
789 {
790         if (action)
791                 new_view(&session_, action->data().toInt());
792         else
793                 // When the icon of the button is clicked, we create a trace view
794                 new_view(&session_, views::ViewTypeTrace);
795 }
796
797 void MainBar::on_actionOpen_triggered()
798 {
799         QSettings settings;
800         const QString dir = settings.value(SettingOpenDirectory).toString();
801
802         // Show the dialog
803         const QString file_name = QFileDialog::getOpenFileName(
804                 this, tr("Open File"), dir, tr(
805                         "sigrok Sessions (*.sr);;"
806                         "All Files (*)"));
807
808         if (!file_name.isEmpty()) {
809                 session_.load_file(file_name);
810
811                 const QString abs_path = QFileInfo(file_name).absolutePath();
812                 settings.setValue(SettingOpenDirectory, abs_path);
813         }
814 }
815
816 void MainBar::on_actionSave_triggered()
817 {
818         export_file(session_.device_manager().context()->output_formats()["srzip"], false, session_.path());
819 }
820
821 void MainBar::on_actionSaveAs_triggered()
822 {
823         export_file(session_.device_manager().context()->output_formats()["srzip"]);
824 }
825
826 void MainBar::on_actionSaveSelectionAs_triggered()
827 {
828         export_file(session_.device_manager().context()->output_formats()["srzip"], true);
829 }
830
831 void MainBar::on_actionSaveSetup_triggered()
832 {
833         QSettings settings;
834         const QString dir = settings.value(SettingSaveDirectory).toString();
835
836         const QString file_name = QFileDialog::getSaveFileName(
837                 this, tr("Save File"), dir, tr(
838                                 "PulseView Session Setups (*.pvs);;"
839                                 "All Files (*)"));
840
841         if (file_name.isEmpty())
842                 return;
843
844         QSettings settings_storage(file_name, QSettings::IniFormat);
845         session_.save_setup(settings_storage);
846 }
847
848 void MainBar::on_actionRestoreSetup_triggered()
849 {
850         QSettings settings;
851         const QString dir = settings.value(SettingSaveDirectory).toString();
852
853         const QString file_name = QFileDialog::getOpenFileName(
854                 this, tr("Open File"), dir, tr(
855                                 "PulseView Session Setups (*.pvs);;"
856                                 "All Files (*)"));
857
858         if (file_name.isEmpty())
859                 return;
860
861         QSettings settings_storage(file_name, QSettings::IniFormat);
862         session_.restore_setup(settings_storage);
863 }
864
865 void MainBar::on_actionConnect_triggered()
866 {
867         // Stop any currently running capture session
868         session_.stop_capture();
869
870         dialogs::Connect dlg(this, session_.device_manager());
871
872         // If the user selected a device, select it in the device list. Select the
873         // current device otherwise.
874         if (dlg.exec())
875                 session_.select_device(dlg.get_selected_device());
876
877         update_device_list();
878 }
879
880 void MainBar::on_add_decoder_clicked()
881 {
882         show_decoder_selector(&session_);
883 }
884
885 void MainBar::add_toolbar_widgets()
886 {
887         addWidget(new_view_button_);
888         addSeparator();
889         addWidget(open_button_);
890         addWidget(save_button_);
891         addSeparator();
892
893         StandardBar::add_toolbar_widgets();
894
895         addWidget(&device_selector_);
896         configure_button_action_ = addWidget(&configure_button_);
897         channels_button_action_ = addWidget(&channels_button_);
898         addWidget(&sample_count_);
899         addWidget(&sample_rate_);
900 #ifdef ENABLE_DECODE
901         addSeparator();
902         addWidget(add_decoder_button_);
903 #endif
904 }
905
906 bool MainBar::eventFilter(QObject *watched, QEvent *event)
907 {
908         if (sample_count_supported_ && (watched == &sample_count_ ||
909                 watched == &sample_rate_) &&
910                 (event->type() == QEvent::ToolTip)) {
911
912                 auto sec = pv::util::Timestamp(sample_count_.value()) / sample_rate_.value();
913                 QHelpEvent *help_event = static_cast<QHelpEvent*>(event);
914
915                 QString str = tr("Total sampling time: %1").arg(
916                         pv::util::format_time_si(sec, pv::util::SIPrefix::unspecified, 0, "s", false));
917                 QToolTip::showText(help_event->globalPos(), str);
918
919                 return true;
920         }
921
922         return false;
923 }
924
925 } // namespace toolbars
926 } // namespace pv