A QR code is white on black, and the whole screen when it is the answer

A camera reads contrast, and a light-on-dark code is what a scanner expects
of a screen, so every code MeshTerm draws is now pure white ink on a pure
black field (the theme's `qr` style, both ends named on both themes), never
black on white.

The share views — a channel's share link, a contact card, the CLI's share
commands run in the menu — are no longer a titled popup with an instruction
over the code. They are `QrScreen`, a **bare frame**: `Screen.bare` and
`frame.compose_bare` draw the body alone on blank rows, with no header, no
footer, no title bar, no box, no hint and no F-key lane, and nothing on it
but the code and the URL it encodes, sat a little above centre. Esc leaves.

The code fits itself to the frame every paint, width and rows both: the
standard fit first, then a lighter error level, then a narrower quiet zone,
before it would ever be cut — a contact card is 57 cells and 29 rows at the
standard fit, the PicoCalc is 53 across and a regular terminal 24 tall. When
code and URL can't share the frame the code is whole at the top and the URL
a page down. The frame states its height before it asks for the body, which
is what lets the screen size to it.

A `qr` fence in a written page is the one exception and keeps its place in
the prose — the About pages' codes flip to white on black like the rest.

Found on the way: the PicoCalc's SGR quantizer matched a colour only when it
was a whole sequence, and Rich writes a style's foreground and background as
one sequence (`ESC[38;2;…;48;2;…m`), so a white-on-black module reached the
console in truecolor. It now walks every sequence's parameter list.

The standard is written into CLAUDE.md under Screens and lists; the gallery
carries the share screen as a specimen on both platforms.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5.1 committed 2026-09-12 03:05:34 -04:00
1 parent 121f75c2a0
commit b56987b24b
16 files changed
+459 -119

No files matched your search

+16 -1
View File
@@ -172,6 +172,21 @@ deliberately, one at a time, and say why in the code.
the query in its footer hint draws the body line only where the footer isn't drawn
(`Platform.footer_fkeys`), never both: the query must be visible on every platform, and
twice on none.
- **A QR code is white on black, and when it is the answer it is the whole screen.**
Modules are pure white ink on a pure black field whatever theme the terminal runs
(`qr._STYLE`, both ends named) — a camera reads contrast, light-on-dark is what a
scanner expects of a screen — and never black on white. A share screen
(`qr.share_screen` → `qr.QrScreen`: the channel share, the contact card, the CLI's
share commands in the menu) is a **bare frame**: `Screen.bare` / `frame.compose_bare`
draw the body alone on blank rows — no header, no footer, no title bar, no box, no
hint, no F-key lane, no instruction — with nothing on it but the code and the URL it
encodes, sat a little above centre; Esc leaves, as everywhere. The code **fits itself
to the frame every paint**, width and rows both: a lighter error level, then a
narrower quiet zone, before it would ever be cut (a contact card is 57 cells and 29
rows at the standard fit; the PicoCalc is 53 across and a regular terminal 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. The one exception is a ` ```qr ` fence in a written page, where the code
is an illustration drawn in the prose where the fence is.
### Written pages
@@ -521,7 +536,7 @@ branch on the platform per frame, and never `from meshterm.platforms import PLAT
base style into every span, so a silent one changes colour inside a selected row. Same
trap outside the theme: `MapCanvas` drops emphasis entirely where bold is brightness,
since its colours arrive quantized and it can't know which bank they landed in, and the
fold's quantizer (`theme._nearest_slot_sgr`) states intent for it — a dim slot leaves as
fold's quantizer (`theme._nearest_slot_params`) states intent for it — a dim slot leaves as
`22;3N`, never a bare `3N`, because `9N` is *how* the console spells bright and adjacent
art spans (the wordmark's bevels, a raster's neighbouring cells) reset nothing between
them, so a bare one inherits the intensity bit and lands a bank too high mid-row.
+9 -10
View File
@@ -15,8 +15,6 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any
import typer
from rich.console import Group
from rich.text import Text
from ..context import AppContext
from ..core import exitcodes
@@ -109,7 +107,7 @@ class ChannelsTool(Tool):
else:
secret = normalize_secret(params["secret"]) if params.get("secret") else random_secret()
await write_channel(ctx, device, idx, name, secret)
self._show_qr(ctx, share_url(name, secret))
await self._show_qr(ctx, name, share_url(name, secret))
return ToolResult(
summary={"index": idx, "name": name},
report=(_written(idx, name, secret),),
@@ -163,7 +161,7 @@ class ChannelsTool(Tool):
report=(_written(idx, None, None, shown=False),),
exit_code=exitcodes.NO_RESULT,
)
self._show_qr(ctx, share_url(slot.name, slot.secret))
await self._show_qr(ctx, slot.name, share_url(slot.name, slot.secret))
return ToolResult(
summary={"index": idx, "shared": True},
report=(_written(idx, slot.name, slot.secret),),
@@ -195,18 +193,19 @@ class ChannelsTool(Tool):
)
@staticmethod
def _show_qr(ctx: AppContext, url: str) -> None:
async def _show_qr(ctx: AppContext, name: str, url: str) -> None:
"""Draw a channel's share link as a QR code — in the menu, and only there.
The QR is for a phone pointed at the screen. Piped into a file it is a block of
block characters wrapped around the one thing that is actually the answer, so a
scripted run states the link and nothing else.
The QR is for a phone pointed at the screen, and there it takes the whole screen
(:func:`~meshterm.ui.qr.share_screen`). Piped into a file it is a block of block
characters wrapped around the one thing that is actually the answer, so a scripted
run states the link and nothing else.
"""
from ..ui.qr import qr_text
from ..ui.qr import share_screen
from ..ui.surface import TuiUi
if isinstance(ctx.ui, TuiUi):
ctx.ui.show(Group(qr_text(url), Text(""), Text(url, style="accent")))
await share_screen(ctx, name=name, url=url)
def register_cli(self, app: typer.Typer) -> None:
"""Register the ``channels`` subcommand group.
+7 -9
View File
@@ -303,7 +303,7 @@ async def apply_ops(
"the device reported no public key — the advert cadence was not saved"
)
elif kind == "share":
report.append(_share_contact(ctx, snapshot))
report.append(await _share_contact(ctx, snapshot))
elif kind == "sync_clock":
import time as _time
from datetime import datetime
@@ -479,20 +479,18 @@ def _script_value(spec: SettingSpec, value: Any) -> str:
return str(value)
def _share_contact(ctx: AppContext, snapshot: dict) -> Facts:
"""State this node's contact card — with the QR code drawn in the menu.
async def _share_contact(ctx: AppContext, snapshot: dict) -> Facts:
"""State this node's contact card — with the QR code drawn in the menu, full-frame.
The QR is for a phone pointed at the screen. Redirected into a file it is a block of
The QR is for a phone pointed at the screen, and there it takes the whole screen
(:func:`~meshterm.ui.qr.share_screen`). Redirected into a file it is a block of
block characters around the one thing that is the answer, so a scripted run states the
link by itself. There is no machine face for the code either, and never will be: it is
a second rendering of ``url``.
"""
from rich.console import Group
from rich.text import Text
from ..ui import fields
from ..ui.config_editor import contact_share_url
from ..ui.qr import qr_text
from ..ui.qr import share_screen
from ..ui.report import BARE, Facts
from ..ui.surface import TuiUi
@@ -503,7 +501,7 @@ def _share_contact(ctx: AppContext, snapshot: dict) -> Facts:
adv_type = int(snapshot.get("adv_type") or 1)
url = contact_share_url(name, public_key, adv_type)
if isinstance(ctx.ui, TuiUi):
ctx.ui.show(Group(qr_text(url), Text(""), Text(url, style="accent")))
await share_screen(ctx, name=name, url=url)
return Facts(
key="share",
fields=(
+6 -8
View File
@@ -75,7 +75,7 @@ from .menus import (
run_steps,
section_heading,
)
from .qr import share_popup
from .qr import share_screen
from .theme import glyph
from .tui import CANCEL, Choice, SelectScreen, Separator
from .widgets import _age_seconds, _format_age, channel_glyph, format_ago
@@ -990,7 +990,7 @@ async def _create_private(
return 0
secret = random_secret()
await write_channel(ctx, device, idx, name.strip(), secret)
await _show_share(ctx, name.strip(), secret, intro="Share this channel:")
await _show_share(ctx, name.strip(), secret)
return 1
@@ -1032,7 +1032,7 @@ async def _add_public(
name = f"#{name}"
secret = derive_secret(name) # what the firmware will compute; kept for the QR/share
await write_channel(ctx, device, idx, name, None) # None => firmware derives the key from name
await _show_share(ctx, name, secret, intro="Share this channel:")
await _show_share(ctx, name, secret)
return 1
@@ -1209,11 +1209,9 @@ async def _reorder_channels(ctx: AppContext, device: Device, slots: list[Channel
# --- shared views ------------------------------------------------------------
async def _show_share(
ctx: AppContext, name: str, secret: bytes, *, intro: str = "Scan to add this channel:"
) -> None:
"""Show the channel's QR code and its share URL in a dismissable window."""
await share_popup(ctx, name=name, url=share_url(name, secret), intro=intro)
async def _show_share(ctx: AppContext, name: str, secret: bytes) -> None:
"""Show the channel's QR code and its share URL, full-frame (see ``share_screen``)."""
await share_screen(ctx, name=name, url=share_url(name, secret))
async def _show_key(ctx: AppContext, slot: ChannelSlot) -> None:
+4 -9
View File
@@ -1238,9 +1238,9 @@ def contact_share_url(name: str, public_key: str, node_type: int = 1) -> str:
async def show_contact_card(
ctx: AppContext, name: str, public_key: str, node_type: int = 1
) -> None:
"""Pop up a node's contact card: a scannable QR code over the raw share link.
"""Show a node's contact card: a scannable QR code over the raw share link, full-frame.
THE share-a-contact popup, used both for our own node (the advert menu's
THE share-a-contact screen, used both for our own node (the advert menu's
``Share QR / URI``) and for any full-keyed contact (the node detail page's
``Share contact``): a phone scans the code — or the link is passed along as text —
and the companion app adds the node as a contact.
@@ -1252,14 +1252,9 @@ async def show_contact_card(
node_type: The MeshCore advert type byte (1 companion, 2 repeater, 3 room,
4 sensor).
"""
from .qr import share_popup
from .qr import share_screen
await share_popup(
ctx,
name=name,
url=contact_share_url(name, public_key, node_type),
intro="Scan to add this node as a contact:",
)
await share_screen(ctx, name=name, url=contact_share_url(name, public_key, node_type))
async def _show_contact_card(ctx: AppContext, snapshot: dict) -> None:
+5 -3
View File
@@ -331,9 +331,11 @@ def _qr(data: str) -> RenderableType:
data: The fence's body — the URL to encode.
Returns:
The code, from :func:`~meshterm.ui.qr.qr_text` — the same black-on-white widget
the share popups draw, so a QR looks the same everywhere in MeshTerm and reads
the same whatever palette the terminal is running.
The code, from :func:`~meshterm.ui.qr.qr_text` — the same white-on-black widget
the share screen draws, so a QR looks the same everywhere in MeshTerm and reads
the same whatever palette the terminal is running. This is the one place a code
sits inside a page rather than taking the whole frame: it is an illustration in
the prose, drawn where the fence is.
"""
from .qr import qr_text
+156 -42
View File
@@ -2,9 +2,18 @@
Each character cell stacks two vertical modules — ``▀`` (upper only), ``▄`` (lower only),
``█`` (both), space (neither) — so a code renders at half the row height of a full-block
one and comfortably fits an interactive window. Modules are always drawn black on a white
background (with the mandatory quiet-zone border), so a phone camera reads the code no
matter what colour theme the terminal itself is using.
one. Modules are always drawn **white on black**: the code's dark modules as white ink,
its light modules and quiet zone as a black field, whatever colour theme the terminal is
running. A phone camera reads contrast, and pure white on pure black is the most of it a
screen has; a light-on-dark code is what every scanner made this decade expects to meet
on a screen.
When the code *is* the answer it is a **full-screen** thing: :func:`share_screen` puts it
on a bare frame — no header, no footer, no title, no box — with nothing beside it but the
URL it encodes, so the whole panel is contrast for the camera and the one line a reader
might type out instead. The one place a code sits *inside* a page is a ``qr`` fence in a
written page (:mod:`~meshterm.ui.markdown`), which draws :func:`qr_text` in the flow of
its prose.
"""
from __future__ import annotations
@@ -14,14 +23,20 @@ from typing import TYPE_CHECKING
from rich.console import Group
from rich.text import Text
from .tui.render import render_lines
from .tui.screen import ScrollScreen
if TYPE_CHECKING:
import segno
from ..context import AppContext
#: Quiet-zone width (modules) around the code. Scanners need at least 4 to lock on.
#: Quiet-zone width (modules) around the code. Scanners want 4 to lock on; 2 still reads
#: on a screen, and is what a code falls back to when its frame is too small for 4.
_BORDER = 4
#: Half-block glyph for each (top-module-dark, bottom-module-dark) pair. Drawn as black
#: ink, so a dark module is black and a light module shows the white cell background.
#: The glyph for each (top-module-dark, bottom-module-dark) pair, drawn as ink — so a
#: dark module is the ink colour and a light module shows the field behind it.
_GLYPH = {
(True, True): "█", # █ full block
(True, False): "▀", # ▀ upper half
@@ -29,57 +44,156 @@ _GLYPH = {
(False, False): " ",
}
#: Constant style for every glyph: black ink on a white field. Naming both ends means the
#: contrast holds regardless of the surrounding terminal palette.
_STYLE = "black on white"
#: Every glyph's style — the theme's ``qr``: pure white ink on a pure black field, both
#: ends named so the contrast holds regardless of the surrounding terminal palette. A
#: theme *name* rather than the hex itself so the PicoCalc's slots are chosen on purpose
#: (its bright white and its black), as every fixed hue in the app is. A console without
#: the theme draws the glyphs unstyled, which the plain CLI face would anyway.
_STYLE = "qr"
#: The fits a code tries, in order, until one is small enough for the frame drawing it:
#: the standard code first, then a lighter error level (a screen is never smudged, so the
#: redundancy buys nothing a camera needs), then the narrower quiet zone. A contact card
#: — a name, a 64-hex key — is 57 cells across and 29 rows tall at the standard fit; the
#: PicoCalc panel is 53 across, and a regular terminal is 24 rows.
_FITS: tuple[tuple[str, int], ...] = (("m", 4), ("l", 4), ("m", 2), ("l", 2))
def qr_text(data: str, *, error: str = "m") -> Text:
"""Render ``data`` as a QR code built from half-block characters.
Args:
data: The string to encode (e.g. a ``meshcore://channel/add`` share URL).
error: QR error-correction level — ``l``/``m``/``q``/``h`` (default ``m``).
Returns:
A Rich :class:`~rich.text.Text` (no-wrap) whose lines draw the code, ready to hand
to ``ctx.ui.view`` / ``ctx.ui.show``.
"""
import segno
qr = segno.make(data, error=error)
rows = [[bool(v) for v in row] for row in qr.matrix_iter(border=_BORDER)]
# Pair rows top-to-bottom; pad an odd final row with light (white) modules so the last
def _draw(code: segno.QRCode, border: int) -> Text:
"""Draw a segno code as half-block rows, ``border`` light modules around it."""
rows = [[bool(v) for v in row] for row in code.matrix_iter(border=border)]
# Pair rows top-to-bottom; pad an odd final row with light modules so the last
# half-block cell renders cleanly.
if len(rows) % 2:
rows.append([False] * len(rows[0]))
text = Text(no_wrap=True)
for top, bottom in zip(rows[0::2], rows[1::2], strict=True):
for i, (top, bottom) in enumerate(zip(rows[0::2], rows[1::2], strict=True)):
if i:
text.append("\n")
line = "".join(_GLYPH[(t, b)] for t, b in zip(top, bottom, strict=True))
text.append(line, style=_STYLE)
text.append("\n")
return text
async def share_popup(ctx: AppContext, *, name: str, url: str, intro: str) -> None:
"""THE share popup: a muted intro, the scannable code, then the URL to copy out.
def qr_text(data: str, *, error: str = "m", border: int = _BORDER) -> Text:
"""Render ``data`` as a QR code built from half-block characters.
One layout for every ``Share {name}`` surface — the channel share and the contact
card both come through here, so a change to how MeshTerm presents a share code (a
caption, a border, a "copied" affordance) lands on all of them at once.
Args:
data: The string to encode (e.g. a ``meshcore://channel/add`` share URL).
error: QR error-correction level — ``l``/``m``/``q``/``h`` (default ``m``).
border: Quiet-zone width in modules (default :data:`_BORDER`).
Returns:
A Rich :class:`~rich.text.Text` (no-wrap) whose lines draw the code, white on
black, ready to hand to ``ctx.ui.view`` / ``ctx.ui.show`` or to sit in a page.
"""
import segno
return _draw(segno.make(data, error=error), border)
def _fit(data: str, width: int, height: int | None) -> Text | None:
"""The code at the first of :data:`_FITS` within ``width`` cells and ``height`` rows.
``None`` when no fit is that small — the caller decides what to relax.
"""
import segno
for error, border in _FITS:
code = segno.make(data, error=error)
modules = code.symbol_size(border=border)[0]
if modules <= width and (height is None or (modules + 1) // 2 <= height):
return _draw(code, border)
return None
def fit_qr(data: str, width: int, height: int | None = None) -> Text:
"""The code for ``data`` at the first of :data:`_FITS` that fits the space given.
A code that fits at no fit is drawn at the smallest anyway: a cut code is not
scannable, but neither is no code, and a larger terminal is one resize away.
Args:
data: The string to encode.
width: Cells available across.
height: Rows available, or ``None`` to fit the width alone.
Returns:
The code, as :func:`qr_text` draws it.
"""
fitted = _fit(data, width, height)
if fitted is None:
error, border = _FITS[-1]
fitted = qr_text(data, error=error, border=border)
return fitted
class QrScreen(ScrollScreen):
"""THE share screen: a code on a bare frame, and under it the URL it encodes.
A **bare frame, not a popup** (:attr:`~meshterm.ui.tui.screen.Screen.bare`): no
header, no footer, no box, no title, no instruction — a camera pointed at the screen
wants the code and nothing arguing with it for contrast, and the reader wants the
one line they might type out instead. Esc leaves, as it does everywhere.
The code is **fitted to the frame every paint** (:func:`fit_qr`), which is why this is
a screen of its own rather than a renderable handed to a result window: only the
frame knows its rows, and a code that outgrows them is cut, and a cut code scans as
nothing. The fit is asked to hold the code *and* the URL first; failing that, the
code alone, with the URL a page down; failing that, the smallest code there is, and
the frame windows it from the top so a larger terminal shows it whole.
"""
bare = True
def __init__(self, url: str, *, title: str) -> None:
"""Set up the share screen for ``url``.
Args:
url: The ``meshcore://…`` share URL, encoded as the code and printed under it.
title: ``Share {name}`` — never drawn on the bare frame; the screen's name
for the log and the stack.
"""
super().__init__(Text(""), title=title, floating=False)
self.url = url
def render_body(self, width: int) -> list[str]:
"""The code fitted to ``width`` and the frame's rows, then a blank row, then the URL."""
# The frame notes its height before it asks for the body (compose_bare), so
# this is the whole terminal's rows; before any paint it is the default 1, and
# the smallest code stands in until the first paint corrects it.
rows = self._scroll_viewport
link = Text(self.url, style="accent", justify="center")
link_rows = len(render_lines(link, width))
code = (
_fit(self.url, width, rows - 1 - link_rows)
or _fit(self.url, width, rows)
or fit_qr(self.url, width)
)
code.justify = "center"
self.replace_content(Group(code, Text(""), link))
return super().render_body(width)
async def share_screen(ctx: AppContext, *, name: str, url: str) -> None:
"""Show the share screen for ``url``: the code, full-frame, and the URL under it.
One surface for every ``Share {name}`` — the channel share and the contact card both
come through here, so a change to how MeshTerm presents a share code lands on all of
them at once. In the menu it is :class:`QrScreen`; on the plain CLI face it prints
the same two things in order, there being no frame to fit.
Args:
ctx: Shared application context (provides the UI surface).
name: What is being shared — the popup's title reads ``Share {name}``.
name: What is being shared — the screen is titled ``Share {name}`` where a
title is stated at all.
url: The ``meshcore://…`` share URL, encoded as the QR code and printed under it.
intro: The one-line instruction above the code ("Scan to add this channel:").
"""
body = Group(
Text(intro, style="muted"),
Text(""),
qr_text(url),
Text(""),
Text(url, style="accent"),
)
await ctx.ui.view(body, title=f"Share {name}", footer_hint="Esc close")
from .surface import TuiUi
title = f"Share {name}"
if isinstance(ctx.ui, TuiUi):
await ctx.ui.session.run_screen(QrScreen(url, title=title))
return
await ctx.ui.view(Group(qr_text(url), Text(""), Text(url, style="accent")), title=title)
+49 -19
View File
@@ -76,6 +76,10 @@ MESH_THEME = Theme(
# A confirmed companion's name on the startup device picker: pure white so the
# devices we've actually talked to before jump out above the merely-detected ports.
"device.known": "bold #ffffff",
# A QR code's modules: pure white ink on a pure black field, both ends named so
# no palette can dilute the contrast a camera reads (see ui/qr.py). Never black
# on white — a light-on-dark code is what a scanner expects of a screen.
"qr": "#ffffff on #000000",
# The picker's Bluetooth TYPE badge: a white rune on the official Bluetooth blue
# (Pantone 300, #0057b8), echoing the real logo so BLE reads at a glance.
"bluetooth": "bold #ffffff on #0057b8",
@@ -299,6 +303,7 @@ MESH_THEME_16 = Theme(
"err.reverse": "reverse bold color(9)",
"you": "bold color(15)",
"device.known": "bold color(15)",
"qr": "bold color(15) on color(0)",
"bluetooth": "bold color(15) on color(4)",
"bluetooth.edge": "not bold color(4)",
"ok": "bold color(10)",
@@ -771,8 +776,11 @@ _FOLD_TABLE: dict[int, str] | None = None
#: console downsamples everything it renders itself, but the braille canvases
#: (``ui.mapcanvas``) emit their own truecolor escapes which pass through Rich verbatim
#: — the fold quantizes those to the 16 slots so the contract holds for every byte out.
_SGR_RGB = _re.compile(r"\x1b\[([34])8;2;(\d+);(\d+);(\d+)m")
_SGR_256 = _re.compile(r"\x1b\[([34])8;5;(\d+)m")
#: Any SGR sequence, its parameter list captured whole. The quantizer walks the list
#: rather than matching a colour standing alone: Rich writes a style's foreground and
#: background as *one* sequence (``ESC[38;2;255;255;255;48;2;0;0;0m`` — a QR module),
#: and a colour in the middle of such a list is no less a colour for having company.
_SGR = _re.compile(r"\x1b\[([\d;]*)m")
_SLOT_RGBS: tuple[tuple[int, int, int], ...] = tuple(
(int(h.lstrip("#")[0:2], 16), int(h.lstrip("#")[2:4], 16), int(h.lstrip("#")[4:6], 16))
@@ -784,8 +792,11 @@ _SLOT_RGBS: tuple[tuple[int, int, int], ...] = tuple(
_SLOT_CACHE: dict[tuple[bool, int, int, int], str] = {}
def _nearest_slot_sgr(background: bool, r: int, g: int, b: int) -> str:
"""The plain 16-colour SGR closest to ``(r, g, b)`` in the :data:`_VT_SLOTS` palette.
def _nearest_slot_params(background: bool, r: int, g: int, b: int) -> str:
"""The 16-colour SGR *parameters* closest to ``(r, g, b)`` in the :data:`_VT_SLOTS` palette.
``22;31``, ``91``, ``40`` — without the ``ESC[…m`` around them, so the answer can be
spliced into a sequence that carries other parameters too (:func:`_quantize_sgr`).
Foregrounds may land on any slot (30–37 / 90–97); backgrounds only on 0–7 (the VT has
no bright backgrounds), so a bright colour used as a fill picks its dim-bank cousin.
@@ -812,11 +823,11 @@ def _nearest_slot_sgr(background: bool, r: int, g: int, b: int) -> str:
),
)
if background:
sgr = f"\x1b[{40 + slot}m"
sgr = f"{40 + slot}"
elif slot < 8:
sgr = f"\x1b[22;{30 + slot}m"
sgr = f"22;{30 + slot}"
else:
sgr = f"\x1b[{90 + slot - 8}m"
sgr = f"{90 + slot - 8}"
cached = _SLOT_CACHE[key] = sgr
return cached
@@ -834,19 +845,38 @@ def _rgb_of_256(index: int) -> tuple[int, int, int]:
def _quantize_sgr(text: str) -> str:
"""Fold any embedded truecolor / 256-colour SGR down to the 16 palette slots."""
if "[38;2;" not in text and "[48;2;" not in text and "8;5;" not in text:
"""Fold any embedded truecolor / 256-colour SGR down to the 16 palette slots.
Every sequence's parameter list is walked (see :data:`_SGR`), so a colour folds
whether it stands alone or shares its sequence with a second colour or an attribute.
"""
if "8;2;" not in text and "8;5;" not in text:
return text
text = _SGR_RGB.sub(
lambda m: _nearest_slot_sgr(
m.group(1) == "4", int(m.group(2)), int(m.group(3)), int(m.group(4))
),
text,
)
return _SGR_256.sub(
lambda m: _nearest_slot_sgr(m.group(1) == "4", *_rgb_of_256(int(m.group(2)))),
text,
)
return _SGR.sub(_quantize_params, text)
def _quantize_params(match: _re.Match[str]) -> str:
"""One SGR sequence with each ``38/48;2;r;g;b`` and ``38/48;5;n`` in it folded to a slot."""
params = match.group(1).split(";")
out: list[str] = []
i = 0
while i < len(params):
head = params[i]
if head in ("38", "48") and i + 1 < len(params):
background = head == "48"
mode = params[i + 1]
rgb = params[i + 2 : i + 5]
if mode == "2" and len(rgb) == 3 and all(x.isdigit() for x in rgb):
out.append(_nearest_slot_params(background, *(int(x) for x in rgb)))
i += 5
continue
if mode == "5" and i + 2 < len(params) and params[i + 2].isdigit():
out.append(_nearest_slot_params(background, *_rgb_of_256(int(params[i + 2]))))
i += 3
continue
out.append(head)
i += 1
return f"\x1b[{';'.join(out)}m"
def _build_fold_table() -> dict[int, str]:
+32
View File
@@ -533,6 +533,38 @@ def compose_startup(screen: Screen, cols: int, rows: int) -> str:
return "\n".join(lines)
def compose_bare(screen: Screen, cols: int, rows: int) -> str:
"""Compose a bare frame: the screen's body on blank rows, and nothing else.
No header, no footer, no title bar, no box, no wordmark — the frame
:attr:`~meshterm.ui.tui.screen.Screen.bare` asks for. The body is drawn at the
terminal's full width (the screen lays its own rows out across it) and sits a little
above true centre when it is shorter than the frame, the optical placement everything
else here anchors to. A body taller than the frame is windowed from the top and
scrolls, so a code that does not fit is at least whole while the reader is at the top
of it, with the URL under it a page down.
Args:
screen: The bare base screen.
cols: Terminal width.
rows: Terminal height.
Returns:
An ANSI string of exactly ``rows`` lines, each within ``cols`` columns.
"""
# The height is known here and nowhere else, and a bare screen may size its body
# to it (the share screen fits its code to the rows), so it is noted *before* the
# body is asked for rather than after, the way the framed composers record it.
screen.note_viewport(rows)
body_lines = screen.render_body(cols)
while body_lines and not _ansi_width(body_lines[-1]):
body_lines.pop() # a trailing blank row would push the block off its anchor
visible, _more_above, _more_below = _visible_slice(screen, body_lines, rows)
top = max(0, (rows - len(body_lines)) * 2 // 5)
lines = [""] * top + visible[: rows - top]
return "\n".join(lines)
def _dialog_layout(screen: Screen, cols: int, rows: int) -> tuple[int, int, int, list[str]]:
"""Size a floating dialog: ``(outer_width, vpad, viewport, body_lines)``."""
# Most dialogs stretch to a generous cap; a screen may instead request a natural width
+7
View File
@@ -81,6 +81,12 @@ class Screen:
chrome: Whether, as the base screen, this layer is wrapped in the session's
persistent header/footer frame. A startup splash sets this ``False`` so the
session instead centers it under the :attr:`banner` with no status bars.
bare: Whether, as the base screen, this layer is the *whole frame*: its body on
blank rows with no header, no footer, no title bar, no box and no wordmark —
for a screen that is one thing a camera or a reader looks at (the share
screen's QR code, see :func:`~meshterm.ui.qr.share_screen`). Nothing is
advertised on it: Esc leaves, and Esc is on every keyboard. Read before
:attr:`chrome`; a bare screen is never floating.
banner: Block-glyph art (one string per row) drawn, centered, above a chromeless
base screen. Ignored while ``chrome`` is ``True``.
footnote: A short line drawn muted and centered *below* a chromeless base screen's
@@ -93,6 +99,7 @@ class Screen:
modal: bool = False
grow_only: bool = False
chrome: bool = True
bare: bool = False
banner: Sequence[str] | None = None
footnote: str | None = None
+3
View File
@@ -1824,6 +1824,9 @@ class TuiSession:
scrub = base.consume_edge_scrub()
if scrub:
self._scrub_right_columns(scrub)
# A bare base (the share screen's QR code) is its body on blank rows, nothing else.
if base.bare:
return self._emit(frame.compose_bare(base, cols, rows))
# A chromeless base (the startup splash) forgoes the header/footer bars and is
# centered under its banner instead of stretched across the terminal.
if not base.chrome:
+62 -5
View File
@@ -44,7 +44,7 @@ from meshterm.ui.channels import (
_next_free_slot,
read_channel_slots,
)
from meshterm.ui.qr import qr_text
from meshterm.ui.qr import QrScreen, fit_qr, qr_text
_ANSI = re.compile(r"\x1b\[[0-9;]*m")
@@ -203,11 +203,27 @@ def test_decrypt_channel_text_rejects_malformed_hex() -> None:
# -- QR rendering -------------------------------------------------------------
def test_qr_text_renders_square_with_quiet_zone() -> None:
"""qr_text produces block rows framed by a light quiet zone, wider than the data."""
console = Console(force_terminal=True, width=120, file=__import__("io").StringIO())
def test_qr_text_renders_white_on_black_with_a_quiet_zone() -> None:
"""qr_text draws white ink on a black field, whatever the terminal's own theme.
A camera reads contrast, and pure white on pure black is the most a screen has;
light-on-dark is what a scanner expects of a screen. Both ends are named so the
surrounding palette can't dilute either.
"""
from meshterm.ui.theme import MESH_THEME
console = Console(
force_terminal=True,
color_system="truecolor",
width=120,
file=__import__("io").StringIO(),
theme=MESH_THEME,
)
console.print(qr_text("meshcore://channel/add?name=Test&secret=" + "ab" * 16))
plain = _ANSI.sub("", console.file.getvalue()).rstrip("\n")
raw = console.file.getvalue()
assert "38;2;255;255;255" in raw, "the ink isn't pure white"
assert "48;2;0;0;0" in raw, "the field isn't pure black"
plain = _ANSI.sub("", raw).rstrip("\n")
lines = plain.splitlines()
assert lines, "QR produced no output"
# A version-appropriate QR for this URL is at least ~25 modules wide plus an 8-module
@@ -216,6 +232,47 @@ def test_qr_text_renders_square_with_quiet_zone() -> None:
assert any("█" in line for line in lines) # dark modules were drawn
def test_a_code_fits_itself_to_the_frame_it_is_drawn_in() -> None:
"""A contact card is 57 cells and 29 rows at the standard fit; frames are smaller.
Rather than be cut — a cut code scans as nothing — the code steps down: a lighter
error level first (a screen is never smudged), then the narrower quiet zone. The
PicoCalc panel is 53 across; a regular terminal is 24 rows.
"""
from rich.cells import cell_len
url = "meshcore://contact/add?name=YUL-Cartierville&public_key=" + "ab" * 32 + "&type=2"
standard = qr_text(url).plain.splitlines()
assert len(standard[0]) > 53 and len(standard) > 24 # the standard fit overflows both
for width in (80, 53, 45):
fitted = fit_qr(url, width).plain.splitlines()
assert max(cell_len(line) for line in fitted) <= width, width
assert len(fit_qr(url, 80, 24).plain.splitlines()) <= 24
def test_the_share_screen_refits_its_code_to_the_frame_every_paint() -> None:
"""The screen fits code *and* link first, the code alone next, and centres the rows."""
from rich.cells import cell_len
url = "meshcore://contact/add?name=YUL-Cartierville&public_key=" + "ab" * 32 + "&type=2"
screen = QrScreen(url, title="Share YUL-Cartierville")
assert screen.bare and not screen.floating
def code_rows(width: int, rows: int) -> list[str]:
screen.note_viewport(rows) # what compose_bare states before asking for the body
lines = [_ANSI.sub("", line) for line in screen.render_body(width)]
assert max(cell_len(line) for line in lines) <= width
assert url[:40] in "".join(lines), "the link is under the code"
blank = next(i for i in range(len(lines) - 1, -1, -1) if not lines[i].strip())
return lines[:blank] # the code is everything above the row that separates it
roomy = code_rows(120, 40)
assert len(roomy) == 29 # the standard fit, where there is room for it
assert roomy[0].startswith(" " * 30), "centred across the whole width"
assert len(code_rows(72, 24)) <= 24 # a regular terminal: the code whole, link below
assert len(code_rows(53, 26)) <= 26 # the PicoCalc: likewise
# -- channel slot model -------------------------------------------------------
+17 -13
View File
@@ -370,27 +370,31 @@ def test_contact_share_url_defaults_to_companion_type() -> None:
assert contact_share_url("n", "00" * 32).endswith("&type=1")
async def test_show_contact_card_pops_the_qr_over_the_link() -> None:
"""The contact card pops a QR code over its link, in one floating view.
async def test_show_contact_card_is_the_qr_over_the_link_on_a_bare_frame() -> None:
"""The contact card is a QR code over its link, and it takes the whole screen.
A scannable code above the raw ``meshcore://`` link, titled with the node's name.
A scannable code above the raw ``meshcore://`` link, on a bare frame — no header,
footer, title or box competes with the code for a camera's attention.
"""
from types import SimpleNamespace
from meshterm.ui.config_editor import show_contact_card
from meshterm.ui.qr import QrScreen
from meshterm.ui.surface import TuiUi
calls: list = []
pushed: list = []
class _Ui:
async def view(self, renderable: Any, **kwargs: Any) -> None:
calls.append((renderable, kwargs))
async def run_screen(screen: Any) -> None:
pushed.append(screen)
await show_contact_card(SimpleNamespace(ui=_Ui()), "Hub", "AB" * 32, node_type=2)
((renderable, kwargs),) = calls
assert kwargs["title"] == "Share Hub"
console = Console(width=200, record=True) # wide enough that the link never wraps
console.print(renderable)
out = console.export_text()
ui = TuiUi(SimpleNamespace(run_screen=run_screen))
await show_contact_card(SimpleNamespace(ui=ui), "Hub", "AB" * 32, node_type=2)
(screen,) = pushed
assert isinstance(screen, QrScreen)
assert screen.title == "Share Hub"
assert screen.bare and not screen.floating, "a QR code is full-screen, never a popup"
screen.note_viewport(60)
out = _plain(screen.render_body(200)) # wide: the link never wraps
assert f"meshcore://contact/add?name=Hub&public_key={'ab' * 32}&type=2" in out
assert "█" in out # the QR actually drew its modules
+9
View File
@@ -868,6 +868,14 @@ def _join_discord(cols: int, rows: int) -> Screen:
return AboutPage("Join Discord", join_discord())
def _share_qr(cols: int, rows: int) -> Screen:
"""The share screen: a contact card's code and link on a bare frame (the widest QR)."""
from meshterm.ui.qr import QrScreen
url = "meshcore://contact/add?name=Lakeside&public_key=" + "ab" * 32 + "&type=2"
return QrScreen(url, title="Share Lakeside")
_ENTRIES: list[_Entry] = [
_Entry("dashboard", _dashboard),
_Entry("contacts", _contacts),
@@ -902,6 +910,7 @@ _ENTRIES: list[_Entry] = [
_Entry("about_author", _about_author),
_Entry("join_discord", _join_discord),
_Entry("support_project", _support_project),
_Entry("share_qr", _share_qr),
]
#: (platform, cols, rows) combos every entry above renders under. PicoCalc gets both its
+31
View File
@@ -243,6 +243,37 @@ def test_fold_quantizes_embedded_truecolor_to_the_slots() -> None:
assert "38;5;" not in eight_bit
def test_fold_quantizes_a_colour_that_shares_its_sequence_with_another() -> None:
"""Rich writes a style's fg and bg as one sequence; each colour in it folds on its own.
The QR module's white-on-black is the case that found it: ``ESC[38;2;…;48;2;…m`` is
two colours in one list, and a matcher for a colour standing alone saw neither.
"""
set_platform(PICOCALC)
folded = fold_text("\x1b[38;2;255;255;255;48;2;0;0;0m█\x1b[0m")
assert "8;2;" not in folded, folded
assert folded.startswith("\x1b[97;40m"), folded # bright white ink, black field
with_attribute = fold_text("\x1b[1;38;5;201;48;2;94;234;212mX\x1b[0m")
assert "8;5;" not in with_attribute and "8;2;" not in with_attribute
assert with_attribute.startswith("\x1b[1;"), with_attribute # the bold survives, in place
def test_the_qr_style_is_white_on_black_on_both_themes() -> None:
"""A code is white ink on a black field on every platform — the PicoCalc's own slots."""
from rich.style import Style
regular = (
Style.parse(MESH_THEME.styles["qr"])
if isinstance(MESH_THEME.styles["qr"], str)
else MESH_THEME.styles["qr"]
)
assert regular.color and regular.color.triplet.hex == "#ffffff"
assert regular.bgcolor and regular.bgcolor.triplet.hex == "#000000"
console = MESH_THEME_16.styles["qr"]
assert console.color and console.color.number == 15
assert console.bgcolor and console.bgcolor.number == 0
def test_fold_drops_zero_width_machinery() -> None:
"""Variation selectors and zero-width joiners are dropped — they have no cell to occupy."""
set_platform(PICOCALC)
+46
View File
@@ -792,6 +792,36 @@ def test_compose_startup_is_chromeless_and_shows_banner() -> None:
assert all(len(line.rstrip()) < 80 for line in plain.split("\n"))
def test_compose_bare_is_the_body_alone_on_blank_rows() -> None:
"""A bare frame: no header, no footer, no title, no box — the body, sat a little high."""
body = Group(Text("CODE", justify="center"), Text("https://x", justify="center"))
screen = ScrollScreen(body, title="Share x", floating=False)
screen.bare = True
out = frame.compose_bare(screen, 53, 26)
rows = out.split("\n")
assert len(rows) == 26 # fills the terminal height exactly
plain = [Text.from_ansi(row).plain for row in rows]
assert not any("Share x" in row or "Esc" in row for row in plain) # no title, no hint
assert not any("─" in row or "│" in row or "╭" in row for row in plain) # no box
filled = [i for i, row in enumerate(plain) if row.strip()]
assert filled == [9, 10] # two body rows, anchored at 2/5 of the blank space
assert plain[9].rstrip() == " " * 24 + "CODE" # centred across the whole width
assert screen._scroll_viewport == 26 # the height, stated before the body was asked for
def test_compose_bare_windows_a_body_taller_than_the_frame_from_the_top() -> None:
"""Too tall to sit, the body scrolls: the top of it — the code — is whole first."""
body = Group(*(Text(f"row {i}") for i in range(40)))
screen = ScrollScreen(body, floating=False)
screen.bare = True
rows = Text.from_ansi(frame.compose_bare(screen, 53, 26)).plain.split("\n")
assert len(rows) == 26
assert rows[0].strip() == "row 0" and rows[25].strip() == "row 25"
screen.scroll_to_bottom()
rows = Text.from_ansi(frame.compose_bare(screen, 53, 26)).plain.split("\n")
assert rows[25].strip() == "row 39"
def test_startup_splash_gives_rows_back_in_order_when_short() -> None:
"""A short terminal sheds the blank line first, then the top of the mark — never the box.
@@ -2842,6 +2872,22 @@ def test_a_dialog_frame_is_composed_here_not_handed_to_prompt_toolkit() -> None:
assert "the list beneath" in _plain(body), "the backdrop must show around the box"
def test_a_bare_base_paints_no_chrome_at_all() -> None:
"""The session draws a bare base through compose_bare: no bars, no lane, no box."""
screen = ScrollScreen(Text("CODE", justify="center"), title="Share x", floating=False)
screen.bare = True
session = _framed_session()
session.push(screen)
text = session._plain_frame()
assert text is not None
rows = text.split("\n")
assert len(rows) == 26
plain = _plain(text)
assert "CODE" in plain
for chrome in ("MeshTerm", "Share x", "Esc", "F1", "─", "│"):
assert chrome not in plain, f"a bare frame drew {chrome!r}"
def test_the_busy_overlay_is_still_prompt_toolkits_to_place() -> None:
"""The one float we don't place: a content-sized window the float container measures."""
from meshterm.ui.tui.overlay import BusyOverlay