1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
use egui_extras::{Column, TableBuilder};

use crate::settings::InputKind;

use super::*;

pub(super) fn widget(
    mut args: In<(&mut egui::Ui, &mut SettingsState, bool)>,
    meta: Root<GameMeta>,
    localization: Localization<GameMeta>,
    keyboard: Res<KeyboardInputs>,
    gamepad: Res<GamepadInputs>,
) {
    let (ui, state, should_reset) = &mut *args;

    if *should_reset {
        state.modified_settings.player_controls = meta.default_settings.player_controls.clone();
    }

    let bigger_font = meta
        .theme
        .font_styles
        .bigger
        .with_color(meta.theme.panel.font_color);
    let normal_font = meta
        .theme
        .font_styles
        .normal
        .with_color(meta.theme.panel.font_color);

    ui.add_space(bigger_font.size * 0.1);

    // Calculate the row height so that it can fit the input buttons
    let small_button_style = &meta.theme.buttons.small;
    let row_height = small_button_style.font.size
        + small_button_style.padding.top
        + small_button_style.padding.bottom;

    let mapping = &mut state.modified_settings.player_controls;

    let mut input_rows = [
        (
            localization.get("move-up"),
            [
                &mut mapping.keyboard1.movement.up,
                &mut mapping.keyboard2.movement.up,
                &mut mapping.gamepad.movement.up,
            ],
        ),
        (
            localization.get("move-down"),
            [
                &mut mapping.keyboard1.movement.down,
                &mut mapping.keyboard2.movement.down,
                &mut mapping.gamepad.movement.down,
            ],
        ),
        (
            localization.get("move-left"),
            [
                &mut mapping.keyboard1.movement.left,
                &mut mapping.keyboard2.movement.left,
                &mut mapping.gamepad.movement.left,
            ],
        ),
        (
            localization.get("move-right"),
            [
                &mut mapping.keyboard1.movement.right,
                &mut mapping.keyboard2.movement.right,
                &mut mapping.gamepad.movement.right,
            ],
        ),
        (
            localization.get("move-up-alt"),
            [
                &mut mapping.keyboard1.movement_alt.up,
                &mut mapping.keyboard2.movement_alt.up,
                &mut mapping.gamepad.movement_alt.up,
            ],
        ),
        (
            localization.get("move-down-alt"),
            [
                &mut mapping.keyboard1.movement_alt.down,
                &mut mapping.keyboard2.movement_alt.down,
                &mut mapping.gamepad.movement_alt.down,
            ],
        ),
        (
            localization.get("move-left-alt"),
            [
                &mut mapping.keyboard1.movement_alt.left,
                &mut mapping.keyboard2.movement_alt.left,
                &mut mapping.gamepad.movement_alt.left,
            ],
        ),
        (
            localization.get("move-right-alt"),
            [
                &mut mapping.keyboard1.movement_alt.right,
                &mut mapping.keyboard2.movement_alt.right,
                &mut mapping.gamepad.movement_alt.right,
            ],
        ),
        (
            localization.get("jump"),
            [
                &mut mapping.keyboard1.jump,
                &mut mapping.keyboard2.jump,
                &mut mapping.gamepad.jump,
            ],
        ),
        (
            localization.get("grab-drop"),
            [
                &mut mapping.keyboard1.grab,
                &mut mapping.keyboard2.grab,
                &mut mapping.gamepad.grab,
            ],
        ),
        (
            localization.get("shoot"),
            [
                &mut mapping.keyboard1.shoot,
                &mut mapping.keyboard2.shoot,
                &mut mapping.gamepad.shoot,
            ],
        ),
        (
            localization.get("slide"),
            [
                &mut mapping.keyboard1.slide,
                &mut mapping.keyboard2.slide,
                &mut mapping.gamepad.slide,
            ],
        ),
        (
            localization.get("ragdoll"),
            [
                &mut mapping.keyboard1.ragdoll,
                &mut mapping.keyboard2.ragdoll,
                &mut mapping.gamepad.ragdoll,
            ],
        ),
        (
            localization.get("pause"),
            [
                &mut mapping.keyboard1.pause,
                &mut mapping.keyboard2.pause,
                &mut mapping.gamepad.pause,
            ],
        ),
        (
            localization.get("menu-confirm"),
            [
                &mut mapping.keyboard1.menu_confirm,
                &mut mapping.keyboard2.menu_confirm,
                &mut mapping.gamepad.menu_confirm,
            ],
        ),
        (
            localization.get("menu-back"),
            [
                &mut mapping.keyboard1.menu_back,
                &mut mapping.keyboard2.menu_back,
                &mut mapping.gamepad.menu_back,
            ],
        ),
        (
            localization.get("menu-start"),
            [
                &mut mapping.keyboard1.menu_start,
                &mut mapping.keyboard2.menu_start,
                &mut mapping.gamepad.menu_start,
            ],
        ),
    ];

    // Create input table
    let width = ui.available_width();
    let label_size = normal_font.size * 7.0;
    let remaining_width = width - label_size;
    let cell_width = remaining_width / 3.1;
    TableBuilder::new(ui)
        .cell_layout(egui::Layout::centered_and_justified(
            egui::Direction::LeftToRight,
        ))
        .column(Column::exact(label_size))
        .column(Column::exact(cell_width))
        .column(Column::exact(cell_width))
        .column(Column::exact(cell_width))
        .header(bigger_font.size * 1.5, |mut row| {
            row.col(|ui| {
                ui.label(bigger_font.rich(localization.get("action")));
            });
            row.col(|ui| {
                ui.label(bigger_font.rich(localization.get("keyboard-1")));
            });
            row.col(|ui| {
                ui.label(bigger_font.rich(localization.get("keyboard-2")));
            });
            row.col(|ui| {
                ui.label(bigger_font.rich(localization.get("gamepad")));
            });
        })
        .body(|mut body| {
            // Keep track of the input button index we are on
            let mut input_idx = 0;

            // Loop through the input rows
            for (title, inputs) in &mut input_rows {
                body.row(row_height, |mut row| {
                    // Add row label
                    row.col(|ui| {
                        ui.label(normal_font.rich(title.to_string()));
                    });

                    // Add buttons for each kind of input
                    for (button_idx, input) in inputs.iter_mut().enumerate() {
                        // The last button is a gamepad binding, the others are keyboard
                        let binding_kind = if button_idx == 2 {
                            BindingKind::Gamepad
                        } else {
                            BindingKind::Keyboard
                        };

                        // Render the button
                        row.col(|ui| {
                            ui.set_width(ui.available_width() * 0.92);

                            let button = BorderedButton::themed(
                                &meta.theme.buttons.small,
                                input.to_string(),
                            )
                            .show(ui);

                            // Start an input binding if the button is clicked
                            if button.clicked() {
                                state.currently_binding_input_idx = Some(input_idx);
                            }
                            // If we are binding an input for this button
                            else if state.currently_binding_input_idx == Some(input_idx) {
                                // Render the binding window
                                egui::Window::new("input_binding_overlay")
                                    .auto_sized()
                                    .collapsible(false)
                                    .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
                                    .frame(egui::Frame::none())
                                    .title_bar(false)
                                    .show(ui.ctx(), |ui| {
                                        let m = meta.theme.panel.border.border_size;
                                        let s = meta.theme.panel.border.scale;
                                        BorderedFrame::new(&meta.theme.panel.border)
                                            // Just enough padding to fit the frame's border image
                                            .padding(egui::Margin {
                                                left: m.left * s,
                                                right: m.right * s,
                                                top: m.top * s,
                                                bottom: m.bottom * s,
                                            })
                                            .show(ui, |ui| {
                                                ui.label(normal_font.rich(localization.get_with(
                                                    "bind-input",
                                                    &fluent_args! {
                                                        "binding" => title.as_ref(),
                                                        "binding_kind" => match binding_kind {
                                                            BindingKind::Keyboard => "keyboard",
                                                            BindingKind::Gamepad => "gamepad",
                                                        }
                                                    },
                                                )));

                                                ui.add_space(normal_font.size / 2.0);

                                                ui.horizontal(|ui| {
                                                    // Cancel button
                                                    if BorderedButton::themed(
                                                        &meta.theme.buttons.small,
                                                        localization.get("cancel"),
                                                    )
                                                    .show(ui)
                                                    .clicked()
                                                    {
                                                        button.request_focus();
                                                        state.currently_binding_input_idx = None;
                                                    }

                                                    // Clear button
                                                    if BorderedButton::themed(
                                                        &meta.theme.buttons.small,
                                                        localization.get("clear-binding"),
                                                    )
                                                    .show(ui)
                                                    .clicked()
                                                    {
                                                        **input = InputKind::None;
                                                        button.request_focus();
                                                        state.currently_binding_input_idx = None;
                                                    }
                                                });

                                                // See if there has been any inputs of the kind we
                                                // are binding.
                                                let bound_input =
                                                    get_input(binding_kind, &keyboard, &gamepad);

                                                // If there has been an input
                                                if let Some(input_kind) = bound_input {
                                                    // Stop listening for inputs
                                                    state.currently_binding_input_idx = None;

                                                    // Reset the focus on the input button
                                                    button.request_focus();

                                                    // Set the input for this button to the pressed
                                                    // input
                                                    **input = input_kind;
                                                }
                                            });
                                    });
                            }
                        });

                        // Increment the input button index
                        input_idx += 1;
                    }
                });
            }
        });
}

/// The kind of input binding to listen for.
enum BindingKind {
    Keyboard,
    Gamepad,
}

fn get_input(
    kind: BindingKind,
    keyboard: &KeyboardInputs,
    gamepad: &GamepadInputs,
) -> Option<InputKind> {
    match kind {
        BindingKind::Keyboard => keyboard.key_events.iter().next().and_then(|event| {
            event
                .button_state
                .pressed()
                .then(|| event.key_code.option().map(InputKind::Keyboard))
                .flatten()
        }),
        BindingKind::Gamepad => {
            gamepad
                .gamepad_events
                .iter()
                .next()
                .and_then(|event| match event {
                    GamepadEvent::Button(e) => {
                        (e.value.abs() > 0.1).then_some(InputKind::Button(e.button))
                    }
                    GamepadEvent::Axis(e) => {
                        if e.value > 0.1 {
                            Some(InputKind::AxisPositive(e.axis))
                        } else if e.value < -0.1 {
                            Some(InputKind::AxisNegative(e.axis))
                        } else {
                            None
                        }
                    }
                    _ => None,
                })
        }
    }
}