diff --git a/meshterm/ui/channels.py b/meshterm/ui/channels.py index aa3b9c5..aec8a93 100644 --- a/meshterm/ui/channels.py +++ b/meshterm/ui/channels.py @@ -90,7 +90,9 @@ from ..core.regions import RegionNameError from ..core.regions import validate as validate_region from ..persistence.repository import ACTIVITY_DRAWN_BUCKETS from ..platforms import get_platform +from . import conversation_sound from .braillechart import activity_peak, activity_sparkline +from .conversation_sound import SOUND_ICON, SOUND_ROW, sound_row from .menus import ( Lane, column_header, @@ -901,7 +903,7 @@ def _detail_items(ctx: AppContext, slot: ChannelSlot) -> list: # ✎ and πŸ—‘ are one cell, and πŸ“± πŸ”‘ πŸ’¬ πŸ”” πŸ”• are two cells. Thus the code measures the # column one time and pads each mark to it. If not, the edit row and the clear row start # their labels one column to the left of the rows above them. - lane = icon_lane(("πŸ“±", "πŸ”‘", "πŸ’¬", "πŸ””", "πŸ”•", "πŸ”–", "✎", "πŸ—‘")) + lane = icon_lane(("πŸ“±", "πŸ”‘", "πŸ’¬", "πŸ””", "πŸ”•", SOUND_ICON, "πŸ”–", "✎", "πŸ—‘")) chat_label = marked_label("πŸ’¬", "Open in chat", "", lane=lane) if unread: chat_label.append(" ●", style="err") @@ -932,6 +934,11 @@ def _detail_items(ctx: AppContext, slot: ChannelSlot) -> list: ), (chat_label, "Read and send messages on this channel", _CHAT), mute_row, + *( + [sound_row(ctx, slot.conversation.key, "channel", lane)] + if conversation_sound.offered(ctx) + else [] + ), _scope_row(ctx, slot, lane), ( marked_label("✎", "Rename / change key…", "", lane=lane), @@ -1003,6 +1010,9 @@ async def _channel_detail( # place and go back to the detail screen (its rows render again to the new # state). Do not count it as a channel change. _toggle_mute(ctx, slot) + elif choice == SOUND_ROW: + # MeshTerm keeps it, as it keeps the mute. It is not a channel change. + await conversation_sound.pick_sound(ctx, slot.conversation.key, "channel", slot.name) elif choice == _SCOPE: # MeshTerm keeps it, as it keeps the mute. Nothing is written to the radio until # a message is sent, so it is not a channel change either. diff --git a/meshterm/ui/conversation_sound.py b/meshterm/ui/conversation_sound.py new file mode 100644 index 0000000..26a5dcf --- /dev/null +++ b/meshterm/ui/conversation_sound.py @@ -0,0 +1,107 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The *Sound…* row of a conversation, and the picker that it opens. + +A channel, a DM, and a room each have a sound setting (refer to +:class:`~meshterm.core.sound_store.SoundStore`): ``off``, ``mentions``, ``all``, or the +default of its kind (a preference). Three pages show the row: the channel detail page, +the node page of a contact, and the page of a room. They all build it here, so that the +words and the picker are the same on each page. + +The row is only on a platform that can play a sound. The PicoCalc has no sound, so a +setting there would change nothing that the user can hear. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from rich.text import Text + +from ..core.preferences import SOUND_WHEN_CHOICES +from .menus import marked_label +from .tui import Choice + +if TYPE_CHECKING: + from ..context import AppContext + +#: The icon of the row. +SOUND_ICON = "πŸ”Š" + +#: The value with which the row resolves. +SOUND_ROW = "sound" + +#: The value of the picker for "follow the default of the kind". The store keeps no record +#: for it. +_DEFAULT = "default" + +#: The preference that holds the default of each kind of conversation. +KIND_PREFERENCE = {"channel": "channel_sound", "dm": "dm_sound", "room": "room_sound"} + + +def offered(ctx: AppContext) -> bool: + """Whether the pages show the row: the platform can play a sound.""" + sound = getattr(ctx, "sound", None) + return sound is not None and sound.available + + +def _default_when(ctx: AppContext, kind: str) -> str: + """The default sound setting of a kind of conversation, from its preference.""" + return str(ctx.preferences.get(KIND_PREFERENCE[kind])) + + +def describe(ctx: AppContext, key: str, kind: str) -> str: + """The description of the row: what the conversation plays now. + + Args: + ctx: The shared application context. + key: The key of the conversation (``chan:…`` or ``dm:…``). + kind: ``channel``, ``dm``, or ``room``. + + Returns: + A short sentence, for example ``Default: mentions only``. + """ + own = ctx.sound_store.get(key) + when = own or _default_when(ctx, kind) + text = { + "off": "No sound", + "mentions": "A sound for mentions only", + "all": "A sound for each message", + }[when] + return text if own else f"Default: {SOUND_WHEN_CHOICES[when]}" + + +def sound_row(ctx: AppContext, key: str, kind: str, lane: int) -> tuple[Text, str, str]: + """The *Sound…* row, as a ``(label, description, value)`` row for ``menu_rows``.""" + return (marked_label(SOUND_ICON, "Sound…", "", lane=lane), describe(ctx, key, kind), SOUND_ROW) + + +async def pick_sound(ctx: AppContext, key: str, kind: str, subject: str) -> bool: + """Ask when the conversation plays a sound, and store the answer. + + Args: + ctx: The shared application context. + key: The key of the conversation. + kind: ``channel``, ``dm``, or ``room``. + subject: The name of the conversation, for the title. + + Returns: + ``True`` if the setting changed. + """ + own = ctx.sound_store.get(key) + current = own or _DEFAULT + default_label = SOUND_WHEN_CHOICES[_default_when(ctx, kind)] + options = [(_DEFAULT, f"Default ({default_label})"), *SOUND_WHEN_CHOICES.items()] + items = [ + Choice(title=label + (" (current)" if value == current else ""), value=value) + for value, label in options + ] + choice = await ctx.ui.select( + f"Sound β€” {subject}", + items, + prompt=f"When this {'conversation' if kind == 'dm' else kind} plays a sound:", + default=current, + ) + if choice is None or choice == current: + return False + ctx.sound_store.set(key, None if choice == _DEFAULT else choice) + return True diff --git a/meshterm/ui/node_detail_screen.py b/meshterm/ui/node_detail_screen.py index 987fc24..194b5fc 100644 --- a/meshterm/ui/node_detail_screen.py +++ b/meshterm/ui/node_detail_screen.py @@ -112,11 +112,19 @@ from rich.text import Text from ..core.connection import ContactNotOnDeviceError, DeviceCommandError from ..core.geo import haversine_km, usable_fix -from ..core.models import NODE_TYPE_LABELS, NODE_TYPE_REPEATER, NODE_TYPE_ROOM, Contact, utcnow +from ..core.models import ( + NODE_TYPE_LABELS, + NODE_TYPE_REPEATER, + NODE_TYPE_ROOM, + Contact, + conversation_key, + is_direct_messageable, + utcnow, +) from ..core.places import SOURCE_USER from ..platforms import Platform, on_platform from ..services.clock_offsets import node_offset, room_posts_blocked -from . import menus +from . import conversation_sound, menus from .device_route_screen import ACTION as DEVICE_ROUTE_ACTION from .device_route_screen import ICON as DEVICE_ROUTE_ICON from .device_route_screen import RouteEnv, open_device_route @@ -1840,6 +1848,12 @@ async def open_node_detail( # map (a roof, a tower), or a place for a node with no location at all. if places is not None and node_id: info_actions.append(_Action("place", "✎", "", "Set place…")) + # The sound of the conversation with this node: a DM with a companion, or the board of a + # room (refer to meshterm.ui.conversation_sound). Only where a sound can play. + sound_kind = _sound_kind(ctx, contact, you, node_type) + sound_key = _sound_key(contact) if sound_kind else None + if sound_kind and sound_key: + info_actions.append(_sound_action(ctx, sound_key, sound_kind)) if you: # Our page is where the user looks at our node, so it offers the tools of the main # menu that act on our node: its whole ``This node`` section, row for row. @@ -2082,6 +2096,12 @@ async def open_node_detail( if await _restore_archived(ctx, contact, self_key, label): contact_removed = True break + elif action == conversation_sound.SOUND_ROW: + assert sound_kind and sound_key # offered only for a conversation + if await conversation_sound.pick_sound(ctx, sound_key, sound_kind, label): + fresh = _sound_action(ctx, sound_key, sound_kind) + base_actions = [fresh if a.key == fresh.key else a for a in base_actions] + screen.replace_info_actions(management(locked)) elif action in ("lock", "unlock"): # No confirm and no notice. The same row that set the lock can reverse it, # and the change of the row into its opposite is the acknowledgement. @@ -2167,6 +2187,42 @@ def _shown_self(info: dict) -> tuple: return tuple(info.get(field) for field in _SHOWN_SELF_FIELDS) +def _sound_kind( + ctx: AppContext, contact: Contact | None, you: bool, node_type: int | None +) -> str | None: + """The kind of the conversation with a node, for its sound row, or ``None`` for no row. + + A companion is a DM, and a room server is a room. Our node, a node with no key, and a + repeater or a sensor (which has no conversation) have no row. Nor does a platform that + cannot play a sound. + """ + if you or contact is None or not conversation_sound.offered(ctx): + return None + if node_type == NODE_TYPE_ROOM: + return "room" + return "dm" if is_direct_messageable(node_type) else None + + +def _sound_key(contact: Contact | None) -> str | None: + """The key of the conversation with a contact (``dm:``), or ``None``. + + The key prefix is the first six bytes of the key, as the address of a direct message + and the history use it (refer to :func:`~meshterm.core.models.conversation_key`). + """ + if contact is None: + return None + prefix = (contact.key_prefix or contact.public_key[:12] or "").lower() + return conversation_key(False, None, prefix) if prefix else None + + +def _sound_action(ctx: AppContext, key: str, kind: str) -> _Action: + """The sound row of the node page, with what the conversation plays now.""" + description = conversation_sound.describe(ctx, key, kind) + return _Action( + conversation_sound.SOUND_ROW, conversation_sound.SOUND_ICON, "", f"Sound β€” {description}…" + ) + + def _management_rows( *, locked: bool, lockable: bool, manageable: bool, archived: bool, whole_key: bool ) -> list[_Action]: diff --git a/meshterm/ui/rooms.py b/meshterm/ui/rooms.py index 7ad589a..b5faf37 100644 --- a/meshterm/ui/rooms.py +++ b/meshterm/ui/rooms.py @@ -48,6 +48,8 @@ from ..core.models import ( is_room, ) from ..platforms import get_platform +from . import conversation_sound +from .conversation_sound import SOUND_ICON, SOUND_ROW, sound_row from .menus import ( Lane, column_header, @@ -495,6 +497,8 @@ async def _room_detail(ctx: AppContext, key: str) -> int: from .room import open_room await open_room(ctx, Conversation(label=room.name, is_channel=False, contact=room)) + elif choice == SOUND_ROW: + await conversation_sound.pick_sound(ctx, f"dm:{_peer(room)}", "room", room.name) elif choice == _FORGET: await _forget(ctx, room) elif choice == _DELETE: @@ -536,7 +540,7 @@ def _detail_items(ctx: AppContext, room: Contact) -> list: stored = bool( ctx.repo.recent_chat_messages(is_channel=False, peer=peer, posts_only=True, limit=1) ) - lane = icon_lane(("πŸ’¬", "↻", "πŸ”‘", "πŸ—‘")) + lane = icon_lane(("πŸ’¬", "↻", "πŸ”‘", SOUND_ICON, "πŸ—‘")) unread = ctx.chat.unread(f"dm:{peer}") rows: list = [] if joined: @@ -556,6 +560,11 @@ def _detail_items(ctx: AppContext, room: Contact) -> list: "Log in with a different password", _PASSWORD, ), + *( + [sound_row(ctx, f"dm:{peer}", "room", lane)] + if conversation_sound.offered(ctx) + else [] + ), ( marked_label("πŸ—‘", "Forget this room…", "err", lane=lane), "Stop logging in, and forget its password", diff --git a/tests/test_conversation_sound.py b/tests/test_conversation_sound.py new file mode 100644 index 0000000..cec67f3 --- /dev/null +++ b/tests/test_conversation_sound.py @@ -0,0 +1,88 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The Sound row of a conversation, and its picker.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path +from types import SimpleNamespace + +from meshterm.core.preferences import Preferences +from meshterm.core.sound_store import SoundStore +from meshterm.ui import conversation_sound +from meshterm.ui.node_detail_screen import _sound_key, _sound_kind + + +class FakeUi: + """Answers the picker with a fixed value, and records what it asked.""" + + def __init__(self, answer: object) -> None: + """Answer each select with ``answer``.""" + self.answer = answer + self.asked: list[tuple[str, list, object]] = [] + + async def select(self, title: str, items: list, *, prompt: str, default: object) -> object: + """Record the question, and return the fixed answer.""" + self.asked.append((title, items, default)) + return self.answer + + +def _ctx(tmp_path: Path, answer: object = None, **prefs: object) -> SimpleNamespace: + return SimpleNamespace( + preferences=Preferences(values=prefs), + sound_store=SoundStore(tmp_path / "sounds.json"), + sound=SimpleNamespace(available=True), + ui=FakeUi(answer), + ) + + +def test_the_description_names_the_default_or_the_own_setting(tmp_path: Path) -> None: + """With no setting, the row names the default of the kind. With one, it names it.""" + ctx = _ctx(tmp_path) + assert conversation_sound.describe(ctx, "chan:a", "channel") == "Default: mentions" + assert conversation_sound.describe(ctx, "dm:b", "dm") == "Default: all messages" + ctx.sound_store.set("chan:a", "off") + assert conversation_sound.describe(ctx, "chan:a", "channel") == "No sound" + + +def test_the_picker_stores_a_setting_and_default_removes_it(tmp_path: Path) -> None: + """A pick stores the setting. ``Default`` removes it again.""" + ctx = _ctx(tmp_path, answer="all") + assert asyncio.run(conversation_sound.pick_sound(ctx, "chan:a", "channel", "Public")) + assert ctx.sound_store.get("chan:a") == "all" + title, items, default = ctx.ui.asked[0] + assert title == "Sound β€” Public" + assert default == "default" + assert [i.value for i in items] == ["default", "off", "mentions", "all"] + ctx.ui.answer = "default" + assert asyncio.run(conversation_sound.pick_sound(ctx, "chan:a", "channel", "Public")) + assert ctx.sound_store.get("chan:a") is None + + +def test_esc_or_the_same_value_changes_nothing(tmp_path: Path) -> None: + """Esc (``None``) and the current value both return ``False`` and write nothing.""" + ctx = _ctx(tmp_path, answer=None) + assert not asyncio.run(conversation_sound.pick_sound(ctx, "dm:b", "dm", "Ann")) + ctx.ui.answer = "default" + assert not asyncio.run(conversation_sound.pick_sound(ctx, "dm:b", "dm", "Ann")) + assert not (tmp_path / "sounds.json").exists() + + +def test_the_row_is_only_where_a_sound_can_play(tmp_path: Path) -> None: + """No sound service, or one that cannot play, means no row.""" + ctx = _ctx(tmp_path) + assert conversation_sound.offered(ctx) + ctx.sound.available = False + assert not conversation_sound.offered(ctx) + assert not conversation_sound.offered(SimpleNamespace()) + + +def test_the_node_page_offers_the_row_for_a_companion_and_a_room(tmp_path: Path) -> None: + """A companion is a DM, a room server is a room, and a repeater has no conversation.""" + ctx = _ctx(tmp_path) + contact = SimpleNamespace(key_prefix="D4E5F6A7B8C9", public_key="d4e5f6a7b8c9" + "0" * 52) + assert _sound_kind(ctx, contact, False, 1) == "dm" + assert _sound_kind(ctx, contact, False, 3) == "room" + assert _sound_kind(ctx, contact, False, 2) is None + assert _sound_kind(ctx, contact, True, 1) is None # our own node + assert _sound_key(contact) == "dm:d4e5f6a7b8c9"