diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md
index 3395aaf..022a265 100644
--- a/.claude/skills/release/SKILL.md
+++ b/.claude/skills/release/SKILL.md
@@ -260,6 +260,20 @@ gh release view vX.Y.Z --json assets --jq '.assets | length'
If a *build* fails, the tag is already public: fix forward with a new patch version rather
than deleting and re-pushing a tag people may have fetched.
+### Tell each fixed issue which release has its fix
+
+An issue is closed when its fix is pushed (JP, 2026-11-16), so the reporter does not yet
+have a version to install. Once the release has landed, comment on each issue whose fix is
+in this release: the issues that commits since the previous tag name, and the issues closed
+since then. Read each one first, and skip one whose fix is not in the range.
+
+```
+git log vPREV..vX.Y.Z --format='%s%n%b' | grep -oE '#[0-9]+' | sort -u
+gh issue comment N --body "The fix is in MeshTerm X.Y.Z: https://github.com/jpmartineau/MeshTerm/releases/tag/vX.Y.Z"
+```
+
+If a fix did not work, say so on the issue and reopen it instead.
+
## 7. The Discord announcement — for JP to post
Once the release has landed and checked out, end by showing JP a short announcement for
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7ab56c1..72dc0d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,39 @@ can change how things behave. It does not only add new things.
## [Unreleased]
+## [0.13.0] - 2026-11-20
+
+**MeshTerm shows the pixel images that other MeshCore apps send.** A channel message can
+carry a very small picture in the MCOimg format, as `im3:` and a line of characters. Before,
+MeshTerm showed those characters as noise. Now the chat draws the picture. Also, Chat no
+longer opens a Public channel that is not on your device.
+
+### Added
+
+- **The chat draws MCOimg pixel images.** A message that is an MCOimg image (version 3,
+ `im3:`) shows a line with its size and its number of colours, and the picture under it.
+ Each pixel is one cell wide, so the picture keeps its own size. A tall picture scrolls
+ with the transcript. The Messages list shows the same line in its preview. An image of
+ version 1 or 2 (`im:`) shows the line, but not the picture: MeshTerm does not decode
+ these older versions. Before, the characters of an image could also look like a mention
+ or a link. Now they do not.
+- **^U shows the picked image on the full screen.** The picture is as large as the screen
+ permits, by a whole number, so each pixel stays square. It never becomes smaller than its
+ own size. Under it are its size, its colours, and the text of the message itself. On the
+ PicoCalc and the Cardputer Zero, the F-key chip reads `Image`.
+- **The Show MCOimg preference turns the pictures in the chat off.** It is in the Display
+ group, and it is on by default. When it is off, the chat shows only the line about each
+ image, and ^U shows the picture.
+
+### Fixed
+
+- **Chat no longer opens a Public channel that is not on your device.** When slot 0 of the
+ device was empty, the Chat picker showed a Public row that looked like a real channel.
+ Each message that you sent there failed with "the device has no contact with that key".
+ Now the row offers to add Public to slot 0, and the chat opens after the device has the
+ channel. The command line lists only the channels on the device, and a refused send
+ names the empty slot.
+
## [0.12.0] - 2026-11-11
**MeshTerm finds wrong clocks, names the place of each node, and lets you choose the route
@@ -880,7 +913,8 @@ commands.
MeshTerm is free and open source, under the Apache 2.0 licence. The licence does not cover
the name and the logo (refer to `NOTICE`). A fork is welcome under its own name.
-[Unreleased]: https://github.com/jpmartineau/MeshTerm/compare/v0.12.0...HEAD
+[Unreleased]: https://github.com/jpmartineau/MeshTerm/compare/v0.13.0...HEAD
+[0.13.0]: https://github.com/jpmartineau/MeshTerm/releases/tag/v0.13.0
[0.12.0]: https://github.com/jpmartineau/MeshTerm/releases/tag/v0.12.0
[0.11.5]: https://github.com/jpmartineau/MeshTerm/releases/tag/v0.11.5
[0.11.4]: https://github.com/jpmartineau/MeshTerm/releases/tag/v0.11.4
diff --git a/CLAUDE.md b/CLAUDE.md
index 1f6afd5..a51ae3b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -326,6 +326,12 @@ deliberately, one at a time, and say why in the code.
narrower quiet zone, before it would ever be cut (a contact card is 57 cells and 29
rows at the standard fit in half blocks; a regular terminal is 24 tall), and when code
and URL can't share the frame the code is whole at the top and the URL a page down.
+ A picked message that is a pixel image (MCOimg, `ui/pixelart.py`) opens its image on the
+ same bare frame instead, grown by a whole number to fill it (`ImageScreen`; the chip
+ reads `Image`, the hint `^U image`); with `show_mcoimg` off, that is the only view.
+ **A pixel image is never shrunk** (JP, 2026-11-20): one pixel is one cell wide in the
+ transcript and on that frame, and a tall one scrolls; only a width the screen can't
+ hold makes it smaller.
A chat message's links open there too, on every platform: ^U on the picked message,
and with several, one code at a time that ←→ step through, clamped. That screen's URL
line is flanked `←`/`→`, lit toward another code and dim at an end — the one mark the
@@ -556,7 +562,7 @@ as a grouped list does. Filling a page in is editing its `.md`; no Python follow
📤 send now · 📨 courier/queue · 💬 chat · 🔔 notify · 🔕 mute (notifications off) ·
📱 QR · 🔗 link · ↻ re-read · ↕ reorder · ⇄ reverse (flip a path's direction) ·
🔖 region/scope · 📌 rooms · 🏆 trophy case/record · ⌨ command line · 📖 read/about · 💰 support/donate ·
- 🚪 quit. Packet-class icons (feed/viewer
+ 🎨 pixel image (an MCOimg picture in a message) · 🚪 quit. Packet-class icons (feed/viewer
lane): 📢 advert · 📊 telemetry · 📦 packet · 💬 message · ✅ ack. Raw payload
classes (`PAYLOAD_ICONS`): 📻 channel text · 💽 channel data · 📩 direct message
(overheard) · 📥 request · 📮 response · 🎭 anon request · 🧭 path · 🎯 trace ·
diff --git a/NOTICE b/NOTICE
index 08b6123..f8e2d26 100644
--- a/NOTICE
+++ b/NOTICE
@@ -39,3 +39,34 @@ Cascadia Code. It is redistributed here unmodified under the SIL Open Font
License, Version 1.1, which is included beside it as CascadiaMono-OFL.txt and
is its only license -- the Apache License above does not apply to it. The
inclusion of this font does not imply that Microsoft endorses MeshTerm.
+
+MCOimg colour tables: meshterm/core/mcoimg_palettes.py holds the colour
+tables of the MCOimg image format, generated from lib/helpers/mcoimg_palette.dart
+and lib/helpers/mcoimg_dynamic_palettes.dart of meshcore-open
+(https://github.com/zjs81/meshcore-open, and the HDDen/meshcore-open fork),
+which are provided under the following license:
+
+ MIT License
+
+ Copyright (c) 2025 zjs81
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+
+MeshTerm's MCOimg decoder is its own code, written from the published format
+reference; only these colour values come from meshcore-open.
diff --git a/README.md b/README.md
index a7ee216..2b9f7d8 100644
--- a/README.md
+++ b/README.md
@@ -27,7 +27,7 @@ run MeshTerm, the more the history of your mesh is worth.
> change something, first say hello on [Discord](https://discord.gg/AZwe5Uvb3S).
> [Read more about how the project is run](#how-this-project-is-run).
-https://github.com/user-attachments/assets/3d0414dc-d3f0-491d-83b7-11686e4922f5
+https://github.com/user-attachments/assets/a4ce1ef1-5c6b-41c3-b629-0514dc617ef3
A video of less than two minutes, in the demo mesh over Montréal (meshterm --demo).
diff --git a/docs/cli/README.md b/docs/cli/README.md
index 0810323..275312e 100644
--- a/docs/cli/README.md
+++ b/docs/cli/README.md
@@ -2072,7 +2072,7 @@ code beside each link. The scripted face prints only the link.
**`--json`:**
```json
-{"page":"discord","title":"Join Discord","version":"0.12.0","text":"Join the Discord\n Questions, ideas, bug reports, and mesh talk.\n\n • https://discord.gg/AZwe5Uvb3S","links":["https://discord.gg/AZwe5Uvb3S"]}
+{"page":"discord","title":"Join Discord","version":"0.13.0","text":"Join the Discord\n Questions, ideas, bug reports, and mesh talk.\n\n • https://discord.gg/AZwe5Uvb3S","links":["https://discord.gg/AZwe5Uvb3S"]}
```
| Field | Type | Meaning |
diff --git a/docs/development/writing-style.md b/docs/development/writing-style.md
index 87d640b..015458c 100644
--- a/docs/development/writing-style.md
+++ b/docs/development/writing-style.md
@@ -207,6 +207,7 @@ and in quoted text.
| reaction | An emoji that a node sends to answer one message. It is a message on the wire, and the chat shows it under the message that it names | |
| part | One of the messages that MeshTerm sends for a message that is too long for one packet | chunk, segment |
| part number | The `[1/3]` at the end of a part | marker (for this) |
+| pixel image | A very small picture in the MCOimg format that a message carries as text (`im3:` and Base91 characters) | picture, MCOimg image |
| sender time | The time that a message or an advert carries, from the clock of the node that sent it. It is a claim, and a node with a wrong clock makes it false | timestamp (alone) |
| arrival time | Our clock when MeshTerm got a received message from the companion (`received_at`) | receive time |
| clock offset | The sender time minus the arrival time. A positive offset is a clock ahead of ours. The offset of a node is the median of its three newest clock samples | skew, drift (for this) |
diff --git a/docs/screenshots/cardputer-zero/map.png b/docs/screenshots/cardputer-zero/map.png
index 6655f72..0394c46 100644
Binary files a/docs/screenshots/cardputer-zero/map.png and b/docs/screenshots/cardputer-zero/map.png differ
diff --git a/docs/screenshots/cardputer-zero/mcoimg.png b/docs/screenshots/cardputer-zero/mcoimg.png
new file mode 100644
index 0000000..32d1b48
Binary files /dev/null and b/docs/screenshots/cardputer-zero/mcoimg.png differ
diff --git a/docs/screenshots/cardputer-zero/menu.png b/docs/screenshots/cardputer-zero/menu.png
index 5edb103..56ce0c9 100644
Binary files a/docs/screenshots/cardputer-zero/menu.png and b/docs/screenshots/cardputer-zero/menu.png differ
diff --git a/docs/screenshots/picocalc-lyra/chat.png b/docs/screenshots/picocalc-lyra/chat.png
index 7876c0b..cfe9552 100644
Binary files a/docs/screenshots/picocalc-lyra/chat.png and b/docs/screenshots/picocalc-lyra/chat.png differ
diff --git a/docs/screenshots/picocalc-lyra/map.png b/docs/screenshots/picocalc-lyra/map.png
index 6f68b26..fd251f5 100644
Binary files a/docs/screenshots/picocalc-lyra/map.png and b/docs/screenshots/picocalc-lyra/map.png differ
diff --git a/docs/screenshots/picocalc-lyra/mcoimg.png b/docs/screenshots/picocalc-lyra/mcoimg.png
new file mode 100644
index 0000000..29eab5d
Binary files /dev/null and b/docs/screenshots/picocalc-lyra/mcoimg.png differ
diff --git a/docs/screenshots/picocalc-lyra/menu.png b/docs/screenshots/picocalc-lyra/menu.png
index ecb8c3a..95793fb 100644
Binary files a/docs/screenshots/picocalc-lyra/menu.png and b/docs/screenshots/picocalc-lyra/menu.png differ
diff --git a/docs/screenshots/picocalc-lyra/paths.png b/docs/screenshots/picocalc-lyra/paths.png
index 234be83..fd70e9b 100644
Binary files a/docs/screenshots/picocalc-lyra/paths.png and b/docs/screenshots/picocalc-lyra/paths.png differ
diff --git a/docs/screenshots/terminal/chat.png b/docs/screenshots/terminal/chat.png
index 2778f30..bc213de 100644
Binary files a/docs/screenshots/terminal/chat.png and b/docs/screenshots/terminal/chat.png differ
diff --git a/docs/screenshots/terminal/map.png b/docs/screenshots/terminal/map.png
index df057fb..210786d 100644
Binary files a/docs/screenshots/terminal/map.png and b/docs/screenshots/terminal/map.png differ
diff --git a/docs/screenshots/terminal/mcoimg.png b/docs/screenshots/terminal/mcoimg.png
new file mode 100644
index 0000000..2984d1b
Binary files /dev/null and b/docs/screenshots/terminal/mcoimg.png differ
diff --git a/docs/screenshots/terminal/menu.png b/docs/screenshots/terminal/menu.png
index c34704c..5827116 100644
Binary files a/docs/screenshots/terminal/menu.png and b/docs/screenshots/terminal/menu.png differ
diff --git a/docs/screenshots/terminal/paths.png b/docs/screenshots/terminal/paths.png
index db9ee34..4aaf129 100644
Binary files a/docs/screenshots/terminal/paths.png and b/docs/screenshots/terminal/paths.png differ
diff --git a/meshterm/__init__.py b/meshterm/__init__.py
index bc59fe1..0f36d59 100644
--- a/meshterm/__init__.py
+++ b/meshterm/__init__.py
@@ -6,7 +6,7 @@ Connects to a companion over USB, Bluetooth, or TCP. For Windows, macOS, and Lin
from datetime import datetime
-__version__ = "0.12.0"
+__version__ = "0.13.0"
__author__ = "Jean-Pierre Martineau"
#: The year when MeshTerm was first published. The copyright span starts in this year.
diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py
index 9745009..9a44dd1 100644
--- a/meshterm/core/connection.py
+++ b/meshterm/core/connection.py
@@ -4556,7 +4556,14 @@ class MeshCoreDevice(Device):
) -> None:
transmit_gate.mark()
async with self.transmitting():
- self._ok(await self._require().commands.send_chan_msg(index, text, timestamp))
+ event = await self._require().commands.send_chan_msg(index, text, timestamp)
+ # For a channel send, "not found" is an empty slot, not a contact. The general
+ # clause names a contact, which was the wrong lead in issue #36.
+ if error_code(event) == 2:
+ raise RuntimeError(
+ f"device rejected the command: the device has no channel in slot {index}"
+ )
+ self._ok(event)
@staticmethod
def _ok(event): # type: ignore[no-untyped-def]
diff --git a/meshterm/core/mcoimg.py b/meshterm/core/mcoimg.py
new file mode 100644
index 0000000..0b22740
--- /dev/null
+++ b/meshterm/core/mcoimg.py
@@ -0,0 +1,190 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Recognize a pixel image in the body of a message: the MCOimg format.
+
+MCOimg is a format for very small pictures (1 to 256 pixels for each side, in practice 10
+to 30) that some MeshCore apps send on a channel. Each image is one packet. As a text
+message, it is a prefix and then Base91 text: ``im:`` for the versions 1 and 2, ``im3:``
+for version 3. A client that does not know the format shows that text as noise. The
+reference is ``docs/mcoimg_v3_reference.md`` in the HDDen/meshcore-open repository (MIT).
+
+This module only *recognizes* an image: :func:`recognize` finds that a body is an image,
+and for a version 3 image it reads the header (the size and the number of colours of the
+palette). Thus the chat can show a short line in place of the noise. It is fast, and it
+does not decode the pixels. The pixel decoder is :mod:`meshterm.core.mcoimg_decode`. It is
+a separate module because it is large: the chat loads it only when it draws the first
+image, and not each time that it opens (approximately 50 ms on the PicoCalc).
+
+Version 3 data, after the Base91 decode::
+
+ 0x13 subtype 1 (MCOimg) in the high nibble, revision 3 in the low
+ nonce: u8 changes with each send, and has no meaning for the picture
+ header: u8 bit 7 transparent, bit 6 white background, bits 5..4 scan,
+ bits 3..0 palette profile
+ dimensions bit-packed, LSB first (refer to :func:`_dimensions`)
+ ... the pixels, which :mod:`meshterm.core.mcoimg_decode` reads
+
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+#: The Base91 alphabet of MCOimg, in the order of its values. It is the alphabet of
+#: basE91, which has no space, no ``'``, no ``-``, and no ``\\``.
+_ALPHABET = (
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~"'
+)
+_VALUE = {char: index for index, char in enumerate(_ALPHABET)}
+
+#: A body that is an image: the prefix and one word of Base91 text. The version digit is
+#: optional, because the versions 1 and 2 use ``im:``.
+_IMAGE = re.compile(r"im(\d?):(\S+)")
+
+#: The shortest Base91 text that MeshTerm accepts as an image of a version whose header it
+#: cannot read. The smallest such image of the reference tests has 11 characters. A
+#: shorter word after ``im:`` is more probably words that a person typed. A version 3 image
+#: needs no minimum, because its first byte and its header must be correct.
+_MIN_TEXT = 8
+
+#: The first byte of a version 3 image: subtype 1 (MCOimg), revision 3.
+_V3 = 0x13
+
+#: The number of colours of each palette profile of version 3, by profile id. The ids
+#: 0 to 5 are the master palettes, 6 to 8 are the grey palettes, and 9 to 15 are the
+#: dynamic palettes (subsets of the global palette of 512 colours).
+_PROFILE_COLOURS = (2, 4, 8, 16, 32, 64, 16, 32, 8, 8, 16, 32, 64, 128, 256, 512)
+
+
+@dataclass(frozen=True)
+class PixelImage:
+ """What a message body tells about the pixel image that it carries.
+
+ Attributes:
+ version: The format version: 3 for ``im3:``, or ``None`` for ``im:``, which is
+ version 1 or 2 (its text does not say which).
+ width: The width in pixels, or ``None`` when MeshTerm cannot read the header.
+ height: The height in pixels, or ``None`` when MeshTerm cannot read the header.
+ colours: The number of colours of the palette, or ``None`` when MeshTerm cannot
+ read the header.
+ """
+
+ version: int | None
+ width: int | None = None
+ height: int | None = None
+ colours: int | None = None
+
+
+def recognize(body: str) -> PixelImage | None:
+ """Return the pixel image that ``body`` carries, or ``None`` when it is not an image.
+
+ The body must be the image and nothing else (spaces at the ends are permitted). An
+ ``im3:`` body must also start with the version 3 byte after the decode. A body with a
+ version that MeshTerm does not know (``im4:``) is an image with no header.
+
+ Args:
+ body: The text of a message, without the ``Name: `` of a channel sender.
+
+ Returns:
+ The image, or ``None``.
+ """
+ match = _IMAGE.fullmatch(body.strip())
+ if match is None:
+ return None
+ digit, text = match.groups()
+ data = base91_decode(text)
+ if data is None:
+ return None
+ version = int(digit) if digit else None
+ if version != 3:
+ # Here MeshTerm cannot read a header, so only the length makes the claim.
+ return PixelImage(version=version) if len(text) >= _MIN_TEXT else None
+ if len(data) < 4 or data[0] != _V3:
+ return None
+ header = data[2]
+ size = _dimensions(_Bits(data[3:]))
+ if size is None:
+ return PixelImage(version=3)
+ width, height = size
+ return PixelImage(3, width, height, _PROFILE_COLOURS[header & 0x0F])
+
+
+def base91_decode(text: str) -> bytes | None:
+ """Decode the Base91 text of an image, or return ``None`` for a character not in it.
+
+ Each pair of characters holds 13 or 14 bits: 13 when the low 13 bits of the pair are
+ more than 88, or else 14. A last single character holds the remaining bits.
+ """
+ out = bytearray()
+ queue = bits = 0
+ value = -1
+ for char in text:
+ index = _VALUE.get(char)
+ if index is None:
+ return None
+ if value < 0:
+ value = index
+ continue
+ value += index * 91
+ queue |= value << bits
+ bits += 13 if (value & 8191) > 88 else 14
+ while bits > 7:
+ out.append(queue & 0xFF)
+ queue >>= 8
+ bits -= 8
+ value = -1
+ if value >= 0:
+ out.append((queue | (value << bits)) & 0xFF)
+ return bytes(out)
+
+
+class _Bits:
+ """A reader of bit fields, LSB first, from a byte string.
+
+ :func:`recognize` uses it. :func:`decode` uses the subclass :class:`_Reader`, which
+ adds the integer forms of the format.
+ """
+
+ def __init__(self, data: bytes) -> None:
+ self._value = int.from_bytes(data, "little")
+ self._left = len(data) * 8
+ self._pos = 0
+
+ def read(self, count: int) -> int | None:
+ """The next ``count`` bits as an unsigned number, or ``None`` past the end."""
+ if self._pos + count > self._left:
+ return None
+ value = (self._value >> self._pos) & ((1 << count) - 1)
+ self._pos += count
+ return value
+
+
+def _dimensions(bits: _Bits) -> tuple[int, int] | None:
+ """Read the width and the height of a version 3 image, or ``None`` past the end.
+
+ The first two bits are the mode. Each mode stores the sizes minus one:
+
+ - 0: a square up to 64, one width of 6 bits.
+ - 1: up to 32 × 32, a width and a height of 5 bits each.
+ - 2: up to 64 × 64, a width and a height of 6 bits each.
+ - 3: up to 256 × 256. One bit is set for a rectangle. Then there is a width of 8 bits,
+ and for a rectangle a height of 8 bits.
+ """
+ mode = bits.read(2)
+ if mode == 0:
+ side = bits.read(6)
+ return None if side is None else (side + 1, side + 1)
+ if mode in (1, 2):
+ size = 5 if mode == 1 else 6
+ width, height = bits.read(size), bits.read(size)
+ elif mode == 3:
+ rectangle = bits.read(1)
+ if rectangle is None:
+ return None
+ width = bits.read(8)
+ height = bits.read(8) if rectangle else width
+ else:
+ return None
+ if width is None or height is None:
+ return None
+ return width + 1, height + 1
diff --git a/meshterm/core/mcoimg_decode.py b/meshterm/core/mcoimg_decode.py
new file mode 100644
index 0000000..e1baa24
--- /dev/null
+++ b/meshterm/core/mcoimg_decode.py
@@ -0,0 +1,1252 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Decode the pixels of a version 3 pixel image (MCOimg).
+
+:func:`decode` decodes all the pixels of a version 3 image into colours. It knows all the
+containers, block algorithms, scan orders, palette profiles, and local palettes of the
+reference. It does not decode the versions 1 and 2. :mod:`meshterm.core.mcoimg` recognizes
+an image and reads its header. This module reads the rest, and it is separate because it
+is large: it loads only when the chat draws its first image.
+
+Version 3 data, after the Base91 decode::
+
+ 0x13 subtype 1 (MCOimg) in the high nibble, revision 3 in the low
+ nonce: u8 changes with each send, and has no meaning for the picture
+ header: u8 bit 7 transparent, bit 6 white background, bits 5..4 scan,
+ bits 3..0 palette profile
+ dimensions bit-packed, LSB first (refer to :func:`~meshterm.core.mcoimg._dimensions`)
+ container: 8 bits bits 7..5 the container, bits 4..0 its context
+ transparent colour a colour reference, only when header bit 7 is set
+ container body bit-packed, then zero bits to the end of the last byte
+
+The palette colours are in :mod:`meshterm.core.mcoimg_palettes`.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from functools import cache
+from typing import NamedTuple
+
+from .mcoimg import _IMAGE, _V3, _Bits, _dimensions, base91_decode
+
+
+@dataclass(frozen=True)
+class Picture:
+ """The decoded pixels of a version 3 image.
+
+ Attributes:
+ width: The width in pixels, 1 to 256.
+ height: The height in pixels, 1 to 256.
+ pixels: The colour of each pixel as (red, green, blue), row by row from the top
+ left (``pixels[y * width + x]``). ``None`` is a transparent pixel.
+ """
+
+ width: int
+ height: int
+ pixels: tuple[tuple[int, int, int] | None, ...]
+
+
+def decode(body: str) -> Picture | None:
+ """Decode the pixels of the version 3 image that ``body`` carries.
+
+ The body must be the image and nothing else, as for
+ :func:`~meshterm.core.mcoimg.recognize`. The function does not raise an error. A body
+ that is not a version 3 image, or that has an error at any point in its data, gives
+ ``None``. The data comes from a stranger on the mesh, so the decoder also limits its
+ work (refer to :data:`_MAX_TEXT` and :data:`_WORK`).
+
+ Args:
+ body: The text of a message, without the ``Name: `` of a channel sender.
+
+ Returns:
+ The picture, or ``None``.
+ """
+ indexed = _decode_refs(body)
+ if indexed is None:
+ return None
+ lookup = _profiles()[indexed.profile].rgb
+ clear = indexed.transparent
+ pixels = tuple(None if ref == clear else lookup[ref] for ref in indexed.refs)
+ return Picture(indexed.width, indexed.height, pixels)
+
+
+class _Indexed(NamedTuple):
+ """A decoded image before its colours: the palette reference of each pixel.
+
+ For a dynamic profile, a reference is an index in ``GLOBAL_512``. For a fixed profile,
+ it is a colour id of the profile. These are the numbers of the reference codec and of
+ its test vectors.
+ """
+
+ width: int
+ height: int
+ #: The palette profile id, 0 to 15 (refer to :data:`~meshterm.core.mcoimg._PROFILE_COLOURS`).
+ profile: int
+ #: The references, row by row from the top left.
+ refs: list[int]
+ #: The reference that is transparent, or ``None``.
+ transparent: int | None
+
+
+def _decode_refs(body: str) -> _Indexed | None:
+ """Decode a version 3 image to palette references, or return ``None`` for any error."""
+ try:
+ return _decode_indexed(body)
+ except Exception: # noqa: BLE001 - hostile data can fail in many ways. Each one is "no image".
+ return None
+
+
+class _Bad(Exception):
+ """The data of an image does not obey a rule of the format."""
+
+
+#: The longest Base91 text that :func:`decode` reads. A message on the mesh is much
+#: shorter. The limit stops a long hostile text before it can make the decode slow.
+_MAX_TEXT = 4096
+
+#: The work limit of a decode, in pixels for each pixel of the image. Each block that the
+#: decoder reads uses the pixels of its rectangle. The regions of a real image do not
+#: overlap, so they use one pixel for each pixel of the image. Hostile regions can overlap
+#: as much as they want, and this limit stops them.
+_WORK = 4
+
+#: The block algorithms that use the compact block header: ``rawGlobal`` (0), ``rawLocal``
+#: (1), and ``biColorMask`` (4). They have no scan order, so the scan is always ``h``.
+_COMPACT_HEADER = frozenset({0, 1, 4})
+
+#: The block algorithms that have a background colour: ``compactSparse`` (3),
+#: ``biColorMask`` (4), and ``varUintSparse`` (15).
+_WITH_BACKGROUND = frozenset({3, 4, 15})
+
+#: The block algorithms that cannot use a shared region palette, because they have no
+#: local palette: ``rawGlobal`` (0), ``directBitplanes`` (10), and ``directRowDelta`` (12).
+_NO_SHARED_PALETTE = frozenset({0, 10, 12})
+
+#: The ids of the grey palette profiles.
+_GREY_PROFILES = frozenset({6, 7, 8})
+
+#: The marker of a hybrid common header in a regions stream. It is not an algorithm id.
+_HYBRID = 31
+
+_WHITE = (255, 255, 255)
+
+
+class _Profile(NamedTuple):
+ """A palette profile of version 3, as the decoder uses it.
+
+ In the decoder, each colour is a colour id of the profile: 0 to ``size - 1``. Only the
+ last step changes the ids of a dynamic profile into ``GLOBAL_512`` indices.
+ """
+
+ size: int
+ #: The number of bits of one colour id in the data.
+ bits: int
+ #: The colour id of white, for the implicit white background.
+ white: int
+ grey: bool
+ #: For a dynamic profile, the ``GLOBAL_512`` index of each colour id. For a fixed
+ #: profile, ``None``.
+ table: tuple[int, ...] | None
+ #: The RGB value of each output reference (refer to :class:`_Indexed`).
+ rgb: tuple[tuple[int, int, int], ...]
+
+
+@cache
+def _profiles() -> tuple[_Profile, ...]:
+ """The 16 palette profiles, by profile id.
+
+ The import of the colour tables occurs here, at the first decode, and not when the
+ module loads. Thus the chat can call :func:`~meshterm.core.mcoimg.recognize` and not
+ load the tables.
+ """
+ from meshterm.core import mcoimg_palettes as tables
+
+ fixed = (
+ tables.MONO,
+ tables.MASTER_4,
+ tables.MASTER_8,
+ tables.MASTER_16,
+ tables.MASTER_32,
+ tables.MASTER_64,
+ tables.GREY_16,
+ tables.GREY_32,
+ tables.GREY_8,
+ )
+ dynamic = (
+ tables.DYNAMIC_8,
+ tables.DYNAMIC_16,
+ tables.DYNAMIC_32,
+ tables.DYNAMIC_64,
+ tables.DYNAMIC_128,
+ tables.DYNAMIC_256,
+ tables.DYNAMIC_512,
+ )
+ profiles = []
+ for ident, colours in enumerate(fixed):
+ size = len(colours)
+ bits = (size - 1).bit_length()
+ profiles.append(_Profile(size, bits, 0, ident in _GREY_PROFILES, None, colours))
+ for table in dynamic:
+ size = len(table)
+ bits = (size - 1).bit_length()
+ white = next(i for i, index in enumerate(table) if tables.GLOBAL_512[index] == _WHITE)
+ profiles.append(_Profile(size, bits, white, False, table, tables.GLOBAL_512))
+ return tuple(profiles)
+
+
+def _decode_indexed(body: str) -> _Indexed | None:
+ """Decode a version 3 image to palette references.
+
+ Returns:
+ The image, or ``None`` when the body is not a version 3 image.
+
+ Raises:
+ _Bad: The data does not obey the format. Other errors can also occur for hostile
+ data. :func:`_decode_refs` catches all of them.
+ """
+ match = _IMAGE.fullmatch(body.strip())
+ if match is None or match.group(1) != "3" or len(match.group(2)) > _MAX_TEXT:
+ return None
+ data = base91_decode(match.group(2))
+ if data is None or len(data) < 5 or data[0] != _V3:
+ return None
+ header = data[2]
+ profile_id = header & 0x0F
+ profile = _profiles()[profile_id]
+ scan = (header >> 4) & 0x03
+ implicit_white = bool(header & 0x40)
+ reader = _Reader(data[3:])
+ size = _dimensions(reader)
+ if size is None:
+ raise _Bad
+ width, height = size
+ if reader.pos != _canonical_dimension_bits(width, height):
+ raise _Bad
+ container_byte = reader.bits(8)
+ container, context = container_byte >> 5, container_byte & 0x1F
+ algorithm = _algorithm(context) if container <= 3 else 0
+ _check_top_level(container, algorithm, scan, implicit_white)
+ transparent = reader.bits(profile.bits) if header & 0x80 else None
+
+ decoder = _Decoder(reader, profile, implicit_white, width * height * _WORK)
+ if container <= 1:
+ # block (0) and compactBlock (1). The checks above made the scan of a compact
+ # block h.
+ refs = _unscan(decoder.block(width, height, algorithm, scan), width, height, scan)
+ elif container <= 3:
+ refs = decoder.bounds(width, height, algorithm, scan, compact=container == 3)
+ elif container <= 5:
+ refs = decoder.regions(width, height, context + 1, compact=container == 5)
+ elif container == 6:
+ refs = [decoder.solid_colour(context)] * (width * height)
+ else:
+ refs = decoder.solid_rects(width, height, context)
+ reader.finish()
+
+ if profile.table is not None:
+ table = profile.table
+ refs = [table[ref] for ref in refs]
+ if transparent is not None:
+ transparent = table[transparent]
+ return _Indexed(width, height, profile_id, refs, transparent)
+
+
+def _canonical_dimension_bits(width: int, height: int) -> int:
+ """The number of bits of the canonical dimensions of a size.
+
+ The format permits only the shortest mode for a size. Each mode has its own number of
+ bits, so a different number of bits after :func:`_dimensions` shows a mode that is
+ not canonical.
+ """
+ if width == height and width <= 64:
+ return 8 # mode 0
+ if width <= 32 and height <= 32:
+ return 12 # mode 1
+ if width <= 64 and height <= 64:
+ return 14 # mode 2
+ return 11 if width == height else 19 # mode 3, square or rectangle
+
+
+def _algorithm(ident: int) -> int:
+ """Check a block algorithm id (0 to 15) and return it."""
+ if ident > 15:
+ raise _Bad
+ return ident
+
+
+def _check_top_level(container: int, algorithm: int, scan: int, implicit_white: bool) -> None:
+ """Check that the header, the container, and the algorithm agree.
+
+ - A ``block`` cannot hold an algorithm of the compact header, and a ``compactBlock``
+ can hold only those algorithms.
+ - Some containers and the ``quadtree`` algorithm (7) permit only the scan ``h``.
+ - The implicit white background is valid only where there is a background colour.
+ """
+ if container == 0 and algorithm in _COMPACT_HEADER:
+ raise _Bad
+ if container == 1 and algorithm not in _COMPACT_HEADER:
+ raise _Bad
+ horizontal = container in (1, 4, 5, 6, 7) or (container == 3 and algorithm in _COMPACT_HEADER)
+ if (horizontal or algorithm == 7) and scan != 0:
+ raise _Bad
+ if implicit_white and container <= 1 and algorithm not in _WITH_BACKGROUND:
+ raise _Bad
+
+
+def _local_bits(colours: int) -> int:
+ """The number of bits of one index in a local palette of ``colours`` colours."""
+ return (colours - 1).bit_length() if colours > 1 else 0
+
+
+def _row_length(scan: int, width: int, height: int) -> int:
+ """The length of one row of the scan sequence: a row for ``h`` and ``s``, else a column."""
+ return width if scan in (0, 2) else height
+
+
+def _scan_positions(width: int, height: int, scan: int) -> list[int]:
+ """The row-major position of each item of the scan sequence.
+
+ - 0 ``h``: rows from the top, each row from the left.
+ - 1 ``v``: columns from the left, each column from the top.
+ - 2 ``s``: as ``h``, but the odd rows go from the right.
+ - 3 ``sv``: as ``v``, but the odd columns go from the bottom.
+ """
+ if scan == 0:
+ return list(range(width * height))
+ if scan == 1:
+ return [y * width + x for x in range(width) for y in range(height)]
+ if scan == 2:
+ return [
+ y * width + x
+ for y in range(height)
+ for x in (range(width) if y % 2 == 0 else range(width - 1, -1, -1))
+ ]
+ return [
+ y * width + x
+ for x in range(width)
+ for y in (range(height) if x % 2 == 0 else range(height - 1, -1, -1))
+ ]
+
+
+def _unscan(linear: list[int], width: int, height: int, scan: int) -> list[int]:
+ """Put the items of a scan sequence back in row-major order."""
+ if len(linear) != width * height:
+ raise _Bad
+ if scan == 0:
+ return linear
+ result = [0] * len(linear)
+ for item, position in zip(linear, _scan_positions(width, height, scan), strict=True):
+ result[position] = item
+ return result
+
+
+def _pick(palette: list[int], index: int) -> int:
+ """The colour at ``index`` in a local palette, or :class:`_Bad` past its end."""
+ if index >= len(palette):
+ raise _Bad
+ return palette[index]
+
+
+def _pick_all(palette: list[int], indices: list[int]) -> list[int]:
+ """The colours of a list of local palette indices."""
+ if indices and max(indices) >= len(palette):
+ raise _Bad
+ return [palette[index] for index in indices]
+
+
+class _Reader(_Bits):
+ """A reader of the bit fields of version 3, which raises :class:`_Bad` past the end.
+
+ It also reads the integer forms of the format. The data is short (a message), so one
+ Python integer holds all of it.
+ """
+
+ @property
+ def pos(self) -> int:
+ """The number of bits that the reader has read."""
+ return self._pos
+
+ def bits(self, count: int) -> int:
+ """The next ``count`` bits as an unsigned number."""
+ if self._pos + count > self._left:
+ raise _Bad
+ value = (self._value >> self._pos) & ((1 << count) - 1)
+ self._pos += count
+ return value
+
+ def flags(self, count: int) -> list[bool]:
+ """The next ``count`` bits, one flag each, in the order of the data."""
+ if count == 0:
+ return []
+ text = format(self.bits(count), "b").zfill(count)
+ return [char == "1" for char in reversed(text)]
+
+ def varuint(self) -> int:
+ """A ``bitVarUint``: 7 bits in each byte, and bit 7 set when a byte follows."""
+ value = 0
+ for shift in range(0, 35, 7):
+ byte = self.bits(8)
+ value |= (byte & 0x7F) << shift
+ if not byte & 0x80:
+ return value
+ raise _Bad
+
+ def compact(self) -> int:
+ """A ``compactUint``: a short prefix, then 2, 4, or 8 bits, or a ``bitVarUint``.
+
+ The ``bitVarUint`` holds the value itself, not the value minus 276. The reference
+ encoder writes it that way.
+ """
+ if not self.bits(1):
+ return self.bits(2)
+ if not self.bits(1):
+ return self.bits(4) + 4
+ if not self.bits(1):
+ return self.bits(8) + 20
+ return self.varuint()
+
+ def range_compact(self, maximum: int) -> int:
+ """A ``rangeCompactUint``: fixed bits up to a maximum of 7, else a ``compactUint``."""
+ if maximum < 0:
+ raise _Bad
+ value = self.bits(maximum.bit_length()) if maximum <= 7 else self.compact()
+ if value > maximum:
+ raise _Bad
+ return value
+
+ def bounded(self, maximum: int) -> int:
+ """A ``boundedCompactUint``: as ``compactUint``, but its last form has fixed bits."""
+ if maximum < 0:
+ raise _Bad
+ if maximum <= 7:
+ value = self.bits(maximum.bit_length())
+ elif not self.bits(1):
+ value = self.bits(2)
+ elif not self.bits(1):
+ value = self.bits(4) + 4
+ elif not self.bits(1):
+ value = self.bits(8) + 20
+ elif maximum < 276:
+ raise _Bad
+ else:
+ value = self.bits((maximum - 276).bit_length()) + 276
+ if value > maximum:
+ raise _Bad
+ return value
+
+ def signed(self) -> int:
+ """A ``signedCompactInt``: a zigzag value in a ``compactUint``."""
+ code = self.compact()
+ return code // 2 if code % 2 == 0 else -((code + 1) // 2)
+
+ def finish(self) -> None:
+ """Check the end: only zero bits to the end of the last byte, and no more bytes."""
+ if (self._pos + 7) // 8 * 8 != self._left or self._value >> self._pos:
+ raise _Bad
+
+
+class _Decoder:
+ """The decoder of the body of one image: the containers and the block algorithms.
+
+ All colours here are colour ids of the profile (refer to :class:`_Profile`).
+ """
+
+ def __init__(self, reader: _Reader, profile: _Profile, implicit_white: bool, work: int):
+ self.reader = reader
+ self.profile = profile
+ self.implicit_white = implicit_white
+ #: The pixels that the blocks can still use (refer to :data:`_WORK`).
+ self.work = work
+
+ # The containers.
+
+ def background(self) -> int:
+ """The background colour of a container or a block: white, or a colour in the data."""
+ if self.implicit_white:
+ return self.profile.white
+ return self.reader.bits(self.profile.bits)
+
+ def solid_colour(self, context: int) -> int:
+ """The colour of a ``solidBackground`` image.
+
+ The low bits of the colour id are in the context. A colour id of more than 5 bits
+ has its high bits in the body.
+ """
+ if self.implicit_white:
+ if context:
+ raise _Bad
+ return self.profile.white
+ bits = self.profile.bits
+ low = min(bits, 5)
+ if context >> low:
+ raise _Bad
+ return context | (self.reader.bits(bits - low) << low)
+
+ def solid_rects(self, width: int, height: int, context: int) -> list[int]:
+ """A ``solidRects`` image: a background, then up to 64 rectangles of one colour."""
+ background = self.background()
+ palette = self.palette()
+ bits = _local_bits(len(palette))
+ count = context + (self.reader.bits(1) << 5) + 1
+ refs = [background] * (width * height)
+ for _ in range(count):
+ x, y, w, h = self.geometry(width, height, compact=True)
+ colour = _pick(palette, self.reader.bits(bits))
+ for row in range(y, y + h):
+ start = row * width + x
+ refs[start : start + w] = [colour] * w
+ return refs
+
+ def bounds(
+ self, width: int, height: int, algorithm: int, scan: int, *, compact: bool
+ ) -> list[int]:
+ """A ``boundsBlock`` or ``compactBoundsBlock``: one block on a background."""
+ background = self.background()
+ x, y, w, h = self.geometry(width, height, compact=compact)
+ linear = self.block(w, h, algorithm, scan, background=background)
+ refs = [background] * (width * height)
+ _paste(refs, width, (x, y, w, h), _unscan(linear, w, h, scan))
+ return refs
+
+ def regions(self, width: int, height: int, count: int, *, compact: bool) -> list[int]:
+ """A ``regions`` or ``compactRegionsStream`` image: blocks on a background.
+
+ A compact stream starts with three flags: a common block header, delta geometry,
+ and a shared local palette. A common header with the id 31 is a hybrid header:
+ the real id follows, and each region has one bit that selects its own header.
+ """
+ reader = self.reader
+ background = self.background()
+ common = delta = shared = False
+ if compact:
+ common, delta, shared = (bool(reader.bits(1)) for _ in range(3))
+ hybrid = False
+ common_algorithm = common_scan = 0
+ if common:
+ ident = reader.bits(5)
+ hybrid = ident == _HYBRID
+ common_algorithm = _algorithm(reader.bits(5) if hybrid else ident)
+ common_scan = self.region_scan(common_algorithm)
+ palette = self.palette() if shared else None
+ refs = [background] * (width * height)
+ box: tuple[int, int, int, int] | None = None
+ for _ in range(count):
+ if delta and box is not None:
+ box = self.delta_geometry(box, width, height)
+ else:
+ box = self.geometry(width, height, compact=compact)
+ own_header = bool(reader.bits(1)) if hybrid else not common
+ if own_header:
+ algorithm = _algorithm(reader.bits(5))
+ scan = self.region_scan(algorithm)
+ else:
+ algorithm, scan = common_algorithm, common_scan
+ _x, _y, w, h = box
+ linear = self.block(w, h, algorithm, scan, shared=palette, background=background)
+ _paste(refs, width, box, _unscan(linear, w, h, scan))
+ return refs
+
+ def region_scan(self, algorithm: int) -> int:
+ """The scan of a region header: ``h`` for a compact header algorithm, else 2 bits."""
+ return 0 if algorithm in _COMPACT_HEADER else self.reader.bits(2)
+
+ def geometry(self, width: int, height: int, *, compact: bool) -> tuple[int, int, int, int]:
+ """A rectangle (x, y, width, height) in the image.
+
+ Plain geometry has 8 bits for each field. Compact geometry has only the bits that
+ the image size, and then the space to the right and below, make necessary.
+ """
+ reader = self.reader
+ x = reader.bits((width - 1).bit_length() if compact else 8)
+ y = reader.bits((height - 1).bit_length() if compact else 8)
+ if x >= width or y >= height:
+ raise _Bad
+ w = reader.bits((width - x - 1).bit_length() if compact else 8) + 1
+ h = reader.bits((height - y - 1).bit_length() if compact else 8) + 1
+ if x + w > width or y + h > height:
+ raise _Bad
+ return x, y, w, h
+
+ def delta_geometry(
+ self, previous: tuple[int, int, int, int], width: int, height: int
+ ) -> tuple[int, int, int, int]:
+ """A rectangle as four signed differences from the previous rectangle."""
+ x, y, w, h = (value + self.reader.signed() for value in previous)
+ if x < 0 or y < 0 or w <= 0 or h <= 0 or x + w > width or y + h > height:
+ raise _Bad
+ return x, y, w, h
+
+ # The local palettes.
+
+ def palette(self) -> list[int]:
+ """A local palette: a list of colour ids with no duplicates.
+
+ A flat palette gives a length and then each colour id. A descriptor palette
+ gives the colour ids in a shorter form (refer to :meth:`descriptor`).
+ """
+ reader = self.reader
+ size, bits = self.profile.size, self.profile.bits
+ if size <= 64:
+ if reader.bits(1):
+ return self.descriptor(reader.bits(2))
+ length = reader.bits(bits) + 1
+ elif not reader.bits(1):
+ length = reader.bits(6) + 1
+ elif not reader.bits(1):
+ length = reader.bits(6) + 65
+ elif not reader.bits(1):
+ length = reader.bits(8) + 129
+ elif not reader.bits(1):
+ length = reader.bits(7) + 385
+ else:
+ return self.descriptor(reader.bits(2))
+ if length > size:
+ raise _Bad
+ colours = [reader.bits(bits) for _ in range(length)]
+ if len(set(colours)) != length:
+ raise _Bad
+ return colours
+
+ def palette_length(self) -> int:
+ """The length of a sorted-delta or ordered-banked palette."""
+ reader = self.reader
+ size = self.profile.size
+ if size <= 64:
+ return reader.bits(self.profile.bits) + 1
+ if not reader.bits(1):
+ return reader.bits(6) + 1
+ if not reader.bits(1):
+ return reader.bits(6) + 65
+ if size <= 128:
+ raise _Bad
+ length = reader.bits((size - 129).bit_length()) + 129
+ if length > size:
+ raise _Bad
+ return length
+
+ def descriptor(self, kind: int) -> list[int]:
+ """A descriptor palette.
+
+ - 0 bitmap: one bit for each colour of the profile.
+ - 1 sorted delta: the length, the first colour id, then the gap to each next one.
+ - 2 range runs: runs of consecutive colour ids.
+ - 3 banked (only for ``dynamicGlobal512``): one bit selects bank bitmaps or the
+ ordered form. Refer to :meth:`banked`.
+
+ All forms except the ordered form give the colour ids in ascending order.
+ """
+ reader = self.reader
+ size, bits = self.profile.size, self.profile.bits
+ if kind == 0:
+ refs = [ref for ref, flag in enumerate(reader.flags(size)) if flag]
+ elif kind == 1:
+ length = self.palette_length()
+ refs = [reader.bits(bits)]
+ while len(refs) < length:
+ refs.append(refs[-1] + reader.compact() + 1)
+ elif kind == 2:
+ runs = reader.range_compact(size - 1) + 1
+ refs = []
+ previous_end = -1
+ for _ in range(runs):
+ start = reader.bits(bits)
+ length = reader.compact() + 1
+ end = start + length - 1
+ if start <= previous_end or end >= size or len(refs) + length > size:
+ raise _Bad
+ refs.extend(range(start, end + 1))
+ previous_end = end
+ else:
+ refs = self.banked()
+ if not refs or len(refs) > size or len(set(refs)) != len(refs):
+ raise _Bad
+ if max(refs) >= size:
+ raise _Bad
+ return refs
+
+ def banked(self) -> list[int]:
+ """A banked palette of ``dynamicGlobal512``: 8 banks of 64 colours.
+
+ - Bank bitmaps (bit 0): a mask of 8 banks, then 64 bits for each selected bank.
+ - Ordered (bit 1): the length, then for each colour its bank and its offset in
+ the bank. A single bank has 3 bits once. Several banks have a mask of 8 bits,
+ and each colour has the index of its bank in the list of selected banks.
+
+ Each selected bank must have one colour or more.
+ """
+ reader = self.reader
+ if self.profile.size != 512:
+ raise _Bad
+ if not reader.bits(1):
+ mask = reader.bits(8)
+ if not mask:
+ raise _Bad
+ refs: list[int] = []
+ for bank in range(8):
+ if mask >> bank & 1:
+ chosen = [
+ bank << 6 | offset for offset, flag in enumerate(reader.flags(64)) if flag
+ ]
+ if not chosen:
+ raise _Bad
+ refs.extend(chosen)
+ return refs
+ length = self.palette_length()
+ if not reader.bits(1):
+ if length > 64:
+ raise _Bad
+ bank = reader.bits(3)
+ return [bank << 6 | reader.bits(6) for _ in range(length)]
+ mask = reader.bits(8)
+ banks = [bank for bank in range(8) if mask >> bank & 1]
+ if len(banks) <= 1 or length > len(banks) * 64:
+ raise _Bad
+ bank_bits = (len(banks) - 1).bit_length()
+ refs = []
+ used = set()
+ for _ in range(length):
+ index = reader.bits(bank_bits)
+ if index >= len(banks):
+ raise _Bad
+ used.add(index)
+ refs.append(banks[index] << 6 | reader.bits(6))
+ if len(used) != len(banks):
+ raise _Bad
+ return refs
+
+ # The block algorithms.
+
+ def block(
+ self,
+ width: int,
+ height: int,
+ algorithm: int,
+ scan: int,
+ *,
+ shared: list[int] | None = None,
+ background: int | None = None,
+ ) -> list[int]:
+ """Decode one block. Return its colours in the order of its scan.
+
+ Args:
+ width: The width of the block.
+ height: The height of the block.
+ algorithm: The block algorithm id, 0 to 15.
+ scan: The scan id, 0 to 3.
+ shared: The shared palette of a regions stream. A block that has a shared
+ palette does not read its own palette.
+ background: The background of the container. A block that has a background
+ uses it, and does not read its own background.
+ """
+ count = width * height
+ self.work -= count
+ if self.work < 0:
+ raise _Bad
+ reader = self.reader
+ profile = self.profile
+ if shared is not None and algorithm in _NO_SHARED_PALETTE:
+ raise _Bad
+ if algorithm == 0: # rawGlobal
+ return [reader.bits(profile.bits) for _ in range(count)]
+ if algorithm in _WITH_BACKGROUND:
+ if background is None:
+ background = self.background()
+ return self.with_background(count, algorithm, shared, background)
+ if algorithm in (10, 12): # directBitplanes, directRowDelta
+ if not (profile.grey or profile.table is not None):
+ raise _Bad
+ if algorithm == 10:
+ return self.adaptive_bitplanes(count, list(range(profile.size)))
+ return self.compact_row_delta(
+ count,
+ _row_length(scan, width, height),
+ profile.bits,
+ profile.size - 1,
+ residual=profile.grey,
+ )
+
+ palette = shared if shared is not None else self.palette()
+ bits = _local_bits(len(palette))
+ if algorithm == 1: # rawLocal
+ return _pick_all(palette, [reader.bits(bits) for _ in range(count)])
+ if algorithm in (2, 14): # compactRle, varUintRle
+ return self.rle(count, palette, varuint=algorithm == 14)
+ if algorithm == 6:
+ return self.lz_pixels(count, palette)
+ if algorithm == 7:
+ if scan != 0:
+ raise _Bad
+ return self.quadtree(width, height, palette)
+ if algorithm == 8:
+ return _pick_all(palette, self.bitplanes(count, bits))
+ if algorithm == 9:
+ return self.adaptive_bitplanes(count, palette)
+ row_length = _row_length(scan, width, height)
+ if algorithm == 13:
+ values = self.row_delta(count, row_length, bits, len(palette) - 1)
+ elif algorithm == 11:
+ values = self.compact_row_delta(
+ count, row_length, bits, len(palette) - 1, residual=False
+ )
+ else: # 5, rowRepeat
+ values = self.row_repeat(count, row_length, bits)
+ return _pick_all(palette, values)
+
+ def with_background(
+ self, count: int, algorithm: int, shared: list[int] | None, background: int
+ ) -> list[int]:
+ """Decode ``biColorMask`` (4), ``compactSparse`` (3), or ``varUintSparse`` (15).
+
+ With its own palette, a sparse block must not have the background in the palette.
+ With a shared palette, each segment must not use the background. A bicolour block
+ has one foreground colour: a colour id, or an index in the shared palette.
+ """
+ reader = self.reader
+ if algorithm == 4:
+ if shared is None:
+ foreground = reader.bits(self.profile.bits)
+ else:
+ foreground = _pick(shared, reader.bits(_local_bits(len(shared))))
+ if foreground == background:
+ raise _Bad
+ return [foreground if flag else background for flag in reader.flags(count)]
+
+ palette = shared
+ if palette is None:
+ palette = self.palette()
+ if background in palette:
+ raise _Bad
+ bits = _local_bits(len(palette))
+ varuint = algorithm == 15
+ refs = [background] * count
+ if varuint:
+ segments = reader.varuint()
+ if segments <= 0 or segments > count:
+ raise _Bad
+ else:
+ segments = reader.bounded(count - 1) + 1
+ position = 0
+ for _ in range(segments):
+ if varuint:
+ skip = reader.varuint()
+ if skip > count - position:
+ raise _Bad
+ position += skip
+ if position >= count:
+ raise _Bad
+ else:
+ if position >= count:
+ raise _Bad
+ position += reader.bounded(count - position - 1)
+ colour = _pick(palette, reader.bits(bits))
+ if colour == background:
+ raise _Bad
+ if varuint:
+ length = reader.varuint()
+ if length <= 0 or position + length > count:
+ raise _Bad
+ else:
+ length = reader.bounded(count - position - 1) + 1
+ refs[position : position + length] = [colour] * length
+ position += length
+ return refs
+
+ def rle(self, count: int, palette: list[int], *, varuint: bool) -> list[int]:
+ """Decode ``compactRle`` or ``varUintRle``: runs of one colour each."""
+ reader = self.reader
+ bits = _local_bits(len(palette))
+ refs: list[int] = []
+ while len(refs) < count:
+ colour = _pick(palette, reader.bits(bits))
+ if varuint:
+ length = reader.varuint()
+ if length <= 0 or len(refs) + length > count:
+ raise _Bad
+ else:
+ length = reader.bounded(count - len(refs) - 1) + 1
+ refs.extend([colour] * length)
+ return refs
+
+ def lz_pixels(self, count: int, palette: list[int]) -> list[int]:
+ """Decode ``lzPixels``: literal runs, and copies of earlier pixels (3 or more)."""
+ reader = self.reader
+ bits = _local_bits(len(palette))
+ refs: list[int] = []
+ while len(refs) < count:
+ done = len(refs)
+ if reader.bits(1):
+ remaining = count - done
+ if done == 0 or remaining < 3:
+ raise _Bad
+ distance = reader.range_compact(done - 1) + 1
+ length = reader.range_compact(remaining - 3) + 3
+ start = done - distance
+ if distance >= length:
+ refs.extend(refs[start : start + length])
+ else:
+ # The copy overlaps the pixels that it makes, so copy one at a time.
+ for index in range(start, start + length):
+ refs.append(refs[index])
+ else:
+ length = reader.range_compact(count - done - 1) + 1
+ refs.extend(_pick(palette, reader.bits(bits)) for _ in range(length))
+ return refs
+
+ def quadtree(self, width: int, height: int, palette: list[int]) -> list[int]:
+ """Decode ``quadtree``: a node is one colour, or it splits in two or four.
+
+ A node one pixel wide splits into a top and a bottom half. A node one pixel high
+ splits into a left and a right half. Other nodes split into four, in the order top
+ left, top right, bottom left, bottom right. The first half is the smaller one.
+ """
+ reader = self.reader
+ bits = _local_bits(len(palette))
+ refs = [palette[0]] * (width * height)
+
+ def node(x: int, y: int, w: int, h: int) -> None:
+ if reader.bits(1):
+ colour = _pick(palette, reader.bits(bits))
+ for row in range(y, y + h):
+ start = row * width + x
+ refs[start : start + w] = [colour] * w
+ return
+ if w == 1 and h == 1:
+ raise _Bad
+ if w == 1:
+ top = h // 2
+ node(x, y, 1, top)
+ node(x, y + top, 1, h - top)
+ elif h == 1:
+ left = w // 2
+ node(x, y, left, 1)
+ node(x + left, y, w - left, 1)
+ else:
+ left, top = w // 2, h // 2
+ node(x, y, left, top)
+ node(x + left, y, w - left, top)
+ node(x, y + top, left, h - top)
+ node(x + left, y + top, w - left, h - top)
+
+ node(0, 0, width, height)
+ return refs
+
+ def bitplanes(self, count: int, bits: int) -> list[int]:
+ """Decode ``bitplanes`` to local indices: each bit plane raw or in runs."""
+ reader = self.reader
+ values = [0] * count
+ for plane in range(bits):
+ mask = 1 << plane
+ if not reader.bits(1):
+ values = _set_flags(values, reader.flags(count), mask)
+ else:
+ self.plane_runs(values, count, mask, short=False)
+ return values
+
+ def adaptive_bitplanes(self, count: int, palette: list[int]) -> list[int]:
+ """Decode ``adaptiveBitplanes``. Each bit plane has a prefix that gives its form.
+
+ The prefixes, in the order of the data: 0 raw, 10 runs, 110 short runs, 11100 all
+ zero, 11110 all one, 11101 a list of the one bits, 11111 a list of the zero bits.
+ """
+ reader = self.reader
+ values = [0] * count
+ for plane in range(_local_bits(len(palette))):
+ mask = 1 << plane
+ if not reader.bits(1):
+ values = _set_flags(values, reader.flags(count), mask)
+ elif not reader.bits(1):
+ self.plane_runs(values, count, mask, short=False)
+ elif not reader.bits(1):
+ self.plane_runs(values, count, mask, short=True)
+ else:
+ form = reader.bits(2)
+ if form & 1: # all one, or all one and then a list of the zero bits
+ values = [value | mask for value in values]
+ if form & 2:
+ self.plane_positions(values, count, mask, set_bit=form == 2)
+ return _pick_all(palette, values)
+
+ def plane_runs(self, values: list[int], count: int, mask: int, *, short: bool) -> None:
+ """Read the runs of one bit plane. The bit value changes after each run."""
+ reader = self.reader
+ bit = reader.bits(1)
+ position = 0
+ while position < count:
+ remaining = count - position
+ length = self.short_run(remaining) if short else reader.range_compact(remaining - 1) + 1
+ if bit:
+ values[position : position + length] = [
+ value | mask for value in values[position : position + length]
+ ]
+ position += length
+ bit ^= 1
+
+ def short_run(self, remaining: int) -> int:
+ """The length of a short run: 0 is 1, 10 is 2, 110 is 3, 111 and a number is 4 or more."""
+ reader = self.reader
+ for length in (1, 2, 3):
+ if not reader.bits(1):
+ if length > remaining:
+ raise _Bad
+ return length
+ return reader.range_compact(remaining - 4) + 4
+
+ def plane_positions(self, values: list[int], count: int, mask: int, *, set_bit: bool) -> None:
+ """Read the list of positions of a sparse bit plane, and set or clear their bit."""
+ reader = self.reader
+ total = reader.range_compact(count - 1) + 1
+ previous = -1
+ for index in range(total):
+ later = total - index - 1
+ position = previous + reader.range_compact(count - previous - later - 2) + 1
+ if set_bit:
+ values[position] |= mask
+ else:
+ values[position] &= ~mask
+ previous = position
+
+ def row_repeat(self, count: int, row_length: int, bits: int) -> list[int]:
+ """Decode ``rowRepeat``: the first row, then each row is a copy (bit 1) or raw."""
+ reader = self.reader
+ values = [reader.bits(bits) for _ in range(row_length)]
+ for _ in range(count // row_length - 1):
+ if reader.bits(1):
+ values.extend(values[-row_length:])
+ else:
+ values.extend(reader.bits(bits) for _ in range(row_length))
+ return values
+
+ def row_delta(self, count: int, row_length: int, bits: int, maximum: int) -> list[int]:
+ """Decode ``rowDelta``: each row is raw, or a change of the predicted row.
+
+ Operations (2 bits): 0 raw, 1 repeat, 2 changes at listed positions, 3 extended.
+ Extended operations (2 bits): 0 a mask and a value for each set bit, 1 segments,
+ 2 a mask and one value for all set bits, 3 a run of repeated rows.
+ """
+ reader = self.reader
+ rows = count // row_length
+ virtual = bool(reader.bits(1))
+ shifts = bool(reader.bits(1))
+ values: list[int] = []
+
+ def value() -> int:
+ result = reader.bits(bits)
+ if result > maximum:
+ raise _Bad
+ return result
+
+ def predictor(row: int) -> int:
+ if not shifts:
+ return 0
+ return self.predictor(row, virtual)
+
+ if not virtual:
+ values.extend(value() for _ in range(row_length))
+ position_bits = (row_length - 1).bit_length()
+ while len(values) < count:
+ row = len(values) // row_length
+ op = reader.bits(2)
+ if op == 0:
+ values.extend(value() for _ in range(row_length))
+ continue
+ if op == 1:
+ values.extend(_predicted(values, row_length, row, 0, virtual))
+ continue
+ if op == 2:
+ current = _predicted(values, row_length, row, predictor(row), virtual)
+ changes = reader.bits(row_length.bit_length())
+ if changes > row_length:
+ raise _Bad
+ previous = -1
+ for _ in range(changes):
+ x = reader.bits(position_bits)
+ if x >= row_length or x <= previous:
+ raise _Bad
+ current[x] = value()
+ previous = x
+ values.extend(current)
+ continue
+ extended = reader.bits(2)
+ if extended == 3:
+ if row + 2 > rows:
+ raise _Bad
+ for _ in range(reader.range_compact(rows - row - 2) + 2):
+ values.extend(_predicted(values, row_length, row, 0, virtual))
+ row += 1
+ continue
+ current = _predicted(values, row_length, row, predictor(row), virtual)
+ if extended == 1:
+ segments = reader.bits(position_bits) + 1
+ previous_end = -1
+ for _ in range(segments):
+ start = reader.bits(position_bits)
+ length = reader.bits(position_bits) + 1
+ if start <= previous_end or start + length > row_length:
+ raise _Bad
+ for x in range(start, start + length):
+ current[x] = value()
+ previous_end = start + length - 1
+ else:
+ positions = [x for x, flag in enumerate(reader.flags(row_length)) if flag]
+ if not positions:
+ raise _Bad
+ shared = value() if extended == 2 else None
+ for x in positions:
+ current[x] = value() if shared is None else shared
+ values.extend(current)
+ return values
+
+ def compact_row_delta(
+ self, count: int, row_length: int, bits: int, maximum: int, *, residual: bool
+ ) -> list[int]:
+ """Decode ``compactRowDelta`` or ``directRowDelta``.
+
+ Operations (3 bits): 0 repeat, 1 raw, 2 changes at listed positions, 3 one value
+ at listed positions, 4 segments, 5 a trimmed mask, 6 a run of repeated rows, 7 the
+ predicted row with no change. A grey ``directRowDelta`` has ``residual``: then
+ operations 2 to 5 have one bit that selects values as differences from the
+ predicted row.
+
+ For operation 3 with differences, the value at the first position is the value at
+ all positions. The reference decoder does this.
+ """
+ reader = self.reader
+ rows = count // row_length
+ virtual = bool(reader.bits(1))
+ values: list[int] = []
+
+ def raw_value() -> int:
+ result = reader.bits(bits)
+ if result > maximum:
+ raise _Bad
+ return result
+
+ if not virtual:
+ values.extend(raw_value() for _ in range(row_length))
+ while len(values) < count:
+ row = len(values) // row_length
+ op = reader.bits(3)
+ if op in (0, 6):
+ repeats = 1 if op == 0 else reader.range_compact(rows - row - 2) + 2
+ for _ in range(repeats):
+ values.extend(_predicted(values, row_length, row, 0, virtual))
+ row += 1
+ continue
+ if op == 1:
+ values.extend(raw_value() for _ in range(row_length))
+ continue
+ guess = _predicted(values, row_length, row, self.predictor(row, virtual), virtual)
+ current = list(guess)
+ if op == 7:
+ values.extend(current)
+ continue
+ differences = residual and bool(reader.bits(1))
+
+ def changed(x: int, differences: bool = differences, guess: list[int] = guess) -> int:
+ if not differences:
+ return raw_value()
+ code = reader.compact() + 1
+ result = guess[x] + ((code + 1) // 2 if code % 2 else -(code // 2))
+ if result < 0 or result > maximum:
+ raise _Bad
+ return result
+
+ if op in (2, 3):
+ positions = self.change_positions(row_length)
+ if op == 3:
+ one = changed(positions[0])
+ for x in positions:
+ current[x] = one
+ else:
+ for x in positions:
+ current[x] = changed(x)
+ else:
+ positions = (
+ self.segment_positions(row_length)
+ if op == 4
+ else self.mask_positions(row_length)
+ )
+ for x in positions:
+ current[x] = changed(x)
+ values.extend(current)
+ return values
+
+ def predictor(self, row: int, virtual: bool) -> int:
+ """A row predictor: 0 is ``same``, 10 is ``left``, 11 is ``right``.
+
+ The first row on the virtual row of zeros permits only ``same``.
+ """
+ reader = self.reader
+ result = 0 if not reader.bits(1) else 1 + reader.bits(1)
+ if result and row == 0 and virtual:
+ raise _Bad
+ return result
+
+ def change_positions(self, row_length: int) -> list[int]:
+ """The positions of ``compactRowDelta`` operations 2 and 3: a count, then gaps."""
+ reader = self.reader
+ total = reader.range_compact(row_length - 1) + 1
+ positions = []
+ previous = -1
+ for index in range(total):
+ later = total - index - 1
+ previous += 1 + reader.range_compact(row_length - previous - later - 2)
+ positions.append(previous)
+ return positions
+
+ def segment_positions(self, row_length: int) -> list[int]:
+ """The positions of ``compactRowDelta`` operation 4: segments, each a gap and a length."""
+ reader = self.reader
+ total = reader.range_compact(row_length - 1) + 1
+ positions: list[int] = []
+ previous_end = 0
+ for index in range(total):
+ later = total - index - 1
+ start = previous_end + reader.range_compact(row_length - previous_end - later - 1)
+ length = reader.range_compact(row_length - start - later - 1) + 1
+ if start + length > row_length:
+ raise _Bad
+ positions.extend(range(start, start + length))
+ previous_end = start + length
+ return positions
+
+ def mask_positions(self, row_length: int) -> list[int]:
+ """The positions of ``compactRowDelta`` operation 5: a start, a span, and a mask."""
+ reader = self.reader
+ start = reader.range_compact(row_length - 1)
+ span = reader.range_compact(row_length - start - 1) + 1
+ positions = [start + offset for offset, flag in enumerate(reader.flags(span)) if flag]
+ if not positions:
+ raise _Bad
+ return positions
+
+
+def _predicted(
+ values: list[int], row_length: int, row: int, predictor: int, virtual: bool
+) -> list[int]:
+ """The predicted row: the previous row, moved one place left or right with wrap.
+
+ ``left[x]`` is ``previous[x - 1]``, and ``right[x]`` is ``previous[x + 1]``. Row 0 on a
+ virtual base has only zeros before it.
+ """
+ if row == 0 and virtual:
+ return [0] * row_length
+ previous = values[(row - 1) * row_length : row * row_length]
+ if predictor == 1:
+ return previous[-1:] + previous[:-1]
+ if predictor == 2:
+ return previous[1:] + previous[:1]
+ return previous
+
+
+def _set_flags(values: list[int], flags: list[bool], mask: int) -> list[int]:
+ """Set the ``mask`` bit in each value whose flag is set."""
+ return [value | mask if flag else value for value, flag in zip(values, flags, strict=True)]
+
+
+def _paste(refs: list[int], width: int, box: tuple[int, int, int, int], block: list[int]) -> None:
+ """Copy a row-major block into the image at its rectangle."""
+ x, y, w, h = box
+ for row in range(h):
+ start = (y + row) * width + x
+ refs[start : start + w] = block[row * w : (row + 1) * w]
diff --git a/meshterm/core/mcoimg_palettes.py b/meshterm/core/mcoimg_palettes.py
new file mode 100644
index 0000000..1523d89
--- /dev/null
+++ b/meshterm/core/mcoimg_palettes.py
@@ -0,0 +1,279 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The colour tables of the MCOimg palette profiles.
+
+This module is data for interoperability, and has no code. A script made it from the
+files ``lib/helpers/mcoimg_palette.dart`` and ``lib/helpers/mcoimg_dynamic_palettes.dart``
+of the meshcore-open repository (HDDen/meshcore-open, a fork of zjs81/meshcore-open, MIT).
+Do not edit the values by hand. A different value changes the colour of a pixel.
+
+- The fixed profiles are tuples of (red, green, blue), in the order of the colour ids.
+- ``GLOBAL_512`` is the dynamic global palette of 512 colours.
+- Each ``DYNAMIC_n`` tuple gives the index in ``GLOBAL_512`` of each colour id of the
+ dynamic profile of n colours.
+"""
+
+from __future__ import annotations
+
+# The tables keep several values on each line, so the formatter must not change them.
+# fmt: off
+
+MONO: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (0, 0, 0),
+)
+
+MASTER_4: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (192, 192, 192), (86, 86, 86), (0, 0, 0),
+)
+
+MASTER_8: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (141, 141, 141), (0, 0, 0), (254, 36, 0), (241, 209, 0),
+ (71, 192, 0), (61, 105, 255), (121, 0, 255),
+)
+
+MASTER_16: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (164, 164, 164), (0, 0, 0), (209, 30, 1), (98, 14, 1),
+ (255, 132, 0), (123, 64, 0), (241, 209, 0), (144, 124, 2), (65, 176, 0),
+ (40, 110, 0), (127, 220, 255), (0, 58, 255), (0, 34, 150), (106, 0, 227),
+ (47, 0, 100),
+)
+
+MASTER_32: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (179, 179, 179), (102, 102, 102), (0, 0, 0), (255, 176, 163),
+ (255, 85, 65), (254, 36, 0), (98, 14, 1), (255, 179, 99), (255, 132, 0),
+ (197, 102, 1), (142, 73, 0), (245, 222, 91), (241, 209, 0), (181, 157, 2),
+ (120, 105, 2), (149, 218, 118), (71, 192, 0), (40, 110, 0), (29, 79, 0),
+ (196, 241, 255), (1, 195, 255), (3, 141, 184), (1, 109, 143), (117, 150, 255),
+ (0, 58, 255), (2, 46, 202), (0, 34, 150), (215, 178, 255), (178, 135, 255),
+ (133, 61, 255), (47, 0, 100),
+)
+
+MASTER_64: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (217, 217, 217), (179, 179, 179), (138, 139, 138), (111, 111, 111),
+ (79, 79, 79), (36, 36, 36), (0, 0, 0), (255, 176, 163), (255, 154, 137),
+ (255, 85, 65), (254, 36, 0), (209, 30, 1), (145, 21, 0), (98, 14, 1),
+ (69, 10, 0), (255, 179, 99), (255, 168, 85), (255, 147, 51), (255, 132, 0),
+ (228, 118, 1), (197, 102, 1), (142, 73, 0), (123, 64, 0), (247, 229, 114),
+ (245, 222, 91), (241, 209, 0), (223, 193, 2), (203, 177, 1), (181, 157, 2),
+ (144, 124, 2), (120, 105, 2), (183, 230, 155), (149, 218, 118), (109, 205, 75),
+ (71, 192, 0), (65, 176, 0), (54, 148, 1), (40, 110, 0), (29, 79, 0),
+ (196, 241, 255), (171, 233, 255), (127, 220, 255), (1, 195, 255), (0, 182, 238),
+ (1, 170, 223), (3, 141, 184), (1, 109, 143), (145, 170, 255), (117, 150, 255),
+ (59, 100, 255), (0, 58, 255), (2, 51, 225), (2, 46, 202), (1, 40, 176),
+ (0, 34, 150), (215, 178, 255), (178, 135, 255), (154, 101, 255), (133, 61, 255),
+ (121, 0, 255), (105, 2, 221), (83, 1, 175), (47, 0, 100),
+)
+
+GREY_16: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (238, 238, 238), (221, 221, 221), (204, 204, 204), (187, 187, 187),
+ (170, 170, 170), (153, 153, 153), (136, 136, 136), (119, 119, 119), (102, 102, 102),
+ (85, 85, 85), (68, 68, 68), (51, 51, 51), (34, 34, 34), (17, 17, 17),
+ (0, 0, 0),
+)
+
+GREY_32: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (247, 247, 247), (239, 239, 239), (230, 230, 230), (222, 222, 222),
+ (214, 214, 214), (206, 206, 206), (197, 197, 197), (189, 189, 189), (181, 181, 181),
+ (173, 173, 173), (165, 165, 165), (156, 156, 156), (148, 148, 148), (140, 140, 140),
+ (132, 132, 132), (123, 123, 123), (115, 115, 115), (107, 107, 107), (99, 99, 99),
+ (90, 90, 90), (82, 82, 82), (74, 74, 74), (66, 66, 66), (57, 57, 57),
+ (49, 49, 49), (41, 41, 41), (33, 33, 33), (24, 24, 24), (16, 16, 16),
+ (8, 8, 8), (0, 0, 0),
+)
+
+GREY_8: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (219, 219, 219), (182, 182, 182), (145, 145, 145), (109, 109, 109),
+ (72, 72, 72), (36, 36, 36), (0, 0, 0),
+)
+
+GLOBAL_512: tuple[tuple[int, int, int], ...] = (
+ (255, 255, 255), (241, 211, 179), (215, 174, 131), (187, 135, 93), (155, 99, 62),
+ (124, 73, 45), (94, 51, 31), (65, 33, 22), (37, 17, 11), (217, 217, 217),
+ (255, 237, 229), (255, 229, 211), (255, 216, 198), (248, 204, 191), (244, 191, 165),
+ (235, 184, 143), (224, 169, 132), (210, 151, 123), (179, 179, 179), (255, 214, 224),
+ (255, 220, 200), (255, 242, 184), (205, 236, 207), (201, 238, 240), (206, 221, 250),
+ (224, 210, 244), (234, 207, 227), (138, 139, 138), (228, 224, 174), (202, 199, 131),
+ (170, 169, 95), (137, 139, 67), (109, 113, 52), (83, 86, 41), (58, 60, 30),
+ (35, 36, 22), (111, 111, 111), (255, 241, 184), (255, 224, 138), (244, 201, 93),
+ (221, 175, 55), (196, 147, 36), (157, 113, 24), (116, 80, 15), (73, 48, 8),
+ (79, 79, 79), (185, 243, 232), (130, 221, 207), (78, 195, 181), (39, 164, 151),
+ (22, 132, 121), (14, 99, 92), (8, 68, 63), (3, 38, 34), (36, 36, 36),
+ (244, 192, 168), (231, 155, 124), (212, 118, 87), (185, 86, 62), (150, 61, 45),
+ (114, 43, 34), (79, 28, 24), (43, 14, 13), (0, 0, 0), (255, 176, 163),
+ (250, 243, 232), (239, 227, 210), (226, 209, 185), (211, 191, 162), (194, 169, 135),
+ (170, 144, 111), (141, 118, 92), (111, 92, 73), (255, 154, 137), (255, 224, 194),
+ (244, 194, 159), (223, 165, 126), (200, 137, 98), (170, 107, 73), (130, 80, 58),
+ (91, 53, 42), (53, 32, 27), (255, 85, 65), (141, 141, 141), (164, 164, 164),
+ (102, 102, 102), (255, 63, 36), (254, 58, 29), (254, 52, 22), (254, 47, 14),
+ (254, 41, 7), (254, 36, 0), (249, 35, 0), (244, 35, 0), (239, 34, 0),
+ (234, 33, 0), (229, 33, 1), (224, 32, 1), (219, 31, 1), (214, 31, 1),
+ (209, 30, 1), (202, 29, 1), (195, 28, 1), (188, 27, 1), (181, 26, 1),
+ (173, 25, 0), (166, 24, 0), (159, 23, 0), (152, 22, 0), (145, 21, 0),
+ (140, 20, 0), (135, 19, 0), (129, 19, 0), (124, 18, 0), (119, 17, 1),
+ (114, 16, 1), (108, 16, 1), (103, 15, 1), (98, 14, 1), (95, 14, 1),
+ (92, 13, 1), (88, 13, 1), (85, 12, 1), (82, 12, 0), (79, 11, 0),
+ (75, 11, 0), (72, 10, 0), (69, 10, 0), (255, 179, 99), (255, 178, 97),
+ (255, 177, 96), (255, 175, 94), (255, 174, 93), (255, 173, 91), (255, 172, 90),
+ (255, 170, 88), (255, 169, 87), (255, 168, 85), (255, 166, 81), (255, 163, 77),
+ (255, 161, 74), (255, 159, 70), (255, 156, 66), (255, 154, 62), (255, 152, 59),
+ (255, 149, 55), (255, 147, 51), (255, 145, 45), (255, 144, 40), (255, 142, 34),
+ (255, 140, 28), (255, 139, 23), (255, 137, 17), (255, 135, 11), (255, 134, 6),
+ (255, 132, 0), (252, 130, 0), (249, 129, 0), (246, 127, 0), (243, 126, 0),
+ (240, 124, 1), (237, 123, 1), (234, 121, 1), (231, 120, 1), (228, 118, 1),
+ (225, 116, 1), (221, 114, 1), (218, 113, 1), (214, 111, 1), (211, 109, 1),
+ (207, 107, 1), (204, 106, 1), (200, 104, 1), (197, 102, 1), (191, 99, 1),
+ (185, 96, 1), (179, 92, 1), (173, 89, 1), (166, 86, 0), (160, 83, 0),
+ (154, 79, 0), (148, 76, 0), (142, 73, 0), (140, 72, 0), (138, 71, 0),
+ (136, 70, 0), (134, 69, 0), (131, 68, 0), (129, 67, 0), (127, 66, 0),
+ (125, 65, 0), (123, 64, 0), (247, 229, 114), (247, 228, 111), (247, 227, 109),
+ (246, 227, 106), (246, 226, 104), (246, 225, 101), (246, 224, 99), (245, 224, 96),
+ (245, 223, 94), (245, 222, 91), (245, 221, 81), (244, 219, 71), (244, 218, 61),
+ (243, 216, 51), (243, 215, 40), (242, 213, 30), (242, 212, 20), (241, 210, 10),
+ (241, 209, 0), (239, 207, 0), (237, 205, 0), (235, 204, 1), (233, 202, 1),
+ (231, 200, 1), (229, 198, 1), (227, 197, 2), (225, 195, 2), (223, 193, 2),
+ (221, 191, 2), (219, 189, 2), (216, 188, 2), (214, 186, 2), (212, 184, 1),
+ (210, 182, 1), (207, 181, 1), (205, 179, 1), (203, 177, 1), (201, 175, 1),
+ (198, 173, 1), (196, 170, 1), (193, 168, 1), (191, 166, 2), (188, 164, 2),
+ (186, 161, 2), (183, 159, 2), (181, 157, 2), (177, 153, 2), (173, 150, 2),
+ (169, 146, 2), (165, 142, 2), (160, 139, 2), (156, 135, 2), (152, 131, 2),
+ (148, 128, 2), (144, 124, 2), (141, 122, 2), (139, 120, 2), (136, 118, 2),
+ (133, 116, 2), (131, 113, 2), (128, 111, 2), (125, 109, 2), (123, 107, 2),
+ (120, 105, 2), (183, 230, 155), (179, 229, 151), (175, 227, 147), (172, 226, 143),
+ (168, 225, 139), (164, 223, 134), (160, 222, 130), (157, 221, 126), (153, 219, 122),
+ (149, 218, 118), (145, 217, 113), (140, 215, 108), (136, 214, 104), (131, 212, 99),
+ (127, 211, 94), (122, 209, 89), (118, 208, 85), (113, 206, 80), (109, 205, 75),
+ (105, 204, 67), (101, 202, 58), (96, 201, 50), (92, 199, 42), (88, 198, 33),
+ (84, 196, 25), (79, 195, 17), (75, 193, 8), (71, 192, 0), (70, 190, 0),
+ (70, 188, 0), (69, 187, 0), (68, 185, 0), (68, 183, 0), (67, 181, 0),
+ (66, 180, 0), (66, 178, 0), (65, 176, 0), (64, 173, 0), (63, 170, 0),
+ (61, 167, 0), (60, 164, 0), (59, 160, 1), (58, 157, 1), (56, 154, 1),
+ (55, 151, 1), (54, 148, 1), (52, 144, 1), (51, 140, 1), (49, 135, 1),
+ (48, 131, 1), (46, 127, 0), (45, 123, 0), (43, 118, 0), (42, 114, 0),
+ (40, 110, 0), (39, 107, 0), (38, 103, 0), (36, 100, 0), (35, 96, 0),
+ (34, 93, 0), (33, 89, 0), (31, 86, 0), (30, 82, 0), (29, 79, 0),
+ (196, 241, 255), (193, 240, 255), (190, 239, 255), (188, 238, 255), (185, 237, 255),
+ (182, 237, 255), (179, 236, 255), (177, 235, 255), (174, 234, 255), (171, 233, 255),
+ (166, 232, 255), (161, 230, 255), (156, 229, 255), (151, 227, 255), (147, 226, 255),
+ (142, 224, 255), (137, 223, 255), (132, 221, 255), (127, 220, 255), (113, 217, 255),
+ (99, 214, 255), (85, 212, 255), (71, 209, 255), (57, 206, 255), (43, 203, 255),
+ (29, 201, 255), (15, 198, 255), (1, 195, 255), (1, 194, 253), (1, 192, 251),
+ (1, 191, 249), (1, 189, 247), (0, 188, 246), (0, 186, 244), (0, 185, 242),
+ (0, 183, 240), (0, 182, 238), (0, 181, 236), (0, 179, 235), (0, 178, 233),
+ (0, 177, 231), (1, 175, 230), (1, 174, 228), (1, 173, 226), (1, 171, 225),
+ (1, 170, 223), (1, 167, 219), (1, 164, 214), (2, 160, 210), (2, 157, 206),
+ (2, 154, 201), (2, 151, 197), (3, 147, 193), (3, 144, 188), (3, 141, 184),
+ (3, 137, 179), (3, 134, 175), (2, 130, 170), (2, 127, 166), (2, 123, 161),
+ (2, 120, 157), (1, 116, 152), (1, 113, 148), (1, 109, 143), (145, 170, 255),
+ (142, 168, 255), (139, 166, 255), (136, 163, 255), (133, 161, 255), (129, 159, 255),
+ (126, 157, 255), (123, 154, 255), (120, 152, 255), (117, 150, 255), (111, 144, 255),
+ (104, 139, 255), (98, 133, 255), (91, 128, 255), (85, 122, 255), (78, 117, 255),
+ (72, 111, 255), (61, 105, 255), (59, 100, 255), (52, 95, 255), (46, 91, 255),
+ (39, 86, 255), (33, 81, 255), (26, 77, 255), (20, 72, 255), (13, 67, 255),
+ (7, 63, 255), (0, 58, 255), (0, 57, 252), (0, 56, 248), (1, 56, 245),
+ (1, 55, 242), (1, 54, 238), (1, 53, 235), (2, 53, 232), (2, 52, 228),
+ (2, 51, 225), (2, 50, 222), (2, 50, 220), (2, 49, 217), (2, 49, 215),
+ (2, 48, 212), (2, 48, 210), (2, 47, 207), (2, 47, 205), (2, 46, 202),
+ (2, 45, 199), (2, 45, 196), (2, 44, 193), (2, 43, 190), (1, 43, 188),
+ (1, 42, 185), (1, 41, 182), (1, 41, 179), (1, 40, 176), (1, 39, 173),
+ (1, 39, 170), (1, 38, 167), (1, 37, 164), (0, 37, 162), (0, 36, 159),
+ (0, 35, 156), (0, 35, 153), (0, 34, 150), (215, 178, 255), (211, 173, 255),
+ (207, 168, 255), (203, 164, 255), (199, 159, 255), (194, 154, 255), (190, 149, 255),
+ (186, 145, 255), (182, 140, 255), (178, 135, 255), (175, 131, 255), (173, 127, 255),
+ (170, 124, 255), (167, 120, 255), (165, 116, 255), (162, 112, 255), (159, 109, 255),
+ (157, 105, 255), (154, 101, 255), (152, 97, 255), (149, 92, 255), (147, 88, 255),
+ (145, 83, 255), (142, 79, 255), (140, 74, 255), (138, 70, 255), (135, 65, 255),
+ (133, 61, 255), (132, 54, 255), (130, 47, 255), (129, 41, 255), (128, 34, 255),
+ (126, 27, 255), (125, 20, 255), (124, 14, 255), (122, 7, 255), (121, 0, 255),
+ (119, 0, 251), (117, 0, 247), (116, 1, 244), (114, 1, 240), (112, 1, 236),
+ (110, 1, 232), (109, 2, 229), (106, 0, 227), (105, 2, 221), (103, 2, 216),
+ (100, 2, 211), (98, 2, 206), (95, 2, 201), (93, 1, 195), (90, 1, 190),
+ (88, 1, 185), (85, 1, 180), (83, 1, 175), (79, 1, 167), (75, 1, 158),
+ (71, 1, 150), (67, 1, 142), (63, 0, 133), (59, 0, 125), (55, 0, 117),
+ (51, 0, 108), (47, 0, 100),
+)
+
+DYNAMIC_8: tuple[int, ...] = (
+ 0, 83, 63, 91, 210, 283, 401, 484,
+)
+
+DYNAMIC_16: tuple[int, ...] = (
+ 0, 84, 63, 100, 118, 155, 191, 210, 246, 292, 310, 338, 411, 447, 492, 511,
+)
+
+DYNAMIC_32: tuple[int, ...] = (
+ 0, 18, 85, 63, 64, 82, 91, 118, 128, 155, 173, 182, 201, 210, 237, 255,
+ 265, 283, 310, 319, 320, 347, 374, 383, 393, 411, 429, 447, 448, 457, 475, 511,
+)
+
+DYNAMIC_64: tuple[int, ...] = (
+ 0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, 100, 109, 118, 127,
+ 128, 137, 146, 155, 164, 173, 182, 191, 192, 201, 210, 219, 228, 237, 246, 255,
+ 256, 265, 274, 283, 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383,
+ 384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, 484, 493, 502, 511,
+)
+
+DYNAMIC_128: tuple[int, ...] = (
+ 0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, 100, 109, 118, 127,
+ 128, 137, 146, 155, 164, 173, 182, 191, 192, 201, 210, 219, 228, 237, 246, 255,
+ 256, 265, 274, 283, 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383,
+ 384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, 484, 493, 502, 511,
+ 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17,
+ 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35,
+ 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53,
+ 55, 56, 57, 58, 59, 60, 61, 62, 65, 66, 67, 68, 69, 70, 71, 72,
+)
+
+DYNAMIC_256: tuple[int, ...] = (
+ 0, 9, 18, 27, 36, 45, 54, 63, 64, 73, 82, 91, 100, 109, 118, 127,
+ 128, 137, 146, 155, 164, 173, 182, 191, 192, 201, 210, 219, 228, 237, 246, 255,
+ 256, 265, 274, 283, 292, 301, 310, 319, 320, 329, 338, 347, 356, 365, 374, 383,
+ 384, 393, 402, 411, 420, 429, 438, 447, 448, 457, 466, 475, 484, 493, 502, 511,
+ 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17,
+ 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35,
+ 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53,
+ 55, 56, 57, 58, 59, 60, 61, 62, 65, 66, 67, 68, 69, 70, 71, 72,
+ 74, 75, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 87, 88, 89, 90,
+ 92, 93, 94, 95, 96, 97, 98, 99, 101, 102, 103, 104, 105, 106, 107, 108,
+ 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 121, 122, 123, 124, 125, 126,
+ 129, 130, 131, 132, 133, 134, 135, 136, 138, 139, 140, 141, 142, 143, 144, 145,
+ 147, 148, 149, 150, 151, 152, 153, 154, 156, 157, 158, 159, 160, 161, 162, 163,
+ 165, 166, 167, 168, 169, 170, 171, 172, 174, 175, 176, 177, 178, 179, 180, 181,
+ 183, 184, 185, 186, 187, 188, 189, 190, 193, 194, 195, 196, 197, 198, 199, 200,
+ 202, 203, 204, 205, 206, 207, 208, 209, 211, 212, 213, 214, 215, 216, 217, 218,
+)
+
+DYNAMIC_512: tuple[int, ...] = (
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
+ 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
+ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
+ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
+ 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127,
+ 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
+ 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
+ 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175,
+ 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
+ 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207,
+ 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223,
+ 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
+ 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
+ 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271,
+ 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287,
+ 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303,
+ 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319,
+ 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335,
+ 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351,
+ 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367,
+ 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383,
+ 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399,
+ 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415,
+ 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431,
+ 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447,
+ 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463,
+ 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479,
+ 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495,
+ 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511,
+)
+
+# fmt: on
diff --git a/meshterm/core/models.py b/meshterm/core/models.py
index c93e9d2..0e185fb 100644
--- a/meshterm/core/models.py
+++ b/meshterm/core/models.py
@@ -917,6 +917,9 @@ class Conversation:
secret: For channels: the 16-byte secret of the channel. MeshTerm uses it only to
show the public or private mark of the channel. ``None`` when it is not known.
contact: The contact, for direct conversations and rooms.
+ on_device: For channels: ``False`` when the device has no such channel. The Chat
+ picker shows the Public channel in this state when no slot has it. The row is
+ an offer to add the channel, and it never opens a chat.
"""
label: str
@@ -925,6 +928,7 @@ class Conversation:
channel_id: str | None = None
secret: bytes | None = None
contact: Contact | None = None
+ on_device: bool = True
@property
def peer(self) -> str | None:
diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py
index 20b3ebb..206aec9 100644
--- a/meshterm/core/preferences.py
+++ b/meshterm/core/preferences.py
@@ -623,6 +623,17 @@ PREFERENCES: tuple[PrefSpec, ...] = (
maximum=86400,
unit="s",
),
+ PrefSpec(
+ key="show_mcoimg",
+ label="Show MCOimg",
+ help="Draw the pixel images of messages. Off: ^U shows one",
+ group="Display",
+ value_type="bool",
+ # On: a pixel image (MCOimg) is what its sender wanted the channel to see. Off: the
+ # chat shows only the line about the image, and ^U on the picked message opens it
+ # (JP, 2026-11-19). A 30 x 30 image takes 15 rows of the transcript.
+ default=True,
+ ),
PrefSpec(
key="clock_report_days",
label="Clock report",
diff --git a/meshterm/demo/history.py b/meshterm/demo/history.py
index 9e315bd..8953fcd 100644
--- a/meshterm/demo/history.py
+++ b/meshterm/demo/history.py
@@ -49,6 +49,13 @@ TX_POWER = 22
#: The map viewport that the demo opens on: the island of Montréal, with the two shores.
MAP_VIEW = (45.5150, -73.5900, 10)
+#: The channel slots whose history draws from the one source of chance of the history. A
+#: channel in a later slot draws from a source of its own, seeded by its name. Thus a
+#: channel added to the demo never changes the rest of it: the shared source gives the same
+#: numbers to everything after the conversations (the traces, the neighbours), and the
+#: video's trace to Brossard keeps the route that it was made for.
+_SHARED_SLOTS = 4
+
def seed(repo: Repository, now: datetime) -> None:
"""Write the full history of the demo into ``repo``.
@@ -128,8 +135,13 @@ def _conversations(
"""
messages: list[ChatMessage] = []
heard: list[traffic.Heard] = _greetings(rng)
+ shared = rng
for channel in world.CHANNELS:
identity = channel_identity(channel.name, channel.secret)
+ if channel.slot < _SHARED_SLOTS:
+ rng = shared
+ else:
+ rng = random.Random(f"meshterm-demo/history/{channel.name}")
for line in script.CHANNEL_LINES.get(channel.name, ()):
offset = -line.age_min * 60.0
sender = world.node(line.sender)
@@ -165,6 +177,7 @@ def _conversations(
created_at=when,
)
)
+ rng = shared
for peer_name, lines in script.DIRECT_LINES.items():
peer = world.node(peer_name)
for line in lines:
@@ -242,26 +255,55 @@ def _greetings(rng: random.Random) -> list[traffic.Heard]:
spoke a few minutes ago was also heard a few minutes ago, and the lists show it as
recent. The function adds one advert before the first line of each sitting in the last
two days (a sitting is a run of lines less than an hour apart).
+
+ The lines of the channels in the shared slots and of the direct messages draw from
+ ``rng``, as they always did. The lines of a later channel come in a second pass, with a
+ source of their own (refer to :data:`_SHARED_SLOTS`). Thus a channel added to the demo
+ does not change the adverts, or anything after them, of the rest of the history.
"""
- lines = [
- line
- for group in (script.CHANNEL_LINES, script.DIRECT_LINES)
- for conversation in group.values()
- for line in conversation
- if line.sender != script.ME and line.age_min < 2 * 1440
- ]
+ slots = {channel.name: channel.slot for channel in world.CHANNELS}
+
+ def recent(conversations) -> list: # noqa: ANN001 - the values of a dict of lines
+ return [
+ line
+ for conversation in conversations
+ for line in conversation
+ if line.sender != script.ME and line.age_min < 2 * 1440
+ ]
+
+ shared = recent(
+ [
+ lines
+ for name, lines in script.CHANNEL_LINES.items()
+ if slots.get(name, _SHARED_SLOTS) < _SHARED_SLOTS
+ ]
+ + list(script.DIRECT_LINES.values())
+ )
+ later = recent(
+ [
+ lines
+ for name, lines in script.CHANNEL_LINES.items()
+ if slots.get(name, _SHARED_SLOTS) >= _SHARED_SLOTS
+ ]
+ )
last_advert: dict[str, float] = {}
heard: list[traffic.Heard] = []
- for line in sorted(lines, key=lambda line: -line.age_min):
- offset = -line.age_min * 60.0
- if offset - last_advert.get(line.sender, -1e12) < 3600.0:
- continue
- sender = world.node(line.sender)
- moment = offset - rng.uniform(60.0, 900.0)
- heard.extend(
- traffic.heard_flood(sender, moment, traffic.advert_body(sender), rng, advert=True)
- )
- last_advert[line.sender] = offset
+ for lines, source in (
+ (shared, rng),
+ (later, random.Random("meshterm-demo/history/greetings")),
+ ):
+ for line in sorted(lines, key=lambda line: -line.age_min):
+ offset = -line.age_min * 60.0
+ if abs(offset - last_advert.get(line.sender, -1e12)) < 3600.0:
+ continue
+ sender = world.node(line.sender)
+ moment = offset - source.uniform(60.0, 900.0)
+ heard.extend(
+ traffic.heard_flood(
+ sender, moment, traffic.advert_body(sender), source, advert=True
+ )
+ )
+ last_advert[line.sender] = offset
return heard
diff --git a/meshterm/demo/script.py b/meshterm/demo/script.py
index 7a97bdd..38be42c 100644
--- a/meshterm/demo/script.py
+++ b/meshterm/demo/script.py
@@ -64,6 +64,19 @@ class Line:
#: The sender name of our own lines.
ME = SELF.name
+#: The pixel images (MCOimg) of the ``#mcoimg`` channel. The woodpecker is a real image
+#: from an MCOimg encoder (30 x 30, 74 bytes). The leaf and the smiley are not compressed:
+#: the small encoder of ``tests/test_mcoimg.py`` made them.
+WOODPECKER = (
+ 'im3:J!jBVY"9UPkugAX54#9BX:e"FM|cL0G|IS.@$q^=N:4D*B9d1d$450M>W/tOqmq`wqd..bJp|}'
+ "d/4v2vpi5BAZ9wD/B"
+)
+MAPLE_LEAF = (
+ 'im3:g/U"eLAAAAAAAAC"BAAAAA5JAAAA_98(AA|;umiCv(umb$1I~lb$O=2AB=0maToIumb$8(umb$O=:EY'
+ "$O=0mDAumb$NAAAumbAAAAAYAAAAA@QAAAAAAAAAAA"
+)
+SMILEY = 'im3:g/U"aLdZSA%ZpL[c%Z>M5wqOW0Dz9Z3BfzEA'
+
#: The channel conversations, by channel name, oldest line first.
CHANNEL_LINES: dict[str, tuple[Line, ...]] = {
"Public": (
@@ -227,6 +240,15 @@ CHANNEL_LINES: dict[str, tuple[Line, ...]] = {
Line(at(0, "08:15"), "Léa", "It's 2 degrees this morning, dress warm!"),
Line(at(0, "08:18"), ME, "Too late, I'm already outside 🥶"),
),
+ "#mcoimg": (
+ Line(at(2, "19:05"), "Noor", "Is this the channel for the pixel art?"),
+ Line(at(2, "19:09"), "Kim-NDG", "Yes! Images go here, so that Public stays readable"),
+ Line(at(0, "08:50"), ME, MAPLE_LEAF),
+ Line(at(0, "09:10"), "Marie-Ève", "Nice leaf 🍁"),
+ Line(at(0, "10:20"), "Noor", SMILEY),
+ Line(at(0, "11:05"), "Kim-NDG", "Pileated woodpecker on Mont-Royal this morning!"),
+ Line(at(0, "11:06"), "Kim-NDG", WOODPECKER),
+ ),
}
#: The direct conversations, by the name of the other node, oldest line first.
diff --git a/meshterm/demo/world.py b/meshterm/demo/world.py
index c3d51ce..a98d293 100644
--- a/meshterm/demo/world.py
+++ b/meshterm/demo/world.py
@@ -610,12 +610,14 @@ class Channel:
#: The channels of the demo device. ``Family`` is a private channel, with a fixed secret
-#: that is not derived from its name.
+#: that is not derived from its name. ``#mcoimg`` carries pixel images (MCOimg), so that
+#: the screenshots can show how the chat draws them.
CHANNELS: tuple[Channel, ...] = (
Channel(0, "Public", DEFAULT_PUBLIC_SECRET),
Channel(1, "#montreal", derive_secret("#montreal"), scope="yul"),
Channel(2, "#cycling", derive_secret("#cycling")),
Channel(3, "Family", hashlib.sha256(b"meshterm-demo/Family").digest()[:16]),
+ Channel(4, "#mcoimg", derive_secret("#mcoimg")),
)
#: Hashtag channels that other people of the mesh use and our device does not have. Our
diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py
index 30000cd..3f6c268 100644
--- a/meshterm/tools/chat.py
+++ b/meshterm/tools/chat.py
@@ -27,7 +27,7 @@ from rich.cells import cell_len
from rich.text import Text
from ..context import AppContext
-from ..core import exitcodes, reactions
+from ..core import exitcodes, mcoimg, reactions
from ..core.channels import (
CHANNEL_SLOT_PROBE_CAP,
DEFAULT_PUBLIC_SECRET,
@@ -71,6 +71,7 @@ from ..ui.widgets import (
format_age,
mention_chip,
mention_mark,
+ pixel_image_text,
self_chip,
)
from .base import Tool, ToolResult, register
@@ -177,6 +178,14 @@ class ChatTool(Tool):
await self._delete_history(ctx, choice.value)
elif choice is CANCEL or choice is None: # Esc: back to the menu
return ToolResult(summary={"conversations": opened, "messages": shown})
+ elif not choice.on_device:
+ # A channel that the device does not have never opens: the device
+ # refuses each send on it. Enter asks to add it. After a refusal, the
+ # picker stays.
+ added = await _add_public_channel(ctx)
+ if added is not None:
+ shown = await open_chat(ctx, added)
+ opened += 1
else:
shown = await open_chat(ctx, choice)
opened += 1
@@ -623,23 +632,26 @@ def _enable_receive_debug() -> None:
def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]:
- """Change cached channel slots into channel conversations, and always offer Public (slot 0).
+ """Change cached channel slots into channel conversations, and offer Public if it is absent.
The picker reads its channels through the session cache
(:meth:`~meshterm.services.device_state.DeviceState.channel_slots`). Thus it uses the one
slow slot probe again, and does not read each slot again each time that Chat opens.
This function maps that cached :class:`~meshterm.core.channel_probe.ChannelSlot` list
- onto the :class:`~meshterm.core.models.Conversation` rows of the picker. When the
- firmware reports no slot for channel 0 (the default public channel), this function
- makes one. Thus there is always a place to chat. :func:`_read_channels` (the CLI path)
- gives the same guarantee.
+ onto the :class:`~meshterm.core.models.Conversation` rows of the picker.
+
+ When slot 0 is empty and no slot has the Public channel, this function adds a Public row
+ with ``on_device=False``. The device cannot send on a slot that it does not have: it
+ refuses the send. Thus that row never opens a chat. It is an offer: Enter asks to add
+ Public to slot 0 (refer to :func:`_add_public_channel`). Issue #36 was a row that looked
+ the same as a real channel and failed on each send.
Args:
slots: The configured channel slots, from the session cache.
Returns:
- One :class:`~meshterm.core.models.Conversation` for each slot, with Public at the
- start when slot 0 is absent.
+ One :class:`~meshterm.core.models.Conversation` for each slot. A Public offer is at
+ the start when the device has no Public channel and slot 0 is empty.
"""
conversations = [
Conversation(
@@ -651,7 +663,9 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]:
)
for slot in slots
]
- if not any(c.channel_idx == 0 for c in conversations):
+ if not any(c.channel_idx == 0 for c in conversations) and not any(
+ slot.secret == DEFAULT_PUBLIC_SECRET for slot in slots
+ ):
conversations.insert(
0,
Conversation(
@@ -660,23 +674,60 @@ def _channels_from_slots(slots: list[ChannelSlot]) -> list[Conversation]:
channel_idx=0,
channel_id="slot:0",
secret=DEFAULT_PUBLIC_SECRET,
+ on_device=False,
),
)
return conversations
+async def _add_public_channel(ctx: AppContext) -> Conversation | None:
+ """Ask to add the Public channel to slot 0. Write it if the user agrees.
+
+ The Chat picker calls this function for its Public offer (``on_device=False``, refer to
+ :func:`_channels_from_slots`). The function asks first and does not write silently,
+ because the write changes what the device stores. The precedent is the contact that is
+ not on the device (refer to :func:`meshterm.ui.chat._restore_contact`).
+
+ Args:
+ ctx: The shared application context.
+
+ Returns:
+ The conversation of the Public channel on the device, ready to open. ``None`` if the
+ user cancelled, or if the probe after the write does not find the channel.
+
+ Raises:
+ DeviceCommandError: If the device refused the write.
+ """
+ from ..ui.channels import write_channel
+
+ add = await ctx.ui.dialog(
+ "This device has no Public channel, so it can't send there. "
+ "Add Public to slot 0 and open it?",
+ [("Cancel", False), ("Add", True)],
+ title="Channel not on device",
+ default=1,
+ )
+ if not add:
+ return None
+ device = await ctx.device()
+ await write_channel(ctx, device, 0, "Public", DEFAULT_PUBLIC_SECRET)
+ channels = _channels_from_slots(await ctx.devstate.channel_slots())
+ return next((c for c in channels if c.on_device and c.channel_idx == 0), None)
+
+
async def _read_channels(device: Device) -> list[Conversation]:
"""Probe the channel slots, and return them as channel conversations.
- This function always offers channel 0 (the default public channel), also when the
- firmware reports no configured slots. Thus there is always a place to chat.
+ This function returns only the channels that are on the device. The device refuses a
+ send on an empty slot. Thus a listed channel that is not on the device is a promise that
+ fails at the first send (issue #36). ``channels join`` with the well-known key adds the
+ Public channel.
Args:
device: The connected device to probe.
Returns:
- One :class:`~meshterm.core.models.Conversation` for each configured channel (at
- least channel 0).
+ One :class:`~meshterm.core.models.Conversation` for each configured channel.
"""
conversations: list[Conversation] = []
for idx in range(CHANNEL_SLOT_PROBE_CAP):
@@ -696,17 +747,6 @@ async def _read_channels(device: Device) -> list[Conversation]:
secret=secret,
)
)
- if not any(c.channel_idx == 0 for c in conversations):
- conversations.insert(
- 0,
- Conversation(
- label="Public",
- is_channel=True,
- channel_idx=0,
- channel_id="slot:0",
- secret=DEFAULT_PUBLIC_SECRET,
- ),
- )
return conversations
@@ -1003,7 +1043,11 @@ def _title(
else:
text.append(lane, style="muted")
text.append(" ")
- if last is not None:
+ if not conversation.on_device:
+ # The preview lane explains the offer. Enter asks to add the channel (it never opens
+ # a chat), so the text ends with the ellipsis of a row that opens a prompt.
+ text.append("not on the device — Enter adds it…", style="muted")
+ elif last is not None:
text.append_text(_preview_text(last, key_of, name_of, us=us))
return text
@@ -1170,7 +1214,14 @@ def _append_body(
refer to :func:`~meshterm.ui.widgets.mention_chip`). It takes the node grey when the
name resolves to no node that we know. A mention of our own name (``us``) has the chip
of our key with a white label, as in the transcript.
+
+ A body that is a pixel image shows the short line of the transcript in place of its
+ Base91 text (refer to :func:`~meshterm.ui.widgets.pixel_image_text`).
"""
+ image = mcoimg.recognize(body)
+ if image is not None:
+ text.append_text(pixel_image_text(image))
+ return
pos = 0
for match in MENTION.finditer(body):
if match.start() > pos:
@@ -1188,7 +1239,14 @@ def _append_body(
def _names_us(last: ChatMessage, us: tuple[str | None, str | None]) -> bool:
"""Whether the message ``last`` has a mention of our name (``us``)."""
name = us[0]
- return bool(name) and any(match.group(1) == name for match in MENTION.finditer(last.text))
+ if not name:
+ return False
+ body = (
+ split_channel_sender(last.text)[1] if last.is_channel and not last.outbound else last.text
+ )
+ if mcoimg.recognize(body) is not None:
+ return False # the Base91 text of an image can hold an ``@[`` by chance
+ return any(match.group(1) == name for match in MENTION.finditer(body))
def _ago(when: Any) -> str:
diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py
index b9fbb25..46867b6 100644
--- a/meshterm/ui/chat.py
+++ b/meshterm/ui/chat.py
@@ -27,7 +27,7 @@ from rich.cells import cell_len
from rich.console import Group, RenderableType
from rich.text import Text
-from ..core import links, parts, reactions
+from ..core import links, mcoimg, parts, preferences, reactions
from ..core.channels import MENTION, split_channel_sender
from ..core.connection import ContactNotOnDeviceError
from ..core.events import EventKind, MeshEvent
@@ -42,6 +42,7 @@ from ..core.models import (
)
from ..core.regions import WILDCARD
from ..platforms import Platform, on_platform
+from . import pixelart
from .compose import MentionEditor
from .pathline import PATH_INK, PathHop
from .qr import QrScreen, qr_strip
@@ -63,11 +64,13 @@ from .widgets import (
mention_hop,
mention_mark,
picked_hop,
+ pixel_image_text,
self_chip,
)
if TYPE_CHECKING:
from ..context import AppContext
+ from ..core.mcoimg_decode import Picture
from ..services.message_paths import TraceWalk
from .map_render import MapMarker
from .map_screen import Locator
@@ -263,10 +266,10 @@ class ChatScreen(Screen):
else:
toggle = ("", "")
lane[1] = FPair(
- "URL→QR",
+ "Image" if self._picked_picture() is not None else "URL→QR",
"url_code",
*toggle,
- enabled=bool(self._picked_urls()),
+ enabled=self._picked_picture() is not None or bool(self._picked_urls()),
opp_enabled=lock is not None,
)
if self._locator is not None or self._pages is not None:
@@ -434,6 +437,8 @@ class ChatScreen(Screen):
self._render_cache: dict | None = None
# The clock tolerance of the last render: which times show as corrected.
self._tolerance_s = clock_tolerance_s()
+ # Whether the last render drew the pixel images (the ``show_mcoimg`` preference).
+ self._show_images = True
# Strong references to the sends, resends, and spinner tickers that a key handler
# starts. The event loop holds only a *weak* reference. Thus the garbage collector
# can remove a task that nothing else names while it runs: the result is a message
@@ -484,7 +489,13 @@ class ChatScreen(Screen):
def _hint_with(self, lock: str) -> str:
"""The key hint, with the ``lock`` atom after ``^O author`` (or no atom for ``""``)."""
if self._selected is not None:
- code = "^U QR" if self._picked_urls() else ""
+ code = (
+ "^U image"
+ if self._picked_picture() is not None
+ else "^U QR"
+ if self._picked_urls()
+ else ""
+ )
where = "^L map" if self._locate_target() is not None else ""
who = "^O author" if self._author_page() is not None else ""
react = "^E react" if self._can_react() else ""
@@ -753,8 +764,11 @@ class ChatScreen(Screen):
locks = self._pages.locked_keys() if self._pages is not None else frozenset()
tolerance = clock_tolerance_s()
self._tolerance_s = tolerance
+ images = bool(preferences.current().show_mcoimg)
+ self._show_images = images
if (
cache is not None
+ and cache["images"] == images
and cache["width"] == width
and cache["spacing"] == spacing
and cache["locks"] == locks
@@ -870,6 +884,7 @@ class ChatScreen(Screen):
"spacing": spacing,
"locks": locks,
"tolerance": tolerance,
+ "images": images,
"ids": ids,
"acked": ackeds,
"selected": selecteds,
@@ -985,6 +1000,10 @@ class ChatScreen(Screen):
:func:`~meshterm.ui.tui.render.render_hanging`). This is because a terminal opens
a link, and a user copies one, only while it is on one line.
+ A body that is a pixel image (MCOimg) shows a short line with its size, and the
+ image under it in half blocks, at the indent of the body (refer to
+ :mod:`~meshterm.ui.pixelart`).
+
Where the platform draws them (:data:`_URL_CODES`, the PicoCalc), each URL in the
body gets a QR code under it. The codes are side by side, at the indent of the
body. Thus the user can open a link from the handheld on a phone, and does not
@@ -997,10 +1016,11 @@ class ChatScreen(Screen):
"""
tolerance = self._tolerance_s
corrected = message.corrected(tolerance)
+ image = mcoimg.recognize(body)
stamp = message.shown_at(tolerance).astimezone()
prefix = Text()
prefix.append("❯ " if selected else " ", style="cursor" if selected else None)
- if self._names_us(body):
+ if image is None and self._names_us(body):
prefix.append_text(mention_mark(self._self_key))
prefix.append(" ")
else:
@@ -1011,7 +1031,7 @@ class ChatScreen(Screen):
else:
prefix.append(" ")
prefix.append(" ")
- body_text = self._body_text(body, message, selected=selected)
+ body_text = self._body_text(body, message, selected=selected, image=image)
whole = [m.span() for m in _WORD.finditer(body_text.plain) if links.urls(m.group())]
# A mention is a chip, and a chip never breaks across two lines.
whole += [(s.start, s.end) for s in body_text.spans if str(s.style) == PATH_INK]
@@ -1028,7 +1048,13 @@ class ChatScreen(Screen):
)
indent = prefix.cell_len
lines += render_hanging(Text(" " * indent), note, width, indent=indent)
- urls = links.urls(body) if _URL_CODES else []
+ if image is not None and self._show_images:
+ picture = pixelart.decoded(body)
+ if picture is not None:
+ indent = prefix.cell_len
+ art = pixelart.picture_text(picture, width - indent, indent=indent)
+ lines += render_lines(art, width, no_wrap=True)
+ urls = links.urls(body) if _URL_CODES and image is None else []
if urls:
lines += render_lines(qr_strip(urls, width, indent=prefix.cell_len), width)
badges = self._fold.badges(message) if self._fold is not None else []
@@ -1076,9 +1102,23 @@ class ChatScreen(Screen):
runs.append((start, len(text))) # the emoji never ends a line alone
return text, runs
- def _body_text(self, body: str, message: ChatMessage, *, selected: bool) -> Text:
- """Build the styled body of a message: mentions in colour, then the glyphs at the end."""
- text = self._render_mentions(body, selected=selected)
+ def _body_text(
+ self,
+ body: str,
+ message: ChatMessage,
+ *,
+ selected: bool,
+ image: mcoimg.PixelImage | None = None,
+ ) -> Text:
+ """Build the styled body of a message: mentions in colour, then the glyphs at the end.
+
+ A body that is a pixel image (``image``) shows a short line in place of its Base91
+ text (refer to :func:`~meshterm.ui.widgets.pixel_image_text`).
+ """
+ if image is not None:
+ text = pixel_image_text(image, style="cursor" if selected else "muted")
+ else:
+ text = self._render_mentions(body, selected=selected)
if message.outbound:
# A direct message shows its own delivery (spinner → ✓/✗, and a retry is
# possible). A channel broadcast has no ack. Thus mark only a channel message
@@ -1447,6 +1487,46 @@ class ChatScreen(Screen):
message = self._messages[max(0, min(self._selected, len(self._messages) - 1))]
return links.urls(self._sender_and_body(message)[1])
+ def _picked_picture(self) -> Picture | None:
+ """The pixel image of the selected message, or ``None`` (no selection, or no image)."""
+ if self._selected is None or not self._messages:
+ return None
+ message = self._messages[max(0, min(self._selected, len(self._messages) - 1))]
+ body = self._sender_and_body(message)[1]
+ return pixelart.decoded(body) if mcoimg.recognize(body) is not None else None
+
+ def _open_image(self) -> bool:
+ """Show the pixel image of the selected message on a bare frame (^U).
+
+ The image is as large as the frame permits, with its caption and the text of the
+ message under it (refer to :class:`~meshterm.ui.pixelart.ImageScreen`). When the
+ ``show_mcoimg`` preference is off, this is the way to see an image. When it is on,
+ this is the large view.
+
+ Returns:
+ ``True`` when the selected message has an image, so that ^U does nothing more.
+ """
+ picture = self._picked_picture()
+ if picture is None:
+ return False
+ if self._codes_open:
+ return True
+ message = self._messages[max(0, min(self._selected or 0, len(self._messages) - 1))]
+ body = self._sender_and_body(message)[1]
+ image = mcoimg.recognize(body)
+ caption = pixel_image_text(image) if image is not None else Text("")
+ self._codes_open = True
+
+ async def run() -> None:
+ try:
+ await self._session.run_screen(pixelart.ImageScreen(picture, caption, body))
+ finally:
+ self._codes_open = False
+ self._session.invalidate()
+
+ self._session.run_detached(run())
+ return True
+
def _open_codes(self) -> None:
"""Show the links of the selected message as QR codes on the share screen (^U).
@@ -1457,6 +1537,8 @@ class ChatScreen(Screen):
message, and when nothing is selected, the screen cannot know which message. One
share screen at a time.
"""
+ if self._open_image():
+ return
urls = self._picked_urls()
if not urls or self._codes_open:
return
diff --git a/meshterm/ui/pixelart.py b/meshterm/ui/pixelart.py
new file mode 100644
index 0000000..2168669
--- /dev/null
+++ b/meshterm/ui/pixelart.py
@@ -0,0 +1,238 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Draw a pixel image (MCOimg) in the terminal with half blocks.
+
+A cell is approximately two times as tall as it is wide. Thus a cell holds two pixels, one
+above the other, and each pixel is square: ``▀`` with the top pixel as its colour and the
+bottom pixel as its background. A transparent pixel shows the page. A cell with only the
+bottom pixel is ``▄`` in that colour, and a cell with no pixel is a space.
+
+An image keeps its own size: one pixel is one cell wide and half a cell tall (JP,
+2026-11-20). A tall image scrolls with the transcript, as a long message does. The one
+exception is an image that is wider than the lane: it becomes smaller to fit the width
+(refer to :func:`fit`), because an image that is cut shows only a part of it. MCOimg
+images are 10 to 30 pixels wide in practice, so this is rare.
+
+On the picked message, ^U opens the image on a bare frame (:class:`ImageScreen`). There it
+becomes larger by a whole number when the frame has the room, so each pixel stays square,
+but it never becomes smaller than its own size. When the ``show_mcoimg`` preference is
+off, the chat shows only the line about the image, and ^U is the way to see it.
+"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+from typing import TYPE_CHECKING
+
+from rich.console import Group
+from rich.style import Style
+from rich.text import Text
+
+from .tui.screen import ScrollScreen
+
+if TYPE_CHECKING:
+ from ..core.mcoimg_decode import Picture
+
+RGB = tuple[int, int, int]
+
+
+@lru_cache(maxsize=128)
+def decoded(body: str) -> Picture | None:
+ """The image of a message body, or ``None``. It keeps the last results.
+
+ A transcript paints many times while a message is visible. Each paint asks again, and
+ the cache answers without a second decode. The decoder is large, so it loads here, at
+ the first image, and not when the chat opens.
+ """
+ from ..core.mcoimg_decode import decode
+
+ return decode(body)
+
+
+def fit(
+ width: int, height: int, max_cols: int, max_rows: int | None = None, *, grow: bool = False
+) -> tuple[int, int]:
+ """The size in pixels at which to draw an image of ``width`` × ``height``.
+
+ The image keeps its proportions, and becomes smaller only to fit ``max_cols`` cells and
+ ``max_rows`` rows (two pixels in each row). ``None`` rows is no limit on the height:
+ then only the width can make the image smaller. With ``grow``, an image that is smaller
+ than that space becomes larger by the largest whole number that fits. Thus each pixel
+ of the image is the same number of cells.
+ """
+ scale = max_cols / width
+ if max_rows is not None:
+ scale = min(scale, (max_rows * 2) / height)
+ if scale >= 1:
+ scale = int(scale) if grow else 1
+ return max(1, int(width * scale)), max(1, int(height * scale))
+
+
+def picture_text(
+ picture: Picture,
+ max_cols: int,
+ *,
+ indent: int = 0,
+ max_rows: int | None = None,
+ grow: bool = False,
+) -> Text:
+ """Draw ``picture`` as lines of half blocks, each after ``indent`` spaces.
+
+ Args:
+ picture: The decoded image.
+ max_cols: The most cells that the image can use, after the indent.
+ indent: The cells of page before each line (the indent of the body of a message).
+ max_rows: The most rows that the image can use, or ``None`` for no limit (the
+ image under a message: a tall image scrolls with the transcript).
+ grow: Make a small image larger to fill the space (refer to :func:`fit`).
+
+ Returns:
+ One :class:`~rich.text.Text` with a line for each two rows of pixels. It has no
+ newline after the last line.
+ """
+ rows_cap = None if max_rows is None else max(1, max_rows)
+ cols, rows = fit(picture.width, picture.height, max(1, max_cols), rows_cap, grow=grow)
+ pixel = _sampler(picture, cols, rows)
+ text = Text(no_wrap=True)
+ for y in range(0, rows, 2):
+ if y:
+ text.append("\n")
+ text.append(" " * indent)
+ for x in range(cols):
+ top = pixel(x, y)
+ bottom = pixel(x, y + 1) if y + 1 < rows else None
+ text.append(*_cell(top, bottom))
+ return text
+
+
+def _sampler(picture: Picture, cols: int, rows: int): # noqa: ANN202
+ """A function that gives the pixel at ``(x, y)`` of the image drawn at ``cols`` × ``rows``.
+
+ A smaller image takes the nearest pixel of the original, so the colours stay the
+ colours of the palette. A mix of colours makes pixel art look blurred.
+ """
+ width, height, pixels = picture.width, picture.height, picture.pixels
+
+ def pixel(x: int, y: int) -> RGB | None:
+ return pixels[(y * height // rows) * width + (x * width // cols)]
+
+ return pixel
+
+
+def _cell(top: RGB | None, bottom: RGB | None) -> tuple[str, Style | None]:
+ """The character and the style of one cell, for its top and bottom pixels."""
+ if top is None and bottom is None:
+ return " ", None
+ if top is None:
+ return "▄", Style(color=_hex(bottom))
+ if bottom is None:
+ return "▀", Style(color=_hex(top))
+ if top == bottom:
+ return "█", Style(color=_hex(top))
+ return "▀", Style(color=_hex(top), bgcolor=_hex(bottom))
+
+
+def _hex(rgb: RGB | None) -> str:
+ """The colour of a pixel as ``#rrggbb``."""
+ r, g, b = rgb # type: ignore[misc]
+ return f"#{r:02x}{g:02x}{b:02x}"
+
+
+#: The cells of page at each side of the image on its bare frame.
+_MARGIN_COLS = 2
+#: The rows of page that the image and its caption leave free on the bare frame, in total.
+#: The frame puts two fifths of the free rows above the block (refer to
+#: :func:`~meshterm.ui.tui.frame.compose_bare`). With three, one row is above and two are
+#: below. With two, the frame puts both below, and the image touches the top.
+_MARGIN_ROWS = 3
+
+
+class ImageScreen(ScrollScreen):
+ """The pixel image of a message on a bare frame, as large as the frame permits (^U).
+
+ It is the share screen of a link (:class:`~meshterm.ui.qr.QrScreen`) for an image: no
+ header, no footer, no box, and no hint. Esc leaves, as it does everywhere. The image
+ fits itself to the frame at each paint, so a larger terminal shows a larger image.
+ Under it are the caption (its size and its colours) and the text of the message itself,
+ the ``im3:`` string that the sender transmitted. Thus the user can examine or copy the
+ text that made the image.
+
+ The image never touches the edges of the frame. It keeps :data:`_MARGIN_COLS` cells at
+ each side and at least one row above and below, as a QR code keeps its quiet zone. The
+ frame puts the block a little above the true centre, as it does for a code.
+
+ The image never becomes smaller than its own size (JP, 2026-11-20), except to fit the
+ width of the frame. On a frame that has the room, it grows by the largest whole number
+ that holds it with its text, or else alone. An image that is taller than the frame
+ (on the 14 rows of the Cardputer, a 30-pixel image) starts at the top of the page, and
+ the arrows scroll it.
+
+ The text of the message has no spaces, so it breaks at the width of the image area,
+ into a block of lines that is centred as one. The text never makes the image smaller
+ than the size that it has alone on the frame: the text can only stop it from growing.
+ When the frame cannot hold both, the image gets the rows, and the text is under it, a
+ page down, as the URL of a large QR code is.
+ """
+
+ bare = True
+
+ def __init__(self, picture: Picture, caption: Text, raw: str = "") -> None:
+ """Set up the screen for ``picture``, with ``caption`` and ``raw`` under it.
+
+ Args:
+ picture: The decoded image.
+ caption: The line about the image, as the chat shows it.
+ raw: The text of the message: the ``im3:`` string.
+ """
+ super().__init__(Text(""), title="Image", floating=False)
+ self.picture = picture
+ self._caption = caption
+ self.raw = raw.strip()
+
+ def render_body(self, width: int) -> list[str]:
+ """The image as large as the frame permits, then its caption and its text."""
+ # The frame notes its height before it asks for the body, as on the share screen.
+ rows = self._scroll_viewport
+ picture = self.picture
+ art_cols = max(1, width - 2 * _MARGIN_COLS)
+ raw_lines = _raw_lines(self.raw, art_cols, width)
+ # The margins, a blank row and the caption, then a blank row and the text.
+ alone = max(1, rows - _MARGIN_ROWS - 2)
+ art_rows = max(1, alone - (1 + len(raw_lines) if raw_lines else 0))
+ size = (picture.width, picture.height)
+ # The smallest that the image can be: its own size, or less only to fit the width.
+ least = fit(*size, art_cols)[0]
+ # The largest that it can be without the text: the text can stop it from growing,
+ # but never make it smaller than that.
+ alone_cols = max(least, fit(*size, art_cols, alone, grow=True)[0])
+ limit: int | None = art_rows
+ if fit(*size, art_cols, art_rows, grow=True)[0] < alone_cols:
+ limit = alone # the text goes a page down
+ if fit(*size, art_cols, limit, grow=True)[0] < least:
+ limit = None # taller than the frame: its own size, and the page scrolls
+ cols, _ = fit(*size, art_cols, limit, grow=limit is not None)
+ indent = max(0, (width - cols) // 2)
+ art = picture_text(picture, art_cols, indent=indent, max_rows=limit, grow=True)
+ caption = self._caption.copy()
+ caption.justify = "center"
+ parts = [art, Text(""), caption]
+ if raw_lines:
+ parts += [Text(""), *raw_lines]
+ self.replace_content(Group(*parts))
+ return super().render_body(width)
+
+
+def _raw_lines(raw: str, max_cols: int, width: int) -> list[Text]:
+ """The text of a message as a block of lines no wider than ``max_cols``, centred in ``width``.
+
+ The text is Base91 characters only, each one cell wide, so a line is a slice of it.
+ Each line has the same indent, so that the block is centred and its last line starts
+ under the others.
+ """
+ if not raw:
+ return []
+ size = max(1, min(len(raw), max_cols))
+ indent = " " * max(0, (width - size) // 2)
+ return [
+ Text(indent + raw[start : start + size], style="muted", no_wrap=True)
+ for start in range(0, len(raw), size)
+ ]
diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py
index 3221503..ec940f2 100644
--- a/meshterm/ui/theme.py
+++ b/meshterm/ui/theme.py
@@ -852,6 +852,7 @@ _GLYPH_MAP: dict[str, str] = {
"🔔": "•", # notify: the badge dot
"🔕": "·", # mute: the hollowed-out dot
"📱": "▓", # QR: a dense block
+ "🎨": "░", # pixel image (MCOimg): a fine grid of dots
"🔗": "&", # link: the joining glyph
"🏆": "★", # trophy case: the best/winner star
"⌨": "❯", # command line: the prompt pointer
diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py
index 5c17c06..3a59d92 100644
--- a/meshterm/ui/widgets.py
+++ b/meshterm/ui/widgets.py
@@ -64,6 +64,7 @@ from .theme import glyph, mark_rgb, name_style, node_style, snr_style
if TYPE_CHECKING:
from ..core.discovery import DiscoveredDevice
+ from ..core.mcoimg import PixelImage
from ..core.regions import Scope
@@ -98,6 +99,35 @@ def channel_glyph(name: str, secret: bytes | None) -> str:
#: The concept icon for a region (the scope of a flood). Refer to the icon table of ``CLAUDE.md``.
REGION_ICON = "🔖"
+#: The concept icon for a pixel image in a message (MCOimg). It is the palette of pixel
+#: art. ``🖼`` is not used, because it is a text character by default and terminals do
+#: not agree about its width.
+IMAGE_ICON = "🎨"
+
+
+def pixel_image_text(image: PixelImage, *, style: str | None = "muted") -> Text:
+ """The short line that a message shows in place of the Base91 text of a pixel image.
+
+ The Base91 text is noise to the user. Its ``@[``, ``]``, and ``.`` characters can also
+ look like a mention or a link. Thus the chat and the Messages list show this line in
+ its place: ``🎨 image · 24×24 · 16 colours`` when MeshTerm can read the header of the
+ image, or else the version of the format.
+
+ Args:
+ image: The image that :func:`~meshterm.core.mcoimg.recognize` found in the body.
+ style: The style of the line: ``muted``, or ``cursor`` on the selected message.
+ """
+ parts = [f"{glyph(IMAGE_ICON)} image"]
+ if image.width is not None and image.height is not None:
+ parts.append(f"{image.width}×{image.height}")
+ if image.colours is not None:
+ parts.append(f"{image.colours} colours")
+ elif image.version is None:
+ parts.append("MCOimg v1/v2")
+ else:
+ parts.append(f"MCOimg v{image.version}")
+ return Text(" · ".join(parts), style=style)
+
def scope_text(scope: Scope | None, *, bare: bool = False) -> Text:
"""The only rendering of the scope of a flood, for each surface that states one.
diff --git a/scripts/screenshots.py b/scripts/screenshots.py
index b5253ac..c069ced 100644
--- a/scripts/screenshots.py
+++ b/scripts/screenshots.py
@@ -6,7 +6,8 @@
The script runs MeshTerm three times, one time for each set: ``terminal`` (the desktop, in
an 80×24 terminal), ``cardputer-zero``, and ``picocalc-lyra``. Each run uses ``--demo``
(refer to :mod:`meshterm.demo`) and types the same keys: it opens the chat on Public,
-the paths of a message, and the map, and it saves each screen as a PNG. The result is
+the paths of a message, the map, and the pixel images of the ``#mcoimg`` channel, and it
+saves each screen as a PNG. The result is
``DIR//.png`` (``DIR`` is ``docs/screenshots`` by default).
The script also draws each wordmark of the startup splash (``meshterm/assets/splash``) as
@@ -361,6 +362,19 @@ def _tour(capture: Capture, type_text: Callable[[str], None], save: Callable[[st
press("enter")
capture.settle(quiet=4.0, timeout=120.0)
save("map")
+ # The pixel images of the #mcoimg channel, from the main menu.
+ press(text="w", ctrl=True)
+ capture.settle(quiet=0.8)
+ press("escape")
+ typed("chat")
+ press("enter")
+ capture.wait_for("Public")
+ capture.settle()
+ typed("mcoimg")
+ press("enter")
+ capture.wait_for("#mcoimg")
+ capture.settle(quiet=1.5)
+ save("mcoimg")
# --------------------------------------------------------------------------- drawing
diff --git a/scripts/video.py b/scripts/video.py
index e160431..1ed52ac 100644
--- a/scripts/video.py
+++ b/scripts/video.py
@@ -356,7 +356,7 @@ def _tour(p: Presenter) -> None:
print("the main menu", flush=True)
p.camera.roll()
- p.hold(3.0)
+ p.hold(2.5)
print("the chat, and the paths of a message", flush=True)
p.type("chat")
@@ -405,7 +405,7 @@ def _tour(p: Presenter) -> None:
# Dave answers a few seconds later (``meshterm.demo.script.REPLIES``). His answer
# mentions our node, so it has our star.
p.wait_for("be there at 2", timeout=30)
- p.hold(3.5)
+ p.hold(3.0)
print("a trace", flush=True)
_menu(p, "trace t")
@@ -415,14 +415,14 @@ def _tour(p: Presenter) -> None:
p.hold(0.4)
p.key("enter")
p.wait_for("Trace — Brossard")
- p.hold(2.0)
+ p.hold(1.5)
p.key("enter", pause=0.0)
p.wait_for("Per-hop medians", timeout=30)
p.hold(1.0)
# The history stores walks of one byte for each hop. Thus this walk of two bytes is new,
# and its records go to the trophy case.
if p.shows("new record"):
- p.hold(3.0)
+ p.hold(2.5)
p.key("enter", pause=0.0) # Close
p.hold(1.5)
p.key("pagedown", pause=0.0)
diff --git a/tests/data/mcoimg/README.md b/tests/data/mcoimg/README.md
new file mode 100644
index 0000000..676ffb6
--- /dev/null
+++ b/tests/data/mcoimg/README.md
@@ -0,0 +1,42 @@
+# MCOimg test vectors
+
+These two files are the test vectors of version 3 of the MCOimg pixel image format. They
+come without change from the folder `docs/mcoimg-js/tests/` of the meshcore-open repository
+([HDDen/meshcore-open](https://github.com/HDDen/meshcore-open), a fork of
+[zjs81/meshcore-open](https://github.com/zjs81/meshcore-open)):
+
+- `v3-js-decoder-fixtures.json`: 39 images, one or more for each container, block
+ algorithm, scan order, and local palette form.
+- `v3-js-encoder-fixtures.json`: 6 images that the JavaScript encoder of the format made.
+
+Each vector has the `im3:` text of an image, its size, its palette profile, and the palette
+reference of each pixel. `tests/test_mcoimg.py` decodes each text and compares the result.
+MeshTerm does not include these files in its package.
+
+The files are under the MIT licence of the meshcore-open repository:
+
+
+
+MIT License
+
+Copyright (c) 2025 zjs81
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
diff --git a/tests/data/mcoimg/v3-js-decoder-fixtures.json b/tests/data/mcoimg/v3-js-decoder-fixtures.json
new file mode 100644
index 0000000..b8a3f6f
--- /dev/null
+++ b/tests/data/mcoimg/v3-js-decoder-fixtures.json
@@ -0,0 +1,847 @@
+{
+ "schema": 1,
+ "generator": "docs/mcoimg-js/tests/v3-decoder-fixtures.js",
+ "fixtures": [
+ {
+ "name": "rawGlobal",
+ "bodyBase64": "egGNAEK+AQ==",
+ "appPayloadBase64": "E3oBjQBCvgE=",
+ "text": "im3:g/5WjAL`NA",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 1,
+ 2,
+ 3,
+ 3,
+ 2,
+ 1,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "compactBlock",
+ "algorithm": "rawGlobal"
+ },
+ {
+ "name": "rawLocal",
+ "bodyBase64": "egGNECLWAg==",
+ "appPayloadBase64": "E3oBjRAi1gI=",
+ "text": "im3:g/5W6LuitA",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 0,
+ 3,
+ 3,
+ 0,
+ 3,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "compactBlock",
+ "algorithm": "rawLocal"
+ },
+ {
+ "name": "compactRle",
+ "bodyBase64": "egGNICCmIQ==",
+ "appPayloadBase64": "E3oBjSAgpiE=",
+ "text": "im3:g/5W[Wqi^F",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 3,
+ 3,
+ 0,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "compactRle"
+ },
+ {
+ "name": "compactSparse",
+ "bodyBase64": "egGNMABOIgA=",
+ "appPayloadBase64": "E3oBjTAATiIA",
+ "text": "im3:g/5WNi+>CGA",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 3,
+ 0,
+ 0,
+ 3,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "compactSparse"
+ },
+ {
+ "name": "biColorMask",
+ "bodyBase64": "egGNQMJa",
+ "appPayloadBase64": "E3oBjUDCWg==",
+ "text": "im3:g/5Wktw8F",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 0,
+ 3,
+ 3,
+ 0,
+ 3,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "compactBlock",
+ "algorithm": "biColorMask"
+ },
+ {
+ "name": "rowRepeat",
+ "bodyBase64": "egGNUCDW",
+ "appPayloadBase64": "E3oBjVAg1g==",
+ "text": "im3:g/5W74qiN",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 0,
+ 3,
+ 0,
+ 3,
+ 0,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "rowRepeat"
+ },
+ {
+ "name": "lzPixels",
+ "bodyBase64": "egGNYCAWHw==",
+ "appPayloadBase64": "E3oBjWAgFh8=",
+ "text": "im3:g/5W](qiqF",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 0,
+ 3,
+ 0,
+ 3,
+ 0,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "lzPixels"
+ },
+ {
+ "name": "quadtree",
+ "bodyBase64": "egEEB2J9",
+ "appPayloadBase64": "E3oBBAdifQ==",
+ "text": "im3:g/N\"qC8]D",
+ "width": 2,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 3,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "quadtree"
+ },
+ {
+ "name": "bitplanesRawAndRle",
+ "bodyBase64": "egGNgGByqm0=",
+ "appPayloadBase64": "E3oBjYBgcqpt",
+ "text": "im3:g/5Wl\"#zslb",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 1,
+ 0,
+ 1,
+ 2,
+ 3,
+ 2,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "bitplanes"
+ },
+ {
+ "name": "adaptiveBitplanesRaw",
+ "bodyBase64": "egGNkCCmBQ==",
+ "appPayloadBase64": "E3oBjZAgpgU=",
+ "text": "im3:g/5W6Lri\"A",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 0,
+ 3,
+ 3,
+ 0,
+ 3,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "adaptiveBitplanes"
+ },
+ {
+ "name": "directBitplanes",
+ "bodyBase64": "egiNoEAVM3g=",
+ "appPayloadBase64": "E3oIjaBAFTN4",
+ "text": "im3:g/WX[Wyd~I8",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "grayscale8",
+ "pixels": [
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "directBitplanes"
+ },
+ {
+ "name": "compactRowDelta",
+ "bodyBase64": "egGNsCCmAA==",
+ "appPayloadBase64": "E3oBjbAgpgA=",
+ "text": "im3:g/5WNiriKA",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 0,
+ 3,
+ 0,
+ 3,
+ 0,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "compactRowDelta"
+ },
+ {
+ "name": "directRowDelta",
+ "bodyBase64": "egiNwADRAA==",
+ "appPayloadBase64": "E3oIjcAA0QA=",
+ "text": "im3:g/WXkt6FNA",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "grayscale8",
+ "pixels": [
+ 0,
+ 1,
+ 2,
+ 3,
+ 0,
+ 1,
+ 2,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "directRowDelta"
+ },
+ {
+ "name": "rowDelta",
+ "bodyBase64": "egGN0CBGAw==",
+ "appPayloadBase64": "E3oBjdAgRgM=",
+ "text": "im3:g/5W74ri0A",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 0,
+ 3,
+ 0,
+ 3,
+ 0,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "rowDelta"
+ },
+ {
+ "name": "varUintRle",
+ "bodyBase64": "egGN4CA2UMAA",
+ "appPayloadBase64": "E3oBjeAgNlDAAA==",
+ "text": "im3:g/5W](riJOFBA",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 3,
+ 3,
+ 0,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "varUintRle"
+ },
+ {
+ "name": "varUintSparse",
+ "bodyBase64": "egGN8AAWCBAQCAA=",
+ "appPayloadBase64": "E3oBjfAAFggQEAgA",
+ "text": "im3:g/5WO?+hmB2WgAA",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 3,
+ 0,
+ 0,
+ 3,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "varUintSparse"
+ },
+ {
+ "name": "adaptiveLegacyRle",
+ "bodyBase64": "egEdkCDOBg==",
+ "appPayloadBase64": "E3oBHZAgzgY=",
+ "text": "im3:g/5WeLs?RB",
+ "width": 8,
+ "height": 1,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 3,
+ 3,
+ 3,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "adaptiveBitplanes"
+ },
+ {
+ "name": "adaptiveShortRle",
+ "bodyBase64": "egEdkCCeNg==",
+ "appPayloadBase64": "E3oBHZAgnjY=",
+ "text": "im3:g/5WeLs?2J",
+ "width": 8,
+ "height": 1,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 3,
+ 3,
+ 3,
+ 0,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "adaptiveBitplanes"
+ },
+ {
+ "name": "adaptiveConstantZero",
+ "bodyBase64": "egEdkCA+",
+ "appPayloadBase64": "E3oBHZAgPg==",
+ "text": "im3:g/5WeLs?D",
+ "width": 8,
+ "height": 1,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "adaptiveBitplanes"
+ },
+ {
+ "name": "adaptiveConstantOne",
+ "bodyBase64": "egEdkCB+",
+ "appPayloadBase64": "E3oBHZAgfg==",
+ "text": "im3:g/5WeLs?H",
+ "width": 8,
+ "height": 1,
+ "paletteProfile": "master4",
+ "pixels": [
+ 3,
+ 3,
+ 3,
+ 3,
+ 3,
+ 3,
+ 3,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "adaptiveBitplanes"
+ },
+ {
+ "name": "adaptiveSparseOne",
+ "bodyBase64": "egEdkCC+CQE=",
+ "appPayloadBase64": "E3oBHZAgvgkB",
+ "text": "im3:g/5WeLs?%uA",
+ "width": 8,
+ "height": 1,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 3,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "adaptiveBitplanes"
+ },
+ {
+ "name": "adaptiveSparseZero",
+ "bodyBase64": "egEdkCD+CQE=",
+ "appPayloadBase64": "E3oBHZAg/gkB",
+ "text": "im3:g/5WeLs?*uA",
+ "width": 8,
+ "height": 1,
+ "paletteProfile": "master4",
+ "pixels": [
+ 3,
+ 0,
+ 3,
+ 3,
+ 3,
+ 3,
+ 0,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "adaptiveBitplanes"
+ },
+ {
+ "name": "boundsBlock",
+ "bodyBase64": "egEMQgQEBATgAQ==",
+ "appPayloadBase64": "E3oBDEIEBAQE4AE=",
+ "text": "im3:g/N\"UXbLi\"+>BA",
+ "width": 4,
+ "height": 4,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 3,
+ 3,
+ 0,
+ 0,
+ 3,
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "boundsBlock",
+ "algorithm": "compactRle"
+ },
+ {
+ "name": "compactBoundsBlock",
+ "bodyBase64": "egEMYFTlAQ==",
+ "appPayloadBase64": "E3oBDGBU5QE=",
+ "text": "im3:g/N\"+h\"OPA",
+ "width": 4,
+ "height": 4,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 2,
+ 0,
+ 0,
+ 3,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "compactBoundsBlock",
+ "algorithm": "rawGlobal"
+ },
+ {
+ "name": "regions",
+ "bodyBase64": "egEMgAQEBAQEtQE=",
+ "appPayloadBase64": "E3oBDIAEBAQEBLUB",
+ "text": "im3:g/N\"CtbLi\"lB/EA",
+ "width": 4,
+ "height": 4,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 3,
+ 0,
+ 0,
+ 3,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "regions",
+ "algorithm": "rawGlobal"
+ },
+ {
+ "name": "compactRegionsSharedDelta",
+ "bodyBase64": "egGNEMqDGrUAQAI=",
+ "appPayloadBase64": "E3oBjRDKgxq1AEAC",
+ "text": "im3:g/5W6LdV9x\"AdZA",
+ "width": 4,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 1,
+ 3,
+ 3,
+ 1,
+ 3,
+ 1,
+ 1,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "compactRegionsStream",
+ "algorithm": "rawGlobal"
+ },
+ {
+ "name": "solidBackground",
+ "bodyBase64": "egEAwg==",
+ "appPayloadBase64": "E3oBAMI=",
+ "text": "im3:g/LAU)",
+ "width": 1,
+ "height": 1,
+ "paletteProfile": "master4",
+ "pixels": [
+ 2
+ ],
+ "transparentColor": null,
+ "container": "solidBackground",
+ "algorithm": "rawGlobal"
+ },
+ {
+ "name": "solidRects",
+ "bodyBase64": "egEM4GBV",
+ "appPayloadBase64": "E3oBDOBgVQ==",
+ "text": "im3:g/N\",>M8C",
+ "width": 4,
+ "height": 4,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 3,
+ 3,
+ 0,
+ 0,
+ 3,
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "solidRects",
+ "algorithm": "rawGlobal"
+ },
+ {
+ "name": "implicitWhiteSolid",
+ "bodyBase64": "ekEEwA==",
+ "appPayloadBase64": "E3pBBMA=",
+ "text": "im3:g/)FCtB",
+ "width": 2,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "solidBackground",
+ "algorithm": "rawGlobal"
+ },
+ {
+ "name": "transparentSolid",
+ "bodyBase64": "eoEEwgM=",
+ "appPayloadBase64": "E3qBBMID",
+ "text": "im3:g/iLnuHA",
+ "width": 2,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 2,
+ 2,
+ 2,
+ 2
+ ],
+ "transparentColor": 3,
+ "container": "solidBackground",
+ "algorithm": "rawGlobal"
+ },
+ {
+ "name": "scanV",
+ "bodyBase64": "ehGJIGByEGQQ",
+ "appPayloadBase64": "E3oRiSBgchBkEA==",
+ "text": "im3:g/DY@WhN[CFXA",
+ "width": 3,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 2,
+ 0,
+ 1,
+ 3,
+ 1
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "compactRle"
+ },
+ {
+ "name": "scanS",
+ "bodyBase64": "eiGJIGByEGQQ",
+ "appPayloadBase64": "E3ohiSBgchBkEA==",
+ "text": "im3:g/oZ@WhN[CFXA",
+ "width": 3,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 1,
+ 2,
+ 1,
+ 0,
+ 3
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "compactRle"
+ },
+ {
+ "name": "scanSV",
+ "bodyBase64": "ejGJIGByEGQQ",
+ "appPayloadBase64": "E3oxiSBgchBkEA==",
+ "text": "im3:g/=a@WhN[CFXA",
+ "width": 3,
+ "height": 2,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 0,
+ 1,
+ 2,
+ 1
+ ],
+ "transparentColor": null,
+ "container": "block",
+ "algorithm": "compactRle"
+ },
+ {
+ "name": "paletteBitmap",
+ "bodyBase64": "egENEJI0",
+ "appPayloadBase64": "E3oBDRCSNA==",
+ "text": "im3:g/5WaL%ZD",
+ "width": 4,
+ "height": 1,
+ "paletteProfile": "master4",
+ "pixels": [
+ 0,
+ 3,
+ 3,
+ 0
+ ],
+ "transparentColor": null,
+ "container": "compactBlock",
+ "algorithm": "rawLocal"
+ },
+ {
+ "name": "paletteSortedDelta",
+ "bodyBase64": "egINEDJBIgM=",
+ "appPayloadBase64": "E3oCDRAyQSID",
+ "text": "im3:g/%WaL&GDzB",
+ "width": 4,
+ "height": 1,
+ "paletteProfile": "master8",
+ "pixels": [
+ 0,
+ 2,
+ 4,
+ 2
+ ],
+ "transparentColor": null,
+ "container": "compactBlock",
+ "algorithm": "rawLocal"
+ },
+ {
+ "name": "paletteRangeRuns",
+ "bodyBase64": "egINENJAFTk=",
+ "appPayloadBase64": "E3oCDRDSQBU5",
+ "text": "im3:g/%WaL4E)wc",
+ "width": 4,
+ "height": 1,
+ "paletteProfile": "master8",
+ "pixels": [
+ 0,
+ 1,
+ 5,
+ 6
+ ],
+ "transparentColor": null,
+ "container": "compactBlock",
+ "algorithm": "rawLocal"
+ },
+ {
+ "name": "paletteBankBitmaps",
+ "bodyBase64": "eg8NEPIrEAAAAAAAAAAgAAAAAAAAAFA=",
+ "appPayloadBase64": "E3oPDRDyKxAAAAAAAAAAIAAAAAAAAABQ",
+ "text": "im3:g/>XaLT(XaL$stPmGlE",
+ "width": 4,
+ "height": 1,
+ "paletteProfile": "dynamicGlobal512",
+ "pixels": [
+ 193,
+ 201,
+ 209,
+ 201
+ ],
+ "transparentColor": null,
+ "container": "compactBlock",
+ "algorithm": "rawLocal"
+ },
+ {
+ "name": "paletteOrderedMultiBank",
+ "bodyBase64": "eg8NEPI3LBAUDAly",
+ "appPayloadBase64": "E3oPDRDyNywQFAwJcg==",
+ "text": "im3:g/>XaL$s+HUc,LJo",
+ "width": 4,
+ "height": 1,
+ "paletteProfile": "dynamicGlobal512",
+ "pixels": [
+ 1,
+ 130,
+ 3,
+ 132
+ ],
+ "transparentColor": null,
+ "container": "compactBlock",
+ "algorithm": "rawLocal"
+ }
+ ]
+}
diff --git a/tests/data/mcoimg/v3-js-encoder-fixtures.json b/tests/data/mcoimg/v3-js-encoder-fixtures.json
new file mode 100644
index 0000000..8128b6d
--- /dev/null
+++ b/tests/data/mcoimg/v3-js-encoder-fixtures.json
@@ -0,0 +1,792 @@
+{
+ "schema": 1,
+ "generator": "mcoimg-v3-codec.global.js Normal/High encoder",
+ "fixtures": [
+ {
+ "name": "mono-checker-normal",
+ "width": 9,
+ "height": 7,
+ "paletteProfile": "mono",
+ "pixels": [
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0
+ ],
+ "compressionLevel": "normal",
+ "maxRegions": 16,
+ "bodyBase64": "QAAhY6DkMwE=",
+ "appPayloadBase64": "E0AAIWOg5DMB",
+ "text": "im3:TAYL>iBNGbA",
+ "byteLength": 8,
+ "charLength": 15,
+ "subtypeVersion": 19,
+ "packetNonce": 64,
+ "mode": "extended",
+ "scan": "h",
+ "container": "block",
+ "algorithm": "lzPixels",
+ "backgroundColor": 0,
+ "regionCount": 0
+ },
+ {
+ "name": "master8-sparse-high",
+ "width": 12,
+ "height": 10,
+ "paletteProfile": "master8",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 2,
+ 2,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 2,
+ 2,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 3,
+ 3,
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 3,
+ 4,
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 3,
+ 3,
+ 3,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "compressionLevel": "high",
+ "maxRegions": 32,
+ "bodyBase64": "QUKtFJoQMSMRmAGWkhEC",
+ "appPayloadBase64": "E0FCrRSaEDEjEZgBlpIRAg==",
+ "text": "im3:CDecxOjD61JY`R)0nxQA",
+ "byteLength": 15,
+ "charLength": 24,
+ "subtypeVersion": 19,
+ "packetNonce": 65,
+ "mode": "regionsBg",
+ "scan": "h",
+ "container": "compactRegionsStream",
+ "algorithm": "rawGlobal",
+ "backgroundColor": 0,
+ "regionCount": 2
+ },
+ {
+ "name": "master16-regions-high",
+ "width": 16,
+ "height": 12,
+ "paletteProfile": "master16",
+ "pixels": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 2,
+ 2,
+ 0,
+ 0,
+ 0,
+ 1,
+ 3,
+ 3,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 2,
+ 2,
+ 0,
+ 0,
+ 0,
+ 1,
+ 3,
+ 3,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 4,
+ 4,
+ 4,
+ 4,
+ 4,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 4,
+ 5,
+ 5,
+ 5,
+ 4,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 4,
+ 5,
+ 6,
+ 5,
+ 4,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 4,
+ 5,
+ 5,
+ 5,
+ 4,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 4,
+ 4,
+ 4,
+ 4,
+ 4,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "compressionLevel": "high",
+ "maxRegions": 32,
+ "bodyBase64": "QkO9JZpExIyIAWbAUQApIxZEwCkHLkI=",
+ "appPayloadBase64": "E0JDvSWaRMSMiAFmwFEAKSMWRMApBy5C",
+ "text": "im3: None:
+ """The Base91 text of an MCOimg image is noise, so the preview shows what it is."""
+ image = ChatMessage(text="Bob: im3:g/5WjAL`NA", is_channel=True, channel_idx=0)
+ assert _preview_text(image, _NO_KEYS).plain.endswith("image · 4×2 · 4 colours")
+
+
def test_preview_keeps_the_whole_message() -> None:
"""The preview is built whole. The cut of the row is the part that the ←→ scroll passes."""
long = ChatMessage(text="x" * 300, is_channel=True, channel_idx=0)
@@ -972,6 +978,83 @@ def test_chat_screen_shows_delivery_glyphs() -> None:
assert "^R" in screen.footer_hint
+def test_a_pixel_image_shows_a_short_line_not_its_text() -> None:
+ """A body that is an MCOimg image shows its size and the image, not its Base91 text."""
+ text = "im3:g/5WjAL`NA"
+ messages = [ChatMessage(text=text, peer="d4e5f6a7")]
+ screen = _screen(_StubSession(), send=None, messages=messages)
+ lines = [_strip_ansi(ln) for ln in screen._body_lines(text, messages[0], 60)]
+ assert lines[0].endswith("image · 4×2 · 4 colours")
+ assert not any("g/5W" in line for line in lines)
+ # Under the line, the 4 x 2 image is one row of four half blocks at the body indent.
+ assert len(lines) == 2
+ assert lines[1].strip() and set(lines[1].strip()) <= set("▀▄█")
+
+
+def test_with_show_mcoimg_on_ctrl_u_still_opens_the_full_screen(monkeypatch) -> None:
+ """With the image in the transcript, ^U on the picked image opens the full screen too."""
+ from meshterm.core import preferences
+ from meshterm.ui.pixelart import ImageScreen
+
+ prefs = preferences.Preferences()
+ monkeypatch.setattr(preferences, "current", lambda: prefs)
+ text = "im3:g/5WjAL`NA"
+ session = _StubSession()
+ opened = []
+
+ async def run_screen(screen): # noqa: ANN001, ANN202
+ opened.append(screen)
+
+ session.run_screen = run_screen
+ screen = _screen(session, send=None, messages=[ChatMessage(text=text, peer="d4e5f6a7")])
+ screen._render_grouped(60)
+ screen._selected = 0
+ assert "^U image" in screen.footer_hint
+
+ async def press() -> None:
+ screen.handle("url_code")
+ await asyncio.sleep(0)
+
+ asyncio.run(press())
+ assert len(opened) == 1 and isinstance(opened[0], ImageScreen)
+ assert opened[0].raw == text
+
+
+def test_with_show_mcoimg_off_the_image_is_behind_ctrl_u(monkeypatch) -> None:
+ """With ``show_mcoimg`` off, only the line shows, and ^U on the picked image opens it."""
+ from meshterm.core import preferences
+ from meshterm.ui.pixelart import ImageScreen
+
+ prefs = preferences.Preferences()
+ prefs.set("show_mcoimg", False)
+ monkeypatch.setattr(preferences, "current", lambda: prefs)
+ text = "im3:g/5WjAL`NA"
+ messages = [ChatMessage(text=text, peer="d4e5f6a7")]
+ session = _StubSession()
+ opened = []
+
+ async def run_screen(screen): # noqa: ANN001, ANN202
+ opened.append(screen)
+
+ session.run_screen = run_screen
+ screen = _screen(session, send=None, messages=messages)
+ screen._render_grouped(60)
+ lines = [_strip_ansi(ln) for ln in screen._body_lines(text, messages[0], 60)]
+ assert len(lines) == 1 and lines[0].endswith("image · 4×2 · 4 colours")
+
+ screen._selected = 0
+ assert screen.fkey_lane is not None
+ assert "^U image" in screen.footer_hint
+
+ async def press() -> None:
+ screen.handle("url_code")
+ await asyncio.sleep(0)
+
+ asyncio.run(press())
+ assert len(opened) == 1 and isinstance(opened[0], ImageScreen)
+ assert (opened[0].picture.width, opened[0].picture.height) == (4, 2)
+
+
def test_wrapped_body_hangs_under_the_first_line() -> None:
"""A body that is too long for the width wraps with a hanging indent under its first line."""
from datetime import datetime, timezone
@@ -3806,3 +3889,95 @@ def test_a_sender_with_no_key_opens_trace_target_under_its_name(monkeypatch) ->
_trace_walk(_trace_ctx(), walk, contacts=[], label="Lindsay", node_type=NODE_TYPE_CHAT)
)
assert calls == [("target", "Lindsay", "3d,51,1b,40,1b,51,3d", "Lindsay", NODE_TYPE_CHAT)]
+
+
+# -- the Public offer (issue #36) ---------------------------------------------
+
+
+def test_picker_offers_public_when_the_device_has_none() -> None:
+ """With no Public on the device, the picker offers it on slot 0, as a row that is not on it."""
+ from meshterm.core.channel_probe import ChannelSlot
+ from meshterm.tools.chat import _channels_from_slots
+
+ (offer,) = _channels_from_slots([])
+ assert offer.label == "Public" and offer.channel_idx == 0 and not offer.on_device
+ other = ChannelSlot(1, "#test", derive_secret("#test"))
+ assert [c.on_device for c in _channels_from_slots([other])] == [False, True]
+
+
+def test_picker_has_no_offer_when_public_is_on_the_device() -> None:
+ """A Public channel on any slot is the real row. The picker adds no second Public."""
+ from meshterm.core.channel_probe import ChannelSlot
+ from meshterm.tools.chat import _channels_from_slots
+
+ on_two = _channels_from_slots([ChannelSlot(2, "Public", DEFAULT_PUBLIC_SECRET)])
+ assert [(c.channel_idx, c.on_device) for c in on_two] == [(2, True)]
+ on_zero = _channels_from_slots([ChannelSlot(0, "Public", DEFAULT_PUBLIC_SECRET)])
+ assert [(c.channel_idx, c.on_device) for c in on_zero] == [(0, True)]
+
+
+def test_offer_row_says_the_channel_is_not_on_the_device(repo: Repository) -> None:
+ """The offer row explains itself in the preview lane, and shows no message preview."""
+ from meshterm.tools.chat import _channels_from_slots
+
+ (offer,) = _channels_from_slots([])
+ title = _title(_RowCtx(repo, unread={}), offer, {}, _NO_KEYS, _lanes([offer]))
+ assert "not on the device — Enter adds it…" in title.plain
+
+
+class _OfferUi:
+ def __init__(self, answer) -> None:
+ self.answer = answer
+ self.asked: list[str] = []
+
+ async def dialog(self, prompt, buttons, **_kw):
+ self.asked.append(prompt)
+ return self.answer
+
+
+class _OfferDevstate:
+ def __init__(self) -> None:
+ self.slots: list = []
+
+ async def channel_slots(self):
+ return list(self.slots)
+
+
+def _offer_ctx(answer, monkeypatch: pytest.MonkeyPatch):
+ from types import SimpleNamespace
+
+ from meshterm.core.channel_probe import ChannelSlot
+
+ writes: list[tuple] = []
+ devstate = _OfferDevstate()
+
+ async def write_channel(ctx, device, idx, name, secret) -> None:
+ writes.append((idx, name, secret))
+ devstate.slots.append(ChannelSlot(idx, name, secret))
+
+ monkeypatch.setattr("meshterm.ui.channels.write_channel", write_channel)
+
+ async def device():
+ return object()
+
+ ctx = SimpleNamespace(ui=_OfferUi(answer), devstate=devstate, device=device)
+ return ctx, writes
+
+
+def test_public_offer_cancel_writes_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Cancel on the offer writes nothing and opens nothing: the picker stays."""
+ from meshterm.tools.chat import _add_public_channel
+
+ ctx, writes = _offer_ctx(False, monkeypatch)
+ assert asyncio.run(_add_public_channel(ctx)) is None
+ assert ctx.ui.asked and writes == []
+
+
+def test_public_offer_add_writes_slot_zero(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Add writes Public with its well-known key to slot 0, and returns the real channel."""
+ from meshterm.tools.chat import _add_public_channel
+
+ ctx, writes = _offer_ctx(True, monkeypatch)
+ added = asyncio.run(_add_public_channel(ctx))
+ assert writes == [(0, "Public", DEFAULT_PUBLIC_SECRET)]
+ assert added is not None and added.on_device and added.channel_idx == 0
diff --git a/tests/test_demo.py b/tests/test_demo.py
index badd7e4..8f19ad8 100644
--- a/tests/test_demo.py
+++ b/tests/test_demo.py
@@ -188,3 +188,36 @@ def test_a_mentioned_node_answers(monkeypatch) -> None: # noqa: ANN001 - the py
assert [m.text for m in messages] == [f"Dave-Lachine: {script.REPLIES['Dave-Lachine']}"]
assert messages[0].is_channel and messages[0].channel == 0
assert f"@[{world.SELF.name}]" in messages[0].text
+
+
+def test_a_later_channel_leaves_the_rest_of_the_history_unchanged(monkeypatch) -> None: # noqa: ANN001
+ """A channel after the shared slots draws from its own source of chance.
+
+ The history draws the conversations, then the traces and the neighbours, from one
+ source. When the ``#mcoimg`` channel took numbers from it, the route that the trace
+ of the video learns moved off Mont-Royal, and the trace to Brossard got no reply. So
+ the shared source must end the conversations in the same state with that channel and
+ without it, and so must it after the greetings, which read the lines of each channel.
+ """
+ import random
+
+ from meshterm.demo import script
+
+ now = utcnow()
+
+ def state_after_conversations() -> tuple:
+ rng = random.Random("meshterm-demo/history")
+ history._conversations(now, rng)
+ return rng.getstate()
+
+ assert any(c.slot >= history._SHARED_SLOTS for c in world.CHANNELS) # else it proves nothing
+ with_channel = state_after_conversations()
+ monkeypatch.setattr(
+ world, "CHANNELS", tuple(c for c in world.CHANNELS if c.slot < history._SHARED_SLOTS)
+ )
+ monkeypatch.setattr(
+ script,
+ "CHANNEL_LINES",
+ {name: lines for name, lines in script.CHANNEL_LINES.items() if name != "#mcoimg"},
+ )
+ assert state_after_conversations() == with_channel
diff --git a/tests/test_gallery.py b/tests/test_gallery.py
index 69914c3..3ac3272 100644
--- a/tests/test_gallery.py
+++ b/tests/test_gallery.py
@@ -843,6 +843,35 @@ def _chat_long_url(cols: int, rows: int) -> Screen:
return screen
+#: A real MCOimg image: a woodpecker, 30 x 30, in 74 bytes (refer to tests/test_mcoimg.py).
+_WOODPECKER = (
+ 'im3:J!jBVY"9UPkugAX54#9BX:e"FM|cL0G|IS.@$q^=N:4D*B9d1d$450M>W/tOqmq`wqd..bJp|}'
+ "d/4v2vpi5BAZ9wD/B"
+)
+
+
+def _chat_image(cols: int, rows: int, *, picked: bool = False) -> Screen:
+ """A channel message that is a pixel image: its caption, and the image in half blocks.
+
+ The image is 30 pixels wide, so it fits after the indent of the body on each platform
+ (44 cells on the PicoCalc), and it is 15 rows tall. With ``picked``, the image message
+ is selected, so the hint names ``^U image`` and the lane lights ``Image``.
+ """
+ conv = Conversation(label="Lakeside art", is_channel=True, channel_idx=3)
+ messages = [
+ ChatMessage(text="Alice: drew this on the trail today", is_channel=True),
+ ChatMessage(text=f"Alice: {_WOODPECKER}", is_channel=True),
+ ]
+ screen = ChatScreen(conv, messages, send=None, names={}, session=_GallerySession(cols, rows))
+ if picked:
+ screen.handle("up")
+ return screen
+
+
+def _chat_image_picked(cols: int, rows: int) -> Screen:
+ return _chat_image(cols, rows, picked=True)
+
+
class _PickerChat:
"""The unread counter that the rows of the picker read live."""
@@ -1966,6 +1995,15 @@ def _links_qr(cols: int, rows: int) -> Screen:
)
+def _image_screen(cols: int, rows: int) -> Screen:
+ """The ^U view of a pixel image: the image on a bare frame, its caption, and its text."""
+ from meshterm.core.mcoimg import recognize
+ from meshterm.ui.pixelart import ImageScreen, decoded
+ from meshterm.ui.widgets import pixel_image_text
+
+ return ImageScreen(decoded(_WOODPECKER), pixel_image_text(recognize(_WOODPECKER)), _WOODPECKER)
+
+
def _clock_drift(cols: int, rows: int) -> Screen:
"""The Clock drift page in its fullest form: a managed node, nodes out of sync, a name.
@@ -2040,6 +2078,8 @@ _ENTRIES: list[_Entry] = [
_Entry("chat_urls", _chat_urls),
_Entry("chat_reactions", _chat_reactions),
_Entry("chat_long_url", _chat_long_url),
+ _Entry("chat_image", _chat_image),
+ _Entry("chat_image_picked", _chat_image_picked),
_Entry("chat_picker", _chat_picker),
_Entry("room", _room),
_Entry("room_read_only", _room_read_only),
@@ -2094,6 +2134,7 @@ _ENTRIES: list[_Entry] = [
_Entry("support_project", _support_project),
_Entry("share_qr", _share_qr),
_Entry("links_qr", _links_qr),
+ _Entry("image_screen", _image_screen),
_Entry("diagnostics", _diagnostics),
_Entry("diagnostics-anonymized", _diagnostics_anonymized),
]
diff --git a/tests/test_mcoimg.py b/tests/test_mcoimg.py
new file mode 100644
index 0000000..2039989
--- /dev/null
+++ b/tests/test_mcoimg.py
@@ -0,0 +1,424 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for the recognition of a pixel image (MCOimg) in the body of a message.
+
+The cases come from the reference test vectors of the format
+(``docs/mcoimg-js/tests/v3-js-*-fixtures.json`` and ``v2-js-fixtures.json`` in the
+HDDen/meshcore-open repository, MIT). Each one is the text of an image and the size and
+the palette profile that its encoder used.
+"""
+
+from __future__ import annotations
+
+import json
+import random
+import time
+from pathlib import Path
+
+import pytest
+
+from meshterm.core import mcoimg, mcoimg_palettes
+from meshterm.core.mcoimg import PixelImage, base91_decode, recognize
+from meshterm.core.mcoimg_decode import Picture, _decode_refs, decode
+
+#: (text, width, height, colours) from the version 3 vectors: one case for each mode of
+#: the dimensions and for each palette profile that the vectors use.
+_V3_CASES = [
+ ("im3:g/5WjAL`NA", 4, 2, 4), # rawGlobal, master4, mode 1
+ ("im3:g/LAU)", 1, 1, 4), # solidBackground, the shortest image
+ ("im3:g/)FCtB", 2, 2, 4), # implicitWhiteSolid, mode 0
+ ("im3:TAYL>iBNGbA", 9, 7, 2), # mono, from the encoder vectors
+]
+
+
+@pytest.mark.parametrize(("text", "width", "height", "colours"), _V3_CASES)
+def test_a_version_3_image_gives_its_size_and_colours(
+ text: str, width: int, height: int, colours: int
+) -> None:
+ """The header of a version 3 image gives its size and the colours of its profile."""
+ assert recognize(text) == PixelImage(3, width, height, colours)
+
+
+def test_base91_decodes_to_the_payload_of_the_vector() -> None:
+ """``im3:g/5WjAL`NA`` is the app payload ``E3oBjQBCvgE=`` (base64) of the vectors."""
+ assert base91_decode("g/5WjAL`NA") == bytes.fromhex("137a018d0042be01")
+
+
+def test_a_version_1_or_2_image_has_no_header_to_read() -> None:
+ """An ``im:`` image is an image, but MeshTerm cannot read its header."""
+ assert recognize("im:CC&tj68MFSB") == PixelImage(None)
+
+
+def test_spaces_at_the_ends_are_permitted() -> None:
+ """Spaces and newlines around the image do not stop the recognition."""
+ assert recognize(" im3:g/5WjAL`NA \n") == PixelImage(3, 4, 2, 4)
+
+
+@pytest.mark.parametrize(
+ "body",
+ [
+ "hello",
+ "im: ok", # a person typed it
+ "im:abc", # too short to be an image with no header
+ "im3:g/5WjAL`NA and more", # an image is the whole body
+ "see im3:g/5WjAL`NA",
+ "im3:hello", # Base91, but not the version 3 byte
+ "im:CC&tj68M'SB", # ' is not in the alphabet
+ ],
+)
+def test_text_that_is_not_an_image(body: str) -> None:
+ """Words that a person typed are not an image."""
+ assert recognize(body) is None
+
+
+def test_an_unknown_version_is_an_image_with_no_header() -> None:
+ """A version that MeshTerm does not know is an image with no header."""
+ assert recognize("im4:CC&tj68MFSB") == PixelImage(4)
+
+
+# The pixel decoder of version 3.
+
+_DATA = Path(__file__).parent / "data" / "mcoimg"
+
+#: The palette profiles by name, in the order of their ids.
+_PROFILE_NAMES = (
+ "mono",
+ "master4",
+ "master8",
+ "master16",
+ "master32",
+ "master64",
+ "grayscale16",
+ "grayscale32",
+ "grayscale8",
+ "dynamicGlobal8",
+ "dynamicGlobal16",
+ "dynamicGlobal32",
+ "dynamicGlobal64",
+ "dynamicGlobal128",
+ "dynamicGlobal256",
+ "dynamicGlobal512",
+)
+
+
+def _vectors() -> list[dict]:
+ """All the vectors of the two files of ``tests/data/mcoimg/``."""
+ found = []
+ for name in ("v3-js-decoder-fixtures.json", "v3-js-encoder-fixtures.json"):
+ found += json.loads((_DATA / name).read_text(encoding="utf-8"))["fixtures"]
+ return found
+
+
+_VECTORS = _vectors()
+
+
+def test_the_vector_files_have_all_their_cases() -> None:
+ """The two vector files have 39 and 6 cases."""
+ assert len(_VECTORS) == 45
+
+
+@pytest.mark.parametrize("vector", _VECTORS, ids=[vector["name"] for vector in _VECTORS])
+def test_a_vector_decodes_to_its_palette_references(vector: dict) -> None:
+ """Each vector decodes to its size, its profile, and the reference of each pixel."""
+ indexed = _decode_refs(vector["text"])
+ assert indexed is not None
+ assert (indexed.width, indexed.height) == (vector["width"], vector["height"])
+ assert _PROFILE_NAMES[indexed.profile] == vector["paletteProfile"]
+ assert indexed.refs == vector["pixels"]
+ assert indexed.transparent == vector.get("transparentColor")
+
+
+def _rgb(profile: str, ref: int) -> tuple[int, int, int]:
+ """The colour of a palette reference of a profile, from the colour tables."""
+ if profile.startswith("dynamic"):
+ return mcoimg_palettes.GLOBAL_512[ref]
+ names = {
+ "mono": "MONO",
+ "grayscale8": "GREY_8",
+ "grayscale16": "GREY_16",
+ "grayscale32": "GREY_32",
+ }
+ name = names.get(profile) or "MASTER_" + profile.removeprefix("master")
+ return getattr(mcoimg_palettes, name)[ref]
+
+
+@pytest.mark.parametrize("vector", _VECTORS, ids=[vector["name"] for vector in _VECTORS])
+def test_a_vector_decodes_to_the_colours_of_its_profile(vector: dict) -> None:
+ """Each vector decodes to the RGB colours of its profile, with transparent pixels."""
+ picture = decode(vector["text"])
+ assert picture is not None
+ assert (picture.width, picture.height) == (vector["width"], vector["height"])
+ clear = vector.get("transparentColor")
+ expected = tuple(
+ None if ref == clear else _rgb(vector["paletteProfile"], ref) for ref in vector["pixels"]
+ )
+ assert picture.pixels == expected
+
+
+def test_mono_is_white_and_black() -> None:
+ """In the ``mono`` profile, colour 0 is white and colour 1 is black."""
+ picture = decode("im3:TAYL>iBNGbA") # mono-checker-normal, 9 x 7
+ assert picture is not None
+ assert picture.pixels[:2] == ((255, 255, 255), (0, 0, 0))
+ assert set(picture.pixels) == {(255, 255, 255), (0, 0, 0)}
+
+
+def test_the_transparent_colour_gives_no_colour() -> None:
+ """A pixel of the transparent colour has no colour."""
+ vector = next(v for v in _VECTORS if v["name"] == "master8-transparent-normal")
+ picture = decode(vector["text"])
+ assert picture is not None
+ clear = [pixel is None for pixel in picture.pixels]
+ assert clear == [ref == 0 for ref in vector["pixels"]]
+ assert any(clear)
+ assert not all(clear)
+
+
+def test_the_colour_tables_have_their_sizes() -> None:
+ """Each colour table has the size of its profile, and a dynamic table has no duplicates."""
+ sizes = {
+ "MONO": 2,
+ "MASTER_4": 4,
+ "MASTER_8": 8,
+ "MASTER_16": 16,
+ "MASTER_32": 32,
+ "MASTER_64": 64,
+ "GREY_8": 8,
+ "GREY_16": 16,
+ "GREY_32": 32,
+ "GLOBAL_512": 512,
+ }
+ for name, size in sizes.items():
+ assert len(getattr(mcoimg_palettes, name)) == size, name
+ for size in (8, 16, 32, 64, 128, 256, 512):
+ table = getattr(mcoimg_palettes, f"DYNAMIC_{size}")
+ assert len(table) == size
+ assert len(set(table)) == size
+ assert all(0 <= index < 512 for index in table)
+ assert mcoimg_palettes.DYNAMIC_512 == tuple(range(512))
+
+
+def test_decode_reads_only_version_3() -> None:
+ """The decoder gives ``None`` for an image of version 1 or 2 and for words."""
+ assert decode("im:CC&tj68MFSB") is None
+ assert decode("hello") is None
+ assert decode("im3:hello") is None
+
+
+@pytest.mark.parametrize("vector", _VECTORS, ids=[vector["name"] for vector in _VECTORS])
+def test_a_truncated_image_gives_none(vector: dict) -> None:
+ """An image with the end of its text cut off gives ``None``."""
+ text = vector["text"]
+ for end in range(len("im3:"), len(text) - 1):
+ assert decode(text[:end]) is None
+
+
+def test_a_changed_image_does_not_raise() -> None:
+ """Change each character of each vector. The result can be an image or ``None``."""
+ alphabet = mcoimg._ALPHABET
+ for vector in _VECTORS:
+ text = vector["text"]
+ for index in range(len("im3:"), len(text)):
+ for char in alphabet[::7]:
+ decode(text[:index] + char + text[index + 1 :])
+
+
+def test_random_base91_does_not_raise() -> None:
+ """Random Base91 text after the prefix gives a picture or ``None``, and never an error."""
+ chooser = random.Random(1234)
+ for _ in range(3000):
+ length = chooser.randint(1, 200)
+ text = "".join(chooser.choice(mcoimg._ALPHABET) for _ in range(length))
+ decode("im3:g/" + text)
+ decode("im3:" + text)
+
+
+def test_a_very_long_text_gives_none() -> None:
+ """The decoder does not read a text that is longer than the limit."""
+ assert decode("im3:g/" + "A" * 10_000) is None
+
+
+def _encode_raw_global(width: int, height: int, profile: int, refs: list[int]) -> str:
+ """Encode an image as ``compactBlock`` and ``rawGlobal``: the minimal encoder of the spec.
+
+ Only square sizes up to 64 are done here (dimension mode 0).
+ """
+ assert width == height <= 64
+ bits = max(1, (len(_PROFILE_COLOURS_BY_ID[profile]) - 1).bit_length())
+ fields = [(0, 2), (width - 1, 6), (0x20, 8)] + [(ref, bits) for ref in refs]
+ value = position = 0
+ for field, count in fields:
+ value |= field << position
+ position += count
+ data = bytes([0x13, 0x5A, profile]) + value.to_bytes((position + 7) // 8, "little")
+ return "im3:" + _base91_encode(data)
+
+
+def _base91_encode(data: bytes) -> str:
+ """The basE91 encoder of the spec."""
+ alphabet = mcoimg._ALPHABET
+ out = []
+ queue = count = 0
+ for byte in data:
+ queue |= byte << count
+ count += 8
+ if count > 13:
+ value = queue & 8191
+ if value > 88:
+ queue >>= 13
+ count -= 13
+ else:
+ value = queue & 16383
+ queue >>= 14
+ count -= 14
+ out += [alphabet[value % 91], alphabet[value // 91]]
+ if count:
+ out.append(alphabet[queue % 91])
+ if count > 7 or queue > 90:
+ out.append(alphabet[queue // 91])
+ return "".join(out)
+
+
+_PROFILE_COLOURS_BY_ID = {5: mcoimg_palettes.MASTER_64}
+
+
+def test_a_64_by_64_image_decodes_quickly() -> None:
+ """A 64 x 64 image of 64 colours decodes in less than 50 ms."""
+ chooser = random.Random(5)
+ refs = [chooser.randrange(64) for _ in range(64 * 64)]
+ text = _encode_raw_global(64, 64, 5, refs)
+ start = time.perf_counter()
+ picture = decode(text)
+ elapsed = time.perf_counter() - start
+ assert picture is not None
+ assert picture.pixels == tuple(mcoimg_palettes.MASTER_64[ref] for ref in refs)
+ assert elapsed < 0.05
+
+
+def test_a_picture_draws_two_pixels_in_each_cell() -> None:
+ """Half blocks: the top pixel is the colour, the bottom pixel is the background."""
+ from meshterm.ui.pixelart import picture_text
+
+ red, blue = (255, 0, 0), (0, 0, 255)
+ picture = Picture(2, 3, (red, None, blue, red, red, None))
+ lines = picture_text(picture, 10, indent=2).plain.split("\n")
+ # Row 0 over row 1: red over blue, nothing over red. Row 2 alone: red, nothing.
+ assert lines == [" ▀▄", " ▀ "]
+
+
+def test_a_wide_picture_becomes_smaller_to_fit_the_lane() -> None:
+ """An image wider than the lane keeps its proportions and fits the lane."""
+ from meshterm.ui.pixelart import fit
+
+ assert fit(64, 64, 40, 40) == (40, 40)
+ assert fit(16, 16, 40, 40) == (16, 16) # never larger
+ assert fit(30, 30, 53, 5) == (10, 10) # five rows hold ten pixels
+
+
+def test_the_image_screen_makes_a_small_image_larger() -> None:
+ """On its bare frame, a 4 x 2 image grows by a whole number to fill the frame."""
+ from meshterm.ui.pixelart import fit
+
+ assert fit(4, 2, 72, 22, grow=True) == (72, 36) # 18 times: the width is the limit
+ assert fit(16, 16, 53, 24, grow=True) == (48, 48) # 3 times: 24 rows hold 48 pixels
+ assert fit(4, 2, 72, 22) == (4, 2) # under a message, never larger
+
+
+@pytest.mark.parametrize(("cols", "rows"), [(72, 24), (120, 40), (53, 26), (53, 14)])
+@pytest.mark.parametrize("text", ["im3:g/5WjAL`NA", "im3:TAYL>iBNGbA"])
+def test_the_image_screen_centres_the_image_with_a_margin(text: str, cols: int, rows: int) -> None:
+ """On its bare frame, the image is centred, a little above the middle, with page around it."""
+ import re
+
+ from meshterm.ui.pixelart import ImageScreen
+ from meshterm.ui.tui.frame import compose_bare
+ from meshterm.ui.widgets import pixel_image_text
+
+ screen = ImageScreen(decode(text), pixel_image_text(recognize(text)))
+ for _ in range(2): # the first paint tells the screen its rows
+ frame = compose_bare(screen, cols, rows)
+ lines = [re.sub(r"\x1b\[[0-9;]*m", "", line) for line in frame.split("\n")]
+ ink = [index for index, line in enumerate(lines) if line.strip()]
+ above, below = ink[0], rows - 1 - ink[-1]
+ assert 1 <= above <= below
+ art = lines[ink[0]]
+ left, right = len(art) - len(art.lstrip()), cols - len(art.rstrip())
+ assert left >= 2 and right >= 2
+ assert abs(left - right) <= 1
+
+
+def test_the_image_screen_shows_the_text_of_the_message_under_the_caption() -> None:
+ """Under the image and its caption, the full screen shows the ``im3:`` string itself."""
+ import re
+
+ from meshterm.ui.pixelart import ImageScreen
+ from meshterm.ui.tui.frame import compose_bare
+ from meshterm.ui.widgets import pixel_image_text
+
+ text = "im3:TAYL>iBNGbA"
+ screen = ImageScreen(decode(text), pixel_image_text(recognize(text)), text)
+ for _ in range(2):
+ frame = compose_bare(screen, 72, 24)
+ lines = [re.sub(r"\x1b\[[0-9;]*m", "", line).strip() for line in frame.split("\n")]
+ caption = next(i for i, line in enumerate(lines) if "image · 9×7 · 2 colours" in line)
+ assert text in lines[caption + 1 :]
+
+
+#: A real image, from an MCOimg encoder and not from the small encoder of these tests: a
+#: woodpecker on a green ground, 30 x 30, in 74 bytes. It uses the 512-colour dynamic
+#: profile and the compact regions stream with three regions, which the reference vectors
+#: test only on very small images. The pixels below were checked by eye (2026-11-20).
+_WOODPECKER = (
+ 'im3:J!jBVY"9UPkugAX54#9BX:e"FM|cL0G|IS.@$q^=N:4D*B9d1d$450M>W/tOqmq`wqd..bJp|}'
+ "d/4v2vpi5BAZ9wD/B"
+)
+
+
+def test_a_real_image_decodes_to_its_pixels() -> None:
+ """The woodpecker decodes to its size, its profile, and the same pixels each time."""
+ import hashlib
+ from collections import Counter
+
+ assert recognize(_WOODPECKER) == PixelImage(3, 30, 30, 512)
+ indexed = _decode_refs(_WOODPECKER)
+ assert indexed is not None
+ assert indexed.profile == 15 # dynamicGlobal512
+ assert indexed.transparent is None
+ refs = b"".join(ref.to_bytes(2, "little") for ref in indexed.refs)
+ assert hashlib.sha256(refs).hexdigest() == (
+ "38a9e47e914e2897fa54e054fb3f0b580c88c8b9df67a2b818a1a7ea68e1bd28"
+ )
+ picture = decode(_WOODPECKER)
+ assert picture is not None
+ assert Counter(picture.pixels) == {
+ (168, 225, 139): 726, # the green ground
+ (0, 0, 0): 118, # the black body
+ (255, 255, 255): 23, # the white stripes
+ (79, 79, 79): 19, # the grey beak and feet
+ (254, 41, 7): 13, # the red crest
+ (181, 157, 2): 1, # the eye
+ }
+
+
+def test_an_image_keeps_its_own_size_on_a_small_frame() -> None:
+ """The woodpecker stays 30 x 30 in the transcript and on the full screen of 53 x 14.
+
+ It is taller than the 14 rows of the Cardputer, so it scrolls. It never becomes
+ smaller (JP, 2026-11-20). Only a frame with more room makes it larger.
+ """
+ import re
+
+ from meshterm.ui.pixelart import ImageScreen, picture_text
+ from meshterm.ui.tui.frame import compose_bare
+ from meshterm.ui.widgets import pixel_image_text
+
+ picture = decode(_WOODPECKER)
+ assert picture is not None
+ inline = picture_text(picture, 42).plain.split("\n")
+ assert len(inline) == 15 and {len(line) for line in inline} == {30}
+
+ screen = ImageScreen(picture, pixel_image_text(recognize(_WOODPECKER)), _WOODPECKER)
+ for _ in range(2):
+ compose_bare(screen, 53, 14)
+ page = [re.sub(r"\x1b\[[0-9;]*m", "", line).strip() for line in screen.render_body(53)]
+ art = [line for line in page if line and set(line) <= set("▀▄█")]
+ assert len(art) == 15 and {len(line) for line in art} == {30}