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, or null to get the latest state.
public KeyboardStateBuilder(KeyboardState? state = null)
{
this.Reset(state);
}
/// Reset the tracked state.
/// The state from which to reset, or null to get the latest state.
public KeyboardStateBuilder Reset(KeyboardState? state = null)
{
this.State = state ??= Keyboard.GetState();
this.PressedButtons.Clear();
foreach (var button in state.Value.GetPressedKeys())
this.PressedButtons.Add(button);
return this;
}
/// 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;
}
}
}