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 HashSet();
/*********
** 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);
}
/// Override the states for a set of buttons.
/// The button state overrides.
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;
}
/// Get the currently pressed buttons.
public IEnumerable GetPressedButtons()
{
foreach (Keys key in this.PressedButtons)
yield return key.ToSButton();
}
/// Get the equivalent state.
public KeyboardState GetState()
{
return
this.State
?? (this.State = new KeyboardState(this.PressedButtons.ToArray())).Value;
}
}
}