From 0b04ce5c94e3ee28dc546c69607451c9b9e0a4c2 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sat, 21 Nov 2026 00:14:29 -0500 Subject: [PATCH] The volume is a slider of ten steps, and each step plays the channel sound Co-Authored-By: Claude Opus 5.5 --- meshterm/services/sound.py | 16 ++++-- meshterm/ui/preferences.py | 20 ++++++- meshterm/ui/slider.py | 114 +++++++++++++++++++++++++++++++++++++ tests/test_gallery.py | 10 ++++ tests/test_slider.py | 84 +++++++++++++++++++++++++++ 5 files changed, 239 insertions(+), 5 deletions(-) create mode 100644 meshterm/ui/slider.py create mode 100644 tests/test_slider.py diff --git a/meshterm/services/sound.py b/meshterm/services/sound.py index 5cf0bb7..bd35b5b 100644 --- a/meshterm/services/sound.py +++ b/meshterm/services/sound.py @@ -303,18 +303,26 @@ class SoundService: self._flash() return audible - def preview(self, event: SoundEvent = SoundEvent.CHANNEL_MESSAGE) -> bool: + def preview( + self, event: SoundEvent = SoundEvent.CHANNEL_MESSAGE, volume: int | None = None + ) -> bool: """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"). + Args: + event: The event whose sound plays. + volume: The volume from 1 to 10, or ``None`` for the ``sound_volume`` + preference. The volume slider gives the value that it shows, before the + user applies it. + Returns: ``True`` if a sound started. """ - return self.available and self._emit(event) + return self.available and self._emit(event, volume) - def _emit(self, event: SoundEvent) -> bool: + def _emit(self, event: SoundEvent, volume: int | None = None) -> bool: """Play the sound of an event in the current theme, with no rules.""" theme = self._prefs.sound_theme if theme == "bell": @@ -329,7 +337,7 @@ class SoundService: try: path = scaled( SOUNDS_DIR / files[event], - int(self._prefs.sound_volume) * 10, + int(self._prefs.sound_volume if volume is None else volume) * 10, self._ctx.settings.config_dir / "sound-cache", ) except (OSError, wave.Error, EOFError) as error: diff --git a/meshterm/ui/preferences.py b/meshterm/ui/preferences.py index a560ed7..912837a 100644 --- a/meshterm/ui/preferences.py +++ b/meshterm/ui/preferences.py @@ -61,7 +61,8 @@ from .menus import ( lane_row, section_heading, ) -from .tui import Choice, Separator +from .slider import SliderScreen +from .tui import CANCEL, Choice, Separator if TYPE_CHECKING: from ..context import AppContext @@ -489,6 +490,23 @@ async def _prompt_value(ctx: AppContext, spec: PrefSpec, current: Any) -> Any: spec.label, items, prompt=f"{spec.description}:", default=current ) + if spec.key == "sound_volume": + # A slider of ten steps, and each step plays the channel message sound at the new + # volume (JP, 2026-11-20). The value is staged, so the preview gives it directly. + result = await ctx.ui.session.run_screen( + SliderScreen( + spec.label, + spec.help, + int(current), + int(spec.minimum or 1), + int(spec.maximum or 10), + on_change=lambda volume: ctx.sound.preview(volume=volume), + more="Louder", + less="Softer", + ) + ) + return None if result is CANCEL else result + def validate(text: str) -> bool | str: try: parse_value(spec, text) diff --git a/meshterm/ui/slider.py b/meshterm/ui/slider.py new file mode 100644 index 0000000..2e92e66 --- /dev/null +++ b/meshterm/ui/slider.py @@ -0,0 +1,114 @@ +# SPDX-License-Identifier: Apache-2.0 +"""A horizontal slider: a dialog that sets a whole number in a short range, one step at a time. + +The Preferences page opens it for the volume of the sounds (JP, 2026-11-20: "a slider +(horizontal) 1 at a time"). ←→ move the value one step, Home and End go to the ends, Enter +sets the value, and Esc keeps the old one. The ends clamp, as each cursor in the app does. + +Each step calls ``on_change`` with the new value. The volume uses it to play the channel +message sound at the new volume, so that the user hears the value while choosing it. A +typed number is not necessary: a short range is faster with the arrows, and the bar shows +where the value is in the range. +""" + +from __future__ import annotations + +from collections.abc import Callable + +from rich.console import Group +from rich.text import Text + +from .braillechart import meter +from .tui.fkeys import FPair +from .tui.render import render_lines +from .tui.screen import Screen + +#: The width of the dialog, in cells. The bar takes what the value label does not. +_WIDTH = 44 + + +class SliderScreen(Screen): + """The slider dialog. It resolves with the value that Enter sets, or with ``CANCEL``.""" + + floating = True + footer_hint = "←→ change · Home/End ends · Enter set · Esc keep" + + def __init__( + self, + title: str, + prompt: str, + value: int, + minimum: int, + maximum: int, + on_change: Callable[[int], None] | None = None, + more: str = "More", + less: str = "Less", + ) -> None: + """Make a slider. + + Args: + title: The title of the dialog (the label of the preference). + prompt: The line above the bar (the description of the preference). + value: The value at the start. The slider clamps it to the range. + minimum: The lowest value. + maximum: The highest value. + on_change: Called with the new value at each step. + more: The F-key chip of a step up on a handheld (six cells at most). + less: The F-key chip of a step down. + """ + super().__init__() + self.title = title + self._prompt = prompt + self._minimum = minimum + self._maximum = maximum + self.value = max(minimum, min(maximum, value)) + self._on_change = on_change + self._more = more + self._less = less + + @property + def dialog_width(self) -> int: + """A small box: the prompt and the bar.""" + return _WIDTH + + @property + def picocalc_lyra_lane(self): + """A step up on F1 and a step down on F2: a directional pair rises to its outer key.""" + return ( + FPair(self._more, "right", enabled=self.value < self._maximum), + FPair(self._less, "left", enabled=self.value > self._minimum), + None, + None, + None, + ) + + def render_body(self, width: int) -> list[str]: + """The prompt, then the bar with the value at its right end. + + The bar is a whole number of cells for each step, so that each step lights whole + cells and the bar never ends on a half cell. The value follows the bar. + """ + label = f" {self.value:>{len(str(self._maximum))}}" + steps = self._maximum - self._minimum + 1 + room = max(steps, width - len(label) - 1) + cells = room - room % steps + fraction = (self.value - self._minimum + 1) / steps + bar = meter(fraction, cells, style="accent", slim=True, track="track") + bar.append(label, style="bold") + return render_lines(Group(Text(self._prompt, style="muted"), Text(""), bar), width) + + def handle(self, action: str, data: str = "") -> None: + """Move one step, go to an end, set, or keep.""" + if action == "escape": + super().handle(action, data) + return + if action == "enter": + self.resolve(self.value) + return + steps = {"left": -1, "right": 1, "home": -self._maximum, "end": self._maximum} + if action in steps: + new = max(self._minimum, min(self._maximum, self.value + steps[action])) + if new != self.value: + self.value = new + if self._on_change is not None: + self._on_change(new) diff --git a/tests/test_gallery.py b/tests/test_gallery.py index cfc433a..36c3580 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -1985,6 +1985,15 @@ def _quit_hold(cols: int, rows: int) -> Screen: return HoldQuitDialog(0.0, clock=lambda: (DIALOG_S + QUIT_S) / 2) +def _volume_slider(cols: int, rows: int) -> Screen: + """The volume slider of the Preferences page, at its default step.""" + from meshterm.core.preferences import get_spec + from meshterm.ui.slider import SliderScreen + + spec = get_spec("sound_volume") + return SliderScreen(spec.label, spec.help, 7, 1, 10, more="Louder", less="Softer") + + def _share_qr(cols: int, rows: int) -> Screen: """The share screen: the code and the link of a contact card on a bare frame (the widest QR).""" from meshterm.ui.qr import QrScreen @@ -2138,6 +2147,7 @@ _ENTRIES: list[_Entry] = [ _Entry("cooldown_countdown", _cooldown_countdown), _Entry("reconnect_reason", _reconnect_reason), _Entry("quit_hold", _quit_hold), + _Entry("volume_slider", _volume_slider), _Entry("about_meshterm", _about_meshterm), _Entry("about_author", _about_author), _Entry("join_discord", _join_discord), diff --git a/tests/test_slider.py b/tests/test_slider.py new file mode 100644 index 0000000..cb6977f --- /dev/null +++ b/tests/test_slider.py @@ -0,0 +1,84 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The horizontal slider: steps of one, clamped ends, a call at each step, Enter and Esc.""" + +from __future__ import annotations + +import asyncio +import re + +from rich.cells import cell_len + +from meshterm.ui.slider import SliderScreen +from meshterm.ui.tui.screen import CANCEL + + +def strip_ansi(text: str) -> str: + """The text of a rendered line, without its SGR codes.""" + return re.sub(r"\x1b\[[0-9;]*m", "", text) + + +def _slider(value: int = 7) -> tuple[SliderScreen, list[int]]: + changes: list[int] = [] + return SliderScreen("Volume", "How loud", value, 1, 10, on_change=changes.append), changes + + +def test_the_arrows_move_one_step_and_call_on_change() -> None: + """→ adds one, ← removes one, and each step calls ``on_change`` with the new value.""" + slider, changes = _slider() + slider.handle("right") + slider.handle("left") + slider.handle("left") + assert slider.value == 6 + assert changes == [8, 7, 6] + + +def test_the_ends_clamp_and_a_step_at_an_end_calls_nothing() -> None: + """Nothing rolls over, and a key that changes nothing plays no preview.""" + slider, changes = _slider(10) + slider.handle("right") + assert slider.value == 10 and changes == [] + slider.handle("home") + assert slider.value == 1 and changes == [1] + slider.handle("left") + assert changes == [1] + slider.handle("end") + assert slider.value == 10 + + +def test_enter_sets_and_esc_keeps() -> None: + """Enter resolves with the value, and Esc resolves with ``CANCEL``.""" + loop = asyncio.new_event_loop() + try: + slider, _ = _slider() + slider.future = loop.create_future() + slider.handle("right") + slider.handle("enter") + assert slider.future.result() == 8 + slider, _ = _slider() + slider.future = loop.create_future() + slider.handle("escape") + assert slider.future.result() is CANCEL + finally: + loop.close() + + +def test_a_start_value_out_of_range_is_clamped() -> None: + """A value from a file that was edited by hand comes into the range.""" + assert _slider(42)[0].value == 10 + assert _slider(-3)[0].value == 1 + + +def test_the_bar_fills_the_line_on_both_widths() -> None: + """The bar and its value fill each line exactly, at 72 and at 53 columns.""" + for width in (40, 49): + lines = _slider()[0].render_body(width) + assert all(cell_len(strip_ansi(line)) <= width for line in lines) + assert strip_ansi(lines[-1]).rstrip().endswith(" 7") + + +def test_the_handheld_lane_dims_a_step_past_an_end() -> None: + """``More`` is dim at the top, and ``Less`` at the bottom.""" + top = _slider(10)[0].picocalc_lyra_lane + assert top[0].enabled is False and top[1].enabled is True + bottom = _slider(1)[0].picocalc_lyra_lane + assert bottom[0].enabled is True and bottom[1].enabled is False