Handle text dialog volume keys with alternate audio engines

This commit is contained in:
Storm Dragon committed 2026-11-26 17:27:26 -05:00
1 parent 8d354dbe1c
commit 31e7472fd1
3 files changed
+102 -5

No files matched your search

+6 -2
View File
@@ -138,7 +138,7 @@ def _show_logo_with_audio(soundData, audioKey):
from .sound import cut_scene
cut_scene(soundData, audioKey)
def display_text(text):
def display_text(text, keyHandler=None):
"""Display and speak text with navigation controls.
Allows users to:
@@ -153,6 +153,8 @@ def display_text(text):
Args:
text (list): List of text lines to display
keyHandler: Optional callable receiving (key, modifiers). Return True
to consume a key, for example to control a game's own audio engine.
"""
# Get service instances
speech = Speech.get_instance()
@@ -186,7 +188,9 @@ def display_text(text):
event = pygame.event.wait()
if event.type == pygame.KEYDOWN:
# Check for Alt modifier
mods = pygame.key.get_mods()
mods = event.mod
if keyHandler is not None and keyHandler(event.key, mods):
continue
altPressed = mods & pygame.KMOD_ALT
# Volume controls (require Alt)
+3 -3
View File
@@ -156,7 +156,7 @@ class VolumeService:
self.masterVolume = max(0.0, min(1.0, self.masterVolume + change))
# Update real-time audio if pygame mixer is provided
if pygameMixer:
if pygameMixer and pygameMixer.get_init():
# Update music volume
if pygameMixer.music.get_busy():
pygameMixer.music.set_volume(self.bgmVolume * self.masterVolume)
@@ -184,7 +184,7 @@ class VolumeService:
self.bgmVolume = max(0.0, min(1.0, self.bgmVolume + change))
# Update real-time audio if pygame mixer is provided
if pygameMixer and pygameMixer.music.get_busy():
if pygameMixer and pygameMixer.get_init() and pygameMixer.music.get_busy():
pygameMixer.music.set_volume(self.bgmVolume * self.masterVolume)
def adjust_sfx_volume(self, change, pygameMixer=None):
@@ -197,7 +197,7 @@ class VolumeService:
self.sfxVolume = max(0.0, min(1.0, self.sfxVolume + change))
# Update real-time audio if pygame mixer is provided
if pygameMixer:
if pygameMixer and pygameMixer.get_init():
# Update all sound channels except reserved ones
for i in range(pygameMixer.get_num_channels()):
channel = pygameMixer.Channel(i)
+93
View File
@@ -0,0 +1,93 @@
"""Text dialog and volume regressions without a window or speech provider."""
import importlib
from pathlib import Path
import sys
from types import ModuleType, SimpleNamespace
import unittest
from unittest.mock import Mock, patch
import pygame
def load_library():
packageName = "_display_test_library"
package = ModuleType(packageName)
package.__path__ = [str(Path(__file__).resolve().parents[1])]
with patch.dict(sys.modules, {packageName: package}):
display = importlib.import_module(f"{packageName}.display")
services = importlib.import_module(f"{packageName}.services")
display.Speech = Mock()
return display, services
class VolumeTests(unittest.TestCase):
def test_uninitialized_mixer_still_updates_each_saved_level(self):
_, services = load_library()
self.assertIsNone(pygame.mixer.get_init())
for method, level in [("adjust_master_volume", "masterVolume"),
("adjust_bgm_volume", "bgmVolume"),
("adjust_sfx_volume", "sfxVolume")]:
for mixer in (None, pygame.mixer):
with self.subTest(method=method, mixer=mixer):
volume = services.VolumeService()
before = getattr(volume, level)
getattr(volume, method)(-0.1, mixer)
self.assertAlmostEqual(getattr(volume, level), before - 0.1)
self.assertIsNone(pygame.mixer.get_init())
def test_active_mixer_keeps_music_and_channel_updates(self):
_, services = load_library()
for method in ("adjust_master_volume", "adjust_bgm_volume", "adjust_sfx_volume"):
with self.subTest(method=method):
volume = services.VolumeService()
mixer = Mock()
mixer.get_init.return_value = (44100, -16, 2)
mixer.get_num_channels.return_value = 1
mixer.Channel.return_value.get_volume.return_value = 0.5
getattr(volume, method)(-0.1, mixer)
if method != "adjust_sfx_volume":
mixer.music.set_volume.assert_called_once_with(volume.bgmVolume * volume.masterVolume)
if method != "adjust_bgm_volume":
mixer.Channel.return_value.set_volume.assert_called_once_with(0.45)
class DisplayTests(unittest.TestCase):
def run_dialog(self, keys, keyHandler=None):
display, services = load_library()
events = [SimpleNamespace(type=pygame.KEYDOWN, key=key, mod=mods) for key, mods in keys]
with patch.object(pygame.event, "clear"), patch.object(pygame.event, "wait", side_effect=events):
if keyHandler is None:
display.display_text(["First", "", "Second"])
else:
display.display_text(["First", "", "Second"], keyHandler=keyHandler)
return display, services
def test_all_default_volume_keys_work_without_mixer(self):
keys = [pygame.K_PAGEUP, pygame.K_PAGEDOWN, pygame.K_HOME,
pygame.K_END, pygame.K_INSERT, pygame.K_DELETE]
self.run_dialog([(key, pygame.KMOD_ALT) for key in keys] + [(pygame.K_RETURN, 0)])
self.assertIsNone(pygame.mixer.get_init())
def test_custom_handler_consumes_keys_before_default_volume_controls(self):
handler = Mock(side_effect=lambda key, mods: bool(mods & pygame.KMOD_ALT))
display, services = load_library()
volume = services.VolumeService.get_instance()
volume.adjust_bgm_volume = Mock(side_effect=AssertionError("Default volume handler used"))
events = [SimpleNamespace(type=pygame.KEYDOWN, key=key, mod=mods) for key, mods in
[(pygame.K_HOME, pygame.KMOD_ALT), (pygame.K_DOWN, 0), (pygame.K_RETURN, 0)]]
with patch.object(pygame.event, "clear"), patch.object(pygame.event, "wait", side_effect=events):
display.display_text(["First", "Second"], keyHandler=handler)
handler.assert_any_call(pygame.K_HOME, pygame.KMOD_ALT)
display.Speech.get_instance.return_value.speak.assert_any_call("First")
volume.adjust_bgm_volume.assert_not_called()
def test_navigation_and_read_all_keep_working(self):
display, _ = self.run_dialog([(pygame.K_DOWN, 0), (pygame.K_DOWN, 0),
(pygame.K_UP, 0), (pygame.K_SPACE, 0), (pygame.K_ESCAPE, 0)])
spoken = [call.args[0] for call in display.Speech.get_instance.return_value.speak.call_args_list]
self.assertEqual(spoken[1:], ["First", "Second", "First", "First\n\nSecond"])
if __name__ == "__main__":
unittest.main()