-
-
Notifications
You must be signed in to change notification settings - Fork 910
/
KeyboardDeviceBase.cs
103 lines (86 loc) · 3.24 KB
/
KeyboardDeviceBase.cs
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections.Generic;
using Stride.Core.Collections;
namespace Stride.Input
{
/// <summary>
/// Base class for keyboard devices
/// </summary>
public abstract class KeyboardDeviceBase : IKeyboardDevice
{
private readonly HashSet<Keys> pressedKeys = new HashSet<Keys>();
private readonly HashSet<Keys> releasedKeys = new HashSet<Keys>();
private readonly HashSet<Keys> downKeys = new HashSet<Keys>();
protected readonly List<KeyEvent> Events = new List<KeyEvent>();
public readonly Dictionary<Keys, int> KeyRepeats = new Dictionary<Keys, int>();
protected KeyboardDeviceBase()
{
PressedKeys = new ReadOnlySet<Keys>(pressedKeys);
ReleasedKeys = new ReadOnlySet<Keys>(releasedKeys);
DownKeys = new ReadOnlySet<Keys>(downKeys);
}
public Core.Collections.IReadOnlySet<Keys> PressedKeys { get; }
public Core.Collections.IReadOnlySet<Keys> ReleasedKeys { get; }
public Core.Collections.IReadOnlySet<Keys> DownKeys { get; }
public abstract string Name { get; }
public abstract Guid Id { get; }
public int Priority { get; set; }
public abstract IInputSource Source { get; }
public virtual void Update(List<InputEvent> inputEvents)
{
pressedKeys.Clear();
releasedKeys.Clear();
// Fire events
foreach (var keyEvent in Events)
{
inputEvents.Add(keyEvent);
if (keyEvent != null)
{
if (keyEvent.IsDown)
{
pressedKeys.Add(keyEvent.Key);
}
else
{
releasedKeys.Add(keyEvent.Key);
}
}
}
Events.Clear();
}
public void HandleKeyDown(Keys key)
{
// Increment repeat count on subsequent down events
int repeatCount;
if (KeyRepeats.TryGetValue(key, out repeatCount))
{
KeyRepeats[key] = ++repeatCount;
}
else
{
KeyRepeats.Add(key, repeatCount);
downKeys.Add(key);
}
var keyEvent = InputEventPool<KeyEvent>.GetOrCreate(this);
keyEvent.IsDown = true;
keyEvent.Key = key;
keyEvent.RepeatCount = repeatCount;
Events.Add(keyEvent);
}
public void HandleKeyUp(Keys key)
{
// Prevent duplicate up events
if (!KeyRepeats.ContainsKey(key))
return;
KeyRepeats.Remove(key);
downKeys.Remove(key);
var keyEvent = InputEventPool<KeyEvent>.GetOrCreate(this);
keyEvent.IsDown = false;
keyEvent.Key = key;
keyEvent.RepeatCount = 0;
Events.Add(keyEvent);
}
}
}