On the PicoCalc, a QR code too big for half blocks steps down to braille

Now that the PicoCalc's fonts draw braille as solid tiles, a braille
cell is a true 2x4 pixel grid, so it can hold a QR code at half the
module size. The fit ladder tries every half-block fit first (a lighter
error level and a narrower quiet zone cost a camera nothing on a
screen), then the same fits in braille. That puts the contact card on
the 53x26 panel whole: the standard code in 29 cells by 15 rows, with
its link under it, where half blocks had to send the link a page down.

Platform.solid_braille says where braille is solid; desktop fonts draw
it dotted, so the regular platform never offers it. Codes are cached
per (data, error level) since the share screen refits every paint.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-09-30 22:32:43 -04:00
1 parent 666fa891f3
commit edacbd0740
4 files changed
+160 -37

No files matched your search

+7 -3
View File
@@ -241,9 +241,13 @@ deliberately, one at a time, and say why in the code.
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
rows at the standard fit; the PicoCalc is 53 across and a regular terminal 24 tall).
Where the font draws braille solid (`Platform.solid_braille`, the PicoCalc's built
fonts) those fits are then tried again in **braille**, two modules a cell and four a
row (`qr._GRIDS`): half the module, the one step that costs a camera anything, so it
comes after the free ones — and it is what puts the contact card on the 53×26 panel
whole, standard fit and URL together. When code and URL still 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
+9
View File
@@ -87,6 +87,12 @@ class Platform:
and quantizes the two scales that would otherwise spend a gradient — the
per-node key hue (:func:`~meshterm.ui.theme.node_style`) and the heard-age heat
(:func:`~meshterm.ui.widgets._recency_style`). Wired in P3.
solid_braille: Whether the console font draws a braille cell's eight dots as solid
tiles with no gap between them or between neighbouring cells — the PicoCalc's
built fonts (``scripts/picocalc``) do — so braille is a true 2×4 pixel grid,
fine enough for what must stay contiguous. It is what lets a QR code step down
to braille when the half-block code does not fit (:mod:`~meshterm.ui.qr`). A
desktop font's braille is dotted, and a code drawn in it scans as nothing.
effects: Whether animated/decorative rendering runs at all — the braille spinner,
which drops to a ``LINE`` fallback. Cheaper on a console where a repaint is
dear. The header battery gauge is deliberately *not* behind it: its sweep is
@@ -128,6 +134,7 @@ class Platform:
emoji: bool
ascii_fold: bool
truecolor: bool
solid_braille: bool
effects: bool
tick_s: float
spinner_tick_s: float
@@ -149,6 +156,7 @@ REGULAR = Platform(
emoji=True,
ascii_fold=False,
truecolor=True,
solid_braille=False,
effects=True,
tick_s=1.0,
spinner_tick_s=0.12,
@@ -176,6 +184,7 @@ PICOCALC = Platform(
emoji=False,
ascii_fold=True,
truecolor=False,
solid_braille=True,
effects=False,
tick_s=2.0,
spinner_tick_s=0.5,
+109 -34
View File
@@ -3,7 +3,11 @@
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. Modules are always drawn **white on black**: the code's dark modules as white ink,
one. Where the console font's braille is solid (:attr:`~meshterm.platforms.Platform.
solid_braille`, the PicoCalc), a code too big for its frame in half blocks steps down to
**braille**, two modules across and four down in every cell: half the module, a quarter
of the area, and still every module touching its neighbours, which is what a camera
needs of it. 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
@@ -19,11 +23,15 @@ its prose.
from __future__ import annotations
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from functools import lru_cache
from typing import TYPE_CHECKING
from rich.console import Group
from rich.text import Text
from ..platforms import Platform, on_platform
from .tui.render import render_lines
from .tui.screen import ScrollScreen
@@ -60,8 +68,69 @@ _STYLE = "qr"
_FITS: tuple[tuple[str, int], ...] = (("m", 4), ("l", 4), ("m", 2), ("l", 2))
def _draw(code: segno.QRCode, border: int, *, indent: int = 0) -> Text:
"""Draw a segno code as half-block rows, ``border`` light modules around it.
#: Dot bit per (column, row) within a braille cell — the Unicode standard layout.
_BRAILLE_DOTS = ((0x01, 0x02, 0x04, 0x40), (0x08, 0x10, 0x20, 0x80))
def _braille(block: Sequence[Sequence[bool]]) -> str:
"""The braille cell lighting each dark module of a 4-row, 2-column ``block``."""
bits = 0
for y, row in enumerate(block):
for x, dark in enumerate(row):
if dark:
bits |= _BRAILLE_DOTS[x][y]
return chr(0x2800 + bits)
@dataclass(frozen=True, slots=True)
class _Grid:
"""How a code's modules pack into cells: ``across`` to a cell, ``down`` to a row.
Attributes:
across: Modules per cell, left to right.
down: Modules per cell row, top to bottom.
glyph: The cell for one ``down``-row by ``across``-column block of modules,
``True`` where the module is dark.
"""
across: int
down: int
glyph: Callable[[Sequence[Sequence[bool]]], str]
def cells(self, modules: int) -> tuple[int, int]:
"""Cells across and rows down a ``modules``-square code takes on this grid."""
return -(-modules // self.across), -(-modules // self.down)
#: One module a cell, two a row — the code every terminal can draw.
_HALF_BLOCK = _Grid(across=1, down=2, glyph=lambda block: _GLYPH[(block[0][0], block[1][0])])
#: Two modules a cell, four a row — half the module, so only where braille is solid.
_BRAILLE = _Grid(across=2, down=4, glyph=_braille)
#: The grids a fitted code may be drawn on, largest module first: a code tries every one
#: of :data:`_FITS` on a grid before it shrinks to the next. Bound per platform — the
#: braille grid is only offered where the font draws braille solid.
_GRIDS: tuple[_Grid, ...] = (_HALF_BLOCK,)
@on_platform
def _bind(platform: Platform) -> None:
"""Offer the braille grid where the console font tiles it (now and on switches)."""
global _GRIDS
_GRIDS = (_HALF_BLOCK, _BRAILLE) if platform.solid_braille else (_HALF_BLOCK,)
@lru_cache(maxsize=8)
def _make(data: str, error: str) -> segno.QRCode:
"""The code for ``data`` at ``error`` — cached, since a fitted code is asked every paint."""
import segno
return segno.make(data, error=error)
def _draw(code: segno.QRCode, border: int, grid: _Grid = _HALF_BLOCK, *, indent: int = 0) -> Text:
"""Draw a segno code on ``grid``, ``border`` light modules around it.
``indent`` is the one way a code is ever moved across a line: the same run of bare
cells in front of *every* row. A code must never be justified — Rich's centring
@@ -70,18 +139,24 @@ def _draw(code: segno.QRCode, border: int, *, indent: int = 0) -> Text:
row skewed is a code no camera can lock on to.
"""
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]))
cols, _ = grid.cells(len(rows))
# Pad the right and the bottom out to whole cells with light modules, so the last
# cell of every row and the last row of cells draw cleanly.
span = cols * grid.across
rows = [row + [False] * (span - len(row)) for row in rows]
rows += [[False] * span for _ in range(-len(rows) % grid.down)]
text = Text(no_wrap=True)
for i, (top, bottom) in enumerate(zip(rows[0::2], rows[1::2], strict=True)):
for i, top in enumerate(range(0, len(rows), grid.down)):
if i:
text.append("\n")
if indent:
text.append(" " * indent)
line = "".join(_GLYPH[(t, b)] for t, b in zip(top, bottom, strict=True))
band = rows[top : top + grid.down]
line = "".join(
grid.glyph([row[x : x + grid.across] for row in band])
for x in range(0, span, grid.across)
)
text.append(line, style=_STYLE)
return text
@@ -98,36 +173,34 @@ def qr_text(data: str, *, error: str = "m", border: int = _BORDER) -> Text:
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)
return _draw(_make(data, error), border)
def _fit(data: str, width: int, height: int | None) -> tuple[segno.QRCode, int] | None:
"""The first of :data:`_FITS` within ``width`` cells and ``height`` rows, as (code, border).
def _fit(data: str, width: int, height: int | None) -> tuple[segno.QRCode, int, _Grid] | None:
"""The first fit within ``width`` cells and ``height`` rows, as (code, border, grid).
``None`` when no fit is that small — the caller decides what to relax.
Every one of :data:`_FITS` on the largest grid, then on the next of :data:`_GRIDS`: on
a screen a lighter error level or a narrower quiet zone costs a camera nothing it
needs, and a module half the size is the one step that does. ``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 code, border
for grid in _GRIDS:
for error, border in _FITS:
code = _make(data, error)
cols, rows = grid.cells(code.symbol_size(border=border)[0])
if cols <= width and (height is None or rows <= height):
return code, border, grid
return None
def _smallest(data: str) -> tuple[segno.QRCode, int]:
"""The last of :data:`_FITS` — what a frame too small for any fit gets anyway."""
import segno
def _smallest(data: str) -> tuple[segno.QRCode, int, _Grid]:
"""The last of :data:`_FITS` on the last of :data:`_GRIDS` — for a frame too small for any."""
error, border = _FITS[-1]
return segno.make(data, error=error), border
return _make(data, error), border, _GRIDS[-1]
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.
"""The code for ``data`` at the first fit that fits the space given (see :func:`_fit`).
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.
@@ -138,10 +211,11 @@ def fit_qr(data: str, width: int, height: int | None = None) -> Text:
height: Rows available, or ``None`` to fit the width alone.
Returns:
The code, as :func:`qr_text` draws it.
The code, white on black, in half blocks or — where the platform's braille is
solid and half blocks do not fit — in braille.
"""
code, border = _fit(data, width, height) or _smallest(data)
return _draw(code, border)
code, border, grid = _fit(data, width, height) or _smallest(data)
return _draw(code, border, grid)
class QrScreen(ScrollScreen):
@@ -181,15 +255,16 @@ class QrScreen(ScrollScreen):
rows = self._scroll_viewport
link = Text(self.url, style="accent", justify="center")
link_rows = len(render_lines(link, width))
code, border = (
code, border, grid = (
_fit(self.url, width, rows - 1 - link_rows)
or _fit(self.url, width, rows)
or _fit(self.url, width, None)
or _smallest(self.url)
)
# Centred as a block — one indent for every row (see _draw), never justified.
indent = max(0, (width - code.symbol_size(border=border)[0]) // 2)
self.replace_content(Group(_draw(code, border, indent=indent), Text(""), link))
cols, _ = grid.cells(code.symbol_size(border=border)[0])
indent = max(0, (width - cols) // 2)
self.replace_content(Group(_draw(code, border, grid, indent=indent), Text(""), link))
return super().render_body(width)
+35
View File
@@ -275,6 +275,41 @@ def test_the_share_screen_refits_its_code_to_the_frame_every_paint() -> None:
assert len(code_rows(53, 26)) <= 26 # the PicoCalc: likewise
def test_where_braille_is_solid_a_code_too_big_for_half_blocks_steps_down_to_it() -> None:
"""On the PicoCalc a contact card keeps its standard fit, in braille, over its link.
In half blocks the card fits the 53x26 panel only by sending its link a page down;
braille's two-by-four cell holds the whole standard code in 29 cells by 15 rows. Every
module has to survive the packing, so the braille is decoded back and held against the
code's own matrix. A desktop font's braille is dotted, so the regular platform never
steps down to it.
"""
import segno
from meshterm.platforms import PICOCALC, set_platform
url = "meshcore://contact/add?name=YUL-Cartierville&public_key=" + "ab" * 32 + "&type=2"
assert not any("⠀" <= ch <= "⣿" for ch in fit_qr(url, 53, 22).plain)
set_platform(PICOCALC)
screen = QrScreen(url, title="Share YUL-Cartierville")
screen.note_viewport(26)
lines = [_ANSI.sub("", line) for line in screen.render_body(53)]
assert len(lines) <= 26 and url[:40] in "".join(lines), "code and link share the panel"
blank = next(i for i in range(len(lines) - 1, -1, -1) if not lines[i].strip())
cells = [line.lstrip(" ") for line in lines[:blank]]
assert (len(cells[0]), len(cells)) == (29, 15)
dots = ((0x01, 0x02, 0x04, 0x40), (0x08, 0x10, 0x20, 0x80))
decoded = [
[bool((ord(row[x // 2]) - 0x2800) & dots[x % 2][y % 4]) for x in range(57)]
for y in range(57)
for row in [cells[y // 4]]
]
matrix = [[bool(v) for v in row] for row in segno.make(url, error="m").matrix_iter(border=4)]
assert decoded == matrix, "a module was lost packing the code into braille"
# -- channel slot model -------------------------------------------------------