1028 lines
43 KiB
Python
1028 lines
43 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""Keyboard and game controller input through one layer of actions.
|
|
|
|
A game names what the player can do, such as accelerate, steer or jump, and
|
|
gives each action default keys and controller inputs. It then asks about
|
|
actions, never keys:
|
|
|
|
controls = Controls([
|
|
Action("steer", "Steer", "driving", keys=["left/right"], pad=["leftStickX", "dpadLeft/dpadRight"], axis=True),
|
|
Action("horn", "Horn", "driving", keys=["h"], pad=["l1"]),
|
|
])
|
|
while playing:
|
|
events = pygame.event.get()
|
|
controls.update(events)
|
|
if controls.pressed("horn"):
|
|
...
|
|
steering = controls.value("steer")
|
|
|
|
Controller inputs are named by position, not by label, so a binding means the
|
|
same button on every controller: south, east, west and north for the four
|
|
face buttons, l1, r1, l2, r2, l3, r3, select, start, guide, touchpad,
|
|
dpadUp, dpadDown, dpadLeft, dpadRight, and the sticks as leftStickX,
|
|
leftStickY, rightStickX and rightStickY, or one direction of one, such as
|
|
leftStickUp. Names are spoken in PlayStation terms unless the controller or
|
|
the player's setting says otherwise.
|
|
|
|
Bindings are written as text, which is also how they are saved:
|
|
|
|
- "h", "page up", "space": one key; "ctrl", "shift" and "alt" are either one.
|
|
- "ctrl+s", "l1+west": hold the first, press the last.
|
|
- "left/right", "dpadLeft/dpadRight": a pair, for an axis, negative first.
|
|
- "leftStickX", "-leftStickY": a whole stick axis, the second reversed.
|
|
|
|
Every library menu accepts the controller through translate_event: the d-pad
|
|
and left stick are the arrow keys, cross is Enter and circle is Escape. Those
|
|
menu controls are fixed, so a player can always find their way back.
|
|
"""
|
|
|
|
import os
|
|
import time
|
|
|
|
import pygame
|
|
|
|
from .i18n import _, N_
|
|
|
|
# Face buttons by position on every controller. Without this SDL 2 swaps A and B, and X and Y, on Nintendo
|
|
# controllers to match their labels. It must be set before the controller subsystem starts.
|
|
os.environ.setdefault("SDL_GAMECONTROLLER_USE_BUTTON_LABELS", "0")
|
|
|
|
padButtons = {
|
|
"south": pygame.CONTROLLER_BUTTON_A,
|
|
"east": pygame.CONTROLLER_BUTTON_B,
|
|
"west": pygame.CONTROLLER_BUTTON_X,
|
|
"north": pygame.CONTROLLER_BUTTON_Y,
|
|
"select": pygame.CONTROLLER_BUTTON_BACK,
|
|
"guide": pygame.CONTROLLER_BUTTON_GUIDE,
|
|
"start": pygame.CONTROLLER_BUTTON_START,
|
|
"l3": pygame.CONTROLLER_BUTTON_LEFTSTICK,
|
|
"r3": pygame.CONTROLLER_BUTTON_RIGHTSTICK,
|
|
"l1": pygame.CONTROLLER_BUTTON_LEFTSHOULDER,
|
|
"r1": pygame.CONTROLLER_BUTTON_RIGHTSHOULDER,
|
|
"dpadUp": pygame.CONTROLLER_BUTTON_DPAD_UP,
|
|
"dpadDown": pygame.CONTROLLER_BUTTON_DPAD_DOWN,
|
|
"dpadLeft": pygame.CONTROLLER_BUTTON_DPAD_LEFT,
|
|
"dpadRight": pygame.CONTROLLER_BUTTON_DPAD_RIGHT,
|
|
# SDL's misc button (share, capture or mic) and touchpad click have no pygame constants.
|
|
"misc": 15,
|
|
"touchpad": 20,
|
|
}
|
|
padButtonNames = {number: name for name, number in padButtons.items()}
|
|
|
|
padAxes = {
|
|
"leftStickX": pygame.CONTROLLER_AXIS_LEFTX,
|
|
"leftStickY": pygame.CONTROLLER_AXIS_LEFTY,
|
|
"rightStickX": pygame.CONTROLLER_AXIS_RIGHTX,
|
|
"rightStickY": pygame.CONTROLLER_AXIS_RIGHTY,
|
|
}
|
|
padTriggers = {"l2": pygame.CONTROLLER_AXIS_TRIGGERLEFT, "r2": pygame.CONTROLLER_AXIS_TRIGGERRIGHT}
|
|
|
|
# One direction of a stick: the axis it is on and the sign. SDL's y axes are positive downwards.
|
|
stickDirections = {}
|
|
for _stick in ("leftStick", "rightStick"):
|
|
stickDirections.update({
|
|
f"{_stick}Left": (f"{_stick}X", -1), f"{_stick}Right": (f"{_stick}X", 1),
|
|
f"{_stick}Up": (f"{_stick}Y", -1), f"{_stick}Down": (f"{_stick}Y", 1),
|
|
})
|
|
|
|
# Every controller input that is on or off, or pressed some way: buttons, triggers and stick directions.
|
|
padInputNames = list(padButtons) + list(padTriggers) + list(stickDirections)
|
|
padNameLookup = {name.lower(): name for name in padInputNames + list(padAxes)}
|
|
|
|
keyModifiers = {
|
|
"ctrl": (pygame.K_LCTRL, pygame.K_RCTRL),
|
|
"shift": (pygame.K_LSHIFT, pygame.K_RSHIFT),
|
|
"alt": (pygame.K_LALT, pygame.K_RALT),
|
|
"meta": (pygame.K_LMETA, pygame.K_RMETA),
|
|
}
|
|
modifierKeyCodes = {code for codes in keyModifiers.values() for code in codes}
|
|
|
|
stickDeadzone = 0.2
|
|
triggerDeadzone = 0.1
|
|
# An analog input counts as held from pressThreshold until it falls below releaseThreshold,
|
|
# so a stick resting near the line does not flicker between the two.
|
|
pressThreshold = 0.5
|
|
releaseThreshold = 0.3
|
|
repeatDelayMs = 500
|
|
repeatIntervalMs = 100
|
|
repeatTickMs = 25
|
|
|
|
# The fixed controller inputs of every library menu, and the key each one stands for.
|
|
# Inputs marked True repeat while held, like a held key.
|
|
menuPadKeys = {
|
|
"dpadUp": (pygame.K_UP, True), "leftStickUp": (pygame.K_UP, True),
|
|
"dpadDown": (pygame.K_DOWN, True), "leftStickDown": (pygame.K_DOWN, True),
|
|
"dpadLeft": (pygame.K_LEFT, True), "leftStickLeft": (pygame.K_LEFT, True),
|
|
"dpadRight": (pygame.K_RIGHT, True), "leftStickRight": (pygame.K_RIGHT, True),
|
|
"south": (pygame.K_RETURN, False),
|
|
"east": (pygame.K_ESCAPE, False),
|
|
"north": (pygame.K_SPACE, False),
|
|
"l1": (pygame.K_PAGEUP, True),
|
|
"r1": (pygame.K_PAGEDOWN, True),
|
|
"l2": (pygame.K_HOME, False),
|
|
"r2": (pygame.K_END, False),
|
|
}
|
|
|
|
rumblePatterns = {
|
|
"tap": (0.0, 0.5, 80),
|
|
"thud": (0.9, 0.2, 180),
|
|
"buzz": (0.4, 0.6, 400),
|
|
"crash": (1.0, 1.0, 600),
|
|
}
|
|
|
|
buttonNameSchemes = ("auto", "playstation", "xbox", "nintendo")
|
|
buttonSchemeTitles = {
|
|
"auto": N_("automatic"),
|
|
"playstation": N_("PlayStation"),
|
|
"xbox": N_("Xbox"),
|
|
"nintendo": N_("Nintendo"),
|
|
}
|
|
|
|
# Spoken names of controller inputs. Each scheme overrides the shared names it labels differently.
|
|
sharedPadNames = {
|
|
"dpadUp": N_("d-pad up"), "dpadDown": N_("d-pad down"),
|
|
"dpadLeft": N_("d-pad left"), "dpadRight": N_("d-pad right"),
|
|
"leftStickUp": N_("left stick up"), "leftStickDown": N_("left stick down"),
|
|
"leftStickLeft": N_("left stick left"), "leftStickRight": N_("left stick right"),
|
|
"rightStickUp": N_("right stick up"), "rightStickDown": N_("right stick down"),
|
|
"rightStickLeft": N_("right stick left"), "rightStickRight": N_("right stick right"),
|
|
"leftStickX": N_("left stick left and right"), "leftStickY": N_("left stick up and down"),
|
|
"rightStickX": N_("right stick left and right"), "rightStickY": N_("right stick up and down"),
|
|
"touchpad": N_("touchpad"),
|
|
"misc": N_("misc button"),
|
|
}
|
|
schemePadNames = {
|
|
"playstation": {
|
|
"south": N_("cross"), "east": N_("circle"), "west": N_("square"), "north": N_("triangle"),
|
|
"l1": N_("L1"), "r1": N_("R1"), "l2": N_("L2"), "r2": N_("R2"), "l3": N_("L3"), "r3": N_("R3"),
|
|
"select": N_("share"), "start": N_("options"), "guide": N_("PS button"), "misc": N_("mute button"),
|
|
},
|
|
"xbox": {
|
|
"south": N_("A"), "east": N_("B"), "west": N_("X"), "north": N_("Y"),
|
|
"l1": N_("LB"), "r1": N_("RB"), "l2": N_("LT"), "r2": N_("RT"),
|
|
"l3": N_("left stick click"), "r3": N_("right stick click"),
|
|
"select": N_("view"), "start": N_("menu"), "guide": N_("Xbox button"), "misc": N_("share"),
|
|
},
|
|
"nintendo": {
|
|
"south": N_("B"), "east": N_("A"), "west": N_("Y"), "north": N_("X"),
|
|
"l1": N_("L"), "r1": N_("R"), "l2": N_("ZL"), "r2": N_("ZR"),
|
|
"l3": N_("left stick click"), "r3": N_("right stick click"),
|
|
"select": N_("minus"), "start": N_("plus"), "guide": N_("home"), "misc": N_("capture"),
|
|
},
|
|
}
|
|
|
|
# Saved key names that would clash with the binding separators or configparser get their own words.
|
|
keySaveNames = {
|
|
pygame.K_COMMA: "comma", pygame.K_PLUS: "plus", pygame.K_SLASH: "slash", pygame.K_PERCENT: "percent",
|
|
pygame.K_KP_PLUS: "keypad plus", pygame.K_KP_DIVIDE: "keypad slash", pygame.K_KP_ENTER: "keypad enter",
|
|
pygame.K_RETURN: "return",
|
|
}
|
|
# Spoken key names that read better than pygame's.
|
|
keySpokenNames = {
|
|
"return": N_("enter"), "up": N_("up arrow"), "down": N_("down arrow"),
|
|
"left": N_("left arrow"), "right": N_("right arrow"), "space": N_("space"),
|
|
"escape": N_("escape"), "backspace": N_("backspace"), "tab": N_("tab"),
|
|
"ctrl": N_("control"), "shift": N_("shift"), "alt": N_("alt"), "meta": N_("meta"),
|
|
"left ctrl": N_("left control"), "right ctrl": N_("right control"),
|
|
}
|
|
|
|
|
|
def _report(message):
|
|
"""Print a problem for whoever runs the game from a terminal."""
|
|
print(f"{message} [{time.ctime()}]")
|
|
|
|
|
|
def key_save_name(keyCode):
|
|
"""The name a key is saved under, such as "page up", "h" or "comma"."""
|
|
if keyCode in keySaveNames:
|
|
return keySaveNames[keyCode]
|
|
name = pygame.key.name(keyCode)
|
|
if name.startswith("[") and name.endswith("]") and len(name) > 2:
|
|
name = f"keypad {name[1:-1]}"
|
|
if not name or name == "unknown key" or any(character in name for character in ",+/%"):
|
|
return f"key{keyCode}"
|
|
return name
|
|
|
|
|
|
_keyCodesByName = None
|
|
|
|
|
|
def key_code_for(name):
|
|
"""The key code saved as name, or None if no key has it."""
|
|
global _keyCodesByName
|
|
if _keyCodesByName is None:
|
|
_keyCodesByName = {}
|
|
for attribute in dir(pygame):
|
|
if attribute.startswith("K_"):
|
|
code = getattr(pygame, attribute)
|
|
_keyCodesByName.setdefault(key_save_name(code), code)
|
|
name = name.strip().lower()
|
|
if name in _keyCodesByName:
|
|
return _keyCodesByName[name]
|
|
if name.startswith("key") and name[3:].isdigit():
|
|
return int(name[3:])
|
|
return None
|
|
|
|
|
|
class Binding:
|
|
"""One way to trigger an action, parsed from text such as "l1+west" or "left/right".
|
|
|
|
device is "keyboard" or "pad". kind is "button" for one input, "pair" for a negative and a
|
|
positive input, or "axis" for a whole stick axis. modifiers must be held for it to count.
|
|
Inputs are ("key", keyCodes) or ("pad", name); a whole axis is ("axis", name).
|
|
"""
|
|
|
|
def __init__(self, text, device):
|
|
self.device = device
|
|
self.text = text.strip()
|
|
self.inverted = False
|
|
body = self.text
|
|
parts = body.split("+")
|
|
# A trailing "+" is the plus key, written "plus", so any empty part is a mistake.
|
|
if any(not part.strip() for part in parts):
|
|
raise ValueError(f"empty part in {text!r}")
|
|
self.modifiers = tuple(self._parse_input(part, allowAxis=False) for part in parts[:-1])
|
|
last = parts[-1].strip()
|
|
if "/" in last:
|
|
negative, _slash, positive = last.partition("/")
|
|
self.kind = "pair"
|
|
self.negative = self._parse_input(negative, allowAxis=False)
|
|
self.positive = self._parse_input(positive, allowAxis=False)
|
|
self.trigger = None
|
|
else:
|
|
if device == "pad" and last.startswith("-"):
|
|
self.inverted = True
|
|
last = last[1:]
|
|
self.trigger = self._parse_input(last, allowAxis=True)
|
|
self.kind = "axis" if self.trigger[0] == "axis" else "button"
|
|
if self.inverted and self.kind != "axis":
|
|
raise ValueError(f"only a whole axis can be reversed: {text!r}")
|
|
self.negative = self.positive = None
|
|
|
|
def _parse_input(self, text, allowAxis):
|
|
text = text.strip()
|
|
if self.device == "keyboard":
|
|
if text.lower() in keyModifiers:
|
|
return ("key", keyModifiers[text.lower()])
|
|
code = key_code_for(text)
|
|
if code is None:
|
|
raise ValueError(f"unknown key {text!r}")
|
|
return ("key", (code,))
|
|
name = padNameLookup.get(text.lower())
|
|
if name is None:
|
|
raise ValueError(f"unknown controller input {text!r}")
|
|
if name in padAxes:
|
|
if not allowAxis:
|
|
raise ValueError(f"a whole axis cannot be part of a pair or held: {text!r}")
|
|
return ("axis", name)
|
|
return ("pad", name)
|
|
|
|
def inputs(self):
|
|
"""The inputs this binding reacts to, each with the modifiers, for finding clashes."""
|
|
if self.kind == "pair":
|
|
triggers = [self.negative, self.positive]
|
|
elif self.kind == "axis":
|
|
axisName = self.trigger[1]
|
|
triggers = [("pad", name) for name, (axis, _sign) in stickDirections.items() if axis == axisName]
|
|
else:
|
|
triggers = [self.trigger]
|
|
return {(self.modifiers, trigger) for trigger in triggers}
|
|
|
|
def __eq__(self, other):
|
|
return isinstance(other, Binding) and (self.device, self.text.lower()) == (other.device, other.text.lower())
|
|
|
|
def __hash__(self):
|
|
return hash((self.device, self.text.lower()))
|
|
|
|
def __repr__(self):
|
|
return f"Binding({self.text!r}, {self.device!r})"
|
|
|
|
|
|
def parse_bindings(texts, device):
|
|
"""Bindings from a list of texts, or one comma-separated text, skipping and reporting bad ones."""
|
|
if isinstance(texts, str):
|
|
texts = [part for part in texts.split(",") if part.strip()]
|
|
bindings = []
|
|
for text in texts:
|
|
try:
|
|
binding = Binding(text, device)
|
|
except ValueError as error:
|
|
_report(f"Ignoring {device} binding {text!r}: {error}")
|
|
continue
|
|
if binding not in bindings:
|
|
bindings.append(binding)
|
|
return bindings
|
|
|
|
|
|
class Action:
|
|
"""Something the player can do, with its default keys and controller inputs.
|
|
|
|
Args:
|
|
actionId (str): What the game asks about, such as "horn".
|
|
label (str or function): What the controls menu says for it; a function is asked each time,
|
|
so a translated label follows a change of language. Defaults to actionId.
|
|
group (str): Actions in one group may not share an input; different groups may.
|
|
keys (list): Default keyboard bindings, such as ["h"] or ["left/right"].
|
|
pad (list): Default controller bindings, such as ["l1", "west"] or ["leftStickX"].
|
|
axis (bool): True for an action that goes both ways, such as steering, so the controls menu
|
|
asks for a stick or for a pair of inputs.
|
|
negativeLabel, positiveLabel (str): What the two directions of an axis are called; "left" and "right".
|
|
"""
|
|
|
|
def __init__(self, actionId, label=None, group="game", keys=(), pad=(), axis=False,
|
|
negativeLabel=None, positiveLabel=None, fixed=False):
|
|
self.actionId = actionId
|
|
self._label = label
|
|
self.group = group
|
|
self.keys = list(keys)
|
|
self.pad = list(pad)
|
|
self.axis = axis
|
|
self._negativeLabel = negativeLabel
|
|
self._positiveLabel = positiveLabel
|
|
self.fixed = fixed
|
|
|
|
@staticmethod
|
|
def _text(value, fallback):
|
|
if callable(value):
|
|
value = value()
|
|
return value if value else fallback
|
|
|
|
@property
|
|
def label(self):
|
|
return self._text(self._label, self.actionId)
|
|
|
|
@property
|
|
def negativeLabel(self):
|
|
return self._text(self._negativeLabel, _("left"))
|
|
|
|
@property
|
|
def positiveLabel(self):
|
|
return self._text(self._positiveLabel, _("right"))
|
|
|
|
def defaults(self, device):
|
|
return list(self.keys if device == "keyboard" else self.pad)
|
|
|
|
|
|
# The library's own menu actions. They cannot be rebound, so every menu always works.
|
|
menuActions = [
|
|
Action("menuUp", N_("Menu up"), "menu", keys=["up"], pad=["dpadUp", "leftStickUp"], fixed=True),
|
|
Action("menuDown", N_("Menu down"), "menu", keys=["down"], pad=["dpadDown", "leftStickDown"], fixed=True),
|
|
Action("menuLeft", N_("Menu left"), "menu", keys=["left"], pad=["dpadLeft", "leftStickLeft"], fixed=True),
|
|
Action("menuRight", N_("Menu right"), "menu", keys=["right"], pad=["dpadRight", "leftStickRight"], fixed=True),
|
|
Action("confirm", N_("Confirm"), "menu", keys=["return", "keypad enter"], pad=["south"], fixed=True),
|
|
Action("back", N_("Back"), "menu", keys=["escape"], pad=["east"], fixed=True),
|
|
]
|
|
|
|
|
|
def controller_scheme(name):
|
|
"""Which button names suit a controller, from the name SDL gives it."""
|
|
lowered = (name or "").lower()
|
|
if any(word in lowered for word in ("xbox", "x-box", "xinput", "microsoft")):
|
|
return "xbox"
|
|
if any(word in lowered for word in ("nintendo", "switch", "joy-con", "joycon", "pro controller")):
|
|
return "nintendo"
|
|
return "playstation"
|
|
|
|
|
|
class PygameDevices:
|
|
"""The real keyboard and controllers, through pygame and SDL's game controller API.
|
|
|
|
Controls talks to the hardware only through this, so tests can give it a fake.
|
|
"""
|
|
|
|
def __init__(self):
|
|
self.started = False
|
|
self.pads = {}
|
|
self.joystickCount = -1
|
|
self.repeatEvent = None
|
|
|
|
def start(self):
|
|
"""Start the controller subsystem once pygame is running. Returns True when started."""
|
|
if self.started:
|
|
return True
|
|
# Some games start only pygame's display, never pygame.init(); that is enough for controllers.
|
|
if not (pygame.get_init() or pygame.display.get_init()):
|
|
return False
|
|
try:
|
|
from pygame._sdl2 import controller
|
|
controller.init()
|
|
self.controllerModule = controller
|
|
self.repeatEvent = pygame.event.custom_type()
|
|
self.started = True
|
|
except Exception as error:
|
|
_report(f"Game controllers are unavailable: {error}")
|
|
self.started = False
|
|
return False
|
|
return True
|
|
|
|
def check(self):
|
|
"""Open new controllers and forget removed ones. Returns (added names, removed names)."""
|
|
if not self.started:
|
|
return [], []
|
|
try:
|
|
count = pygame.joystick.get_count()
|
|
except pygame.error:
|
|
return [], []
|
|
removed = []
|
|
for instanceId, pad in list(self.pads.items()):
|
|
try:
|
|
attached = pad.attached()
|
|
except Exception:
|
|
attached = False
|
|
if not attached:
|
|
removed.append(getattr(pad, "name", ""))
|
|
del self.pads[instanceId]
|
|
added = []
|
|
if count != self.joystickCount or removed:
|
|
self.joystickCount = count
|
|
for index in range(count):
|
|
try:
|
|
if not self.controllerModule.is_controller(index):
|
|
continue
|
|
instanceId = pygame.joystick.Joystick(index).get_instance_id()
|
|
if instanceId in self.pads:
|
|
continue
|
|
pad = self.controllerModule.Controller(index)
|
|
self.pads[instanceId] = pad
|
|
added.append(pad.name)
|
|
except Exception as error:
|
|
_report(f"Could not open controller {index}: {error}")
|
|
return added, removed
|
|
|
|
def controllers(self):
|
|
return list(self.pads.values())
|
|
|
|
def key_state(self):
|
|
try:
|
|
return pygame.key.get_pressed()
|
|
except pygame.error:
|
|
return {}
|
|
|
|
def ticks(self):
|
|
return pygame.time.get_ticks()
|
|
|
|
def set_repeat_timer(self, running):
|
|
"""Ask for one repeat tick soon, or stop. Each tick is asked for again while a menu input is held,
|
|
so the ticks stop by themselves once nothing reads them."""
|
|
if self.repeatEvent is not None:
|
|
pygame.time.set_timer(self.repeatEvent, repeatTickMs if running else 0, 1 if running else 0)
|
|
|
|
def wait(self, timeoutMs):
|
|
return pygame.event.wait(timeoutMs)
|
|
|
|
|
|
_sharedDevices = None
|
|
|
|
|
|
def shared_devices():
|
|
global _sharedDevices
|
|
if _sharedDevices is None:
|
|
_sharedDevices = PygameDevices()
|
|
return _sharedDevices
|
|
|
|
|
|
def _default_config():
|
|
from .services import ConfigService
|
|
return ConfigService.get_instance()
|
|
|
|
|
|
def _default_speak(text):
|
|
from .speech import speak
|
|
speak(text)
|
|
|
|
|
|
class Controls:
|
|
"""The player's actions, from the keyboard and any connected controller.
|
|
|
|
Making one makes it the game's controls, which library menus and controls_menu use.
|
|
Make it after initialize_gui, so the player's saved bindings can be read.
|
|
|
|
Args:
|
|
actions (list): The game's Actions. The library's menu actions are always added.
|
|
config: Where bindings are saved, anything with localConfig (a ConfigParser) and
|
|
write_local_config(), such as ConfigService or Config. Defaults to the game's config.ini.
|
|
groupLabels (dict or function): What the controls menu says for each group; a group without
|
|
one is spoken with underscores read as spaces.
|
|
speak (function): Says hot-plug messages; defaults to the library's speak.
|
|
devices: The hardware; tests pass a fake.
|
|
"""
|
|
|
|
_instance = None
|
|
keyboardSection = "keyboard"
|
|
padSection = "controller"
|
|
optionsSection = "controller options"
|
|
|
|
@classmethod
|
|
def get_instance(cls):
|
|
"""The game's controls, or controls with only the menu actions if the game made none."""
|
|
if cls._instance is None:
|
|
cls()
|
|
return cls._instance
|
|
|
|
def __init__(self, actions=(), config=None, groupLabels=None, speak=None, devices=None):
|
|
self.devices = devices if devices is not None else shared_devices()
|
|
self._config = config
|
|
self.groupLabels = groupLabels
|
|
self.speak = speak if speak is not None else _default_speak
|
|
self.actions = {}
|
|
for action in list(menuActions) + list(actions):
|
|
if action.actionId in self.actions:
|
|
raise ValueError(f"two actions are called {action.actionId!r}")
|
|
self.actions[action.actionId] = action
|
|
self.rumbleEnabled = True
|
|
self.rumbleStrength = 100
|
|
self.buttonNames = "auto"
|
|
self.bindings = {}
|
|
for action in self.actions.values():
|
|
for device in ("keyboard", "pad"):
|
|
self.bindings[(action.actionId, device)] = parse_bindings(action.defaults(device), device)
|
|
self._load()
|
|
self._rebuild()
|
|
self._held = set()
|
|
self._pressed = set()
|
|
self._padState = {}
|
|
self._axisState = {}
|
|
self._keyState = {}
|
|
self._previousAxes = {}
|
|
self._menuHeld = {}
|
|
self._repeatRunning = False
|
|
Controls._instance = self
|
|
|
|
# Saved settings
|
|
|
|
@property
|
|
def config(self):
|
|
if self._config is None:
|
|
self._config = _default_config()
|
|
return self._config
|
|
|
|
def _load(self):
|
|
try:
|
|
parser = self.config.localConfig
|
|
except Exception as error:
|
|
_report(f"Could not read control settings: {error}")
|
|
return
|
|
byLowerId = {actionId.lower(): action for actionId, action in self.actions.items() if not action.fixed}
|
|
for device, section in (("keyboard", self.keyboardSection), ("pad", self.padSection)):
|
|
if not parser.has_section(section):
|
|
continue
|
|
for option, value in parser.items(section, raw=True):
|
|
action = byLowerId.get(option.lower())
|
|
if action is None:
|
|
continue
|
|
self.bindings[(action.actionId, device)] = parse_bindings(value, device)
|
|
if parser.has_section(self.optionsSection):
|
|
section = self.optionsSection
|
|
try:
|
|
self.rumbleEnabled = parser.getboolean(section, "rumble", fallback=True)
|
|
self.rumbleStrength = max(0, min(100, parser.getint(section, "rumble strength", fallback=100)))
|
|
except ValueError as error:
|
|
_report(f"Ignoring a bad rumble setting: {error}")
|
|
names = parser.get(section, "button names", fallback="auto", raw=True).strip().lower()
|
|
self.buttonNames = names if names in buttonNameSchemes else "auto"
|
|
|
|
def save(self):
|
|
"""Save the bindings that differ from the game's defaults, and the controller options."""
|
|
try:
|
|
parser = self.config.localConfig
|
|
for device, section in (("keyboard", self.keyboardSection), ("pad", self.padSection)):
|
|
if not parser.has_section(section):
|
|
parser.add_section(section)
|
|
for action in self.game_actions():
|
|
current = self.bindings[(action.actionId, device)]
|
|
if current == parse_bindings(action.defaults(device), device):
|
|
parser.remove_option(section, action.actionId)
|
|
else:
|
|
parser.set(section, action.actionId, ", ".join(binding.text for binding in current))
|
|
if not parser.items(section, raw=True):
|
|
parser.remove_section(section)
|
|
if not parser.has_section(self.optionsSection):
|
|
parser.add_section(self.optionsSection)
|
|
parser.set(self.optionsSection, "rumble", "on" if self.rumbleEnabled else "off")
|
|
parser.set(self.optionsSection, "rumble strength", str(self.rumbleStrength))
|
|
parser.set(self.optionsSection, "button names", self.buttonNames)
|
|
self.config.write_local_config()
|
|
except Exception as error:
|
|
_report(f"Could not save control settings: {error}")
|
|
|
|
# Bindings
|
|
|
|
def game_actions(self):
|
|
"""The actions a player can rebind, in the order the game gave them."""
|
|
return [action for action in self.actions.values() if not action.fixed]
|
|
|
|
def get_bindings(self, actionId, device):
|
|
"""The bindings of one action on "keyboard" or "pad", as text."""
|
|
return [binding.text for binding in self.bindings[(actionId, device)]]
|
|
|
|
def set_bindings(self, actionId, device, texts, save=True):
|
|
"""Replace the bindings of one action on one device. Fixed menu actions cannot change."""
|
|
if self.actions[actionId].fixed:
|
|
raise ValueError(f"{actionId} cannot be rebound")
|
|
self.bindings[(actionId, device)] = parse_bindings(texts, device)
|
|
self._rebuild()
|
|
if save:
|
|
self.save()
|
|
|
|
def reset_action(self, actionId, save=True):
|
|
action = self.actions[actionId]
|
|
for device in ("keyboard", "pad"):
|
|
self.bindings[(actionId, device)] = parse_bindings(action.defaults(device), device)
|
|
self._rebuild()
|
|
if save:
|
|
self.save()
|
|
|
|
def reset_all(self):
|
|
for action in self.game_actions():
|
|
self.reset_action(action.actionId, save=False)
|
|
self.save()
|
|
|
|
def conflicts(self, actionId, binding):
|
|
"""Other actions in the same group with a binding that shares an input with binding."""
|
|
group = self.actions[actionId].group
|
|
wanted = binding.inputs()
|
|
found = []
|
|
for other in self.game_actions():
|
|
if other.actionId == actionId or other.group != group:
|
|
continue
|
|
for existing in self.bindings[(other.actionId, binding.device)]:
|
|
if existing.inputs() & wanted:
|
|
found.append((other.actionId, existing))
|
|
return found
|
|
|
|
def _rebuild(self):
|
|
"""Work out which inputs to watch, and which held inputs change a plain binding into another."""
|
|
self._watchedKeys = set()
|
|
self._chordTriggers = {}
|
|
for (actionId, device), bindings in self.bindings.items():
|
|
for binding in bindings:
|
|
for modifiers, trigger in binding.inputs():
|
|
for item in modifiers + (trigger,):
|
|
if item[0] == "key":
|
|
self._watchedKeys.add(item)
|
|
if modifiers:
|
|
self._chordTriggers.setdefault(trigger, set()).add(modifiers)
|
|
|
|
# Hardware
|
|
|
|
def start(self):
|
|
"""Start listening to controllers. initialize_gui calls this; games need not."""
|
|
if self.devices.start():
|
|
# Controllers plugged in before the game started are not announced; only later changes are.
|
|
self.devices.check()
|
|
|
|
def connected(self):
|
|
"""True when at least one controller is connected."""
|
|
return bool(self.devices.controllers())
|
|
|
|
def controller_names(self):
|
|
return [getattr(pad, "name", "") for pad in self.devices.controllers()]
|
|
|
|
def _check_devices(self):
|
|
if not getattr(self.devices, "started", True) and not self.devices.start():
|
|
return
|
|
added, removed = self.devices.check()
|
|
for _name in removed:
|
|
self.speak(_("Controller disconnected"))
|
|
for _name in added:
|
|
self.speak(_("Controller connected"))
|
|
|
|
def read_pad(self):
|
|
"""Every controller input now, without changing what this frame's held and pressed say.
|
|
|
|
Returns ({input name: 0 to 1}, {axis name: -1 to 1}), with dead zones taken out.
|
|
"""
|
|
padState, axisState, _keyState = self._poll()
|
|
return padState, axisState
|
|
|
|
def _poll(self):
|
|
"""Read every controller input and the watched keys now."""
|
|
pads = self.devices.controllers()
|
|
padState = {}
|
|
axisState = {}
|
|
for name, number in padButtons.items():
|
|
padState[name] = 1.0 if any(self._safe(pad.get_button, number) for pad in pads) else 0.0
|
|
for name, number in padTriggers.items():
|
|
padState[name] = max([deadzone(self._safe(pad.get_axis, number) / 32767, triggerDeadzone)
|
|
for pad in pads] or [0.0])
|
|
for name, number in padAxes.items():
|
|
values = [deadzone(self._safe(pad.get_axis, number) / 32767, stickDeadzone) for pad in pads]
|
|
axisState[name] = max(values, key=abs) if values else 0.0
|
|
for name, (axisName, sign) in stickDirections.items():
|
|
padState[name] = max(0.0, axisState[axisName] * sign)
|
|
keys = self.devices.key_state()
|
|
keyState = {}
|
|
for item in self._watchedKeys:
|
|
keyState[item] = 1.0 if any(self._key_down(keys, code) for code in item[1]) else 0.0
|
|
return padState, axisState, keyState
|
|
|
|
@staticmethod
|
|
def _safe(method, number):
|
|
try:
|
|
return method(number) or 0
|
|
except Exception:
|
|
return 0
|
|
|
|
@staticmethod
|
|
def _key_down(keys, code):
|
|
try:
|
|
return bool(keys[code])
|
|
except (IndexError, KeyError, TypeError):
|
|
return False
|
|
|
|
def _magnitude(self, item):
|
|
if item[0] == "key":
|
|
return self._keyState.get(item, 0.0)
|
|
return self._padState.get(item[1], 0.0)
|
|
|
|
# Game frames
|
|
|
|
def update(self, events=()):
|
|
"""Read input for one frame. Call it once a frame with the events the game took from pygame.
|
|
|
|
pressed() is then true for inputs that went down since the last update, held() for inputs
|
|
that are down now, and value() gives how far each action is pushed.
|
|
"""
|
|
self._check_devices()
|
|
if self._repeatRunning:
|
|
self.devices.set_repeat_timer(False)
|
|
self._repeatRunning = False
|
|
previousHeld = self._held
|
|
downEvents = set()
|
|
for event in events:
|
|
eventType = getattr(event, "type", None)
|
|
if eventType == pygame.KEYDOWN and not getattr(event, "controller", False):
|
|
for item in self._watchedKeys:
|
|
if event.key in item[1]:
|
|
downEvents.add(item)
|
|
elif eventType == pygame.CONTROLLERBUTTONDOWN:
|
|
name = padButtonNames.get(getattr(event, "button", None))
|
|
if name:
|
|
downEvents.add(("pad", name))
|
|
self._padState, axisState, self._keyState = self._poll()
|
|
self._previousAxes = self._axisState
|
|
self._axisState = axisState
|
|
held = set()
|
|
for item, value in [(("pad", name), value) for name, value in self._padState.items()] + \
|
|
list(self._keyState.items()):
|
|
threshold = releaseThreshold if item in previousHeld else pressThreshold
|
|
if value >= threshold and value > 0:
|
|
held.add(item)
|
|
# A tap between two frames still counts, as held for this frame.
|
|
for item in downEvents:
|
|
held.add(item)
|
|
if item[0] == "key":
|
|
self._keyState[item] = 1.0
|
|
else:
|
|
self._padState[item[1]] = max(self._padState.get(item[1], 0.0), 1.0)
|
|
# A key down while it was already held is the key repeating, not a new press.
|
|
self._pressed = {item for item in held if item not in previousHeld}
|
|
self._held = held
|
|
self._menuHeld = {name: True for name in menuPadKeys if ("pad", name) in held}
|
|
|
|
def _modifiers_held(self, binding):
|
|
return all(item in self._held for item in binding.modifiers)
|
|
|
|
def _suppressed(self, binding, trigger):
|
|
"""A plain binding gives way to a binding of the same input with modifiers that are held."""
|
|
if binding.modifiers:
|
|
return False
|
|
return any(all(item in self._held for item in modifiers) for modifiers in self._chordTriggers.get(trigger, ()))
|
|
|
|
def _binding_state(self, binding):
|
|
"""(held, pressed, value) for one binding this frame."""
|
|
if not self._modifiers_held(binding):
|
|
return False, False, 0.0
|
|
if binding.kind == "axis":
|
|
sign = -1 if binding.inverted else 1
|
|
value = self._axisState.get(binding.trigger[1], 0.0) * sign
|
|
previous = abs(self._previousAxes.get(binding.trigger[1], 0.0))
|
|
return abs(value) >= pressThreshold, abs(value) >= pressThreshold > previous, value
|
|
if binding.kind == "pair":
|
|
states = {}
|
|
for item in (binding.negative, binding.positive):
|
|
live = not self._suppressed(binding, item)
|
|
states[item] = (live and item in self._held, live and item in self._pressed,
|
|
self._magnitude(item) if live else 0.0)
|
|
negative, positive = states[binding.negative], states[binding.positive]
|
|
return (negative[0] or positive[0], negative[1] or positive[1], positive[2] - negative[2])
|
|
if self._suppressed(binding, binding.trigger):
|
|
return False, False, 0.0
|
|
return (binding.trigger in self._held, binding.trigger in self._pressed, self._magnitude(binding.trigger))
|
|
|
|
def _states(self, actionId):
|
|
if actionId not in self.actions:
|
|
raise KeyError(f"no action called {actionId!r}")
|
|
return [self._binding_state(binding) for device in ("keyboard", "pad")
|
|
for binding in self.bindings[(actionId, device)]]
|
|
|
|
def held(self, actionId):
|
|
"""True while any input of the action is down."""
|
|
return any(state[0] for state in self._states(actionId))
|
|
|
|
def pressed(self, actionId):
|
|
"""True only in the frame an input of the action went down."""
|
|
return any(state[1] for state in self._states(actionId))
|
|
|
|
def value(self, actionId):
|
|
"""How far the action is pushed, -1.0 to 1.0, with the dead zone taken out. Buttons give 0 or 1."""
|
|
values = [state[2] for state in self._states(actionId)]
|
|
return max(values, key=abs) if values else 0.0
|
|
|
|
# Rumble
|
|
|
|
def rumble(self, low, high, durationMs):
|
|
"""Shake every connected controller: low and high are motor strengths from 0 to 1.
|
|
|
|
Does nothing without a controller, or when the player turned rumble off. The player's
|
|
strength setting scales both motors.
|
|
"""
|
|
if not self.rumbleEnabled or self.rumbleStrength <= 0:
|
|
return False
|
|
scale = self.rumbleStrength / 100
|
|
played = False
|
|
for pad in self.devices.controllers():
|
|
try:
|
|
played = bool(pad.rumble(min(1.0, low * scale), min(1.0, high * scale), int(durationMs))) or played
|
|
except Exception as error:
|
|
_report(f"Rumble failed: {error}")
|
|
return played
|
|
|
|
def rumble_pattern(self, name):
|
|
"""Play a named rumble from rumblePatterns: "tap", "thud", "buzz" or "crash", or one a game adds."""
|
|
return self.rumble(*rumblePatterns[name])
|
|
|
|
# Names
|
|
|
|
def button_scheme(self):
|
|
"""The button names in use: the player's choice, or the connected controller's kind."""
|
|
if self.buttonNames != "auto":
|
|
return self.buttonNames
|
|
names = self.controller_names()
|
|
return controller_scheme(names[0]) if names else "playstation"
|
|
|
|
def input_name(self, item):
|
|
"""The spoken name of one input."""
|
|
kind, value = item
|
|
if kind == "key":
|
|
for modifier, codes in keyModifiers.items():
|
|
if value == codes:
|
|
return _(keySpokenNames[modifier])
|
|
name = key_save_name(value[0])
|
|
return _(keySpokenNames[name]) if name in keySpokenNames else name
|
|
scheme = self.button_scheme()
|
|
if scheme == "playstation" and value == "select" and \
|
|
any(word in name.lower() for name in self.controller_names() for word in ("dualsense", "ps5")):
|
|
return _("create")
|
|
spoken = schemePadNames.get(scheme, {}).get(value) or sharedPadNames.get(value) or value
|
|
return _(spoken)
|
|
|
|
def binding_name(self, binding):
|
|
"""The spoken name of a binding, such as "L1 plus square" or "left stick left and right, reversed"."""
|
|
if binding.kind == "pair":
|
|
# Translators: the two inputs of a pair, such as "left arrow and right arrow".
|
|
name = _("{negative} and {positive}").format(negative=self.input_name(binding.negative),
|
|
positive=self.input_name(binding.positive))
|
|
elif binding.kind == "axis":
|
|
name = self.input_name(binding.trigger)
|
|
if binding.inverted:
|
|
name = _("{input}, reversed").format(input=name)
|
|
else:
|
|
name = self.input_name(binding.trigger)
|
|
for modifier in reversed(binding.modifiers):
|
|
# Translators: hold one input and press another, such as "L1 plus square".
|
|
name = _("{held} plus {pressed}").format(held=self.input_name(modifier), pressed=name)
|
|
return name
|
|
|
|
def describe(self, actionId):
|
|
"""The action's bindings as spoken: keyboard first, then controller, or "not set"."""
|
|
names = [self.binding_name(binding) for device in ("keyboard", "pad")
|
|
for binding in self.bindings[(actionId, device)]]
|
|
return ", ".join(names) if names else _("not set")
|
|
|
|
def group_label(self, group):
|
|
label = None
|
|
if callable(self.groupLabels):
|
|
label = self.groupLabels(group)
|
|
elif self.groupLabels:
|
|
label = self.groupLabels.get(group)
|
|
return label if label else group.replace("_", " ")
|
|
|
|
# Library menus
|
|
|
|
def translate_event(self, event):
|
|
"""The event a library menu should act on: controller menu input becomes the matching key.
|
|
|
|
The d-pad and left stick become the arrow keys, repeating while held; cross (south) becomes
|
|
Enter, circle (east) Escape, triangle (north) Space, L1 and R1 Page Up and Page Down, and
|
|
L2 and R2 Home and End. The key event made has button set to the input's position name and
|
|
controller set to True. Stick movement and repeat ticks that make no key come back as
|
|
NOEVENT; every other event, other controller buttons among them, comes back unchanged.
|
|
"""
|
|
self._check_devices()
|
|
eventType = getattr(event, "type", None)
|
|
repeatEvent = getattr(self.devices, "repeatEvent", None)
|
|
controllerEvents = (pygame.CONTROLLERBUTTONDOWN, pygame.CONTROLLERBUTTONUP, pygame.CONTROLLERAXISMOTION)
|
|
if eventType not in controllerEvents and (repeatEvent is None or eventType != repeatEvent):
|
|
return event
|
|
pressedButton = None
|
|
if eventType == pygame.CONTROLLERBUTTONDOWN:
|
|
pressedButton = padButtonNames.get(getattr(event, "button", None))
|
|
self._padState, self._axisState, self._keyState = self._poll()
|
|
now = self.devices.ticks()
|
|
produced = None
|
|
stillHeld = {}
|
|
for name, (key, repeats) in menuPadKeys.items():
|
|
value = self._padState.get(name, 0.0)
|
|
wasHeld = name in self._menuHeld
|
|
isHeld = value >= (releaseThreshold if wasHeld else pressThreshold) and value > 0
|
|
if name == pressedButton:
|
|
if produced is None:
|
|
produced = (key, name)
|
|
stillHeld[name] = now + repeatDelayMs
|
|
continue
|
|
if isHeld and not wasHeld:
|
|
if produced is None:
|
|
produced = (key, name)
|
|
stillHeld[name] = now + repeatDelayMs
|
|
elif isHeld:
|
|
nextRepeat = self._menuHeld[name]
|
|
if repeats and nextRepeat is not True and now >= nextRepeat:
|
|
if produced is None:
|
|
produced = (key, name)
|
|
nextRepeat = now + repeatIntervalMs
|
|
stillHeld[name] = nextRepeat
|
|
self._menuHeld = stillHeld
|
|
# The game's next frame must not take an input held over from the menu for a new press.
|
|
self._held = {("pad", name) for name, value in self._padState.items() if value >= pressThreshold}
|
|
self._held |= {item for item, value in self._keyState.items() if value}
|
|
self._pressed = set()
|
|
needRepeat = any(menuPadKeys[name][1] for name in stillHeld)
|
|
if needRepeat or self._repeatRunning:
|
|
self.devices.set_repeat_timer(needRepeat)
|
|
self._repeatRunning = needRepeat
|
|
if produced is None:
|
|
if eventType in (pygame.CONTROLLERBUTTONDOWN, pygame.CONTROLLERBUTTONUP):
|
|
return event
|
|
return pygame.event.Event(pygame.NOEVENT)
|
|
key, name = produced
|
|
return pygame.event.Event(pygame.KEYDOWN, key=key, mod=0, unicode="", scancode=0,
|
|
button=name, controller=True)
|
|
|
|
def ignore_held_inputs(self):
|
|
"""Treat every controller input down now as already handled, by menus and by the next frame.
|
|
|
|
For after listening for a binding, so a stick still pushed does not also move the menu.
|
|
"""
|
|
self._padState, self._axisState, self._keyState = self._poll()
|
|
self._menuHeld = {name: True for name in menuPadKeys if self._padState.get(name, 0.0) >= releaseThreshold}
|
|
self._held = {("pad", name) for name, value in self._padState.items() if value >= releaseThreshold}
|
|
self._held |= {item for item, value in self._keyState.items() if value}
|
|
self._pressed = set()
|
|
|
|
def translate_events(self, events):
|
|
"""translate_event for each of a list of events, leaving out what made nothing."""
|
|
translated = (self.translate_event(event) for event in events)
|
|
return [event for event in translated if event.type != pygame.NOEVENT]
|
|
|
|
|
|
def deadzone(value, zone):
|
|
"""value with the dead zone taken out and the rest stretched back to the full range."""
|
|
value = max(-1.0, min(1.0, value))
|
|
if abs(value) < zone:
|
|
return 0.0
|
|
return (abs(value) - zone) / (1 - zone) * (1 if value > 0 else -1)
|
|
|
|
|
|
_controllerEventTypes = {
|
|
pygame.CONTROLLERBUTTONDOWN, pygame.CONTROLLERBUTTONUP, pygame.CONTROLLERAXISMOTION,
|
|
pygame.CONTROLLERDEVICEADDED, pygame.CONTROLLERDEVICEREMOVED, pygame.JOYDEVICEADDED, pygame.JOYDEVICEREMOVED,
|
|
}
|
|
|
|
|
|
def translate_event(event):
|
|
"""Controls.translate_event on the game's controls.
|
|
|
|
Before anything has made the game's controls, which initialize_gui does, a keyboard event
|
|
comes back as it is, without starting the controls.
|
|
"""
|
|
if Controls._instance is None and getattr(event, "type", None) not in _controllerEventTypes:
|
|
return event
|
|
return Controls.get_instance().translate_event(event)
|
|
|
|
|
|
def translate_events(events):
|
|
"""translate_event for each of a list of events, leaving out what made nothing."""
|
|
translated = (translate_event(event) for event in events)
|
|
return [event for event in translated if event.type != pygame.NOEVENT]
|
|
|
|
|
|
def pad_button(event):
|
|
"""The position name of the controller button an event is about, or None."""
|
|
if getattr(event, "button", None) in padButtons:
|
|
return event.button
|
|
if getattr(event, "type", None) in (pygame.CONTROLLERBUTTONDOWN, pygame.CONTROLLERBUTTONUP):
|
|
return padButtonNames.get(event.button)
|
|
return None
|