#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework.Input;
namespace StardewModdingAPI.Framework.Input
{
/// Manages keyboard state.
internal class KeyboardStateBuilder : IInputStateBuilder
{
/*********
** Fields
*********/
/// The underlying keyboard state.
private KeyboardState? State;
/// The pressed buttons.
private readonly HashSet PressedButtons = new();
/*********
** Public methods
*********/
/// Construct an instance.
/// The initial state.
public KeyboardStateBuilder(KeyboardState state)
{
this.State = state;
this.PressedButtons.Clear();
foreach (var button in state.GetPressedKeys())
this.PressedButtons.Add(button);
}
///
public KeyboardStateBuilder OverrideButtons(IDictionary overrides)
{
foreach (var pair in overrides)
{
if (pair.Key.TryGetKeyboard(out Keys key))
{
this.State = null;
if (pair.Value.IsDown())
this.PressedButtons.Add(key);
else
this.PressedButtons.Remove(key);
}
}
return this;
}
///
public IEnumerable GetPressedButtons()
{
foreach (Keys key in this.PressedButtons)
yield return key.ToSButton();
}
///
public KeyboardState GetState()
{
return
this.State
?? (this.State = new KeyboardState(this.PressedButtons.ToArray())).Value;
}
}
}