summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/Input/KeyboardStateBuilder.cs
blob: eadb7a8a7c6026583fea09ee67547e35b6e601c9 (plain)
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
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework.Input;

namespace StardewModdingAPI.Framework.Input
{
    /// <summary>Manages keyboard state.</summary>
    internal class KeyboardStateBuilder : IInputStateBuilder<KeyboardStateBuilder, KeyboardState>
    {
        /*********
        ** Fields
        *********/
        /// <summary>The underlying keyboard state.</summary>
        private KeyboardState? State;

        /// <summary>The pressed buttons.</summary>
        private readonly HashSet<Keys> PressedButtons = new HashSet<Keys>();


        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="state">The initial state.</param>
        public KeyboardStateBuilder(KeyboardState state)
        {
            this.State = state;

            this.PressedButtons.Clear();
            foreach (var button in state.GetPressedKeys())
                this.PressedButtons.Add(button);
        }

        /// <inheritdoc />
        public KeyboardStateBuilder OverrideButtons(IDictionary<SButton, SButtonState> 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;
        }

        /// <inheritdoc />
        public IEnumerable<SButton> GetPressedButtons()
        {
            foreach (Keys key in this.PressedButtons)
                yield return key.ToSButton();
        }

        /// <inheritdoc />
        public KeyboardState GetState()
        {
            return
                this.State
                ?? (this.State = new KeyboardState(this.PressedButtons.ToArray())).Value;
        }
    }
}