diff --git a/scripts/README.md b/scripts/README.md index 9bdafd9..6f74314 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -5,6 +5,7 @@ These are tools for the repository. None of them is in the wheel. | Script | What it is for | |---|---| | `basemap-doctor.py` | Finds why a user's map has no basemap: certificates, DNS, proxy, or colour depth | +| `ladders/` | The tools with which JP chooses a visual value by eye: each draws the candidates side by side with MeshTerm's own renderer (the lightness of the node hues, the threshold of the chip seams). `README.md` there explains the method, and how Claude Code opens a ladder in a new window | | `cardputer-zero/` | `build-deb.sh` builds the Debian package for M5Stack's app store. Run it on the Cardputer Zero or on another arm64 Debian 13 system. `store/` holds the listing for the store (`app-builder.json`, which `czdev publish` reads), its icon, and its screenshots. `screenshot.py` saves the display of a Cardputer as a 320×170 PNG over SSH, as the store wants a screenshot. `store-publish.py` sends a package to the store with M5Stack's `czdev`, with two corrections. The release workflow runs it after each release. `launcher-entry.sh` puts a source checkout in the Cardputer Zero's app launcher. `remove` takes it out. `meshterm.png` is the package's icon: the website's logo, at the launcher's 100×100 size. `meshterm-dev.png` is its negative, for the checkout's entry, so that the two entries look different. `type-text.py` types a pasted string (an API key, a Wi-Fi password) on the Cardputer's keyboard from another computer, over SSH | | `screenshots.py` | Makes the screenshots of the website from the demo mesh (`--demo`): the main menu, the chat, the paths of a message, and the map, for the terminal, the Cardputer Zero, and the PicoCalc. They are the same at each run. The result goes to `docs/screenshots//`. It also draws the two wordmarks of the splash into `docs/screenshots/splash/`, which the website uses as its splash | | `video.py` | Makes the demo video of the website from the demo mesh: a tour of less than two minutes in the terminal, with its poster and its play card. The result goes to `src/` of the `meshterm.net` checkout beside this one | diff --git a/scripts/ladders/README.md b/scripts/ladders/README.md new file mode 100644 index 0000000..e4aab4b --- /dev/null +++ b/scripts/ladders/README.md @@ -0,0 +1,113 @@ +# Ladders + +A ladder is a small script that draws the candidates for a visual value side by side, in +the user's own terminal, with MeshTerm's own renderer. JP looks at the ladder and chooses +the value. Then the value goes into the code, with the date and a reference to the ladder. + +## Why we use ladders + +Some values of the visual language are a decision of the eye. Two examples: how far apart +two chip fills must be before the seam between them is solid, and how light the hue of a +node is. A calculation cannot choose such a value. The measures (the OKLab distance, the +APCA contrast) only put limits on it. Also, two terminals with different fonts and colour +settings show the same value differently. Thus the eye of the user, on the user's own +terminal, is the authority. + +A ladder makes this decision fast. One look at all the candidates replaces many rounds of +"change it to X and run the app again". + +## The method + +1. **Measure the problem first.** Find a number that shows the problem, for example the + contrast of each chip (`contrast.py`). The number tells you which values to put on the + ladder. Later, it goes into the comment of the constant and into the commit message. +2. **Draw with the real renderer.** A ladder imports `meshterm` from this checkout and + draws through the same functions as the app (`PathLine`, `node_style`, `_chip_fill`). + It never copies a colour or a rule. Thus the ladder shows what the app will show. +3. **Read the live constants.** Each ladder prints the value that the code has now, and + draws it as one of the rows. An argument moves the value, so that the user can compare + values without an edit. +4. **Draw each candidate in each form that the app draws.** A hue is a chip, a name in a + route, and a name on the page. A seam is solid or thin. Put the difficult cases on the + ladder: the weakest and the strongest hues, and the nearest neighbours. +5. **Put one line of numbers on each candidate.** The numbers do not decide. But they + show what the eye sees, and they let you write the reason in the code. +6. **Let the user choose, in rounds.** The first ladder is wide (for example, a lightness + from 0.70 to 0.85). The next ones are narrower, around the value that the user names. +7. **Write the decision where it is used.** The constant gets the value, the date, "JP on + a ladder", and the path of the ladder. Add the decision to the table below. + +## The ladders + +| Script | What it draws | Constant | Decisions | +|---|---|---|---| +| `hue_ladder.py` | The node wheel: the HSV wheel of before, the live spectrum, and candidate wheels at one OKLab lightness each, as chips and as names | `theme._NODE_LIGHTNESS` | 0.72 (JP, 2026-10-29) | +| `seam_ladder.py` | Pairs of chips sorted by the OKLab distance of their fills, each with a solid and a thin seam, and a line at the threshold | `pathline.SEAM_BLUR` | 0.06 (JP, 2026-09-16) | +| `contrast.py` | Not a ladder: a table of the contrast between the label and the fill of each node chip (OKLab, WCAG 2, APCA) | | | + +`ladderkit.py` holds the parts that all the ladders share: the console that keeps its +colour, and the two contrast measures. + +## Run a ladder + +In your own terminal, from the root of the repository: + +``` +python scripts/ladders/hue_ladder.py --L 0.70 0.75 +python scripts/ladders/seam_ladder.py --blur 0.08 +python scripts/ladders/contrast.py --hsv +``` + +Each script has `--help`. The terminal must have truecolor and a font with the powerline +glyphs, as for the chips of the app. + +## When Claude opens the window + +On Windows, Claude Code can open a ladder in a new Windows Terminal window for JP: + +``` +scripts\ladders\launch.ps1 hue_ladder --L 0.70 0.75 +scripts\ladders\launch.ps1 -Snap seam_ladder +``` + +`launch.ps1` opens the window and waits until the ladder writes its marker file. Then it +prints what the ladder found: the colour system, virtual terminal processing, and if +stdout is the console. With `-Snap`, it also takes a screenshot of the window +(`snap.ps1`). Claude examines that picture before it tells JP that the ladder is ready. In +the new window, `ladder ` runs the same ladder again with other values. The +path of the checkout must have no spaces (refer to trap 1). + +Three traps made the first launches fail. Two sessions met all three on the same night +(2026-10-28 and 2026-10-29), and the second session did not know that the first had solved +them. This folder keeps the solution in one place. The launcher stops each trap: + +1. **Windows Terminal gives the command line as one name.** When `wt.exe` sends a new tab + to a window that is already open, it puts quotes around the whole command line. Then + Windows looks for one file whose name is the whole line, and the tab shows the error + 0x80070002 ("The system cannot find the file specified"). Thus the tab runs `run.cmd`, + whose path has no spaces, with no arguments. The name of the ladder and its arguments + go in environment variables (`LADDER_NAME`, `LADDER_ARGS`), because the tab gets the + environment of the process that runs `wt.exe`. +2. **The new tab gets the environment of Claude Code.** Claude Code runs its commands with + `NO_COLOR=1`, and Rich removes all colour when it sees that variable. The tab got it + too, so the first ladder was black and white. `run.cmd` and `run.ps1` remove it, and + the console of the ladder sets `no_color=False`. +3. **Rich uses the console API of Windows.** On Windows, Rich examines the console mode + of stdout. When virtual terminal processing is off, Rich does not write ANSI codes. It + uses the console API of Windows, which has 16 colours, and which writes no colour at + all into a capture. `ladderkit.console` turns the processing on and sets + `legacy_windows=False`. Also, `run.ps1` starts Python with `Start-Process + -NoNewWindow`, so that Python writes to the console itself and not to a PowerShell pipe. + +The most important lesson is not a trap: **do not tell the user that a window is ready +before you check it.** A launch that fails prints nothing in the shell that started it, and +a ladder with no colour runs with no error. Only the marker file and the screenshot show +the result. On 2026-10-29, Claude told JP two times that the ladder was ready, and each +time it was not. + +## Keep them working + +The ladders use private names of the package (`_chip_fill`, `_spectrum_colours`, +`_NODE_HUE_SAT`). When the code changes, a ladder can break, and the tests do not run the +ladders. Correct a ladder when you use it again, and keep it in this folder. A new ladder +also goes here, with a row in the table above. diff --git a/scripts/ladders/contrast.py b/scripts/ladders/contrast.py new file mode 100644 index 0000000..d4cb37e --- /dev/null +++ b/scripts/ladders/contrast.py @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The contrast between the label and the fill of each node chip, as a table. + + python scripts/ladders/contrast.py # each 16th byte of the live spectrum + python scripts/ladders/contrast.py --step 1 # all 256 bytes + python scripts/ladders/contrast.py --hsv # the HSV wheel of before 2026-10-29 + +This script is not a ladder. It is the measurement that comes before one: it shows the +problem as numbers. Three measures are in the table: the OKLab difference in lightness, the +WCAG 2 ratio, and the APCA ``Lc`` (refer to ``ladderkit.apca``). On the HSV wheel, the APCA +contrast went from 19 (blue) to 64 (yellow). This number started the hue ladder. +""" + +from __future__ import annotations + +import argparse + +from hue_ladder import hsv_hex +from ladderkit import apca, console, wcag +from rich.text import Text + +from meshterm.ui import oklab, theme +from meshterm.ui.pathline import _chip_fill + + +def main() -> None: + """Print the table and the range of each measure.""" + parser = argparse.ArgumentParser(description="Label-on-fill contrast of the node chips.") + parser.add_argument("--step", type=int, default=16, help="show each Nth byte") + parser.add_argument("--hsv", action="store_true", help="measure the HSV wheel of before") + args = parser.parse_args() + con = console(width=120) + colour_of = hsv_hex if args.hsv else (lambda byte: theme._NODE_SPECTRUM[byte]) + + rows = [] + for byte in range(256): + label = colour_of(byte) + fill = _chip_fill(label) + lab_l, fill_l = oklab.from_hex(label)[0], oklab.from_hex(fill)[0] + rows.append((byte, label, fill, lab_l, fill_l, wcag(label, fill), apca(label, fill))) + + header = "byte chip label fill L label/fill ΔL WCAG APCA" + con.print(Text(header, style="bold")) + for byte, label, fill, lab_l, fill_l, ratio, lc in rows[:: args.step]: + line = Text(f" {byte:02x} ") + line.append(f" {byte:02x} ", style=f"bold {label} on {fill}") + line.append( + f" {label} {fill} {lab_l:.2f} / {fill_l:.2f} {lab_l - fill_l:.2f}" + f" {ratio:4.2f} {lc:5.1f}" + ) + con.print(line) + for name, index in (("L label", 3), ("WCAG", 5), ("APCA", 6)): + low, high = min(rows, key=lambda r: r[index]), max(rows, key=lambda r: r[index]) + con.print( + Text( + f"{name:8} min {low[index]:6.2f} (byte {low[0]:02x})" + f" max {high[index]:6.2f} (byte {high[0]:02x})", + style="#a2a2a2", + ) + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/ladders/hue_ladder.py b/scripts/ladders/hue_ladder.py new file mode 100644 index 0000000..8b64473 --- /dev/null +++ b/scripts/ladders/hue_ladder.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Hue ladder: the node wheel at several OKLab lightnesses, as chips and as names. + + python scripts/ladders/hue_ladder.py # L 0.70 0.75 0.80 0.85 + python scripts/ladders/hue_ladder.py --L 0.70 0.72 0.74 # a narrower round + python scripts/ladders/hue_ladder.py --chroma max # the most chroma at that L + python scripts/ladders/hue_ladder.py --chroma 0.12 # one chroma for each hue + +The first block is the HSV wheel that the spectrum used before 2026-10-29. The second is the +live spectrum (``theme._NODE_SPECTRUM``). The other blocks are candidates: each byte keeps +the hue angle of the HSV wheel, at one lightness for all hues. With ``--chroma keep`` (the +default), each byte also keeps its HSV chroma, and ``oklab.fitted`` lowers it where the +gamut cannot hold it. + +The real ``PathLine`` draws each chip and each name. Thus the fills +(``CHIP_LIGHTNESS``), the seams (``SEAM_BLUR`` and the thin seam), and the labels follow +the live rules. A line of numbers is on each block: the lightness of the labels, the +difference in lightness between label and fill, the APCA contrast of the chips, and the +smallest distance between two names 16 bytes apart (how well the wheel keeps nodes apart). + +JP chose ``_NODE_LIGHTNESS`` 0.72 on this ladder (2026-10-29). +""" + +from __future__ import annotations + +import argparse +import colorsys +import math +from collections.abc import Callable + +from ladderkit import apca, console +from rich.console import Console +from rich.text import Text + +from meshterm.ui import oklab, theme +from meshterm.ui.pathline import CHIP_LIGHTNESS, SEAM_BLUR, PathHop, PathLine, _chip_fill + +Wheel = Callable[[int], str] + + +def hsv_hex(byte: int) -> str: + """The colour of a byte on the HSV wheel that the spectrum used before 2026-10-29.""" + r, g, b = colorsys.hsv_to_rgb(byte / 256, theme._NODE_HUE_SAT, theme._NODE_HUE_VAL) + return f"#{round(r * 255):02x}{round(g * 255):02x}{round(b * 255):02x}" + + +def oklch_hex(byte: int, lightness: float, chroma: str) -> str: + """The HSV hue angle of a byte at one lightness, with the chroma that ``--chroma`` names.""" + _, a, b = oklab.from_hex(hsv_hex(byte)) + angle, own = math.atan2(b, a), math.hypot(a, b) + c = 0.5 if chroma == "max" else own if chroma == "keep" else float(chroma) + return oklab.to_hex(oklab.fitted((lightness, c * math.cos(angle), c * math.sin(angle)))) + + +def live_hex(byte: int) -> str: + """The colour of a byte on the live spectrum.""" + return theme._NODE_SPECTRUM[byte] + + +def stats(colour_of: Wheel) -> str: + """The line of numbers for one wheel.""" + labels = [colour_of(byte) for byte in range(256)] + fills = [_chip_fill(label) for label in labels] + ls = [oklab.from_hex(label)[0] for label in labels] + dl = [oklab.from_hex(lb)[0] - oklab.from_hex(f)[0] for lb, f in zip(labels, fills, strict=True)] + lc = [apca(lb, f) for lb, f in zip(labels, fills, strict=True)] + step = [oklab.distance(labels[i], labels[(i + 16) % 256]) for i in range(256)] + return ( + f"label L {min(ls):.2f}–{max(ls):.2f} · ΔL {min(dl):.2f}–{max(dl):.2f}" + f" · APCA {min(lc):.0f}–{max(lc):.0f} · 16-step name distance min {min(step):.3f}" + ) + + +def hops(colour_of: Wheel, bytes_: list[int]) -> list[PathHop]: + """The hops of a line: each byte as its own label, in the colour of the wheel.""" + return [PathHop(f"{b:02x}", style=f"bold {colour_of(b)}") for b in bytes_] + + +WHEEL = list(range(0, 256, 16)) +RUNS = { + "greens": list(range(0x40, 0x60, 4)), # near hues blur here + "blues ": list(range(0x98, 0xB8, 4)), # the weakest contrast on the HSV wheel + "yellow": list(range(0x18, 0x38, 4)), # the strongest contrast on the HSV wheel +} + + +def block(con: Console, title: str, colour_of: Wheel) -> None: + """One wheel: the whole wheel as chips, three runs of near hues, and the names.""" + con.print(Text(f"── {title} ──", style="bold"), Text(stats(colour_of), style="#a2a2a2")) + wheel = PathLine(hops(colour_of, WHEEL), mode="powerline").text() + con.print(Text(" wheel ").append_text(wheel)) + for name, run in RUNS.items(): + chips = PathLine(hops(colour_of, run), mode="powerline").text() + names = PathLine(hops(colour_of, run), mode="plain").text() + con.print(Text(f" {name} ").append_text(chips).append(" ").append_text(names)) + names = PathLine(hops(colour_of, WHEEL), mode="plain").text() + con.print(Text(" names ").append_text(names)) + con.print() + + +def main() -> None: + """Draw the HSV wheel, the live spectrum, and one wheel for each ``--L``.""" + parser = argparse.ArgumentParser(description="The node wheel at several OKLab lightnesses.") + parser.add_argument("--L", type=float, nargs="+", default=[0.70, 0.75, 0.80, 0.85]) + parser.add_argument("--chroma", default="keep", help="keep | max | a number such as 0.12") + args = parser.parse_args() + con = console() + con.print( + Text( + f"CHIP_LIGHTNESS {CHIP_LIGHTNESS} · SEAM_BLUR {SEAM_BLUR} · chroma {args.chroma}" + " · chips are byte labels on the live fill rule", + style="#a2a2a2", + ) + ) + con.print() + block(con, "HSV S 0.65 V 0.95 (before 2026-10-29)", hsv_hex) + block(con, f"live: theme spectrum, L {theme._NODE_LIGHTNESS:.2f}", live_hex) + for lightness in args.L: + block( + con, + f"OKLCH L {lightness:.2f}", + lambda b, lightness=lightness: oklch_hex(b, lightness, args.chroma), + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/ladders/ladderkit.py b/scripts/ladders/ladderkit.py new file mode 100644 index 0000000..b57463d --- /dev/null +++ b/scripts/ladders/ladderkit.py @@ -0,0 +1,110 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The shared parts of the ladders: a console that keeps its colour, and two contrast measures. + +A ladder draws real colours in the user's own terminal. On Windows, three things can remove +that colour, and :func:`console` stops each of them (refer to ``README.md``, "When Claude +opens the window"). +""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +#: The root of the repository. A ladder imports ``meshterm`` from this checkout, and not +#: from an installed package, so that it always reads the live constants. +REPO = Path(__file__).resolve().parents[2] +if str(REPO) not in sys.path: + sys.path.insert(0, str(REPO)) + +from rich.console import Console # noqa: E402 + + +def _enable_vt() -> str: + """Turn on virtual terminal processing for stdout, so that the console reads ANSI codes.""" + if os.name != "nt": + return "n/a" + import ctypes + + kernel32 = ctypes.windll.kernel32 + handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE + mode = ctypes.c_uint32() + if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)): + return "not a console" + ok = kernel32.SetConsoleMode(handle, mode.value | 0x0004) # VIRTUAL_TERMINAL_PROCESSING + return f"mode {mode.value:#x} -> {'on' if ok else 'FAILED'}" + + +def console(width: int = 220) -> Console: + """A Rich console that always writes truecolor ANSI codes. + + * ``no_color=False``: a Windows Terminal tab that Claude Code opens gets the environment + of Claude Code, which has ``NO_COLOR=1``. Rich removes all colour when it sees it. + * ``legacy_windows=False``, and virtual terminal processing on: when the processing is + off, Rich uses the console API of Windows. That API has 16 colours, and in a capture + it writes no colour at all. + + If the environment variable ``LADDER_MARKER`` names a file, the function writes what it + found to that file. ``launch.ps1`` reads the file to make sure that the ladder started, + with colour. + """ + sys.stdout.reconfigure(encoding="utf-8") # the powerline glyphs + vt = _enable_vt() + con = Console( + force_terminal=True, + color_system="truecolor", + no_color=False, + legacy_windows=False, + width=width, + highlight=False, + ) + marker = os.environ.get("LADDER_MARKER") + if marker: + Path(marker).write_text( + f"color_system={con.color_system} no_color={con.no_color}" + f" legacy_windows={con.legacy_windows} vt={vt} isatty={sys.stdout.isatty()}\n", + encoding="utf-8", + ) + return con + + +def _channels(colour: str) -> tuple[float, float, float]: + """The three channels of a ``#rrggbb`` colour, from 0 to 1.""" + return int(colour[1:3], 16) / 255, int(colour[3:5], 16) / 255, int(colour[5:7], 16) / 255 + + +def wcag(text: str, ground: str) -> float: + """The WCAG 2 contrast ratio of two ``#rrggbb`` colours (1 to 21).""" + + def luminance(colour: str) -> float: + def linear(c: float) -> float: + return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 + + r, g, b = (linear(c) for c in _channels(colour)) + return 0.2126 * r + 0.7152 * g + 0.0722 * b + + lighter, darker = sorted((luminance(text), luminance(ground)), reverse=True) + return (lighter + 0.05) / (darker + 0.05) + + +def apca(text: str, ground: str) -> float: + """The APCA contrast ``Lc`` of text on a ground (0.0.98G-4g), as a positive number. + + APCA is the contrast model of the WCAG 3 draft. Unlike the WCAG 2 ratio, it knows the + polarity (light text on a dark ground is not the same as dark text on a light ground), + and it is closer to what the eye sees for text. ``Lc`` 45 is a common minimum for body + text, and ``Lc`` 30 for large text. + """ + + def screen_luminance(colour: str) -> float: + r, g, b = _channels(colour) + y = 0.2126729 * r**2.4 + 0.7151522 * g**2.4 + 0.0721750 * b**2.4 + return y + (0.022 - y) ** 1.414 if y < 0.022 else y + + yt, yg = screen_luminance(text), screen_luminance(ground) + if yg > yt: # dark text on a light ground + s = (yg**0.56 - yt**0.57) * 1.14 + return 0.0 if s < 0.1 else (s - 0.027) * 100 + s = (yg**0.65 - yt**0.62) * 1.14 # light text on a dark ground + return 0.0 if s > -0.1 else -(s + 0.027) * 100 diff --git a/scripts/ladders/launch.ps1 b/scripts/ladders/launch.ps1 new file mode 100644 index 0000000..d8e08d3 --- /dev/null +++ b/scripts/ladders/launch.ps1 @@ -0,0 +1,44 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# Open a ladder in a new Windows Terminal window, in colour, and make sure that it started. +# +# scripts\ladders\launch.ps1 hue_ladder --L 0.70 0.75 +# scripts\ladders\launch.ps1 -Snap seam_ladder --blur 0.08 +# +# The first argument is the name of the ladder (a script in this folder, without ".py"). +# The other arguments go to the ladder. With -Snap, the script also takes a screenshot of +# the window and prints the path of the PNG. Refer to README.md for the three traps that +# this script avoids. +# +# The script has no param block on purpose. A param block lets PowerShell read "--L" as a +# parameter of this script. Without one, each argument arrives in $args as it was typed. + +$snap = $args -contains '-Snap' +$rest = @($args | Where-Object { $_ -ne '-Snap' } | ForEach-Object { "$_" }) +if ($rest.Count -lt 1) { Write-Error 'usage: launch.ps1 [-Snap] [arguments]'; exit 2 } +$name = $rest[0] -replace '\.py$', '' +if (-not (Test-Path (Join-Path $PSScriptRoot "$name.py"))) { Write-Error "no ladder $name.py"; exit 2 } + +# The tab cannot take arguments on its command line (trap 1). It gets its environment from +# this process, so the ladder and its arguments go in environment variables. +$marker = Join-Path $env:TEMP "meshterm-ladder-$name.txt" +if (Test-Path $marker) { Remove-Item $marker -Confirm:$false } +$env:LADDER_NAME = $name +$env:LADDER_ARGS = ($rest | Select-Object -Skip 1) -join ' ' +$env:LADDER_MARKER = $marker +Start-Process -FilePath wt.exe -ArgumentList @('-w', 'new', '--size', '190,52', (Join-Path $PSScriptRoot 'run.cmd')) + +# A launch that fails prints nothing here. Only the marker of the ladder shows that it ran. +$started = $false +foreach ($i in 1..40) { + if (Test-Path $marker) { $started = $true; break } + Start-Sleep -Milliseconds 500 +} +if (-not $started) { Write-Error "the ladder did not start in 20 s (no $marker)"; exit 1 } +"started: $(Get-Content $marker)" + +if ($snap) { + Start-Sleep -Seconds 2 # let the ladder finish its output + $png = Join-Path $env:TEMP "meshterm-ladder-$name.png" + & (Join-Path $PSScriptRoot 'snap.ps1') -Title "Ladder $name" -Out $png +} diff --git a/scripts/ladders/run.cmd b/scripts/ladders/run.cmd new file mode 100644 index 0000000..8c0458d --- /dev/null +++ b/scripts/ladders/run.cmd @@ -0,0 +1,8 @@ +@echo off +rem SPDX-License-Identifier: Apache-2.0 +rem +rem The new Windows Terminal tab runs this file, with no arguments (refer to README.md, +rem trap 1). launch.ps1 puts the ladder and its arguments in the environment. +rem Claude Code runs its commands with NO_COLOR=1, and the tab gets it too (trap 2). +set NO_COLOR= +powershell.exe -NoExit -ExecutionPolicy Bypass -NoLogo -File "%~dp0run.ps1" diff --git a/scripts/ladders/run.ps1 b/scripts/ladders/run.ps1 new file mode 100644 index 0000000..3b0a411 --- /dev/null +++ b/scripts/ladders/run.ps1 @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# Runs in the new tab that launch.ps1 opens. It runs the ladder one time, and then it gives +# the command "ladder " to run the same ladder again with other values. + +Remove-Item Env:NO_COLOR -ErrorAction SilentlyContinue +$Host.UI.RawUI.WindowTitle = "Ladder $env:LADDER_NAME" # snap.ps1 finds the window by it + +$global:LadderPython = Join-Path $PSScriptRoot '..\..\.venv\Scripts\python.exe' +if (-not (Test-Path $global:LadderPython)) { $global:LadderPython = 'python' } +$global:LadderScript = Join-Path $PSScriptRoot "$env:LADDER_NAME.py" + +# Start-Process -NoNewWindow gives Python the console itself, and not a PowerShell pipe +# (trap 3). +function global:ladder { + $line = (@("`"$global:LadderScript`"") + @($args | ForEach-Object { "$_" })) -join ' ' + Start-Process -FilePath $global:LadderPython -ArgumentList $line -NoNewWindow -Wait +} + +ladder $env:LADDER_ARGS +Write-Host '' +Write-Host "Run it again with other values: ladder (ladder --help lists them)" diff --git a/scripts/ladders/seam_ladder.py b/scripts/ladders/seam_ladder.py new file mode 100644 index 0000000..a83a9c5 --- /dev/null +++ b/scripts/ladders/seam_ladder.py @@ -0,0 +1,153 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Seam ladder: real pairs of chips, sorted by the OKLab distance of their fills. + + python scripts/ladders/seam_ladder.py # the ladder at the live SEAM_BLUR + python scripts/ladders/seam_ladder.py --blur 0.08 # move the threshold, without an edit + python scripts/ladders/seam_ladder.py --per-bin 3 --max 0.20 --step 0.01 + +Each pair is drawn in two ways: with the solid interlock and with the thin chevron. A line +crosses the ladder at the threshold. Under the line, the widget draws the thin seam, and +over it, the solid seam. The question for the user: on which pairs can you find the solid +point without a search? The last part draws the wheel in steps of ``0x08``, as the widget +draws it now. + +JP set ``SEAM_BLUR`` to 0.06 on the first version of this ladder (2026-09-16). This version +was made again on 2026-10-28. JP set the value on the HSV wheel. The spectrum of one +lightness (2026-10-29) has fills that differ only in hue and chroma. +""" + +from __future__ import annotations + +import argparse + +from ladderkit import console +from rich.text import Text + +from meshterm.ui import oklab, pathline +from meshterm.ui.pathline import ( + POWERLINE_SEP, + POWERLINE_THIN, + PathHop, + PathLine, + _spectrum_colours, + _spectrum_seam, +) + +JND = 0.02 # the smallest difference that a user can see between two large patches + + +def hop(byte: int) -> PathHop: + """The hop of a node whose key starts with ``byte``.""" + return PathHop(f"{byte:02x}", key=f"{byte:02x}") + + +def pair(a: PathHop, b: PathHop, form: str) -> Text: + """Two chips with a seam between them: ``solid``, ``thin``, or what the widget draws.""" + ca, cb = _spectrum_colours(a), _spectrum_colours(b) + text = Text() + text.append_text(PathLine._chip(a, ca)) + if form == "solid": + text.append(POWERLINE_SEP, style=f"{ca.fill} on {cb.fill}") + elif form == "thin": + text.append(POWERLINE_THIN, style=f"{_spectrum_seam(ca)} on {cb.fill}") + else: + text.append_text(PathLine._seam(ca, cb)) + text.append_text(PathLine._chip(b, cb)) + return text + + +def around(x: float, y: float) -> float: + """The distance between two positions on the wheel of 256 bytes.""" + return min((x - y) % 256, (y - x) % 256) + + +def main() -> None: + """Draw the ladder of pairs, then the wheel as the widget draws it.""" + parser = argparse.ArgumentParser(description="Pairs of chips around the SEAM_BLUR line.") + parser.add_argument("--blur", type=float, default=pathline.SEAM_BLUR) + parser.add_argument("--per-bin", type=int, default=2) + parser.add_argument("--step", type=float, default=0.005) + parser.add_argument("--max", type=float, default=0.15) + parser.add_argument("--max-gap", type=int, default=48, help="largest first-byte gap sampled") + args = parser.parse_args() + in_code = pathline.SEAM_BLUR + pathline.SEAM_BLUR = args.blur # _fills_blur reads the module global when it runs + + con = console() + fills = {b: _spectrum_colours(hop(b)).fill for b in range(256)} + + pairs = [] + for gap in range(1, args.max_gap + 1): + for a in range(256): + b = (a + gap) % 256 + pairs.append((oklab.distance(fills[a], fills[b]), a, b)) + + bins: dict[int, list[tuple[float, int, int]]] = {} + for d, a, b in pairs: + if d < args.max: + bins.setdefault(int(d / args.step), []).append((d, a, b)) + + rows = [] + for index in sorted(bins): + members = bins[index] + # Take one pair from each sector of the wheel, and turn the sectors a little for each + # bin. Thus the ladder shows each part of the wheel, and not only the reds at its start. + offset = (index * 53) % 256 + chosen = set() + for i in range(args.per_bin): + centre = (offset + i * 256 / args.per_bin) % 256 + best = min( + members, + key=lambda p, centre=centre: around(p[1] + ((p[2] - p[1]) % 256) / 2, centre), + ) + chosen.add(best) + rows += chosen + rows.sort() + + con.print() + con.print( + Text("Seam ladder", style="bold"), + Text( + f" · SEAM_BLUR {args.blur:.3f} (code: {in_code:.3f}) · 1 JND = {JND}", + style="#a2a2a2", + ), + ) + con.print( + Text( + "Under the line the seam is thin; over it, solid. Which one can you find " + "without a search?", + style="#a2a2a2", + ) + ) + con.print() + con.print(Text(" dist JND pair solid thin today", style="bold")) + ruled = False + for d, a, b in rows: + if not ruled and d >= args.blur: + con.print(Text(f" ── SEAM_BLUR {args.blur:.3f} " + "─" * 46, style="bold #e5c07b")) + ruled = True + verdict = "thin" if d < args.blur else "solid" + line = Text(f" {d:.3f} {d / JND:4.1f} {a:02x}→{b:02x} ") + line.append_text(pair(hop(a), hop(b), "solid")) + line.append(" ") + line.append_text(pair(hop(a), hop(b), "thin")) + line.append(" ") + line.append(verdict, style="#a2a2a2" if verdict == "thin" else "bold") + con.print(line) + + con.print() + con.print(Text("Around the wheel, as the widget draws it now (steps of 0x08):", style="bold")) + for start in range(0, 256, 64): + ribbon = Text(" ") + bytes_ = list(range(start, start + 64, 8)) + for i, byte in enumerate(bytes_): + c = _spectrum_colours(hop(byte)) + if i: + ribbon.append_text(PathLine._seam(_spectrum_colours(hop(bytes_[i - 1])), c)) + ribbon.append_text(PathLine._chip(hop(byte), c)) + con.print(ribbon) + con.print() + + +if __name__ == "__main__": + main() diff --git a/scripts/ladders/snap.ps1 b/scripts/ladders/snap.ps1 new file mode 100644 index 0000000..f26142c --- /dev/null +++ b/scripts/ladders/snap.ps1 @@ -0,0 +1,32 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# Take a screenshot of a Windows Terminal window, found by its title, and save it as a PNG. +# Claude examines this picture before it tells the user that a ladder is ready. +# +# scripts\ladders\snap.ps1 -Title "Ladder hue_ladder" -Out $env:TEMP\ladder.png + +param([string]$Title, [string]$Out) +Add-Type -AssemblyName System.Drawing +Add-Type @' +using System; +using System.Runtime.InteropServices; +public static class LadderWindow { + [StructLayout(LayoutKind.Sequential)] public struct RECT { public int L, T, R, B; } + [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindow(string cls, string title); + [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); +} +'@ +[LadderWindow]::SetProcessDPIAware() | Out-Null # physical pixels, also on a scaled display +$window = [LadderWindow]::FindWindow('CASCADIA_HOSTING_WINDOW_CLASS', $Title) +if ($window -eq [IntPtr]::Zero) { Write-Error "no Windows Terminal window has the title '$Title'"; exit 1 } +[LadderWindow]::SetForegroundWindow($window) | Out-Null +Start-Sleep -Milliseconds 400 +$rect = New-Object LadderWindow+RECT +[LadderWindow]::GetWindowRect($window, [ref]$rect) | Out-Null +$size = New-Object System.Drawing.Size ($rect.R - $rect.L), ($rect.B - $rect.T) +$bitmap = New-Object System.Drawing.Bitmap $size.Width, $size.Height +[System.Drawing.Graphics]::FromImage($bitmap).CopyFromScreen($rect.L, $rect.T, 0, 0, $size) +$bitmap.Save($Out, [System.Drawing.Imaging.ImageFormat]::Png) +"snapshot: $Out ($($size.Width)x$($size.Height))"