diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py index 29f2140..429919f 100644 --- a/meshterm/core/preferences.py +++ b/meshterm/core/preferences.py @@ -50,12 +50,12 @@ from dataclasses import dataclass from pathlib import Path from typing import Any +from ..platforms import ALL_PLATFORMS from .advert_store import DEFAULT_QUIET_S, QUIET_CHOICES_S from .atomicwrite import write_atomically from .courier_store import DONE_CAP from .geo import DEFAULT_VIEW_FRACTION from .models import CLOCK_TOLERANCE_S, NAME_OVERLAP_DAYS -from ..platforms import ALL_PLATFORMS from .watch_store import ALERT_CAP, DEFAULT_SILENCE_HOURS, OFF, SILENCE_CHOICES_H if sys.version_info >= (3, 11): @@ -172,7 +172,7 @@ _SOUND_THEME_CHOICES: dict[str, str] = { } #: When the title bar flashes for a notification. ``silent`` flashes only when no sound -#: plays for it: sounds are off, the theme is ``none``, the platform has no sound, or the +#: plays for it: the sounds are muted, the theme is ``none``, the platform has no sound, or the #: player failed. _FLASH_CHOICES: dict[str, str] = {"off": "off", "on": "on", "silent": "when silent"} @@ -502,41 +502,41 @@ PREFERENCES: tuple[PrefSpec, ...] = ( default="https://nominatim.openstreetmap.org", ), # --- Sound --------------------------------------------------------------------- - PrefSpec( - key="sounds", - label="Sounds", - help="Play a sound for notifications. ^S turns it on or off", - group="Sound", - value_type="bool", - # Off: a new user hears nothing until they ask for it (the request on Discord, - # 2026-09-26: "Defaulted to off though"). ^S changes this preference from any - # screen, and the header shows its state (๐Ÿ”Š on, ๐Ÿ”‡ off). - default=False, - platforms=_SOUND_PLATFORMS, - ), PrefSpec( key="sound_theme", label="Sound theme", help="The set of sounds that notifications play", group="Sound", value_type="enum", + # Android, and not muted (JP, 2026-11-20). "No sound" is a theme, not a mute: the + # user who wants no sound at all selects it. default="android", choices=_SOUND_THEME_CHOICES, platforms=_SOUND_PLATFORMS, ), PrefSpec( - key="sound_volume_pct", + key="sound_muted", + label="Mute", + help="Mute the sounds for now. ^S mutes or unmutes on any screen", + group="Sound", + value_type="bool", + # A mute is for now, and the theme is for always. ^S changes this preference from + # any screen, and the header shows its state (๐Ÿ”Š on, ๐Ÿ”‡ muted). + default=False, + platforms=_SOUND_PLATFORMS, + ), + PrefSpec( + key="sound_volume", label="Volume", - help="How loud the sounds play, before the volume of the system", + help="How loud the sounds play: 1 is 10%, 10 is 100%", group="Sound", value_type="int", - # MeshTerm scales the samples itself (JP, 2026-11-20), because winsound, the only - # player on Windows, has no volume control. Thus the volume is the same with each - # player. 70: the AOSP chimes are loud at full scale. - default=70, - minimum=5, - maximum=100, - unit="%", + # A slider of ten steps (JP, 2026-11-20). MeshTerm scales the samples itself, + # because winsound, the only player on Windows, has no volume control. Thus the + # volume is the same with each player. + default=7, + minimum=1, + maximum=10, platforms=_SOUND_PLATFORMS, ), PrefSpec( @@ -827,6 +827,11 @@ RETIRED: frozenset[str] = frozenset( # and later the weekly flood advert (``weekly_flood_advert``) replaced them. "advert_direct_hours", "advert_flood_hours", + # The first form of the sound preferences, replaced on the day they were made + # (2026-11-20): a sound on/off switch that the mute and the "no sound" theme + # replaced, and a volume in percent that a slider of ten steps replaced. + "sounds", + "sound_volume_pct", } ) diff --git a/meshterm/services/sound.py b/meshterm/services/sound.py index 32cfa73..5cf0bb7 100644 --- a/meshterm/services/sound.py +++ b/meshterm/services/sound.py @@ -258,8 +258,8 @@ class SoundService: @property def enabled(self) -> bool: - """Whether sounds are on: the platform can play them, and the user turned them on.""" - return self.available and bool(self._prefs.sounds) + """Whether sounds can play now: the platform can play them, and they are not muted.""" + return self.available and not bool(self._prefs.sound_muted) @property def audible_theme(self) -> bool: @@ -267,18 +267,18 @@ class SoundService: return self._prefs.sound_theme != "none" def toggle(self) -> bool: - """Turn sounds on or off (the ^S key), and save the preference. + """Mute or unmute the sounds (the ^S key), and save the preference. Returns: - ``True`` if sounds are now on. + ``True`` if the sounds are now on (not muted). """ - now_on = not bool(self._prefs.sounds) - self._prefs.set("sounds", now_on) + muted = not bool(self._prefs.sound_muted) + self._prefs.set("sound_muted", muted) try: self._prefs.save() except OSError as error: log.warning("sound: could not save the preferences: %s", error) - return now_on + return not muted def notify(self, event: SoundEvent) -> bool: """Play the sound of an event, and flash the title bar if the preference says so. @@ -304,7 +304,7 @@ class SoundService: return audible def preview(self, event: SoundEvent = SoundEvent.CHANNEL_MESSAGE) -> bool: - """Play the sound of an event at the current volume, also when sounds are off. + """Play the sound of an event at the current volume, also when the sounds are muted. The Preferences page calls it while the user changes the volume or the theme (JP, 2026-11-20: "while adjusting the volume, play the channel message sound"). @@ -329,7 +329,7 @@ class SoundService: try: path = scaled( SOUNDS_DIR / files[event], - int(self._prefs.sound_volume_pct), + int(self._prefs.sound_volume) * 10, self._ctx.settings.config_dir / "sound-cache", ) except (OSError, wave.Error, EOFError) as error: diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 8951131..759818c 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -40,7 +40,7 @@ from .menus import ( section_heading, ) from .surface import TuiUi -from .theme import make_console +from .theme import glyph, make_console from .tui import ( Choice, PopToMenu, @@ -377,9 +377,25 @@ def _header_segments(ctx: AppContext, cache: dict) -> list[Text]: badge.append("โ–ฒ", style="err") badge.append(f" {alerts}", style="warn") segments.append(badge) + speaker = _sound_badge(ctx) + if speaker: + segments.append(speaker) return segments +def _sound_badge(ctx: AppContext) -> Text: + """The state of the sounds in the header: ๐Ÿ”Š on, ๐Ÿ”‡ off, or nothing. + + The header shows nothing where no sound can play: on a platform with no sound (the + PicoCalc), and with the ``none`` theme (JP, 2026-11-20: "No sound, no speaker emoji at + all"). ^S changes the state from any screen. + """ + sound = getattr(ctx, "sound", None) + if sound is None or not sound.available or not sound.audible_theme: + return Text() + return Text(glyph(_SOUND_ON_ICON if sound.enabled else _SOUND_OFF_ICON), style="muted") + + def _demo_name() -> str: """The name of our node in the demo world.""" from ..demo.world import SELF @@ -467,6 +483,9 @@ async def run_menu(ctx: AppContext) -> None: session.set_quit_confirm(lambda: _confirm_quit(ctx, session)) # What a held Esc engages while its dialog is open. The app keeps it while it exits. session.set_quiesce(lambda: _off_the_air(ctx)) + # ^S mutes or unmutes the sounds from any screen. The bell theme rings the terminal. + session.set_sound_toggle(lambda: _toggle_sound(ctx)) + ctx.sound.set_hooks(bell=session.bell) # Where a terminal gives the keys, MeshTerm asks the keyboard whether Esc is still # held. Thus a held Esc quits there too. The emulator reads its keys itself, and the # keyboard of its machine is not the keyboard of the handheld. @@ -589,6 +608,27 @@ _QUIT_ICON = "๐Ÿšช" #: :class:`_MainMenu`). _QUIT_VALUE = "__quit__" +#: The icons of the sound state: in the header, and on the Sounds row of the menu. +_SOUND_ON_ICON = "๐Ÿ”Š" +_SOUND_OFF_ICON = "๐Ÿ”‡" + +#: The value with which the Sounds row resolves. The row mutes or unmutes the sounds, and +#: the menu stays (refer to :func:`_menu_round`). +_SOUND_VALUE = "__sound__" + + +def _toggle_sound(ctx: AppContext) -> None: + """Mute or unmute the sounds (the Sounds row, and ^S from any screen). + + When the sounds come on, the channel message sound plays one time. Thus the user hears + that they are on, and how loud they are. + """ + sound = ctx.sound + if not sound.available or not sound.audible_theme: + return + if sound.toggle(): + sound.preview() + async def _confirm_quit(ctx: AppContext, session: TuiSession) -> bool: """Open the quit confirm as a dialog over the current screen, and return whether to leave. @@ -725,7 +765,9 @@ def _menu_lane(tools: Sequence[Any]) -> int: The column width from :func:`~meshterm.ui.menus.icon_lane`: ``0`` where the platform draws no icon lane. """ - return icon_lane([*(tool.icon for tool in tools), _QUIT_ICON]) + return icon_lane( + [*(tool.icon for tool in tools), _QUIT_ICON, _SOUND_ON_ICON, _SOUND_OFF_ICON] + ) def _menu_labels(tools: Sequence[Any], *, lane: int | None = None) -> list[Text]: @@ -760,7 +802,7 @@ def _menu_labels(tools: Sequence[Any], *, lane: int | None = None) -> list[Text] return labels -def _menu_items(tools: Sequence[Any]) -> list: +def _menu_items(tools: Sequence[Any], sound: Any = None) -> list: """The rows of the main menu: the tools under their section headings, then Quit. This function is separate from :func:`_menu_loop`, so that the list can be built and @@ -779,6 +821,8 @@ def _menu_items(tools: Sequence[Any]) -> list: tools: The visible tools of the menu, in the order in which they are drawn (already sorted by category, so that each heading opens its section only one time). + sound: The sound service (:class:`~meshterm.services.sound.SoundService`), for the + Sounds row above Quit. ``None``, or a platform with no sound, has no such row. Returns: The :class:`~meshterm.ui.tui.Choice` and :class:`~meshterm.ui.tui.Separator` @@ -800,6 +844,26 @@ def _menu_items(tools: Sequence[Any]) -> list: # stays (Choice.hscroll_from). items.append(Choice(title=row, value=tool.name, hscroll_from=name_w + 2)) items.append(Separator(" ")) + if sound is not None and sound.available: + # The row names the state that the sounds are in now, and Enter changes it. The + # title is read at each paint, so ^S on another screen shows here too. + # With the "no sound" theme, the row has no speaker (JP, 2026-11-20: "No sound, no + # speaker emoji at all") and Enter does nothing: there is nothing to mute. + def sounds_title() -> Text: + if not sound.audible_theme: + label = Text(" " * (lane + 1) if lane else "") # an empty icon column + label.append("No sound") + hint = "the sound theme is in Preferences" + else: + on = sound.enabled + label = icon_mark(_SOUND_ON_ICON if on else _SOUND_OFF_ICON, "", lane) + label.append("Sound on" if on else "Sound muted") + hint = "^S on any screen" + label.append(" " * max(2, name_w - label.cell_len + 2)) + label.append(hint, style="muted") + return label + + items.append(Choice(title=sounds_title, value=_SOUND_VALUE)) # Quit has no description, so it is not part of name_w. Only its icon uses the icon # column of the tools. quit_label = icon_mark(_QUIT_ICON, "", lane) @@ -833,7 +897,7 @@ async def _menu_loop(ctx: AppContext, session: TuiSession) -> None: session: The running TUI session. """ tools = [tool for tool in all_tools() if tool.menu_visible] - items = _menu_items(tools) + items = _menu_items(tools, ctx.sound) # Drive the menu list here (instead of through session.select), so that it stays on # the stack while the quit dialog shows over it. The confirm is drawn as a centred box @@ -931,6 +995,9 @@ async def _menu_round( if await session.confirm_quit(): raise _Quit() return + if selection == _SOUND_VALUE: + _toggle_sound(ctx) + return # A ``popup`` tool runs while the menu is still pushed. Thus its prompts and its # result show over the menu as modal dialogs, and do not replace the screen. tool = next((t for t in tools if t.name == selection), None) diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index f83bd7f..e6f1292 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -851,6 +851,8 @@ _GLYPH_MAP: dict[str, str] = { "๐Ÿ“จ": "=", # courier/queue: stacked letters "๐Ÿ””": "โ€ข", # notify: the badge dot "๐Ÿ”•": "ยท", # mute: the hollowed-out dot + "๐Ÿ”Š": "โ—„", # sounds on: the cone of a speaker + "๐Ÿ”‡": "โŒซ", # sounds off: the speaker with a cross in it "๐Ÿ“ฑ": "โ–“", # QR: a dense block "๐ŸŽจ": "โ–‘", # pixel image (MCOimg): a fine grid of dots "๐Ÿ”—": "&", # link: the joining glyph diff --git a/meshterm/ui/tui/session.py b/meshterm/ui/tui/session.py index 6243693..71c914a 100644 --- a/meshterm/ui/tui/session.py +++ b/meshterm/ui/tui/session.py @@ -124,6 +124,10 @@ _CTRL_LETTER_CHORDS: dict[str, str] = { "p": "paths", "q": "quit", "r": "retry", + # ^S mutes or unmutes the sounds from any screen (JP, 2026-11-20). S for sound and + # silence. It is the XOFF key, but the raw mode clears IXON/IXOFF (refer to the text + # above), so the terminal never takes it to freeze the screen. + "s": "sound", "u": "url_code", "v": "paste_clipboard", "w": "to_menu", @@ -631,6 +635,8 @@ class TuiSession: # (refer to :meth:`set_quiesce`). Then the quiesce while it is held. Then the # one-way flag that :meth:`leave` raises, which tells if the app is on its way out. self._quiesce: Callable[[], AbstractAsyncContextManager[Any]] | None = None + # What ^S does: the app mutes or unmutes its sounds (refer to set_sound_toggle). + self._sound_toggle: Callable[[], None] | None = None self._quiet: Quiet | None = None self._leaving = False # The Esc of a terminal, held back while the keyboard says that the key is still @@ -812,6 +818,24 @@ class TuiSession: """ self._quiesce = enter + def set_sound_toggle(self, toggle: Callable[[], None] | None) -> None: + """Declare what ^S does: mute or unmute the sounds of the app, from any screen. + + Args: + toggle: Mutes or unmutes the sounds, or ``None`` for nothing. + """ + self._sound_toggle = toggle + + def bell(self) -> None: + """Ring the terminal bell (BEL), for the ``bell`` sound theme. + + Over SSH, the bell rings on the computer of the user, because the terminal there + gets the byte. + """ + output = getattr(self._app, "output", None) + if output is not None: + output.bell() + def set_esc_probe(self, down: Callable[[], bool] | None) -> None: """Declare how to ask whether the Esc key is physically down, for the Esc of a terminal. @@ -2411,6 +2435,13 @@ class TuiSession: # ^W can hit. self._exit_app() return + if action == "sound": + # Mute or unmute the sounds, from any screen (^S). The app declares what the key + # does, because only the app has the sound service (refer to set_sound_toggle). + if self._sound_toggle is not None: + self._sound_toggle() + self.invalidate() + return if action == "paste_clipboard": # Some terminals send Ctrl-V as the literal control key, with no bracketed-paste # sequence, so the event has no text. Read the OS clipboard here, and give the diff --git a/tests/test_sound.py b/tests/test_sound.py index c5d1442..d6fdd12 100644 --- a/tests/test_sound.py +++ b/tests/test_sound.py @@ -71,9 +71,17 @@ def test_each_theme_file_exists_and_is_16_bit_pcm() -> None: assert reader.getsampwidth() == 2 -def test_sounds_are_off_by_default(tmp_path: Path) -> None: - """A new user hears nothing, and the default flash replaces the sound.""" +def test_sounds_play_by_default(tmp_path: Path) -> None: + """The default is the Android theme, not muted (JP, 2026-11-20).""" service, player, _, flashes, _ = _service(tmp_path) + assert service.notify(SoundEvent.DIRECT_MESSAGE) is True + assert len(player.played) == 1 + assert flashes == [] + + +def test_a_muted_service_is_silent_and_flashes(tmp_path: Path) -> None: + """A mute plays nothing, and the default flash replaces the sound.""" + service, player, _, flashes, _ = _service(tmp_path, sound_muted=True) assert service.notify(SoundEvent.DIRECT_MESSAGE) is False assert player.played == [] assert flashes == [1] @@ -81,7 +89,9 @@ def test_sounds_are_off_by_default(tmp_path: Path) -> None: def test_an_event_plays_its_file_of_the_theme(tmp_path: Path) -> None: """An event plays its own file of the theme, and the flash stays off.""" - service, player, _, flashes, _ = _service(tmp_path, sounds=True) + service, player, _, flashes, _ = _service( + tmp_path, + ) assert service.notify(SoundEvent.MENTION) is True assert player.played[0].name.startswith("android-Ariel-") assert flashes == [] # when silent: a sound played, so no flash @@ -89,7 +99,7 @@ def test_an_event_plays_its_file_of_the_theme(tmp_path: Path) -> None: def test_the_volume_scales_a_cached_copy(tmp_path: Path) -> None: """A volume below 100 plays a scaled copy from the cache: 50% is a quarter.""" - service, player, _, _, _ = _service(tmp_path, sounds=True, sound_volume_pct=50) + service, player, _, _, _ = _service(tmp_path, sound_volume=5) service.notify(SoundEvent.DIRECT_MESSAGE) copy = player.played[0] assert copy.parent == tmp_path / "sound-cache" @@ -108,7 +118,7 @@ def test_the_volume_scales_a_cached_copy(tmp_path: Path) -> None: def test_full_volume_plays_the_file_of_the_package(tmp_path: Path) -> None: """At 100%, the service plays the file of the package, with no copy.""" - service, player, _, _, _ = _service(tmp_path, sounds=True, sound_volume_pct=100) + service, player, _, _, _ = _service(tmp_path, sound_volume=10) service.notify(SoundEvent.ROOM_POST) assert player.played == [SOUNDS_DIR / "android/Ceres.wav"] @@ -122,7 +132,7 @@ def test_the_gain_follows_the_square_of_the_volume() -> None: def test_the_bell_theme_rings_the_bell(tmp_path: Path) -> None: """The bell theme rings the terminal bell and plays no file.""" - service, player, _, _, bells = _service(tmp_path, sounds=True, sound_theme="bell") + service, player, _, _, bells = _service(tmp_path, sound_theme="bell") assert service.notify(SoundEvent.CHANNEL_MESSAGE) is True assert bells == [1] assert player.played == [] @@ -130,7 +140,7 @@ def test_the_bell_theme_rings_the_bell(tmp_path: Path) -> None: def test_the_none_theme_is_silent_and_flashes(tmp_path: Path) -> None: """The none theme plays nothing, so the default flash shows the event.""" - service, player, _, flashes, _ = _service(tmp_path, sounds=True, sound_theme="none") + service, player, _, flashes, _ = _service(tmp_path, sound_theme="none") assert service.notify(SoundEvent.DIRECT_MESSAGE) is False assert player.played == [] assert flashes == [1] @@ -138,7 +148,9 @@ def test_the_none_theme_is_silent_and_flashes(tmp_path: Path) -> None: def test_the_tick_is_off_by_default(tmp_path: Path) -> None: """The packet tick is off until the user turns it on.""" - service, player, _, flashes, _ = _service(tmp_path, sounds=True) + service, player, _, flashes, _ = _service( + tmp_path, + ) assert service.notify(SoundEvent.PACKET_TICK) is False assert player.played == [] assert flashes == [] # a tick never flashes @@ -146,7 +158,7 @@ def test_the_tick_is_off_by_default(tmp_path: Path) -> None: def test_the_tick_plays_at_most_one_each_quarter_second(tmp_path: Path) -> None: """The tick plays at most one time each 250 ms.""" - service, player, clock, _, _ = _service(tmp_path, sounds=True, packet_tick=True) + service, player, clock, _, _ = _service(tmp_path, packet_tick=True) assert service.notify(SoundEvent.PACKET_TICK) is True clock.now += 0.1 assert service.notify(SoundEvent.PACKET_TICK) is False @@ -157,7 +169,7 @@ def test_the_tick_plays_at_most_one_each_quarter_second(tmp_path: Path) -> None: def test_no_tick_right_after_another_sound(tmp_path: Path) -> None: """A tick does not play over the start of another sound.""" - service, player, clock, _, _ = _service(tmp_path, sounds=True, packet_tick=True) + service, player, clock, _, _ = _service(tmp_path, packet_tick=True) service.notify(SoundEvent.DIRECT_MESSAGE) clock.now += 0.1 assert service.notify(SoundEvent.PACKET_TICK) is False @@ -166,25 +178,28 @@ def test_no_tick_right_after_another_sound(tmp_path: Path) -> None: def test_a_failed_player_counts_as_silent(tmp_path: Path) -> None: """A player that fails counts as silent, so the flash shows the event.""" - service, _, _, flashes, _ = _service(tmp_path, works=False, sounds=True) + service, _, _, flashes, _ = _service( + tmp_path, + works=False, + ) assert service.notify(SoundEvent.DIRECT_MESSAGE) is False assert flashes == [1] @pytest.mark.parametrize( - ("mode", "sounds", "flashes"), + ("mode", "muted", "flashes"), [ - ("off", False, 0), ("off", True, 0), - ("on", False, 1), + ("off", False, 0), ("on", True, 1), - ("silent", False, 1), - ("silent", True, 0), + ("on", False, 1), + ("silent", True, 1), + ("silent", False, 0), ], ) -def test_the_flash_modes(tmp_path: Path, mode: str, sounds: bool, flashes: int) -> None: +def test_the_flash_modes(tmp_path: Path, mode: str, muted: bool, flashes: int) -> None: """The flash follows its preference: off, on, or only when no sound plays.""" - service, _, _, flashed, _ = _service(tmp_path, sounds=sounds, notify_flash=mode) + service, _, _, flashed, _ = _service(tmp_path, sound_muted=muted, notify_flash=mode) service.notify(SoundEvent.DIRECT_MESSAGE) assert len(flashed) == flashes @@ -192,16 +207,18 @@ def test_the_flash_modes(tmp_path: Path, mode: str, sounds: bool, flashes: int) def test_the_picocalc_is_silent_and_flashes(tmp_path: Path) -> None: """The PicoCalc plays no sound, also for a preview, and it flashes.""" set_platform(PICOCALC_LYRA) - service, player, _, flashes, _ = _service(tmp_path, sounds=True) + service, player, _, flashes, _ = _service( + tmp_path, + ) assert service.notify(SoundEvent.DIRECT_MESSAGE) is False assert service.preview() is False assert player.played == [] assert flashes == [1] -def test_the_preview_plays_also_when_sounds_are_off(tmp_path: Path) -> None: - """The preview plays the channel message sound also when sounds are off.""" - service, player, _, flashes, _ = _service(tmp_path) +def test_the_preview_plays_also_when_muted(tmp_path: Path) -> None: + """The preview plays the channel message sound also when the sounds are muted.""" + service, player, _, flashes, _ = _service(tmp_path, sound_muted=True) assert service.preview() is True assert player.played[0].name.startswith("android-InCallNotification-") assert flashes == [] @@ -212,7 +229,7 @@ def test_toggle_changes_and_saves_the_preference(tmp_path: Path) -> None: prefs = Preferences(path=tmp_path / "preferences.toml") ctx = SimpleNamespace(preferences=prefs, settings=SimpleNamespace(config_dir=tmp_path)) service = SoundService(ctx, player=FakePlayer()) # type: ignore[arg-type] - assert service.toggle() is True - assert Preferences.load(tmp_path / "preferences.toml").sounds is True - assert service.toggle() is False - assert Preferences.load(tmp_path / "preferences.toml").sounds is False + assert service.toggle() is False # muted + assert Preferences.load(tmp_path / "preferences.toml").sound_muted is True + assert service.toggle() is True # on again + assert Preferences.load(tmp_path / "preferences.toml").sound_muted is False diff --git a/tests/test_sound_controls.py b/tests/test_sound_controls.py new file mode 100644 index 0000000..de11e77 --- /dev/null +++ b/tests/test_sound_controls.py @@ -0,0 +1,118 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The controls of the sounds: the ๐Ÿ”Š/๐Ÿ”‡ header badge, the Sound row, and ^S.""" + +from __future__ import annotations + +from collections.abc import Iterator +from types import SimpleNamespace + +import pytest + +from meshterm.platforms import CARDPUTER_ZERO, REGULAR, set_platform +from meshterm.tools import all_tools, load_all_tools +from meshterm.ui import menu +from meshterm.ui.tui import Choice +from meshterm.ui.tui.session import _CTRL_LETTER_CHORDS + + +class FakeSound: + """The parts of the sound service that the controls read.""" + + def __init__(self, available: bool = True, enabled: bool = False, theme: str = "android"): + """Make a service in a fixed state.""" + self.available = available + self.enabled = enabled + self.audible_theme = theme != "none" + self.previews = 0 + + def toggle(self) -> bool: + """Turn the sounds on or off.""" + self.enabled = not self.enabled + return self.enabled + + def preview(self) -> bool: + """Count the previews.""" + self.previews += 1 + return True + + +@pytest.fixture +def regular() -> Iterator[None]: + """Run on the regular platform.""" + set_platform(REGULAR) + yield + set_platform(REGULAR) + + +def test_the_badge_shows_the_state_of_the_sounds(regular: None) -> None: + """๐Ÿ”Š while the sounds are on, ๐Ÿ”‡ while they are off.""" + ctx = SimpleNamespace(sound=FakeSound(enabled=True)) + assert menu._sound_badge(ctx).plain == "๐Ÿ”Š" + ctx.sound.enabled = False + assert menu._sound_badge(ctx).plain == "๐Ÿ”‡" + + +def test_no_badge_where_no_sound_can_play(regular: None) -> None: + """No speaker with the ``none`` theme, nor on a platform with no sound.""" + assert menu._sound_badge(SimpleNamespace(sound=FakeSound(theme="none"))).plain == "" + assert menu._sound_badge(SimpleNamespace(sound=FakeSound(available=False))).plain == "" + + +def test_the_cardputer_badge_is_one_glyph_of_its_font() -> None: + """The Cardputer draws no emoji, so the badge is the compact glyph.""" + set_platform(CARDPUTER_ZERO) + try: + ctx = SimpleNamespace(sound=FakeSound(enabled=True)) + assert menu._sound_badge(ctx).plain == "โ—„" + ctx.sound.enabled = False + assert menu._sound_badge(ctx).plain == "โŒซ" + finally: + set_platform(REGULAR) + + +def _sound_row(sound: FakeSound | None) -> Choice | None: + load_all_tools() + tools = [tool for tool in all_tools() if tool.menu_visible] + rows = [r for r in menu._menu_items(tools, sound) if isinstance(r, Choice)] + return next((r for r in rows if r.value == menu._SOUND_VALUE), None) + + +def test_the_menu_row_names_the_state_now(regular: None) -> None: + """The row says the state of the sounds at each paint.""" + sound = FakeSound() + row = _sound_row(sound) + assert row is not None + assert "Sound muted" in row.title().plain + sound.enabled = True + assert "Sound on" in row.title().plain + sound.audible_theme = False + title = row.title().plain + assert "No sound" in title and "๐Ÿ”Š" not in title and "๐Ÿ”‡" not in title + + +def test_no_menu_row_where_no_sound_can_play(regular: None) -> None: + """The PicoCalc, or no service at all, has no Sounds row.""" + assert _sound_row(FakeSound(available=False)) is None + assert _sound_row(None) is None + + +def test_the_toggle_plays_the_preview_only_when_the_sounds_come_on() -> None: + """Unmute: the channel message sound plays one time. Mute: nothing plays.""" + ctx = SimpleNamespace(sound=FakeSound()) + menu._toggle_sound(ctx) + assert ctx.sound.enabled and ctx.sound.previews == 1 + menu._toggle_sound(ctx) + assert not ctx.sound.enabled and ctx.sound.previews == 1 + + +def test_the_toggle_does_nothing_with_the_no_sound_theme() -> None: + """With the ``none`` theme there is nothing to mute.""" + ctx = SimpleNamespace(sound=FakeSound(theme="none")) + menu._toggle_sound(ctx) + assert not ctx.sound.enabled and ctx.sound.previews == 0 + + +def test_ctrl_s_is_the_sound_chord_and_ctrl_e_reveals() -> None: + """^S turns the sounds on or off, and ^E shows a concealed value (JP, 2026-11-20).""" + assert _CTRL_LETTER_CHORDS["s"] == "sound" + assert _CTRL_LETTER_CHORDS["e"] == "reveal"