]> git.sesse.net Git - nageru/blob - nageru/input_mapping_dialog.cpp
Make number of cards flexible at runtime.
[nageru] / nageru / input_mapping_dialog.cpp
1 #include "input_mapping_dialog.h"
2
3 #include <assert.h>
4 #include <stdbool.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <QAbstractItemView>
8 #include <QComboBox>
9 #include <QDialogButtonBox>
10 #include <QFileDialog>
11 #include <QHeaderView>
12 #include <QList>
13 #include <QMessageBox>
14 #include <QPushButton>
15 #include <QTableWidget>
16 #include <QVariant>
17 #include <functional>
18 #include <memory>
19 #include <set>
20 #include <string>
21 #include <utility>
22
23 #include "alsa_pool.h"
24 #include "defs.h"
25 #include "shared/post_to_main_thread.h"
26 #include "ui_input_mapping.h"
27
28 using namespace std;
29 using namespace std::placeholders;
30
31 namespace {
32
33 bool uses_device(const InputMapping &mapping, DeviceSpec device)
34 {
35         for (const InputMapping::Bus &bus : mapping.buses) {
36                 if (bus.device == device) {
37                         return true;
38                 }
39         }
40         return false;
41 }
42
43 }  // namespace
44
45 InputMappingDialog::InputMappingDialog()
46         : ui(new Ui::InputMappingDialog),
47           mapping(global_audio_mixer->get_input_mapping()),
48           old_mapping(mapping),
49           devices(global_audio_mixer->get_devices())
50 {
51         for (unsigned bus_index = 0; bus_index < mapping.buses.size(); ++bus_index) {
52                 bus_settings.push_back(global_audio_mixer->get_bus_settings(bus_index));
53         }
54
55         ui->setupUi(this);
56         ui->table->setSelectionBehavior(QAbstractItemView::SelectRows);
57         ui->table->setSelectionMode(QAbstractItemView::SingleSelection);  // Makes implementing moving easier for now.
58
59         fill_ui_from_mapping(mapping);
60         connect(ui->table, &QTableWidget::cellChanged, this, &InputMappingDialog::cell_changed);
61         connect(ui->ok_cancel_buttons, &QDialogButtonBox::accepted, this, &InputMappingDialog::ok_clicked);
62         connect(ui->ok_cancel_buttons, &QDialogButtonBox::rejected, this, &InputMappingDialog::cancel_clicked);
63         connect(ui->add_button, &QPushButton::clicked, this, &InputMappingDialog::add_clicked);
64         connect(ui->remove_button, &QPushButton::clicked, this, &InputMappingDialog::remove_clicked);
65         connect(ui->up_button, &QPushButton::clicked, bind(&InputMappingDialog::updown_clicked, this, -1));
66         connect(ui->down_button, &QPushButton::clicked, bind(&InputMappingDialog::updown_clicked, this, 1));
67         connect(ui->save_button, &QPushButton::clicked, this, &InputMappingDialog::save_clicked);
68         connect(ui->load_button, &QPushButton::clicked, this, &InputMappingDialog::load_clicked);
69
70         update_button_state();
71         connect(ui->table, &QTableWidget::itemSelectionChanged, this, &InputMappingDialog::update_button_state);
72
73         saved_callback = global_audio_mixer->get_state_changed_callback();
74         global_audio_mixer->set_state_changed_callback([this]{
75                 post_to_main_thread([this]{
76                         devices = global_audio_mixer->get_devices();
77                         for (unsigned row = 0; row < mapping.buses.size(); ++row) {
78                                 fill_row_from_bus(row, mapping.buses[row]);
79                         }
80                 });
81         });
82 }
83
84 InputMappingDialog::~InputMappingDialog()
85 {
86         global_audio_mixer->set_state_changed_callback(saved_callback);
87 }
88
89 void InputMappingDialog::fill_ui_from_mapping(const InputMapping &mapping)
90 {
91         ui->table->verticalHeader()->hide();
92         ui->table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
93         ui->table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
94         ui->table->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
95         ui->table->horizontalHeader()->setSectionsClickable(false);
96
97         ui->table->setRowCount(mapping.buses.size());
98         for (unsigned row = 0; row < mapping.buses.size(); ++row) {
99                 fill_row_from_bus(row, mapping.buses[row]);
100         }
101 }
102
103 void InputMappingDialog::fill_row_from_bus(unsigned row, const InputMapping::Bus &bus)
104 {
105         QString name(QString::fromStdString(bus.name));
106         ui->table->setItem(row, 0, new QTableWidgetItem(name));
107
108         // Card choices. If there's already a combobox here, we try to modify
109         // the elements in-place, so that the UI doesn't go away under the user's feet
110         // if they are in the process of choosing an item.
111         QComboBox *card_combo = static_cast<QComboBox *>(ui->table->cellWidget(row, 1));
112         if (card_combo == nullptr) {
113                 card_combo = new QComboBox;
114         }
115         unsigned current_index = 0;
116         if (card_combo->count() == 0) {
117                 card_combo->addItem(QString("(none)   "));
118         }
119         for (const auto &spec_and_info : devices) {
120                 QString label(QString::fromStdString(spec_and_info.second.display_name));
121                 if (spec_and_info.first.type == InputSourceType::ALSA_INPUT) {
122                         ALSAPool::Device::State state = global_audio_mixer->get_alsa_card_state(spec_and_info.first.index);
123                         if (state == ALSAPool::Device::State::EMPTY) {
124                                 continue;
125                         } else if (state == ALSAPool::Device::State::STARTING) {
126                                 label += " (busy)";
127                         } else if (state == ALSAPool::Device::State::DEAD) {
128                                 label += " (dead)";
129                         }
130                 } else if (!global_audio_mixer->get_active(spec_and_info.first)) {
131                         // Should nominally be skipped, but if we used it before it went away,
132                         // we'll need to allow the user to still see it.
133                         if (uses_device(mapping, spec_and_info.first) ||
134                             uses_device(old_mapping, spec_and_info.first)) {
135                                 label += " (dead)";
136                         } else {
137                                 continue;
138                         }
139                 }
140                 ++current_index;
141                 if (unsigned(card_combo->count()) > current_index) {
142                         card_combo->setItemText(current_index, label + "   ");
143                         card_combo->setItemData(current_index, qulonglong(DeviceSpec_to_key(spec_and_info.first)));
144                 } else {
145                         card_combo->addItem(
146                                 label + "   ",
147                                 qulonglong(DeviceSpec_to_key(spec_and_info.first)));
148                 }
149                 if (bus.device == spec_and_info.first) {
150                         card_combo->setCurrentIndex(current_index);
151                 }
152         }
153         // Remove any excess items from earlier. (This is only for paranoia;
154         // they should be held, so it shouldn't matter.)
155         while (unsigned(card_combo->count()) > current_index + 1) {
156                 card_combo->removeItem(current_index + 1);
157         }
158         connect(card_combo, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
159                 bind(&InputMappingDialog::card_selected, this, card_combo, row, _1));
160         ui->table->setCellWidget(row, 1, card_combo);
161
162         setup_channel_choices_from_bus(row, bus);
163 }
164
165 void InputMappingDialog::setup_channel_choices_from_bus(unsigned row, const InputMapping::Bus &bus)
166 {
167         // Left and right channel.
168         // TODO: If there's already a widget here, modify it instead of creating a new one,
169         // as we do with card choices.
170         for (unsigned channel = 0; channel < 2; ++channel) {
171                 QComboBox *channel_combo = new QComboBox;
172                 channel_combo->addItem(QString("(none)"));
173                 if (bus.device.type == InputSourceType::CAPTURE_CARD ||
174                     bus.device.type == InputSourceType::ALSA_INPUT) {
175                         auto device_it = devices.find(bus.device);
176                         assert(device_it != devices.end());
177                         unsigned num_device_channels = device_it->second.num_channels;
178                         for (unsigned source = 0; source < num_device_channels; ++source) {
179                                 char buf[256];
180                                 snprintf(buf, sizeof(buf), "Channel %u   ", source + 1);
181                                 channel_combo->addItem(QString(buf));
182                         }
183                         channel_combo->setCurrentIndex(bus.source_channel[channel] + 1);
184                 } else {
185                         assert(bus.device.type == InputSourceType::SILENCE);
186                         channel_combo->setCurrentIndex(0);
187                 }
188                 connect(channel_combo, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
189                         bind(&InputMappingDialog::channel_selected, this, row, channel, _1));
190                 ui->table->setCellWidget(row, 2 + channel, channel_combo);
191         }
192 }
193
194 void InputMappingDialog::ok_clicked()
195 {
196         global_audio_mixer->set_state_changed_callback(saved_callback);
197         global_audio_mixer->set_input_mapping(mapping);
198         for (unsigned bus_index = 0; bus_index < mapping.buses.size(); ++bus_index) {
199                 global_audio_mixer->set_bus_settings(bus_index, bus_settings[bus_index]);
200                 global_audio_mixer->reset_peak(bus_index);
201         }
202         accept();
203 }
204
205 void InputMappingDialog::cancel_clicked()
206 {
207         global_audio_mixer->set_state_changed_callback(saved_callback);
208         global_audio_mixer->set_input_mapping(old_mapping);
209         reject();
210 }
211
212 void InputMappingDialog::cell_changed(int row, int column)
213 {
214         if (column != 0) {
215                 // Spurious; only really the name column should fire these.
216                 return;
217         }
218         mapping.buses[row].name = ui->table->item(row, column)->text().toStdString();
219 }
220
221 void InputMappingDialog::card_selected(QComboBox *card_combo, unsigned row, int index)
222 {
223         uint64_t key = card_combo->itemData(index).toULongLong();
224         mapping.buses[row].device = key_to_DeviceSpec(key);
225         setup_channel_choices_from_bus(row, mapping.buses[row]);
226 }
227
228 void InputMappingDialog::channel_selected(unsigned row, unsigned channel, int index)
229 {
230         mapping.buses[row].source_channel[channel] = index - 1;
231 }
232
233 void InputMappingDialog::add_clicked()
234 {
235         QTableWidgetSelectionRange all(0, 0, ui->table->rowCount() - 1, ui->table->columnCount() - 1);
236         ui->table->setRangeSelected(all, false);
237
238         InputMapping::Bus new_bus;
239         new_bus.name = "New input";
240         new_bus.device.type = InputSourceType::SILENCE;
241         mapping.buses.push_back(new_bus);
242         bus_settings.push_back(AudioMixer::get_default_bus_settings());
243         ui->table->setRowCount(mapping.buses.size());
244
245         unsigned row = mapping.buses.size() - 1;
246         fill_row_from_bus(row, new_bus);
247         ui->table->editItem(ui->table->item(row, 0));  // Start editing the name.
248         update_button_state();
249 }
250
251 void InputMappingDialog::remove_clicked()
252 {
253         assert(ui->table->rowCount() != 0);
254
255         set<int, greater<int>> rows_to_delete;  // Need to remove in reverse order.
256         for (const QTableWidgetSelectionRange &range : ui->table->selectedRanges()) {
257                 for (int row = range.topRow(); row <= range.bottomRow(); ++row) {
258                         rows_to_delete.insert(row);
259                 }
260         }
261         if (rows_to_delete.empty()) {
262                 rows_to_delete.insert(ui->table->rowCount() - 1);
263         }
264
265         for (int row : rows_to_delete) {
266                 ui->table->removeRow(row);
267                 mapping.buses.erase(mapping.buses.begin() + row);
268                 bus_settings.erase(bus_settings.begin() + row);
269         }
270         update_button_state();
271 }
272
273 void InputMappingDialog::updown_clicked(int direction)
274 {
275         assert(ui->table->selectedRanges().size() == 1);
276         const QTableWidgetSelectionRange &range = ui->table->selectedRanges()[0];
277         int a_row = range.bottomRow();
278         int b_row = range.bottomRow() + direction;
279
280         swap(mapping.buses[a_row], mapping.buses[b_row]);
281         swap(bus_settings[a_row], bus_settings[b_row]);
282         fill_row_from_bus(a_row, mapping.buses[a_row]);
283         fill_row_from_bus(b_row, mapping.buses[b_row]);
284
285         QTableWidgetSelectionRange a_sel(a_row, 0, a_row, ui->table->columnCount() - 1);
286         QTableWidgetSelectionRange b_sel(b_row, 0, b_row, ui->table->columnCount() - 1);
287         ui->table->setRangeSelected(a_sel, false);
288         ui->table->setRangeSelected(b_sel, true);
289 }
290
291 void InputMappingDialog::save_clicked()
292 {
293 #if HAVE_CEF
294         // The native file dialog uses GTK+, which interferes with CEF's use of the GLib main loop.
295         QFileDialog::Option options(QFileDialog::DontUseNativeDialog);
296 #else
297         QFileDialog::Option options(QFileDialog::Option(0));
298 #endif
299         QString filename = QFileDialog::getSaveFileName(this,
300                 "Save input mapping", QString(), tr("Mapping files (*.mapping)"), /*selectedFilter=*/nullptr, options);
301         if (!filename.endsWith(".mapping")) {
302                 filename += ".mapping";
303         }
304         if (!save_input_mapping_to_file(devices, mapping, filename.toStdString())) {
305                 QMessageBox box;
306                 box.setText("Could not save mapping to '" + filename + "'. Check that you have the right permissions and try again.");
307                 box.exec();
308         }
309 }
310
311 void InputMappingDialog::load_clicked()
312 {
313 #if HAVE_CEF
314         // The native file dialog uses GTK+, which interferes with CEF's use of the GLib main loop.
315         QFileDialog::Option options(QFileDialog::DontUseNativeDialog);
316 #else
317         QFileDialog::Option options(QFileDialog::Option(0));
318 #endif
319         QString filename = QFileDialog::getOpenFileName(this,
320                 "Load input mapping", QString(), tr("Mapping files (*.mapping)"), /*selectedFilter=*/nullptr, options);
321         InputMapping new_mapping;
322         if (!load_input_mapping_from_file(devices, filename.toStdString(), &new_mapping)) {
323                 QMessageBox box;
324                 box.setText("Could not load mapping from '" + filename + "'. Check that the file exists, has the right permissions and is valid.");
325                 box.exec();
326                 return;
327         }
328
329         mapping = new_mapping;
330         bus_settings.clear();
331         for (unsigned bus_index = 0; bus_index < mapping.buses.size(); ++bus_index) {
332                 bus_settings.push_back(global_audio_mixer->get_bus_settings(bus_index));
333         }
334         devices = global_audio_mixer->get_devices();  // New dead cards may have been made.
335         fill_ui_from_mapping(mapping);
336 }
337
338 void InputMappingDialog::update_button_state()
339 {
340         ui->add_button->setDisabled(mapping.buses.size() >= MAX_BUSES);
341         ui->remove_button->setDisabled(mapping.buses.size() == 0);
342         ui->up_button->setDisabled(
343                 ui->table->selectedRanges().empty() ||
344                 ui->table->selectedRanges()[0].bottomRow() == 0);
345         ui->down_button->setDisabled(
346                 ui->table->selectedRanges().empty() ||
347                 ui->table->selectedRanges()[0].bottomRow() == ui->table->rowCount() - 1);
348 }