Merge branch 'main' into cardputer-zero
This commit is contained in:
commit
e31d24e12b
6 files changed
+161
-33
No files matched your search
@@ -241,10 +241,14 @@ 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
|
||||
is an illustration drawn in the prose where the fence is.
|
||||
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.
|
||||
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. Where the font draws braille solid
|
||||
(`Platform.solid_braille`, the PicoCalc's built fonts) every code — share screen and
|
||||
page fence alike — is drawn in **braille**, one module a dot, eight a cell
|
||||
(`qr._GRID`), so the contact card is 29 cells by 15 rows there and shares the 53×26
|
||||
panel with its URL at the standard fit.
|
||||
|
||||
### Written pages
|
||||
|
||||
|
||||
@@ -39,9 +39,9 @@ https://patreon.com/MeshTerm
|
||||
## Other ways to help
|
||||
|
||||
- Spread the word and let others know how awesome **MeshTerm** is!
|
||||
- Join the Discord community!
|
||||
- Join the **Discord** community!
|
||||
- Open an issue on **Discord** when you encounter a bug or problem!
|
||||
- Give this project a Star **⭐** on **GitHub**!
|
||||
- Open an issue on **GitHub** when you encounter a bug or problem!
|
||||
|
||||
*https://github.com/jpmartineau/MeshTerm*
|
||||
|
||||
|
||||
@@ -104,6 +104,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 every QR code be
|
||||
drawn in braille, one module a dot (: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
|
||||
@@ -151,6 +157,7 @@ class Platform:
|
||||
emoji: bool
|
||||
font: str
|
||||
truecolor: bool
|
||||
solid_braille: bool
|
||||
effects: bool
|
||||
tick_s: float
|
||||
spinner_tick_s: float
|
||||
@@ -179,6 +186,7 @@ REGULAR = Platform(
|
||||
emoji=True,
|
||||
font="",
|
||||
truecolor=True,
|
||||
solid_braille=False,
|
||||
effects=True,
|
||||
tick_s=1.0,
|
||||
spinner_tick_s=0.12,
|
||||
@@ -208,6 +216,7 @@ PICOCALC = Platform(
|
||||
emoji=False,
|
||||
font="picocalc",
|
||||
truecolor=False,
|
||||
solid_braille=True,
|
||||
effects=False,
|
||||
tick_s=2.0,
|
||||
spinner_tick_s=0.5,
|
||||
|
||||
+95
-24
@@ -1,9 +1,13 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Render a string as a scannable QR code in the terminal, using half-block characters.
|
||||
"""Render a string as a scannable QR code in the terminal, in half blocks or in braille.
|
||||
|
||||
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 draws braille solid (:attr:`~meshterm.platforms.Platform.
|
||||
solid_braille`, the PicoCalc), every code is drawn in **braille** instead: one module a
|
||||
dot, eight a cell, two across and four down — a quarter of the area, with every module
|
||||
still 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
|
||||
|
||||
@@ -55,13 +63,74 @@ _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.
|
||||
#: — a name, a 64-hex key — is 57 cells across and 29 rows tall at the standard fit in half
|
||||
#: blocks (29 by 15 in braille); a regular terminal is 24 rows.
|
||||
_FITS: tuple[tuple[str, int], ...] = (("m", 4), ("l", 4), ("m", 2), ("l", 2))
|
||||
|
||||
|
||||
#: 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])])
|
||||
|
||||
#: One module a dot: two a cell, four a row — only where the font draws braille solid.
|
||||
_BRAILLE = _Grid(across=2, down=4, glyph=_braille)
|
||||
|
||||
#: The grid every code on this platform is drawn on. Bound per platform: braille where the
|
||||
#: font tiles it, since a desktop font's braille is dotted and a code drawn in it scans as
|
||||
#: nothing.
|
||||
_GRID = _HALF_BLOCK
|
||||
|
||||
|
||||
@on_platform
|
||||
def _bind(platform: Platform) -> None:
|
||||
"""Draw codes in braille where the console font tiles it (now and on switches)."""
|
||||
global _GRID
|
||||
_GRID = _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, *, indent: int = 0) -> Text:
|
||||
"""Draw a segno code as half-block rows, ``border`` light modules around it.
|
||||
"""Draw a segno code on the platform's 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
|
||||
@@ -69,25 +138,32 @@ def _draw(code: segno.QRCode, border: int, *, indent: int = 0) -> Text:
|
||||
modules loses cells and lands a column off its neighbours, and a finder square one
|
||||
row skewed is a code no camera can lock on to.
|
||||
"""
|
||||
grid = _GRID
|
||||
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
|
||||
|
||||
|
||||
def qr_text(data: str, *, error: str = "m", border: int = _BORDER) -> Text:
|
||||
"""Render ``data`` as a QR code built from half-block characters.
|
||||
"""Render ``data`` as a QR code, in half blocks or — where braille is solid — braille.
|
||||
|
||||
Args:
|
||||
data: The string to encode (e.g. a ``meshcore://channel/add`` share URL).
|
||||
@@ -98,9 +174,7 @@ 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:
|
||||
@@ -108,22 +182,18 @@ def _fit(data: str, width: int, height: int | None) -> tuple[segno.QRCode, int]
|
||||
|
||||
``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):
|
||||
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
|
||||
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
|
||||
|
||||
error, border = _FITS[-1]
|
||||
return segno.make(data, error=error), border
|
||||
return _make(data, error), border
|
||||
|
||||
|
||||
def fit_qr(data: str, width: int, height: int | None = None) -> Text:
|
||||
@@ -188,7 +258,8 @@ class QrScreen(ScrollScreen):
|
||||
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)
|
||||
cols, _ = _GRID.cells(code.symbol_size(border=border)[0])
|
||||
indent = max(0, (width - cols) // 2)
|
||||
self.replace_content(Group(_draw(code, border, indent=indent), Text(""), link))
|
||||
return super().render_body(width)
|
||||
|
||||
|
||||
@@ -84,12 +84,16 @@ import struct
|
||||
PSF2_MAGIC = 0x864AB572
|
||||
|
||||
# --- braille: 2-wide dot grid; the codepoint's low byte says which dots lit ------------
|
||||
COLS = [[1, 2], [4, 5]]
|
||||
# MeshTerm never sets braille to be read: every braille cell it draws is pixels -- a chart,
|
||||
# the map, a meter. So each dot is a solid tile of its whole share of the cell, half the
|
||||
# width by a quarter of the height, with no gap between dots or between neighbouring
|
||||
# cells, and a run of lit dots reads as one continuous mark instead of a dotted one.
|
||||
COLS = [[0, 1, 2], [3, 4, 5]]
|
||||
BIT = {0: (0, 0), 1: (0, 1), 2: (0, 2), 6: (0, 3),
|
||||
3: (1, 0), 4: (1, 1), 5: (1, 2), 7: (1, 3)}
|
||||
|
||||
#: Dot-row bands per cell height: 3px pitch at 6x12, 2px at 6x8.
|
||||
BANDS12 = [[0, 1], [3, 4], [6, 7], [9, 10]]
|
||||
#: Dot-row bands per cell height: four 3px rows at 6x12, four 2px rows at 6x8.
|
||||
BANDS12 = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
|
||||
BANDS8 = [[0, 1], [2, 3], [4, 5], [6, 7]]
|
||||
|
||||
|
||||
|
||||
@@ -275,6 +275,46 @@ 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_every_code_is_drawn_in_it() -> None:
|
||||
"""On the PicoCalc a code is braille, one module a dot — eight to a cell.
|
||||
|
||||
So the contact card is 29 cells by 15 rows at the standard fit and shares the 53x26
|
||||
panel with its link, where half blocks sent the link a page down; and a page's code
|
||||
is braille too. 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 draws a code in it.
|
||||
"""
|
||||
import segno
|
||||
|
||||
from meshterm.platforms import PICOCALC, set_platform
|
||||
|
||||
def is_braille(text: str) -> bool:
|
||||
return any("⠀" <= ch <= "⣿" for ch in text)
|
||||
|
||||
url = "meshcore://contact/add?name=YUL-Cartierville&public_key=" + "ab" * 32 + "&type=2"
|
||||
channel = "meshcore://channel/add?name=Test&secret=" + "ab" * 16
|
||||
assert not is_braille(fit_qr(url, 53, 22).plain) and not is_braille(qr_text(channel).plain)
|
||||
|
||||
set_platform(PICOCALC)
|
||||
assert is_braille(qr_text(channel).plain) and "█" not in qr_text(channel).plain
|
||||
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 -------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user