-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControlSettings.cs
More file actions
474 lines (416 loc) · 14.3 KB
/
ControlSettings.cs
File metadata and controls
474 lines (416 loc) · 14.3 KB
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
using System;
using System.Collections.Generic;
using System.Globalization;
using FunkEngine;
using Godot;
using GodotSteam;
public partial class ControlSettings : Node2D, IFocusableMenu
{ //TODO: Add messages when an invalid key is attempted to be set.
public static readonly string LoadPath = "res://Scenes/UI/Remapping/Remap.tscn";
public IFocusableMenu Prev { get; set; }
private Control _focused;
[Export]
private Button _closeButton;
[Export]
private Panel _remapPopup;
[Export]
private Label _remapLabel;
private string _keyboardRemap = "CONTROLS_CHOOSE_TEXT_KEYBOARD";
private string _controllerRemap = "CONTROLS_CHOOSE_TEXT_CONTROLLER";
private string _invalidMessage = "CONTROLS_CHOOSE_INVALID";
private string _duplicateInput = "CONTROLS_CHOOSE_DUPLICATE";
[Export]
private Label _remapDescription;
[Export]
private Timer _remapTimer;
private static readonly string IconPath = "res://Scenes/UI/Remapping/Assets/";
[Export]
private TabContainer _remapTabs;
private Key _tempKeyboardKey;
private JoyButton _tempJoyButton;
private string _chosenKey = "";
//These just don't play well with inputs
private readonly HashSet<Key> _invalidKeys = new HashSet<Key>
{
Key.Ctrl,
Key.Meta,
Key.Alt,
Key.Insert,
Key.Home,
Key.End,
Key.Delete,
Key.Pagedown,
Key.Pageup,
Key.Print,
Key.Scrolllock,
Key.Pause,
Key.Escape,
Key.Numlock,
};
#region String Definition Spam
//The below arrays should be aligned, e.g. all things representing left arrow should be at 0
private const int InputOptions = 6; //1 for each button on an input tab.
private readonly Sprite2D[] _inputSprites = new Sprite2D[InputOptions * 2];
private readonly string[] _inputNodeNames =
[
"LeftArrow",
"RightArrow",
"UpArrow",
"DownArrow",
"SecondaryPlacement",
"Inventory",
];
private readonly string[] _inputSuffixes =
[
"_arrowLeft",
"_arrowRight",
"_arrowUp",
"_arrowDown",
"_secondaryPlacement",
"_inventory", //TODO: Bag icon, since we can't translate Inv similarly in chinese.
];
private readonly string[] _inputMapNames =
[
"WASD_arrowLeft",
"WASD_arrowRight",
"WASD_arrowUp",
"WASD_arrowDown",
"WASD_secondaryPlacement",
"WASD_inventory",
"CONTROLLER_arrowLeft",
"CONTROLLER_arrowRight",
"CONTROLLER_arrowUp",
"CONTROLLER_arrowDown",
"CONTROLLER_secondaryPlacement",
"CONTROLLER_inventory",
"Pause",
];
private const string KeyboardPrefix = "WASD";
private const string JoyPrefix = "CONTROLLER";
private const string KeyboardTabPath = "Panel/TabContainer/CONTROLS_KEYBOARD/";
private const string JoyTabPath = "Panel/TabContainer/CONTROLS_CONTROLLER/";
private const string ButtonNameSuffix = "Button";
private const string SpriteNameSuffix = "Key";
#endregion
#region Initialization
//To think about: Setting things in export arrays.
public override void _Ready()
{
//Sets up buttons in scene, for each button, sets its pressed event
for (int i = 0; i < _inputNodeNames.Length; i++)
{
string keyboardPath = KeyboardTabPath + _inputNodeNames[i] + ButtonNameSuffix;
string controllerPath = JoyTabPath + _inputNodeNames[i] + ButtonNameSuffix;
var i1 = i; //Lambda functions capture changes to the value of i, use extra vars
GetNode<Button>(keyboardPath).Pressed += () => OnRemapButtonPressed(_inputSuffixes[i1]);
var i2 = i;
GetNode<Button>(controllerPath).Pressed += () =>
OnRemapButtonPressed(_inputSuffixes[i2]);
}
_remapTabs.CurrentTab =
SaveSystem.GetConfigValue(SaveSystem.ConfigSettings.InputType).ToString()
== KeyboardPrefix
? 0
: 1;
_remapDescription.Text = Tr(_remapTabs.CurrentTab == 0 ? _keyboardRemap : _controllerRemap);
_remapTimer.Timeout += OnTimerEnd;
_remapTabs.TabChanged += (_) => ChangeInputType();
_closeButton.Pressed += ReturnToPrev;
InitInputSprites();
}
private void InitInputSprites()
{
for (int i = 0; i < InputOptions; i++)
{
var path = KeyboardTabPath + _inputNodeNames[i] + SpriteNameSuffix;
var sprite = GetNode<Sprite2D>(path);
_inputSprites[i] = sprite;
var jPath = JoyTabPath + _inputNodeNames[i] + SpriteNameSuffix;
var jSprite = GetNode<Sprite2D>(jPath);
_inputSprites[i + InputOptions] = jSprite;
}
UpdateKeySprites();
}
#endregion
#region Focus and Menus
public override void _Process(double delta)
{
if (_remapPopup.Visible)
_remapLabel.Text = ((int)_remapTimer.TimeLeft + 1).ToString();
NoNullFocus();
}
public void ResumeFocus()
{
ProcessMode = ProcessModeEnum.Inherit;
}
public void PauseFocus()
{
ProcessMode = ProcessModeEnum.Disabled;
}
public void OpenMenu(IFocusableMenu prev)
{
Prev = prev;
Prev.PauseFocus();
_remapTabs.GetTabControl(_remapTabs.CurrentTab).GetChild<Control>(0).GrabFocus();
}
public void ReturnToPrev()
{
Prev.ResumeFocus();
QueueFree();
}
private void NoNullFocus()
{
var focusedNode = GetViewport().GuiGetFocusOwner();
if (focusedNode != null)
return;
_remapTabs.GetTabBar().GrabFocus();
}
#endregion
/// <summary>
/// Called from changing tabs, sets correct input type based on selected tab.
/// </summary>
private void ChangeInputType()
{
SaveSystem.UpdateConfig(
SaveSystem.ConfigSettings.InputType,
_remapTabs.CurrentTab == 0 ? KeyboardPrefix : JoyPrefix
);
_remapDescription.Text = Tr(_remapTabs.CurrentTab == 0 ? _keyboardRemap : _controllerRemap);
}
/// <summary>
/// Updates all the key sprites to the correct sprite, based on what input is set.
/// </summary>
private void UpdateKeySprites()
{
for (int i = 0; i < InputOptions * 2; i++)
{
var events = InputMap.ActionGetEvents(_inputMapNames[i]);
if (events.Count <= 0)
continue;
string textureName = events[0].AsText();
// Clean up the texture name
if (_inputMapNames[i].StartsWith(KeyboardPrefix))
textureName = CleanKeyboardText(textureName);
else
textureName = textureName.Replace("/", "");
_inputSprites[i].Texture = GD.Load<Texture2D>($"{IconPath}{textureName}.png");
}
}
/// <summary>
/// Should exclusively be called from pressing a remap button.
/// </summary>
/// <param name="keyName">The input suffix of the button.</param>
private void OnRemapButtonPressed(string keyName)
{
_chosenKey = keyName;
StartInputCountdown();
}
private const int TimeForInput = 5;
/// <summary>
/// Start the input countdown window.
/// </summary>
private void StartInputCountdown()
{
_remapLabel.Text = TimeForInput.ToString();
_remapTimer.Start(TimeForInput);
_tempJoyButton = JoyButton.Invalid;
_tempKeyboardKey = Key.None;
_remapPopup.Visible = true;
}
private void OnTimerEnd()
{
_remapPopup.Visible = false;
}
public override void _Input(InputEvent @event)
{
if (_remapPopup.Visible)
{
if (@event.IsActionPressed("Pause"))
{
_remapTimer.Stop();
OnTimerEnd();
GetViewport().SetInputAsHandled();
return;
}
if (
(@event is InputEventKey || @event is InputEventJoypadButton)
&& IsUniqueKey(@event.AsText())
)
{
HandleRemapInput(@event);
GetViewport().SetInputAsHandled();
}
else
{
// when popup is visible we ignore everything except valid remaps
GetViewport().SetInputAsHandled();
}
}
else if (@event.IsActionPressed("ui_cancel"))
{
ReturnToPrev();
GetViewport().SetInputAsHandled();
}
}
/// <summary>
/// Parses if the input is a valid button to set, and whether it is a controller input or keyboard.
/// </summary>
/// <param name="event">The recent input event.</param>
private void HandleRemapInput(InputEvent @event)
{
bool isKeyboard = _remapTabs.CurrentTab == 0;
switch (isKeyboard)
{
case true when @event is InputEventKey keyEvent:
{
if (
_invalidKeys.Contains(keyEvent.Keycode)
|| !FileAccess.FileExists($"{IconPath}{CleanKeyboardText(@event.AsText())}.png")
)
{
_remapDescription.Text = Tr(_invalidMessage);
return;
}
string action = KeyboardPrefix + _chosenKey;
InputMap.ActionEraseEvents(action);
InputMap.ActionAddEvent(action, keyEvent);
SaveKeyInput(_chosenKey, keyEvent);
break;
}
case false when @event is InputEventJoypadButton joyEvent:
{
string action = JoyPrefix + _chosenKey;
InputMap.ActionEraseEvents(action);
InputMap.ActionAddEvent(action, joyEvent);
SaveKeyInput(_chosenKey, joyEvent);
break;
}
default:
return;
}
UpdateKeySprites();
_remapPopup.Visible = false;
}
/// <summary>
/// Dictionary of button input suffix and the config settings that correspond. This feels fine enough.
/// </summary>
private static readonly Dictionary<
string,
(SaveSystem.ConfigSettings keyboard, SaveSystem.ConfigSettings controller)
> ConfigMap = new()
{
{
"_arrowUp",
(SaveSystem.ConfigSettings.InputKeyboardUp, SaveSystem.ConfigSettings.InputControllerUp)
},
{
"_arrowDown",
(
SaveSystem.ConfigSettings.InputKeyboardDown,
SaveSystem.ConfigSettings.InputControllerDown
)
},
{
"_arrowLeft",
(
SaveSystem.ConfigSettings.InputKeyboardLeft,
SaveSystem.ConfigSettings.InputControllerLeft
)
},
{
"_arrowRight",
(
SaveSystem.ConfigSettings.InputKeyboardRight,
SaveSystem.ConfigSettings.InputControllerRight
)
},
{
"_secondaryPlacement",
(
SaveSystem.ConfigSettings.InputKeyboardSecondary,
SaveSystem.ConfigSettings.InputControllerSecondary
)
},
{
"_inventory",
(
SaveSystem.ConfigSettings.InputKeyboardInventory,
SaveSystem.ConfigSettings.InputControllerInventory
)
},
};
public static string GetTextureForInput(string inputMapName)
{
var events = InputMap.ActionGetEvents(inputMapName);
if (events.Count <= 0)
return null;
string textureName = events[0].AsText();
// Clean up the texture name
if (inputMapName.StartsWith(KeyboardPrefix))
textureName = CleanKeyboardText(textureName);
else
textureName = textureName.Replace("/", "");
return $"{IconPath}{textureName}.png";
}
/// <summary>
/// Saves the key to the input based on its input name into the correct config setting.
/// </summary>
/// <param name="button">buttone name string.</param>
/// <param name="key">The input key to be saved.</param>
private void SaveKeyInput(string button, InputEvent key)
{
//Just checks if the button is a button we account for, and gets the correct config setting
if (!ConfigMap.TryGetValue(button, out var configPair))
return;
int keycode = key switch
{
InputEventKey keyEvent => (int)keyEvent.PhysicalKeycode,
InputEventJoypadButton joyEvent => (int)joyEvent.ButtonIndex,
_ => -1,
};
if (keycode < 0)
return;
var config = key is InputEventKey ? configPair.keyboard : configPair.controller;
SaveSystem.UpdateConfig(config, keycode);
}
/// <summary>
/// Keyboard input key as text standardization.
/// </summary>
/// <param name="text">An input event as text.</param>
/// <returns></returns>
private static string CleanKeyboardText(string text)
{
return text.Replace(" (Physical)", "");
}
/// <summary>
/// Returns true if the key is not already mapped to one of our concerned input maps. E.g. returns false if this key is already set on the menu
/// </summary>
/// <param name="keyText">An input event as text.</param>
/// <returns></returns>
private bool IsUniqueKey(string keyText)
{
//nested loops bad, but theoretically this should act as a single loop
//since each action only has 1 event (keybinding)
foreach (string action in _inputMapNames)
{
foreach (InputEvent evt in InputMap.ActionGetEvents(action))
{
if (
(
evt is InputEventKey keyEvent
&& CleanKeyboardText(keyEvent.AsText()) == keyText
) || (evt is InputEventJoypadButton padEvent && padEvent.AsText() == keyText)
)
{
_remapDescription.Text = Tr(_duplicateInput);
return false;
}
}
}
return true;
}
public static bool IsOutOfFocus(Node asker)
{
return !asker.GetWindow().HasFocus() || SteamWhisperer.IsOverlayActive;
}
}