from typing import Union, Dict
[docs]
class KeyBindings:
"""Per-device button/key binding storage.
Stores one binding string per supported device category:
X-Box, Playstation, Keyboard, or Free.
"""
def __init__(self):
self.xbox = None # type: Union[str, None]
self.playstation = None # type: Union[str, None]
self.keyboard = None # type: Union[str, None]
self.free = None # type: Union[str, None]
[docs]
def get(self, device: str) -> Union[str, None]:
if device == 'X-Box':
return self.xbox
elif device == 'Playstation':
return self.playstation
elif device == "Keyboard":
return self.keyboard
elif device == "Free":
return self.free
raise KeyError("Unknown device '{}'".format(device))
def __getitem__(self, device: str) -> Union[str, None]:
return self.get(device)
def __setitem__(self, device: str, binding: str):
if device == "X-Box":
self.xbox = binding
elif device == "Playstation":
self.playstation = binding
elif device == "Free":
self.free = binding
elif device == "Keyboard":
self.keyboard = binding
else:
raise KeyError("Unknown device '{}'".format(device))
[docs]
def to_dict(self) -> Dict[str, Union[None, str]]:
return {
"X-Box": self.xbox,
"Playstation": self.playstation,
"Keyboard": self.keyboard,
"Free": self.free
}
[docs]
@staticmethod
def from_dict(d: Dict[str, Union[None, str]]):
bindings = KeyBindings()
if "X-Box" in d:
bindings.xbox = d['X-Box']
if "Free" in d:
bindings.free = d['Free']
if "Playstation" in d:
bindings.playstation = d['Playstation']
if "Keyboard" in d:
bindings.keyboard = d['Keyboard']
return bindings