diff --git a/AI-README.md b/AI-README.md index 83951fb..a4337a3 100644 --- a/AI-README.md +++ b/AI-README.md @@ -138,6 +138,11 @@ loop that already reads `pygame.event.get()`, check for Escape there instead. fades out and pauses while it is open and comes back after. - `sg.display_text(lines)`: a list of lines the player can move through. - `sg.get_input(prompt, text="")`: ask the player to type something. +- **Speech options:** make `speechPreferences = sg.SpeechPreferences()` at + startup, before the first spoken menu, to restore the player's saved Speech + Dispatcher module, voice, rate, pitch and volume. When `speechPreferences.enabled`, + offer `sg.speech_options_menu(sounds, speechPreferences)` in the game's options + menu; Left and Right change each setting, and changes are saved for you. ## Sounds diff --git a/README.md b/README.md index ffc55f1..9d8fc1c 100644 --- a/README.md +++ b/README.md @@ -309,9 +309,46 @@ exit_game() or as the class, game.exit_game() ``` +#### Speech options menu + +Most games need only this. `SpeechPreferences()` restores the player's saved +module, voice, rate, pitch and volume, and `speech_options_menu()` lets them +change those settings, saving each change in the game's own config.ini under a +`speech` section: + +```python +# At startup, after initialize_gui and before the first spoken menu. +speechPreferences = sg.SpeechPreferences() + +# In the game's options menu, offered only with Speech Dispatcher. +if speechPreferences.enabled: + options.append("speech_options") +... +if choice == "speech_options": + sg.speech_options_menu(sounds, speechPreferences) +``` + +In the menu, Up and Down move between Speech module, Speech voice, Speech +rate, Speech pitch, Speech volume and Back, and Home and End go to the first +and last. Left and Right, or Enter, change the setting the player is on: +modules and voices go to the next or previous one, wrapping at the ends, and +rate, pitch and volume change by 5 and stop at -100 and 100. Page Up and Page +Down change them by 25, or skip 10 modules or voices. Delete puts rate, pitch +or volume back to its default. Every change is said in the new settings, so +the player hears it. Escape, or Enter on Back, returns. + +A game with its own menus can use `SpeechPreferences` without the menu: +`items()` gives `(label, key)` pairs such as `("Speech rate, 25", "rate")`, +`adjust(key, direction, large=False)` changes and saves one setting, +`reset(key)` puts a number back to its default, and each returns what to say +if the change failed, or None. Say `label(key)` after a change, with +`speech.lastSpoken["text"] = None` first so it is not skipped as a repeat. +`SpeechPreferences(config=..., section=..., smallStep=..., largeStep=...)` +saves to another `Config` or section, or changes the step sizes. + #### Speech Dispatcher preferences -Games can offer module, synthesis voice, language, rate, pitch and volume +Below the menu, games can offer module, synthesis voice, language, rate, pitch and volume controls through the existing speech singleton or the package functions below. `supports_speech_settings()` lets an options menu offer these controls only when Speech Dispatcher is active. Other providers continue using @@ -336,8 +373,9 @@ errors = sg.apply_speech_settings(saveData.get("speech", {}), preview=False) `get_speech_settings()` returns a copy of successful explicit overrides, not server defaults. An empty dictionary leaves the connection's system defaults -alone. Games own saving: the library never creates a separate preferences file. -For an INI save such as Grave Racer's `Settings`, store each returned key under +alone. `apply_speech_settings()` itself saves nothing: `SpeechPreferences` +saves to the game's existing config.ini, and a game that keeps its settings +elsewhere can save this dictionary itself. For an INI save such as Grave Racer's `Settings`, store each returned key under a `speech` section using `str(value)` and pass that section's dictionary back to `apply_speech_settings()` on startup. Numeric strings from INI are accepted. Skip applying saved preferences on unsupported providers and retain those saved diff --git a/__init__.py b/__init__.py index 7262274..6a7aef8 100755 --- a/__init__.py +++ b/__init__.py @@ -60,6 +60,9 @@ from .display import display_text, initialize_gui # Import menu functions from .menu import game_menu, instruction_menu, learn_sounds, instructions, credits, donate, exit_game +# Import speech preferences and their menu +from .speech_options import SpeechPreferences, speech_options_menu + # Update imports to reference Scoreboard methods high_scores = Scoreboard.display_high_scores has_high_scores = Scoreboard.has_high_scores @@ -120,6 +123,8 @@ __all__ = [ 'list_speech_voices', 'get_speech_settings', 'apply_speech_settings', + 'SpeechPreferences', + 'speech_options_menu', # Translations 'set_language', 'set_language_reset', 'language_code', 'translated_file', diff --git a/locales/libstormgames.pot b/locales/libstormgames.pot index eaa9ff5..3b80657 100644 --- a/locales/libstormgames.pot +++ b/locales/libstormgames.pot @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: libstormgames\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-24 00:01-0500\n" +"POT-Creation-Date: 2026-11-29 01:27-0500\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -18,27 +18,27 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" -#: display.py:170 utils.py:260 +#: display.py:175 utils.py:260 msgid "" "Press space to read the whole text. Use up and down arrows to navigate the " "text line by line. Press c to copy the current line to the clipboard or t to " "copy the entire text. Press enter or escape when you are done reading." msgstr "" -#: display.py:177 utils.py:267 +#: display.py:182 utils.py:267 msgid "End of text." msgstr "" -#: display.py:225 utils.py:313 +#: display.py:232 utils.py:313 #, python-brace-format msgid "Copied {text} to the clipboard." msgstr "" -#: display.py:227 display.py:235 utils.py:315 utils.py:324 +#: display.py:234 display.py:242 utils.py:315 utils.py:324 msgid "Failed to copy the text to the clipboard." msgstr "" -#: display.py:233 utils.py:322 +#: display.py:240 utils.py:322 msgid "Copied entire message to the clipboard." msgstr "" @@ -283,17 +283,17 @@ msgstr "" msgid "exit game" msgstr "" -#: menu.py:448 +#: menu.py:481 msgid "No sounds available to learn." msgstr "" -#: menu.py:463 +#: menu.py:496 msgid "" "Starting with root directory sounds. Use left and right arrows or page up " "and page down to navigate categories." msgstr "" -#: menu.py:466 +#: menu.py:499 #, python-brace-format msgid "" "Starting with {category} sounds. Use left and right arrows or page up and " @@ -301,39 +301,39 @@ msgid "" msgstr "" #. Translators: a sound's name and what it is, as in "bell: the lap bell". -#: menu.py:493 +#: menu.py:526 #, python-brace-format msgid "{sound}: {description}" msgstr "" -#: menu.py:499 +#: menu.py:532 #, python-brace-format msgid "Root directory: {sound}, {number} of {total}" msgstr "" -#: menu.py:502 +#: menu.py:535 #, python-brace-format msgid "{category}: {sound}, {number} of {total}" msgstr "" -#: menu.py:506 +#: menu.py:539 #, python-brace-format msgid "{sound}, {number} of {total}" msgstr "" -#: menu.py:553 +#: menu.py:588 msgid "Could not play sound." msgstr "" -#: menu.py:571 +#: menu.py:608 msgid "Instructions file is missing." msgstr "" -#: menu.py:589 +#: menu.py:627 msgid "Credits file is missing." msgstr "" -#: menu.py:599 +#: menu.py:637 msgid "The donation page has been opened in your browser." msgstr "" @@ -369,32 +369,92 @@ msgstr "" msgid "Could not display high scores." msgstr "" -#: speech.py:304 speech.py:311 +#: speech.py:180 +msgid "Speech settings preview." +msgstr "" + +#: speech.py:436 speech.py:443 msgid "Press any key to repeat or enter to continue." msgstr "" -#: speech.py:470 +#: speech.py:602 #, python-brace-format msgid "First: {message}" msgstr "" -#: speech.py:473 +#: speech.py:605 msgid "No previous messages" msgstr "" -#: speech.py:475 speech.py:489 speech.py:506 +#: speech.py:607 speech.py:621 speech.py:638 msgid "Speech history not available" msgstr "" -#: speech.py:487 +#: speech.py:619 msgid "No messages in history" msgstr "" -#: speech.py:501 +#: speech.py:633 #, python-brace-format msgid "Last: {message}" msgstr "" -#: speech.py:504 +#: speech.py:636 msgid "No next messages" msgstr "" + +#: speech_options.py:32 +msgid "Speech module" +msgstr "" + +#: speech_options.py:33 +msgid "Speech voice" +msgstr "" + +#: speech_options.py:34 +msgid "Speech rate" +msgstr "" + +#: speech_options.py:35 +msgid "Speech pitch" +msgstr "" + +#: speech_options.py:36 +msgid "Speech volume" +msgstr "" + +#. Translators: a speech option and its value, such as "Speech rate, 25" or "Speech voice, System default". +#: speech_options.py:113 +#, python-brace-format +msgid "{setting}, {value}" +msgstr "" + +#: speech_options.py:114 +msgid "System default" +msgstr "" + +#: speech_options.py:128 +#, python-brace-format +msgid "Could not change speech setting: {error}" +msgstr "" + +#: speech_options.py:156 +msgid "No speech choices available." +msgstr "" + +#: speech_options.py:203 +msgid "Speech settings need Speech Dispatcher." +msgstr "" + +#: speech_options.py:205 +msgid "Back" +msgstr "" + +#: speech_options.py:212 +msgid "Speech options" +msgstr "" + +#: speech_options.py:212 +#, python-brace-format +msgid "{title}. {item}" +msgstr "" diff --git a/speech_options.py b/speech_options.py new file mode 100644 index 0000000..1ed0d34 --- /dev/null +++ b/speech_options.py @@ -0,0 +1,244 @@ +#!/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 .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 = 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()) diff --git a/tests/test_speech_options.py b/tests/test_speech_options.py new file mode 100644 index 0000000..ff2dcf0 --- /dev/null +++ b/tests/test_speech_options.py @@ -0,0 +1,183 @@ +"""Speech preferences and their menu, with a fake Speech Dispatcher connection and config. + +Run from the library root: python -m unittest discover -s tests -v +""" + +import configparser +import importlib.util +from pathlib import Path +import sys +from types import ModuleType, SimpleNamespace +import unittest +from unittest.mock import Mock, patch + +import pygame + + +def load_speech_options(): + """Load the real speech options code with its framework dependencies replaced.""" + packageName = "_speech_options_test_library" + package = ModuleType(packageName) + package.__path__ = [str(Path(__file__).resolve().parents[1])] + modules = {packageName: package} + for moduleName, names in {"speech": ["Speech"], "services": ["ConfigService"], "menu": []}.items(): + dependency = ModuleType(f"{packageName}.{moduleName}") + for name in names: + setattr(dependency, name, Mock()) + modules[dependency.__name__] = dependency + modules[f"{packageName}.menu"].is_language_reset = ( + lambda event: event.key == pygame.K_F12 and getattr(event, "shift", False)) + spec = importlib.util.spec_from_file_location(f"{packageName}.speech_options", + Path(package.__path__[0]) / "speech_options.py") + module = importlib.util.module_from_spec(spec) + with patch.dict(sys.modules, modules): + spec.loader.exec_module(module) + return module + + +class FakeSpeech: + """Just enough of Speech, with Speech Dispatcher behind it.""" + + def __init__(self, modules=("espeak-ng", "rhvoice"), voices=("Alan", "Bella", "Clara")): + self.settings = {} + self.lastSpoken = {"text": None} + self.spoken = [] + self.failures = {} + self.modules = list(modules) + self.voices = list(voices) + self.spd = SimpleNamespace(get_output_module=lambda: "espeak-ng", get_rate=lambda: 10, + get_pitch=lambda: 0, get_volume=lambda: 100) + + def supports_speech_settings(self): + return True + + def list_speech_modules(self): + return self.modules + + def list_speech_voices(self): + return [{"name": name, "language": "en", "variant": "none"} for name in self.voices] + + def apply_speech_settings(self, settings, preview=True, previewText=None): + errors = {} + for key, value in settings.items(): + if key in self.failures: + errors[key] = self.failures[key] + continue + if key == "module": + self.settings.pop("voice", None) + self.settings[key] = value + return errors + + def get_speech_settings(self): + return dict(self.settings) + + def speak(self, text): + self.spoken.append(text) + + +class SpeechOptionsTestCase(unittest.TestCase): + def setUp(self): + self.module = load_speech_options() + self.config = SimpleNamespace(localConfig=configparser.ConfigParser(), write_local_config=Mock()) + self.speech = FakeSpeech() + + def make_preferences(self, **options): + return self.module.SpeechPreferences(self.speech, self.config, **options) + + +class SpeechPreferencesTests(SpeechOptionsTestCase): + def test_restores_saved_settings_and_reads_the_rest(self): + self.config.localConfig["speech"] = {"module": "rhvoice", "rate": "40"} + preferences = self.make_preferences() + self.assertEqual(self.speech.settings, {"module": "rhvoice", "rate": "40"}) + self.assertEqual(preferences.values, {"module": "rhvoice", "rate": 40, "pitch": 0, "volume": 100}) + self.assertEqual(preferences.label("voice"), "Speech voice, System default") + self.assertEqual(preferences.label("rate"), "Speech rate, 40") + + def test_module_change_forgets_the_saved_voice(self): + self.config.localConfig["speech"] = {"module": "espeak-ng", "voice": "Alan"} + preferences = self.make_preferences() + self.assertIsNone(preferences.adjust("module", 1)) + self.assertEqual(dict(self.config.localConfig["speech"]), {"module": "rhvoice"}) + self.assertNotIn("voice", preferences.values) + self.config.write_local_config.assert_called() + + def test_choices_wrap_and_start_from_either_end(self): + preferences = self.make_preferences() + preferences.adjust("voice", -1) + self.assertEqual(preferences.values["voice"], "Clara") + preferences.adjust("voice", 1) + self.assertEqual(preferences.values["voice"], "Alan") + preferences.adjust("voice", 1, large=True) + self.assertEqual(preferences.values["voice"], "Bella") # 10 along three voices, wrapping + + def test_numbers_step_and_stop_at_the_limits(self): + preferences = self.make_preferences() + preferences.adjust("rate", 1) + self.assertEqual(preferences.values["rate"], 15) + for _press in range(5): + preferences.adjust("rate", 1, large=True) + self.assertEqual(preferences.values["rate"], 100) + self.assertEqual(self.config.localConfig["speech"]["rate"], "100") + self.assertIsNone(preferences.reset("rate")) + self.assertEqual(preferences.values["rate"], 0) + + def test_failed_change_is_reported_and_not_saved(self): + preferences = self.make_preferences() + self.speech.failures["pitch"] = "Broken" + self.assertIn("Broken", preferences.adjust("pitch", 1)) + self.assertEqual(preferences.values["pitch"], 0) + self.assertFalse(self.config.localConfig.has_section("speech")) + + def test_no_choices_is_said(self): + self.speech.voices = [] + self.assertEqual(self.make_preferences().adjust("voice", 1), "No speech choices available.") + + def test_nothing_without_speech_dispatcher(self): + self.speech.supports_speech_settings = lambda: False + self.speech.apply_speech_settings = Mock() + preferences = self.make_preferences() + self.assertFalse(preferences.enabled) + self.assertEqual(preferences.items(), []) + self.speech.apply_speech_settings.assert_not_called() + + +class SpeechOptionsMenuTests(SpeechOptionsTestCase): + def run_menu(self, keyCodes, preferences=None): + events = [SimpleNamespace(type=pygame.KEYDOWN, key=key) for key in keyCodes] + self.sounds = {"menu-move": Mock(), "menu-select": Mock()} + with patch("pygame.event.wait", side_effect=events), patch("pygame.event.clear"): + self.module.speech_options_menu(self.sounds, preferences or self.make_preferences()) + return self.speech.spoken + + def test_left_and_right_change_the_setting_and_say_it(self): + spoken = self.run_menu([pygame.K_RIGHT, pygame.K_DOWN, pygame.K_DOWN, pygame.K_DOWN, pygame.K_LEFT, + pygame.K_PAGEUP, pygame.K_DELETE, pygame.K_ESCAPE]) + self.assertEqual(spoken, [ + "Speech options. Speech module, espeak-ng", + "Speech module, rhvoice", + "Speech voice, System default", + "Speech rate, 10", + "Speech pitch, 0", + "Speech pitch, -5", + "Speech pitch, 20", + "Speech pitch, 0", + ]) + + def test_enter_on_back_returns_and_the_ends_stop(self): + spoken = self.run_menu([pygame.K_UP, pygame.K_END, pygame.K_DOWN, pygame.K_RETURN]) + self.assertEqual(spoken, ["Speech options. Speech module, espeak-ng", "Back"]) + self.sounds["menu-select"].play.assert_called_once() + + def test_enter_on_a_setting_moves_it_on(self): + spoken = self.run_menu([pygame.K_RETURN, pygame.K_ESCAPE]) + self.assertEqual(spoken[-1], "Speech module, rhvoice") + + def test_without_speech_dispatcher_it_says_so(self): + self.speech.supports_speech_settings = lambda: False + spoken = self.run_menu([]) + self.assertEqual(spoken, ["Speech settings need Speech Dispatcher."]) + + +if __name__ == "__main__": + unittest.main()