From 1ff2eecf7603316bb10c5f1d46a65f6fd7ef6f5d Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Thu, 19 Nov 2026 22:41:18 -0500 Subject: [PATCH] ^U opens a chat's pixel image full-frame; chat_images preference On a picked message that is an MCOimg image, ^U opens it on a bare frame, grown by a whole number to fill it, with its caption under it. The lane chip reads Image and the hint ^U image. The new chat_images preference (Display, on by default) can turn the inline drawing off; then the chat shows the caption only, and ^U is the way to see the image. Refs #37. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 3 ++ meshterm/core/preferences.py | 11 ++++++ meshterm/ui/chat.py | 62 +++++++++++++++++++++++++++--- meshterm/ui/pixelart.py | 73 +++++++++++++++++++++++++++++++++--- tests/test_chat.py | 35 +++++++++++++++++ tests/test_mcoimg.py | 9 +++++ 6 files changed, 182 insertions(+), 11 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 9b0f211..422fea3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -326,6 +326,9 @@ deliberately, one at a time, and say why in the code. narrower quiet zone, before it would ever be cut (a contact card is 57 cells and 29 rows at the standard fit in half blocks; a regular terminal is 24 tall), and when code and URL can't share the frame the code is whole at the top and the URL a page down. + A picked message that is a pixel image (MCOimg, `ui/pixelart.py`) opens its image on the + same bare frame instead, grown by a whole number to fill it (`ImageScreen`; the chip + reads `Image`, the hint `^U image`); with `chat_images` off, that is the only view. A chat message's links open there too, on every platform: ^U on the picked message, and with several, one code at a time that ←→ step through, clamped. That screen's URL line is flanked `←`/`→`, lit toward another code and dim at an end — the one mark the diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py index 91d10a9..94b07e6 100644 --- a/meshterm/core/preferences.py +++ b/meshterm/core/preferences.py @@ -599,6 +599,17 @@ PREFERENCES: tuple[PrefSpec, ...] = ( maximum=86400, unit="s", ), + PrefSpec( + key="chat_images", + label="Chat images", + help="Draw the pixel images of messages. Off: ^U shows one", + group="Display", + value_type="bool", + # On: a pixel image (MCOimg) is what its sender wanted the channel to see. Off: the + # chat shows only the line about the image, and ^U on the picked message opens it + # (JP, 2026-11-19). A 30 x 30 image takes 15 rows of the transcript. + default=True, + ), PrefSpec( key="clock_report_days", label="Clock report", diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index 4446527..03fa4b3 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -25,7 +25,7 @@ from rich.cells import cell_len from rich.console import Group, RenderableType from rich.text import Text -from ..core import links, mcoimg +from ..core import links, mcoimg, preferences from ..core.channels import MENTION, split_channel_sender from ..core.connection import ContactNotOnDeviceError from ..core.events import EventKind, MeshEvent @@ -247,10 +247,10 @@ class ChatScreen(Screen): else: toggle = ("", "") lane[1] = FPair( - "URL→QR", + "Image" if self._picked_picture() is not None else "URL→QR", "url_code", *toggle, - enabled=bool(self._picked_urls()), + enabled=self._picked_picture() is not None or bool(self._picked_urls()), opp_enabled=lock is not None, ) if self._locator is not None or self._pages is not None: @@ -393,6 +393,8 @@ class ChatScreen(Screen): self._render_cache: dict | None = None # The clock tolerance of the last render: which times show as corrected. self._tolerance_s = clock_tolerance_s() + # Whether the last render drew the pixel images (the ``chat_images`` preference). + self._show_images = True # Strong references to the sends, resends, and spinner tickers that a key handler # starts. The event loop holds only a *weak* reference. Thus the garbage collector # can remove a task that nothing else names while it runs: the result is a message @@ -442,7 +444,13 @@ class ChatScreen(Screen): def _hint_with(self, lock: str) -> str: """The key hint, with the ``lock`` atom after ``^O author`` (or no atom for ``""``).""" if self._selected is not None: - code = "^U QR" if self._picked_urls() else "" + code = ( + "^U image" + if self._picked_picture() is not None + else "^U QR" + if self._picked_urls() + else "" + ) where = "^L map" if self._locate_target() is not None else "" who = "^O author" if self._author_page() is not None else "" if self._is_channel and self._retry_target() is not None: @@ -676,8 +684,11 @@ class ChatScreen(Screen): locks = self._pages.locked_keys() if self._pages is not None else frozenset() tolerance = clock_tolerance_s() self._tolerance_s = tolerance + images = bool(preferences.current().chat_images) + self._show_images = images if ( cache is not None + and cache["images"] == images and cache["width"] == width and cache["spacing"] == spacing and cache["locks"] == locks @@ -788,6 +799,7 @@ class ChatScreen(Screen): "spacing": spacing, "locks": locks, "tolerance": tolerance, + "images": images, "ids": ids, "acked": ackeds, "selected": selecteds, @@ -950,7 +962,7 @@ class ChatScreen(Screen): ) indent = prefix.cell_len lines += render_hanging(Text(" " * indent), note, width, indent=indent) - if image is not None: + if image is not None and self._show_images: picture = pixelart.decoded(body) if picture is not None: indent = prefix.cell_len @@ -1343,6 +1355,44 @@ class ChatScreen(Screen): message = self._messages[max(0, min(self._selected, len(self._messages) - 1))] return links.urls(self._sender_and_body(message)[1]) + def _picked_picture(self) -> mcoimg.Picture | None: + """The pixel image of the selected message, or ``None`` (no selection, or no image).""" + if self._selected is None or not self._messages: + return None + message = self._messages[max(0, min(self._selected, len(self._messages) - 1))] + body = self._sender_and_body(message)[1] + return pixelart.decoded(body) if mcoimg.recognize(body) is not None else None + + def _open_image(self) -> bool: + """Show the pixel image of the selected message on a bare frame (^U). + + The image is as large as the frame permits (refer to + :class:`~meshterm.ui.pixelart.ImageScreen`). When the ``chat_images`` preference is + off, this is the way to see an image. When it is on, this is the large view. + + Returns: + ``True`` when the selected message has an image, so that ^U does nothing more. + """ + picture = self._picked_picture() + if picture is None: + return False + if self._codes_open: + return True + message = self._messages[max(0, min(self._selected or 0, len(self._messages) - 1))] + image = mcoimg.recognize(self._sender_and_body(message)[1]) + caption = pixel_image_text(image) if image is not None else Text("") + self._codes_open = True + + async def run() -> None: + try: + await self._session.run_screen(pixelart.ImageScreen(picture, caption)) + finally: + self._codes_open = False + self._session.invalidate() + + self._session.run_detached(run()) + return True + def _open_codes(self) -> None: """Show the links of the selected message as QR codes on the share screen (^U). @@ -1353,6 +1403,8 @@ class ChatScreen(Screen): message, and when nothing is selected, the screen cannot know which message. One share screen at a time. """ + if self._open_image(): + return urls = self._picked_urls() if not urls or self._codes_open: return diff --git a/meshterm/ui/pixelart.py b/meshterm/ui/pixelart.py index 62dcd67..2417e00 100644 --- a/meshterm/ui/pixelart.py +++ b/meshterm/ui/pixelart.py @@ -9,6 +9,11 @@ bottom pixel is ``▄`` in that colour, and a cell with no pixel is a space. An image that is wider than the lane, or taller than the rows that the platform can give it, becomes smaller (refer to :func:`fit`). Pixel art loses detail when it becomes smaller, but an image that is cut loses more: the user sees only a part of it. + +On the picked message, ^U opens the image on a bare frame (:class:`ImageScreen`). There it +becomes as large as the frame permits, by a whole number, so each pixel stays square. When +the ``chat_images`` preference is off, the chat shows only the line about the image, and +^U is the way to see it. """ from __future__ import annotations @@ -16,11 +21,13 @@ from __future__ import annotations from functools import lru_cache from typing import TYPE_CHECKING +from rich.console import Group from rich.style import Style from rich.text import Text from ..core import mcoimg from ..platforms import Platform, on_platform +from .tui.screen import ScrollScreen if TYPE_CHECKING: from ..core.mcoimg import Picture @@ -55,29 +62,46 @@ def decoded(body: str) -> Picture | None: return mcoimg.decode(body) -def fit(width: int, height: int, max_cols: int, max_rows: int) -> tuple[int, int]: +def fit( + width: int, height: int, max_cols: int, max_rows: int, *, grow: bool = False +) -> tuple[int, int]: """The size in pixels at which to draw an image of ``width`` × ``height``. - The image keeps its proportions. It never becomes larger, and it becomes smaller only - to fit ``max_cols`` cells and ``max_rows`` rows (two pixels in each row). + The image keeps its proportions, and becomes smaller only to fit ``max_cols`` cells and + ``max_rows`` rows (two pixels in each row). With ``grow``, an image that is smaller than + that space becomes larger by the largest whole number that fits. Thus each pixel of the + image is the same number of cells. """ - scale = min(1.0, max_cols / width, (max_rows * 2) / height) + scale = min(max_cols / width, (max_rows * 2) / height) + if scale >= 1: + scale = int(scale) if grow else 1 return max(1, int(width * scale)), max(1, int(height * scale)) -def picture_text(picture: Picture, max_cols: int, *, indent: int = 0) -> Text: +def picture_text( + picture: Picture, + max_cols: int, + *, + indent: int = 0, + max_rows: int | None = None, + grow: bool = False, +) -> Text: """Draw ``picture`` as lines of half blocks, each after ``indent`` spaces. Args: picture: The decoded image. max_cols: The most cells that the image can use, after the indent. indent: The cells of page before each line (the indent of the body of a message). + max_rows: The most rows that the image can use. ``None`` is the rows that the + platform gives an image under a message. + grow: Make a small image larger to fill the space (refer to :func:`fit`). Returns: One :class:`~rich.text.Text` with a line for each two rows of pixels. It has no newline after the last line. """ - cols, rows = fit(picture.width, picture.height, max(1, max_cols), _max_rows) + rows_cap = _max_rows if max_rows is None else max(1, max_rows) + cols, rows = fit(picture.width, picture.height, max(1, max_cols), rows_cap, grow=grow) pixel = _sampler(picture, cols, rows) text = Text(no_wrap=True) for y in range(0, rows, 2): @@ -122,3 +146,40 @@ def _hex(rgb: RGB | None) -> str: """The colour of a pixel as ``#rrggbb``.""" r, g, b = rgb # type: ignore[misc] return f"#{r:02x}{g:02x}{b:02x}" + + +class ImageScreen(ScrollScreen): + """The pixel image of a message on a bare frame, as large as the frame permits (^U). + + It is the share screen of a link (:class:`~meshterm.ui.qr.QrScreen`) for an image: no + header, no footer, no box, and no hint. Esc leaves, as it does everywhere. The image + fits itself to the frame at each paint, so a larger terminal shows a larger image. One + line under it gives its size and its colours, centred. + """ + + bare = True + + def __init__(self, picture: Picture, caption: Text) -> None: + """Set up the screen for ``picture``, with ``caption`` under it. + + Args: + picture: The decoded image. + caption: The line about the image, as the chat shows it. + """ + super().__init__(Text(""), title="Image", floating=False) + self.picture = picture + self._caption = caption + + def render_body(self, width: int) -> list[str]: + """The image as large as ``width`` and the frame rows permit, then its caption.""" + # The frame notes its height before it asks for the body, as on the share screen. + rows = self._scroll_viewport + picture = self.picture + art_rows = max(1, rows - 2) # a blank row and the caption + cols, _ = fit(picture.width, picture.height, width, art_rows, grow=True) + indent = max(0, (width - cols) // 2) + art = picture_text(picture, width, indent=indent, max_rows=art_rows, grow=True) + caption = self._caption.copy() + caption.justify = "center" + self.replace_content(Group(art, Text(""), caption)) + return super().render_body(width) diff --git a/tests/test_chat.py b/tests/test_chat.py index cb14ef8..aa84a0b 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -991,6 +991,41 @@ def test_a_pixel_image_shows_a_short_line_not_its_text() -> None: assert lines[1].strip() and set(lines[1].strip()) <= set("▀▄█") +def test_with_chat_images_off_the_image_is_behind_ctrl_u(monkeypatch) -> None: + """With ``chat_images`` off, only the line shows, and ^U on the picked image opens it.""" + from meshterm.core import preferences + from meshterm.ui.pixelart import ImageScreen + + prefs = preferences.Preferences() + prefs.set("chat_images", False) + monkeypatch.setattr(preferences, "current", lambda: prefs) + text = "im3:g/5WjAL`NA" + messages = [ChatMessage(text=text, peer="d4e5f6a7")] + session = _StubSession() + opened = [] + + async def run_screen(screen): # noqa: ANN001, ANN202 + opened.append(screen) + + session.run_screen = run_screen + screen = _screen(session, send=None, messages=messages) + screen._render_grouped(60) + lines = [_strip_ansi(ln) for ln in screen._body_lines(text, messages[0], 60)] + assert len(lines) == 1 and lines[0].endswith("image · 4×2 · 4 colours") + + screen._selected = 0 + assert screen.fkey_lane is not None + assert "^U image" in screen.footer_hint + + async def press() -> None: + screen.handle("url_code") + await asyncio.sleep(0) + + asyncio.run(press()) + assert len(opened) == 1 and isinstance(opened[0], ImageScreen) + assert (opened[0].picture.width, opened[0].picture.height) == (4, 2) + + def test_wrapped_body_hangs_under_the_first_line() -> None: """A body that is too long for the width wraps with a hanging indent under its first line.""" from datetime import datetime, timezone diff --git a/tests/test_mcoimg.py b/tests/test_mcoimg.py index 5450472..627524d 100644 --- a/tests/test_mcoimg.py +++ b/tests/test_mcoimg.py @@ -311,3 +311,12 @@ def test_a_wide_picture_becomes_smaller_to_fit_the_lane() -> None: assert fit(64, 64, 40, 40) == (40, 40) assert fit(16, 16, 40, 40) == (16, 16) # never larger assert fit(30, 30, 53, 5) == (10, 10) # five rows hold ten pixels + + +def test_the_image_screen_makes_a_small_image_larger() -> None: + """On its bare frame, a 4 x 2 image grows by a whole number to fill the frame.""" + from meshterm.ui.pixelart import fit + + assert fit(4, 2, 72, 22, grow=True) == (72, 36) # 18 times: the width is the limit + assert fit(16, 16, 53, 24, grow=True) == (48, 48) # 3 times: 24 rows hold 48 pixels + assert fit(4, 2, 72, 22) == (4, 2) # under a message, never larger