Games name their actions with default keys and controller inputs and ask Controls whether they are held, pressed or how far they are pushed. Library menus, text display, message boxes, cut scenes, power bars and pause work with a controller. controls_menu lets players rebind and set rumble; only changes from the defaults are saved in config.ini. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
246 lines
11 KiB
Python
246 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""Speech Dispatcher preferences a player can change and keep.
|
|
|
|
SpeechPreferences restores the saved module, voice, rate, pitch and volume
|
|
when it is made, changes them a step at a time and saves each change in the
|
|
game's own local config, in a "speech" section. speech_options_menu() is a
|
|
ready-made menu for them, where Left and Right change the setting the player
|
|
is on and the change is heard straight away.
|
|
|
|
Both do nothing useful without Speech Dispatcher: check enabled, or
|
|
supports_speech_settings(), before offering them.
|
|
"""
|
|
|
|
import time
|
|
|
|
import pygame
|
|
|
|
from .controls import translate_event
|
|
from .i18n import _, N_, reset_language
|
|
from .menu import is_language_reset
|
|
from .services import ConfigService
|
|
from .speech import Speech
|
|
|
|
speechSettingKeys = ("module", "voice", "rate", "pitch", "volume")
|
|
numericSettingKeys = ("rate", "pitch", "volume")
|
|
# Speech Dispatcher's own defaults: 0 for rate and pitch, 100 for volume.
|
|
numericDefaults = {"rate": 0, "pitch": 0, "volume": 100}
|
|
# What is saved: the settings above, and a language if a game sets one through apply_speech_settings.
|
|
savedSettingKeys = ("module", "voice", "language", "rate", "pitch", "volume")
|
|
|
|
speechSettingTitles = {
|
|
"module": N_("Speech module"),
|
|
"voice": N_("Speech voice"),
|
|
"rate": N_("Speech rate"),
|
|
"pitch": N_("Speech pitch"),
|
|
"volume": N_("Speech volume"),
|
|
}
|
|
|
|
|
|
def _report(message):
|
|
"""Print a problem for whoever runs the game from a terminal."""
|
|
print(f"{message} [{time.ctime()}]")
|
|
|
|
|
|
class SpeechPreferences:
|
|
"""The player's speech settings: restored when made, saved on every change.
|
|
|
|
Args:
|
|
speech: The Speech to change; defaults to the game's speech.
|
|
config: Where to save, anything with localConfig (a ConfigParser) and
|
|
write_local_config(), such as ConfigService or Config. Defaults to
|
|
ConfigService.get_instance(), the game's own config.ini.
|
|
section (str): The config section the settings are saved in.
|
|
smallStep (int): How far one press changes rate, pitch or volume.
|
|
largeStep (int): How far a large step changes them.
|
|
largeChoiceStep (int): How many modules or voices a large step skips.
|
|
"""
|
|
|
|
def __init__(self, speech=None, config=None, section="speech", smallStep=5, largeStep=25, largeChoiceStep=10):
|
|
self.speech = speech if speech is not None else Speech.get_instance()
|
|
self.config = config if config is not None else ConfigService.get_instance()
|
|
self.section = section
|
|
self.smallStep = smallStep
|
|
self.largeStep = largeStep
|
|
self.largeChoiceStep = largeChoiceStep
|
|
self.enabled = self.speech.supports_speech_settings()
|
|
self.values = {}
|
|
if not self.enabled:
|
|
return
|
|
errors = self.speech.apply_speech_settings(self.saved_settings(), preview=False)
|
|
for key, error in errors.items():
|
|
_report(f"Could not restore speech {key}: {error}")
|
|
# Speech Dispatcher cannot say which voice is in use, so the voice is
|
|
# "System default" until the player picks one. The rest it can say.
|
|
for key in ("module", *numericSettingKeys):
|
|
try:
|
|
value = getattr(self.speech.spd, "get_output_module" if key == "module" else f"get_{key}")()
|
|
if key != "module":
|
|
value = int(value)
|
|
if not -100 <= value <= 100:
|
|
raise ValueError("out of range")
|
|
self.values[key] = value
|
|
except Exception as error:
|
|
_report(f"Could not read speech {key}: {error}")
|
|
if key in numericDefaults:
|
|
self.values[key] = numericDefaults[key]
|
|
for key, value in self.speech.get_speech_settings().items():
|
|
self.values[key] = int(value) if key in numericSettingKeys else value
|
|
|
|
def saved_settings(self):
|
|
"""The settings saved in the config, as strings, which apply_speech_settings accepts."""
|
|
parser = self.config.localConfig
|
|
if not parser.has_section(self.section):
|
|
return {}
|
|
return {key: value for key in savedSettingKeys if (value := parser.get(self.section, key, fallback=""))}
|
|
|
|
def save(self):
|
|
"""Save the settings now in use, replacing the section so a module change also forgets the old voice."""
|
|
try:
|
|
parser = self.config.localConfig
|
|
parser.remove_section(self.section)
|
|
parser.add_section(self.section)
|
|
for key, value in self.speech.get_speech_settings().items():
|
|
parser.set(self.section, key, str(value).replace("%", "%%"))
|
|
self.config.write_local_config()
|
|
except Exception as error:
|
|
_report(f"Could not save speech settings: {error}")
|
|
|
|
def label(self, key):
|
|
"""What to say for a setting, such as "Speech rate, 25" or "Speech voice, System default"."""
|
|
value = self.values.get(key)
|
|
# Translators: a speech option and its value, such as "Speech rate, 25" or "Speech voice, System default".
|
|
return _("{setting}, {value}").format(setting=_(speechSettingTitles[key]),
|
|
value=value if value is not None else _("System default"))
|
|
|
|
def items(self):
|
|
"""(label, key) for each setting, or nothing without Speech Dispatcher."""
|
|
return [(self.label(key), key) for key in speechSettingKeys] if self.enabled else []
|
|
|
|
def set(self, key, value):
|
|
"""Change one setting and save it. Returns what to say if it failed, else None."""
|
|
try:
|
|
errors = self.speech.apply_speech_settings({key: value}, preview=False)
|
|
except Exception as error:
|
|
errors = {key: str(error) or type(error).__name__}
|
|
if errors:
|
|
_report(f"Could not change speech {key}: {errors}")
|
|
return _("Could not change speech setting: {error}").format(error="; ".join(errors.values()))
|
|
self.values[key] = value
|
|
if key == "module":
|
|
self.values.pop("voice", None)
|
|
self.save()
|
|
return None
|
|
|
|
def adjust(self, key, direction, large=False):
|
|
"""Move a setting up (direction 1) or down (direction -1) one step, and save it.
|
|
|
|
Rate, pitch and volume change by smallStep, or largeStep if large, and
|
|
stop at -100 and 100. Modules and voices go to the next or previous
|
|
one, or largeChoiceStep along if large, wrapping round at the ends.
|
|
Returns what to say if it failed, else None.
|
|
"""
|
|
if key in numericSettingKeys:
|
|
step = (self.largeStep if large else self.smallStep) * direction
|
|
value = max(-100, min(100, self.values.get(key, numericDefaults[key]) + step))
|
|
return self.set(key, value) if value != self.values.get(key) else None
|
|
try:
|
|
if key == "module":
|
|
choices = list(self.speech.list_speech_modules())
|
|
else:
|
|
choices = [voice["name"] for voice in self.speech.list_speech_voices()]
|
|
except Exception as error:
|
|
_report(f"Could not list speech {key} choices: {error}")
|
|
choices = []
|
|
if not choices:
|
|
return _("No speech choices available.")
|
|
current = self.values.get(key)
|
|
if current in choices:
|
|
index = (choices.index(current) + direction * (self.largeChoiceStep if large else 1)) % len(choices)
|
|
else:
|
|
# Nothing chosen yet: the first going up, the last going down.
|
|
index = 0 if direction > 0 else len(choices) - 1
|
|
return self.set(key, choices[index])
|
|
|
|
def reset(self, key):
|
|
"""Put rate, pitch or volume back to Speech Dispatcher's default. Returns an error to say, or None."""
|
|
if key not in numericDefaults or self.values.get(key) == numericDefaults[key]:
|
|
return None
|
|
return self.set(key, numericDefaults[key])
|
|
|
|
|
|
def speech_options_menu(sounds, preferences=None, title=None):
|
|
"""A menu of the speech settings, for a game's options menu.
|
|
|
|
Up and Down move between the settings, and Home and End to the first and
|
|
last. Left and Right, or Enter, change the setting the player is on: rate,
|
|
pitch and volume by a small step, modules and voices to the next one.
|
|
Page Up and Page Down change it by a large step. Delete puts rate, pitch
|
|
or volume back to its default. Each change is said with the new settings,
|
|
so the player hears it. Escape, or Enter on Back, returns.
|
|
|
|
Args:
|
|
sounds (dict): The game's sounds, for menu-move and menu-select.
|
|
preferences (SpeechPreferences): The settings to change; made, and
|
|
the saved ones restored, if not given.
|
|
title (str): Said when the menu opens; "Speech options" if not given.
|
|
"""
|
|
preferences = preferences if preferences is not None else SpeechPreferences()
|
|
speech = preferences.speech
|
|
|
|
def say(text):
|
|
# Said even if it was just said, since hearing the new settings is the point.
|
|
speech.lastSpoken["text"] = None
|
|
speech.speak(text)
|
|
|
|
def play(name):
|
|
try:
|
|
sounds[name].play()
|
|
except Exception:
|
|
pass
|
|
|
|
if not preferences.enabled:
|
|
say(_("Speech settings need Speech Dispatcher."))
|
|
return
|
|
backLabel = _("Back")
|
|
keys = list(speechSettingKeys) + [None]
|
|
index = 0
|
|
|
|
def current_label():
|
|
return preferences.label(keys[index]) if keys[index] else backLabel
|
|
|
|
say(_("{title}. {item}").format(title=title or _("Speech options"), item=current_label()))
|
|
pygame.event.clear()
|
|
while True:
|
|
event = translate_event(pygame.event.wait())
|
|
if event.type == pygame.QUIT:
|
|
return
|
|
if event.type != pygame.KEYDOWN:
|
|
continue
|
|
key = keys[index]
|
|
if is_language_reset(event):
|
|
say(reset_language())
|
|
elif event.key == pygame.K_ESCAPE:
|
|
return
|
|
elif event.key in (pygame.K_UP, pygame.K_DOWN, pygame.K_HOME, pygame.K_END):
|
|
target = {pygame.K_UP: max(0, index - 1), pygame.K_DOWN: min(len(keys) - 1, index + 1),
|
|
pygame.K_HOME: 0, pygame.K_END: len(keys) - 1}[event.key]
|
|
if target != index:
|
|
index = target
|
|
play("menu-move")
|
|
say(current_label())
|
|
elif event.key == pygame.K_RETURN and key is None:
|
|
play("menu-select")
|
|
return
|
|
elif key is not None and event.key in (pygame.K_LEFT, pygame.K_RIGHT, pygame.K_RETURN,
|
|
pygame.K_PAGEUP, pygame.K_PAGEDOWN, pygame.K_DELETE):
|
|
if event.key == pygame.K_DELETE:
|
|
error = preferences.reset(key)
|
|
else:
|
|
direction = -1 if event.key in (pygame.K_LEFT, pygame.K_PAGEDOWN) else 1
|
|
error = preferences.adjust(key, direction, large=event.key in (pygame.K_PAGEUP, pygame.K_PAGEDOWN))
|
|
play("menu-move")
|
|
# Saying the setting after changing it is the preview, in the new voice.
|
|
say(error or current_label())
|