using System.Collections.Generic;
using Microsoft.Xna.Framework.Input;
namespace StardewModdingAPI.Framework.Input
{
/// Manages mouse state.
internal class MouseStateBuilder : IInputStateBuilder
{
/*********
** Fields
*********/
/// The underlying mouse state.
private MouseState? State;
/// The current button states.
private IDictionary ButtonStates;
/// The mouse wheel scroll value.
private int ScrollWheelValue;
/*********
** Accessors
*********/
/// The X cursor position.
public int X { get; private set; }
/// The Y cursor position.
public int Y { get; private set; }
/*********
** Public methods
*********/
/// Construct an instance.
/// The initial state, or null to get the latest state.
public MouseStateBuilder(MouseState? state = null)
{
this.Reset(state);
}
/// Reset the tracked state.
/// The state from which to reset, or null to get the latest state.
public MouseStateBuilder Reset(MouseState? state = null)
{
this.State = state ??= Mouse.GetState();
this.ButtonStates = new Dictionary
{
[SButton.MouseLeft] = state.Value.LeftButton,
[SButton.MouseMiddle] = state.Value.MiddleButton,
[SButton.MouseRight] = state.Value.RightButton,
[SButton.MouseX1] = state.Value.XButton1,
[SButton.MouseX2] = state.Value.XButton2
};
this.X = state.Value.X;
this.Y = state.Value.Y;
this.ScrollWheelValue = state.Value.ScrollWheelValue;
return this;
}
/// Override the states for a set of buttons.
/// The button state overrides.
public MouseStateBuilder OverrideButtons(IDictionary overrides)
{
foreach (var pair in overrides)
{
if (this.ButtonStates.ContainsKey(pair.Key))
{
this.State = null;
this.ButtonStates[pair.Key] = pair.Value.IsDown() ? ButtonState.Pressed : ButtonState.Released;
}
}
return this;
}
/// Get the currently pressed buttons.
public IEnumerable GetPressedButtons()
{
foreach (var pair in this.ButtonStates)
{
if (pair.Value == ButtonState.Pressed)
yield return pair.Key;
}
}
/// Get the equivalent state.
public MouseState GetState()
{
if (this.State == null)
{
this.State = new MouseState(
x: this.X,
y: this.Y,
scrollWheel: this.ScrollWheelValue,
leftButton: this.ButtonStates[SButton.MouseLeft],
middleButton: this.ButtonStates[SButton.MouseMiddle],
rightButton: this.ButtonStates[SButton.MouseRight],
xButton1: this.ButtonStates[SButton.MouseX1],
xButton2: this.ButtonStates[SButton.MouseX2]
);
}
return this.State.Value;
}
}
}