One keyboard and mouse for a Mac and a Windows PC over the local network, in either direction.
Beamer 1.5.1
Toby Kalkmanae17f4773714
diff --cc README.mdindex 7b7d711,5afb69d..b952201--- a/README.md+++ b/README.md@@@ -16,13 -16,13 +16,13 @@@ still work, and what you type never lea## Download- Free, with no account. Mac and Windows downloads are on the [releases page](https://github.com/kalkman-code/beamer/releases/latest).-Free, with no account. Every installer is on the [releases page](https://github.com/kalkman-code/beamer/releases/latest).++Free, with no account. Mac and Windows downloads, and an experimental Linux Flatpak, are on the [releases page](https://github.com/kalkman-code/beamer/releases/latest).| Platform | Get it | Notes ||---|---|---|-| macOS 13 or later, Apple silicon | `Beamer-<version>.dmg` | Signed and notarised by Apple. Not for Intel Macs |+| macOS 13 or later, Apple silicon or Intel | `Beamer-<version>.dmg` | One universal app, signed and notarised by Apple || Windows 10 and 11 | `Beamer-Setup-<version>.exe` | Not code-signed; see step 1 below |- | Linux, through Flatpak (experimental) | Build and install using [the Linux instructions](docs/flatpak-build.md) | GNOME on Wayland, or X11; not yet tested on a real desktop |-| Windows, through winget | `winget install KalkmanCode.Beamer` | The same installer, without the warning |++| Linux, through Flatpak (experimental) | `Beamer-<version>-x86_64.flatpak`, or build it with [the Linux instructions](docs/flatpak-build.md) | GNOME on Wayland, or X11; tested on one GNOME Wayland desktop |## Quick start@@@ -32,14 -32,17 +32,15 @@@the pointer crosses but the keyboard does not. On Windows,run the installer. It is not code-signed, because a certificate costs money and Beamer is free,so Windows says "Windows protected your PC" the first time: choose More info, then Run anyway.- Beamer on Windows runs as administrator, so expect one UAC prompt when you open it. For Linux,- follow [the Flatpak build and install instructions](docs/flatpak-build.md).- winget does not show that warning. Beamer on Windows runs as administrator, so expect one UAC- prompt when you open it.-2. **Pair them.** Both Overview pages lead with pairing until it is done. On the PC, press Pair a- Mac; a six-digit code appears. On the Mac, choose the PC from the list and type the code. It- lasts a minute and works once. If the PC never appears in the list, as on guest Wi-Fi or across- a VPN, type the address the PC shows next to its code into "PC not listed?" on the Mac and press- Find. The PC joins the list, and you pair with the code as before.-3. **Cross.** Push the Mac's pointer off the right-hand edge of its screen, or double-tap Right- Option, and the Mac's keyboard and trackpad are on the PC. Push back through the PC's left edge,- or double-tap again, to come home. The PC's own keyboard and mouse go the other way: push- through the same edge, or double-tap Right Ctrl.++ Beamer on Windows runs as administrator, so expect one UAC prompt when you open it. On Linux,++ install the Flatpak with `flatpak install --user Beamer-<version>-x86_64.flatpak`, or build it with++ [the Flatpak instructions](docs/flatpak-build.md).+2. **Pair them.** On one machine, choose Pair a machine to show a six-digit code. On the other,+ choose that machine from the list and enter the code. It lasts a minute and works once. If it+ does not appear in the list, enter the address shown with its code on the other machine.+3. **Cross.** Push the pointer through the edge you set, or use the shortcut. On Wayland, an edge+ sends input out and the shortcut brings it back. The other machine's keyboard and pointer come+ with it. Cross back through the edge or use the shortcut again.That is all most people need. The edge, the keys and everything else can be changed in eachmachine's settings.@@@ -136,10 -127,16 +137,10 @@@ when Same on all machines is onkeyboard there.- **Files do not cross**, only text and images, up to 256KB of text and an 8MB image.- **AltGr is out of reach from the Mac.**-- **A dead key typed on the PC does not cross**, so an accent typed as two keys on the PC's- layout arrives on the Mac without it. Shortcuts and letters follow each machine's own layout.-- **Intel Macs are not supported.** The Mac app is built for Apple silicon only.-- **The Windows installer is unsigned.** SmartScreen warns until it has a download history; winget- avoids it.-- **macOS 27 beta 4 could block a signed app's local-network access** even when Terminal could- reach the PC. The released macOS 27 does not, so the DMG no longer carries a workaround; for that- beta, `mac_app/Beamer Tunnel.command` in this repository forwards the link over SSH: open it,- leave its window running, then open Beamer, which uses the tunnel only when its direct connection- is blocked.+- **Linux on Wayland has fewer controls.** Its limits are listed under [Linux](#linux).- - **Linux gestures are not supported.** Linux can still receive zoom and back/forward as key chords.++- **Linux gestures are not supported.**+- **The Windows installer is unsigned.** SmartScreen may warn when you first run it; choose More+ info, then Run anyway.## In detail@@@ -267,8 -267,8 +268,8 @@@ the Mac's system gestures do the equiva| Three or four fingers left or right (Spaces) | Switch virtual desktop, the same way round || Thumb and three fingers spread (Show desktop) | Show desktop || Thumb and three fingers pinched (Launchpad) | Start |--| Two-finger pinch | Zoom (Ctrl+scroll) |--| Two-finger swipe between pages | Back and forward (Alt+Left/Right) |++++A two-finger pinch and a two-finger swipe between pages are not passed to the other machine yet.The Mac classifies a system gesture when it ends and sends one message. The PC replays it as a realswipe through a synthetic Precision Touchpad, so Windows' own touchpad settings apply and Task View@@@ -356,29 -357,6 +357,32 @@@ password. Without it, the Mac reports `</details>+<a id="linux"></a>+<details>+<summary><strong>Linux</strong></summary>+- Linux support is experimental: the window, tray and pairing with other machines have not yet been- tested on a real Linux desktop. Build and install Beamer with- [the Flatpak instructions](docs/flatpak-build.md). Flatpak needs Flathub to install the KDE runtime++Linux support is experimental. Install the x86_64 Flatpak from the release page with++`flatpak install --user Beamer-<version>-x86_64.flatpak`, or build it with++[the Flatpak instructions](docs/flatpak-build.md). On one Fedora 44 GNOME desktop under Wayland,++paired with a Mac and with a Windows PC, the window and tray, pairing, crossing both ways, typing and the clipboard work;++there, crossings show no edge animation on the Linux machine and the selected option in settings is++not filled in. X11 on real hardware has not been tested. Flatpak needs Flathub to install the KDE runtime+if it is not already present. The same package is built for GNOME under Wayland and for X11.++On Wayland, the desktop limits what Beamer can do:++- “On Wayland the shortcut only brings input back: the desktop lets input go to another machine only+ when the pointer pushes through an edge, and keys on the Stays on this PC list cannot stay here+ while input is away.”+- “On Wayland Beamer cannot see a full-screen app, or a mouse button held before the pointer reaches+ an edge, so the edges are never held for one and a drag can cross.”+- “On Wayland the desktop does not let Beamer draw at the edges of the screen, so crossings show no+ effect on this machine. The other machines still show theirs.”++Linux does not offer gestures. KDE Plasma has not been tested.++</details>+<details><summary><strong>Building from source</strong></summary>diff --cc VERSIONindex bc80560,1c99cf0..26ca594--- a/VERSION+++ b/VERSION@@@ -1,1 -1,1 +1,1 @@@- 1.5.0-1.4.4++1.5.1diff --cc WIRE.mdindex 9c6a02b,0000000..662378fmode 100644,000000..100644--- a/WIRE.md+++ b/WIRE.md@@@ -1,1458 -1,0 +1,1470 @@@+# The link, wire version 6++How machines running Beamer 1.5.0 and later know each other, open an encrypted link, and hand+input from one to another, exactly enough to write a second implementation. Pairing, the+exchange that gives two machines their shared token, is in [PAIRING.md](PAIRING.md); this file+says what changes in it for 1.5.0 and otherwise leans on it. What the link protects and what it+does not is in [SECURITY.md](SECURITY.md).++Version 6 replaces version 5 (1.4.1 to 1.4.3) outright. Version 5 had two machines and two roles,+a Mac and a PC; version 6 has any number of machines, each with its own identity, and a platform+is something a machine says about itself rather than what it is. There is no fallback: a+machine on version 6 refuses a version 5 peer and says which machine to update.++Beamer 1.5.0 is built to it. The last sections list where it departs from version 5 and from its+first design, what has been decided, and the questions still open.++## Terms++- **Machine.** One install of Beamer: a desktop app, or later a phone app. Each has an id.+- **Peer.** A machine this one has paired with. Each peer has its own token.+- **Link.** One TCP connection between two peers. The machine that opens it is the+ **initiator**; the one that accepts it is the **responder**. Input only ever travels from+ initiator to responder, so between two desktops that may each drive the other there are two+ links, one each way, as in version 5. A phone only ever initiates.+- **Owner.** The machine whose input a responder is injecting now. A responder has at most one+ owner at a time, or none. The owner is always the initiator of the link the input arrives on.+- **Route.** A number the owner raises each time it moves its input, so that a late request+ cannot move input that has already moved.+- **Zone.** A stretch of a machine's own screen (an edge, part of one, a corner or the notch)+ that leads to one peer.++## Encodings++- **Ids.** A machine id is 16 bytes from the operating system's secure random source, made once+ per install. Sixteen zero bytes is never an id. In JSON and in the settings file it is+ PAIRING.md's `b64` (URL-safe base64 without padding, 22 characters), with the same rule:+ decode, encode again, and refuse the text if it differs. A machine id never travels in the+ clear on a link: the preamble carries the pair's key id instead (section 2). Pairing sends+ both machines' ids in the clear, once (section 6).+- **Tokens.** A token made by pairing is the `b64` of 32 bytes: 43 characters that decode and+ encode again to themselves. That spelling proves nothing about where a token came from: 43 `A`s+ spell 32 zero bytes, and a user could have typed them. So what links is an entry made by+ pairing on 1.5.0 or later (`from_1_4` false) whose token has that spelling. A token migrated+ from 1.4.x never links, whatever its spelling, and neither does one of any other shape, a+ **typed token** (sections 1 and 2).+- **Messages** are UTF-8 JSON objects of the shape `{"type": <string>, "data": <object>}`, with+ no byte order mark. Unknown types are ignored, and so are unknown keys inside `data`.+- **Not a message.** A frame's plaintext that is not UTF-8, not JSON, or JSON whose top level is+ not an object (`[]`, `"x"`, `1`) is not a message at all. It ends the link once the handshake+ is done (section 2, frames); as the first frame it is answered `invalid_hello` (section 2,+ step 7). Nothing below applies to it.+- **Malformed messages.** A message is malformed when it has no string `type` or no object+ `data`, holds `NaN` or an infinity, or has a known field whose value is outside what this+ document allows; section 10's shared values are the one exception, each left out on its own.+ A field that does not belong to a message, or to that kind of the message, is ignored like an+ unknown one. A sender never repeats a key; a receiver may refuse a message that does, or keep+ the last value (Swift's decoders keep the last, Android's `org.json` refuses), and neither may+ matter to what a correct sender sends. A malformed message is ignored as a whole, with three+ exceptions: a malformed first frame and a malformed `ack` end the link, and a malformed `focus`+ naming the receiver is answered with `refuse` (section 5). A receiver whose JSON parser+ refuses outright a text that breaks one of the rules above the parser cannot see past (a byte+ order mark, `NaN`, a lone surrogate) may end the link instead of ignoring the message; a+ correct sender never sends one, and the vectors record what the desktops do, which is to+ ignore it.+- **Numbers.** "Integer" means a JSON number with no fraction or exponent (`1`, never `1.0` or+ `1e0`), and never `true` or `false`. A parser that turns JSON into a platform number type must+ check the text, not the value: Swift's `JSONSerialization` gives `true` and `1.0` as numbers+ that cast to `1`. "Number" means any finite JSON number.+- **Strings.** Lengths are in Unicode code points unless a limit says bytes, and a string is+ malformed if it is not valid Unicode (a lone surrogate).+- **Names** are 1 to 48 code points, cut and checked exactly as PAIRING.md says.+- **Platforms** are `"macos"`, `"windows"`, `"linux"`, `"ios"` and `"android"`. Any other+ string of 1 to 16 characters from `a-z`, `0-9` and `_` is accepted and treated as `"linux"` for+ the key table; anything else is malformed.+- **Hex in the vectors** is bytes in wire order.++## 1. Identity and the peers list++### What each machine keeps++Each app keeps its settings in one JSON file:++| App | File |+|---|---|+| Mac | `~/Library/Application Support/Beamer/settings.json` |+| Windows | `%LOCALAPPDATA%\Beamer\settings.json` |+| Linux | `$XDG_CONFIG_HOME/Beamer/settings.json`, else `~/.config/Beamer/settings.json` |++Beside the machine's other settings, which keep the names 1.4.x gave them, it holds:++| Field | Meaning |+|---|---|+| `schema` | `6` |+| `machine_id` | this machine's id, `b64` |+| `name` | this machine's name as shown to peers; the computer's name when empty |+| `port` | the TCP port this machine accepts links on, 24820 unless the user chose another |+| `shortcut` | whether the switch shortcut is one of this machine's ways across |+| `peers` | a list of peer entries, below, at most 32 |+| `zones` | this machine's zones, section 8 |+| `migrated_token_sha256` | lower-case hex SHA-256 of the UTF-8 of the last 1.4.x `auth_token` migrated, or `""` |++A peer entry:++| Field | Type | Meaning |+|---|---|---|+| `id` | `b64` or `""` | the peer's machine id; `""` only for the entry migrated from 1.4.x |+| `name` | string | the peer's name, from pairing, then from every `hello` or `welcome` |+| `platform` | string | the peer's platform, from pairing, then from every `hello` or `welcome` |+| `token` | string | the shared token from pairing, never reused for another peer |+| `host` | string | the IPv4 address to open a link to the peer at; `""` for a phone |+| `port` | integer | the peer's own link port; 0 for a phone, which is never dialled |+| `hw` | string | the peer's hardware address for wake-on-LAN, `aa:bb:cc:dd:ee:ff`, or `""` |+| `send` | boolean | this machine's input may go to the peer |+| `allow_drive` | boolean | the peer may drive this machine |+| `side` | string | which edge of this machine faces the peer (`left`, `right`, `top`, `bottom`), or `""` |+| `side_set_at` | integer | unix seconds of the last change to `side` at either end, 0 when never changed |+| `side_by` | `b64` or `""` | the machine that made that change; `""` only with `side_set_at` 0 |+| `paired_with` | list of `b64` | the ids the peer last said it is paired with (the `paired` message) |+| `paired_at` | integer | unix seconds of the pairing, 0 for a migrated entry |+| `linked` | boolean | a version 6 link with this peer has authenticated at least once |+| `from_1_4` | boolean | this entry was migrated from a 1.4.x pairing, and never links |+| `way_back` | boolean, optional | what the peer last said in `arrangement`'s `way_back` (section 8): whether one of its zones leads here; absent until it says |+| `way_back_by` | `b64`, optional | what the peer last said in `arrangement`'s `way_back_by` (section 8): the machine whose zone holds the side it has for this one; absent when it named none |++Rules:++- **Two entries never share an id**, and no entry has this machine's own id. Pairing refuses+ both (section 6), and a link that would make either true is refused (section 2).+- **Two entries never share a key id** (section 2: 16 bytes computed from the token, never+ stored). Pairing refuses a token whose key id is already an entry's (section 6), and the+ re-migration below skips one. With tokens from pairing a clash means the same token twice.+- **At most one entry has `id: ""`**, and it is the one with `from_1_4: true`. Zones for it+ name it by `""`.+- **An entry migrated from 1.4.x, or with a typed token,** is kept and shown, but never linked:+ it is not dialled, the responder never computes or matches its key id, and Overview asks the+ user to pair that machine again: "*name* was paired on Beamer 1.4. Pair the two again to link+ them on 1.5.0." A new pairing with that machine replaces it (section 6).+- **Removing a peer** resets a local Match design with selection to None, then deletes its entry+ and token, closes its links, and ends its ownership if it holds it (section 4). Its next link's+ key id is unknown here, so it is closed with nothing sent, and the peer says this machine closed+ the connection (section 2).+- **Turning `allow_drive` off** ends that peer's ownership at once. Turning `send` off lets go of+ that peer if this machine's input is on it, and closes the link this machine opened to it.+- **Writes are atomic**: a new file beside the old, then a rename over it.+- The machine id never changes for the life of the settings file. A new file (the user deleted+ it, or a fresh install) is a new machine, which every peer must pair with again. A file copied+ to a second computer (a restored backup, a migration assistant) makes two machines with one+ id and the same tokens: their peers see one machine whose links keep replacing each other.+ Deleting `settings.json` on the copy makes it a new machine.++### The migration from 1.4.x++1.4.x keeps its settings in `config.json` in the same folder, shaped differently on each app.+Each app migrates its own when it starts and finds no `settings.json`:++1. Read `config.json`. If it is missing or does not parse, start with defaults and no peers.+2. Make the machine id.+3. Copy every field 1.5.0 still uses under the same name, then move the pairing fields into one+ peer entry as the tables below say. When `auth_token` is empty, there is no peer entry.+4. Set `migrated_token_sha256` from `auth_token` (`""` when it is empty).+5. Write `settings.json` atomically. Never write `config.json` again.++On the Mac:++| 1.4.x field | Becomes |+|---|---|+| `host` | `peers[0].host` |+| `port` | `port`, and `peers[0].port` |+| `auth_token` | `peers[0].token` |+| `pc_name` | `peers[0].name` |+| `mac_address` (the PC's, for wake-on-LAN) | `peers[0].hw` |+| `send_to_windows` | `peers[0].send` |+| `allow_windows_to_drive` | `peers[0].allow_drive` |+| `crossing.edge` | `peers[0].side` |+| `crossing.arrangement_set_at` | `peers[0].side_set_at` |+| `crossing.methods`, `crossing.edge_parts`, `crossing.corner` | `zones`, and `shortcut` (section 8) |+| `key_map` | kept as it is: a style name, or a map (section 7) |+| — | `peers[0]`: `platform` `"windows"`, `id` `""`, `from_1_4` true, `linked` false, `paired_at` 0 |++On Windows:++| 1.4.x field | Becomes |+|---|---|+| `mac_host` | `peers[0].host` |+| `port` | `port`, and `peers[0].port` |+| `auth_token` | `peers[0].token` |+| `paired_with` | `peers[0].name` |+| `mac_hardware_address` | `peers[0].hw` |+| `send_to_mac` | `peers[0].send` |+| `allow_mac_to_drive` | `peers[0].allow_drive` |+| `mac_return_edge` | `peers[0].side` |+| `arrangement_set_at` | `peers[0].side_set_at` |+| `crossing_methods`, `crossing_edge_parts`, `crossing_corner` | `zones`, and `shortcut` (section 8) |+| `modifier_style` | kept as it is (section 7) |+| `host` (this PC's own address, as shown) | dropped: the pairing sheet shows the live address |+| `mac_resistance_px` | dropped: the owner sends its resistance with every `focus` |+| — | `peers[0]`: `platform` `"macos"`, `id` `""`, `from_1_4` true, `linked` false, `paired_at` 0 |++On both, `peers[0].side_by` is this machine's own id when `side_set_at` is above 0, else `""`:+two migrated ends that disagree at the same second then settle by the larger id (section 8).++Every other field (the shortcut key and style, the Design page, pointer and scroll speed, the+keys that stay, appearance, update checks, Hide addresses, Same on both machines) keeps its+1.4.x name and value. A field 1.4.x did not have takes its default.++**Idempotent.** Once `settings.json` exists, starting again changes nothing in it (unless `config.json`'s+token has changed, below), and+`config.json` is byte for byte what 1.4.x left. A start that fails before step 5 leaves no+`settings.json`; the next start migrates again with a new machine id, which no peer has learnt.++**Downgrade.** Because `config.json` is never written, installing 1.4.x again finds its own+settings as they were at the upgrade. Changes made under 1.5.0 do not go back with it. Both+machines have to go back, because a 1.4.x machine speaks version 5, which 1.5.0 refuses.++**Pairing again under 1.4.x, then upgrading again.** On every start that finds `settings.json`,+if `config.json` holds a non-empty `auth_token` whose SHA-256 differs from+`migrated_token_sha256`, that one pair is migrated again: the `from_1_4` entry is replaced (or+added, if the user had removed it, in which case it gets zones from `config.json`'s methods as the first+migration made them, and is not added at all when the list already holds 32), with `id` `""`, `linked` false and `paired_with` empty; zones+that named the replaced entry name `""`; and `migrated_token_sha256` is updated. A token that+has not changed is never migrated twice, so a peer the user removed stays removed. A token whose+key id is another entry's already is not migrated, and `migrated_token_sha256` is still updated.+A typed token is never refused by that check. Either way the migrated entry never links.++**Why a migrated pairing never links.** 1.4.x kept one `auth_token` and nothing about where it+came from: pairing wrote it, and so did the token field on the Mac's Connection page and the+PC's settings, and the name pairing saved beside it stayed when a user typed a new token. A+typed token can be weak, and its key id (section 2), seen on any link, lets someone test guesses+against it offline. The spelling cannot tell the two apart, so the migration keeps the entry to+show the user which machine it was, and the user pairs the two again. The entry keeps `id: ""`,+since 1.4.x never had ids. 1.5.0's first two betas let a migrated token of pairing's spelling+link and learn its peer's id; such an entry keeps that id and does not link either.++## 2. The link++### Who connects to whom++Every desktop listens on its `port` for links from its peers. It keeps one link open to each+peer with `send` true, a `host` and a non-zero `port`, reconnecting every two seconds while it is+down, as version 5 did for its one peer. A phone listens for nothing; it opens a link to each+desktop it is paired with while its app is open, at once when the app comes to the front and+every two seconds while a link is down.++Version 5's Mac could reach its PC through an SSH tunnel on 127.0.0.1:24822 when macOS 27's+local network rules blocked it. 1.5.0 keeps it for the one peer whose address the tunnel was set+up for; a link that arrives from a loopback address never changes a saved `host`.++### The preamble++Each side's first bytes are a preamble, in the clear:++| Offset | Bytes | Field |+|---|---|---|+| 0 | 5 | `BEAMY`, ASCII |+| 5 | 1 | the version, `0x06` |+| 6 | 8 | the nonce prefix: random, new for every link |+| 14 | 16 | the pair's key id (below) |+| 30 | 32 | the sender's ephemeral X25519 share: new for every link |++62 bytes in all, the same layout both ways. The key id is in the clear so the responder can+choose the one token to try before anything is decrypted; it belongs to the pair, not to either+machine, so the responder's preamble carries the same key id as the initiator's. Neither+machine's id is in the clear: each travels inside the first frame (`hello` and `welcome`) and is+checked there.++```+key_id = HKDF-SHA-256(ikm = the token as saved, as text, salt = b"beamer-link-v6",+ info = b"beamer-key-id", length = 16)+```++That is the first 16 bytes of HKDF's first block. Every entry's key id is computed from its token+when it is needed and never stored. A key id is an offline test of its token, harmless for 256+random bits and fatal for a typed word, and a token's spelling cannot tell the two apart, so a+key id is only ever sent or matched for an entry this machine made by pairing on 1.5.0 or later+(section 1). Every other entry is never used for a link at all.++The ephemeral share is `X25519(secret, 9)` (RFC 7748's base point), from 32 bytes of fresh+randomness the side draws for this link alone and forgets once the link's keys are made.++### The handshake++The responder:++1. Holds at most four connections in their handshakes, and at most one from any one address+ (the source IPv4 address, whatever the port). A new connection from an address that already+ has one replaces it; a new one from another address when four are held replaces the oldest.+ An authenticated link never counts against the four. The preamble must arrive within **1 second**+ and the whole handshake within **5 seconds** of the connection being accepted. Beside the+ four slots, at most **32** connections are being dealt with before they authenticate,+ counting those in a slot, those being answered and drained (step 2) and those whose slot+ was taken by a newer one but are not yet closed; a connection past the 32 is closed at+ once, with nothing read or sent.+2. Reads 6 bytes.+ - Not `BEAMY`: a Beamer from before version 4, which opened with a cleartext frame. It+ answers with the version 5 legacy frame, a 4-byte big-endian length then the JSON+ `{"type":"welcome","data":{"version":6,"error":"version_mismatch"}}`, and closes.+ - Any version below 6: reads the 8 bytes left of a 14-byte version 4 or 5 preamble, answers+ with the **short reply** (`BEAMY`, `0x06`, 8 random bytes: 14 bytes, no id), and closes.+ A version 5 Beamer reads that as a newer peer and says so in its own words. This machine's+ status names the peer whose `host` is the connection's address, if one is.+ - A version above 6: answers with the short reply and closes.++ Wherever it answers and closes, it frees the connection's handshake slot, shuts its sending+ side, then reads and discards what the peer sends for up to one second, so the answer is+ not lost to a reset. At most **8** connections drain at once; past that one is closed as+ soon as its answer is sent, without draining. A draining connection still counts against+ the 32 of step 1.+3. Reads the other 56 bytes, and looks up the entry made by pairing (section 1) whose token has+ this key id. None: it closes, sending nothing. There is never a second try with another+ token, and no entry is looked up by anything else.+4. Draws its own ephemeral secret and share, and computes the shared secret from the+ initiator's share (below). When the result is 32 zero bytes, or the platform's X25519 refuses+ the share, it closes, sending nothing.+5. Draws its own nonce prefix, drawing again while it equals the initiator's, and sends its+ preamble, with the same key id.+6. Makes the two keys (below) and reads the first frame, whose length field must be at least+ 21 and at most **4096**; a larger claim is refused before the frame is read. A frame that+ fails its tag, or whose counter is not 1, closes the link with nothing sent back.+7. Requires that frame to be a valid `hello` (below). Any first frame whose tag checks but which+ is not a valid `hello` (a plaintext that is not JSON or not an object, another `type`, a+ malformed field) is answered with `welcome` carrying only `version` 6 and+ `error: "invalid_hello"`, and the link is closed. This is the one place a plaintext that is+ not a JSON object is answered rather than ending the link at once. A paired peer with `in_use`+ set to `false` receives this same refusal after its authenticated `hello`.+8. Checks the `id` in `hello`. When it is this machine's own, or is not the entry's, it answers+ `welcome` carrying only `version` 6 and `error: "wrong_id"`, and closes. Only a holder of the+ token can read that answer, so it tells nobody else anything. Otherwise it sets `linked`, and+ saves what changed.+9. Sends `welcome`, then its announcements (section 3).+10. Closes any earlier link it accepted from the same peer id; a link this machine opened to that+ peer is a separate link and stays. If the closed link's peer was the owner, the ownership+ ends first (section 4).++The initiator:++1. Connects, with a one-second timeout. From the moment the connection is up, the whole+ handshake must finish within **5 seconds**. It dials only an entry made by pairing (section 1).+2. Draws its ephemeral secret and share and sends its preamble, with the entry's key id.+3. Reads 6 bytes.+ - Not `BEAMY`: says the peer did not answer as a Beamer, and closes.+ - A version below 6: reads the 8 bytes left, closes, and says the peer runs an older Beamer,+ naming it: "Update Beamer on *name*: it is older than this one."+ - A version above 6: closes and says this machine is the older one.+ - The connection closes or resets before a byte arrives. A responder that does not know the+ key id closes like this, and so does a version 5 responder, after reading 14 of the 62+ bytes; on Windows and Linux that close can destroy the version 5 preamble in flight. So:+ when the entry has never linked on version 6 (`linked` false), "Update Beamer on *name* to+ 1.5.0; if it is up to date, pair the two again"; otherwise "*name* closed the connection: it- may have removed this machine, or be too busy to answer".++ may have removed this machine, or be too busy to answer". After such closes, and nothing else,++ for 60 seconds running on an entry that has linked (any other result starts the 60 seconds++ again), it says "*name* no longer has this pairing: remove *name* here++ and pair the two again", and dials that entry every 30 seconds rather than every 2 until a++ link is made or the entry changes.+ - Nothing within the handshake's 5 seconds (the initiator has no separate deadline for the+ preamble): says the peer is probably running a Beamer from before version 4.+4. Reads the other 56 bytes and checks them: the prefix must differ from its own, and the key id+ must be the one it sent. It computes the shared secret from the responder's share, which must+ not give 32 zero bytes or be refused by the platform's X25519. On any failure it closes+ without sending anything and says a different Beamer answered at that address.+5. Makes the two keys, sends `hello`, and reads the `welcome`, whose length field is also held+ to 21 to 4096. The key id matched, so the peer holds this token: a failed tag here means+ something on the path altered the link ("*name* could not be authenticated"), and a closed+ connection says what a close in step 3 says, by `linked`.+6. Requires a valid `welcome`. One with `error: "invalid_hello"` means this app sent something+ the peer could not read; it says so and closes. One with `error: "wrong_id"` means the peer+ holds this pair's token under another machine's id: it closes, stops dialling that entry until+ its settings change or the app starts again, and says "*name* has this pairing under another+ machine: remove it on both and pair again." Any other `error` is a `welcome` that is not+ valid.+7. Checks the `id` in `welcome`: not this machine's own, and the entry's. On a failure it+ closes, sending nothing more, and says a different Beamer answered at that address. Otherwise+ it sets `linked`.+8. Sends its announcements.++The initiator sends `hello`, and its own id in it, before it has seen the responder's id. Both+are sealed under keys only a holder of the token can make, so only the paired machine, or one+that has its token, ever reads either id.++### The keys++```+shared = X25519(this side's ephemeral secret, the other side's ephemeral share)+key(direction) = HKDF-SHA-256(ikm = the token as saved, as text || shared,+ salt = b"beamer-link-v6",+ info = b"beamer-frames" || 0x06 || key_id || prefix_I || prefix_R+ || share_I || share_R || direction,+ length = 32)+direction = 0x01 for frames the initiator seals, 0x02 for frames the responder seals+```++- `prefix_I` and `share_I` are the initiator's, `prefix_R` and `share_R` the responder's: the+ order is fixed by role, not by who is computing. `info` is always 111 bytes: 13 of label, the+ version byte, 16 of key id, 8 and 8 of prefix, 32 and 32 of share, and the direction byte.+- `ikm` is 75 bytes for a token made by pairing: the token's 43 ASCII characters of `b64`, never+ the 32 bytes they spell, then the 32 bytes of `shared`.+- HKDF is RFC 5869, and X25519 RFC 7748 (the scalar clamped, bit 255 of the incoming share+ ignored). A `shared` of 32 zero bytes ends the handshake, and so does a platform's X25519+ that throws on a low-order share (CryptoKit, Node), exactly as PAIRING.md treats `K`. The+ check is on the output: every low-order share gives zeros, and nothing else does.+- What the keys bind: the token, the version, both prefixes and both shares in role order, and+ the direction. So a recorded link cannot be played into a new one (fresh prefixes and shares+ change the keys), frames cannot be reflected back at their sender (the direction byte), and a+ link cannot be moved to another pair (the key id and the token). The machine ids are not in+ the keys: `hello` and `welcome` carry them sealed, and a frame cannot be altered without its tag+ failing.+- **Forward secrecy.** The shared secret never leaves either side, and both ephemeral secrets are+ forgotten once the keys are made, so a token that leaks later does not open a recording of a+ link made before. It still lets its holder open new links as either machine, until the pair+ is removed.++### Frames++As version 5:++```+frame = length (4 bytes, big-endian) || counter (4 bytes, big-endian) || ciphertext || tag (16 bytes)+length = 4 + len(plaintext) + 16, at least 21 (the ciphertext is as long as the plaintext)+nonce = the sealing side's prefix (8 bytes) || counter (the frame's 4 counter bytes, big-endian, as sent)+AEAD = ChaCha20-Poly1305 (RFC 8439), no associated data+```++- Each side counts its own frames from 1. A receiver refuses any counter that is not one more+ than the last it accepted. The last frame a side may send carries 2^32 - 1; a sender that needs+ another closes the link and reconnects.+- The plaintext is one message. A frame may claim at most 16 MiB, except the first each way.+- **A frame begins** when its first length byte arrives, by a monotonic clock, and must arrive+ whole within **30 seconds** of that byte, whatever its size; one still arriving after that+ ends the link. Between its bytes the link's liveness still holds (section 3).+- Only a `clipboard` is ever larger than 64 KiB of plaintext, and a receiver parses such a frame+ only where it would take that clipboard: a responder from its owner, an initiator from a peer+ it let go of no more than 10 seconds before the frame began (section 5, the clipboard). Any+ other plaintext over 64 KiB is authenticated, so its counter is spent, and dropped unparsed;+ the link stays up.+- Anything that fails (the tag, the counter, a length out of range, a frame past its 30 seconds,+ a plaintext that is not a message: Encodings) ends the link.++### `hello` and `welcome`++`hello`, the initiator's first frame:++| Field | |+|---|---|+| `version` | the integer `6` |+| `id` | the initiator's machine id, `b64` |+| `name` | the initiator's name |+| `platform` | the initiator's platform |+| `app` | its app version, such as `"1.5.0"`: 1 to 32 printable ASCII characters (0x20 to 0x7E); shown, never compared |+| `caps` | capabilities, below: a list of at most 16 strings of 1 to 32 printable ASCII characters; one this machine does not know is ignored, and a repeat means the same as one |+| `port` | integer 0 to 65535: the port the initiator accepts links on, 0 when it accepts none |+| `hw` | optional: its hardware address on the interface this link leaves from, six two-digit lower-case hex groups joined by colons |++`welcome`, the responder's first frame, has `version`, `id` (the responder's machine id),+`name`, `platform`, `app`, `caps`, optionally `hw`, and:++| Field | |+|---|---|+| `accepts` | `true` when this initiator may drive the responder (`allow_drive`), else `false` |+| `error` | only in the `invalid_hello` and `wrong_id` answers, which have no other field but `version` |++Each end updates the peer entry from what the other sent: `name` and `platform` always, and `hw`+when it is present (an absent `hw` keeps the saved one). The responder also takes `port` from+`hello`, and `host` from the address the link came from when `port` is not 0 and that address+is neither loopback nor link-local. A change is saved.++Capabilities say what a machine does with a message it receives:++| Capability | Means |+|---|---|+| `clipboard` | it takes clipboard text |+| `clipboard_image` | it takes clipboard images |+| `gestures` | it acts on `gesture` |+| `media_keys` | it acts on the media key names (section 7) |+| `text` | it types `text` |+| `settings` | it receives Same on all machines (`settings`) |+| `design_sync` | with `settings`, it sends and receives direct Design states (`settings.data.design_sync`) and can be followed |++A sender does not send a message its peer's capabilities do not cover. A receiver that gets one+anyway drops it, and still acknowledges it when it carries a `seq`.++### What it does not do++- **The key id is in the clear.** It is the same on every link of one pair, so anyone on the+ path can recognise that pair's links on another network, and anyone who can reach a+ responder can learn whether a key id it has seen is one of its pairs, because it answers that+ key id and not others. Nothing in the clear links one machine's different pairings, and the+ machine ids are never in the clear. The key id is a test of its token for anyone who sees it,+ which is why only tokens made by pairing (256 random bits) are used.+- **Handshakes can be crowded out.** Anyone who can reach the port can keep the four slots+ busy, and one who has seen a pair's key id holds a slot for the whole 5 seconds and costs an+ X25519 each time. Replacing the oldest means a real peer's next try still gets in unless the+ flood comes from several addresses at once; something on the LAN that can do that can deny+ service in simpler ways. Two peers behind one address (a NAT) take turns, and the one+ replaced retries two seconds later.+- **A token holder is trusted.** Forward secrecy protects recordings from a token that leaks+ later; it does not stop the holder of a leaked token opening a new link as either machine, or+ sitting between the two on the path and reading what passes.+- **The address is not authenticated.** A peer's `host` comes from pairing, a beacon, a QR, or+ the source of an authenticated link. Something on the path can point a machine at the wrong+ address; it cannot read or forge a link, whose keys come from the token.++## 3. Messages++Initiator to responder:++| `type` | `data` | Carries `seq` |+|---|---|---|+| `hello` | section 2 | no |+| `ping` | `{}` | no |+| `focus` | section 5 | no |+| `keydown`, `keyup` | `key`, optional `us` (section 7) | yes |+| `mousemove` | `dx`, `dy` | yes |+| `mousedown`, `mouseup` | `button`: `left`, `right`, `middle`, `back` or `forward` | yes |+| `scroll` | `dy`, `dx`, `mode` | yes |+| `gesture` | `name`: `swipe_up`, `swipe_down`, `swipe_left`, `swipe_right`, `spread` or `pinch` | yes |+| `text` | `text` (section 10) | yes |++Responder to initiator:++| `type` | `data` |+|---|---|+| `welcome` | section 2 |+| `ack` | `seq`, `held_us`, optional `locked` (section 9) |+| `accept` | `route` (section 5) |+| `refuse` | `route`, `why` (section 5) |+| `accepts` | `accepts` (section 4) |+| `switch` | section 5 |++Either way:++| `type` | `data` |+|---|---|+| `clipboard` | optional `text`; optional `image` (standard base64 with padding, of a PNG) with `image_format: "png"` |+| `arrangement` | `edge`, `set_at`, `by` (section 8) |+| `settings` | section 10 |+| `paired` | `ids`: list of `b64`, at most 32 |++- **`seq`** is in `data`: an integer from 1 to 2^53 - 1 that each initiator counts from 1 on+ every new link (and from 1 again on a reconnect) and raises by one per input message. The responder acknowledges the+ highest `seq` it has dealt with, whether it injected the message, used it at an edge, or+ dropped it (section 4). No other message carries a `seq`.+- **`mousemove`**: `dx` and `dy` are integers from -65535 to 65535, relative motion in the+ sender's logical pixels (points on a Mac) after its own acceleration; positive `dy` is down.+ The sender keeps the fractions and sends whole pixels. A phone sends its own points after its+ acceleration curve.+- **`scroll`**: `dy` and `dx` are numbers from -65535 to 65535; `mode` is `"pixel"` for a+ trackpad's continuous delta in points, or `"line"` for whole wheel notches. Both are in the Mac's+ convention, as version 5 sends them: `dy` and `dx` are Core Graphics' scroll axes 1 and 2 as a+ Mac reports them, the user's scrolling direction already applied, and a Mac receiver posts them+ as they stand. A Windows receiver takes positive `dy` as its wheel's positive and positive `dx`+ as its horizontal wheel's positive; the `dx` mapping is still to be confirmed+ on hardware. Any other sender, a phone included, sends what a Mac would for the same+ movement. A sender always sends all three; a receiver takes a+ missing `dx` as 0 and a missing `mode` as `"line"`, as version 5 did.+- **Clipboard limits**: text at most 256 KiB as UTF-8. An image at most 8 MiB before base64,+ and a PNG a receiver can decode without the file deciding how much memory that takes, checked+ from its bytes before anything decodes it:+ - the PNG signature, then an `IHDR` chunk of 13 bytes, whose width and height are each 1 to+ 16384 and whose product is at most 2^25 (33,554,432 pixels: an 8K screen is 33,177,600);+ - every chunk (4-byte big-endian length, type, data, CRC) inside the file, up to `IEND`; bytes+ after `IEND` are ignored, and CRCs are not checked;+ - a still with one header: no second `IHDR`, and none of APNG's `acTL`, `fcTL` or `fdAT`;+ - what a decoder inflates besides the pixels, the zlib streams of `iCCP`, `zTXt` and an `iTXt`+ whose compression flag is 1, at most 4 MiB inflated in all. Each stream must be one whole+ zlib stream ending where its chunk ends: one that is not zlib, is cut short or has bytes after+ its end counts as over, and so does an `iTXt` whose compression flag is neither 0 nor 1, or+ any of the three without the null bytes that end its keyword (and, in `iTXt`, its language+ and translated keyword, when it is compressed).++ A few megabytes of PNG can otherwise claim gigabytes once decoded. A sender never sends an+ image outside these limits, and a receiver drops one, without decoding it. Over any limit,+ that part is dropped and the rest of the message stands.+- **Liveness.** An initiator sends `ping` when it has sent nothing for a second; a responder's+ `ack` heartbeat does the same the other way (section 9). A side that receives no byte at all for+ 2.5 seconds (a responder) or 2 seconds (an initiator) ends the link. Any byte counts, so a large+ clipboard frame arriving slowly keeps the link alive while it comes.+- **`paired`** lists the ids of every peer the sender has, less the receiver's. A machine sends+ it only to peers it may send input to (`send` true), since those are the ones whose Crossing+ page needs it: after the handshake and again whenever its list changes. The receiver stores it+ in `paired_with` (section 5, the Crossing page).+- **Announcements.** After the handshake each end sends `paired` when the rule above allows,+ `arrangement` when this pair has a side, and `settings` when the other's capabilities list+ `settings`, except for a zero-port phone: phones never take part in shared settings or Match design.+- **Which link.** Between two desktops with a link each way, `arrangement`, `settings` and+ `paired` go on the link this machine opened when it is up, else on the other. When neither+ machine may send to the other there is no link, and nothing passes until one exists.++## 4. Input ownership++A responder has one owner or none. Only the owner's input is injected.++**Taking input.** An initiator asks for input with a `focus` whose `target` is the+responder's own id. The responder decides under one lock, in this order:++1. The `route` is not higher than the last this link had accepted: ignored, no answer. The+ owner has already moved on.+2. Fields other than `route` and `target` malformed: `refuse {why: "malformed"}`.+3. `allow_drive` false for this initiator: `refuse {why: "not_allowed"}`.+4. This machine's own input is on another machine: `refuse {why: "busy"}`. A machine never+ drives and is driven at once.+5. This machine sent this initiator home, or ended its ownership by force, less than 5 seconds+ ago: `refuse {why: "sent_home"}`.+6. Another peer is the owner: `refuse {why: "owned"}`.+7. A `stay` from an initiator that is not the owner: `refuse {why: "malformed"}`.+8. Otherwise it accepts, and the initiator is the owner. When it already was, the `focus` moves+ the pointer or re-arms the zones in place.++The answer, `accept {route}` or `refuse {route, why}`, is sent the moment the decision is made,+before the pointer is placed, an arrival plays or a lock screen is dealt with. A `focus` naming+this machine whose `route` or `target` is itself malformed cannot be answered with its route and+is ignored; the owner's wait for an answer (section 5) covers it.++There is no taking over. A second machine waits until the owner lets go. This differs from+version 5, where any new link replaced the old one.++**What a non-owner's messages do:**++| Message | From the owner | From anyone else |+|---|---|---|+| input (`seq` messages) | injected | dropped, acknowledged |+| `clipboard` | set on this machine | dropped |+| `focus` naming this machine | as above | as above |+| `focus` naming another machine | the owner lets go | ignored |+| `ping`, `arrangement`, `paired` | handled | handled |+| `settings` | handled if its caps list `settings` | the same |++**Ownership ends** when the owner sends a `focus` naming another target; when its link ends for+any reason or is replaced by another from the same peer; when the user removes the peer or turns+its `allow_drive` off; and by force, when this machine sent the owner home and it has not let go+within 1 second. Every time it ends, the responder:++1. releases every key and button it injected for that owner, before injecting anything else;+2. drops its armed zones;+3. on a let-go `focus` only, sends the owner its own clipboard when something other than a+ `clipboard` message changed it while that owner drove (section 5, the clipboard);+4. when it ended in any way but a let-go `focus` and the link is still up, sends+ `refuse {route, why}` on it (`not_allowed` when `allow_drive` was turned off, `sent_home` when+ it was ended by force), and from then on drops that link's input, still acknowledging it,+ until a `focus` of its is accepted again.++The owner, for its part, sends `keyup` and `mouseup` for everything it pressed and has not+released on that link before the `focus` that lets go, and swallows the physical releases that+follow. The other way round, a key or button pressed on the owner while its input was at home is+released at home: its release, and nothing else of it, stays there when it comes after the input+has left. The responder's release is the backstop for a link that dies or an owner that misbehaves.++**Per link.** Each responder link keeps its own `seq` count, its own ACK timer, its own last+accepted `route`, and its own record of keys and buttons held. Each initiator link keeps its own+`seq` count, its own unacknowledged sends and round-trip samples, and its own record of keys held+down on that peer. A machine's route counter is one.++**`accepts`**, responder to initiator, `{accepts: bool}`: sent whenever `allow_drive` for that+initiator changes, so an owner or a phone knows at once rather than at its next link.++**A machine that is driven does not drive.** When a desktop that is owned is asked to send its+own input elsewhere (its shortcut, its edge, a menu), it sends its owner home (section 5) and+waits up to 1 second for the owner to let go, ending the ownership by force if it does not; then+the move it was asked for goes ahead. A desktop whose own input is on another machine refuses to+be taken (`busy`), counting from the moment it sends a taking `focus` until that take is refused,+times out or is let go. Two desktops that try to take each other at the same moment are both refused+and both stay at home, and the next try works.++## 5. Routing++### `focus`, `accept`, `refuse` and `switch`++`focus`, owner to responder:++| Field | |+|---|---|+| `route` | integer, 1 to 2^53 - 1 |+| `target` | `b64`: where input is going. The responder's own id means here; any other id means the responder is being let go |+| `edge`, `offset` | where to land the pointer: `left`, `right`, `top` or `bottom`, and how far along that edge of the responder, any number, which the receiver clamps to 0.0 to 1.0 (never malformed for its range) |+| `resistance_px` | integer 0 to 1000: how far the owner's hand must push through a zone on the responder |+| `reach` | list of `b64`, at most 32, no repeats: the peers the owner can send input to now, less the owner and the responder |+| `stay` | `true`: re-arm in place; land nothing, play nothing |++Which fields each kind of `focus` has:++| Kind | `edge`, `offset` | `resistance_px` | `reach` | `stay` |+|---|---|---|---|---|+| take, by a zone | both | yes | yes | absent |+| take, by the shortcut or a menu | neither | yes | yes | absent |+| re-arm in place | neither | yes | yes | `true` |+| let go (`target` another machine) | neither | absent | absent | absent |++A take without `resistance_px` uses 120, and a phone, which has no hand at an edge, may leave it+out. A take or re-arm without `reach` has an empty one. A `reach` that names the owner or the+responder has those ignored. `edge` without `offset`, `offset` without `edge`, or `stay` with+anything but `true`, is malformed; on a re-arm `edge` and `offset` do not belong and are ignored.++`accept`, responder to the initiator whose taking `focus` it accepted: `route`.++`refuse`, responder to an initiator whose taking `focus` it did not accept: `route`, and `why`,+one of `"owned"`, `"not_allowed"`, `"busy"`, `"sent_home"` and `"malformed"`. A valid `route` is+all a `refuse` needs: one whose `why` is missing, not a string, or another string is not+malformed, and the initiator acts on it at once as a refusal it cannot name.++A `refuse` may also carry **`other`**, a machine id: with `owned`, the owner that holds the+responder; with `busy`, the machine the responder's own input is on. The responder includes it+whenever it knows that machine's id, and never with any other `why`. It is there so the initiator+can say which machine is in the way ("Can't cross to Bee: it is being driven from Sea"); the+initiator names it by its own peer entry for that id, and as another machine when it has none, or+when `other` is not a valid id or is the initiator's own, in which case it is ignored and the+refusal still stands. A version 6 machine from before 1.5.0-beta.5 ignores it, as it ignores any+unknown key (Encodings).++`switch`, responder to its owner only:++| Field | |+|---|---|+| `route` | the last `route` the responder accepted from this owner |+| `next` | `b64`: where input should go. The owner's own id means home |+| `edge`, `offset` | where to arrive on `next`, both or neither, as in `focus` (`offset` clamped, never malformed for its range) |++### The route++The owner keeps one route number for all its links, 0 when it starts. It raises it by one every+time it moves its input or re-arms in place, and every `focus` of that move carries the new+number: the `focus` letting go of the machine it leaves and the `focus` taking the machine it+goes to carry the same route. The owner remembers which machine its input is on (none, when at+home), the current route, and the `reach` it last sent there.++The owner acts on a `switch` only when it comes from the machine its input is on and carries the+current route. Anything else is ignored: it was sent before a move that has already happened, so+acting on it would move input a second time. One exception: a `switch` whose `next` is the owner,+from the machine its input is on, is honoured when its route is at least that of the take that+began the current visit, so a machine that sends its owner home while a re-arm is crossing it is+not left holding the input, and a send-home left over from an earlier visit still is not obeyed.+What the owner does with a `next` it cannot follow is below.++The responder ignores a `focus` whose `route` is not higher than the last it accepted on that+link (section 4). Routes on different links are not compared.++### Input comes home++One procedure, used everywhere below: the owner raises the route, sends the machine its input+was on `focus {route, target: owner}` if that link is still up, leaves its own pointer where it+was captured unless an `edge` and `offset` say where to land it, and swallows the releases of+keys it had sent there. A phone simply stops driving. It is used when:++- a `switch` names the owner;+- the owner's own shortcut, menu or edge brings it home;+- a `refuse` arrives for the current route from the machine its input is on, or a take from home+ has had no answer for 1 second;+- the link to that machine ends for any reason, a send that fails included, or its watchdog+ fires (no byte for 2 seconds).++Each says why, naming the machine: "*name* is being driven from another machine", "*name* does+not accept input from this one", "*name* is driving another machine", "*name* sent the input+back", "Lost the link to *name*".++### Moving input++**From the owner's own screen, from home, or by its own shortcut or menu.** A desktop's pointer+pushes through one of its zones (section 8) to peer P, or the shortcut or a menu picks P, whether+the input is at home or on another machine B. The owner raises the route. When the input is on+B, it first lets go of B: B's releases, then `focus {route, target: P}` to B. Then it sends P the+taking `focus`, then its clipboard, then input, without waiting: a refusal sends the input home,+not back to B, and whatever reached P in the meantime was dropped there. No answer within 1+second also sends it home. A phone picking a machine does the same.++**Onward from the machine being driven.** While owned, a responder watches its own pointer, as+version 5's return edge did. It arms each of its own zones whose peer is the owner or is in the+owner's latest `reach`, at the owner's `resistance_px`, and nothing else. When the pointer pushes+through a zone to peer N, it sends the owner `switch {route, next: N, edge, offset}`, with `edge`+and `offset` where that zone lands the pointer on N. It then disarms its zones and waits; input+that arrives in the meantime is injected. The zones cannot tell the owner's motion from the+machine's own mouse, so a local push through a zone sends the owner onward too, as in version 5.++**What the owner does with that `switch`**, input being on B:++- `next` is the owner: input comes home, landing at `edge` and `offset`.+- `next` is a peer N that was in the `reach` last sent to B, and the owner still has a live link+ to N and may send to it: the owner raises the route and sends N the taking `focus`. It holds+ its input, sending it nowhere, until N answers. B is not let go yet, so it keeps the input if+ N does not take it.+ - On `accept`, it sends B `focus {route, target: N}`, then N its clipboard and the held input.+ - On `refuse`, or no answer within 1 second, it raises the route again, sends B+ `focus {route, target: B, stay: true, resistance_px, reach}` with a fresh `reach` that leaves+ N out for the next 3 seconds, sends B the held input, and says N could not be reached.+ - Anything else that moves the input while it waits (a send-home from B, a lost link to B, the+ owner's own shortcut or menu) ends the wait and cancels its timer.+ - **A take given up closes N's link.** When the wait ends with no answer from N, by its 1+ second or by anything above, the owner closes the link it opened to N before it sends+ anything else, then goes on as that event says. N may have accepted already with its+ `accept` held up on the path; the close ends that ownership (section 4), so N is never left+ owned by an owner that drives elsewhere. N is out of `reach` until its link is up again, and+ the owner acts on nothing more that arrives on the closed link, an `accept` it had already+ read included. The one exception is the owner's own shortcut or menu picking N itself: that+ take follows the first on the same link, and its answer is the one awaited.+ - It ignores an `accept` whose route is not that of a take it sent. An `accept` for a take+ from home or by the shortcut that comes after its wait ended is answered with a let-go+ `focus` carrying the owner's current route and naming wherever its input is now (its own id+ when home); that take's own let-go has gone on the same link already, so this one changes+ nothing.+- `next` is anything else (outside that `reach`, or a link that has dropped since): the same as a+ refusal from N, without asking N.++**Keeping `reach` true.** When the set of peers the owner can send to changes while its input is+on a machine (a link comes up or drops, an `accepts` arrives, or a peer left out after a hand-over+that failed has had its 3 seconds), it raises the route and sends that machine a `stay` with the+new `reach`. While it waits on a hand-over it sends none; the `stay` or the take that ends the+wait carries the reach as it is then, and one more `stay` follows an `accept` if the reach for+the new machine changed during the wait.++**Sent home from the driven machine.** A responder's own user can always send the owner home:+its shortcut, a menu, a direction switch turned off, or Windows locking (as version 5). It+disarms its zones and sends `switch {route, next: the owner}` without `edge` or `offset`, and the+owner's input comes home. If the owner has not let go within 1 second, the ownership ends by+force (section 4).++### Chains need a direct link from the input to every machine++A to B to C works like this, with the keyboard on A: A drives B; B's pointer reaches B's zone for+C; B sends `switch {next: C}` to A; A takes C and lets go of B. A needs its own link to C. B never+relays A's input: it would sit in the path of every keystroke meant for C and would need a second+layer of encryption. So a chain is a full mesh of pairings from wherever the input is: three+desktops take three pairings, and a phone that drives all three takes three more.++Because each machine configures only its own zones, and each zone names only the peer beyond it,+no machine needs the whole layout. The owner follows `switch` and needs no model of the screens,+which is what lets a phone drive a chain.++### What the Crossing page may offer++A machine M can offer a zone to peer P when M is paired with P. It can check the rest from the+`paired` lists it holds: for each machine that may hold input while M is driven (M itself, and+every peer with `allow_drive` true), whether it is paired with P. The first design let M offer+a zone only when every one of them is. That is open question 3, built as its recommendation in+1.5.0: `reach` already stops a zone firing for an owner that could not follow it, so the zone is+offered, and the page names each machine that may drive M, has linked, and is not paired with P.+A zone never leads to a phone.++### Which machine the shortcut picks++The shortcut, a Send button and a menu's own item with no machine named send input to the machine+it was last on, while that one can take it (its link is up and it accepts input); else to the+first in the list of peers that can; else to the first this machine sends to at all, so the+refusal or the wake names it. Never to a phone, or to an entry with no id yet. A menu item that+names a machine sends input there, from home or straight from the machine it is on.++### The clipboard follows the input++- When an owner takes a machine, it sends its own clipboard after the taking `focus` (in a+ chain, after the `accept`) and before any input, unless that machine is known to hold it+ already: the clipboard went there or came from there, and has not changed here or come from+ another peer since. So something copied on B and brought home reaches C when C is taken next,+ and is never sent back to B.+- When a machine is let go by a `focus`, it sends its clipboard to the owner only when something+ other than a `clipboard` message changed it while that owner drove, so what the owner brought+ is never echoed back. It never sends one otherwise, so a paired device cannot+ collect a clipboard by taking and letting go of an idle machine.+- An initiator takes a clipboard only from a machine it has let go of, once per let-go, when its+ frame begins (its first length byte arrives, section 2) within 10 seconds of that let-go; any+ other is dropped. Like any frame it then has 30 seconds to arrive whole. A later move (a refusal+ from the next machine, say) does not cost the machine let go its one clipboard. It sets it on+ itself (a desktop) or keeps it (a phone), and sends it on to the machine its input is on now, if+ any. That is how something copied on B reaches C in a chain, through A, and it leaves it on A's+ clipboard, as it would if the input had come home.+- In a chain, B's clipboard reaches C a round trip after C was taken, so a paste in that moment+ gets C's older clipboard. Holding the input for it would add that round trip to every crossing+ in a chain; version 6 does not.+- Version 5 sent the clipboard before `focus`. Version 6 sends it after, because a responder takes+ a clipboard only from its owner; the input that follows it on the same link is still behind it.++### A phone++- A phone is an initiator only. A desktop's entry for a phone has `port` 0, `host` `""` and+ `send` false, and is never dialled; its `allow_drive` is the switch that lets the phone drive.+- A phone has no side, zones, jump key or wake-on-LAN address. Desktops ignore its `arrangement`+ and `settings` messages, even if it advertises `settings` or `design_sync`.+- A phone's entries for desktops have `send` true and `allow_drive` false. It learns from each+ `welcome`'s `accepts` which desktops it may drive, and leaves the others out of `reach`.+- A `switch` whose `next` is the phone means stop: the phone lets go with+ `focus {target: phone}` and drives nothing until the user picks a machine. `edge` is ignored.+- A phone may leave `resistance_px` out; the desktop's zones then push at 120.+- A phone that cannot hear beacons finds a desktop whose address changed by scanning its QR+ again (section 6).++## 6. Pairing in 1.5.0 (pairing version 3)++The exchange is PAIRING.md's, CPace with the code as the password, with these changes:++1. **Version and labels.** Beacons say `pairing: 3`, `pair_start` says `v: 3`, CI is+ `b"beamer-pair-v3"`, and the token's HKDF info is `b"beamer-pair-token-v3"`. The rest of the+ computation, the four messages, rules 1 to 10 and the encodings are PAIRING.md's.+2. **Identities.** Each side's identity is its 16-byte machine id: `requester_id` in ADa and+ `host_id` in ADb. A `pair_start` or `pair_answer` whose `id` is not exactly 16 bytes, or is+ all zero, is refused.+3. **What the exchange proves.** `pair_start` and `pair_answer` each gain `platform` and `port`+ (the sender's link port, 0 for a phone), and both go into the associated data:++ ```+ ADa = lv_cat(b"requester", requester_id, requester_name as UTF-8, requester_platform as ASCII, requester_port as 2 bytes big-endian)+ ADb = lv_cat(b"host", host_id, host_name as UTF-8, host_platform as ASCII, host_port as 2 bytes big-endian)+ ```++ So everything pairing saves about the other machine is proved, except its address.+4. **Checking the identity received**, as the CPace draft's section 10.1.1 requires:+ - The requester, once `Tb` checks out, refuses when the host's id is its own or belongs to any+ of its peers, except as the replacement below allows. It sends `pair_confirm` with `tag: ""` and `error: "known"`,+ once, stores nothing, and says the machine is already paired, naming the entry and when it+ was paired.+ - The host, once `Ta` checks out, refuses the same way: `pair_done` with `ok: false` and+ `error: "known"`, and the code is dropped. A `pair_confirm` carrying `error: "known"` is+ unauthenticated, so it cannot be told from a wrong code ended the same way; the host's window+ says "That machine may already be paired here, or the code was wrong."+ - An entry that has never linked (`linked` false), was made by pairing less than 10 minutes+ before, and has the same name and platform as the new pairing proves, is replaced by it+ rather than refused, so a pairing whose `pair_done` was lost can be done again at once.+ Any other match is `known`.+ - The entry migrated from 1.4.x (`from_1_4` true), which never links (section 1), is replaced+ by a pairing that proves its id, when an earlier beta linked it and so learnt one; and, when+ it has `id: ""`, by a pairing that completes with the machine at its saved `host` (the+ address `pair_start` came from, for the host; the address it reached, for the requester),+ or that proves its `name` and `platform`. It is replaced, never counted, under the rule in+ item 5. A pairing with the machine at its saved `host` that proves the entry's `platform`+ takes over its `side`, `side_set_at`, `side_by` and zones: every 1.4.x upgrader pairs again,+ since no 1.4.x token migrates, and is at the screen pairing that machine on purpose, so the+ arrangement should not have to be set twice. A match by name alone takes nothing, and the+ entry's zones go with it: pairing proves the code, not which machine that entry was, and+ anyone who saw the code can claim a name, which is safe only because the entry never links+ and nothing of it carries over.+ - To pair two linked machines afresh, the user removes each from the other's list first.+ Re-pairing never replaces a linked peer's token.+ - An id proves only that it arrived unaltered, not that the machine sending it owns it.+ Someone who sees a code can pair under another machine's id and name, which that machine's+ own pairing will then find `known`. The window naming the entry and its date is how the user+ tells.+5. **Storing.** The host writes the new peer entry before it sends `pair_done`, and sends+ `ok: false` with `error: "refused"` if the write fails, so `Td` now proves the host saved the+ token. The requester writes its entry after `Td` checks out. Each side first computes the new+ token's key id (section 2): when it is already one of its entries' key ids, the host sends+ `ok: false` with `error: "refused"` and the requester stores nothing and says pairing failed.+ With a fresh 256-bit token that never happens; the check keeps key ids unique whatever the+ entries hold. A clash the requester finds after `Td` leaves the host holding an entry that+ never links, which is the lost-`pair_done` case above: pairing again within 10 minutes+ replaces it.+6. **Beacons.** A beacon carries `platform`, and carries `id` (`b64`) only while a code is up, so+ a machine does not broadcast a stable id on every network it joins.+7. **The QR's secret.** With every code it shows, the host draws 16 random bytes, the code's+ **QR secret**, shown only inside the QR (below) and dropped with the code. A requester that+ read the code from a QR sends `qr: 1` in `pair_start`, and a requester that was typed the code+ sends no `qr`. The host takes the password from `pair_start` alone:++ | `pair_start` | PRS |+ |---|---|+ | no `qr` | the code, six ASCII digits (6 bytes, as PAIRING.md) |+ | `qr: 1` | the code's six ASCII digits followed by the QR secret's 16 raw bytes (22 bytes) |++ `qr` with any value but the integer `1` makes `pair_start` malformed. Nothing else changes: the+ generator's zero padding follows PRS's length by PAIRING.md's formula (`z` is 95 for the+ 22-byte form), and `qr` is not in ADa, since a `qr` stripped or added on the path makes the+ two passwords differ and the exchange fail at `Ta` or `Tb`, which costs the code (rule 1) and+ nothing else.++ What it buys: an exchange that uses the QR secret gives someone on the path no useful guess,+ where the code alone gives one in a million a side. It does not close the typed path: while+ a code is up, anyone who guesses it may still try one `pair_start` without `qr`, with the same+ one in a million as before, and rule 1 then drops the code.++New errors:++| `error` | In | When |+|---|---|---|+| `known` | `pair_done`, `pair_confirm` | the other side's id is already one of this machine's peers' (bar the replacement in item 4), or this machine's own |+| `full` | `pair_answer` | the host reached 32 peers while this code was up; the code is dropped |++A host with 32 peers shows no code, and a requester with 32 does not start. That holds when one+of the 32 is an entry a new pairing would replace (a lost `pair_done`, or the one migrated from+1.4.x): the user removes a peer first. A known limit, left as it is. Pairing versions 2+and 3 never pair: a 1.5.0 requester shown a `pairing: 2` beacon says the other machine runs an+older Beamer before sending anything; a 1.5.0 host answers a `v: 2` `pair_start` with `version`+and drops its code; a 1.4.3 requester shown a `pairing: 3` beacon says the versions differ. This+protects a 1.4.3 machine from having its one pairing overwritten by a 1.5.0 requester that could+not then use it.++After pairing, each side's peer entry holds the other's `id`, `name`, `platform` and `port` as+the exchange proved them, the token, `paired_at`, `linked` false, `send` and `allow_drive` true+(for a phone, as section 5 says), `side` empty, and `host`: the requester saves the address it+reached the host at, and the host the address `pair_start` came from, unless the requester's+`port` is 0.++### Either end++Every desktop both announces and discovers. Each sends a beacon every 2 seconds to UDP 24821+while it runs, with `pair` and `id` only while a code is up, and each keeps the list of machines+it hears. Any desktop can show a code (and be the host) or enter one (and be the requester).++**Finding a peer whose address changed.** When the link to a peer with `send` true has been down+for 10 seconds, a desktop tries a link at the source address of a beacon carrying that peer's+exact name, at the peer's saved `port`, and saves the address only once that link authenticates.+It never tries a beacon with another name, nor one whose `id` is not the peer's; one at another+paired machine's saved address it tries after the rest, since two machines may have swapped+addresses. With several such beacons it tries them in turn. It tries at most one address per peer every 30 seconds,+and shows nothing when a try fails. A forged beacon can therefore cost one failed connection attempt every 30 seconds, never+a saved address and never a message that prompts the user to pair again.++### Pairing over TCP, from a code++Broadcast does not cross subnets or VPNs, and an iPhone needs an entitlement Apple grants on+application to send or receive it. So a host also accepts the exchange over TCP, on port 24821,+while a code is up and only then.++- **Framing.** Each message is a 4-byte big-endian length, 1 to 1024, then the same JSON object a+ datagram would carry, `beamy: 1` included. The desktops write it compact, with every character+ outside ASCII escaped as `\uXXXX`; a receiver accepts any spelling of the same JSON, since the+ exchange binds the decoded name and id, never these bytes.+- **Order.** The requester connects. The host sends its `beacon` at once (with `pair` and `id`);+ the requester checks it says `pairing: 3` and sends `pair_start` with that `pair`; the host+ answers `pair_answer`; the requester sends `pair_confirm`; the host sends `pair_done` and+ closes. A side that refuses sends its refusal first (`pair_answer` or `pair_done` with+ `ok: false`, or `pair_confirm` with `tag: ""`), then closes. Anything out of order, or a second+ `pair_start`, closes the connection with nothing sent.+- **Limits.** A connection has 10 seconds from being accepted to finish. The host holds at most+ four such connections at once and one per address, on the same terms as the link's handshakes.+ The requester's connect times out after 3 seconds.+- **One exchange per code, across both transports.** The UDP and TCP paths share the one pairing+ host, so rule 1 holds whichever way the first `pair_start` came. Rules 2 to 10 hold unchanged;+ the requester's memory of failed codes (rule 3) covers codes it sent either way.+- **The exchange under way is left alone.** Once a `pair_start` has bound the code, the host+ takes `pair_confirm` only from the address that `pair_start` came from (over TCP, only on its+ connection), and ignores any other without an answer; and the connection that bound the code+ is never the one a new connection replaces.+- **Checking and storing are one step.** A machine may host one pairing and request another at+ once. Each side makes its `known`, key id and 32-peer checks and writes its entry under one+ lock shared by both roles, so two pairings finishing together cannot pass 32 peers or leave two+ entries with one id. The host answers a count reached since `pair_start` with `pair_done`,+ `ok: false`, `refused`.+- **The fixed answer time** of 50 milliseconds applies as it does over UDP.++**The code on the screen.** While a code is up, each desktop's pairing sheet shows it as six+digits with this machine's address, and as a QR code of this text:++```+beamer://pair?host=<address>&port=<port>&code=<code>&k=<secret>+```++- `host` is a dotted IPv4 address, since the link is IPv4 only: the machine's address in a private+ range (10/8, 172.16/12, 192.168/16) when it has one, preferring the interface of its default+ route, and otherwise the default route's.+- `port` is 24821 in decimal. It is carried so a later version can move it. A number has one+ spelling, decimal digits with no sign and no leading zero, and so has each octet of `host`.+- `code` is the six digits.+- `k` is the code's QR secret as `b64`: exactly 22 characters, one spelling (Encodings).+- The four keys come in that order, lower case, each once, with nothing else. A reader refuses+ any other text, a QR without `k` included. The text is read as it is, with no percent-decoding.+ The pairing sheet never shows `k` as text.++A desktop can pair the same way by typing an address and a code: "Pair by address". That path+has no QR secret and sends no `qr`.++A phone that scans the QR of a desktop it is already paired with (the `id` in the host's TCP+beacon is a peer's) does not pair: it closes the pairing connection, tries its link at that+address, and saves the address once the link authenticates. That needs someone at the desktop to+show a code; finding a moved desktop without that (Bonjour, say) is left to the phone apps.++## 7. Keys++### Names++A key travels as `key`, a name, in `keydown` and `keyup`:++- **A character key** sends the character its layout types, as a string of exactly one code+ point, with Shift applied: `"A"` with Shift down, `"a"` without. While Command, Control or Alt+ (not Shift) is held, it sends the key's own unshifted character from its layout instead, so+ Option-V on a Mac is `"v"` and not `"√"`, and a German keyboard's Command-Z is `"z"`. Numpad+ keys send their character (`"1"`, `"+"`). When Windows cannot compose a dead key and the next+ character into one code point, it sends the visible sequence through `text` instead; a held base+ key repeats its character as `text` and its physical key-up remains swallowed.+- **`us`** is sent beside a character: the unshifted, lower-case character the same key position+ types on a US layout, for a receiver whose layout cannot type `key`. A key with no US+ character (on a JIS keyboard, say) sends none.+- **Any other key** sends one of these names:++ | Group | Names |+ |---|---|+ | Modifiers | `shift`, `shift_r`, `ctrl`, `ctrl_r`, `alt`, `alt_r`, `cmd`, `cmd_r`, `caps_lock` |+ | Editing and movement | `backspace`, `tab`, `enter`, `esc`, `space`, `delete`, `insert`, `home`, `end`, `page_up`, `page_down`, `left`, `right`, `up`, `down` |+ | Function | `f1` to `f24` |+ | Windows keys | `menu`, `print_screen`, `pause`, `num_lock`, `scroll_lock`, `browser_back`, `browser_forward` |+ | Media (`media_keys`) | `volume_mute`, `volume_down`, `volume_up`, `media_next`, `media_prev`, `media_stop`, `media_play_pause` |++ The numpad's Enter is `enter`.+- **`keyup`** carries the same `key` and `us` as the `keydown` it releases, even if Shift changed+ in between. Auto-repeat is more `keydown`s with no `keyup` between them. `caps_lock` is sent as a+ `keydown` and a `keyup` together on each press.+- **On the receiver**, `ctrl` is Control, `alt` is Option or Alt, and `cmd` is Command on a Mac,+ the Windows key on Windows and Super on Linux. It types a character as given, pressing or+ releasing Shift around it as its own layout needs, and falls back to `us` when its layout has no+ key for the character. A name it cannot press is dropped.+- **A phone** has no physical keys to map. It shows a modifier row named for the platform it is+ driving and sends names directly: Command-C to a Mac is `keydown cmd`, `keydown "c"` with `us`+ `"c"`, `keyup "c"`, `keyup cmd`.++### Which physical key sends which name++The machines fall in two families: the Mac (`macos`, `ios`), and the PC (`windows`, `linux`,+`android`, and any unknown platform). Between two machines of the same family every key goes out+as itself. Between the two families, the sender applies its user's saved style:++| Physical key on the sender | Same family | Across, Semantic (the default) | Across, Positional | Across, Mac keyboard layout (PC sender only) |+|---|---|---|---|---|---|+| Mac Control | `ctrl` | `cmd` | `ctrl` | — |+| Mac right Control | `ctrl_r` | `cmd` | `ctrl` | — |+| Mac Command | `cmd` | `ctrl` | `cmd` | — |+| Mac right Command | `cmd_r` | `ctrl` | `cmd` | — |+| Mac Option | `alt` | `alt` | `alt` | — |+| Mac right Option | `alt_r` | `alt` | `alt` | — |+| PC Control | `ctrl` | `cmd` | `ctrl` | `ctrl` |+| PC right Control | `ctrl_r` | `cmd_r` | `ctrl_r` | `ctrl_r` |+| PC Windows or Super | `cmd` | `ctrl` | `cmd` | `alt` |+| PC right Windows or Super | `cmd_r` | `ctrl_r` | `cmd_r` | `alt_r` |+| PC Alt | `alt` | `alt` | `alt` | `cmd` |+| PC right Alt or AltGr | `alt_r` | `alt_r` | `alt_r` | `cmd_r` |++- Semantic makes the everyday shortcuts line up: Command-C on a Mac arrives as Control-C on a PC,+ and Control-C on a PC as Command-C on a Mac. Positional keeps each key in its place. Mac keyboard+ layout maps a PC keyboard's modifiers to the corresponding Mac keys by their positions.+- The Mac's rows across families are 1.4.x's `DEFAULT_KEY_MAP` and `LEGACY_POSITIONAL_KEY_MAP`+ as they stand, sides folded. The PC's are Windows' capture names and 1.4.x's `POSITIONAL_SWAP`.+ Same family is new: the Mac as itself with its sides kept (the first design named the folded+ positional map), and Windows' capture swapped back, since the Windows receiver presses the Windows key for+ `cmd`.+- The saved style is the Mac's `key_map` (a style name, or a map a user wrote by hand, which+ applies across families only) and Windows' `modifier_style`. Both survive the migration. A+ Linux app keeps `modifier_style` as Windows does.+- The PC keeps `modifier_style` locally; it is not sent to peers or shared by Same on all machines.+ Key messages contain only the resulting key names, which older peers already understand. A+ settings file without this field defaults to Semantic.+- A Linux sender reads keys by evdev code: `KEY_LEFTCTRL` and `KEY_RIGHTCTRL` are PC Control,+ `KEY_LEFTMETA` and `KEY_RIGHTMETA` Windows or Super, `KEY_LEFTALT` Alt and `KEY_RIGHTALT` right+ Alt or AltGr. A Linux receiver presses the same codes for the same names.++## 8. Zones++A zone is part of this machine's screen that leads to one peer:++```json+{"peer": "<b64>", "kind": "edge"}+{"peer": "<b64>", "kind": "part", "parts": ["start", "middle"]}+{"peer": "<b64>", "kind": "corner", "corner": "top_right", "edge": "right"}+{"peer": "<b64>", "kind": "notch"}+```++Any zone may also carry `"off": true`, which keeps it in the list and out of use. `peer` is `""`+only for the entry migrated from 1.4.x, which never links. A zone never names a phone.++- **Which edge a zone crosses.** An `edge` zone is the whole of its peer's `side`, and a `part`+ zone is some of its thirds (`start`, `middle` and `end`, top to bottom or left to right), so+ changing the side moves them. A `corner` zone names its corner and the edge it counts as+ crossing, one of the two that corner touches. A `notch` zone is the Mac's notch and crosses the+ top edge. These are 1.4.x's rules: its corner and notch could lead to the PC through an edge+ other than the one facing it, and a zone keeps that. The migration never changes where a+ pointer lands, so it writes what 1.4.x did: a Mac's corner zone crosses by the corner's own+ left or right edge whatever the side (the way home, which is not a zone, uses the side), and a+ PC's corner zone crosses the side (1.4.x built its corner push with the return edge), or the+ corner's own left or right edge while no side is set. An app with no control for a corner's+ edge writes the same again on every save.+- **Where the pointer lands.** At the peer's edge opposite the one crossed, at the fraction along+ it where the pointer left. A `corner` zone lands at the end of that edge nearest the corner: 0.0+ for a top or left end, 1.0 for a bottom or right one.+- **What they measure.** The thirds and corners are measured as 1.4.x measures them+ (`return_edge.py`): a third against the display the pointer is on, a corner in an 8-pixel box+ that wins over the edge it sits in.+- **Order and overlap.** Corners are checked first, then edges, then parts, then the notch, and the+ first that holds the pointer wins. Apart from a corner inside an edge, two zones in use never+ cover the same stretch: the settings refuse a list where they would, and an `arrangement` that+ would make two overlap is applied and turns the clashing zones for the sender `off`, with a- notice naming both machines. A zone's stretch is its peer's `side` for an `edge` zone, the++ notice naming both machines. The exception is a machine with no link up at that moment, in++ either direction: its clashing zones are set aside instead (`off` and `"aside": true`), with a++ notice saying it is not connected, and the same holds when the user gives a machine a side or a++ way on the Crossing page, which then offers no thirds of a side held only by such a machine. A++ machine that is only asleep must not lose its layout: when it links, a zone set aside is put back++ in use, unless another zone in use covers that stretch, when it stays `off` like any other clash.++ Only a machine whose link reports that it no longer has this pairing (section 2, initiator step++ 3) keeps its zones `off` for good, and the app says so in its window, not only in its log. Any++ edit of the zone by the user clears `aside`. A zone's stretch is its peer's `side` for an `edge` zone, the+ chosen thirds of it for a `part` zone, and the corner for a `corner` zone; the `notch` is a+ stretch of its own, which only another `notch` zone covers: it fires on a dwell and 1.4.x let+ it stand beside the edge, but a Mac has one notch, so it leads to one machine. 1.4.x let the+ edge and the thirds both be on, where the edge covered the thirds, so the migration and a+ save of those methods write the thirds `off`. Two machines may share one side by thirds.+- **Every machine starts with its whole edge.** Pairing gives the new machine an `edge` zone,+ and so does an `arrangement` for a machine that has no zone yet, and so does reading a+ settings file in which a paired desktop has none (pairing made no zones before 1.5.0-beta.5).+ On a Mac with one desktop machine paired and no side for it, Beamer holds `right` unstamped and+ with no author, as the Crossing page shows, so the edge crosses from pairing and a side either+ machine chooses wins over it.+ An `edge` zone whose side another zone in use already covers is written `off`, so the file+ stays one the settings accept. A machine with a side and no way in, because another machine+ holds that side, is named on the Crossing page with the machine that holds it.+- **A peer with no zones** can still be reached by the shortcut and the menus.+- **The same list, both ways.** A machine's zones are where its own pointer crosses when its own+ hardware drives, and where a driven pointer is sent onward or home (section 5).+- **Never shared.** Zones and the direction switches belong to the machine that has them, and no+ message carries them. Only a pair's `side` is kept in step between the two, by `arrangement`.++**`arrangement`** says which of the sender's edges faces the receiver: `{edge, set_at, by}`.+`edge` is `left`, `right`, `top` or `bottom`; `set_at` an integer of unix seconds; `by` the+machine that made the change. The receiver sets its own `side` for the sender to the opposite+edge, and stores `set_at` and `by` as `side_set_at` and `side_by`, when the message is newer+than what it holds: a higher `set_at`, or the same `set_at` and the larger `by` compared as+bytes. It ignores one whose `set_at` is more than a day ahead of its own clock, or above+2^53 - 2. A change made here is stamped with the current time, and never lower than the stamp+held plus one. A side is never cleared by message. A machine with three peers keeps three sides,+each settled with that one peer.++`arrangement` may also carry **`way_back`**, a boolean: whether the sender has a zone in use, and+able to fire (an `edge` or `part` zone of a side that is set, a `corner` or a `notch`), that leads+to the receiver. The sender includes it every time it sends an `arrangement`: when the link comes+up, when it changes that machine's side or zones, and, once it has applied an `arrangement` from+that machine, in answer, so the machine that set the side learns at once that it was taken but+leads nowhere. The receiver keeps the last one it was told as `way_back` on the sender's entry,+whether or not the side in the same message was newer, and its Crossing page names the sender as+having no way back while it is `false`. An answer is sent only after an `arrangement` that changed+something here, so two machines never answer each other in turn. A version 6 machine from before+1.5.0-beta.5 ignores it, as it ignores any unknown key (Encodings).++With `way_back` false, `arrangement` may also carry **`way_back_by`**, a machine id: the machine+whose zone in use already covers the sender's side for the receiver, which is why the sender's own+zone there was turned `off` (Every machine starts with its whole edge, and Order and overlap). The+sender includes it whenever one such machine holds that side, the first in its zone list when+several do, and never with `way_back` true or absent. The receiver keeps it as `way_back_by` on the+sender's entry beside `way_back`, and drops it whenever an `arrangement` from the sender carries+`way_back` without it; one that is not a valid id, or is the receiver's own, is ignored as if+absent. With it, the receiver's Crossing page says which machine is in the way ("Bee has Sea on its+left too"), naming it by its own entry for that id and as another machine when it has none. A+version 6 machine from before 1.5.0-beta.5 ignores it, as it ignores any unknown key (Encodings).++**From 1.4.x's settings.** The migration turns the one pair's ways across into zones for its one+peer, one of each kind, with `off` set for each method that was not on: an `edge` zone; a `part`+zone with the saved thirds, `off` as well when the edge is on; a `corner` zone with the saved+corner, crossing the edge the rule above gives; and, on the Mac, a `notch` zone.+`shortcut` in the methods sets the machine's `shortcut`. So the one-machine Crossing page turns a+way across on and off by `off`, and finds the thirds and corner it had.++## 9. The round trip++Every `ack` says how long the responder held it:++| Field | |+|---|---|+| `seq` | the highest `seq` dealt with on this link, 0 before any |+| `held_us` | integer microseconds from dealing with that `seq` to sending this `ack`, 0 to 2^31 - 1; the sender clamps to that range |+| `locked` | `true` while Windows clears its lock screen and drops input; absent otherwise |++- An initiator ends the link on an `ack` that is malformed, whose `seq` goes backwards, or whose+ `seq` is higher than any it sent: the stream cannot be trusted.+- An `ack` whose `seq` is higher than the last one gives one sample:+ `round trip = (now - when that seq was sent) - held_us`, and 0 if that is below 0. An `ack` that+ repeats a `seq` gives none, and carries `held_us: 0`. The owner measures every link that+ carries its input, a phone included.+- **When the responder acknowledges**, timed from the last `ack` it sent on that link: input dealt+ with 15 ms or more after it is acknowledged at once; input dealt with sooner is acknowledged 15+ ms after it, in one `ack` for everything up to then; and with no input, an `ack` goes 0.4+ seconds after the last, as a heartbeat. 1.4.x held every `ack` 15 ms, so its figure read up to+ 15 ms high; with `held_us` the figure is the network and the injection, whatever the timer.++**The jitter window's inputs.** Each initiator link keeps its samples, with the time each was+taken, for the last 30 seconds while it carries input. From them the app shows the median and+the spread and decides on the warning (Open questions, 4). It logs, every 60 seconds while input is+on that link, the count, the median, the 95th percentile, the largest and the mean `held_us`, so a+report can be read from the log.++## 10. Text and shared settings++**`text`** is a string the receiver types as it stands, for a phone's keyboard, where naming each+key would lose accents and emoji. The receiver advertises `text` only if it can type any Unicode+text.++- At most 4096 bytes as UTF-8. A longer one is dropped whole, and acknowledged.+- `\n` is typed as Return and `\t` as Tab. Every other character from U+0000 to U+001F, and U+007F+ to U+009F, is dropped.+- It is typed as characters, not keys, so the receiver's layout and any modifier the sender has+ down play no part. A sender does not send `text` while it holds a modifier on that link.+- It carries a `seq` and is acknowledged like any input.++**`settings`** is Same on all machines: 1.5.0's Same on both machines, extended from one peer to+every peer.++```json+{"type": "settings", "data": {+ "on": true, "set_at": 1790000000, "by": "<b64>",+ "crossing": {"resistance_px": 120, "block_while_dragging": true, "shortcut": true,+ "trigger_key": "alt_r", "trigger_style": "double_tap", "double_tap_ms": 300},+ "design": {"glow_style": "glow", "glow_colour": "colourful", "effect_length": "normal",+ "shortcut_arrival": true, "shortcut_arrival_style": "match"}}}+```++- `on` is a boolean, `set_at` an integer of unix seconds, `by` the `b64` id of the machine that+ made the change, or `""`. A sender always sends all three. A receiver reads a missing `by` as+ `""`, and also reads a `by` spelt in standard base64 with padding, as the desktops do; a+ message missing `on` or `set_at`, or with any of the three of the wrong type or not an id, is+ malformed and ignored whole. The receiver validates this envelope before reading `design_sync`,+ so a malformed outer field drops the optional Design state with the rest of the message.+ `crossing` and `design` are objects, present only when `on` is+ true; one that is absent or is not an object brings no values, and the message stands.+- **Each value stands alone.** Unlike every other message, a value in `crossing` or `design`+ outside the table below, or one this receiver cannot hold (an effect it does not have), is+ left out and the rest still applied, and the message is not malformed for it; an unknown key+ is ignored. Whether a message is newer, and whether it is sent on, is decided by `set_at` and+ `by` alone: one with values left out still wins, takes its stamp, and is sent on as it came.+- The values:++ | Key | Allowed |+ |---|---|+ | `resistance_px` | integer 0 to 500 |+ | `block_while_dragging`, `shortcut`, `shortcut_arrival` | boolean |+ | `trigger_key` | a key name from section 7 that is not a character, a media key, `browser_back`, `browser_forward`, `backspace`, `tab`, `enter`, `esc`, `space` or `print_screen` |+ | `trigger_style` | `"double_tap"` or `"hold"` |+ | `double_tap_ms` | integer 50 to 2000 |+ | `glow_style` | `"glow"`, `"beam"`, or an effect id from `effects.py` |+ | `glow_colour` | `"signal"`, `"colourful"`, `"ocean"`, `"sunset"`, `"mono"`, or a colour pack id from `effects.py` |+ | `effect_length` | `"short"`, `"normal"` or `"long"` |+ | `shortcut_arrival_style` | `"match"`, `"locator"`, or an effect id from `effects.py` |++- Shared: the crossing's feel (resistance, the drag guard, the shortcut and its key) and the+ Design page. Never shared: zones, `side`, the direction switches, the Mac's notch look and+ haptics, and appearance. Version 5's `methods`, `edge_parts` and `corner` are zones now and+ leave the message, and with them goes 1.5.0's mirroring of the corner.+- **Newer wins**: a higher `set_at`, or the same `set_at` and the larger `by` as bytes. This+ replaces the Mac winning a tie, since there may be no Mac. A `set_at` more than a day ahead of+ the receiver's clock, or above 2^53 - 2, is ignored.+- **From and to whom.** A machine takes `settings` only from a peer whose capabilities list+ `settings`, and sends its state to every such peer after each handshake and on every change. One+ that takes a newer state sends it on, unchanged, to every other such peer it has a link to. An+ older or equal one is not sent on, so it stops. Turning it off travels the same way.+- A change made here is stamped with the current time, and never lower than the stamp held plus+ one, so a change on a machine whose clock is behind still wins.++**Follow a machine's design.** Each machine's Design page has **Match design with**: None, or one+paired machine advertising both `settings` and `design_sync`. The selection is local; there is no+group object and the selection is never sent. Only machines linked now are listed, plus the one+followed while it is away; with none, the page says so in one line. A linked machine that does not+advertise `design_sync` is shown unavailable with “Needs beta.6 or later”. Eligibility is the+capability alone; the `app` version string is never compared.++The optional `design_sync` member is independent of `on`. A capable machine sends its own current+Design state to each directly linked capable peer after link-up and whenever its Design changes,+even while Same on all machines is off. The state is:++```json+{"type":"settings","data":{"on":false,"set_at":1790000000,"by":"<b64>",+ "design_sync":{"set_at":1790000001,"by":"<b64>","values":{+ "glow_style":"glow","glow_colour":"colourful","effect_length":"normal",+ "effect_size":"medium","shortcut_arrival":true,"shortcut_arrival_style":"match"}}}}+```++`design_sync` is a complete independently stamped Design state. Its `set_at` and `by` use the+newer-wins ordering and clock bounds above. Values are validated individually; unsupported keys or+values are ignored. Missing `effect_size` means `"medium"`; its wire type is string and allowed+values are `"small"`, `"medium"` and `"large"`. Same on all machines has precedence: the follow+selection stays set but does not apply while Same is on. A newer state from the selected machine+applies to this machine's Design only when its stamp is newer than this machine's own Design stamp.+The follower keeps the leader's `set_at` and `by`, so an announcement carries the same stamp through+a chain (C follows B, B follows A) and both sides of a mutual follow converge on the newest state+when their initial announcements cross in flight. If applying a state leaves every Design value+identical, it is not a change and nothing is announced; the newer stamp is still kept locally, so an+older state cannot replace it.++While a machine follows another, its followed Design controls (style, landing animation, colour,+length and size) are locked, dimmed under a “Following <name>'s design” banner whose Stop+following button ends it and keeps the design shown; local controls stay live. Turning off+Same on all machines resumes following from the selected machine's latest received state. Removing+or unpairing the selected machine resets the selection to None. An offline followed machine leaves+the last look in place; the next link-up sends its current state and catches the follower up.+Older peers ignore the optional field. A peer that does not send it cannot be followed.++## Versions++- **Wire version 6** is in Beamer 1.5.0 and later. It refuses versions 5 and below, and they refuse+ it; each side names the other machine to update.+- **Pairing version 3** is in 1.5.0 and later, and pairs only with itself.+- 1.4.x's settings are migrated once and kept, so going back to 1.4.x on both machines works.++## The vectors++The test vectors for version 6 and pairing version 3 are `core/tests/v6_vectors.json`, and+version 5's, kept byte for byte, `core/tests/v5_vectors.json`; the tests beside them replay each+one against the code and against the primitives written out by hand.++## Changes from version 5++- The preamble is 62 bytes and carries the pair's key id and an ephemeral X25519 share; the keys+ take the X25519 result beside the token and bind the key id, both shares and a direction byte+ in place of the prefixes' order, which gives forward secrecy; the salt is `beamer-link-v6`.+- `hello` and `welcome` carry each machine's id, checked there, and a `hello` naming the wrong id+ is answered `wrong_id`; a typed token, and any token migrated from 1.4.x, no longer links.+- The handshake is bounded as a whole (5 seconds, the preamble in 1) on both sides, where version+ 5's initiator bounded each read at 2 seconds; one pending handshake per address.+- A responder keeps one link per peer and at most one owner, where version 5 kept one link and let+ the newest replace it. `focus` is answered with `accept` or `refuse`.+- `focus` and `switch` name machines by id, not `"mac"` and `"windows"`, and carry a route.+ `focus` no longer carries `return_edge`: the responder's own zones say where its edges lead,+ and the owner sends only its `resistance_px`.+- `hello` no longer carries `return_edge` and `resistance_px`; the arrangement travels only as+ `arrangement`, which names the sender's edge and a `by`, not `mac_edge`.+- `hello` and `welcome` carry the name, platform, app version and capabilities; the `settings: 1`+ flag became the `settings` capability.+- The clipboard follows `focus` instead of going before it, and goes back only when it changed+ under the owner that is leaving.+- `ack` carries `held_us`, and the responder acknowledges a lone event at once.+- Each initiator counts `seq` from 1 on every link; version 5's Mac carried it across reconnects.+- New messages: `accept`, `accepts`, `refuse`, `paired`, `text`.+- `settings` gains the optional `design_sync` member for per-machine Design matches; older betas+ ignore it, while 1.5 keeps it separate from the existing `on` switch.++## Changes from the first design++- **Taking input.** The first design let a `focus` in when it named "the current owner's own switch+ request by its route number". Version 6 has no such path: only a machine with no owner, or its+ own owner, can be taken, and a hand-over is the owner letting go.+- **Non-owners.** The first design dropped a non-owner's `focus`, `arrangement` and settings. Version 6+ answers its `focus` with `refuse`, so it can take its input home at once, and handles+ `arrangement` and `settings` from any peer, because they are between two paired machines rather+ than part of driving; dropping them would lose every change made while nobody drives.+- **The clipboard** is one per machine, not one per link; it follows the input through the owner.+- **Capabilities** gain `clipboard`, since a phone may take no clipboard at all.+- **A driven machine is not taken** (`busy`): the first design did not say what a machine whose own input+ is elsewhere does when taken.+- **Mac to Mac keys** keep their sides; the first design named 1.4.x's positional map, which folds them.+- **Pairing's associated data** gains platform and port, so the pairing code's AD construction+ changes too, not only the bytes fed in.+- **The id in the clear.** The first design put the sender's machine id in the preamble and both ids in+ the keys. Version 6 puts a per-pair key id there instead, with the ids sealed in `hello` and+ `welcome`, and adds forward secrecy (decided 1 and 2).+- **Pairing by QR** carries a second secret (decided 7).+- **Design matching** is a local choice to follow one machine directly. Applying a newer state+ republishes the local result so chains carry on; identical values publish nothing, so mutual+ follows converge without forwarding received state (decided 8).++## Decided++Decided on 30-09-2026, 6 on 01-10-2026, and 8 on 02-10-2026. The text above already follows these.++1. **A per-pair key id in the preamble, not the machine id.** The first 16 bytes of+ `HKDF-SHA-256(token, salt "beamer-link-v6", info "beamer-key-id")`; the machine ids travel in+ `hello` and `welcome` and are checked there; there is no empty-id lookup; key ids are unique+ across entries (section 2).+2. **Forward secrecy in version 6.** An ephemeral X25519 share in each preamble, the result in+ `ikm` and both shares in `info`; a zero result ends the handshake (section 2).+6. **No typed tokens, and no migrated ones.** Follows from 1: 1.5.0 has no token field, and a+ key id is an offline test of its token. The first decision let a migrated token of pairing's+ spelling link; since a typed token can have that spelling and 1.4.x kept no record of which+ it was, no migrated token links, and Overview asks the user to pair that machine again+ (sections 1 and 2).+7. **The QR's extra secret.** 16 random bytes per code in the QR as `k`; `qr: 1` in+ `pair_start` makes the password the code followed by those bytes (section 6).+8. **Follow a machine's Design directly.** A local selection names at most one paired machine and+ never goes on the wire. Machines send their own stamped Design to direct capable peers; a+ follower that changes applies and announces its own resulting state. Identical values announce+ nothing, so a mutual follow converges. Same on all machines takes precedence (section 10).++## Open questions++Open. None touches the wire; the recommendation in each is the design 1.5.0 follows until it is+decided.++3. **The Crossing page and missing pairings.** The first design offered a zone to P only when+ every machine that may drive this one is paired with P. Adding a phone that is not paired with+ P would then take away a zone the desktops use. **Recommendation: offer the zone whenever this+ machine is paired with P, arm it only for owners whose `reach` includes P (section 5), and have+ the page name each machine that cannot follow it.**+4. **The jitter warning's threshold.** **Recommendation: warn when, over the last 30 seconds and at+ least 50 samples, the 95th percentile is 20 ms or more above the median**, and show the median+ and that gap in plain words.+5. **A peer that is already paired.** Pairing refuses a machine already in the list once it has+ linked, so to pair again after one side has removed the other, the user removes it on both.+ **Recommendation: keep the refusal**; the window says exactly which machine still has it.diff --cc core/crash_log.pyindex 0000000,0000000..665bbfcnew file mode 100644--- /dev/null+++ b/core/crash_log.py@@@ -1,0 -1,0 +1,44 @@@++"""What a crash leaves behind, for both apps: an exception that ends a worker thread goes to the log,++and on macOS a fatal signal writes every thread's Python stack beside it.++++Without this a thread's uncaught exception went to stderr, which a bundled app has nowhere to show,++and a native crash left only the system's report, which names the C frames but not the Python++line that called into them (06-10-2026: a crash under rapid switching on an Intel Mac, with nothing++in Beamer.log to say where).++"""++++from __future__ import annotations++++import faulthandler++import logging++import sys++import threading++++# Held for the life of the process: faulthandler writes to the descriptor, not the object.++_fault_file = None++++++def install(directory, logger=None, fatal_signals=None) -> None:++ """`directory` is where the app's log lives; `crash.log` is written there on a fatal signal.++ `fatal_signals` defaults to macOS only: on Windows faulthandler also reports access violations++ that the code raising them goes on to handle, and would fill the file with crashes that were not."""++ global _fault_file++ logger = logger or logging.getLogger("Beamer")++++ def log_thread_exception(args):++ if issubclass(args.exc_type, SystemExit):++ return++ name = args.thread.name if args.thread is not None else "unknown"++ logger.critical("thread %s ended on an uncaught exception", name,++ exc_info=(args.exc_type, args.exc_value, args.exc_traceback))++++ threading.excepthook = log_thread_exception++ if fatal_signals is None:++ fatal_signals = sys.platform == "darwin"++ if not fatal_signals:++ return++ try:++ _fault_file = open(f"{directory}/crash.log", "a", encoding="utf-8")++ faulthandler.enable(file=_fault_file, all_threads=True)++ except (OSError, ValueError, RuntimeError):++ logger.exception("could not set up crash.log")diff --cc core/link.pyindex b7c532c,0000000..4c9e830mode 100644,000000..100644--- a/core/link.py+++ b/core/link.py@@@ -1,814 -1,0 +1,840 @@@+"""The initiator's side of the link: WIRE.md sections 2, 3 and 9 from the machine that opens it.++One OutboundLink per peer entry with `send` on. It dials the entry's `host` and `port`, runs the+initiator's half of the handshake (section 2), keeps the link alive (a `ping` after a second of+silence, the link ended after two without a byte), numbers the input it is given, measures the+round trip from each `ack` and reconnects every couple of seconds while it is down. Nothing in it+knows which platform it runs on, and it decides nothing about routing: the owner (core/owner.py)+says what to send, the app hands it here, and every inbound message other than `ack` goes back to+the app through `message`.++Callbacks, each on the link's own thread, never with a lock of the link's held:+`state(link, up, text)` for every change of how the link is doing, `text` being the sentence to+show; `up(link, fields)` once the handshake is done and before anything else is sent, `fields`+being the `welcome` as protocol.read_welcome gives it (`id` as 16 bytes); `message(link, message)`."""++import collections+import errno+import logging+import math+import socket+import threading+import time++from core import peerlist+from core import protocol+from core import receiver++LOGGER = logging.getLogger("Beamer")++CONNECT_SECONDS = 1.0+HANDSHAKE_SECONDS = 5.0+RECONNECT_SECONDS = 2.0++FORGOTTEN_AFTER_SECONDS = 60.0++FORGOTTEN_RETRY_SECONDS = 30.0+PING_SECONDS = 1.0+SILENCE_SECONDS = 2.0+READ_SECONDS = 0.1+QUEUE_LIMIT = 2048+QUEUE_BYTES = 32 * 1024 * 1024+STALL_SECONDS = 2.0+SENT_RECORD_LIMIT = 20000+MEDIA_KEYS = frozenset({"volume_mute", "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"})+WINDOW_SECONDS = 30.0+LOG_SECONDS = 60.0+FOLLOW_AFTER_SECONDS = 10.0+FOLLOW_EVERY_SECONDS = 30.0+SEND_CHUNK = 65536+_CAP_FOR = {protocol.MSG_GESTURE: "gestures", protocol.MSG_TEXT: "text", protocol.MSG_SETTINGS: "settings"}+++class LinkEnded(Exception):+ """The link is over; `text` is the sentence to show."""++ def __init__(self, text, kind="failed", stop_dialling=False):+ super().__init__(text)+ self.text = text+ self.kind = kind+ self.stop_dialling = stop_dialling+++def connection_ended(exc, name):+ """What a failed connect says, in the words 1.4.x used, naming the peer."""+ number = getattr(exc, "errno", None)+ if number in (51, 64, 65, errno.EHOSTUNREACH, errno.ENETUNREACH):+ return LinkEnded(f"{name} is unreachable from this machine. Check that both can communicate on the local network.", "unreachable")+ if number in (61, errno.ECONNREFUSED):+ return LinkEnded(f"{name} is reachable, but Beamer is not listening on this port.", "refused")+ if isinstance(exc, (socket.timeout, TimeoutError)):+ return LinkEnded(f"{name} did not answer before the connection timed out.", "timeout")+ return LinkEnded(f"Connection failed: {exc}", "failed")+++class OutboundLink:+ def __init__(+ self,+ token,+ book,+ identity,+ *,+ state=None,+ up=None,+ message=None,+ socket_factory=socket.create_connection,+ tunnel=None,+ clock=time.monotonic,+ reconnect_seconds=RECONNECT_SECONDS,+ hardware=None,+ large=None,+ ):+ self.token = token+ self.key_id = protocol.key_id(token) if protocol.is_paired_token(token) else None+ self._book = book+ self._identity = identity+ # `hardware(host)`: this machine's address on the interface that reaches `host`, asked for each+ # link's own host so every peer is sent the address its wake-on-LAN must go to.+ self._hardware = hardware+ # `large(link, began)`: whether a frame too large for any message but a clipboard, which began+ # arriving at `began`, may be read: only the clipboard of a let-go (owner.expects_clipboard).+ # Any other such frame is opened, so its counter is spent, and dropped without being parsed.+ self._large = large+ self._callbacks = (state, up, message)+ self._muted = False+ self._factory = socket_factory+ self._tunnel = tunnel+ self._clock = clock+ self._reconnect = reconnect_seconds+ self._stop = threading.Event()+ self._thread = None+ self._lock = threading.Lock()+ self._wake = threading.Event()+ self._stall = threading.Event()+ self._live = False+ self._sock = None+ self._pending = None+ self._session = None+ self._outbox = collections.deque()+ self._cond = threading.Condition(self._lock)+ self._seq = 0+ self.last_sent_seq = 0+ self._written_seq = 0+ self._sent_at = collections.deque()+ self._samples = collections.deque()+ self._period = []+ self._last_ack_seq = -1+ self.last_ack_at = None+ self._last_rx = 0.0+ self._last_tx = 0.0+ self._logged_at = 0.0+ self._caps = frozenset()+ self.peer_id = ""+ self.peer_platform = ""+ self.peer_name = ""+ self.via_tunnel = False+ self._queued_bytes = 0+ self._ping_queued = False+ self._writing = False+ self._locked = False+ self._last_progress = 0.0+ self.down_since = clock()+ self._blocked_for = None+ self._try_host = None+ self._followed_at = None+ self._followed_to = None+ self._answered = False+ self._checked_at = 0.0+ self.status = ""+ # What the last report was, for the app to word in its own way: "connected", "removed",- # "off", "unreachable", "refused", "timeout", "stopped", "closed", "older", "newer",++ # "off", "unreachable", "refused", "timeout", "stopped", "closed", "forgotten", "older", "newer",+ # "not_beamer", "different", "unauthenticated", "wrong_id", "unreadable", "failed".+ self.kind = "failed"+ self.dialled = None+ self._drop_reason = None++ # Lifetime++ @property+ def running(self):+ return self._thread is not None and self._thread.is_alive()++ @property+ def caps(self):+ return self._caps++ def start(self):+ old = self._thread+ if old is not None and old.is_alive() and self._stop.is_set() and old is not threading.current_thread():+ old.join(timeout=2.0)+ with self._lock:+ if self.running:+ self._blocked_for = None+ self._wake.set()+ return+ self._stop.clear()+ self._muted = False+ self._blocked_for = None+ self._thread = threading.Thread(target=self._run, name="Beamer-link", daemon=True)+ self._thread.start()++ def stop(self, wait=True):+ """End the link for good. By default this returns once its thread has, so nothing is+ reported afterwards; a caller that must not wait (a window removing machines, with the+ thread possibly in a 3 second connect) passes `wait=False`: the socket is closed, the+ thread ends on its own, and from this call on nothing it does is reported."""+ self._muted = not wait+ self._stop.set()+ self._wake.set()+ self._close()+ thread = self._thread+ if wait and thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)++ def drop(self, reason):+ """End the link now, saying why; the link then reconnects as it would after any loss."""+ self._drop_reason = reason+ self._close()++ def flush(self, timeout=0.5):+ """Wait, for at most `timeout`, until what is queued has been written: a machine that is+ stopping gives the let-go `focus` it just posted time to leave."""+ end = time.monotonic() + timeout+ while time.monotonic() < end:+ with self._cond:+ if not self._live or (not self._outbox and not self._writing):+ return+ time.sleep(0.01)++ def refresh(self):+ """The entry changed: a link that stopped dialling after `wrong_id` may try again."""+ self._blocked_for = None+ self._wake.set()++ def live(self):+ return self._live++ # Reading the entry++ def entry(self):+ for peer in self._book.peers():+ if peer.get("token") == self.token:+ return peer+ return None++ @staticmethod+ def _target(entry):+ """Where to dial the entry, or None when it is not dialled: send off, no address, or not+ made by pairing (a typed token, or any token migrated from 1.4.x)."""+ host, port = entry.get("host"), entry.get("port")+ if (not protocol.linkable(entry) or entry.get("in_use", True) is not True or entry.get("send") is not True+ or not host or isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535):+ return None+ return host, port++ def _name(self, entry):+ """What this link's sentences call the machine: its label, so two of one name are told apart."""+ entry = entry or {}+ try:+ shown = peerlist.label_for(self._book.peers(), token=entry.get("token"))+ except Exception:+ shown = ""+ return shown or entry.get("name") or entry.get("host") or "The other machine"++ # The thread++ def _run(self):++ closed_since = None+ try:+ while not self._stop.is_set():+ try:+ entry = self.entry()+ except Exception:+ # A settings file that cannot be read this once (a lock, a half-written save) is+ # not a removed pairing; the thread must outlive it or the peer is never dialled again.+ LOGGER.exception("Could not read the settings for a link; trying again")+ self._wake.wait(self._reconnect)+ self._wake.clear()+ continue+ if entry is None:+ self._report(False, "This pairing was removed", "removed")+ return+ target = self._target(entry)+ shape = (entry.get("host"), entry.get("port"), entry.get("id"))+ if self._blocked_for is not None and self._blocked_for != shape:+ self._blocked_for = None+ with self._lock:+ tried, self._try_host = self._try_host, None+ if self._blocked_for is not None:+ self._wake.wait(0.25)+ self._wake.clear()+ continue+ if target is None:+ # A beacon's address is tried only for an entry that could be dialled at all.+ self._wake.wait(0.25)+ self._wake.clear()+ continue+ port = target[1]+ host = tried or target[0]++ wait = self._reconnect+ try:+ self._connect(entry, host, port, direct=tried is not None)++ closed_since = None+ except LinkEnded as ended:+ # A try at a beacon's address that fails shows nothing: a forged beacon must+ # not be able to put a message in front of the user, or block the real address.+ if tried is None and not self._stop.is_set():- self._report(False, ended.text, ended.kind)++ # Closed unanswered, and only that, for a minute by a machine this one has linked++ # with: it no longer has this pairing (WIRE.md section 2, initiator step 3). A++ # peer that is busy or still waking answers something else, or answers, within++ # that time. Said once, and dialled slowly, rather than every two seconds for++ # ever (06-10-2026).++ now = self._clock()++ if ended.kind == "closed" and entry.get("linked"):++ if closed_since is None:++ closed_since = now++ else:++ closed_since = None++ if closed_since is not None and now - closed_since >= FORGOTTEN_AFTER_SECONDS:++ name = self._name(entry)++ if self.kind != "forgotten":++ LOGGER.info("%s has closed every handshake for %d seconds; it no longer has this pairing",++ name, FORGOTTEN_AFTER_SECONDS)++ self._report(False, f"{name} no longer has this pairing: remove {name} here and pair "++ "the two again", "forgotten")++ wait = max(wait, FORGOTTEN_RETRY_SECONDS)++ else:++ self._report(False, ended.text, ended.kind)+ if ended.stop_dialling:+ self._blocked_for = shape+ except Exception:++ closed_since = None+ LOGGER.exception("the link to %s failed", self._name(entry))+ if tried is None and not self._stop.is_set():+ self._report(False, "The link failed", "failed")+ if self._stop.is_set():+ break- self._wake.wait(self._reconnect)++ self._wake.wait(wait)+ self._wake.clear()+ finally:+ self._live = False++ def _report(self, up, text, kind=None):+ self.status = text+ if kind is not None:+ self.kind = kind+ state = self._callbacks[0]+ if state is not None and not self._muted:+ try:+ state(self, up, text)+ except Exception:+ LOGGER.exception("state callback failed")++ def _call(self, index, *args):+ callback = self._callbacks[index]+ if callback is None or self._muted:+ return+ try:+ callback(self, *args)+ except Exception:+ LOGGER.exception("link callback failed")++ # The handshake (WIRE.md section 2, the initiator)++ def _connect(self, entry, host, port, direct):+ name = self._name(entry)+ sock = None+ self.via_tunnel = False+ self._dialled_to, self._dialled_port = host, port+ try:+ try:+ sock = self._factory((host, port), timeout=CONNECT_SECONDS)+ except OSError as exc:+ if exc.errno != errno.EHOSTUNREACH or self._tunnel is None or direct:+ raise connection_ended(exc, name) from None+ try:+ sock = self._tunnel()+ except OSError as tunnel_exc:+ raise LinkEnded("macOS 27 blocked direct LAN access. Open /Applications/Beamer Tunnel.command.", "blocked") from tunnel_exc+ self.via_tunnel = True+ self.status = f"Connecting to {host}:{port}"+ with self._lock:+ self._pending = sock+ if self._stop.is_set():+ raise LinkEnded("This link was stopped", "off")+ deadline = time.monotonic() + HANDSHAKE_SECONDS+ fields = self._handshake(_Interruptible(sock, self._stop), entry, host, deadline, direct)+ if self._stop.is_set():+ raise LinkEnded("This link was stopped", "off")+ except LinkEnded:+ self._forget_pending(sock)+ raise+ except (socket.timeout, TimeoutError):+ self._forget_pending(sock)+ if self._answered:+ raise LinkEnded(f"{name} stopped responding", "stopped") from None+ raise LinkEnded(f"{name} did not answer as a Beamer: it is probably running one from before version 4", "not_beamer") from None+ except (protocol.ConnectionClosed, ConnectionError):+ self._forget_pending(sock)+ raise LinkEnded(self._closed_text(entry), "closed") from None+ except OSError as exc:+ self._forget_pending(sock)+ raise connection_ended(exc, name) from None+ except protocol.AuthenticationError:+ self._forget_pending(sock)+ raise LinkEnded(f"{name} could not be authenticated: something on the path altered the link", "unauthenticated") from None+ except protocol.ProtocolError as exc:+ self._forget_pending(sock)+ raise LinkEnded(f"{name} did not answer like Beamer: {exc}", "failed") from None+ self._answered = True+ sock.settimeout(READ_SECONDS)+ with self._lock:+ self._pending = None+ self._serve(sock, fields)++ def _hardware_towards(self, host, identity):+ """The `hw` for the hello to `host`. The hook is optional and never fatal: a hook that raises+ sends none, because the field is optional on the wire and the link matters more."""+ if self._hardware is None:+ return identity.get("hw")+ try:+ return self._hardware(host) or None+ except Exception:+ LOGGER.exception("Could not read this machine's hardware address towards %s", host)+ return None++ def _forget_pending(self, sock):+ with self._lock:+ if self._pending is sock:+ self._pending = None+ _close_socket(sock)++ def _closed_text(self, entry):+ name = self._name(entry)+ if not entry.get("linked"):+ return f"Update Beamer on {name} to 1.5.0; if it is up to date, pair the two again"+ return f"{name} closed the connection: it may have removed this machine, or be too busy to answer"++ def _handshake(self, sock, entry, host, deadline, direct):+ name = self._name(entry)+ identity = self._identity()+ own_id = bytes(identity["id"])+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)+ session = protocol.LinkSession(self.token, protocol.ROLE_INITIATOR)+ sock.sendall(session.preamble())+ try:+ # No separate deadline for the preamble: the handshake's five seconds cover it all.+ preamble = protocol.recv_link_preamble(sock, deadline)+ except protocol.VersionMismatch as exc:+ if exc.peer_version is None:+ raise LinkEnded(f"{name} did not answer as a Beamer", "not_beamer") from None+ if exc.peer_version < protocol.LINK_VERSION:+ raise LinkEnded(f"Update Beamer on {name}: it is older than this one", "older") from None+ raise LinkEnded(f"{name} runs a newer Beamer: update Beamer on this machine", "newer") from None+ try:+ session.accept_preamble(preamble)+ except protocol.PreambleRefused:+ raise LinkEnded(f"A different Beamer answered at {host}", "different") from None+ hello = protocol.hello_v6(+ own_id, identity["name"], identity["platform"], identity["app"], identity["caps"], int(identity.get("port") or 0), self._hardware_towards(host, identity))+ sock.settimeout(max(0.001, deadline - time.monotonic()))+ protocol.send_msg(sock, session, hello)+ try:+ welcome = protocol.read_welcome(protocol.recv_first_msg(sock, session, deadline))+ except protocol.HelloRefused as refused:+ if refused.error == protocol.ERROR_WRONG_ID:+ raise LinkEnded(f"{name} has this pairing under another machine: remove it on both and pair again.", "wrong_id", stop_dialling=True) from None+ raise LinkEnded(f"{name} could not read what this machine sent first; Beamer on the two machines may differ", "unreadable") from None+ except (protocol.InvalidWelcome, protocol.NotAnObject):+ raise LinkEnded(f"A different Beamer answered at {host}", "different") from None+ changes = {"name": welcome["name"], "platform": welcome["platform"]}+ if welcome["hw"] is not None:+ changes["hw"] = welcome["hw"]+ if direct and host != entry.get("host"):+ changes["host"] = host+ try:+ outcome, _ = self._book.admit(self.key_id, own_id, welcome["id"], changes)+ except Exception:+ LOGGER.exception("Could not save what the link to %s taught", name)+ raise LinkEnded(f"Could not save what {name} told this machine", "failed") from None+ if outcome == receiver.GONE:+ raise LinkEnded("This pairing was removed", "removed")+ if outcome == receiver.WRONG_ID:+ raise LinkEnded(f"A different Beamer answered at {host}", "different")+ sock.settimeout(READ_SECONDS)+ welcome["session"] = session+ return welcome++ # A live link++ def _serve(self, sock, fields):+ session = fields.pop("session")+ entry = self.entry() or {}+ now = self._clock()+ with self._lock:+ self._sock, self._session = sock, session+ self._caps = frozenset(fields["caps"])+ self.peer_id = protocol.id_text(fields["id"])+ self.peer_platform = fields["platform"]+ self.peer_name = fields["name"]+ self._reset_link_state()+ self._last_rx = self._last_tx = self._last_progress = self._logged_at = now+ self._live = True+ name = self._name(entry)+ writer = threading.Thread(target=self._write, args=(sock, session), name="Beamer-link-writer", daemon=True)+ writer.start()+ way = " via the secure macOS 27 fallback" if self.via_tunnel else ""+ self.dialled = (self._dialled_to, self._dialled_port)+ self._report(True, f"Connected to {name}{way}", "connected")+ self._call(1, fields)+ reason, kind = f"{name} closed the connection", "closed"+ try:+ self._read(sock, session, name)+ except LinkEnded as ended:+ reason, kind = ended.text, ended.kind+ except (protocol.ConnectionClosed, ConnectionError):+ pass+ except protocol.AuthenticationError:+ reason, kind = f"{name} could not be authenticated: something on the path altered the link", "unauthenticated"+ except (OSError, protocol.ProtocolError) as exc:+ reason, kind = f"The link to {name} failed: {exc}", "failed"+ finally:+ if self._drop_reason is not None:+ reason, kind, self._drop_reason = self._drop_reason, "failed", None+ self._close()+ writer.join(timeout=1.0)+ self.down_since = self._clock()+ self._followed_at = None+ self._report(False, reason, kind)++ def _reset_link_state(self):+ self._outbox.clear()+ self._queued_bytes = 0+ self._ping_queued = False+ self._writing = False+ self._seq = self.last_sent_seq = self._written_seq = 0+ self._sent_at.clear()+ self._samples.clear()+ self._period = []+ self._last_ack_seq = -1+ self.last_ack_at = None+ self._locked = False+ self._drop_reason = None++ def _close(self, only=None):+ with self._cond:+ if only is not None and self._sock is not only:+ return+ sock, self._sock = self._sock, None+ pending = self._pending if only is None else None+ self._live = False+ self._cond.notify_all()+ _close_socket(sock)+ _close_socket(pending)++ def _read(self, sock, session, name):+ buffer = bytearray()+ began = None+ while not self._stop.is_set() and self._sock is sock:+ try:+ chunk = sock.recv(65536)+ except socket.timeout:+ chunk = None+ now = self._clock()+ if chunk is not None:+ if not chunk:+ raise protocol.ConnectionClosed("closed")+ if not buffer:+ began = now+ buffer.extend(chunk)+ self._last_rx = now+ elif now - self._last_rx > SILENCE_SECONDS:+ raise LinkEnded(f"{name} stopped responding", "stopped")+ while len(buffer) >= protocol.HEADER_SIZE:+ length = int.from_bytes(buffer[:protocol.HEADER_SIZE], "big")+ if length < protocol.MIN_FRAME_BYTES or length > protocol.MAX_FRAME_BYTES:+ raise protocol.ProtocolError(f"invalid message length: {length}")+ if len(buffer) < protocol.HEADER_SIZE + length:+ break+ if now - began > protocol.FRAME_COMPLETE_SECONDS:+ raise LinkEnded(f"{name} took too long to send one message", "stopped")+ body = bytes(buffer[protocol.HEADER_SIZE:protocol.HEADER_SIZE + length])+ del buffer[:protocol.HEADER_SIZE + length]+ plain = session.open_raw(body)+ if len(plain) > protocol.SMALL_MESSAGE_BYTES and not self._large_due(began or now):+ LOGGER.warning("Dropped a %d byte message from %s that no clipboard was due for", len(plain), name)+ else:+ self._deal(protocol.parse_message(plain), began or now)+ began = now if buffer else None+ if buffer and now - began > protocol.FRAME_COMPLETE_SECONDS:+ raise LinkEnded(f"{name} took too long to send one message", "stopped")+ self._tick(now)++ def _large_due(self, began):+ if self._large is None:+ return True+ try:+ return bool(self._large(self, began))+ except Exception:+ LOGGER.exception("Could not tell whether a large message was due")+ return False++ def _deal(self, message, began):+ if message.get("type") == protocol.MSG_ACK:+ self._ack(protocol.read_ack(message))+ return+ message.began_at = began+ self._call(2, message)++ def _tick(self, now):+ if self._writing and now - self._last_progress > STALL_SECONDS:+ raise LinkEnded(f"{self._name(self.entry())} stopped accepting data", "stopped")+ if now - self._checked_at >= 1.0:+ self._checked_at = now+ entry = self.entry()+ if entry is None:+ raise LinkEnded("This pairing was removed", "removed")+ if entry.get("send") is not True:+ raise LinkEnded("Sending to this machine was switched off", "off")+ if now - self._last_tx >= PING_SECONDS:+ self._tick_ping()+ if now - self._logged_at >= LOG_SECONDS:+ self._logged_at = now+ self._log_round_trips()++ def _log_round_trips(self):+ """Section 9's line for the minute just past: what was measured, and nothing when no input+ was on this link."""+ with self._lock:+ period, self._period = self._period, []+ if not period:+ return+ ordered = sorted(sample for sample, _held in period)+ count = len(ordered)+ LOGGER.info(+ "round trip to %s: %d samples, median %.1f ms, 95th percentile %.1f ms, largest %.1f ms, mean held_us %.0f",+ self.peer_name, count, ordered[count // 2] * 1000, ordered[math.ceil(count * 0.95) - 1] * 1000,+ ordered[-1] * 1000, sum(held for _sample, held in period) / count)++ def _tick_ping(self):+ with self._cond:+ if self._ping_queued:+ return+ self._ping_queued = True+ if not self._enqueue(protocol.ping_msg(), seq=False):+ self._ping_queued = False++ # Sending++ def post(self, message):+ """A message that carries no `seq`. False when the link is down, the queue is full, or the+ peer cannot take it; a clipboard keeps only the parts its capabilities cover."""+ if not self._live:+ return False+ kind = message.get("type")+ if kind == protocol.MSG_CLIPBOARD:+ data = dict(message.get("data") or {})+ if "clipboard" not in self._caps:+ data.pop("text", None)+ if "clipboard_image" not in self._caps:+ data.pop("image", None)+ data.pop("image_format", None)+ if not data.get("text") and "image" not in data:+ return True+ message = {"type": kind, "data": data}+ elif _CAP_FOR.get(kind) is not None and _CAP_FOR[kind] not in self._caps:+ return True+ return self._enqueue(message, seq=False)++ def send_input(self, message):+ """An input message: given the link's next `seq` and its send time recorded. False when the+ link is down or its queue is full, which the caller treats as the link having failed."""+ kind = message.get("type")+ if kind not in protocol.INPUT_TYPES or not self._live:+ return False+ if kind in _CAP_FOR and _CAP_FOR[kind] not in self._caps:+ return True+ if kind in (protocol.MSG_KEYDOWN, protocol.MSG_KEYUP) and (message.get("data") or {}).get("key") in MEDIA_KEYS and "media_keys" not in self._caps:+ return True+ return self._enqueue(message, seq=True)++ def _enqueue(self, message, seq):+ size = _weight(message)+ with self._cond:+ if not self._live or len(self._outbox) >= QUEUE_LIMIT or self._queued_bytes + size > QUEUE_BYTES:+ return False+ self._queued_bytes += size+ if seq:+ self._seq += 1+ data = dict(message.get("data") or {})+ data["seq"] = self._seq+ message = {"type": message["type"], "data": data}+ self.last_sent_seq = self._seq+ self._outbox.append(message)+ self._cond.notify()+ return True++ def _write(self, sock, session):+ try:+ while True:+ with self._cond:+ while not self._outbox or self._stall.is_set():+ if self._sock is not sock:+ return+ self._cond.wait(0.05)+ if self._sock is not sock:+ return+ message = self._outbox.popleft()+ self._queued_bytes = max(0, self._queued_bytes - _weight(message))+ if message.get("type") == protocol.MSG_PING:+ self._ping_queued = False+ self._writing = True+ self._last_progress = self._clock()+ seq = message.get("data", {}).get("seq")+ if seq is not None and message["type"] in protocol.INPUT_TYPES:+ # Before the write: the peer's `ack` can reach the reader before this thread+ # runs again, and it must find the seq already counted as sent.+ with self._lock:+ self._written_seq = seq+ self._sent_at.append((seq, self._clock()))+ self._check_sent_record()+ frame = memoryview(session.seal(message))+ sent = 0+ while sent < len(frame):+ try:+ sent += sock.send(frame[sent:sent + SEND_CHUNK])+ self._last_progress = self._clock()+ except socket.timeout:+ if self._sock is not sock:+ return+ self._last_tx = self._clock()+ self._writing = False+ except (OSError, protocol.ProtocolError, ValueError) as exc:+ LOGGER.info("Sending to %s failed: %s", self.peer_name, exc)+ self._close(only=sock)++ # Acknowledgements (section 9)++ def _check_sent_record(self):+ if len(self._sent_at) > SENT_RECORD_LIMIT:+ raise protocol.ProtocolError("the peer has not acknowledged anything it was sent")++ def _ack(self, ack):+ seq, held = ack["seq"], ack["held_us"]+ now = self._clock()+ with self._lock:+ if seq < self._last_ack_seq:+ raise protocol.ProtocolError("ack moved backwards")+ if seq > self._written_seq:+ raise protocol.ProtocolError("ack is ahead of anything sent")+ advanced = seq > self._last_ack_seq+ self._last_ack_seq = seq+ self.last_ack_at = now+ sent = None+ while self._sent_at and self._sent_at[0][0] <= seq:+ sent_seq, at = self._sent_at.popleft()+ if sent_seq == seq:+ sent = at+ if advanced and sent is not None:+ sample = max(0.0, now - sent - held / 1_000_000)+ self._samples.append((now, sample))+ self._period.append((sample, held))+ while self._samples and now - self._samples[0][0] > WINDOW_SECONDS:+ self._samples.popleft()+ self._locked = ack["locked"]++ @property+ def peer_locked(self):+ return bool(getattr(self, "_locked", False)) and self._live++ def round_trips(self, max_age=WINDOW_SECONDS):+ """The round trips measured in the last `max_age` seconds (thirty at most), oldest first."""+ now = self._clock()+ with self._lock:+ return [sample for at, sample in self._samples if now - at <= min(max_age, WINDOW_SECONDS)]++ # Following a peer to a new address (section 6)++ def follow(self, machines):+ """`machines`: what discovery hears, dicts with `name`, `address` and, while that machine shows+ a code, `id`. A link down for ten seconds is tried once at the address of a beacon with this+ entry's exact name, at its saved port, at most every thirty seconds. The address is saved only+ once the link authenticates. Two machines may share a name, so a beacon whose `id` is another+ machine's is passed over, one at another paired machine's saved address is tried after the+ rest (the two may have swapped addresses), and several are tried in turn rather than the+ first for ever."""+ if self._live or self.key_id is None:+ return+ now = self._clock()+ if now - self.down_since < FOLLOW_AFTER_SECONDS:+ return+ if self._followed_at is not None and now - self._followed_at < FOLLOW_EVERY_SECONDS:+ return+ entry = self.entry()+ if entry is None or self._target(entry) is None or not entry.get("name"):+ return+ others = {peer.get("host") for peer in self._book.peers() if peer.get("token") != self.token}+ own_id = entry.get("id")+ found = [m["address"] for m in machines+ if m.get("name") == entry["name"] and m.get("address") and m["address"] != entry.get("host")+ and not (own_id and m.get("id") and m["id"] != own_id)]+ found = [address for address in found if address not in others] + [address for address in found if address in others]+ if not found:+ return+ address = found[(found.index(self._followed_to) + 1) % len(found)] if self._followed_to in found else found[0]+ self._followed_at = now+ self._followed_to = address+ with self._lock:+ self._try_host = address+ self._wake.set()+++class _Interruptible:+ """The handshake's socket: `recv` waits in short slices so `stop()` is noticed within a tenth+ of a second. Shutting a socket down from another thread does not wake a blocked read on every+ platform (macOS does not), and a handshake can otherwise hold a stopped link for five seconds."""++ def __init__(self, sock, stopped):+ self._sock = sock+ self._stopped = stopped+ self._timeout = None++ def settimeout(self, value):+ self._timeout = value++ def recv(self, size):+ end = None if self._timeout is None else time.monotonic() + self._timeout+ while True:+ if self._stopped.is_set():+ raise OSError(errno.ECONNABORTED, "the link was stopped")+ left = 0.1 if end is None else min(0.1, end - time.monotonic())+ if left <= 0:+ raise socket.timeout("timed out")+ self._sock.settimeout(left)+ try:+ return self._sock.recv(size)+ except socket.timeout:+ continue++ def __getattr__(self, name):+ return getattr(self._sock, name)+++def _weight(message):+ """About how many bytes a queued message holds: a clipboard's text and image, else nothing."""+ if message.get("type") != protocol.MSG_CLIPBOARD:+ return 0+ data = message.get("data") or {}+ return len(data.get("text") or "") * 4 + len(data.get("image") or "")+++def _close_socket(sock):+ if sock is None:+ return+ try:+ sock.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ sock.close()+ except OSError:+ passdiff --cc core/tests/test_crash_log.pyindex 0000000,0000000..0b7620cnew file mode 100644--- /dev/null+++ b/core/tests/test_crash_log.py@@@ -1,0 -1,0 +1,75 @@@++"""core/crash_log.py: a worker thread's uncaught exception reaches the log, and a fatal signal leaves++every thread's Python stack in crash.log."""++++import logging++import os++import subprocess++import sys++import tempfile++import threading++import unittest++from pathlib import Path++++from core import crash_log++++REPO = Path(__file__).resolve().parent.parent.parent++++++class Catch(logging.Handler):++ def __init__(self):++ super().__init__()++ self.records = []++++ def emit(self, record):++ self.records.append(record)++++++class AThreadThatRaises(unittest.TestCase):++ def setUp(self):++ before = threading.excepthook++ self.addCleanup(setattr, threading, "excepthook", before)++ self.logger = logging.getLogger("crash-log-test")++ self.logger.propagate = False++ self.catch = Catch()++ self.logger.addHandler(self.catch)++ self.addCleanup(self.logger.removeHandler, self.catch)++++ def test_its_exception_and_the_thread_are_in_the_log(self):++ with tempfile.TemporaryDirectory() as directory:++ crash_log.install(directory, self.logger, fatal_signals=False)++++ def fails():++ raise ValueError("lost on a worker thread")++++ worker = threading.Thread(target=fails, name="Beamer-link")++ worker.start()++ worker.join()++ [record] = self.catch.records++ self.assertEqual(record.levelno, logging.CRITICAL)++ self.assertIn("Beamer-link", record.getMessage())++ self.assertIs(record.exc_info[0], ValueError)++++[email protected](hasattr(os, "kill") and sys.platform != "win32", "a fatal signal is a POSIX test")++class AFatalSignal(unittest.TestCase):++ def test_leaves_the_python_stack_of_every_thread_in_crash_log(self):++ with tempfile.TemporaryDirectory() as directory:++ script = (++ "import os, signal, threading, time\n"++ "from core import crash_log\n"++ f"crash_log.install({directory!r}, fatal_signals=True)\n"++ "def waits_on_the_link():\n"++ " time.sleep(30)\n"++ "threading.Thread(target=waits_on_the_link, daemon=True).start()\n"++ "time.sleep(0.2)\n"++ "os.kill(os.getpid(), signal.SIGSEGV)\n"++ )++ result = subprocess.run([sys.executable, "-c", script], cwd=REPO, capture_output=True, timeout=30)++ self.assertNotEqual(result.returncode, 0)++ text = (Path(directory) / "crash.log").read_text(encoding="utf-8")++ self.assertIn("Segmentation fault", text)++ self.assertIn("waits_on_the_link", text)++++++if __name__ == "__main__":++ unittest.main()diff --cc core/tests/test_link.pyindex 56f2b37,0000000..2c1361cmode 100644,000000..100644--- a/core/tests/test_link.py+++ b/core/tests/test_link.py@@@ -1,1173 -1,0 +1,1241 @@@+"""core.link.OutboundLink, the initiator's side of WIRE.md sections 2, 3 and 9, against a real+LinkResponder on loopback (responder_harness.Machine) and a scripted responder where a test needs+a peer that misbehaves."""+++import errno+import socket+import struct+import threading+import time+import unittest+from unittest import mock++from core import protocol, receiver+from core import link as link_module+from core.link import OutboundLink+from core.tests.responder_harness import B, C, CAPS, HERE, TOKENS, Machine, Settings, entry, wait_for++LOOPBACK = "127.0.0.1"+++class Side:+ """The initiator's own settings, with one peer entry for the machine it dials."""++ def __init__(self, machine=None, peer=HERE, own=B, token=None, **fields):+ port = machine.port if machine is not None else 24820+ data = entry(peer, "Far", token=token or TOKENS[B], host=LOOPBACK, port=port, send=True, **fields)+ self.settings = Settings([data])+ self.settings.data["machine_id"] = protocol.id_text(own)+ self.own = own+ self.book = receiver.PeerBook(self.settings.load, self.settings.save)+ self.states, self.ups, self.messages = [], [], []++ def identity(self, **fields):+ data = {"id": self.own, "name": "Near", "platform": "macos", "app": "1.5.0", "caps": list(CAPS), "port": 24820}+ data.update(fields)+ return data++ def link(self, **kwargs):+ kwargs.setdefault("reconnect_seconds", 0.05)+ link = OutboundLink(+ self.settings.data["peers"][0]["token"], self.book, self.identity,+ state=lambda link, up, text: self.states.append((up, text)),+ up=lambda link, fields: self.ups.append(fields),+ message=lambda link, message: self.messages.append(message),+ **kwargs,+ )+ return link++ def peer(self):+ return self.settings.data["peers"][0]++ def last_text(self):+ return self.states[-1][1] if self.states else None+++def machine_with_peer(**kwargs):+ from core.tests.responder_harness import entry as make+ return Machine([make(B, "Peer")], **kwargs).start()+++class Scripted:+ """A listener that runs `script(connection)` for each connection."""++ def __init__(self, script):+ self.script = script+ self.listener = socket.socket()+ self.listener.bind((LOOPBACK, 0))+ self.listener.listen(4)+ self.port = self.listener.getsockname()[1]+ self.connections = 0+ self.stopped = False+ self.thread = threading.Thread(target=self._serve, daemon=True)+ self.thread.start()++ def _serve(self):+ while not self.stopped:+ try:+ connection, _ = self.listener.accept()+ except OSError:+ return+ self.connections += 1+ threading.Thread(target=self._one, args=(connection,), daemon=True).start()++ def _one(self, connection):+ try:+ self.script(connection)+ except Exception:+ pass+ finally:+ try:+ connection.close()+ except OSError:+ pass++ def stop(self):+ self.stopped = True+ self.listener.close()+++def scripted_session(connection, token):+ """The responder's half of the handshake up to its own preamble; the session and hello."""+ session = protocol.LinkSession(token, protocol.ROLE_RESPONDER)+ session.accept_preamble(protocol.recv_link_preamble(connection, time.monotonic() + 5))+ connection.sendall(session.preamble())+ hello = protocol.read_hello(protocol.recv_first_msg(connection, session, time.monotonic() + 5))+ return session, hello+++class LinkHandshakeTests(unittest.TestCase):+ def setUp(self):+ self.machine = machine_with_peer()+ self.addCleanup(self.machine.stop)++ def start(self, side, **kwargs):+ link = side.link(**kwargs)+ self.addCleanup(link.stop)+ link.start()+ return link++ def test_links_and_saves_what_the_welcome_taught(self):+ side = Side(self.machine)+ link = self.start(side)+ self.assertTrue(wait_for(lambda: side.ups), side.states)+ fields = side.ups[0]+ self.assertEqual(fields["id"], HERE)+ self.assertTrue(fields["accepts"])+ self.assertEqual(fields["platform"], "windows")+ self.assertIn("clipboard", fields["caps"])+ self.assertTrue(link.live())+ self.assertTrue(side.peer()["linked"])+ self.assertEqual(side.peer()["name"], "Here")+ self.assertEqual(link.peer_id, protocol.id_text(HERE))+ self.assertTrue(wait_for(lambda: self.machine.links))++ def test_accepts_is_false_when_the_peer_does_not_let_this_machine_drive(self):+ self.machine.settings.peer(TOKENS[B])["allow_drive"] = False+ side = Side(self.machine)+ self.start(side)+ self.assertTrue(wait_for(lambda: side.ups), side.states)+ self.assertFalse(side.ups[0]["accepts"])++ def test_a_different_id_than_the_entry_has_is_refused_and_taught_nothing(self):+ side = Side(self.machine, peer=ident_other())+ self.start(side)+ self.assertTrue(wait_for(lambda: side.states and not side.states[-1][0]), side.states)+ self.assertEqual(side.ups, [])+ self.assertIn("different Beamer", side.last_text())++ def test_a_typed_token_is_never_dialled(self):+ side = Side(self.machine, token="hunter2")+ link = self.start(side)+ time.sleep(0.4)+ self.assertEqual(self.machine.links, [])+ self.assertFalse(link.live())++ def test_a_migrated_entry_is_never_dialled_whatever_its_token(self):+ for fields in ({"linked": False, "id": ""}, {"linked": True}):+ with self.subTest(fields=fields):+ side = Side(self.machine, from_1_4=True)+ side.peer().update(fields)+ now = [1000.0]+ link = self.start(side, clock=lambda: now[0])+ time.sleep(0.4)+ self.assertEqual(self.machine.links, [])+ self.assertFalse(link.live())+ now[0] += 60+ link.follow([{"name": "Far", "address": "127.0.0.2"}])+ self.assertIsNone(link._try_host)+ link.stop()++ def test_send_off_is_not_dialled(self):+ side = Side(self.machine)+ side.peer()["send"] = False+ self.start(side)+ time.sleep(0.3)+ self.assertEqual(self.machine.links, [])+++ def test_a_peer_that_does_not_know_the_key_id_closes_and_the_text_follows_linked(self):+ for linked, expected in ((False, "Update Beamer on Far to 1.5.0"), (True, "closed the connection")):+ side = Side(self.machine, token=other_token(), linked=linked)+ link = self.start(side)+ self.assertTrue(wait_for(lambda: side.states and not side.states[-1][0]), side.states)+ self.assertIn(expected, side.last_text())+ link.stop()++ def test_an_entry_removed_stops_the_link(self):+ side = Side(self.machine)+ link = self.start(side)+ self.assertTrue(wait_for(lambda: side.ups))+ side.settings.data["peers"].clear()+ self.assertTrue(wait_for(lambda: not link.live() and not link.running, 5.0))++ def test_one_failed_read_of_the_settings_does_not_end_the_link(self):+ side = Side(self.machine)+ reads = []+ load = side.settings.load++ def flaky():+ reads.append(1)+ if len(reads) == 1:+ raise PermissionError("settings.json is locked")+ return load()++ side.book = receiver.PeerBook(flaky, side.settings.save)+ link = self.start(side)+ self.assertTrue(wait_for(lambda: side.ups, 5.0), side.states)+ self.assertTrue(link.running)+++def ident_other():+ return bytes((200 + i) % 256 for i in range(1, 17))+++def other_token():+ import base64+ return base64.urlsafe_b64encode(bytes((9 + i) % 256 for i in range(32))).decode("ascii").rstrip("=")+++class LinkRefusalTests(unittest.TestCase):+ def serve(self, script):+ server = Scripted(script)+ self.addCleanup(server.stop)+ return server++ def link(self, side, **kwargs):+ link = side.link(**kwargs)+ self.addCleanup(link.stop)+ link.start()+ return link++ def test_a_version_5_peer_is_named_as_older(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"BEAMY\x05" + bytes(8))+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states), side.states)+ self.assertIn("Update Beamer on Far: it is older than this one", side.last_text())++ def test_two_machines_of_one_name_are_told_apart_in_what_the_link_says(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"BEAMY\x05" + bytes(8))+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ side.peer()["name"] = "Studio"+ twin = entry(C, "studio", token=TOKENS[C], host="192.0.2.9", port=24820, send=True)+ side.settings.data["peers"].append(twin)+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states), side.states)+ self.assertIn(f"Update Beamer on Studio ({protocol.id_text(HERE)[-4:]}): it is older than this one", side.last_text())++ def test_a_newer_peer_says_this_machine_is_older(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"BEAMY\x07" + bytes(8))+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("newer Beamer", side.last_text())++ def test_a_peer_that_is_not_a_beamer_is_said_to_be_one_from_before_version_4(self):+ def script(connection):+ connection.recv(62)+ time.sleep(6)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states, 8.0), side.states)+ self.assertIn("before version 4", side.last_text())++ def test_a_peer_that_answers_with_something_else_is_said_not_to_be_a_beamer(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"HTTP/1.1 400 Bad Request\r\n\r\n")+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states), side.states)+ self.assertEqual(side.last_text(), "Far did not answer as a Beamer")++ def test_a_responder_that_names_another_key_id_is_a_different_beamer(self):+ def script(connection):+ connection.recv(62)+ connection.sendall(b"BEAMY\x06" + bytes(8) + bytes(16) + bytes(32))+ time.sleep(0.5)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("different Beamer", side.last_text())++ def test_wrong_id_stops_dialling_until_the_entry_changes(self):+ def script(connection):+ session, _ = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.wrong_id_v6())+ time.sleep(0.3)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ link = self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("under another machine: remove it on both and pair again", side.last_text())+ seen = server.connections+ time.sleep(0.5)+ self.assertEqual(server.connections, seen)+ side.peer()["host"] = "localhost"+ self.assertTrue(wait_for(lambda: server.connections > seen, 3.0))+ link.stop()+++ def closing_peer(self, **fields):++ """A peer that closes every handshake unanswered, dialled with a clock the test turns."""++ def script(connection):++ connection.recv(62)++++ server = self.serve(script)++ side = Side(None, **fields)++ side.peer()["port"] = server.port++ now = [1000.0]++ return server, side, now++++ def seen(self, side, count):++ return wait_for(lambda: len(side.states) >= count, 5.0)++++ def test_a_machine_that_closes_unanswered_for_a_minute_is_said_to_have_removed_this_one_and_dialled_slowly(self):++ # 06-10-2026: the lent laptop dialled the rig every two seconds on a pairing the rig no longer had.++ server, side, now = self.closing_peer(linked=True)++ self.link(side, clock=lambda: now[0])++ self.assertTrue(self.seen(side, 3), side.states)++ self.assertTrue(all("no longer has this pairing" not in text for _up, text in side.states))++ self.assertIn("may have removed this machine", side.states[0][1])++ now[0] += link_module.FORGOTTEN_AFTER_SECONDS++ self.assertTrue(wait_for(lambda: "no longer has this pairing" in (side.last_text() or ""), 5.0), side.states)++ self.assertEqual(side.last_text(), "Far no longer has this pairing: remove Far here and pair the two again")++ seen = server.connections++ time.sleep(0.5)++ self.assertEqual(server.connections, seen)++++ def test_a_peer_that_is_slow_to_answer_for_under_a_minute_is_never_said_to_have_removed_this_one(self):++ server, side, now = self.closing_peer(linked=True)++ self.link(side, clock=lambda: now[0])++ self.assertTrue(self.seen(side, 2), side.states)++ now[0] += link_module.FORGOTTEN_AFTER_SECONDS - 1++ before = len(side.states)++ self.assertTrue(self.seen(side, before + 3), side.states)++ self.assertTrue(all("no longer has this pairing" not in text for _up, text in side.states))++++ def test_any_other_result_starts_the_minute_again(self):++ server, side, now = self.closing_peer(linked=True)++ refuse = [False]++++ def factory(address, timeout):++ if refuse[0]:++ raise ConnectionRefusedError(errno.ECONNREFUSED, "refused")++ return socket.create_connection(address, timeout=timeout)++++ self.link(side, clock=lambda: now[0], socket_factory=factory)++ self.assertTrue(self.seen(side, 2), side.states)++ now[0] += link_module.FORGOTTEN_AFTER_SECONDS - 1++ refuse[0] = True++ self.assertTrue(wait_for(lambda: side.states and side.states[-1][1].endswith("not listening on this port."), 5.0),++ side.states)++ refuse[0] = False++ now[0] += 5++ before = len(side.states)++ self.assertTrue(self.seen(side, before + 3), side.states)++ self.assertTrue(all("no longer has this pairing" not in text for _up, text in side.states))++++ def test_a_machine_never_linked_that_closes_unanswered_is_never_said_to_have_removed_this_one(self):++ server, side, now = self.closing_peer(linked=False)++ self.link(side, clock=lambda: now[0])++ self.assertTrue(self.seen(side, 2), side.states)++ now[0] += 10 * link_module.FORGOTTEN_AFTER_SECONDS++ before = len(side.states)++ self.assertTrue(self.seen(side, before + 2), side.states)++ self.assertTrue(all("no longer has this pairing" not in text for _up, text in side.states))+++ def test_invalid_hello_says_this_app_sent_something_unreadable(self):+ def script(connection):+ session, _ = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.invalid_hello_v6())+ time.sleep(0.3)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("could not read", side.last_text())++ def test_a_welcome_naming_this_machine_is_closed_with_nothing_taught(self):+ def script(connection):+ session, _ = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(B, "Me", "macos", "1.5.0", CAPS, True))+ time.sleep(0.3)++ server = self.serve(script)+ side = Side(None)+ side.peer()["port"] = server.port+ side.peer()["id"] = ""+ self.link(side)+ self.assertTrue(wait_for(lambda: side.states))+ self.assertIn("different Beamer", side.last_text())+ self.assertEqual(side.peer()["id"], "")+ self.assertEqual(side.ups, [])+++class LinkLiveTests(unittest.TestCase):+ def setUp(self):+ self.machine = machine_with_peer()+ self.addCleanup(self.machine.stop)+ self.side = Side(self.machine)+ self.link = self.side.link()+ self.addCleanup(self.link.stop)+ self.link.start()+ self.assertTrue(wait_for(lambda: self.side.ups), self.side.states)++ def take(self, route=1):+ self.assertTrue(self.link.post(protocol.focus_v6(route, HERE, resistance_px=120, reach=[])))+ self.assertTrue(wait_for(lambda: any(m["type"] == protocol.MSG_ACCEPT for m in self.side.messages)), self.side.messages)++ def test_send_input_numbers_from_one_and_the_responder_injects_for_its_owner(self):+ self.take()+ self.assertTrue(self.link.send_input(protocol.key_msg("keydown", "a")))+ self.assertTrue(self.link.send_input(protocol.mousemove_msg(3, 4)))+ self.assertTrue(wait_for(lambda: ("move", 3, 4) in self.machine.injected()))+ self.assertIn(("key", "a", True), self.machine.injected())+ self.assertEqual(self.link.last_sent_seq, 2)++ def test_acks_give_round_trip_samples_that_are_never_negative(self):+ self.take()+ for _ in range(5):+ self.link.send_input(protocol.mousemove_msg(1, 1))+ time.sleep(0.03)+ self.assertTrue(wait_for(lambda: self.link.round_trips()), "no round trip measured")+ self.assertTrue(all(sample >= 0 for sample in self.link.round_trips()))+ self.assertIsNotNone(self.link.last_ack_at)++ def test_inbound_messages_other_than_acks_reach_the_callback(self):+ self.link.post(protocol.focus_v6(1, HERE, resistance_px=120, reach=[]))+ self.assertTrue(wait_for(lambda: self.side.messages))+ self.assertEqual(self.side.messages[0]["type"], protocol.MSG_ACCEPT)+ self.assertNotIn(protocol.MSG_ACK, [m["type"] for m in self.side.messages])++ def test_a_clipboard_is_dropped_when_the_peer_lacks_the_capability(self):+ self.link._caps = frozenset()+ self.assertTrue(self.link.post(protocol.clipboard_msg("hello")))+ time.sleep(0.2)+ self.assertEqual(self.machine.clipboard.set_calls, [])++ def test_settings_are_not_sent_to_a_peer_without_the_capability(self):+ self.link._caps = frozenset()+ self.assertTrue(self.link.post(protocol.settings_msg({"a": 1})))+ time.sleep(0.2)+ self.assertEqual(self.machine.settings_seen, [])++ def test_the_link_reconnects_after_the_responder_closes_it(self):+ first = len(self.side.ups)+ self.machine.responder.peers_changed()+ self.side.peer()["linked"] = True+ for link in list(self.machine.responder._links.values()):+ link.close()+ self.assertTrue(wait_for(lambda: len(self.side.ups) > first, 5.0), self.side.states)++ def test_stop_ends_the_link_and_the_responder_sees_it_go(self):+ self.link.stop()+ self.assertTrue(wait_for(lambda: (protocol_id(B), False) in self.machine.links))+ self.assertFalse(self.link.live())++ def test_a_full_queue_reports_failure(self):+ self.link._stall.set()+ results = [self.link.send_input(protocol.mousemove_msg(1, 1)) for _ in range(2100)]+ self.link._stall.clear()+ self.assertIn(False, results)+ self.assertEqual(results.count(True), 2048)+++def protocol_id(ident):+ return ident+++class LinkLivenessTests(unittest.TestCase):+ def test_a_silent_peer_ends_the_link_after_two_seconds(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ time.sleep(6)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ began = time.monotonic()+ self.assertTrue(wait_for(lambda: "stopped responding" in (side.last_text() or ""), 5.0), side.states)+ self.assertGreaterEqual(time.monotonic() - began, 1.5)+ self.assertFalse(link.live())++ def test_an_idle_link_pings_each_second(self):+ pings = []++ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ connection.settimeout(3)+ started = time.monotonic()+ while time.monotonic() - started < 2.6:+ try:+ message = protocol.recv_msg(connection, session)+ except OSError:+ return+ if message["type"] == protocol.MSG_PING:+ pings.append(message)+ protocol.send_msg(connection, session, protocol.ack_v6(0, 0))++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link()+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: len(pings) >= 2, 4.0), pings)++ def test_an_ack_ahead_of_anything_sent_ends_the_link(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ protocol.send_msg(connection, session, protocol.ack_v6(5, 0))+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ self.assertTrue(wait_for(lambda: not link.live(), 3.0))++ def test_an_ack_with_a_negative_held_us_ends_the_link(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ protocol.send_msg(connection, session, {"type": "ack", "data": {"seq": 0, "held_us": -1}})+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ self.assertTrue(wait_for(lambda: not link.live(), 3.0))++ def test_an_ack_that_says_locked_sets_peer_locked_until_one_that_does_not(self):+ cleared = threading.Event()++ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ protocol.send_msg(connection, session, protocol.ack_v6(0, 0, locked=True))+ cleared.wait(5)+ protocol.send_msg(connection, session, protocol.ack_v6(0, 0))+ time.sleep(2)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ self.assertTrue(wait_for(lambda: link.peer_locked), side.states)+ cleared.set()+ self.assertTrue(wait_for(lambda: not link.peer_locked), side.states)+ self.assertTrue(link.live())+++class FakeClock:+ def __init__(self):+ self.now = 1000.0++ def __call__(self):+ return self.now+++class LinkFollowTests(unittest.TestCase):+ def link(self, clock, tried):+ side = Side(None)+ side.peer()["host"] = "192.168.77.7"++ def factory(address, timeout=None):+ tried.append(address)+ raise OSError("no route")++ link = side.link(socket_factory=factory, clock=clock, reconnect_seconds=0.02)+ self.addCleanup(link.stop)+ return side, link++ def test_a_peer_not_in_use_has_no_dial_target(self):+ side, _link = self.link(FakeClock(), [])+ side.peer()["in_use"] = False+ self.assertIsNone(OutboundLink._target(side.peer()))++ def test_a_beacon_with_the_exact_name_is_tried_once_the_link_has_been_down_ten_seconds(self):+ clock, tried = FakeClock(), []+ side, link = self.link(clock, tried)+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ tried.clear()+ beacon = [{"name": "Far", "address": "192.168.77.9"}, {"name": "Other", "address": "192.168.77.10"}]+ link.follow(beacon)+ time.sleep(0.2)+ self.assertNotIn(("192.168.77.9", 24820), tried)+ clock.now += 11+ link.follow(beacon)+ self.assertTrue(wait_for(lambda: ("192.168.77.9", 24820) in tried), tried)+ self.assertNotIn(("192.168.77.10", 24820), tried)+ tried.clear()+ clock.now += 5+ link.follow(beacon)+ time.sleep(0.2)+ self.assertNotIn(("192.168.77.9", 24820), tried)+ clock.now += 30+ link.follow(beacon)+ self.assertTrue(wait_for(lambda: ("192.168.77.9", 24820) in tried), tried)++ def test_a_beacon_that_names_another_machine_is_never_tried_and_one_at_its_address_is_tried_last(self):+ clock, tried = FakeClock(), []+ side, link = self.link(clock, tried)+ side.settings.data["peers"].append(entry(C, "Far", token=TOKENS[C], host="192.168.77.20", port=24820, send=True))+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ beacons = [{"name": "Far", "address": "192.168.77.20"},+ {"name": "Far", "address": "192.168.77.21", "id": protocol.id_text(C)},+ {"name": "Far", "address": "192.168.77.22", "id": protocol.id_text(HERE)}]+ tried.clear()+ clock.now += 11+ link.follow(beacons)+ self.assertTrue(wait_for(lambda: ("192.168.77.22", 24820) in tried), tried)+ self.assertNotIn(("192.168.77.20", 24820), tried)+ # Two machines may have swapped addresses, so the other machine's saved one is still tried, last.+ clock.now += 31+ link.follow(beacons)+ self.assertTrue(wait_for(lambda: ("192.168.77.20", 24820) in tried), tried)+ self.assertNotIn(("192.168.77.21", 24820), tried)++ def test_several_beacons_with_the_name_are_tried_in_turn(self):+ clock, tried = FakeClock(), []+ side, link = self.link(clock, tried)+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ beacons = [{"name": "Far", "address": "192.168.77.9"}, {"name": "Far", "address": "192.168.77.10"}]+ for address in ("192.168.77.9", "192.168.77.10", "192.168.77.9"):+ tried.clear()+ clock.now += 31+ link.follow(beacons)+ self.assertTrue(wait_for(lambda: (address, 24820) in tried), (address, tried))++ def test_a_failed_try_shows_nothing_and_saves_nothing(self):+ clock, tried = FakeClock(), []+ side, link = self.link(clock, tried)+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ clock.now += 11+ link.follow([{"name": "Far", "address": "192.168.77.9"}])+ self.assertTrue(wait_for(lambda: ("192.168.77.9", 24820) in tried))+ self.assertEqual(side.peer()["host"], "192.168.77.7")++ def test_the_address_is_saved_once_the_link_authenticates_there(self):+ machine = machine_with_peer()+ self.addCleanup(machine.stop)+ clock = FakeClock()+ side = Side(machine)+ side.peer()["host"] = "10.255.255.1"++ real = socket.create_connection++ def factory(address, timeout=None):+ if address[0] == "10.255.255.1":+ raise OSError("no route")+ return real(address, timeout=timeout)++ link = side.link(socket_factory=factory, clock=clock)+ self.addCleanup(link.stop)+ link.start()+ time.sleep(0.2)+ clock.now += 11+ link.follow([{"name": "Far", "address": LOOPBACK}])+ self.assertTrue(wait_for(lambda: side.ups), side.states)+ self.assertEqual(side.peer()["host"], LOOPBACK)+++class LinkTunnelTests(unittest.TestCase):+ def test_an_unreachable_host_falls_back_to_the_tunnel(self):+ import errno+ machine = machine_with_peer()+ self.addCleanup(machine.stop)+ side = Side(machine)++ def factory(address, timeout=None):+ raise OSError(errno.EHOSTUNREACH, "no route")++ link = side.link(socket_factory=factory, tunnel=lambda: socket.create_connection((LOOPBACK, machine.port), timeout=1))+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups), side.states)+ self.assertTrue(link.via_tunnel)+++class LinkHeldTests(unittest.TestCase):+ def test_held_us_is_taken_off_the_sample_and_never_goes_below_zero(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ message = protocol.recv_msg(connection, session)+ while message["type"] == protocol.MSG_PING:+ message = protocol.recv_msg(connection, session)+ time.sleep(0.05)+ protocol.send_msg(connection, session, protocol.ack_v6(message["data"]["seq"], 5_000_000))+ time.sleep(0.5)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link()+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ link.send_input(protocol.mousemove_msg(1, 1))+ self.assertTrue(wait_for(lambda: link.round_trips()))+ self.assertEqual(link.round_trips(), [0.0])+++class LinkReviewFindingsTests(unittest.TestCase):+ """What the cold review of the first version found, each shown failing before it was fixed."""++ def test_an_ack_that_beats_the_writers_bookkeeping_does_not_end_the_link(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ connection.settimeout(5)+ while True:+ message = protocol.recv_msg(connection, session)+ seq = message["data"].get("seq")+ if seq:+ protocol.send_msg(connection, session, protocol.ack_v6(seq, 0))++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port++ def slow_clock():+ time.sleep(0.003)+ return time.monotonic()++ link = side.link(clock=slow_clock)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ for _ in range(30):+ self.assertTrue(link.send_input(protocol.mousemove_msg(1, 1)))+ time.sleep(0.01)+ time.sleep(0.3)+ self.assertTrue(link.live(), side.states)++ def test_stop_during_a_handshake_ends_the_thread_and_start_runs_it_again(self):+ def script(connection):+ time.sleep(6)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=0.05)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: server.connections))+ began = time.monotonic()+ link.stop()+ self.assertLess(time.monotonic() - began, 1.0)+ self.assertFalse(link.running)+ before = server.connections+ link.start()+ self.assertTrue(wait_for(lambda: server.connections > before), "the link did not dial again")++ def test_stop_without_waiting_returns_at_once_reports_nothing_after_and_start_runs_it_again(self):+ # A window removing machines must not wait on a link thread that is in a handshake.+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ time.sleep(0.5)+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link()+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: server.connections))+ time.sleep(0.1)+ began = time.monotonic()+ link.stop(wait=False)+ self.assertLess(time.monotonic() - began, 0.05)+ states, ups = list(side.states), list(side.ups)+ time.sleep(1.2)+ self.assertEqual((side.states, side.ups), (states, ups))+ self.assertFalse(link.running)+ before = server.connections+ link.start()+ self.assertTrue(wait_for(lambda: server.connections > before), "the link did not dial again")++ def test_nothing_is_reported_after_stop_returns(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ time.sleep(0.8)+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link()+ link.start()+ self.assertTrue(wait_for(lambda: server.connections))+ time.sleep(0.2)+ link.stop()+ states, ups, saved = list(side.states), list(side.ups), side.settings.saves+ time.sleep(1.5)+ self.assertEqual((side.states, side.ups, side.settings.saves), (states, ups, saved))++ def test_a_failed_try_at_a_beacons_address_shows_nothing_and_blocks_nothing(self):+ def script(connection):+ connection.close()++ server = Scripted(script)+ self.addCleanup(server.stop)+ clock = FakeClock()+ side = Side(None)+ side.peer()["host"] = "10.255.255.1"+ side.peer()["port"] = server.port+ real = socket.create_connection++ def factory(address, timeout=None):+ if address[0] == "10.255.255.1":+ raise OSError("no route")+ return real(address, timeout=timeout)++ link = side.link(socket_factory=factory, clock=clock)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.states))+ clock.now += 11+ shown = list(side.states)+ link.follow([{"name": "Far", "address": LOOPBACK}])+ self.assertTrue(wait_for(lambda: server.connections))+ time.sleep(0.3)+ self.assertEqual(side.states[: len(shown)], shown)+ self.assertFalse(any("closed the connection" in text for _, text in side.states[len(shown):]))++ def test_a_try_never_dials_a_peer_with_send_off(self):+ tried = []++ def factory(address, timeout=None):+ tried.append(address)+ raise OSError("no route")++ clock = FakeClock()+ side = Side(None)+ link = side.link(socket_factory=factory, clock=clock, reconnect_seconds=0.02)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: tried))+ clock.now += 11+ side.peer()["send"] = False+ link._try_host = "192.168.77.9"+ link._wake.set()+ tried.clear()+ time.sleep(0.4)+ self.assertEqual(tried, [])++ def test_a_peer_that_stops_reading_ends_the_link(self):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ for _ in range(60):+ protocol.send_msg(connection, session, protocol.ack_v6(0, 0))+ time.sleep(0.2)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ big = protocol.clipboard_msg("x" * 200_000)+ for _ in range(100):+ if not link.post(big):+ break+ self.assertTrue(wait_for(lambda: not link.live(), 8.0), "a wedged writer kept the link up")++ def test_only_one_ping_waits_in_the_queue(self):+ side = Side(None)+ link = side.link()+ link._live = True+ link._sock = object()+ for _ in range(20):+ link._tick_ping()+ self.assertEqual(sum(1 for m in link._outbox if m["type"] == protocol.MSG_PING), 1)++ def test_send_input_takes_only_input_and_filters_media_keys(self):+ side = Side(None)+ link = side.link()+ link._live = True+ link._sock = object()+ link._caps = frozenset()+ self.assertFalse(link.send_input(protocol.settings_msg({})))+ self.assertTrue(link.send_input(protocol.key_msg("keydown", "volume_up")))+ self.assertEqual(len(link._outbox), 0)+ link._caps = frozenset({"media_keys"})+ self.assertTrue(link.send_input(protocol.key_msg("keydown", "volume_up")))+ self.assertEqual(len(link._outbox), 1)++ def test_flush_waits_for_the_queue_to_be_written(self):+ machine = machine_with_peer()+ self.addCleanup(machine.stop)+ side = Side(machine)+ link = side.link()+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ link.post(protocol.focus_v6(1, HERE, resistance_px=120, reach=[]))+ link.flush(2.0)+ self.assertEqual(len(link._outbox), 0)+ self.assertTrue(wait_for(lambda: machine.responder.owner == B))++ def test_peer_locked_is_forgotten_on_a_new_link(self):+ side = Side(None)+ link = side.link()+ link._locked = True+ link._live = True+ self.assertTrue(link.peer_locked)+ link._reset_link_state()+ self.assertFalse(link.peer_locked)+++class LinkFramingTests(unittest.TestCase):+ def serve(self, after_welcome):+ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ after_welcome(connection, session)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: side.ups))+ return side, link++ def test_a_frame_that_arrives_a_byte_at_a_time_is_one_message(self):+ def after(connection, session):+ frame = session.seal(protocol.accept_msg(3))+ for index in range(len(frame)):+ connection.sendall(frame[index:index + 1])+ time.sleep(0.002)+ time.sleep(1)++ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: side.messages), side.states)+ self.assertEqual(side.messages[0]["data"]["route"], 3)++ def test_a_frame_that_takes_longer_than_its_deadline_from_its_first_byte_ends_the_link(self):+ # A byte every tenth of a second keeps the link alive, so only the frame's own deadline,+ # counted from its first length byte, can end it.+ def after(connection, session):+ connection.sendall(struct.pack(">I", 1000))+ for _ in range(40):+ connection.sendall(b"\x00")+ time.sleep(0.1)++ with mock.patch.object(protocol, "FRAME_COMPLETE_SECONDS", 0.8):+ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: side.states and not side.states[-1][0], 3.0), side.states)+ self.assertIn("too long", side.last_text())+ self.assertEqual(side.messages, [])++ def test_a_frame_completed_after_its_deadline_is_not_dispatched(self):+ class Socket:+ def __init__(self, chunks):+ self.chunks = iter(chunks)++ def recv(self, size):+ return next(self.chunks)++ frame = struct.pack(">I", protocol.MIN_FRAME_BYTES) + bytes(protocol.MIN_FRAME_BYTES)+ sock = Socket((frame[:1], frame[1:], b""))+ times = iter((-1.0, 0.0, 0.25))+ link = OutboundLink("", None, lambda: {}, clock=lambda: next(times, 0.3))+ link._sock = sock+ session = mock.Mock()+ session.open_raw.return_value = b"{}"+ with mock.patch.object(protocol, "FRAME_COMPLETE_SECONDS", 0.2):+ with mock.patch.object(protocol, "parse_message", return_value={"type": "accept", "data": {}}):+ with mock.patch.object(link, "_deal") as deal:+ with self.assertRaisesRegex(link_module.LinkEnded, "took too long to send one message"):+ link._read(sock, session, "peer")+ deal.assert_not_called()++ def test_two_frames_in_one_segment_are_two_messages(self):+ def after(connection, session):+ connection.sendall(session.seal(protocol.accept_msg(3)) + session.seal(protocol.accept_msg(4)))+ time.sleep(1)++ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: len(side.messages) == 2))++ def big(self, allowed):+ """A frame past SMALL_MESSAGE_BYTES, then a small one, to a link whose `large` hook says+ `allowed`; what the link hands on, once the small one is through."""+ parsed = []+ real_parse = protocol.parse_message+ filler = {"type": protocol.MSG_CLIPBOARD, "data": {"text": "x" * (protocol.SMALL_MESSAGE_BYTES + 10)}}++ def after(connection, session):+ connection.sendall(session.seal(filler) + session.seal(protocol.accept_msg(3)))+ time.sleep(1)++ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ after(connection, session)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side = Side(None)+ side.peer()["port"] = server.port+ asked = []+ link = side.link(reconnect_seconds=30, large=lambda link_, began: asked.append((link_, began)) or allowed)+ self.addCleanup(link.stop)+ with mock.patch.object(protocol, "parse_message", side_effect=lambda plain: parsed.append(len(plain)) or real_parse(plain)):+ link.start()+ self.assertTrue(wait_for(lambda: any(m.get("type") == protocol.MSG_ACCEPT for m in side.messages)), side.states)+ self.assertEqual([who for who, _ in asked], [link])+ self.assertIsInstance(asked[0][1], float)+ self.assertTrue(link.live())+ return side, parsed++ def test_a_frame_too_large_for_anything_but_a_clipboard_is_never_parsed_unless_one_is_expected(self):+ side, parsed = self.big(False)+ self.assertEqual([m["type"] for m in side.messages], [protocol.MSG_ACCEPT])+ self.assertTrue(all(size <= protocol.SMALL_MESSAGE_BYTES for size in parsed), parsed)++ def test_an_expected_clipboard_of_any_size_is_handed_on(self):+ side, parsed = self.big(True)+ self.assertEqual([m["type"] for m in side.messages], [protocol.MSG_CLIPBOARD, protocol.MSG_ACCEPT])++ def test_a_frame_claiming_more_than_the_maximum_ends_the_link(self):+ def after(connection, session):+ connection.sendall((protocol.MAX_FRAME_BYTES + 1).to_bytes(4, "big"))+ time.sleep(1)++ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: not link.live(), 3.0))++ def test_a_replayed_frame_ends_the_link(self):+ def after(connection, session):+ frame = session.seal(protocol.accept_msg(3))+ connection.sendall(frame + frame)+ time.sleep(1)++ side, link = self.serve(after)+ self.assertTrue(wait_for(lambda: not link.live(), 3.0))+ self.assertEqual(len(side.messages), 1)+++class GeminiFindingsTests(unittest.TestCase):+ def test_a_link_that_is_down_refuses_what_its_capabilities_would_have_dropped(self):+ side = Side(None)+ link = side.link()+ self.assertFalse(link.post(protocol.clipboard_msg("x")))+ self.assertFalse(link.post(protocol.settings_msg({})))+ self.assertFalse(link.send_input(protocol.gesture_msg("pinch")))++ def test_a_drop_reason_is_forgotten_with_the_link(self):+ side = Side(None)+ link = side.link()+ link._drop_reason = "stale"+ link._reset_link_state()+ self.assertIsNone(link._drop_reason)++ def test_a_peer_that_never_acknowledges_cannot_grow_the_send_record_without_end(self):+ side = Side(None)+ link = side.link()+ link._live = True+ link._sock = object()+ for index in range(link_module.SENT_RECORD_LIMIT + 1):+ link._sent_at.append((index, 0.0))+ with self.assertRaises(protocol.ProtocolError):+ link._check_sent_record()+++class RoundTripLogTests(unittest.TestCase):+ """Section 9: every 60 seconds while input is on the link, the count, median, 95th percentile,+ largest and mean held_us of the round trips measured since the last line."""++ def setUp(self):+ self.now = [100.0]+ self.side = Side(None)+ self.link = self.side.link(clock=lambda: self.now[0])+ self.link.peer_name = "Far"+ self.link._logged_at = 100.0++ def acks(self, count, held_us=1000):+ self.link._written_seq = count+ for seq in range(1, count + 1):+ self.link._sent_at.append((seq, 100.0))+ self.now[0] = 100.2+ for seq in range(1, count + 1):+ self.link._ack({"seq": seq, "held_us": held_us * seq, "locked": False})++ def test_the_minute_gives_count_median_95th_percentile_largest_and_mean_held(self):+ self.acks(20)+ with self.assertLogs("Beamer", "INFO") as logged:+ self.now[0] = 160.1+ self.link._tick(160.1)+ text = logged.output[-1]+ self.assertIn("round trip to Far", text)+ self.assertIn("20 samples", text)+ for word in ("median", "95th percentile", "largest", "mean held_us 10500"):+ self.assertIn(word, text)++ def test_a_minute_without_input_logs_nothing(self):+ with self.assertNoLogs("Beamer", "INFO"):+ self.now[0] = 160.1+ self.link._tick(160.1)++ def test_what_was_logged_is_not_counted_again(self):+ self.acks(5)+ self.now[0] = 160.1+ self.link._tick(160.1)+ with self.assertNoLogs("Beamer", "INFO"):+ self.now[0] = 220.2+ self.link._tick(220.2)+++class LinkHardwareTests(unittest.TestCase):+ """`hw` in the hello is the address on the interface towards the host this link dials."""++ def hello_of(self, side, **kwargs):+ seen = []++ def script(connection):+ session, hello = scripted_session(connection, TOKENS[B])+ seen.append(hello)+ protocol.send_msg(connection, session, protocol.welcome_v6(HERE, "Here", "windows", "1.5.0", CAPS, True))+ time.sleep(1)++ server = Scripted(script)+ self.addCleanup(server.stop)+ side.peer()["port"] = server.port+ link = side.link(reconnect_seconds=30, **kwargs)+ self.addCleanup(link.stop)+ link.start()+ self.assertTrue(wait_for(lambda: seen), side.states)+ return seen[0]++ def test_the_hook_is_asked_with_the_host_this_link_dials(self):+ asked = []+ side = Side(None)+ hello = self.hello_of(side, hardware=lambda host: asked.append(host) or "aa:bb:cc:dd:ee:01")+ self.assertEqual(asked, [LOOPBACK])+ self.assertEqual(hello["hw"], "aa:bb:cc:dd:ee:01")++ def test_the_hook_wins_over_the_identitys_own_hw(self):+ side = Side(None)+ side.identity = lambda: {"id": B, "name": "Near", "platform": "macos", "app": "1.5.0", "caps": list(CAPS),+ "port": 24820, "hw": "11:11:11:11:11:11"}+ hello = self.hello_of(side, hardware=lambda host: "aa:bb:cc:dd:ee:02")+ self.assertEqual(hello["hw"], "aa:bb:cc:dd:ee:02")++ def test_without_a_hook_the_identitys_hw_is_sent_as_before(self):+ side = Side(None)+ side.identity = lambda: {"id": B, "name": "Near", "platform": "macos", "app": "1.5.0", "caps": list(CAPS),+ "port": 24820, "hw": "11:11:11:11:11:11"}+ self.assertEqual(self.hello_of(side)["hw"], "11:11:11:11:11:11")++ def test_a_hook_that_raises_sends_no_hw_and_the_link_still_comes_up(self):+ def broken(host):+ raise OSError("no adapter table")++ side = Side(None)+ hello = self.hello_of(side, hardware=broken)+ self.assertIsNone(hello["hw"])+ self.assertTrue(wait_for(lambda: side.ups), side.states)++ def test_a_hook_that_knows_nothing_sends_no_hw(self):+ side = Side(None)+ self.assertIsNone(self.hello_of(side, hardware=lambda host: "")["hw"])+++if __name__ == "__main__":+ unittest.main()diff --cc core/tests/test_ways.pyindex 40a2490,0000000..7d81f3dmode 100644,000000..100644--- a/core/tests/test_ways.py+++ b/core/tests/test_ways.py@@@ -1,587 -1,0 +1,737 @@@+"""core/ways.py: a machine's zones read and written one peer at a time, the side settled with each+peer, the machine the shortcut picks, and the pairings a zone needs (WIRE.md sections 5 and 8)."""++import unittest++from core import protocol, ways++HERE = protocol.id_text(bytes(range(1, 17)))+A = protocol.id_text(bytes(range(20, 36)))+B = protocol.id_text(bytes(range(40, 56)))+C = protocol.id_text(bytes(range(60, 76)))+PHONE = protocol.id_text(bytes(range(80, 96)))+++def peer(ident, name, **fields):+ data = {"id": ident, "name": name, "platform": "windows", "host": "10.9.9.9", "port": 24820, "hw": "",+ "send": True, "allow_drive": True, "side": "", "side_set_at": 0, "side_by": "", "paired_with": [],+ "paired_at": 1, "linked": True, "from_1_4": False, "token": "k" + ident}+ data.update(fields)+ return data+++def settings(*peers, zones=()):+ return {"machine_id": HERE, "shortcut": True, "peers": list(peers), "zones": list(zones)}+++def mac_corner_edge(corner, side):+ return corner.split("_")[1]+++def pc_corner_edge(corner, side):+ return side if side in ways.EDGES else corner.split("_")[1]+++MAC = ("edge", "part", "corner", "notch")+PC = ("edge", "part", "corner")+++class ReadingOnePeer(unittest.TestCase):+ def test_a_peer_with_no_zones_reads_as_nothing_in_use_and_the_defaults(self):+ found = ways.ways(settings(peer(A, "Ay", side="left")), A)+ self.assertEqual(found, {"side": "left", "methods": [], "parts": ["middle"], "corner": "top_left"})++ def test_only_that_peers_zones_in_use_count(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="right"), zones=[+ {"peer": A, "kind": "edge"},+ {"peer": A, "kind": "corner", "corner": "bottom_left", "edge": "left", "off": True},+ {"peer": B, "kind": "part", "parts": ["start", "end"]},+ {"peer": B, "kind": "corner", "corner": "top_right", "edge": "right"},+ ])+ self.assertEqual(ways.ways(held, A), {"side": "left", "methods": ["edge"], "parts": ["middle"], "corner": "bottom_left"})+ self.assertEqual(ways.ways(held, B), {"side": "right", "methods": ["part", "corner"], "parts": ["start", "end"],+ "corner": "top_right"})++ def test_an_unknown_peer_reads_as_nothing(self):+ self.assertEqual(ways.ways(settings(), A)["methods"], [])+++class JumpKeys(unittest.TestCase):+ def test_changing_trigger_rejects_keys_used_in_an_existing_jump_chord(self):+ held = settings(peer(A, "Ay", jump_key="ctrl+shift+f13"))+ for trigger in ("ctrl", "ctrl_r", "shift_r", "f13"):+ with self.subTest(trigger=trigger), self.assertRaises(ValueError):+ ways.check_trigger_key(held, trigger)+ ways.check_trigger_key(held, "alt_r")++ def test_missing_jump_key_is_none(self):+ self.assertIsNone(ways.jump_key(peer(A, "Ay")))++ def test_trigger_key_cannot_be_recorded_as_a_jump_key(self):+ held = settings(peer(A, "Ay"))+ with self.assertRaisesRegex(ValueError, "trigger"):+ ways.check_jump_key(held, A, "ctrl+f9", "f9")++ def test_a_chord_with_the_trigger_key_or_its_modifier_is_refused(self):+ # A chord holding the trigger's modifier would start its double-tap or hold, and leave the+ # modifier held here once input had jumped away.+ held = settings(peer(A, "Ay"))+ for value, trigger in (("ctrl+f9", "f9"), ("ctrl+alt+2", "alt_r"), ("alt+2", "alt_r")):+ with self.subTest(value=value), self.assertRaisesRegex(ValueError, "trigger"):+ ways.check_jump_key(held, A, value, trigger)+ self.assertEqual(ways.check_jump_key(held, A, "ctrl+cmd+2", "alt_r"), "ctrl+cmd+2")++ def test_space_is_recorded_by_its_name_not_as_a_blank(self):+ self.assertFalse(ways.valid_jump_key("cmd+ "))+ self.assertEqual(ways.jump_chord(["cmd"], "space"), "cmd+space")++ def test_shift_alone_is_not_enough_because_it_would_swallow_typing(self):+ for value in ("shift+a", "shift+2"):+ with self.subTest(value=value), self.assertRaises(ValueError):+ ways.check_jump_key(settings(peer(A, "Ay")), A, value, "alt_r")+ self.assertEqual(ways.jump_chord(["shift"], "a"), None)++ def test_bare_modifiers_and_unrecognised_words_are_not_jump_chords(self):+ for value in ("ctrl", "nonsense+2", "shift+ctrl+2"):+ with self.subTest(value=value), self.assertRaises(ValueError):+ ways.check_jump_key(settings(peer(A, "Ay")), A, value, "alt_r")+ with self.assertRaises(ValueError):+ ways.check_jump_key(settings(peer(A, "Ay")), A, 2, "alt_r")++ def test_shifted_printable_keys_and_plus_have_stable_chords(self):+ self.assertEqual(ways.jump_chord(["ctrl", "shift"], "@"), "ctrl+shift+@")+ self.assertEqual(ways.jump_chord(["ctrl"], "+"), "ctrl+plus")+ self.assertEqual(ways.jump_chord(["ctrl_r"], "2"), "ctrl+2")++ def test_another_peers_jump_key_cannot_be_reused(self):+ held = settings(peer(A, "Ay", jump_key="ctrl+shift+2"), peer(B, "Bee"))+ with self.assertRaisesRegex(ValueError, "already"):+ ways.check_jump_key(held, B, "ctrl+shift+2", "alt_r")++ def test_clearing_a_jump_key_removes_it(self):+ entry = peer(A, "Ay", jump_key="ctrl+shift+2")+ self.assertIsNone(ways.check_jump_key(settings(entry), A, "", "alt_r"))++ def test_a_chord_finds_its_in_use_machine(self):+ held = settings(peer(A, "Ay", jump_key="ctrl+shift+2"), peer(B, "Bee", jump_key="ctrl+shift+3"))+ self.assertEqual(ways.jump_peer(held["peers"], "ctrl+shift+3"), B)++ def test_a_not_in_use_machines_jump_key_is_ignored(self):+ held = settings(peer(A, "Ay", jump_key="ctrl+shift+2", in_use=False))+ self.assertIsNone(ways.jump_peer(held["peers"], "ctrl+shift+2"))+++class WritingOnePeer(unittest.TestCase):+ def test_one_zone_of_each_kind_is_written_for_that_peer_and_the_others_are_left_alone(self):+ other = {"peer": B, "kind": "edge"}+ held = settings(peer(A, "Ay"), peer(B, "Bee", side="right"), zones=[other])+ changed = ways.edit(held, A, side="left", methods=["corner"], parts=["start"], corner="top_left",+ kinds=MAC, corner_edge=mac_corner_edge, now=1000)+ self.assertTrue(changed)+ mine = [zone for zone in held["zones"] if zone["peer"] == A]+ self.assertEqual(sorted(zone["kind"] for zone in mine), sorted(MAC))+ self.assertEqual({zone["kind"] for zone in mine if not zone.get("off")}, {"corner"})+ self.assertEqual(next(zone for zone in mine if zone["kind"] == "corner")["edge"], "left")+ self.assertIn(other, held["zones"])+ self.assertEqual(held["peers"][1]["side"], "right")++ def test_a_new_side_is_stamped_by_this_machine_and_never_below_the_last_stamp(self):+ held = settings(peer(A, "Ay", side="right", side_set_at=5000, side_by=A))+ self.assertTrue(ways.edit(held, A, side="top", methods=["edge"], parts=["middle"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=100))+ entry = held["peers"][0]+ self.assertEqual((entry["side"], entry["side_set_at"], entry["side_by"]), ("top", 5001, HERE))++ def test_an_unchanged_side_keeps_its_stamp_and_says_so(self):+ held = settings(peer(A, "Ay", side="right", side_set_at=5000, side_by=A))+ self.assertFalse(ways.edit(held, A, side="right", methods=["part"], parts=["end"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=9000))+ self.assertEqual((held["peers"][0]["side_set_at"], held["peers"][0]["side_by"]), (5000, A))++ def test_the_pc_corner_crosses_the_side(self):+ held = settings(peer(A, "Ay"))+ ways.edit(held, A, side="top", methods=["corner"], parts=["middle"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=1)+ corner = next(zone for zone in held["zones"] if zone["kind"] == "corner")+ self.assertEqual(corner["edge"], "top")++ def test_edge_and_its_thirds_both_on_write_the_thirds_off(self):+ held = settings(peer(A, "Ay"))+ ways.edit(held, A, side="left", methods=["edge", "part"], parts=["start"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=1)+ self.assertEqual(ways.ways(held, A)["methods"], ["edge"])++ def test_an_unknown_peer_raises(self):+ with self.assertRaises(KeyError):+ ways.edit(settings(), A, side="left", methods=[], parts=["middle"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=1)++ def test_a_zone_the_user_kept_keeps_its_other_fields(self):+ held = settings(peer(A, "Ay", side="left"), zones=[{"peer": A, "kind": "edge", "off": True, "later": 1}])+ ways.edit(held, A, side="left", methods=["edge"], parts=["middle"], corner="top_left",+ kinds=PC, corner_edge=pc_corner_edge, now=1)+ self.assertEqual([zone for zone in held["zones"] if zone["kind"] == "edge"], [{"peer": A, "kind": "edge", "later": 1}])+++class Clashes(unittest.TestCase):+ def test_two_machines_on_one_whole_edge_clash_and_the_sentence_names_both(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])+ self.assertEqual(ways.clash(held, "this Mac"),+ "Ay and Bee would both lead from the right edge of this Mac. Move one of them to another "+ "side, or give each its own thirds of the edge.")++ def test_two_machines_on_different_thirds_of_one_edge_do_not_clash(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"), zones=[+ {"peer": A, "kind": "part", "parts": ["start"]}, {"peer": B, "kind": "part", "parts": ["middle", "end"]}])+ self.assertIsNone(ways.clash(held, "this PC"))++ def test_a_corner_inside_another_machines_edge_does_not_clash(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="top"), zones=[+ {"peer": A, "kind": "edge"}, {"peer": B, "kind": "corner", "corner": "top_right", "edge": "top"}])+ self.assertIsNone(ways.clash(held, "this PC"))++ def test_one_corner_for_two_machines_clashes(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="top"), zones=[+ {"peer": A, "kind": "corner", "corner": "top_right", "edge": "right"},+ {"peer": B, "kind": "corner", "corner": "top_right", "edge": "top"}])+ self.assertEqual(ways.clash(held, "this PC"),+ "Ay and Bee would both lead from the top right corner of this PC. Choose another corner "+ "for one of them.")++ def test_one_notch_for_two_machines_clashes(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="top"), zones=[+ {"peer": A, "kind": "notch"}, {"peer": B, "kind": "notch"}])+ self.assertEqual(ways.clash(held, "this Mac"),+ "Ay and Bee would both lead from the notch of this Mac. Turn the notch off for one of them.")++ def test_two_of_one_machines_own_zones_over_one_stretch_clash(self):+ held = settings(peer(A, "Ay", side="right"), zones=[+ {"peer": A, "kind": "edge"}, {"peer": A, "kind": "part", "parts": ["middle"]}])+ self.assertEqual(ways.clash(held, "this Mac"), "Two of the ways to Ay cover the right edge of this Mac. Keep one of them.")++ def test_zones_that_are_off_never_clash(self):+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])+ self.assertIsNone(ways.clash(held, "this PC"))+++class EveryMachineHasAWayIn(unittest.TestCase):+ """A machine paired, or one whose side arrives, crosses by its whole edge unless that edge is+ another machine's already (the rig's beta.3 file of 01-10: the laptop's side set, no zone)."""++ def test_a_machine_with_no_zone_gets_its_whole_edge(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="right"), zones=[{"peer": A, "kind": "edge"}])+ self.assertTrue(ways.ensure_zones(held))+ self.assertIn({"peer": B, "kind": "edge"}, held["zones"])+ self.assertFalse(ways.ensure_zones(held))++ def test_one_whose_side_is_another_machines_edge_gets_it_off_so_the_settings_stay_readable(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="left"), zones=[{"peer": A, "kind": "edge"}])+ ways.ensure_zones(held)+ self.assertIn({"peer": B, "kind": "edge", "off": True}, held["zones"])+ self.assertIsNone(ways.clash(held, "this PC"))++ def test_a_machine_with_its_zones_all_off_keeps_them_as_they_are(self):+ held = settings(peer(A, "Ay", side="left"), zones=[{"peer": A, "kind": "edge", "off": True}])+ self.assertFalse(ways.ensure_zones(held))++ def test_a_phone_and_an_entry_with_no_id_get_none(self):+ held = settings(peer(PHONE, "Phone", port=0, host="", send=False), peer("", "Old", from_1_4=True))+ self.assertFalse(ways.ensure_zones(held))+ self.assertEqual(held["zones"], [])++ def test_an_arrangement_for_a_machine_with_no_zone_gives_it_its_edge(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee"), zones=[{"peer": A, "kind": "edge"}])+ self.assertEqual(ways.arrangement(held, B, "left", 20, B, "this PC"), (True, []))+ self.assertIn({"peer": B, "kind": "edge"}, held["zones"])++ def test_an_arrangement_onto_another_machines_edge_gives_it_the_edge_off_and_says_so(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop"), zones=[{"peer": A, "kind": "edge"}])+ changed, notices = ways.arrangement(held, B, "right", 20, B, "this PC")+ self.assertTrue(changed)+ self.assertEqual(notices, ["MacBook Pro and Laptop now lead from the same part of this PC's screen, so "+ "Laptop's edge is off."])+ self.assertIn({"peer": B, "kind": "edge", "off": True}, held["zones"])+++class Blocked(unittest.TestCase):+ def test_a_machine_whose_side_is_taken_and_has_no_way_in_is_told_which_machine_has_it(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop", side="left"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])+ self.assertEqual(ways.blocked_sentence(held, B, "this PC"),+ "Laptop has no way in: MacBook Pro already leads from the left edge of this PC. "+ "Give each its own thirds of that edge under Part of the edge, or move one to another side.")+ self.assertEqual(ways.blocked_sentence(held, A, "this PC"), "")++ def test_thirds_left_free_by_another_machine_are_no_block(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop", side="left"), zones=[+ {"peer": A, "kind": "part", "parts": ["start"]}, {"peer": B, "kind": "part", "parts": ["end"]}])+ self.assertEqual(ways.blocked_sentence(held, B, "this PC"), "")++ def test_a_machine_with_a_corner_in_use_is_not_blocked(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop", side="left"), zones=[+ {"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True},+ {"peer": B, "kind": "corner", "corner": "top_left", "edge": "left"}])+ self.assertEqual(ways.blocked_sentence(held, B, "this PC"), "")++ def test_a_machine_with_no_side_is_not_blocked(self):+ held = settings(peer(A, "MacBook Pro", side="left"), peer(B, "Laptop"), zones=[{"peer": A, "kind": "edge"}])+ self.assertEqual(ways.blocked_sentence(held, B, "this PC"), "")+++class WayBack(unittest.TestCase):+ """What a machine tells another with its `arrangement`: whether it has a zone in use leading there."""++ def test_a_zone_in_use_with_a_side_or_a_corner_is_a_way(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee"), peer(C, "Sea", side="top"), zones=[+ {"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"},+ {"peer": C, "kind": "edge", "off": True}, {"peer": C, "kind": "corner", "corner": "top_left", "edge": "top"}])+ self.assertEqual([ways.has_way(held, ident) for ident in (A, B, C)], [True, False, True])++ def test_an_arrangement_keeps_what_the_sender_said_whether_or_not_its_side_is_newer(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=50, side_by=A))+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False), (True, []))+ self.assertIs(held["peers"][0]["way_back"], False)+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False), (False, []))+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC"), (False, []))+ self.assertIs(held["peers"][0]["way_back"], False)+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC", way_back=True), (True, []))+ self.assertIs(held["peers"][0]["way_back"], True)++ def test_the_sentence_names_the_machine_with_no_way_back(self):+ held = settings(peer(A, "Desk-PC", way_back=False), peer(B, "Bee", way_back=True), peer(C, "Sea"))+ self.assertEqual(ways.no_way_back_sentence(held, A),+ "Desk-PC has no way back to this machine: none of its edges leads here. Its own "+ "Crossing page says why.")+ self.assertEqual(ways.no_way_back_sentence(held, B), "")+ self.assertEqual(ways.no_way_back_sentence(held, C), "")+++ def test_with_no_way_back_the_sender_names_the_machine_whose_zone_holds_that_side(self):+ # The laptop on 02-10-2026: the Mac and the rig both on its left, the rig's edge in use.+ held = settings(peer(A, "Mac", side="left"), peer(B, "Rig", side="left"),+ zones=[{"peer": A, "kind": "edge", "off": True}, {"peer": B, "kind": "edge"}])+ self.assertEqual(ways.way_back_by(held, A), B)+ self.assertIsNone(ways.way_back_by(held, B))+ held["zones"][0].pop("off")+ held["zones"][1]["off"] = True+ self.assertIsNone(ways.way_back_by(held, A))+ # Off by choice, with nobody else on that side: no way back, and nobody in the way.+ held["zones"][0]["off"] = True+ self.assertIsNone(ways.way_back_by(held, A))++ def test_what_each_machine_is_told_of_its_way_back_so_a_change_reaches_every_machine_it_touches(self):+ # Moving one machine can open or close another's way back: Sol's review, 02-10-2026.+ held = settings(peer(A, "Mac", side="left"), peer(B, "Rig", side="left"),+ zones=[{"peer": A, "kind": "edge", "off": True}, {"peer": B, "kind": "edge"}])+ before = ways.way_back_state(held)+ self.assertEqual(before, {A: (False, B), B: (True, None)})+ held["peers"][1]["side"] = "right"+ held["zones"][0].pop("off")+ after = ways.way_back_state(held)+ self.assertEqual(sorted(peer for peer in after if after[peer] != before.get(peer)), [A])++ def test_an_arrangement_keeps_who_is_in_the_way_only_beside_a_way_back_of_false(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=50, side_by=A))+ self.assertEqual(ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False, way_back_by=C), (True, []))+ self.assertEqual(held["peers"][0]["way_back_by"], C)+ ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False)+ self.assertNotIn("way_back_by", held["peers"][0])+ ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False, way_back_by=C)+ ways.arrangement(held, A, "right", 50, A, "this PC", way_back=True, way_back_by=C)+ self.assertNotIn("way_back_by", held["peers"][0])+ # This machine's own id, or one that is not an id, is ignored as if absent.+ for odd in (HERE, "x"):+ ways.arrangement(held, A, "right", 50, A, "this PC", way_back=False, way_back_by=odd)+ self.assertNotIn("way_back_by", held["peers"][0])++ def test_the_sentence_names_the_machine_in_the_way_and_where_to_change_it(self):+ held = settings(peer(A, "Laptop-PC", side="right", way_back=False, way_back_by=B), peer(B, "Desk-PC"))+ self.assertEqual(ways.no_way_back_sentence(held, A),+ "Laptop-PC has Desk-PC on its left too, so none of its edges leads back here. On "+ "Laptop-PC's Crossing page, share that side by thirds or move one of them.")+ held["peers"][0]["way_back_by"] = C+ self.assertEqual(ways.no_way_back_sentence(held, A),+ "Laptop-PC has another machine on its left too, so none of its edges leads back here. On "+ "Laptop-PC's Crossing page, share that side by thirds or move one of them.")+++class Arrangement(unittest.TestCase):+ def test_a_newer_arrangement_sets_the_opposite_side_for_that_peer_only(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=10, side_by=HERE), peer(B, "Bee", side="right"))+ changed, notices = ways.arrangement(held, A, "left", 20, A, "this PC")+ self.assertTrue(changed)+ self.assertEqual(notices, [])+ self.assertEqual((held["peers"][0]["side"], held["peers"][0]["side_set_at"], held["peers"][0]["side_by"]),+ ("right", 20, A))+ self.assertEqual(held["peers"][1]["side"], "right")++ def test_an_older_one_or_a_tie_lost_on_the_id_changes_nothing(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=10, side_by=C))+ self.assertEqual(ways.arrangement(held, A, "left", 9, A, "this PC"), (False, []))+ self.assertEqual(ways.arrangement(held, A, "left", 10, A, "this PC"), (False, []))+ self.assertEqual(held["peers"][0]["side"], "left")++ def test_a_tie_won_on_the_id_applies(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=10, side_by=A))+ self.assertEqual(ways.arrangement(held, A, "left", 10, C, "this PC"), (True, []))++ def test_a_side_that_now_overlaps_turns_the_senders_zones_off_and_names_both(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="right"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])+ changed, notices = ways.arrangement(held, A, "left", 20, A, "this Mac")+ self.assertTrue(changed)+ self.assertEqual(notices, ["Bee and Ay now lead from the same part of this Mac's screen, so Ay's edge is off."])+ self.assertTrue(next(zone for zone in held["zones"] if zone["peer"] == A)["off"])+ self.assertNotIn("off", next(zone for zone in held["zones"] if zone["peer"] == B))++ def test_an_unknown_peer_bad_edge_or_bad_by_changes_nothing(self):+ held = settings(peer(A, "Ay", side="left"))+ self.assertEqual(ways.arrangement(held, B, "left", 20, B, "this PC"), (False, []))+ self.assertEqual(ways.arrangement(held, A, "middle", 20, A, "this PC"), (False, []))+ self.assertEqual(ways.arrangement(held, A, "left", 20, "nope", "this PC"), (False, []))+++class TheShortcutsMachine(unittest.TestCase):+ def test_the_machine_input_was_last_on_while_it_can_take_input(self):+ peers = [peer(A, "Ay"), peer(B, "Bee")]+ self.assertEqual(ways.shortcut_peer(peers, B, lambda ident: True), B)++ def test_else_the_first_that_can_take_input(self):+ peers = [peer(A, "Ay"), peer(B, "Bee"), peer(C, "Sea")]+ self.assertEqual(ways.shortcut_peer(peers, A, lambda ident: ident == C), C)+ self.assertEqual(ways.shortcut_peer(peers, None, lambda ident: ident != A), B)++ def test_else_the_first_this_machine_sends_to_so_the_refusal_or_the_wake_names_it(self):+ peers = [peer(A, "Ay", send=False), peer(B, "Bee"), peer(C, "Sea")]+ self.assertEqual(ways.shortcut_peer(peers, None, lambda ident: False), B)++ def test_a_machine_this_one_does_not_send_to_is_never_picked(self):+ peers = [peer(A, "Ay", send=False)]+ self.assertIsNone(ways.shortcut_peer(peers, A, lambda ident: True))++ def test_a_machine_not_in_use_is_never_picked(self):+ peers = [peer(A, "Ay", in_use=False), peer(B, "Bee")]+ self.assertEqual(ways.shortcut_peer(peers, A, lambda ident: True), B)++ def test_a_phone_or_an_entry_without_an_id_is_never_picked(self):+ peers = [peer(PHONE, "Phone", port=0, host="", send=False), peer("", "Old", from_1_4=True)]+ self.assertIsNone(ways.shortcut_peer(peers, None, lambda ident: True))++ def test_nothing_paired_picks_nothing(self):+ self.assertIsNone(ways.shortcut_peer([], None, lambda ident: True))+++class MissingPairings(unittest.TestCase):+ def test_a_machine_that_may_drive_this_one_and_is_not_paired_with_the_zones_peer_is_named(self):+ held = settings(peer(A, "Ay", paired_with=[B]), peer(B, "Bee", paired_with=[A]), peer(C, "Sea", paired_with=[A]))+ self.assertEqual([entry["id"] for entry in ways.missing_pairings(held, B)], [C])+ self.assertEqual([entry["id"] for entry in ways.missing_pairings(held, A)], [])++ def test_a_machine_not_allowed_to_drive_this_one_needs_no_pairing(self):+ held = settings(peer(A, "Ay"), peer(B, "Bee", allow_drive=False))+ self.assertEqual(ways.missing_pairings(held, A), [])++ def test_a_machine_not_in_use_needs_no_pairing(self):+ held = settings(peer(A, "Ay"), peer(B, "Bee", in_use=False))+ self.assertEqual(ways.missing_pairings(held, A), [])++ def test_a_machine_that_has_never_linked_is_not_judged(self):+ held = settings(peer(A, "Ay"), peer(B, "Bee", linked=False))+ self.assertEqual(ways.missing_pairings(held, A), [])++ def test_a_phone_that_may_drive_this_one_counts(self):+ held = settings(peer(A, "Ay"), peer(PHONE, "Phone", port=0, host="", send=False))+ self.assertEqual([entry["id"] for entry in ways.missing_pairings(held, A)], [PHONE])++ def test_the_sentence_names_each_machine_and_the_one_it_needs(self):+ held = settings(peer(A, "Ay"), peer(B, "Bee", paired_with=[]))+ self.assertEqual(ways.missing_sentence(held, A, "this Mac"),+ "While Bee drives this Mac, this way to Ay does nothing: Bee is not paired with Ay. "+ "Pair them to use it from there too.")+ held["peers"].append(peer(C, "Sea"))+ self.assertEqual(ways.missing_sentence(held, A, "this Mac"),+ "While Bee or Sea drives this Mac, this way to Ay does nothing: neither is paired "+ "with Ay. Pair them to use it from there too.")+ self.assertEqual(ways.missing_sentence(settings(peer(A, "Ay")), A, "this Mac"), "")++++class TheShownDefault(unittest.TestCase):+ """The Mac's page shows Right for its one machine before a side is set, so the settings hold it+ from the moment that machine is paired, not from the first save (beta.4: Edge did nothing until+ a save of another way wrote it)."""++ def test_the_one_machine_not_placed_holds_right_unstamped_so_its_edge_fires(self):+ held = settings(peer(A, "Ay"), zones=[{"peer": A, "kind": "edge"}])+ self.assertFalse(ways.has_way(held, A))+ self.assertTrue(ways.default_side(held))+ entry = held["peers"][0]+ self.assertEqual((entry["side"], entry["side_set_at"], entry["side_by"]), ("right", 0, ""))+ self.assertTrue(ways.has_way(held, A))+ self.assertFalse(ways.default_side(held))++ def test_the_held_default_loses_to_a_side_the_peer_chooses(self):+ held = settings(peer(A, "Ay"), zones=[{"peer": A, "kind": "edge"}])+ ways.default_side(held)+ self.assertEqual(ways.arrangement(held, A, "bottom", 1_899_999_000, A, "this Mac"), (True, []))+ self.assertEqual(held["peers"][0]["side"], "top")++ def test_a_default_never_moves_a_side_already_set(self):+ held = settings(peer(A, "Ay", side="left", side_set_at=5, side_by=A), zones=[{"peer": A, "kind": "edge"}])+ self.assertFalse(ways.default_side(held))+ self.assertEqual(held["peers"][0]["side"], "left")++ def test_with_several_machines_none_is_given_a_side_nobody_chose(self):+ held = settings(peer(A, "Ay"), peer(B, "Bee"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])+ self.assertFalse(ways.default_side(held))+ self.assertEqual([entry["side"] for entry in held["peers"]], ["", ""])++ def test_a_machine_paired_beside_the_one_migrated_from_1_4_is_given_no_side(self):+ # The migrated entry has no id and holds the 1.4 side: Right as well would clash with it.+ held = settings(peer("", "Studio", side="right", from_1_4=True), peer(A, "Ay"),+ zones=[{"peer": "", "kind": "edge"}, {"peer": A, "kind": "edge"}])+ self.assertFalse(ways.default_side(held))+ self.assertEqual(held["peers"][1]["side"], "")++ def test_a_phone_alone_is_given_no_side(self):+ held = settings(peer(PHONE, "Phone", port=0, host="", send=False))+ self.assertFalse(ways.default_side(held))+++class TheCornerFollowsAnArrivingSide(unittest.TestCase):+ def test_a_corner_that_crosses_the_side_is_rewritten_for_the_side_that_arrives(self):+ held = settings(peer(A, "Ay", side="top", side_set_at=5, side_by=A),+ zones=[{"peer": A, "kind": "corner", "corner": "top_right", "edge": "top"}])+ self.assertEqual(ways.arrangement(held, A, "left", 10, A, "this PC", corner_edge=pc_corner_edge), (True, []))+ self.assertEqual((held["peers"][0]["side"], held["zones"][0]["edge"]), ("right", "right"))++++class SharingASide(unittest.TestCase):+ """A machine put on a side another machine already crosses from is offered that side by thirds+ on the spot, rather than refused (beta.4, 02-10-2026: "it rejects the option and hides it")."""++ def two_on_the_right(self, rig_zone=None):+ return settings(peer(A, "Desk-PC", side="right"), peer(B, "Laptop-PC", side="right"),+ zones=[rig_zone or {"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])++ def test_a_machine_whose_side_another_holds_whole_is_offered_the_end_third(self):+ held = self.two_on_the_right()+ self.assertEqual(ways.share_offer(held, B),+ {"side": "right", "holders": [A], "thirds": {"start": A, "middle": A, "end": B}})++ def test_free_thirds_go_to_the_machine_asking(self):+ held = self.two_on_the_right({"peer": A, "kind": "part", "parts": ["end"]})+ self.assertEqual(ways.share_offer(held, B)["thirds"], {"start": B, "middle": B, "end": A})++ def test_nothing_is_offered_where_nothing_is_in_the_way(self):+ held = settings(peer(A, "Ay", side="left"), peer(B, "Bee", side="right"),+ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])+ self.assertIsNone(ways.share_offer(held, B))+ self.assertIsNone(ways.share_offer(self.two_on_the_right(), A))++ def test_sharing_writes_each_machines_thirds_and_turns_their_whole_edges_off(self):+ held = self.two_on_the_right()+ changed = ways.share(held, "right", {"start": A, "middle": A, "end": B}, kinds=MAC)+ self.assertEqual(sorted(changed), sorted([A, B]))+ mine = {(zone["peer"], zone["kind"]): zone for zone in held["zones"]}+ self.assertTrue(mine[(A, "edge")].get("off"))+ self.assertTrue(mine[(B, "edge")].get("off"))+ self.assertEqual((mine[(A, "part")]["parts"], mine[(A, "part")].get("off")), (["start", "middle"], None))+ self.assertEqual((mine[(B, "part")]["parts"], mine[(B, "part")].get("off")), (["end"], None))+ self.assertIsNone(ways.clash(held, "this Mac"))+ self.assertTrue(ways.has_way(held, A) and ways.has_way(held, B))++ def test_a_machine_on_that_side_left_with_no_third_crosses_there_no_more(self):+ held = self.two_on_the_right()+ ways.share(held, "right", {"start": B, "middle": B, "end": B}, kinds=MAC)+ self.assertFalse(ways.has_way(held, A))+ self.assertIsNone(ways.clash(held, "this Mac"))++ def test_a_machine_left_with_no_third_keeps_a_part_zone_the_settings_accept(self):+ # Sol's review: an empty `parts` made the Mac's store refuse the whole share.+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"), peer(C, "Sea", side="right"),+ zones=[{"peer": A, "kind": "part", "parts": ["start", "middle"]},+ {"peer": C, "kind": "part", "parts": ["end"]},+ {"peer": B, "kind": "edge", "off": True}])+ ways.share(held, "right", {"start": A, "middle": A, "end": B}, kinds=MAC)+ sea = next(zone for zone in held["zones"] if zone["peer"] == C and zone["kind"] == "part")+ self.assertTrue(sea.get("off"))+ self.assertTrue(sea["parts"])+ self.assertIsNone(ways.clash(held, "this Mac"))++ def test_sharing_reports_every_machine_whose_way_back_it_changed_not_only_whose_zones(self):+ # Sol's review: Sea's blocker moved from Ay to Bee, and only Ay and Bee were told.+ held = settings(peer(A, "Ay", side="right"), peer(B, "Bee", side="right"), peer(C, "Sea", side="right"),+ zones=[{"peer": B, "kind": "part", "parts": ["middle"], "off": True},+ {"peer": A, "kind": "edge"},+ {"peer": B, "kind": "edge", "off": True},+ {"peer": C, "kind": "edge", "off": True}])+ before = ways.way_back_state(held)+ changed = ways.share(held, "right", {"start": A, "middle": A, "end": B}, kinds=MAC)+ after = ways.way_back_state(held)+ self.assertTrue({peer for peer in after if after[peer] != before.get(peer)} <= set(changed), changed)++ def test_a_split_naming_a_machine_not_on_that_side_or_leaving_a_third_out_is_refused(self):+ held = self.two_on_the_right()+ held["peers"].append(peer(C, "Sea", side="left"))+ for thirds in ({"start": A, "middle": A, "end": C}, {"start": A, "middle": B}):+ with self.subTest(thirds=thirds), self.assertRaises(ValueError):+ ways.share(held, "right", thirds, kinds=MAC)++++class AMachineThatIsGone(unittest.TestCase):++ """A machine that will not link again (a live USB, a reinstall, one that removed this machine)++ kept its edge, and a machine that is here, put on that side, lost its way back instead (1.5.0++ beta, 06-10-2026: the PC kept a live USB on its right, the Mac arrived on its right, and input++ on the PC had no way home)."""++++ def pc_with_a_gone_machine_on_the_right(self):++ return settings(peer(A, "MacBook Pro", side="bottom"), peer(B, "live-usb", side="right"),++ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}])++++ @staticmethod++ def only(*idents):++ return lambda ident: ident in idents++++ def test_an_arrangement_from_a_machine_that_is_here_takes_the_side_from_one_that_is_not(self):++ held = self.pc_with_a_gone_machine_on_the_right()++ changed, notices = ways.arrangement(held, A, "left", 20, A, "this PC", live=self.only(A))++ self.assertTrue(changed)++ self.assertEqual(notices, ["live-usb is not connected, so MacBook Pro takes that part of this PC's "++ "screen for now and live-usb's edge is set aside until it connects."])++ self.assertTrue(ways.has_way(held, A))++ self.assertFalse(ways.has_way(held, B))++ self.assertIsNone(ways.clash(held, "this PC"))++++ def test_without_liveness_the_machine_arriving_still_gives_way_as_before(self):++ held = self.pc_with_a_gone_machine_on_the_right()++ ways.arrangement(held, A, "left", 20, A, "this PC")++ self.assertFalse(ways.has_way(held, A))++++ def test_two_machines_that_are_both_here_keep_the_rule_and_the_share_offer(self):++ held = self.pc_with_a_gone_machine_on_the_right()++ _, notices = ways.arrangement(held, A, "left", 20, A, "this PC", live=self.only(A, B))++ self.assertFalse(ways.has_way(held, A))++ self.assertIn("MacBook Pro's edge is off", notices[0])++ self.assertEqual(ways.share_offer(held, A, live=self.only(A, B))["holders"], [B])++++ def test_a_machine_that_is_not_here_is_offered_no_third_and_blocks_nothing(self):++ held = settings(peer(A, "MacBook Pro", side="right"), peer(B, "live-usb", side="right"),++ zones=[{"peer": A, "kind": "edge", "off": True}, {"peer": B, "kind": "edge"}])++ self.assertIsNone(ways.share_offer(held, A, live=self.only(A)))++ self.assertEqual(ways.blocked_sentence(held, A, "this PC", live=self.only(A)), "")++ self.assertIn("live-usb already leads", ways.blocked_sentence(held, A, "this PC"))++++ def test_choosing_the_edge_on_the_crossing_page_takes_it_from_a_machine_that_is_not_here(self):++ # "I tried to set up edge but it wasn't clicking": the edit, then the clash check the stores make.++ held = settings(peer(A, "MacBook Pro", side="right"), peer(B, "live-usb", side="right"),++ zones=[{"peer": A, "kind": "edge", "off": True}, {"peer": B, "kind": "edge"}])++ ways.edit(held, A, side="right", methods=["edge"], parts=[], corner="top_left", kinds=PC,++ corner_edge=pc_corner_edge, now=30)++ self.assertIsNotNone(ways.clash(held, "this PC"))++ self.assertEqual(len(ways.give_way(held, A, "this PC", self.only(A))), 1)++ self.assertIsNone(ways.clash(held, "this PC"))++ self.assertTrue(ways.has_way(held, A))++++ def test_giving_way_leaves_zones_elsewhere_and_machines_that_are_here_alone(self):++ held = settings(peer(A, "Mac", side="right"), peer(B, "Gone", side="left"), peer(C, "Here", side="top"),++ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge"}, {"peer": C, "kind": "edge"}])++ self.assertEqual(ways.give_way(held, A, "this PC", self.only(A, C)), [])++ self.assertEqual(ways.give_way(held, A, "this PC", None), [])++ self.assertTrue(all(zone.get("off") is not True for zone in held["zones"]))++++++class AMachineThatIsAsleep(unittest.TestCase):++ """A lid shut is not a machine gone: the zone taken from a machine with no link is set aside, comes++ back when the machine connects, and is off for good only for one that removed this pairing++ (review of the one-sided forget fix, 06-10-2026)."""++++ def asleep(self):++ held = settings(peer(A, "MacBook Pro", side="right"), peer(B, "Laptop", side="right"),++ zones=[{"peer": A, "kind": "edge"}, {"peer": B, "kind": "edge", "off": True}])++ ways.edit(held, B, side="right", methods=["edge"], parts=[], corner="top_left", kinds=PC,++ corner_edge=pc_corner_edge, now=30)++ return held++++ @staticmethod++ def zone(held, peer_id):++ return next(zone for zone in held["zones"] if zone["peer"] == peer_id and zone["kind"] == "edge")++++ def test_a_machine_with_no_link_has_its_zone_set_aside_not_lost(self):++ held = self.asleep()++ notices = ways.give_way(held, B, "this PC", lambda ident: ident == B)++ self.assertEqual(len(notices), 1)++ self.assertEqual(self.zone(held, A), {"peer": A, "kind": "edge", "off": True, "aside": True})++ self.assertFalse(ways.has_way(held, A))++ self.assertTrue(ways.has_way(held, B))++++ def test_the_zone_comes_back_when_the_machine_connects_and_the_stretch_is_free(self):++ held = self.asleep()++ ways.give_way(held, B, "this PC", lambda ident: ident == B)++ self.zone(held, B)["off"] = True # the machine that took the stretch lets it go++ live, gone = (lambda ident: True), (lambda ident: False)++ self.assertTrue(ways.presence_due(held, live, gone))++ self.assertEqual(ways.settle_presence(held, "this PC", live, gone), [])++ self.assertEqual(self.zone(held, A), {"peer": A, "kind": "edge"})++ self.assertFalse(ways.presence_due(held, live, gone))++++ def test_it_waits_while_the_machine_is_still_asleep(self):++ held = self.asleep()++ ways.give_way(held, B, "this PC", lambda ident: ident == B)++ before = [dict(zone) for zone in held["zones"]]++ self.assertFalse(ways.presence_due(held, lambda ident: ident == B, lambda ident: False))++ self.assertEqual(ways.settle_presence(held, "this PC", lambda ident: ident == B, lambda ident: False), [])++ self.assertEqual(held["zones"], before)++++ def test_a_machine_back_over_a_stretch_another_holds_stays_off_and_says_so(self):++ held = self.asleep()++ ways.give_way(held, B, "this PC", lambda ident: ident == B)++ notices = ways.settle_presence(held, "this PC", lambda ident: True, lambda ident: False)++ self.assertEqual(notices, ["MacBook Pro is connected again, but Laptop leads from that part of this PC's "++ "screen, so MacBook Pro's edge stays off. Share the side on the Crossing page."])++ self.assertEqual(self.zone(held, A), {"peer": A, "kind": "edge", "off": True})++ self.assertIsNone(ways.clash(held, "this PC"))++ self.assertEqual(ways.share_offer(held, A, live=lambda ident: True)["holders"], [B])++++ def test_a_machine_that_removed_this_pairing_stays_off_for_good_and_the_page_says_so(self):++ held = self.asleep()++ ways.give_way(held, B, "this PC", lambda ident: ident == B)++ gone = lambda ident: ident == A++ notices = ways.settle_presence(held, "this PC", lambda ident: ident == B, gone)++ self.assertEqual(notices, ["MacBook Pro no longer has this pairing, so its edge stays off. Remove "++ "MacBook Pro here and pair the two again."])++ self.assertEqual(self.zone(held, A), {"peer": A, "kind": "edge", "off": True})++ self.assertFalse(ways.presence_due(held, lambda ident: True, lambda ident: False))++ self.assertEqual(ways.gone_sentence(held, A, "this PC", gone),++ "MacBook Pro no longer has this pairing, so it has no way in. Remove MacBook Pro here and "++ "pair the two again.")++ self.assertEqual(ways.gone_sentence(held, B, "this PC", gone), "")++++ def test_a_zone_the_user_changes_while_it_is_set_aside_is_no_longer_set_aside(self):++ for methods in (["edge"], []):++ with self.subTest(methods=methods):++ held = self.asleep()++ ways.give_way(held, B, "this PC", lambda ident: ident == B)++ ways.edit(held, A, side="right", methods=methods, parts=[], corner="top_left", kinds=PC,++ corner_edge=pc_corner_edge, now=40)++ self.assertNotIn("aside", self.zone(held, A))++ if methods:++ self.zone(held, B)["off"] = True++ ways.settle_presence(held, "this PC", lambda ident: True, lambda ident: False)++ self.assertEqual("off" in self.zone(held, A), not methods)++++++class TheShortcutIsNotTakenByAStaleEntry(unittest.TestCase):++ def test_with_nothing_ready_the_machine_last_used_is_named_before_an_older_entry(self):++ # The lent laptop listed the PC's old pairing first; the shortcut named it rather than the Mac.++ peers = [peer(A, "Old PC"), peer(B, "MacBook Pro")]++ self.assertEqual(ways.shortcut_peer(peers, B, lambda ident: False), B)++ self.assertEqual(ways.shortcut_peer(peers, None, lambda ident: False), A)+++++if __name__ == "__main__":+ unittest.main()diff --cc core/ways.pyindex 5063799,0000000..9a3a23emode 100644,000000..100644--- a/core/ways.py+++ b/core/ways.py@@@ -1,585 -1,0 +1,684 @@@+"""A machine's zones, one peer at a time (WIRE.md sections 5 and 8), shared by both desktops.++What the Crossing page reads and writes for the machine it has chosen, the side settled with each+peer by `arrangement`, the sentence for two zones over one stretch, which machine the shortcut and+the Send button pick, and which machines that may drive this one cannot follow a zone. Pure: each+app calls these on its settings under its own lock and writes the file itself.+"""++import base64+import binascii++import copy+import re+from typing import Callable, Optional++from core import peerlist+from core import return_edge+from core.settings_sync import next_stamp++EDGES = return_edge.EDGES+CORNERS = return_edge.CORNERS+PARTS = return_edge.PARTS+DEFAULT_PARTS = ["middle"]+DEFAULT_CORNER = "top_left"+# How a notice names each kind of zone.+KIND_WORDS = {"edge": "edge", "part": "part of the edge", "corner": "corner", "notch": "notch"}+_JUMP_MODIFIERS = {"alt", "cmd", "ctrl", "shift"}+_JUMP_KEYS = {"backspace", "caps_lock", "delete", "down", "end", "enter", "esc", "home", "insert",+ "left", "page_down", "page_up", "pause", "print_screen", "right", "space", "tab", "up",+ "menu", "num_lock", "scroll_lock", "browser_back", "browser_forward", "volume_mute",+ "volume_down", "volume_up", "media_next", "media_prev", "media_stop", "media_play_pause"}+++def part_names(edge: str) -> dict:+ """The labels for thirds along an edge, in the direction they run."""+ if edge in ("left", "right"):+ return {"start": "Top", "middle": "Middle", "end": "Bottom"}+ return {"start": "Left", "middle": "Middle", "end": "Right"}+++def parts_phrase(edge: str, parts) -> str:+ """The selected thirds in a sentence, defaulting to the middle when none are known."""+ names = part_names(edge)+ chosen = [names[part].lower() for part in PARTS if part in parts] or ["middle"]+ joined = chosen[0] if len(chosen) == 1 else ", ".join(chosen[:-1]) + " and " + chosen[-1]+ return f"the {joined} of the {edge} edge"+++def toggle_part(parts, part, on) -> list:+ """The selected thirds after a change, keeping one selected so Part of the edge can cross."""+ chosen = set(parts) | {part} if on else set(parts) - {part}+ if not chosen:+ chosen = set(parts)+ return [name for name in PARTS if name in chosen]+++def valid_jump_key(value) -> bool:+ """Whether a recorded jump key is one modifier chord with a single non-modifier key."""+ if not isinstance(value, str) or not value or value != value.lower():+ return False+ parts = value.split("+")+ if len(parts) < 2 or any(not part for part in parts) or len(set(parts)) != len(parts):+ return False+ modifiers = [part for part in parts if part in _JUMP_MODIFIERS]+ keys = [part for part in parts if part not in _JUMP_MODIFIERS]+ if not set(modifiers) - {"shift"} or len(keys) != 1:+ return False+ if parts[:-1] != [name for name in ("ctrl", "alt", "shift", "cmd") if name in modifiers]:+ return False+ key = keys[0]+ return (key in _JUMP_KEYS or key == "plus" or re.fullmatch(r"[a-z0-9]", key) is not None+ or re.fullmatch(r"f(?:[1-9]|1[0-9]|2[0-4])", key) is not None+ or (len(key) == 1 and key.isprintable() and key not in "+ "))+++def jump_chord(modifiers, key) -> Optional[str]:+ """The stable spelling shared by both capture hooks and the key recorders."""+ modifiers = {name[:-2] if name in {"alt_r", "cmd_r", "ctrl_r", "shift_r"} else name for name in modifiers}+ modifiers &= _JUMP_MODIFIERS+ key = key.lower() if isinstance(key, str) else ""+ if key == "+":+ key = "plus"+ value = "+".join([name for name in ("ctrl", "ctrl_r", "alt", "alt_r", "shift", "shift_r", "cmd", "cmd_r")+ if name in modifiers] + [key])+ return value if valid_jump_key(value) else None+++def jump_key(peer: dict) -> Optional[str]:+ """The peer's optional local jump chord, or None when absent or empty."""+ value = peer.get("jump_key") if peer.get("port") != 0 else None+ return value if isinstance(value, str) and value else None+++def check_jump_key(settings: dict, peer: str, value, trigger_key: str) -> Optional[str]:+ """Validate and clash-check a peer's jump chord before it is stored; empty clears it."""+ if value in (None, ""):+ return None+ entry = _entry(settings, peer)+ if entry is not None and entry.get("port") == 0:+ raise ValueError("a phone cannot be a jump target")+ if not isinstance(value, str):+ raise ValueError("choose a modifier and one non-modifier key")+ if not valid_jump_key(value):+ raise ValueError("choose a modifier and one non-modifier key")+ if _trigger_in_chord(trigger_key, value):+ raise ValueError("that key is the trigger shortcut's: pick a chord without it")+ for entry in settings.get("peers", []):+ if entry.get("id") != peer and jump_key(entry) == value:+ raise ValueError("that key is already assigned to another machine")+ return value+++def _trigger_in_chord(trigger_key, chord):+ parts = chord.split("+")+ return (parts[-1] == trigger_key+ or isinstance(trigger_key, str) and trigger_key.removesuffix("_r") in parts)+++def check_trigger_key(settings, trigger_key):+ """Apply the same overlap rule whichever side of a shortcut/jump clash is edited."""+ for peer in settings.get("peers", []):+ chord = jump_key(peer)+ if chord and _trigger_in_chord(trigger_key, chord):+ raise ValueError(f"That shortcut clashes with the jump key {chord}; the jump key has been kept.")+++def shared_trigger_values(settings, values):+ """Keep the local jump and trigger on a clash, while allowing the other shared values."""+ if "trigger_key" not in values:+ return values, None+ try:+ check_trigger_key(settings, values["trigger_key"])+ except ValueError as exc:+ return {key: value for key, value in values.items() if key != "trigger_key"}, str(exc)+ return values, ""+++def jump_peer(peers: list, chord: str) -> Optional[str]:+ """The in-use machine assigned this jump chord, or None."""+ return next((entry.get("id") for entry in peers+ if entry.get("in_use", True) is True and entry.get("id") and jump_key(entry) == chord), None)+++def _entry(settings: dict, peer: str) -> Optional[dict]:+ return next((entry for entry in settings["peers"] if entry.get("id") == peer), None)+++def _mine(settings: dict, peer: str) -> dict:+ found = {}+ for zone in settings["zones"]:+ if zone.get("peer") == peer:+ found.setdefault(zone.get("kind"), zone)+ return found+++def ways(settings: dict, peer: str) -> dict:+ """The ways across to one peer as the Crossing page shows them: its `side`, the kinds of zone in+ use in section 8's order of kinds, the thirds and the corner its zones hold (the defaults where+ it has none)."""+ entry = _entry(settings, peer) or {}+ mine = _mine(settings, peer)+ parts = mine.get("part", {}).get("parts")+ corner = mine.get("corner", {}).get("corner")+ return {+ "side": entry.get("side") if entry.get("side") in EDGES else "",+ "methods": [kind for kind in KIND_WORDS if kind in mine and mine[kind].get("off") is not True],+ "parts": [part for part in PARTS if part in parts] if isinstance(parts, list) and parts else list(DEFAULT_PARTS),+ "corner": corner if corner in CORNERS else DEFAULT_CORNER,+ }+++def edit(settings: dict, peer: str, *, side: str, methods, parts, corner: str, kinds,+ corner_edge: Callable[[str, str], str], now: float) -> bool:+ """Writes one peer's ways: its `side`, and one zone of each of `kinds` (the kinds this app+ offers), in use when named in `methods` and `off` otherwise. The whole edge covers its thirds,+ so with both chosen the thirds are written `off` (section 8). `corner_edge(corner, side)` is+ the edge this app's corner crosses. A changed side is stamped by this machine, never below the+ stamp held plus one. Returns whether the side changed, which the caller sends as `arrangement`.+ KeyError when no entry has `peer`."""+ entry = _entry(settings, peer)+ if entry is None:+ raise KeyError(peer)+ if entry.get("port") == 0:+ raise ValueError("a phone cannot have a side or zones")+ side = side if side in EDGES else ""+ moved = bool(side) and side != entry.get("side")+ if moved:+ entry.update(side=side, side_set_at=next_stamp(entry.get("side_set_at"), now), side_by=settings["machine_id"])+ methods = set(methods)+ if "edge" in methods:+ methods.discard("part")+ parts = [part for part in PARTS if part in parts] or list(DEFAULT_PARTS)+ corner = corner if corner in CORNERS else DEFAULT_CORNER+ fields = {"edge": {}, "part": {"parts": parts}, "corner": {"corner": corner, "edge": corner_edge(corner, side)},+ "notch": {}}+ mine = _mine(settings, peer)+ for kind in kinds:+ zone = mine.get(kind)+ if zone is None:+ zone = {"peer": peer, "kind": kind}+ settings["zones"].append(zone)+ zone.update(fields[kind])++ zone.pop("aside", None)+ if kind in methods:+ zone.pop("off", None)+ else:+ zone["off"] = True+ return moved+++def _stretch(zone: dict, sides: dict) -> set:+ """What a zone in use covers, for the rule that two never share one (section 8); the notch is+ one stretch of its own, as a Mac has one notch."""+ if zone.get("kind") == "notch":+ return {("notch",)}+ side = sides.get(zone.get("peer"), "")+ kind = zone.get("kind")+ if kind == "corner" and zone.get("corner") in CORNERS:+ return {("corner", zone["corner"])}+ if kind == "edge" and side in EDGES:+ return {(side, part) for part in PARTS}+ if kind == "part" and side in EDGES and isinstance(zone.get("parts"), list):+ return {(side, part) for part in zone["parts"] if part in PARTS}+ return set()++- def share_offer(settings: dict, peer: str) -> Optional[dict]:- """Propose thirds for `peer` when another machine already uses part of its side."""++def share_offer(settings: dict, peer: str, live: Optional[Callable[[str], bool]] = None) -> Optional[dict]:++ """Propose thirds for `peer` when another machine already uses part of its side. A machine with++ no link now is never offered a third: choosing the side takes it from that one (`give_way`)."""+ entry = _entry(settings, peer)+ side = entry.get("side") if entry else ""+ if side not in EDGES:+ return None+ sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}- holders = _side_holders(settings, peer)++ holders = _side_holders(settings, peer, live)+ if not holders:+ return None+ holder_set = set(holders)+ assigned = {}+ for zone in settings["zones"]:+ owner = zone.get("peer")+ if owner not in holder_set or zone.get("off") is True or sides.get(owner) != side:+ continue+ if zone.get("kind") not in ("edge", "part"):+ continue+ covered = {part for stretch_side, part in _stretch(zone, sides) if stretch_side == side}+ if not covered:+ continue+ for part in PARTS:+ if part in covered:+ assigned.setdefault(part, owner)+ thirds = {part: assigned.get(part, peer) for part in PARTS}+ if peer not in thirds.values():+ thirds["end"] = peer+ return {"side": side, "holders": holders, "thirds": thirds}+++def share(settings: dict, side: str, thirds: dict, *, kinds) -> list:+ """Writes a side split by thirds (`thirds`: part -> machine id) after checking every third and its+ machine, before anything changes: each machine on that side gets its thirds as a part zone in use+ and its whole edge off; one left with none keeps its part zone off. Returns every machine to tell:+ those whose zones changed and those whose way back or way_back_by did (section 8)."""+ if side not in EDGES or not isinstance(thirds, dict) or set(thirds) != set(PARTS):+ raise ValueError("a split needs every third of a known side")+ peers = {entry.get("id"): entry for entry in peerlist.desktops(settings["peers"])}+ if any(not isinstance(peer, str) or peers.get(peer, {}).get("side") != side for peer in thirds.values()):+ raise ValueError("every third must belong to a machine on that side")+ if "part" not in kinds:+ raise ValueError("this app does not offer parts of an edge")+ sides = {entry.get("id"): entry.get("side", "") for entry in settings["peers"]}+ owners = set(thirds.values())+ told = way_back_state(settings)+ changed = []+ for entry in settings["peers"]:+ if entry.get("port") == 0:+ continue+ peer = entry.get("id")+ mine = _mine(settings, peer)+ zones = [zone for zone in mine.values() if zone.get("off") is not True and+ any(stretch[0] == side for stretch in _stretch(zone, sides))]+ if entry.get("side") != side or (not zones and peer not in owners):+ continue+ edge = mine.get("edge")+ part = mine.get("part")+ expected = [name for name in PARTS if thirds[name] == peer]+ before = (dict(edge) if edge else None, dict(part) if part else None)+ if edge is not None:+ edge["off"] = True++ edge.pop("aside", None)+ if part is None:+ part = {"peer": peer, "kind": "part"}+ settings["zones"].append(part)++ part.pop("aside", None)+ if expected:+ part["parts"] = expected+ part.pop("off", None)+ else:+ # Off, never empty: the settings refuse a part zone that names no third.+ if not (isinstance(part.get("parts"), list) and part["parts"]):+ part["parts"] = list(DEFAULT_PARTS)+ part["off"] = True+ if before != (dict(edge) if edge else None, dict(part)):+ changed.append(peer)+ # A machine whose zones did not change can still be told something new: who holds its side.+ changed += [peer for peer, state in way_back_state(settings).items() if told.get(peer) != state and peer not in changed]+ return changed+++def _clashing(settings: dict):+ """The first two zones in use that cover one stretch, and that stretch; None when none do."""+ sides = {entry.get("id"): entry.get("side", "") for entry in settings["peers"]}+ seen = {}+ for zone in settings["zones"]:+ if zone.get("off") is True:+ continue+ for stretch in sorted(_stretch(zone, sides)):+ if stretch in seen:+ return seen[stretch], zone, stretch+ seen[stretch] = zone+ return None+++def clash(settings: dict, here: str) -> Optional[str]:+ """The sentence for two zones in use over one stretch of this machine's screen, naming the+ machines they lead to, or None when there is no such pair. `here` is "this Mac" or "this PC"."""+ found = _clashing(settings)+ if found is None:+ return None+ first, second, stretch = found+ peers = settings["peers"]+ one = peerlist.label_for(peers, peer_id=first.get("peer")) or peerlist.UNNAMED+ other = peerlist.label_for(peers, peer_id=second.get("peer")) or peerlist.UNNAMED+ where = {"notch": "the notch", "corner": f"the {stretch[-1].replace('_', ' ')} corner"}.get(+ stretch[0], f"the {stretch[0]} edge")+ if first.get("peer") == second.get("peer"):+ return f"Two of the ways to {one} cover {where} of {here}. Keep one of them."+ fix = {"notch": "Turn the notch off for one of them.", "corner": "Choose another corner for one of them."}.get(+ stretch[0], "Move one of them to another side, or give each its own thirds of the edge.")+ return f"{one} and {other} would both lead from {where} of {here}. {fix}"+++def _id_bytes(text) -> Optional[bytes]:+ if not isinstance(text, str) or not text:+ return None+ try:+ data = base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))+ except (binascii.Error, ValueError):+ return None+ return data if len(data) == 16 and any(data) and base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") == text else None+++def arrangement(settings: dict, peer: str, edge: str, set_at: int, by: str, here: str, way_back=None,- way_back_by=None, corner_edge: Optional[Callable[[str, str], str]] = None):++ way_back_by=None, corner_edge: Optional[Callable[[str, str], str]] = None,++ live: Optional[Callable[[str], bool]] = None):+ """A peer's `arrangement` (section 8): `edge` is the peer's edge that faces this machine, so this+ machine's side for it is the opposite. Taken when newer than the side held: a higher stamp, or the+ same stamp and the larger `by` as bytes. A machine with no zone yet gets its whole edge for that+ side, and a side that would put two zones in use over one stretch is applied and turns this peer's+ clashing zones off. `way_back` and `way_back_by`, when carried, are kept on the entry whether or+ not the side was newer. `corner_edge(corner, side)`, the app's own, rewrites the edge its corner zones- for the peer cross, as `edit` does, since a PC's corner crosses the side. Returns (changed,- notices), a sentence for each zone turned off; `here` is "this Mac" or "this PC"."""++ for the peer cross, as `edit` does, since a PC's corner crosses the side. `live(id)`, when given,++ says whether a machine has a link up now: one that has not gives way (`give_way`). Returns++ (changed, notices), a sentence for each zone turned off; `here` is "this Mac" or "this PC"."""+ entry = _entry(settings, peer)+ by_bytes = _id_bytes(by)+ if entry is None or entry.get("port") == 0 or edge not in EDGES or by_bytes is None:+ return False, []+ told = isinstance(way_back, bool) and entry.get("way_back") is not way_back+ if told:+ entry["way_back"] = way_back+ if isinstance(way_back, bool):+ holder = _id_bytes(way_back_by)+ valid_holder = holder is not None and way_back is False and holder != _id_bytes(settings.get("machine_id"))+ if valid_holder:+ valid_text = way_back_by+ if entry.get("way_back_by") != valid_text:+ entry["way_back_by"] = valid_text+ told = True+ elif "way_back_by" in entry:+ del entry["way_back_by"]+ told = True+ held = (int(entry.get("side_set_at") or 0), _id_bytes(entry.get("side_by")) or b"")+ if (int(set_at), by_bytes) <= held:+ return told, []+ entry.update(side=return_edge.OPPOSITE[edge], side_set_at=int(set_at), side_by=by)+ if corner_edge is not None:+ for zone in settings["zones"]:+ if zone.get("peer") == peer and zone.get("kind") == "corner" and zone.get("corner") in CORNERS:+ zone["edge"] = corner_edge(zone["corner"], entry["side"])+ if peer not in {zone.get("peer") for zone in settings["zones"]}:+ settings["zones"].append({"peer": peer, "kind": "edge"})- return True, _turn_off_clashes(settings, entry, here)++ return True, _turn_off_clashes(settings, entry, here, live)+++def _zoned(entry: dict) -> bool:+ """A machine that crosses by zones: a desktop with an id, never a phone."""+ return bool(entry.get("id")) and entry.get("port") != 0+++def default_side(settings: dict) -> bool:+ """The Mac's one paired machine with no side holds Right, the side its Crossing page shows, so+ its edge crosses from pairing rather than from the first save. Unstamped and with no author, so a+ side either machine chooses wins over it. Only with one desktop, as the page counts them: a+ second, even the one migrated from 1.4.x, may hold Right already. True when it wrote the side."""+ desktops = peerlist.desktops(settings["peers"])+ if len(desktops) != 1:+ return False+ entry = desktops[0]+ if not _zoned(entry) or entry.get("side") in EDGES:+ return False+ entry.update(side="right", side_set_at=0, side_by="")+ return True+++def ensure_zones(settings: dict) -> bool:+ """Gives every machine with no zone at all its whole edge, `off` when its side is another machine's+ already, so the settings stay readable (section 8, overlap). Pairing never made zones before+ 1.5.0-beta.5, so a machine paired since 1.4.x has none until this runs. True when it added any."""+ sides = {entry.get("id"): entry.get("side", "") for entry in settings["peers"]}+ covered = set()+ for zone in settings["zones"]:+ if zone.get("off") is not True:+ covered |= _stretch(zone, sides)+ zoned = {zone.get("peer") for zone in settings["zones"]}+ added = False+ for entry in settings["peers"]:+ if not _zoned(entry) or entry["id"] in zoned:+ continue+ zone = {"peer": entry["id"], "kind": "edge"}+ stretch = _stretch(zone, sides)+ if stretch & covered:+ zone["off"] = True+ else:+ covered |= stretch+ settings["zones"].append(zone)+ added = True+ return added+++def has_way(settings: dict, peer: str) -> bool:+ """Whether a zone in use leads to `peer` and can fire: a corner or the notch, or an edge or thirds+ of a side that is set. What `arrangement`'s `way_back` says to that machine."""+ sides = {entry.get("id"): entry.get("side", "") for entry in settings["peers"]}+ return any(zone.get("peer") == peer and zone.get("off") is not True and _stretch(zone, sides)+ for zone in settings["zones"])++- def blocked_sentence(settings: dict, peer: str, here: str) -> str:++def blocked_sentence(settings: dict, peer: str, here: str, live: Optional[Callable[[str], bool]] = None) -> str:+ """The Crossing page's sentence for a machine whose side another machine's edge already holds and- that has no way in of its own; "" otherwise."""++ that has no way in of its own; "" otherwise, and "" for a holder with no link now, which gives way."""+ entry = _entry(settings, peer) or {}+ side = entry.get("side")+ if side not in EDGES or has_way(settings, peer):+ return ""- holder = _side_holder(settings, peer)++ holders = _side_holders(settings, peer, live)++ holder = holders[0] if holders else None+ if holder is None:+ return ""+ peers = settings["peers"]+ name = peerlist.label_for(peers, peer_id=peer) or peerlist.UNNAMED+ other = peerlist.label_for(peers, peer_id=holder) or peerlist.UNNAMED+ return (f"{name} has no way in: {other} already leads from the {side} edge of {here}. Give each its own "+ "thirds of that edge under Part of the edge, or move one to another side.")+++def no_way_back_sentence(settings: dict, peer: str) -> str:+ """The Crossing page's sentence for a machine that said, in its `arrangement`, that none of its+ zones leads to this one; "" otherwise."""+ entry = _entry(settings, peer) or {}+ if entry.get("way_back") is not False:+ return ""+ name = peerlist.label_for(settings["peers"], peer_id=peer) or peerlist.UNNAMED+ other_id = entry.get("way_back_by")+ other_bytes = _id_bytes(other_id)+ if other_bytes is not None and other_bytes != _id_bytes(settings.get("machine_id")):+ other = peerlist.label_for(settings["peers"], peer_id=other_id) or "another machine"+ side = entry.get("side")+ facing = return_edge.OPPOSITE[side] if side in EDGES else None+ where = f" on its {facing} too" if facing else " too"+ return (f"{name} has {other}{where}, so none of its edges leads back here. On {name}'s Crossing page, "+ "share that side by thirds or move one of them.")+ return f"{name} has no way back to this machine: none of its edges leads here. Its own Crossing page says why."+++def way_back_by(settings: dict, peer: str) -> Optional[str]:+ """The machine whose active edge or part zone holds `peer`'s side here, when no way leads to it."""+ return _side_holder(settings, peer) if not has_way(settings, peer) else None+++def way_back_state(settings: dict) -> dict:+ """What this machine tells every zoned peer about its way back, keyed by peer id."""+ return {entry["id"]: (has_way(settings, entry["id"]), way_back_by(settings, entry["id"]))+ for entry in settings["peers"] if _zoned(entry)}+++def _side_holder(settings: dict, peer: str) -> Optional[str]:+ """The first active edge or part zone holding `peer`'s side, in zone order."""+ holders = _side_holders(settings, peer)+ return holders[0] if holders else None++- def _side_holders(settings: dict, peer: str) -> list:- """Every machine with an active edge or part zone over `peer`'s side, in zone order."""++def _side_holders(settings: dict, peer: str, live: Optional[Callable[[str], bool]] = None) -> list:++ """Every machine with an active edge or part zone over `peer`'s side, in zone order; with `live`,++ only those with a link up now."""+ entry = _entry(settings, peer) or {}+ side = entry.get("side")+ if side not in EDGES:+ return []+ sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}+ stretches = {(side, part) for part in PARTS}+ holders = []+ for zone in settings["zones"]:+ owner = zone.get("peer")+ if (owner != peer and owner not in holders and zone.get("off") is not True- and zone.get("kind") in ("edge", "part") and _stretch(zone, sides) & stretches):++ and zone.get("kind") in ("edge", "part") and _stretch(zone, sides) & stretches++ and (live is None or live(owner))):+ holders.append(owner)+ return holders++- def settle(settings: dict, peer: str, here: str) -> list:++def settle(settings: dict, peer: str, here: str, live: Optional[Callable[[str], bool]] = None) -> list:+ """After a machine's side moved here: its zones that now clash with another machine's are turned- off, as when the side arrives from that machine, and a sentence for each is returned."""++ off, as when the side arrives from that machine, and a sentence for each is returned. With++ `live`, a machine with no link now gives way instead (`give_way`)."""+ entry = _entry(settings, peer)- return _turn_off_clashes(settings, entry, here) if entry is not None else []++ return _turn_off_clashes(settings, entry, here, live) if entry is not None else []++++++def give_way(settings: dict, peer: str, here: str, live: Optional[Callable[[str], bool]]) -> list:++ """Sets aside every zone in use of a machine with no link now (`live(id)` false) that covers a++ stretch one of `peer`'s zones in use covers, and returns a sentence for each. The zone is `off`++ and carries `aside`: a machine with its lid shut is not gone, so `settle_presence` puts the zone++ back when it connects, and turns it off for good only when it is found to have removed this one++ (06-10-2026). Nothing without `live`."""++ if live is None:++ return []++ sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}++ wanted = set()++ for zone in settings["zones"]:++ if zone.get("peer") == peer and zone.get("off") is not True:++ wanted |= _stretch(zone, sides)++ peers = settings["peers"]++ name = peerlist.label_for(peers, peer_id=peer) or peerlist.UNNAMED++ notices = []++ for zone in settings["zones"]:++ owner = zone.get("peer")++ if owner == peer or zone.get("off") is True or not (_stretch(zone, sides) & wanted) or live(owner):++ continue++ zone["off"] = True++ zone["aside"] = True++ other = peerlist.label_for(peers, peer_id=owner) or peerlist.UNNAMED++ notices.append(f"{other} is not connected, so {name} takes that part of {here}'s screen for now and "++ f"{other}'s {KIND_WORDS.get(zone.get('kind'), 'zone')} is set aside until it connects.")++ return notices++++++def presence_due(settings: dict, live: Callable[[str], bool], gone: Callable[[str], bool]) -> bool:++ """Whether `settle_presence` would change anything now: a zone is set aside (`give_way`) for a++ machine that has connected, or has removed this pairing, since."""++ if not any(zone.get("aside") is True for zone in settings["zones"]):++ return False++ probe = copy.deepcopy(settings)++ settle_presence(probe, "", live, gone)++ return probe != settings++- def _turn_off_clashes(settings: dict, entry: dict, here: str) -> list:++def settle_presence(settings: dict, here: str, live: Callable[[str], bool], gone: Callable[[str], bool]) -> list:++ """What became of the zones `give_way` set aside, as the links stand now: a machine with a link++ up has its zone back unless another zone in use covers that stretch (then it stays off, as when two++ machines that are both here want one stretch, and the Crossing page offers the thirds), and a machine++ `gone(id)` says has removed this pairing keeps its zone off for good. Returns a sentence for each++ zone it settled, apart from those put back; settings change in place."""++ sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}++ peers = settings["peers"]++ notices = []++ for zone in settings["zones"]:++ if zone.get("aside") is not True:++ continue++ owner = zone.get("peer")++ if zone.get("off") is not True:++ del zone["aside"]++ continue++ name = peerlist.label_for(peers, peer_id=owner) or peerlist.UNNAMED++ word = KIND_WORDS.get(zone.get("kind"), "zone")++ if gone(owner):++ del zone["aside"]++ notices.append(f"{name} no longer has this pairing, so its {word} stays off. Remove {name} here and "++ "pair the two again.")++ elif live(owner):++ del zone["aside"]++ stretch = _stretch(zone, sides)++ holder = next((other.get("peer") for other in settings["zones"] if other is not zone++ and other.get("off") is not True and _stretch(other, sides) & stretch), None)++ if holder is None:++ del zone["off"]++ else:++ held = peerlist.label_for(peers, peer_id=holder) or peerlist.UNNAMED++ notices.append(f"{name} is connected again, but {held} leads from that part of {here}'s screen, so "++ f"{name}'s {word} stays off. Share the side on the Crossing page.")++ return notices++++++def gone_sentence(settings: dict, peer: str, here: str, gone: Callable[[str], bool]) -> str:++ """The Crossing page's sentence for a machine that has removed this pairing, "" for any other."""++ if not gone(peer):++ return ""++ name = peerlist.label_for(settings["peers"], peer_id=peer) or peerlist.UNNAMED++ if has_way(settings, peer):++ return (f"{name} no longer has this pairing. If another machine takes its side, {here} gives it up. "++ f"Remove {name} here and pair the two again.")++ return f"{name} no longer has this pairing, so it has no way in. Remove {name} here and pair the two again."++++++def _turn_off_clashes(settings: dict, entry: dict, here: str, live: Optional[Callable[[str], bool]] = None) -> list:++ notices = give_way(settings, entry.get("id"), here, live)+ sides = {item.get("id"): item.get("side", "") for item in settings["peers"]}+ peers = settings["peers"]+ covered = {}+ mine = []+ for zone in settings["zones"]:+ if zone.get("off") is True:+ continue+ if zone.get("peer") == entry.get("id"):+ mine.append(zone)+ continue+ for stretch in _stretch(zone, sides):+ covered.setdefault(stretch, zone.get("peer"))- notices = []+ name = peerlist.label_for(peers, peer_id=entry.get("id")) or peerlist.UNNAMED+ for zone in mine:+ stretch = _stretch(zone, sides)+ other = next((covered[item] for item in sorted(stretch) if item in covered), None)+ if other is None:+ for item in stretch:+ covered.setdefault(item, entry.get("id"))+ continue+ zone["off"] = True+ other_name = peerlist.label_for(peers, peer_id=other) or peerlist.UNNAMED+ notices.append(f"{other_name} and {name} now lead from the same part of {here}'s screen, so {name}'s "+ f"{KIND_WORDS.get(zone.get('kind'), 'zone')} is off.")+ return notices+++def _sendable(entry: dict) -> bool:+ return bool(entry.get("id")) and entry.get("in_use", True) is True and entry.get("send") is True and entry.get("port") != 0+++def shortcut_peer(peers: list, last: Optional[str], ready: Callable[[str], bool]) -> Optional[str]:+ """The machine the shortcut, the Send button and the tray send this machine's input to: the one- it was last on while that one can take it, else the first in the list that can, else the first- this machine sends to at all, so the refusal or the wake names it. Never a machine this one does- not send to, a phone, or an entry with no id yet. `ready(id)` says whether one can take input now."""++ it was last on while that one can take it, else the first in the list that can, else the one it++ was last on, else the first this machine sends to at all, so the refusal or the wake names it: a++ stale entry higher in the list must not take the shortcut from the machine just used (06-10-2026).++ Never a machine this one does not send to, a phone, or an entry with no id yet. `ready(id)` says++ whether one can take input now."""+ candidates = [entry["id"] for entry in peers if _sendable(entry)]+ if last in candidates and ready(last):+ return last- return next((ident for ident in candidates if ready(ident)), candidates[0] if candidates else None)++ fallback = last if last in candidates else (candidates[0] if candidates else None)++ return next((ident for ident in candidates if ready(ident)), fallback)+++def missing_pairings(settings: dict, peer: str) -> list:+ """The machines that may drive this one and that a zone to `peer` cannot take onward, because+ they are not paired with `peer` (section 5, "What the Crossing page may offer"). A machine is+ judged only once it has linked, since its `paired` list arrives on a link."""+ return [entry for entry in settings["peers"]+ if entry.get("id") != peer and entry.get("in_use", True) is True and entry.get("allow_drive") is True and entry.get("linked") is True+ and peer not in (entry.get("paired_with") or [])]+++def missing_sentence(settings: dict, peer: str, here: str) -> str:+ """The Crossing page's sentence for `missing_pairings`, "" when there are none."""+ missing = missing_pairings(settings, peer)+ if not missing:+ return ""+ peers = settings["peers"]+ names = [peerlist.label_for(peers, peer_id=entry.get("id")) or peerlist.UNNAMED for entry in missing]+ target = peerlist.label_for(peers, peer_id=peer) or peerlist.UNNAMED+ drivers = names[0] if len(names) == 1 else ", ".join(names[:-1]) + " or " + names[-1]+ if len(names) == 1:+ why = f"{names[0]} is not paired with {target}"+ elif len(names) == 2:+ why = f"neither is paired with {target}"+ else:+ why = f"none of them is paired with {target}"+ return f"While {drivers} drives {here}, this way to {target} does nothing: {why}. Pair them to use it from there too."diff --cc docs/flatpak-build.mdindex 4053069,0000000..c142fecmode 100644,000000..100644--- a/docs/flatpak-build.md+++ b/docs/flatpak-build.md@@@ -1,55 -1,0 +1,55 @@@+# Build Beamer's Linux Flatpak+- Linux support in Beamer 1.5.0 is experimental. The Flatpak has been built and installed on an aarch64 Fedora 44 machine, and its Wayland back ends pass an automated test in a headless GNOME session. The normal window and tray, a physical mouse and keyboard, and pairing with a Mac or Windows PC have not yet been tested on a real Linux desktop, and neither has an x86_64 build. Please tell us how it goes.++Linux support in Beamer 1.5 is experimental. Each release from 1.5.1 carries an x86_64 Flatpak; this page is for building it yourself, or for another architecture. On one Fedora 44 GNOME desktop under Wayland, paired with a Mac and with a Windows PC, the window and tray, pairing, crossing both ways, typing and the clipboard work; there, crossings show no edge animation on the Linux machine and the selected option in settings is not filled in. X11 on real hardware has not been tested. Please tell us how it goes.++The app ID is `uk.co.kalkman.beamer`, matching the existing app's bundle identifier. The manifest uses PySide BaseApp 6.11 (PySide 6.11.2) and KDE Platform/SDK 6.11. Python modules and libei 1.6.0 are pinned, downloaded with SHA-256 verification and built offline. The KDE runtime already provides libxcb and libxkbcommon, including its X11 library.++## Fedora++From this repository's root on Fedora:++```bash+sudo dnf install -y flatpak flatpak-builder+flatpak remote-add --user --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo+bash tools/build_flatpak.sh x86_64+flatpak install --user -y "dist/flatpak/x86_64/Beamer-$(cat VERSION)-x86_64.flatpak"+flatpak run --env=XDG_SESSION_TYPE=wayland --command=python3 uk.co.kalkman.beamer /app/share/beamer/tools/flatpak_import_probe.py+flatpak run --env=XDG_SESSION_TYPE=x11 --command=python3 uk.co.kalkman.beamer /app/share/beamer/tools/flatpak_import_probe.py+```++The script installs the SDK, runtime and BaseApp from Flathub automatically. No host Python, pip, compiler, development libraries or pip generator is needed. Omit the architecture argument to build for the current machine. The output, build repository and builder cache are gitignored. The bundle is the app, not the KDE runtime; installing it needs Flathub and downloads the runtime if absent. Rebuilding uses the checked-in `VERSION` without changing Mac or Windows build numbers.++Flatpak **1.18.2 has a BaseApp/SELinux build regression**, [upstream issue #6818](https://github.com/flatpak/flatpak/issues/6818), fixed in [1.18.3](https://github.com/flatpak/flatpak/releases/tag/1.18.3). The script refuses 1.18.2 rather than changing SELinux. If Fedora still supplies 1.18.2, update it first. On 03-10-2026, Fedora 44's updates-testing repository supplies released Flatpak 1.18.4:++```bash+sudo dnf --enablerepo=updates-testing upgrade -y flatpak flatpak-selinux+bash tools/build_flatpak.sh x86_64+```++The build disables rofiles-fuse, so no host FUSE setup is needed; Flatpak's build and application sandboxes remain enabled.++## Run on the real desktop++```bash+flatpak run uk.co.kalkman.beamer+```++The manifest grants Wayland, fallback X11, network, shared IPC and graphics rendering. RemoteDesktop, InputCapture and Clipboard use `org.freedesktop.portal.Desktop`, which [Flatpak already permits on its filtered D-Bus](https://docs.flatpak.org/en/latest/sandbox-permissions.html#d-bus-access). Qt's tray additionally needs `org.kde.StatusNotifierWatcher`, as its [upstream implementation](https://github.com/qt/qtbase/blob/6.11/src/gui/platform/unix/dbusmenu/qdbusmenuconnection.cpp) shows. The inherited KDE config-file and unrelated bus grants are removed. It grants no host filesystem, input devices, unrestricted device access or unrestricted session bus.++Start at sign-in is currently disabled: this Python installation is not a frozen executable, and the existing XDG autostart backend returns no installed executable. A future Flatpak implementation needs the [Background portal](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Background.html); granting host config access would not fix it.++## Installed Wayland proof++The proof additionally needs GNOME Shell, xdg-desktop-portal-gnome, wl-clipboard, D-Bus tools and the system Python's GTK 4/PyGObject. Those are test tools, not build or app dependencies. It creates its own headless GNOME session and leaves the real desktop alone.++```bash+bash tools/flatpak_wayland_proof.sh+```++This wraps the existing `tools/wayland_proof.sh`. Its proof Python, Beamer modules, PySide, PyNaCl, jeepney and libei run inside the installed Flatpak. The compositor, portal services, GTK observer and wl-copy/wl-paste are external peers on the guest. Temporary per-run permissions let the harness drive Mutter, spawn those peers and share their observation files; they do not change the installed manifest or persist overrides. This is a backend integration proof, not a test of the normal Beamer window or pairing flow.++For the source comparison, using a Linux venv with `win_app/requirements-linux.txt`:++```bash+PYTHON="$HOME/venv/bin/python" bash tools/wayland_proof.sh+```diff --cc mac_app/kvm_bridge_app.pyindex be6d856,6dd0e4d..cdc6870--- a/mac_app/kvm_bridge_app.py+++ b/mac_app/kvm_bridge_app.py@@@ -19,16 -21,13 +19,17 @@@ from PyObjCTools import AppHelpesys.path.insert(0, str(Path(__file__).resolve().parent.parent))+import bridgeimport config as config_moduleimport crossing-import return_edge+from core import return_edgeimport desktop_mac-import effects++from core import crash_log+from core import effects+from core.locale import americaniseimport effects_overlayimport gestures+import hardware_macimport ignored_titlesimport keyboard_layoutimport notch_beam@@@ -235,6 -226,6 +236,7 @@@ class GestureOverlay"""SIZE = 400.0++ PANEL_ALPHA = 1.0 / 255.0def __init__(self, controller, logger):self.controller = controller@@@ -278,7 -269,7 +280,9 @@@panel.setLevel_(AppKit.NSStatusWindowLevel)panel.setOpaque_(False)panel.setHasShadow_(False)-- panel.setBackgroundColor_(AppKit.NSColor.colorWithCalibratedWhite_alpha_(0.0, 0.02))++ # The faintest fill there is, one step in 255: a clear window lets events through to the app++ # beneath, and 0.02 darkened a 400-point square round the pointer enough to read as a grey box.++ panel.setBackgroundColor_(AppKit.NSColor.colorWithCalibratedWhite_alpha_(0.0, self.PANEL_ALPHA))panel.setIgnoresMouseEvents_(False)panel.setCollectionBehavior_(AppKit.NSWindowCollectionBehaviorCanJoinAllSpaces)view = _GestureCaptureView.alloc().initWithFrame_(@@@ -1565,181 -1286,17 +1569,182 @@@ class ControlWindow(AppKit.NSObject))resistance = self.resistance_ruler.valueself.resistance_numeral.set(str(resistance))- self.push_strip.show(resistance / 500.0, link_state.peer_name(self.controller.cfg))+ self.push_strip.show(resistance / 500.0, self._chosen_label())+ side = self.edge_select.valueself.resistance_hint.set(- "Switches the moment the pointer touches the edge."+ "Switches the moment this Mac's pointer touches the edge. Each screen supplies its own zones."if resistance == 0- else "How far to push past the edge before it gives. It applies as you drag, and lights the "- f"{self.edge_select.value} edge of this screen so you can feel the size of it."+ else "Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones. "+ f"This screen's {side} edge lights to show the resistance."+ if side+ else "Follows this Mac's mouse or trackpad on every screen; each screen supplies its own zones.")self.modifier_note.set({- "semantic": "Command arrives on Windows as Control, so Command-C copies there too, and Control arrives as the Windows key.",- "positional": "Each key arrives as the key in its place, so Command arrives as the Windows key.",- }.get(self.modifier_select.value, "Custom: the key map in config.json is kept as it is."))+ "semantic": "On a PC, Command arrives as Control, so Command-C copies there too, and Control arrives as the Windows key. "+ "Between two Macs every key arrives as itself.",+ "positional": "On a PC, each key arrives as the key in its place, so Command arrives as the Windows key. "+ "Between two Macs every key arrives as itself.",+ }.get(self.modifier_select.value, "Custom: the key map in settings.json is kept as it is."))++ @objc.python_method+ def _load_ways(self, flat=None):+ """The chosen machine's ways into the page's controls, from the settings (core/ways.py);+ with nothing active, from `flat`, the crossing settings as 1.4.x kept them. A chosen machine+ no longer paired or in use gives way to the first active machine."""+ settings = self.settings_store.current()+ peers = peerlist.desktops(settings["peers"])+ available = [entry for entry in peers if entry.get("in_use", True) is True]+ if self.chosen_peer not in {entry["id"] for entry in available}:+ self.chosen_peer = available[0]["id"] if available else None+ if self.chosen_peer is None:+ flat = flat or self.controller.cfg.crossing+ held = {"side": flat["edge"], "methods": flat["methods"], "parts": flat["edge_parts"], "corner": flat["corner"]}+ else:+ held = core_ways.ways(settings, self.chosen_peer)+ self.edge_select.value = pages.shown_side(held["side"], len(peers))+ for name in core_ways.KIND_WORDS:+ self.method_boxes[name].value = name in held["methods"]+ for name, tile in self.part_boxes.items():+ tile.value = name in held["parts"]+ self.corner_select.value = held["corner"]+ self._show_machines()++ @objc.python_method+ def _show_machines(self):+ """The machine picker, shown with more than one machine paired and built again when the+ machines or their names change, and the words on the page that name the chosen one."""+ settings = self.settings_store.current()+ peers = peerlist.desktops(settings["peers"])+ available = [entry for entry in peers if entry.get("in_use", True) is True]+ if self.chosen_peer not in {entry["id"] for entry in available} and (available or self.chosen_peer is not None):+ self._load_ways()+ self._reflect()+ return+ labels = peerlist.labels(peers)+ choices = [(entry["id"], self._shown(labels[entry["token"]])) for entry in peers+ if entry.get("in_use", True) is True]+ several = len(choices) > 1+ if choices != self._picker_choices:+ self._picker_choices = choices+ for view in list(self.machine_row.arrangedSubviews()):+ self.machine_row.removeArrangedSubview_(view)+ view.removeFromSuperview()+ self.machine_select = None+ if several:+ self.machine_select = widgets.Segmented(choices, columns=min(len(choices), 4), on_change=self._machine_picked)+ widgets.add(self.machine_row, widgets.field_row("Machine", self.machine_select.view)[0])+ motion.set_hidden(self.machine_row, not several)+ if self.machine_select is not None and self.machine_select.value != self.chosen_peer:+ self.machine_select.value = self.chosen_peer+ label = self._chosen_label() if several else None+ self.ways_heading.setStringValue_(f"Ways from this screen to {self._chosen_label()}" if self.chosen_peer else "Ways from this screen")+ caption = pages.where_caption(label)+ if self.edge_caption.text != caption:+ self.edge_caption.set(caption)+ self.edge_select.view.setAccessibilityLabel_(caption)+ self.edge_note.set(pages.notch_or_corner_note(label))+ chosen = self.chosen_peer- offer = core_ways.share_offer(settings, chosen) if chosen else None++ offer = core_ways.share_offer(settings, chosen, self._live) if chosen else None+ holders = [self._shown(peerlist.label_for(peers, peer_id=peer) or peerlist.UNNAMED)+ for peer in offer["holders"]] if offer else []+ identity = (offer["side"], tuple(offer["holders"]), tuple(offer["thirds"].items())) if offer else None+ if identity != getattr(self, "_share_identity", None):+ self._share_identity = identity+ self.share_thirds = dict(offer["thirds"]) if offer else {}+ motion.set_hidden(self.share_box, offer is None)+ if offer:+ side = offer["side"]+ self.share_title.set(f"Share the {side} edge")+ self.share_sentence.set(pages.share_sentence(holders, side, self._chosen_label()))+ self.share_button.set_title(f"Share the {side} edge")+ self.share_recipients = [chosen, *offer["holders"]]+ for part, tile in self.share_tiles.items():+ tile.name.set(pages.part_names(side)[part])+ owner = self.share_thirds[part]+ tile.set_detail(self._shown(peerlist.label_for(peers, peer_id=owner) or peerlist.UNNAMED))+ tile.value = owner == chosen+ self.share_button.set_enabled(chosen in self.share_thirds.values())+ for note, sentence in (- (self.blocked_note, core_ways.blocked_sentence(settings, chosen, "this Mac") if chosen and not offer else ""),++ (self.blocked_note, (core_ways.blocked_sentence(settings, chosen, "this Mac", self._live) if chosen and not offer else "")++ or (core_ways.gone_sentence(settings, chosen, "this Mac", self._gone) if chosen else "")),+ (self.missing_note, core_ways.missing_sentence(settings, chosen, "this Mac") if chosen else ""),+ (self.no_way_back_note, core_ways.no_way_back_sentence(settings, chosen) if chosen else "")):+ note.set(self._shown(sentence))+ motion.set_hidden(note.view, not sentence)++ self._show_jump_key()++ @objc.python_method+ def _share_third(self, part):+ """Move one offered third to the next machine without writing until Share is pressed."""+ recipients = self.share_recipients+ current = recipients.index(self.share_thirds[part])+ self.share_thirds[part] = recipients[(current + 1) % len(recipients)]+ self._show_machines()++ @objc.python_method+ def _share_side(self):+ """Apply the proposed split, rebuild the live zones and tell every affected machine."""+ side, thirds = self._share_identity[0], dict(self.share_thirds)+ try:+ changed = self.settings_store.share_side(side, thirds)+ cfg = self.settings_store.load()+ except (SettingsError, ValueError):+ self.logger.exception("The shared side could not be saved")+ return+ self.controller.cfg = cfg+ self.controller.zones_changed()+ for peer in changed:+ self._tell(peer)+ self._load_ways()+ self._reflect()++ @objc.python_method+ def _machine_picked(self, peer):+ # A change still waiting out the pause belongs to the machine being left.+ self._flush()+ self.chosen_peer = peer+ self._load_ways()+ self._reflect()++ @objc.python_method+ def _flush(self):+ """Writes a change still waiting out _changed's pause now, and the pause then writes nothing."""+ if self._save_pending:+ self._apply_serial += 1+ self._apply_settings()++ @objc.python_method+ def _chosen_label(self):+ """What the page calls the chosen machine; with nothing paired, what it always has."""+ peers = self.settings_store.current()["peers"]+ labels = peerlist.labels(peers)+ found = next((labels[entry["token"]] for entry in peers if entry["id"] == self.chosen_peer), None)+ return self._shown(found) if found else link_state.peer_name(self.controller.cfg)++ @objc.python_method+ def _diagram_machines(self, methods):+ """Every machine as the drawing shows it: the chosen one as the controls have it, which may+ be a moment ahead of the settings, the rest as saved."""+ settings = self.settings_store.current()+ peers = peerlist.desktops(settings["peers"])+ live = {+ "side": self.edge_select.value or "",+ "methods": [name for name in methods if name != "shortcut"],+ "parts": [name for name, tile in self.part_boxes.items() if tile.value],+ "corner": self.corner_select.value or "top_right",+ }+ if not peers:+ return [{"key": "", "label": link_state.peer_name(self.controller.cfg), "chosen": True, **live}]+ labels = peerlist.labels(peers)+ machines = []+ for entry in peers:+ chosen = entry["id"] == self.chosen_peer+ held = live if chosen else core_ways.ways(settings, entry["id"])+ machines.append({"key": entry["id"], "label": self._shown(labels[entry["token"]]), "chosen": chosen,+ "side": held["side"], "methods": list(held["methods"]), "parts": list(held["parts"]),+ "corner": held["corner"]})+ return machines@objc.python_methoddef _show_arrangement(self, methods):@@@ -1766,79 -1326,13 +1771,121 @@@@objc.python_methoddef _show_peer(self):- cfg = self.controller.cfg- self.peer.value.set(self._shown(link_state.peer_name(cfg)))- if not cfg.host:+ """The machine the status speaks of (where input is, else where the shortcut would send it), else+ the first one paired: its name and address."""+ entry = self._focus_entry()+ if entry is None:+ self.peer.value.set("—")self.peer_footer.set("Not paired")+ return+ self.peer.value.set(self._shown(self._machine_label()))+ host, port = entry.get("host"), entry.get("port")+ if not host:+ self.peer_footer.set("No address")else:# The port does not fit a third of the status module at the narrow grid.- self.peer_footer.set(self._shown(f"{cfg.host}:{cfg.port}" if self.wide else cfg.host))+ self.peer_footer.set(self._shown(f"{host}:{port}" if self.wide else host))++ @objc.python_method+ def _first_label(self):+ return self.controller.peer_label or "the other machine"++ @objc.python_method+ def _focus_entry(self):+ peers = self.controller.book.peers()+ wanted = self.controller._in_question()+ return next((peer for peer in peers if wanted is not None and peer.get("id") == wanted), peers[0] if peers else None)++ @objc.python_method+ def _machine_label(self):+ """What the window calls the machine its status is about: where input is, else the first."""+ controller = self.controller+ return controller.on_label or controller.peer_label or link_state.peer_name(controller.cfg)+++ @objc.python_method++ def _live(self, peer):++ """Whether `peer` has a link up now, either way. One that has none gives way on the Crossing++ page and to an arrangement (core/ways.py give_way)."""++ link = self.controller._peers_up.get(peer)++ return (link is not None and link.live()) or peer in self.inbound_ids()++++ @objc.python_method++ def _gone(self, peer):++ """Whether `peer` has removed this pairing: the link this Mac dials to it was closed unanswered++ for a minute (core/link.py). Its zones set aside by `give_way` then stay off for good."""++ entry = next((item for item in self.settings_store.current()["peers"] if item.get("id") == peer), None)++ link = self.controller.links.get(entry["token"]) if entry else None++ return link is not None and link.kind == "forgotten"++++ @objc.python_method++ def settle_presence(self):++ """Puts back the zones set aside for a machine that has connected since, and keeps off for good,++ and says so, those of one that has removed this pairing (core/ways.py settle_presence). Run on++ every status tick, whether or not the window is shown."""++ if not core_ways.presence_due(self.settings_store.current(), self._live, self._gone):++ return++ self._flush()++ before = core_ways.way_back_state(self.settings_store.current())++ try:++ changed, notices = self.settings_store.settle_presence(self._live, self._gone)++ cfg = self.settings_store.load() if changed else None++ except SettingsError:++ self.logger.exception("could not settle the zones set aside")++ return++ if not changed:++ return++ self.controller.cfg = cfg++ self.controller.zones_changed()++ for notice in notices:++ self.controller._alert("Beamer", notice)++ self._load(config_to_raw(cfg))++ self.refresh()++ for target, state in core_ways.way_back_state(self.settings_store.current()).items():++ if before.get(target) != state:++ self._tell(target)+++ @objc.python_method+ def inbound_ids(self):+ """The ids of the machines that have a link up to this Mac."""+ windows_input = self.windows_input+ if windows_input is None:+ return set()+ return {protocol.id_text(peer) for peer in windows_input.server.links()}++ @objc.python_method+ def _follow_first_peer(self):+ """A pairing stored from the pairing service's thread can change which machine the flat+ settings read; until the controller has them, a save from this window would write the old+ first machine back over it."""+ peers = self.controller.book.peers()+ desktop = peerlist.first_desktop(peers)+ first = desktop["token"] if desktop is not None else ""+ if first != (self.controller.cfg.auth_token or ""):+ self.peers_changed()++ @objc.python_method+ def peers_changed(self):+ """A machine was paired or removed: the controller reads the settings again (without+ `update_config`, which would bring input home), the links follow the peers, and the+ address fields show the first machine. A change still waiting out the pause is written+ first: the page reloads from the settings below, which would otherwise drop it."""+ self._flush()+ try:+ cfg = self.settings_store.load()+ except SettingsError as exc:+ self.logger.warning("settings not read after the peers changed: %s", exc)+ return+ peer_ids = {entry.get("id") for entry in self.settings_store.current()["peers"]}+ if cfg.design_follow_peer and cfg.design_follow_peer not in peer_ids:+ raw = config_to_raw(cfg)+ raw["design_follow_peer"] = ""+ cfg = self.settings_store.save(raw)+ self.controller.peers_changed()+ self.controller.apply_settings(cfg)+ if self.windows_input is not None:+ self.windows_input.sync(cfg)+ self._load(config_to_raw(cfg))+ self.refresh()@objc.python_methoddef _shown(self, text):@@@ -3404,108 -2491,35 +3451,109 @@@if self.previews is not None:# The tiles' renderers read the colour from the applied settings, which land only now.self.previews.repaint()- if moved and self.windows_input is not None:- self.windows_input.send_arrangement(- cfg.crossing["edge"], cfg.crossing.get("arrangement_set_at", 0)- )- self._say("Saved. Changes apply as you make them.", "ink_2")+ if shared:+ self._send_same()+ elif design_changed:+ self._send_same()+ self._refresh_design_follow()+ if self._write_ways():+ self._say("Saved. Changes apply as you make them.", "ink_2")@objc.python_method- def apply_arrangement(self, mac_edge, set_at):- """Windows changed which edge of this Mac leads to it. Applied here- rather than at either link, because this is the side that owns the- settings file. An arrangement older than this Mac's own is ignored:- both ends stamp their changes, and the newer one stands."""- if mac_edge == self.controller.cfg.crossing.get("edge"):- return- mine = self.controller.cfg.crossing.get("arrangement_set_at", 0)- if mine and not protocol.arrangement_wins(set_at, mine):- self.logger.info("ignoring an older arrangement from the PC (%s vs %s)", set_at, mine)+ def _write_ways(self):+ """The chosen machine's side and zones from the page's controls (core/ways.py), the engine+ built again from them, and every machine whose way back changed told, along with the chosen+ machine when its side or way changed. False, with the store's sentence said and the controls+ back at what is saved, when the store refuses them."""+ peer = self.chosen_peer+ current = self.settings_store.current()+ if peer not in {entry["id"] for entry in current["peers"]}:+ # None chosen, or one removed while its change waited: nothing of its to write.+ return True+ side = self.edge_select.value or ""+ methods = [name for name in core_ways.KIND_WORDS if self.method_boxes[name].value]+ parts = [name for name, tile in self.part_boxes.items() if tile.value] or ["middle"]- offer = core_ways.share_offer(current, peer)++ offer = core_ways.share_offer(current, peer, self._live)+ occupied = {part for part, owner in offer["thirds"].items() if owner in offer["holders"]} if offer else set()+ if offer and side == offer["side"] and (+ "edge" in methods or "part" in methods and occupied.intersection(parts)):+ self._load_ways()+ self._reflect()+ self.window.makeFirstResponder_(self.share_button.view)+ return False+ before = core_ways.way_back_state(current)+ had_way = core_ways.has_way(current, peer)+ try:+ moved = self.settings_store.set_ways(+ peer, side=side, corner=self.corner_select.value,- methods=methods, parts=parts)++ methods=methods, parts=parts, live=self._live)+ cfg = self.settings_store.load()+ except SettingsError as exc:+ self._say(str(exc), "fault")+ self._load_ways()+ self._reflect()+ return False+ # Straight onto the controller rather than through apply_settings, which would send the+ # first machine's side a second time when that is the machine chosen.+ self.controller.cfg = cfg+ self.controller.zones_changed()+ if moved:+ # A side moved onto another machine's turns this machine's ways there off: show what was kept.+ self._load_ways()+ self._reflect()+ updated = self.settings_store.current()+ changed_peers = [target for target, state in core_ways.way_back_state(updated).items()+ if before.get(target) != state]+ if moved or core_ways.has_way(updated, peer) != had_way:+ changed_peers.append(peer)+ for target in dict.fromkeys(changed_peers):+ self._tell(target)+ return True++ @objc.python_method+ def _tell(self, peer):+ """This Mac's side for `peer` as held, with whether a way leads there (WIRE.md section 8), over+ this Mac's link to it, else the one it opened here. Nothing while no side is set."""+ entry = next((item for item in self.settings_store.current()["peers"] if item["id"] == peer), None)+ if entry is None or entry.get("side") not in crossing.EDGES:return- raw = config_to_raw(self.controller.cfg)- raw["crossing"] = {**raw["crossing"], "edge": mac_edge, "arrangement_set_at": int(set_at)}+ side, at, by = entry["side"], entry.get("side_set_at", 0), entry.get("side_by") or None+ if not self.controller.send_arrangement(peer, side, at, by) and self.windows_input is not None:+ self.windows_input.send_arrangement(peer, side, at, by)++ @objc.python_method+ def apply_arrangement(self, peer, edge, set_at, by, way_back=None, way_back_by=None):+ """A machine changed which of its edges faces this Mac (`edge` is its own). Applied here+ rather than at either link, because this is the side that owns the settings file; kept only+ when newer than the side held for that machine, a tie going to the larger `by` (WIRE.md+ section 8). A side that would put two machines' zones over one stretch turns that machine's+ clashing zones off, and says so. `way_back` is kept whatever the side; a message that changed+ anything here is answered with this Mac's own, so that machine learns at once whether a way+ leads back to it, and one that changed nothing is not, so two machines never answer in turn."""+ # A change still waiting out the pause is written first: the page reloads from the+ # settings below, which would otherwise drop it.+ self._flush()+ before = core_ways.way_back_state(self.settings_store.current())try:- changed, notices = self.settings_store.arrangement(peer, edge, set_at, by, way_back, way_back_by)- cfg = self.settings_store.save(raw)++ changed, notices = self.settings_store.arrangement(peer, edge, set_at, by, way_back, way_back_by,++ live=self._live)+ cfg = self.settings_store.load() if changed else Noneexcept (SettingsError, TypeError, ValueError):- self.logger.exception("could not save the arrangement the PC sent")+ self.logger.exception("could not save the arrangement %s sent", peer)+ return+ if not changed:returnself.controller.cfg = cfg- self.controller.crossing = crossing.CrossingEngine.from_config(cfg.crossing)- self.logger.info("the PC moved the crossing to this Mac's %s edge", mac_edge)+ self.controller.zones_changed()+ for notice in notices:+ self.controller._alert("Beamer", notice)+ self.logger.info("%s's arrangement: this Mac's %s edge", peer, crossing.OPPOSITE[edge])+ self._load(config_to_raw(cfg))self.refresh()+ changed_peers = [target for target, state in core_ways.way_back_state(self.settings_store.current()).items()+ if before.get(target) != state]+ for target in dict.fromkeys([*changed_peers, peer]):+ self._tell(target)def quitApp_(self, _sender):self.quit_handler()@@@ -3919,6 -3087,6 +3967,7 @@@ class TrayApp(rumps.App)def refresh_status(self, _timer):self.windows_input.sync(self.controller.cfg)++ self.control_window.settle_presence()self.measure_notch()if self.control_window.window.isVisible():self.control_window.refresh()@@@ -4117,6 -3206,6 +4166,10 @@@def _crossing_feedback_main(self, kind, step):try:++ if kind in ("home", "arrive"):++ # Input is home: the gesture panel goes now, not on the next status tick up to 0.4 s++ # later, when it would still sit over the landing animation and take the first click.++ self.gesture_overlay.sync()if kind == "home":self._show_landing(step.pin[0], step.pin[1])return@@@ -4258,6 -3347,6 +4311,7 @@@ def main(argv=None)AppKit.NSApplication.sharedApplication()theme.init_fonts()logger = configure_logging()++ crash_log.install(LOG_DIRECTORY, logger)# Which faces actually carried the window: the only way to tell the bundled copies failed to# register is to say what was used instead.logger.info("type: %s / %s", theme.sans(), theme.mono())diff --cc mac_app/link_state.pyindex 4de1098,272623f..597b816--- a/mac_app/link_state.py+++ b/mac_app/link_state.py@@@ -78,21 -76,23 +78,23 @@@ def describe(controller) -> LinkStatevia = " through the macOS 27 tunnel" if tunnel else ""return LinkState("mac", INK, "On Mac", linked, f"Connected to {peer}{via}.", SIGNAL)if not (cfg.host and cfg.auth_token):- return LinkState("unpaired", AMBER, "Not paired", "Setup", "Pair with a PC on Overview and Beamer connects on its own.", AMBER)+ return LinkState("unpaired", AMBER, "Not paired", "Setup", "Pair a machine on Overview and Beamer connects on its own.", AMBER)address = f"{cfg.host} port {cfg.port}"- if status == AUTH_FAILED_STATUS:- return LinkState("token", FAULT, "Token mismatch", "Refused", f"{peer} refused this Mac's shared token. Pair again to write a fresh one.", FAULT)- if status == OLD_RECEIVER_STATUS or status.startswith("Windows receiver speaks Beamer protocol"):++ if kind == "forgotten":++ return LinkState("forgotten", FAULT, "Pairing removed", "Refused", f"{peer} no longer has this pairing: remove {peer} here and pair the two again.", FAULT)+ if kind in ("unauthenticated", "wrong_id", "different", "unreadable"):+ return LinkState("token", FAULT, "Token mismatch", "Refused", f"{peer} refused this Mac's token. Remove it, then pair again to write a fresh one.", FAULT)+ if kind in ("older", "newer", "not_beamer"):return LinkState("version", FAULT, "Version mismatch", "Refused", f"{peer} runs a different Beamer from this Mac. Update both to the same version.", FAULT)- if status.startswith("Windows rejected the connection"):- return LinkState("rejected", FAULT, "Refused", "Refused", status + ".", FAULT)- if status == NOT_WOKEN_STATUS:+ if status.endswith(NOT_WOKEN_SUFFIX):return LinkState("not_woken", FAULT, "Did not wake", "No reply", f"{peer} did not answer within a minute of the wake-up packet.", FAULT)- if status.startswith("macOS 27 blocked direct LAN access"):+ if kind == "blocked":return LinkState("blocked", FAULT, "Blocked", "Tunnel", "macOS 27 blocked direct LAN access. Open Beamer Tunnel from Applications.", FAULT)- if status.startswith("Windows is unreachable") or status.startswith("Windows did not answer before"):- return LinkState("unreachable", FAULT, "Unreachable", "No reply", f"{address} is not answering. The PC may be asleep or off this network.", FAULT)- if status.startswith("Windows is reachable, but Beamer is not listening"):- return LinkState("not_listening", FAULT, "Not listening", "No receiver", f"{peer} answers, but Beamer is not listening on port {cfg.port}. Open Beamer on the PC.", FAULT)- if status == "Windows stopped responding":+ if kind in ("unreachable", "timeout"):+ return LinkState("unreachable", FAULT, "Unreachable", "No reply", f"{address} is not answering. {peer} may be asleep or off this network.", FAULT)+ if kind == "refused":+ return LinkState("not_listening", FAULT, "Not listening", "No receiver", f"{peer} answers, but Beamer is not listening on port {cfg.port}. Open Beamer on {peer}.", FAULT)+ if kind in ("stopped", "closed"):return LinkState("stopped", FAULT, "No reply", "Dropped", f"{peer} stopped responding. Beamer keeps trying to reconnect.", FAULT)if status.startswith("Connecting to") or status in ("Waiting to connect", "Settings saved; reconnecting"):return LinkState("waiting", AMBER, "Waiting", "Looking", f"Looking for {peer}. It connects on its own once Beamer is open there.", AMBER, True)diff --cc mac_app/machines.pyindex d992265,0000000..3359b8emode 100644,000000..100644--- a/mac_app/machines.py+++ b/mac_app/machines.py@@@ -1,86 -1,0 +1,86 @@@+"""One row of the Overview's list of machines: its name, where it is, what its link is doing.++Pure, so every state a row can be in is tested against a word. The faults take their sentence from+the link itself (core/link.py words them, naming the machine), so a version 5 machine that closes+the connection reads "Update Beamer on <name> to 1.5.0..." here and nowhere else is it reworded.+"""++from __future__ import annotations++from dataclasses import dataclass++from core import protocol+from link_state import AMBER, FAULT, INK, SIGNAL, LinkState++PLATFORMS = {"windows": "Windows", "macos": "Mac", "linux": "Linux", "ios": "iPhone", "android": "Android"}- TOKEN_KINDS = ("unauthenticated", "wrong_id", "different", "unreadable")++TOKEN_KINDS = ("unauthenticated", "wrong_id", "different", "unreadable", "forgotten")+VERSION_KINDS = ("older", "newer", "not_beamer")+++@dataclass(frozen=True)+class Row:+ token: str+ label: str+ platform: str+ address: str+ state: LinkState+ in_use: bool+ drives: bool+ driven: bool+ phone: bool = False+++def platform_name(platform: str) -> str:+ return PLATFORMS.get(platform, "Other")+++def row(entry: dict, label: str, live: bool, kind: str, status: str, here: bool, driving: bool, inbound: bool,+ has_link: bool) -> Row:+ """`live`, `kind` and `status` are the outbound link's, and `has_link` whether this Mac dials+ the machine at all; `inbound` is whether the machine has a link up to this Mac; `here` and+ `driving` are where input is."""+ host, port = entry.get("host"), entry.get("port")+ address = f"{host} · port {port}" if host and port else "No address"+ return Row(+ entry["token"], label, platform_name(entry.get("platform", "")), address,+ _state(entry, label, live, kind, status, here, driving, inbound, has_link), entry.get("in_use", True) is True,+ entry.get("send") is True, entry.get("allow_drive") is True, port == 0,+ )+++def _state(entry, label, live, kind, status, here, driving, inbound, has_link) -> LinkState:+ if entry.get("in_use", True) is not True:+ return LinkState("not_in_use", AMBER, "NOT IN USE", "NOT IN USE", f"{label} is not in use on this Mac.", AMBER)+ if not protocol.linkable(entry):+ return LinkState(+ "pair_again", AMBER, "Pair again", "Pair again",+ f"{label} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.", AMBER,+ )+ if driving:+ return LinkState(+ "driving", SIGNAL, "Driving this Mac", "Live",+ f"{label}'s keyboard and pointer are on this Mac. Push the pointer back through the edge it arrived by to send them home.",+ SIGNAL,+ )+ if here:+ return LinkState(+ "here", SIGNAL, "Input here", "Live",+ f"This Mac's keyboard and pointer are on {label}. Do the same again to bring them home.", SIGNAL,+ )+ if live or inbound:+ return LinkState("linked", INK, "Linked", "Linked", f"Connected to {label}.", SIGNAL)+ if not has_link:+ return LinkState("waiting", AMBER, "Waiting", "Waiting", f"Waiting for {label} to connect.", AMBER)+ if kind in TOKEN_KINDS:+ return LinkState("token", FAULT, "Refused", "Refused", status, FAULT)+ if kind in VERSION_KINDS or (kind == "closed" and not entry.get("linked")):+ return LinkState("version", FAULT, "Version", "Refused", status, FAULT)+ if kind in ("unreachable", "timeout"):+ return LinkState("unreachable", FAULT, "Unreachable", "No reply", status, FAULT)+ if kind == "refused":+ return LinkState("not_listening", FAULT, "Not listening", "No receiver", status, FAULT)+ if kind == "blocked":+ return LinkState("blocked", FAULT, "Blocked", "Tunnel", status, FAULT)+ if kind in ("stopped", "closed", "failed") and status:+ return LinkState("dropped", FAULT, "Dropped", "Dropped", f"{status.rstrip('.')}. Beamer keeps trying to reconnect.", FAULT)+ return LinkState("waiting", AMBER, "Waiting", "Looking", f"Looking for {label}. It connects on its own once Beamer is open there.", AMBER, True)diff --cc mac_app/settings_store.pyindex f915908,1aa541c..8962798--- a/mac_app/settings_store.py+++ b/mac_app/settings_store.py@@@ -1,21 -1,7 +1,22 @@@+"""The Mac's settings.json (WIRE.md section 1) and the migration from 1.4.x's config.json.++The app above this layer still speaks Config, so the file is read into the shape 1.4.x had, with+the first desktop feeding host and auth_token; settings.json holds the rest (other peers, zones) for the steps+that follow. config.json is only ever read, so a downgrade finds its settings as they were.+"""++import base64+import binascii+import copy+import dataclasses+import hashlibimport json++import loggingimport os+import secretsimport tempfile-from dataclasses import replace+import threading+import timefrom pathlib import Pathimport config as config_module@@@ -32,23 -15,8 +33,25 @@@ from key_codes import KEY_NAME_TO_CODfrom wake import parse_mac++LOGGER = logging.getLogger(__name__)++APP_SUPPORT_DIRECTORY = Path.home() / "Library" / "Application Support" / "Beamer"-DEFAULT_SETTINGS_PATH = APP_SUPPORT_DIRECTORY / "config.json"+DEFAULT_SETTINGS_PATH = APP_SUPPORT_DIRECTORY / "settings.json"+LEGACY_FILE = "config.json"++SCHEMA = 6+MAX_PEERS = 32+# What moves out of `crossing` into the peer and the zones once a peer exists (WIRE.md sections 1 and 8).+MOVED_CROSSING = ("methods", "edge", "edge_parts", "corner", "arrangement_set_at")+ZONE_KINDS = tuple(method for method in METHODS if method != "shortcut")+# Fields settings.json has that Config has no name for; everything else in it is Config's own.+SETTINGS_ONLY = ("schema", "machine_id", "name", "port", "shortcut", "migrated_token_sha256", "peers", "zones", "crossing")+PEER_DEFAULTS = {+ "id": "", "name": "", "platform": "", "token": "", "host": "", "port": 0, "hw": "", "send": True,+ "allow_drive": True, "in_use": True, "side": "", "side_set_at": 0, "side_by": "", "paired_with": [], "paired_at": 0,+ "linked": False, "from_1_4": False, "jump_key": "",+}+class SettingsError(Exception):pass@@@ -152,466 -77,39 +155,482 @@@ def config_to_raw(cfg)}+def _corner_edge(corner):+ """The Mac's corner crossing always left by the corner's left or right edge (crossing.py); only the+ way home used the side, and that is the entry's `side`, not the zone's."""+ return corner.split("_")[1]+++def _zones_for(peer_id, crossing):+ """One zone of each kind for a peer, from the crossing methods 1.4.x had (WIRE.md section 8)."""+ corner = crossing["corner"]+ wanted = [+ {"peer": peer_id, "kind": "edge"},+ {"peer": peer_id, "kind": "part", "parts": list(crossing["edge_parts"])},+ {"peer": peer_id, "kind": "corner", "corner": corner, "edge": _corner_edge(corner)},+ {"peer": peer_id, "kind": "notch"},+ ]+ methods = crossing["methods"]+ for zone in wanted:+ # The whole edge covers its thirds, so both on would be two zones over one stretch.+ if zone["kind"] not in methods or (zone["kind"] == "part" and "edge" in methods):+ zone["off"] = True+ return wanted+++def _apply_zones(zones, peer_id, crossing):+ """Bring the peer's own zone of each kind to the crossing choices, keeping anything else in the list."""+ result = list(zones)+ for new in _zones_for(peer_id, crossing):+ for index, zone in enumerate(result):+ if zone.get("peer") == peer_id and zone.get("kind") == new["kind"]:+ merged = {**zone, **{key: value for key, value in new.items() if key != "off"}}++ merged.pop("aside", None)+ if new.get("off"):+ merged["off"] = True+ else:+ merged.pop("off", None)+ result[index] = merged+ break+ else:+ result.append(new)+ return result+++def _crossing_from_zones(settings, peer):+ """The crossing choices the zones and `shortcut` stand for, read for one peer."""+ mine = {}+ for zone in settings["zones"]:+ if zone.get("peer") == peer["id"] and zone.get("kind") in ZONE_KINDS:+ mine.setdefault(zone["kind"], zone)+ parts = mine.get("part", {}).get("parts")+ corner = mine.get("corner", {}).get("corner")+ return {+ "methods": (["shortcut"] if settings["shortcut"] else [])+ + [kind for kind in ZONE_KINDS if kind in mine and mine[kind].get("off") is not True],+ "edge": peer["side"] or config_module.DEFAULT_CROSSING["edge"],+ "edge_parts": list(parts) if isinstance(parts, list) and parts else list(config_module.DEFAULT_CROSSING["edge_parts"]),+ "corner": corner if corner in CORNERS else config_module.DEFAULT_CROSSING["corner"],+ "arrangement_set_at": peer["side_set_at"],+ }+++def raw_from_settings(settings):+ """settings.json in config.json's shape, with the first desktop standing in for the one PC."""+ raw = {name: copy.deepcopy(value) for name, value in settings.items() if name not in SETTINGS_ONLY}+ crossing = dict(settings["crossing"])+ peer = peerlist.first_desktop(settings["peers"])+ if peer is not None:+ raw.update(+ host=peer["host"], port=peer["port"], auth_token=peer["token"], pc_name=peer["name"],+ mac_address=peer["hw"], send_to_windows=peer["send"], allow_windows_to_drive=peer["allow_drive"],+ )+ crossing.update(_crossing_from_zones(settings, peer))+ else:+ raw.update(+ host="", port=settings["port"], auth_token="", pc_name="", mac_address="",+ send_to_windows=True, allow_windows_to_drive=True,+ )+ raw["crossing"] = crossing+ return raw+++def _entry_from_config(cfg, machine_id):+ """The peer entry a 1.4.x pairing becomes: no id until the first link, and never linked."""+ crossing = cfg.crossing+ stamp = crossing["arrangement_set_at"]+ return {+ "id": "", "name": cfg.pc_name, "platform": "windows", "token": cfg.auth_token, "host": cfg.host,+ "port": cfg.port, "hw": cfg.mac_address, "send": cfg.send_to_windows, "allow_drive": cfg.allow_windows_to_drive,+ "side": crossing["edge"], "side_set_at": stamp, "side_by": machine_id if stamp else "",+ "paired_with": [], "paired_at": 0, "linked": False, "from_1_4": True,+ }+++def _rename_zones(zones, old, new):+ return [{**zone, "peer": new} if zone.get("peer") == old else zone for zone in zones]+++def _merge_config(base, cfg):+ """`base` with `cfg`'s pairing fields in the first desktop and the rest by name."""+ settings = copy.deepcopy(base)+ raw = config_to_raw(cfg)+ machine_id = settings["machine_id"]+ for name, value in raw.items():+ if name not in ("host", "port", "auth_token", "pc_name", "mac_address", "send_to_windows",+ "allow_windows_to_drive", "crossing"):+ settings[name] = value+ settings["shortcut"] = "shortcut" in cfg.crossing["methods"]+ crossing = {name: value for name, value in raw["crossing"].items()}+ peers, zones = settings["peers"], settings["zones"]+ peer = peerlist.first_desktop(peers)+ at = peers.index(peer) if peer is not None else None+ if not cfg.auth_token:+ if at is not None:+ gone = peers.pop(at)+ settings["zones"] = [zone for zone in zones if zone.get("peer") != gone["id"]]+ elif peer is None or peer["token"] != cfg.auth_token:+ entry = _entry_from_config(cfg, machine_id)+ if at is not None:+ zones = _rename_zones(zones, peer["id"], "")+ peers[at] = entry+ else:+ peers.append(entry)+ settings["zones"] = _apply_zones(zones, "", crossing)+ else:+ # A machine's side and zones are written by `set_ways` and `arrangement` only: the flat view+ # mirrors the first machine's, and one read before another machine's arrangement landed+ # would otherwise put the old side back.+ # Its name and hardware address are learnt on its link: written here only with a new address,+ # which clears what was learnt at the old one, or a save from a window read before one was+ # learnt would put the old one back.+ if cfg.host != peer.get("host"):+ peer.update(name=cfg.pc_name, hw=cfg.mac_address)+ peer.update(host=cfg.host, port=cfg.port, send=cfg.send_to_windows, allow_drive=cfg.allow_windows_to_drive)+ settings["crossing"] = {+ name: value for name, value in crossing.items() if not (peerlist.first_desktop(peers) is not None and name in MOVED_CROSSING)+ }+ return settings++class SettingsStore:+ """`path` is settings.json. Given a config.json instead (the name 1.4.x used), the settings go+ beside it and that file is what gets migrated."""+def __init__(self, path=None):- self.path = Path(path).expanduser() if path else DEFAULT_SETTINGS_PATH+ path = Path(path).expanduser() if path else DEFAULT_SETTINGS_PATH+ self.legacy_path = path.with_name(LEGACY_FILE)+ self.path = path.with_name("settings.json") if path.name == LEGACY_FILE else path+ # Held around every change to the file, and by the links around theirs (PeerBook.lock), so+ # an id learnt on a link thread and a save from the window cannot cross.+ self.lock = threading.RLock()+ self._cache = None+ # The token of the first machine in the flat settings last handed out by load() or save(),+ # which is what a window holds until it reads them again.+ self._handed_token = ""++ def current(self):+ """The settings as this process holds them: read once, then kept in step with every save,+ so the links can look at the peers a few times a second without reading the file."""+ with self.lock:+ if self._cache is None:+ self.load_settings()+ return self._cache++ def book(self):+ """A PeerBook over these settings, for the links."""+ return receiver.PeerBook(self.current, self.save_settings, self.lock)def load(self):+ return self._config(self.load_settings())++ def add_peer(self, entry, replaced=None):+ """Stores a pairing (`PairingService`'s `store`): `entry` joins the peers, taking the place+ of `replaced` when there is one. Raises SettingsError, writing nothing, if it cannot be saved."""+ with self.lock:+ settings = copy.deepcopy(self.current())+ if replaced is not None:+ held = next((peer for peer in settings["peers"] if peer["token"] == replaced.get("token")), None)+ # The snapshot `replaced` came from was taken before this lock: it may have changed+ # or gone since (WIRE.md section 6, item 4).+ if held is None or held["id"] != replaced.get("id") or held["linked"] != replaced.get("linked"):+ raise SettingsError("the machine being replaced changed while pairing")+ peerlist.add_peer(settings, entry, replaced)+ self.save_settings(settings)++ def set_peer(self, token, **switches):+ """Turns `send`, `allow_drive` and `in_use` on or off for the machine holding `token`; returns+ its entry, None when no machine holds it."""+ if not switches or any(name not in ("send", "allow_drive", "in_use") or not isinstance(value, bool) for name, value in switches.items()):+ raise SettingsError("only send, allow_drive and in_use can be switched, each on or off")+ with self.lock:+ settings = copy.deepcopy(self.current())+ entry = next((peer for peer in settings["peers"] if peer["token"] == token), None)+ if entry is None:+ return None+ entry.update(switches)+ return copy.deepcopy(next(peer for peer in self.save_settings(settings)["peers"] if peer["token"] == token))++ def set_jump_key(self, peer_id, value, trigger_key):+ """Sets or clears one peer's local jump chord after the shared clash checks."""+ with self.lock:+ settings = copy.deepcopy(self.current())+ entry = next((peer for peer in settings["peers"] if peer["id"] == peer_id), None)+ if entry is None:+ raise SettingsError("that machine is no longer paired with this Mac")+ try:+ entry["jump_key"] = ways.check_jump_key(settings, peer_id, value, trigger_key) or ""+ except ValueError as exc:+ raise SettingsError(str(exc)) from exc+ return copy.deepcopy(next(peer for peer in self.save_settings(settings)["peers"] if peer["id"] == peer_id))++ def remove_peer(self, token):+ """Removes the machine holding `token`, with its zones, and returns its entry; None when+ no machine holds it."""+ with self.lock:+ settings = copy.deepcopy(self.current())+ removed = peerlist.remove_peer(settings, token)+ if removed is not None:+ self.save_settings(settings)+ return removed+- def set_ways(self, peer, *, side, methods, parts, corner):++ def set_ways(self, peer, *, side, methods, parts, corner, live=None):+ """Writes one machine's side and zones, as the Crossing page shows them for it (core/ways.py).- Returns whether its side moved, which the caller sends it as `arrangement`; SettingsError, writing- nothing, for a machine not in the list or zones that would clash with another's."""++ A machine with no link now (`live(id)` false) gives way to them. Returns whether its side++ moved, which the caller sends it as `arrangement`; SettingsError, writing nothing, for a++ machine not in the list or zones that would clash with another's."""+ with self.lock:+ settings = copy.deepcopy(self.current())+ try:+ moved = ways.edit(settings, peer, side=side, methods=methods, parts=parts, corner=corner,+ kinds=ZONE_KINDS, corner_edge=lambda corner, _side: _corner_edge(corner), now=time.time())+ except KeyError:+ raise SettingsError("that machine is no longer paired with this Mac") from None+ if moved:+ # Moved onto a side another machine's edge holds: the side stands and this machine's+ # way there goes off, as when the side arrives from it; the page says who holds it.- ways.settle(settings, peer, "this Mac")++ ways.settle(settings, peer, "this Mac", live)++ for notice in ways.give_way(settings, peer, "this Mac", live):++ LOGGER.info("%s", notice)+ self.save_settings(settings)+ return moved++ def share_side(self, side, thirds):+ """Split one side's zones under the store lock, returning every machine whose zones changed."""+ with self.lock:+ settings = copy.deepcopy(self.current())+ changed = ways.share(settings, side, thirds, kinds=ZONE_KINDS)+ self.save_settings(settings)+ return changed++ def set_hardware(self, peer, address):+ """Writes the hardware address learnt for a machine (wake-on-LAN); True when it changed."""+ address = parse_mac(address)+ if address is None:+ return False+ with self.lock:+ settings = copy.deepcopy(self.current())+ entry = next((item for item in settings["peers"] if item["id"] == peer), None)+ if entry is None or entry.get("port") == 0 or entry["hw"] == address:+ return False+ entry["hw"] = address+ self.save_settings(settings)+ return True+- def arrangement(self, peer, edge, set_at, by, way_back=None, way_back_by=None):++ def settle_presence(self, live, gone):++ """What became of the zones set aside for a machine with no link (core/ways.py settle_presence).++ Returns (changed, notices): whether the file was written, and a sentence for each zone that++ stays off for good or could not be put back."""++ with self.lock:++ settings = copy.deepcopy(self.current())++ notices = ways.settle_presence(settings, "this Mac", live, gone)++ changed = settings != self.current()++ if changed:++ self.save_settings(settings)++ return changed, notices++++ def arrangement(self, peer, edge, set_at, by, way_back=None, way_back_by=None, live=None):+ """A machine's `arrangement`, kept when it is newer than the side held for that machine, and+ its `way_back` whatever the side (core/ways.py). Returns (changed, notices), a sentence for each+ zone it turned off."""+ with self.lock:+ settings = copy.deepcopy(self.current())+ changed, notices = ways.arrangement(settings, peer, edge, set_at, by, "this Mac", way_back,- way_back_by=way_back_by)++ way_back_by=way_back_by, live=live)+ if changed:+ self.save_settings(settings)+ return changed, notices++ def save(self, raw):try:- cfg = config_module.load_config(str(self.path))- except (config_module.ConfigError, json.JSONDecodeError, OSError, TypeError, ValueError) as exc:+ cfg = config_module.parse_config(raw)+ except (config_module.ConfigError, TypeError, ValueError, OverflowError) as exc:raise SettingsError(str(exc)) from exc- cfg = self._migrate_port(cfg)self._validate(cfg)- return cfg-- def _migrate_port(self, cfg):- """Move a config still on the old default port, and write the move down.+ with self.lock:+ handed = self._handed_token+ base = self.load_settings()+ self._config(base)+ if cfg.trigger_key != base.get("trigger_key"):+ try:+ ways.check_trigger_key(base, cfg.trigger_key)+ except ValueError as exc:+ raise SettingsError(str(exc)) from exc+ cfg = self._without_stale_pairing(cfg, base, handed)+ return self._config(self.save_settings(_merge_config(base, cfg)))- 51820 sat inside the 49152-65535 range both operating systems hand out for- themselves, so it was never a port anyone could rely on keeping -- WinNAT claimed it on- one PC and the app could not listen at all. Nobody chose that number, it was what the- app shipped with, so it moves; a port a user typed is theirs and is left alone.- """- if cfg.port != protocol.LEGACY_DEFAULT_PORT:+ @staticmethod+ def _without_stale_pairing(cfg, base, handed):+ """A caller that still holds the flat settings from before the first machine changed (a+ pairing stored from the pairing service's thread, a removal) would have its old machine+ written back over the new one, or the new one popped if there had been none. Its machine+ fields are the file's own then; everything else it changed is kept."""+ desktop = peerlist.first_desktop(base["peers"])+ first = desktop["token"] if desktop is not None else ""+ if cfg.auth_token == first or cfg.auth_token != handed:return cfg- cfg = replace(cfg, port=protocol.DEFAULT_PORT)+ current = raw_from_settings(base)+ return dataclasses.replace(+ cfg, host=current["host"], port=current["port"], auth_token=current["auth_token"], pc_name=current["pc_name"],+ mac_address=current["mac_address"], send_to_windows=current["send_to_windows"],+ allow_windows_to_drive=current["allow_windows_to_drive"],+ )++ def load_settings(self):+ """The whole of settings.json, made from config.json on the first start and kept in step with it after."""+ with self.lock:+ if not self.path.exists():+ settings = self._migrate()+ else:+ settings = self._reimport(self._read())+ self._cache = copy.deepcopy(settings)+ return settings++ def save_settings(self, settings):+ """Check and write `settings` atomically; returns what was written."""+ with self.lock:+ written = self._save_settings(settings)+ self._cache = copy.deepcopy(written)+ return written++ def _save_settings(self, settings):+ settings = self._complete(settings)try:- self.save(config_to_raw(cfg))+ before = self._read()except SettingsError:- # The port in hand is what matters; a read-only config directory must not- # stop the app connecting on it.- pass+ before = None+ if before:+ unnamed = next((peer for peer in before["peers"] if peer["id"] == ""), None)+ if unnamed:+ learnt = next((peer for peer in settings["peers"] if peer["token"] == unnamed["token"] and peer["id"]), None)+ if learnt:+ settings["zones"] = _rename_zones(settings["zones"], "", learnt["id"])+ self._ensure_zones(settings)+ self._check(settings)+ self._write(settings)+ return settings++ def _config(self, settings):+ try:+ cfg = config_module.parse_config(raw_from_settings(settings))+ except (config_module.ConfigError, TypeError, ValueError, OverflowError) as exc:+ raise SettingsError(str(exc)) from exc+ self._validate(cfg)+ self._handed_token = cfg.auth_tokenreturn cfg- def save(self, raw):+ def _fresh(self):+ return {+ "schema": SCHEMA,+ "machine_id": new_machine_id(),+ "name": "",+ "port": protocol.DEFAULT_PORT,+ "shortcut": True,+ "migrated_token_sha256": "",+ "peers": [],+ "zones": [],+ "crossing": {},+ }++ def _read(self):+ try:+ settings = json.loads(self.path.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError, ValueError) as exc:+ raise SettingsError(f"{self.path.name} could not be read: {exc}") from exc+ if not isinstance(settings, dict) or settings.get("schema") != SCHEMA:+ raise SettingsError(f"{self.path.name} is not a schema {SCHEMA} settings file")+ settings = self._complete(settings)+ self._ensure_zones(settings)+ self._check(settings)+ return settings++ def _complete(self, settings):+ """A copy with every field the format has, so a hand-edited file missing one does not break a read."""+ settings = copy.deepcopy(settings)+ for name in ("name", "port", "shortcut", "migrated_token_sha256", "crossing"):+ settings.setdefault(name, self._fresh()[name])+ for name in ("machine_id", "peers", "zones"):+ if name not in settings:+ raise SettingsError(f"{name} is missing; settings.json is not written over a file that lacks it")+ if not isinstance(settings["peers"], list):+ raise SettingsError("peers must be a list")+ settings["peers"] = [{**PEER_DEFAULTS, **peer} if isinstance(peer, dict) else peer for peer in settings["peers"]]+ peerlist.normalise_phones(settings)+ if not isinstance(settings["crossing"], dict):+ raise SettingsError("crossing must be a JSON object")+ settings["crossing"] = {+ **{name: value for name, value in config_module.DEFAULT_CROSSING.items() if name not in MOVED_CROSSING},+ **settings["crossing"],+ } if peerlist.first_desktop(settings["peers"]) is not None else {**config_module.DEFAULT_CROSSING, **settings["crossing"]}+ return settings++ @staticmethod+ def _ensure_zones(settings):+ """Give old pairs their edge and the one unplaced desktop its shown side on every read and save.+ Run after a learnt id has renamed migrated zones, or that machine would get a second edge."""+ if (isinstance(settings["zones"], list)+ and all(isinstance(item, dict) for item in settings["peers"] + settings["zones"])+ and all(isinstance(item.get("id"), str) for item in settings["peers"])):+ ways.ensure_zones(settings)+ ways.default_side(settings)++ def _check(self, settings):+ if not is_machine_id(settings["machine_id"]):+ raise SettingsError("machine_id must be a 16-byte id that is not all zero")+ for name, kind in (("name", str), ("shortcut", bool), ("migrated_token_sha256", str), ("zones", list)):+ if not isinstance(settings[name], kind):+ raise SettingsError(f"{name} must be {kind.__name__}")+ if isinstance(settings["port"], bool) or not isinstance(settings["port"], int) or not 1 <= settings["port"] <= 65535:+ raise SettingsError("port must be between 1 and 65535")+ if not all(isinstance(zone, dict) and isinstance(zone.get("peer"), str) and zone.get("kind") in ZONE_KINDS+ for zone in settings["zones"]):+ raise SettingsError("every zone needs a peer and a kind of " + ", ".join(ZONE_KINDS))+ for zone in settings["zones"]:+ if "off" in zone and not isinstance(zone["off"], bool):+ raise SettingsError("a zone's off must be true or false")+ if zone["kind"] == "corner" and (zone.get("corner") not in CORNERS or zone.get("edge") not in EDGES):+ raise SettingsError("a corner zone needs a corner and the edge it crosses")+ if zone["kind"] == "part" and not (isinstance(zone.get("parts"), list) and zone["parts"]+ and all(part in return_edge.PARTS for part in zone["parts"])):+ raise SettingsError("a part zone needs thirds of " + ", ".join(return_edge.PARTS))+ peers = settings["peers"]+ if len(peers) > MAX_PEERS:+ raise SettingsError(f"at most {MAX_PEERS} peers")+ ids, key_ids, empty = set(), set(), 0+ for peer in peers:+ if not isinstance(peer, dict):+ raise SettingsError("every peer must be a JSON object")+ for name, default in PEER_DEFAULTS.items():+ value = peer[name]+ if isinstance(default, bool) != isinstance(value, bool) or not isinstance(value, type(default)):+ raise SettingsError(f"peer {name} must be {type(default).__name__}")+ if "way_back_by" in peer and not isinstance(peer["way_back_by"], str):+ raise SettingsError("peer way_back_by must be str")+ if not isinstance(peer["jump_key"], str) or (peer["jump_key"] and not ways.valid_jump_key(peer["jump_key"])):+ raise SettingsError("peer jump_key must be an empty string or a recorded modifier chord")+ if peer["id"] == "":+ empty += 1+ if not peer["from_1_4"] or empty > 1:+ raise SettingsError("only the entry migrated from 1.4.x may have an empty id")+ elif not is_machine_id(peer["id"]) or peer["id"] == settings["machine_id"] or peer["id"] in ids:+ raise SettingsError("a peer id must be a machine id that is neither ours nor another peer's")+ ids.add(peer["id"])+ if protocol.is_paired_token(peer["token"]):+ if protocol.key_id(peer["token"]) in key_ids:+ raise SettingsError("two peers share one token")+ key_ids.add(protocol.key_id(peer["token"]))+ if any(zone["peer"] not in ids for zone in settings["zones"]):+ raise SettingsError("a zone names a peer that is not in the list")+ self._check_overlap(settings)++ def _check_overlap(self, settings):+ """Two zones in use never cover one stretch (WIRE.md section 8); a corner inside an edge is the+ exception, and the notch stands beside the top edge, as 1.4.x let it, but leads to one machine."""+ sentence = ways.clash(settings, "this Mac")+ if sentence is not None:+ raise SettingsError(sentence)++ def _write(self, settings):self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)try:os.chmod(self.path.parent, 0o700)diff --cc mac_app/setup.pyindex b3650cb,bf7c82f..7955b4f--- a/mac_app/setup.py+++ b/mac_app/setup.py@@@ -68,20 -67,15 +68,20 @@@ setupoptions={"py2app": {"argv_emulation": False,- # cryptography ships a compiled _rust extension plus cffi; py2app's own recipe pulls- # both in, but naming the package keeps its data files and submodules in the bundle.- # PyNaCl (nacl) is the same shape: a compiled _sodium extension reached through cffi.- "packages": ["rumps", "cryptography", "cffi", "nacl"],- # effects.py imports its fx_* modules by name at first use, which py2app's import scan- # cannot see, so they are named here or the bundle ships without a single effect.+ # PyNaCl (nacl) ships a compiled _sodium extension reached through cffi; naming both+ # packages keeps their data files and submodules in the bundle.+ "packages": ["rumps", "cffi", "nacl"],+ # core/effects.py imports its fx_* modules by name at first use, which py2app's import+ # scan cannot see, so they are named here or the bundle ships without a single effect.+ # The rest of core/ is named too, through the repo root put on sys.path above, so a module+ # the scan misses cannot drop out; naming the package whole would ship its tests too."includes": [- "objc", "AppKit", "ApplicationServices", "Quartz",- "fx_ink", "fx_instrument", "fx_membrane", "fx_sparks", "fx_warp",+ "objc", "AppKit", "ApplicationServices", "Quartz", "UserNotifications",- "core.effects", "core.ignored", "core.keytable", "core.link", "core.owner", "core.pairing",++ "core.crash_log", "core.effects", "core.ignored", "core.keytable", "core.link", "core.owner", "core.pairing",+ "core.peerlist", "core.protocol", "core.receiver", "core.return_edge", "core.settings_sync",+ "core.updates", "core.wol",+ "core.fx_ink", "core.fx_instrument", "core.fx_membrane", "core.fx_sparks", "core.fx_warp",+ "core.fx_light", "core.fx_material", "core.fx_folio", "core.fx_selvedge",],"iconfile": "../Beamer.icns","plist": {diff --cc mac_app/tests/test_bridge.pyindex 1be8989,d77cfad..3c647a2--- a/mac_app/tests/test_bridge.py+++ b/mac_app/tests/test_bridge.py@@@ -418,71 -633,83 +418,103 @@@ class ControllerTests(unittest.TestCaseself.assertIsNone(second_down)self.assertIsNone(second_up)self.assertTrue(self.controller.redirecting)- self.assertIs(self.controller.sock, sock)+ self.assertTrue(link.live())+ self.assertEqual(link.dropped, [])+ self.assertFalse(link.stopped)+++ def test_the_shortcut_there_and_back_never_clicks_on_this_mac(self):++ """Toby 06-10: a grey box round the pointer after the shortcut, "which clicked on return". A++ click made while away, and one held across the return, reach this Mac as nothing but the++ user's own events: no button is posted, made or handed back that the hand did not press."""++ bring_up(self.controller)++ landings = []++ self.controller.on_crossing = lambda kind, step: landings.append(kind)++ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": FakeQuartz.kCGEventFlagMaskAlternate}++ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x3D, "flags": 0}+- def test_sequence_is_added_once_per_outbound_event(self):- first = self.controller._prepare_outbound(- {"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}}- )- second = self.controller._prepare_outbound(- {"type": protocol.MSG_KEYUP, "data": {"key": "a"}}- )- self.assertEqual(first["data"]["seq"], 1)- self.assertEqual(second["data"]["seq"], 2)-- def test_watchdog_drops_connection_after_two_seconds_without_ack(self):- alerts = []- self.controller.on_user_alert = lambda title, message: alerts.append((title, message))- sock = FakeSocket()- link(self.controller, sock)- self.controller.redirecting = True- self.controller.connected_at = 10.0- self.controller.last_ack_at = 10.0- self.clock.value = 10.0 + ACK_TIMEOUT_SECONDS + 0.01- self.assertTrue(self.controller._watchdog_tick())++ def double_tap(start):++ for at, event in ((start, down), (start, up), (start + 0.1, down), (start + 0.1, up)):++ self.clock.value = at++ self._tap(FakeQuartz.kCGEventFlagsChanged, event)++++ posted = []++ with mock.patch("input_injector_mac._post", side_effect=posted.append):++ double_tap(10.0)++ self.assertTrue(self.controller.redirecting)++ click = [self._tap(FakeQuartz.kCGEventLeftMouseDown, {}), self._tap(FakeQuartz.kCGEventLeftMouseUp, {})]++ self.assertEqual(click, [None, None])++ held = self._tap(FakeQuartz.kCGEventLeftMouseDown, {})++ self.assertIsNone(held)++ drain(self.controller)++ double_tap(11.0)++ self.assertFalse(self.controller.redirecting)++ release = {"mine": True}++ self.assertIs(self._tap(FakeQuartz.kCGEventLeftMouseUp, release), release)++ self.assertEqual(posted, [])++ self.assertEqual(landings, ["home"])++ self.assertNotIn(protocol.MSG_MOUSEDOWN, [message["type"] for message in drain(self.controller)])+++ def test_a_failed_connection_while_redirecting_brings_input_home_and_alerts_at_once(self):+ # Otherwise input would simply vanish into a dead connection.+ link = bring_up(self.controller)+ self.assertTrue(self.controller.set_redirecting(True))+ self.controller._connection_failed("Windows stopped responding")self.assertFalse(self.controller.redirecting)- self.assertTrue(sock.closed)+ self.assertEqual(link.dropped, ["Windows stopped responding"])self.assertEqual(self.controller.connection_status, "Windows stopped responding")- # Killing an active redirect must alert the user immediately, since- # otherwise input would simply vanish into a dead connection.- self.assertEqual(alerts, [("Beamer", "Input returned to this Mac")])-- def test_watchdog_detects_a_dead_socket_while_not_redirecting(self):- # Previously the watchdog only ran while redirecting, so a half-open- # connection was invisible while idle: the UI stayed green and a- # double-tap would "succeed" into a void. It must now be detected and- # torn down the same way regardless of redirect state.- sock = FakeSocket()- link(self.controller, sock)- self.controller.redirecting = False- self.controller.connected_at = 10.0- self.controller.last_ack_at = 10.0- self.clock.value = 10.0 + ACK_TIMEOUT_SECONDS + 0.01- self.assertTrue(self.controller._watchdog_tick())+ self.assertEqual(self.alerts, [("Beamer", "Input returned to this Mac")])++ def test_jump_chord_for_the_current_peer_returns_input_home_and_is_swallowed(self):+ link = bring_up(self.controller)+ self.controller.book.data["peers"][0]["id"] = protocol.id_text(PEER_ID)+ self.controller.book.data["peers"][0]["jump_key"] = "ctrl+shift+2"+ self.assertTrue(self.controller.set_redirecting(True))+ flags = FakeQuartz.kCGEventFlagMaskControl | FakeQuartz.kCGEventFlagMaskShift+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x13, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "flags": flags,+ "unicode": "2"}+ up = {FakeQuartz.kCGKeyboardEventKeycode: 0x13, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "flags": flags,+ "unicode": "2"}+ self.assertIsNone(self._tap(FakeQuartz.kCGEventKeyDown, down))+ self.assertFalse(self.controller.redirecting)+ repeat = {**down, FakeQuartz.kCGKeyboardEventAutorepeat: 1}+ self.assertIsNone(self._tap(FakeQuartz.kCGEventKeyDown, repeat))+ self.assertFalse(self.controller.redirecting)+ self.assertIsNone(self._tap(FakeQuartz.kCGEventKeyUp, up))+ self.assertEqual(link.sent, [])++ def test_a_key_repeating_when_its_modifiers_arrive_is_not_a_jump_and_nothing_jumps_while_recording(self):+ bring_up(self.controller)+ self.controller.book.data["peers"][0]["id"] = protocol.id_text(PEER_ID)+ self.controller.book.data["peers"][0]["jump_key"] = "ctrl+shift+2"+ flags = FakeQuartz.kCGEventFlagMaskControl | FakeQuartz.kCGEventFlagMaskShift+ down = {FakeQuartz.kCGKeyboardEventKeycode: 0x13, FakeQuartz.kCGKeyboardEventAutorepeat: 0, "flags": flags,+ "unicode": "2"}+ self._tap(FakeQuartz.kCGEventKeyDown, {**down, FakeQuartz.kCGKeyboardEventAutorepeat: 1})+ self.assertFalse(self.controller.redirecting)+ self.controller.jump_recording = True+ self._tap(FakeQuartz.kCGEventKeyDown, down)self.assertFalse(self.controller.redirecting)- self.assertIsNone(self.controller.sock)- self.assertTrue(sock.closed)+ self.controller.jump_recording = False+ self._tap(FakeQuartz.kCGEventKeyDown, down)+ self.assertTrue(self.controller.redirecting)++ def test_a_failed_connection_while_idle_drops_the_link_without_an_alert(self):+ link = bring_up(self.controller)+ self.controller._connection_failed("Windows stopped responding")+ self.assertFalse(self.controller.redirecting)+ self.assertEqual(link.dropped, ["Windows stopped responding"])self.assertEqual(self.controller.connection_status, "Windows stopped responding")+ self.assertEqual(self.alerts, [])- def test_watchdog_sends_idle_ping_after_a_second_of_silence(self):- sock = FakeSocket()- link(self.controller, sock)- self.controller.connected_at = 10.0- self.controller.last_ack_at = 10.0- self.controller.last_send_at = 10.0- self.clock.value = 10.0 + PING_INTERVAL_SECONDS- self.assertFalse(self.controller._watchdog_tick())- self.assertEqual(len(sock.sent), 1)- self.assertEqual(sent_messages(self.controller, sock)[-1], protocol.ping_msg())- self.assertEqual(self.controller.last_send_at, self.clock.value)-- def test_watchdog_suppresses_idle_ping_while_traffic_flows(self):- sock = FakeSocket()- link(self.controller, sock)- self.controller.connected_at = 10.0- self.controller.last_ack_at = 10.0- self.controller.last_send_at = 11.5- self.clock.value = 11.6- self.assertFalse(self.controller._watchdog_tick())- self.assertEqual(sock.sent, [])+ def test_input_is_dropped_while_not_redirecting(self):+ link = bring_up(self.controller)+ self.controller._process_outbound({"type": protocol.MSG_KEYDOWN, "data": {"key": "a"}})+ self.assertEqual(link.sent, [])def test_set_redirecting_true_refuses_while_receiving(self):- # Invariant 2: redirecting and receiving must never both be True.- # set_receiving enforces this by turning redirecting off first- # (bridge.py:709-710); set_redirecting has no matching check, so a- # manual switch (the menu bar's toggleRedirect_, kvm_bridge_app.py:1703)- # while Windows is already driving this Mac corrupts the pair. This- # asserts the invariant, which the current code violates.- sock = FakeSocket()- link(self.controller, sock)+ # Redirecting and receiving must never both be True: a Mac driven by another machine+ # and driving one at once is a machine with two owners.+ bring_up(self.controller)self.controller.receiving = Trueself.controller.set_redirecting(True)self.assertFalse(diff --cc mac_app/tests/test_crossing_matrix.pyindex dc5e430,2d636ce..6f69607--- a/mac_app/tests/test_crossing_matrix.py+++ b/mac_app/tests/test_crossing_matrix.py@@@ -179,9 -194,6 +179,10 @@@ class ArrangementFromEitherSideTests(unsettings_store=self.store,logger=types.SimpleNamespace(info=lambda *a: self.logged.append(a), exception=lambda *a: None),refresh=lambda: None,+ _load=lambda raw: None,+ _flush=lambda: None,+ _tell=lambda peer: self.told.append(peer),++ _live=lambda peer: True,)def test_a_newer_arrangement_from_the_pc_is_applied_with_its_stamp_and_arms_the_new_edge(self):diff --cc mac_app/tests/test_crossing_page_machines.pyindex f9249f6,0000000..fd4e4eamode 100644,000000..100644--- a/mac_app/tests/test_crossing_page_machines.py+++ b/mac_app/tests/test_crossing_page_machines.py@@@ -1,629 -1,0 +1,695 @@@+"""The Crossing page with several machines paired, in the real settings window (WIRE.md sections 5+and 8): a machine is chosen at the top of Ways in, everything per machine below it shows and writes+that machine's ways, the drawing places every machine, and the menu bar sends input to each. Built+as the README's screenshots build it, never put on screen, starting no network."""++import base64+import copy+import json+import logging+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import AppKit # noqa: E402+import rumps.rumps as rumps_module # noqa: E402++AppKit.NSApplication.sharedApplication()++import bridge # noqa: E402+import kvm_bridge_app # noqa: E402+import settings_store # noqa: E402+from bridge_fakes import PAIRED_TOKEN # noqa: E402+from core import protocol, ways # noqa: E402+from fake_link import FakeLink # noqa: E402+from wake import WakingController # noqa: E402++BEE = protocol.id_text(bytes(range(40, 56)))+SEA = protocol.id_text(bytes(range(70, 86)))+OAK = protocol.id_text(bytes(range(90, 106)))+++def token(start):+ return base64.urlsafe_b64encode(bytes(range(start, start + 32))).decode("ascii").rstrip("=")+++def entry(ident, secret, name, side="", own="", **extra):+ return {**settings_store.PEER_DEFAULTS, "id": ident, "name": name, "platform": "windows", "token": secret,+ "host": "192.0.2.30", "port": 24820, "paired_at": 1_700_000_000, "linked": True, "side": side,+ "side_set_at": 100 if side else 0, "side_by": own if side else "", **extra}+++class Page(unittest.TestCase):+ """This Mac with Bee on its right by its edge, and Sea on its left by its top third."""++ def setUp(self):+ self.directory = tempfile.TemporaryDirectory()+ self.addCleanup(self.directory.cleanup)+ path = Path(self.directory.name) / "config.json"+ raw = settings_store.config_to_raw(settings_store.editable_default_config())+ raw.update(host="192.0.2.20", auth_token=PAIRED_TOKEN)+ path.write_text(json.dumps(raw))+ self.store = settings_store.SettingsStore(path)+ self.later = []+ patcher = mock.patch.object(kvm_bridge_app.AppHelper, "callLater", lambda _delay, call: self.later.append(call))+ patcher.start()+ self.addCleanup(patcher.stop)++ def build(self, peers, zones=()):+ settings = copy.deepcopy(self.store.current())+ own = settings["machine_id"]+ settings["peers"] = [entry(*peer[:3], **{"own": own, **(peer[3] if len(peer) > 3 else {})}) for peer in peers]+ settings["zones"] = list(zones)+ self.store.save_settings(settings)+ logger = logging.getLogger("test-crossing-page-machines")+ book, identity = bridge.links_from_store(self.store, "1.5.0")+ self.controller = WakingController(self.store.load(), logger=logger, book=book, identity=identity,+ link_factory=FakeLink)+ with mock.patch.object(kvm_bridge_app, "accessibility_granted", return_value=True), \+ mock.patch.object(kvm_bridge_app, "input_monitoring_granted", return_value=True):+ self.window = kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(+ self.controller, self.store, logger)+ self.addCleanup(self.window.appearance_watch.stop)+ self.window.windows_input = mock.Mock()+ self.window.windows_input.send_arrangement.return_value = True- self.window.windows_input.server.links.return_value = []++ # Every machine linked to this Mac: one with no link gives way instead (core/ways.py give_way).++ self.window.windows_input.server.links.return_value = [protocol.read_id(peer[0]) for peer in peers]++ self.window.windows_input.server.caps_of.return_value = None+ self.sent = []+ self.sent_by = []+ self.controller.send_arrangement = lambda peer, edge, set_at, by=None: (+ self.sent.append((peer, edge, set_at)) or self.sent_by.append(by) or True)+ return self.window++ def two(self):+ return self.build(+ [(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "left"})],+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "part", "parts": ["start"]},+ {"peer": SEA, "kind": "corner", "corner": "bottom_left", "edge": "left"}])++ def ways_of(self, peer):+ return ways.ways(self.store.current(), peer)++ def methods(self):+ return [name for name, tile in self.window.method_boxes.items() if tile.value]++ def toggle(self, way):+ self.window.method_boxes[way]._toggle()++ def pick(self, peer):+ self.window.machine_select._choose(peer)+++class OneOrNoMachine(Page):+ def test_with_one_machine_there_is_no_picker_and_the_page_reads_as_today(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "left"})], [{"peer": BEE, "kind": "edge"}])+ self.assertTrue(window.machine_row.isHidden())+ self.assertEqual(window.edge_caption.text, "Where the other machine is")+ self.assertEqual(window.edge_select.value, "left")+ self.assertEqual(self.methods(), ["edge", "shortcut"])++ def test_one_machine_with_no_side_shows_right_as_it_always_has(self):+ window = self.build([(BEE, token(100), "Bee")])+ self.assertEqual(window.edge_select.value, "right")++ def test_one_machine_not_placed_holds_the_shown_right_unstamped_before_any_save_so_its_own_side_wins(self):+ window = self.build([(BEE, token(100), "Bee")], [{"peer": BEE, "kind": "edge"}])+ held = self.store.current()["peers"][0]+ self.assertEqual((held["side"], held["side_set_at"], held["side_by"]), ("right", 0, ""))+ window._apply_settings()+ self.assertEqual(self.sent, [])+ window.apply_arrangement(BEE, "bottom", 1_790_000_000, BEE, True)+ self.assertEqual(self.ways_of(BEE)["side"], "top")+++class SharingSide(Page):+ def build_blocked(self):+ window = self.build(+ [(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "right"})],+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge", "off": True}])+ window._machine_picked(SEA)+ window._select_page("crossing")+ return window++ def test_the_panel_offers_thirds_under_the_side_picker_and_replaces_the_blocked_sentence(self):+ window = self.build_blocked()+ self.assertFalse(window.share_box.isHidden())+ self.assertEqual([window.share_tiles[p].name.text for p in ("start", "middle", "end")],+ ["Top", "Middle", "Bottom"])+ self.assertEqual([window.share_tiles[p].detail.text for p in ("start", "middle", "end")],+ ["Bee", "Bee", "Sea"])+ self.assertTrue(window.blocked_note.view.isHidden())++ def test_a_tile_moves_to_the_next_machine_and_share_writes_and_tells_both(self):+ window = self.build_blocked()+ window.share_tiles["start"]._toggle()+ self.assertEqual(window.share_tiles["start"].detail.text, "Sea")+ window._share_side()+ zones = {(z["peer"], z["kind"]): z for z in self.store.current()["zones"]}+ self.assertEqual(zones[(BEE, "part")]["parts"], ["middle"])+ self.assertEqual(zones[(SEA, "part")]["parts"], ["start", "end"])+ self.assertTrue(zones[(BEE, "edge")].get("off"))+ self.assertTrue(zones[(SEA, "edge")].get("off"))+ self.assertEqual({peer for peer, _edge, _stamp in self.sent}, {BEE, SEA})++ def test_turning_on_edge_keeps_it_off_and_focuses_the_share_panel(self):+ window = self.build_blocked()+ self.toggle("edge")+ window._flush()+ self.assertFalse(window.method_boxes["edge"].value)+ self.assertFalse(window.share_box.isHidden())+ self.assertTrue(window.blocked_note.view.isHidden())+ self.assertIs(window.window.firstResponder(), window.share_button.view)+++ def test_edge_turns_on_over_a_machine_with_no_link_and_that_machines_edge_goes_off(self):++ # 06-10-2026: a machine gone for good held the side, and Edge would not turn on until it was moved.++ window = self.build_blocked()++ window.windows_input.server.links.return_value = [protocol.read_id(SEA)]++ window._show_machines()++ self.assertTrue(window.share_box.isHidden())++ self.toggle("edge")++ window._flush()++ self.assertTrue(window.method_boxes["edge"].value)++ zones = {(zone["peer"], zone["kind"]): zone for zone in self.store.current()["zones"]}++ self.assertTrue(zones[(BEE, "edge")].get("off"))++ self.assertTrue(zones[(BEE, "edge")].get("aside"))++ self.assertIsNone(zones[(SEA, "edge")].get("off"))++ self.assertIsNone(ways.clash(self.store.current(), "this Mac"))++++ def lid_shut(self):++ """Sea given Bee's side while Bee, with its lid shut, has no link to this Mac."""++ window = self.build_blocked()++ window.windows_input.server.links.return_value = [protocol.read_id(SEA)]++ window._show_machines()++ self.toggle("edge")++ window._flush()++ return window++++ def bee_zone(self):++ return next(zone for zone in self.store.current()["zones"] if zone["peer"] == BEE and zone["kind"] == "edge")++++ def test_a_machine_with_its_lid_shut_has_its_edge_set_aside_and_gets_it_back_when_it_connects(self):++ window = self.lid_shut()++ self.assertEqual(self.bee_zone(), {"peer": BEE, "kind": "edge", "off": True, "aside": True})++ self.toggle("edge")++ window._flush()++ window.settle_presence()++ self.assertTrue(self.bee_zone().get("aside"))++ window.windows_input.server.links.return_value = [protocol.read_id(BEE), protocol.read_id(SEA)]++ self.sent.clear()++ window.settle_presence()++ self.assertEqual(self.bee_zone(), {"peer": BEE, "kind": "edge"})++ self.assertIn(BEE, {peer for peer, _edge, _stamp in self.sent})++ self.assertIsNone(ways.clash(self.store.current(), "this Mac"))++++ def test_a_machine_back_over_a_side_another_holds_stays_off_and_the_page_offers_thirds(self):++ window = self.lid_shut()++ window.windows_input.server.links.return_value = [protocol.read_id(BEE), protocol.read_id(SEA)]++ window.settle_presence()++ self.assertEqual(self.bee_zone(), {"peer": BEE, "kind": "edge", "off": True})++ window._machine_picked(BEE)++ self.assertFalse(window.share_box.isHidden())++++ def test_a_machine_that_removed_this_pairing_stays_off_for_good_and_the_page_says_so(self):++ window = self.lid_shut()++ link = FakeLink(token(100), self.controller.book, None)++ link.kind = "forgotten"++ self.controller.links[token(100)] = link++ alerts = []++ self.controller.on_user_alert = lambda title, message: alerts.append(message)++ window.settle_presence()++ self.assertEqual(self.bee_zone(), {"peer": BEE, "kind": "edge", "off": True})++ self.assertEqual(alerts, ["Bee no longer has this pairing, so its edge stays off. Remove Bee here and pair "++ "the two again."])++ window._machine_picked(BEE)++ self.assertIn("Bee no longer has this pairing", window.blocked_note.text)++ self.assertFalse(window.blocked_note.view.isHidden())+++ def test_turning_on_an_overlapping_part_keeps_it_off_and_focuses_the_share_panel(self):+ window = self.build_blocked()+ self.toggle("part")+ window._flush()+ self.assertFalse(window.method_boxes["part"].value)+ self.assertFalse(window.share_box.isHidden())+ self.assertTrue(window.blocked_note.view.isHidden())+ self.assertIs(window.window.firstResponder(), window.share_button.view)++ def test_the_first_machine_paired_crosses_at_the_right_edge_the_page_shows_with_nothing_saved(self):+ # beta.4 on three machines: Edge showed on, the pointer did not cross until a Notch save wrote the side.+ window = self.build([])+ self.store.add_peer(entry(BEE, token(100), "Bee", linked=False))+ window.peers_changed()+ self.controller.cfg = self.store.load()+ self.controller.zones_changed()+ self.assertEqual(window.edge_select.value, "right")+ self.assertIn("edge", self.ways_of(BEE)["methods"])+ found = [(way.peer, way.edge, "edge" in way.methods) for way in self.controller.crossing.ways]+ self.assertEqual(found, [(BEE, "right", True)])+ self.assertEqual(self.sent, [])++ def test_a_second_machine_paired_is_given_no_side_and_the_first_keeps_its_right(self):+ window = self.build([(BEE, token(100), "Bee")], [{"peer": BEE, "kind": "edge"}])+ self.store.add_peer(entry(SEA, token(150), "Sea", linked=False))+ window.peers_changed()+ self.assertEqual([(peer["side"], peer["side_set_at"]) for peer in self.store.current()["peers"]],+ [("right", 0), ("", 0)])++ def test_with_one_machine_a_change_writes_its_ways_and_sends_it_the_side(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "left"})], [{"peer": BEE, "kind": "edge"}])+ window.edge_select._choose("top")+ window._apply_settings()+ self.assertEqual(self.ways_of(BEE)["side"], "top")+ self.assertEqual([(peer, edge) for peer, edge, _at in self.sent], [(BEE, "top")])++ def test_with_none_paired_the_page_writes_the_flat_settings_as_today(self):+ window = self.build([])+ self.assertTrue(window.machine_row.isHidden())+ self.toggle("corner")+ window._apply_settings()+ self.assertIn("corner", self.store.load().crossing["methods"])+++class ChoosingAMachine(Page):+ def test_with_two_machines_the_picker_names_each_and_starts_on_the_first(self):+ window = self.two()+ self.assertFalse(window.machine_row.isHidden())+ self.assertEqual([title for _value, title in window.machine_select.choices], ["Bee", "Sea"])+ self.assertEqual(window.machine_select.value, BEE)+ self.assertEqual(window.edge_caption.text, "Where Bee is")+ self.assertEqual((window.edge_select.value, self.methods()), ("right", ["edge", "shortcut"]))++ def test_the_picker_omits_machines_not_in_use_and_keeps_their_zones(self):+ window = self.two()+ zones = list(self.store.current()["zones"])+ self.store.set_peer(token(150), in_use=False)+ window._show_machines()+ self.assertEqual(window._picker_choices, [(BEE, "Bee")])+ self.assertTrue(window.machine_row.isHidden())+ self.assertEqual(self.store.current()["zones"], zones)++ def test_turning_off_the_chosen_machine_selects_an_active_machine(self):+ window = self.two()+ window._machine_picked(SEA)+ self.store.set_peer(token(150), in_use=False)+ window._show_machines()+ self.assertEqual(window.chosen_peer, BEE)+ self.assertTrue(window.machine_row.isHidden())++ def test_choosing_a_machine_shows_its_ways(self):+ window = self.two()+ self.pick(SEA)+ self.assertEqual(window.edge_caption.text, "Where Sea is")+ self.assertEqual(window.edge_select.value, "left")+ self.assertEqual(self.methods(), ["part", "corner", "shortcut"])+ self.assertEqual([name for name, tile in window.part_boxes.items() if tile.value], ["start"])+ self.assertEqual(window.corner_select.value, "bottom_left")+ self.assertEqual(window.push_strip.other_name, "Sea")++ def test_a_change_writes_the_chosen_machines_ways_and_leaves_the_others_alone(self):+ window = self.two()+ bee = self.ways_of(BEE)+ self.pick(SEA)+ self.toggle("notch")+ window._apply_settings()+ self.assertIn("notch", self.ways_of(SEA)["methods"])+ self.assertEqual(self.ways_of(BEE), bee)+ self.assertEqual(self.sent, [])++ def test_a_new_side_is_sent_to_that_machine_and_over_its_own_link_when_this_macs_is_down(self):+ window = self.two()+ self.pick(SEA)+ window.edge_select._choose("top")+ window._apply_settings()+ stamp = next(peer for peer in self.store.current()["peers"] if peer["id"] == SEA)["side_set_at"]+ self.assertEqual(self.sent, [(SEA, "top", stamp)])+ window.windows_input.send_arrangement.assert_not_called()+ self.controller.send_arrangement = lambda *_args: False+ window.edge_select._choose("bottom")+ window._apply_settings()+ window.windows_input.send_arrangement.assert_called_once()+ self.assertEqual(window.windows_input.send_arrangement.call_args.args[:2], (SEA, "bottom"))++ def test_the_engine_is_built_again_once_a_machines_ways_change(self):+ window = self.two()+ self.pick(SEA)+ with mock.patch.object(self.controller, "zones_changed") as rebuilt:+ self.toggle("notch")+ window._apply_settings()+ rebuilt.assert_called()++ def test_a_way_that_overlaps_an_existing_side_shows_the_share_panel_without_writing(self):+ window = self.two()+ self.pick(SEA)+ # Moved onto Bee's side, Sea keeps the side and its ways there go off (core/ways.py settle).+ window.edge_select._choose("right")+ window._apply_settings()+ before = copy.deepcopy(self.store.current())+ self.toggle("edge")+ window._apply_settings()+ self.assertFalse(window.method_boxes["edge"].value)+ self.assertFalse(window.share_box.isHidden())+ self.assertIn("Bee already crosses from the right edge", window.share_sentence.text)+ self.assertTrue(window.blocked_note.view.isHidden())+ self.assertEqual(window.edge_select.value, "right")+ self.assertEqual(self.store.current()["zones"], before["zones"])++ def test_a_corner_clash_keeps_its_refusal_naming_both_and_the_controls_go_back(self):+ window = self.build(+ [(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "right"})],+ [{"peer": BEE, "kind": "corner", "corner": "top_right", "edge": "right"},+ {"peer": SEA, "kind": "corner", "corner": "top_right", "edge": "right", "off": True}])+ self.pick(SEA)+ before = copy.deepcopy(self.store.current())+ self.toggle("corner")+ window._apply_settings()+ self.assertEqual(window.message_label.ink, "fault")+ self.assertIn("Bee", window.message_label.text)+ self.assertIn("Sea", window.message_label.text)+ self.assertFalse(window.method_boxes["corner"].value)+ self.assertEqual(self.store.current()["zones"], before["zones"])++ def test_switching_machines_saves_a_change_still_waiting_first(self):+ window = self.two()+ self.toggle("corner")+ self.assertTrue(self.later)+ self.pick(SEA)+ self.assertIn("corner", self.ways_of(BEE)["methods"])+ sea = self.ways_of(SEA)+ for call in self.later:+ call()+ self.assertEqual(self.ways_of(SEA), sea)+ self.assertEqual(self.methods(), ["part", "corner", "shortcut"])++ def test_the_shortcut_resistance_and_drag_guard_stay_this_macs_own(self):+ window = self.two()+ self.pick(SEA)+ held = (self.ways_of(BEE), self.ways_of(SEA))+ dragging = self.store.load().crossing["block_while_dragging"]+ self.toggle("shortcut")+ window.dragging_box._toggle()+ window._apply_settings()+ self.assertFalse(self.store.current()["shortcut"])+ self.assertNotIn("shortcut", self.store.load().crossing["methods"])+ self.assertEqual(self.store.load().crossing["block_while_dragging"], not dragging)+ self.assertEqual((self.ways_of(BEE), self.ways_of(SEA)), held)+ self.pick(BEE)+ self.assertFalse(window.method_boxes["shortcut"].value)++ def test_a_machine_with_no_side_shows_none_with_several_paired(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}), (OAK, token(200), "Oak")],+ [{"peer": BEE, "kind": "edge"}])+ self.pick(OAK)+ self.assertIsNone(window.edge_select.value or None)+ window._apply_settings()+ self.assertEqual(self.ways_of(OAK)["side"], "")++ def test_removing_the_chosen_machine_falls_back_to_the_first_and_one_left_hides_the_picker(self):+ window = self.two()+ self.pick(SEA)+ self.store.remove_peer(token(150))+ window.peers_changed()+ self.assertTrue(window.machine_row.isHidden())+ self.assertEqual(window.edge_select.value, "right")+ self.assertEqual(window.edge_caption.text, "Where the other machine is")++ def test_a_third_machine_paired_joins_the_picker(self):+ window = self.two()+ self.store.add_peer(entry(OAK, token(200), "Oak"))+ window.peers_changed()+ self.assertEqual([title for _value, title in window.machine_select.choices], ["Bee", "Sea", "Oak"])++ def test_a_name_learnt_on_a_link_reaches_the_picker_on_the_next_tick(self):+ window = self.two()+ settings = copy.deepcopy(self.store.current())+ settings["peers"][1]["name"] = "Sea Studio"+ self.store.save_settings(settings)+ window.refresh()+ self.assertEqual([title for _value, title in window.machine_select.choices], ["Bee", "Sea Studio"])++ def test_an_arrangement_from_the_chosen_machine_moves_its_control(self):+ window = self.two()+ self.pick(SEA)+ window.apply_arrangement(SEA, "top", 5000, SEA)+ self.assertEqual(window.edge_select.value, "bottom")+ self.assertEqual(window.machine_select.value, SEA)++ def test_an_arrangement_arriving_keeps_a_change_still_waiting(self):+ window = self.two()+ self.pick(SEA)+ self.toggle("notch")+ window.apply_arrangement(BEE, "right", 5000, BEE)+ self.assertIn("notch", self.ways_of(SEA)["methods"])+ self.assertTrue(window.method_boxes["notch"].value)+ self.assertEqual(self.ways_of(BEE)["side"], "left")++ def test_a_machine_paired_keeps_a_change_still_waiting(self):+ window = self.two()+ self.pick(SEA)+ self.toggle("notch")+ self.store.add_peer(entry(OAK, token(200), "Oak"))+ window.peers_changed()+ self.assertIn("notch", self.ways_of(SEA)["methods"])+ self.assertTrue(window.method_boxes["notch"].value)++ def test_a_change_waiting_for_a_machine_just_removed_is_dropped_without_a_fault(self):+ window = self.two()+ self.pick(SEA)+ self.toggle("notch")+ self.store.remove_peer(token(150))+ window.peers_changed()+ self.assertNotIn(SEA, [item["id"] for item in self.store.current()["peers"]])+ self.assertEqual(window.machine_select, None)++ def test_a_missing_pairing_is_noted_under_the_ways(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right", "allow_drive": True, "paired_with": []}),+ (SEA, token(150), "Sea", {"side": "left", "allow_drive": True, "paired_with": [BEE]})],+ [{"peer": BEE, "kind": "edge"}])+ expected = ways.missing_sentence(self.store.current(), SEA, "this Mac")+ self.assertTrue(expected)+ self.assertEqual(window.missing_note.view.isHidden(), not ways.missing_sentence(self.store.current(), BEE, "this Mac"))+ self.pick(SEA)+ self.assertFalse(window.missing_note.view.isHidden())+ self.assertEqual(window.missing_note.text, expected)+++class WayBack(Page):+ """`arrangement`'s `way_back` (WIRE.md section 8): what each machine is told, and what it said."""++ def entry_of(self, peer):+ return next(item for item in self.store.current()["peers"] if item["id"] == peer)++ def test_turning_off_every_way_to_a_machine_tells_it_so_with_its_side_as_it_was(self):+ window = self.two()+ self.pick(SEA)+ self.toggle("part")+ self.toggle("corner")+ window._apply_settings()+ self.assertEqual(self.sent, [(SEA, "left", 100)])+ self.assertEqual(self.sent_by, [self.store.current()["machine_id"]])+ self.toggle("corner")+ window._apply_settings()+ self.assertEqual(len(self.sent), 2)++ def test_moving_one_machine_tells_every_machine_whose_way_back_it_changed(self):+ # Sol's review, 02-10-2026: Sea was told Bee holds its side, and moving Bee told Bee alone,+ # so Sea's page kept naming Bee as in the way.+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "right"})],+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge", "off": True}])+ self.assertEqual(ways.way_back_by(self.store.current(), SEA), BEE)+ self.pick(BEE)+ window.edge_select._choose("top")+ window._apply_settings()+ self.assertEqual(sorted(peer for peer, _edge, _at in self.sent), sorted([BEE, SEA]))+ self.assertIsNone(ways.way_back_by(self.store.current(), SEA))++ def test_removing_the_machine_in_the_way_tells_the_one_it_blocked(self):+ # Opus review: unpairing Sea left Bee told Sea held its side until Bee's link next came up.+ window = self.build([(BEE, token(100), "Bee", {"side": "left"}), (SEA, token(150), "Sea", {"side": "left"})],+ [{"peer": BEE, "kind": "edge", "off": True}, {"peer": SEA, "kind": "edge"}])+ self.assertEqual(ways.way_back_by(self.store.current(), BEE), SEA)+ window.panel._remove(token(150))+ self.assertIn(BEE, [peer for peer, _edge, _at in self.sent])++ def test_an_arrangement_that_changed_something_is_answered_with_this_macs_own(self):+ window = self.two()+ window.apply_arrangement(SEA, "top", 5000, SEA, True)+ self.assertEqual(self.sent, [(SEA, "bottom", 5000)])+ self.assertEqual(self.sent_by, [SEA])+ self.assertIs(self.entry_of(SEA)["way_back"], True)+ window.apply_arrangement(SEA, "top", 5000, SEA, True)+ self.assertEqual(len(self.sent), 1)+ window.apply_arrangement(SEA, "top", 5000, SEA, False)+ self.assertEqual(len(self.sent), 2)+ self.assertIs(self.entry_of(SEA)["way_back"], False)++ def test_the_answer_goes_over_the_link_the_machine_opened_when_this_macs_is_down(self):+ window = self.two()+ self.controller.send_arrangement = lambda *_args: False+ window.apply_arrangement(SEA, "top", 5000, SEA, True)+ window.windows_input.send_arrangement.assert_called_once_with(SEA, "bottom", 5000, SEA)+++class TheNotes(Page):+ """What the page says under the ways about a machine it cannot reach, or that cannot reach back."""++ def test_a_machine_whose_side_another_holds_is_named_in_the_share_panel(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "right"})],+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge", "off": True}])+ self.pick(SEA)+ self.assertFalse(window.share_box.isHidden())+ self.assertIn("Bee already crosses from the right edge", window.share_sentence.text)+ self.assertTrue(window.blocked_note.view.isHidden())+ self.pick(BEE)+ self.assertTrue(window.share_box.isHidden())++ def test_a_machine_that_said_no_way_leads_back_is_named_until_it_says_one_does(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}),+ (SEA, token(150), "Sea", {"side": "left", "way_back": False})],+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge"}])+ self.assertTrue(window.no_way_back_note.view.isHidden())+ self.pick(SEA)+ self.assertFalse(window.no_way_back_note.view.isHidden())+ self.assertEqual(window.no_way_back_note.text, ways.no_way_back_sentence(self.store.current(), SEA))+ window.apply_arrangement(SEA, "right", 5000, SEA, True)+ self.assertTrue(window.no_way_back_note.view.isHidden())++ def test_an_arrangement_names_the_machine_holding_the_way_back_side(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}),+ (SEA, token(150), "Sea", {"side": "left"})],+ [{"peer": BEE, "kind": "edge"}, {"peer": SEA, "kind": "edge", "off": True}])+ self.pick(SEA)+ window.apply_arrangement(SEA, "right", 5000, SEA, False, BEE)+ entry = next(item for item in self.store.current()["peers"] if item["id"] == SEA)+ self.assertEqual(entry["way_back_by"], BEE)+ self.assertIn("Bee on its right too", window.no_way_back_note.text)+++class TheOverview(Page):+ def test_the_address_shown_is_the_machine_the_status_speaks_of(self):+ window = self.build([(BEE, token(100), "Bee", {"host": "192.0.2.31"}), (SEA, token(150), "Sea", {"host": "192.0.2.32"})])+ with mock.patch.object(self.controller, "_in_question", return_value=SEA):+ window._show_peer()+ self.assertIn("192.0.2.32", window.peer_footer.text)+++class TheDrawing(Page):+ def test_the_drawing_has_every_machine_with_the_chosen_one_marked(self):+ window = self.build([(BEE, token(100), "Bee", {"side": "right"}), (SEA, token(150), "Sea", {"side": "top"}),+ (OAK, token(200), "Oak")], [{"peer": BEE, "kind": "edge"}])+ self.pick(SEA)+ machines = window.arrangement_diagram.machines+ self.assertEqual([(m["label"], m["side"], m["chosen"]) for m in machines],+ [("Bee", "right", False), ("Sea", "top", True), ("Oak", "", False)])+ self.assertEqual(machines[0]["methods"], ["edge"])+ label = window.arrangement_diagram.accessibilityLabel()+ for words in ("Bee is to the right of this Mac.", "Sea is above this Mac.", "Oak is not placed yet."):+ self.assertIn(words, label)+ drawing = window.arrangement_diagram+ drawing.setFrame_(((0, 0), (480, drawing.HEIGHT)))+ drawing._draw(False)+ self.assertEqual(drawing.not_placed.string(), "Not placed yet: Oak")+ self.assertTrue(drawing.screens[OAK][0].isHidden())+ self.assertFalse(drawing.screens[SEA][0].isHidden())++ def test_the_chosen_machines_drawing_follows_the_controls_before_the_save(self):+ window = self.two()+ self.pick(SEA)+ window.edge_select._choose("bottom")+ sea = window.arrangement_diagram.machines[1]+ self.assertEqual((sea["side"], sea["chosen"]), ("bottom", True))+++class Wording(Page):+ def test_the_switch_is_same_on_all_machines(self):+ window = self.two()+ self.assertEqual(window.same_switch.words.text, "Same on all machines")+++class TheMenuBar(Page):+ def tray(self):+ tray = mock.Mock()+ tray.controller = self.controller+ tray.control_window = self.window+ return tray++ def test_a_machines_item_sends_input_to_it(self):+ self.two()+ self.controller.event_tap = object()+ self.controller.input_error = None+ with mock.patch.object(self.controller, "set_redirecting", return_value=True) as switch:+ kvm_bridge_app.TrayApp._send_to(self.tray(), SEA)+ switch.assert_called_once_with(True, peer=SEA)++ def test_the_item_of_the_machine_input_is_on_brings_it_back(self):+ self.two()+ self.controller.event_tap = object()+ self.controller.input_error = None+ self.controller.owner.on = SEA+ self.controller.redirecting = True+ with mock.patch.object(self.controller, "set_redirecting", return_value=True) as switch:+ kvm_bridge_app.TrayApp._send_to(self.tray(), SEA)+ switch.assert_called_once_with(False)++ def test_another_machines_item_moves_input_straight_there(self):+ self.two()+ self.controller.event_tap = object()+ self.controller.input_error = None+ self.controller.owner.on = BEE+ self.controller.redirecting = True+ with mock.patch.object(self.controller, "set_redirecting", return_value=True) as switch:+ kvm_bridge_app.TrayApp._send_to(self.tray(), SEA)+ self.assertEqual(switch.call_args_list, [mock.call(True, peer=SEA)])++ def menu_tray(self):+ tray = self.tray()+ # The menu rumps.App keeps, which rumps does not export.+ tray.menu = rumps_module.Menu()+ tray.toggle_item = kvm_bridge_app.rumps.MenuItem(kvm_bridge_app.TOGGLE_ITEM)+ tray.menu.add(tray.toggle_item)+ tray.menu.add(kvm_bridge_app.rumps.MenuItem("Pause crossing"))+ tray._send_keys = []+ return tray++ def titles(self, tray):+ return [item.title for item in tray.menu.values() if not item.hidden]++ def test_with_two_machines_the_menu_has_an_item_each_in_place_of_the_one(self):+ self.two()+ tray = self.menu_tray()+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.assertEqual(self.titles(tray), ["Send input to Bee", "Send input to Sea", "Pause crossing"])+ self.controller.owner.on = SEA+ self.controller.redirecting = True+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.assertEqual(self.titles(tray), ["Send input to Bee", "Bring input back", "Pause crossing"])++ def test_with_one_machine_the_menu_keeps_its_one_item(self):+ self.build([(BEE, token(100), "Bee", {"side": "left"})])+ tray = self.menu_tray()+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.assertEqual(self.titles(tray), [kvm_bridge_app.TOGGLE_ITEM, "Pause crossing"])++ def test_a_machine_switched_off_leaves_the_menu(self):+ self.two()+ tray = self.menu_tray()+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.store.set_peer(token(150), send=False)+ kvm_bridge_app.TrayApp._machine_items(tray)+ self.assertEqual(self.titles(tray), [kvm_bridge_app.TOGGLE_ITEM, "Pause crossing"])++ def test_without_the_permissions_nothing_is_sent_and_it_says_why(self):+ self.two()+ self.controller.event_tap = None+ tray = self.tray()+ with mock.patch.object(self.controller, "set_redirecting") as switch:+ kvm_bridge_app.TrayApp._send_to(tray, SEA)+ switch.assert_not_called()+ tray.notify_user.assert_called_once()+++if __name__ == "__main__":+ unittest.main()diff --cc mac_app/tests/test_effect_fires.pyindex ea92730,02750ab..0ff2b65--- a/mac_app/tests/test_effect_fires.py+++ b/mac_app/tests/test_effect_fires.py@@@ -54,6 -49,6 +54,7 @@@ class _FakeTrayAppself.notch_beam = mock.Mock()self.notch_island = mock.Mock()self.haptics = mock.Mock()++ self.gesture_overlay = mock.Mock()class MainThreadHopTest(unittest.TestCase):@@@ -208,8 -203,8 +209,36 @@@ class HomeArrivalTest(unittest.TestCaseapp.effects_overlay.switched.assert_not_called()++class GestureOverlayOnReturnTest(unittest.TestCase):++ """Toby 06-10: after the shortcut a grey box sat round the pointer and went only after the++ landing animation. The gesture panel takes clicks, so it has to go as input comes home."""++++ def test_input_coming_home_takes_the_gesture_panel_down_at_once(self):++ for kind, step in (("home", crossing.Step(pin=(400.0, 300.0))),++ ("arrive", crossing.Step(mac_edge="right", pin=(1727.0, 558.0)))):++ with self.subTest(kind=kind):++ app = _FakeTrayApp(_feel())++ app._crossing_feedback_main(kind, step)++ app.gesture_overlay.sync.assert_called_once_with()++++ def test_a_push_at_the_edge_leaves_the_gesture_panel_to_the_status_tick(self):++ app = _FakeTrayApp(_feel())++ app._crossing_feedback_main("pressure", crossing.Step(pressure=0.2))++ app.gesture_overlay.sync.assert_not_called()++++ def test_the_gesture_panel_is_one_step_off_clear(self):++ """A clear panel lets gestures through to the app beneath; 0.02 read as a grey box."""++ from kvm_bridge_app import GestureOverlay++ overlay = GestureOverlay(controller=None, logger=logging.getLogger("test-effect-fires"))++ overlay._ensure_panel()++ alpha = overlay.panel.backgroundColor().alphaComponent()++ self.assertGreater(alpha, 0.0)++ self.assertLessEqual(alpha, 1.0 / 255.0 + 1e-6)++ self.assertFalse(overlay.panel.isVisible())++++class DrivenReturnEdgeTest(unittest.TestCase):- """The PC-driven return edge: receiver.py's pressure_callback and arrival_callback, wired in+ """The PC-driven return edge: LinkResponder's pressure_callback and arrival_callback, wired inkvm_bridge_app.py's TrayApp.__init__ as WindowsInput(pressure_callback=self._driven_pressure,arrival_callback=self._driven_arrival), land here after the main-thread hop proved above."""diff --cc mac_app/tests/test_link_state.pyindex 57610c6,31bed75..037dd9b--- a/mac_app/tests/test_link_state.py+++ b/mac_app/tests/test_link_state.py@@@ -85,47 -54,31 +85,53 @@@ class LinkStateTest(unittest.TestCase)self.assertState("waking", "amber", waking=True, connected=False)def test_tunnel_is_tagged(self):- state = link_state.describe(controller(status=link_state.TUNNEL_STATUS))+ state = link_state.describe(controller(via_tunnel=True))self.assertEqual((state.key, state.tag), ("mac", "Tunnel"))-- def test_every_failure_status_has_a_word(self):- cases = {- AUTH_FAILED_STATUS: "token",- OLD_RECEIVER_STATUS: "version",- "Windows receiver speaks Beamer protocol v3, this Mac v4 — update both apps": "version",- "Windows rejected the connection: busy": "rejected",- NOT_WOKEN_STATUS: "not_woken",- connection_error_message(OSError(65, "No route")): "unreachable",- connection_error_message(OSError(65, "Open /Applications/Beamer Tunnel.command")): "blocked",- connection_error_message(OSError(61, "Refused")): "not_listening",- connection_error_message(TimeoutError()): "unreachable",- "Windows stopped responding": "stopped",- "Connecting to 192.168.1.3:51820": "waiting",- "Waiting to connect": "waiting",- "Settings saved; reconnecting": "waiting",- "Windows closed the connection": "dropped",- "send failed: broken pipe": "dropped",- "": "dropped",- }- for status, key in cases.items():- with self.subTest(status=status):- self.assertState(key, "amber" if key == "waiting" else "fault", status=status, connected=False)+ self.assertIn("tunnel", state.detail)++ def test_every_failure_kind_has_a_word(self):+ ended = lambda number, name="Windows": connection_ended(OSError(number, "x"), name)+ cases = [+ ("unauthenticated", "Windows could not be authenticated", "token"),+ ("wrong_id", "Windows has this pairing under another machine", "token"),+ ("different", "A different Beamer answered", "token"),+ ("unreadable", "Windows could not read what this machine sent first", "token"),++ ("forgotten", "Windows no longer has this pairing: remove Windows here and pair the two again", "forgotten"),+ ("older", "Update Beamer on Windows: it is older than this one", "version"),+ ("newer", "Windows runs a newer Beamer", "version"),+ ("not_beamer", "Windows did not answer as a Beamer", "version"),+ ("failed", not_woken_status("Windows"), "not_woken"),+ ("failed", not_woken_status("Desk (AAAA)"), "not_woken"),+ (ended(65).kind, ended(65).text, "unreachable"),+ (ended(51).kind, ended(51).text, "unreachable"),+ (connection_ended(TimeoutError(), "Windows").kind, connection_ended(TimeoutError(), "Windows").text, "unreachable"),+ ("blocked", "macOS 27 blocked direct LAN access. Open /Applications/Beamer Tunnel.command.", "blocked"),+ (ended(61).kind, ended(61).text, "not_listening"),+ ("stopped", "Windows stopped responding", "stopped"),+ ("closed", "Windows closed the connection", "stopped"),+ ("failed", "Connecting to 192.168.1.3:51820", "waiting"),+ ("failed", "Waiting to connect", "waiting"),+ ("failed", "Settings saved; reconnecting", "waiting"),+ ("failed", "Connection failed: broken pipe", "dropped"),+ ("failed", "", "dropped"),+ ("off", "This link was stopped", "dropped"),+ ("none", "", "dropped"),+ ]+ for kind, status, key in cases:+ with self.subTest(kind=kind, status=status):+ self.assertState(key, "amber" if key == "waiting" else "fault", kind=kind, status=status, connected=False)+++ def test_a_machine_that_removed_this_pairing_is_said_to_have_done_so_not_to_have_refused_a_token(self):++ state = link_state.describe(controller(kind="forgotten", connected=False, peer_label="Desk"))++ self.assertEqual(state.word, "Pairing removed")++ self.assertEqual(state.detail, "Desk no longer has this pairing: remove Desk here and pair the two again.")+++ def test_the_word_comes_from_the_kind_not_the_sentence(self):+ self.assertState("token", "fault", kind="unauthenticated", status="Something this build never said", connected=False)+ self.assertState("dropped", "fault", kind="failed", status="Windows is unreachable from this machine.", connected=False)++ def test_a_stale_failure_kind_is_ignored_while_connected(self):+ self.assertState("mac", "ink", kind="refused")def test_unpaired(self):cfg = SimpleNamespace(host="192.168.1.3", port=51820, auth_token="", pc_name="")diff --cc mac_app/tests/test_machines_panel.pyindex 2b48d02,0000000..acc3644mode 100644,000000..100644--- a/mac_app/tests/test_machines_panel.py+++ b/mac_app/tests/test_machines_panel.py@@@ -1,760 -1,0 +1,774 @@@+"""The Overview's machines list and pairing sheet in the real settings window: built as+the README's screenshots build it, never put on screen, starting no network."""++import base64+import json+import logging+import sys+import tempfile+import time+import unittest+from pathlib import Path+from unittest import mock++sys.path.insert(0, str(Path(__file__).resolve().parents[2]))++import AppKit # noqa: E402++AppKit.NSApplication.sharedApplication()++import bridge # noqa: E402+import kvm_bridge_app # noqa: E402+import settings_store # noqa: E402+from bridge_fakes import PAIRED_TOKEN # noqa: E402- from core import pairing # noqa: E402++from core import feature_flags, pairing # noqa: E402+from fake_link import FakeLink # noqa: E402+from wake import WakingController # noqa: E402++FIRST = base64.urlsafe_b64encode(bytes(range(1, 17))).decode().rstrip("=")+SECOND = base64.urlsafe_b64encode(bytes(range(21, 37))).decode().rstrip("=")+SECOND_TOKEN = base64.urlsafe_b64encode(bytes(range(100, 132))).decode().rstrip("=")+THIRD = base64.urlsafe_b64encode(bytes(range(60, 76))).decode().rstrip("=")+THIRD_TOKEN = base64.urlsafe_b64encode(bytes(range(200, 232))).decode().rstrip("=")+++def entry(ident, token, name, platform="windows", host="192.0.2.30", **extra):+ return {**settings_store.PEER_DEFAULTS, "id": ident, "name": name, "platform": platform, "token": token,+ "host": host, "port": 24820, "paired_at": 1_700_000_000, **extra}+++class FakeService:+ """The parts of PairingService the panel reads and calls."""++ def __init__(self):+ self.code = None+ self.seconds_left = 0+ self.outcome = None+ self.known = None+ self.error = None+ self.tcp_error = None+ self.tcp_port = 24821+ self.heard = []+ self.begun = 0+ self.cancelled = 0+ self.paired = []+ self.qr = "beamer://pair?host=192.0.2.9&port=24821&code=123456&k=" + "A" * 22+ self.result = None++ def begin_pairing(self):+ self.begun += 1+ self.code = "482913"+ self.seconds_left = 60+ return self.code++ def cancel_pairing(self):+ self.cancelled += 1+ self.code = None++ def machines(self):+ return self.heard++ def qr_text(self, address=None):+ return self.qr if self.code else None++ def pair(self, machine, code):+ self.paired.append(("machine", machine["name"], code))+ return self._done()++ def pair_by_address(self, address, code, port=24821):+ self.paired.append(("address", address, code))+ return self._done()++ def _done(self):+ if isinstance(self.result, Exception):+ raise self.result+ return self.result+++def heard(name="Laptop", pair_id="abc", **extra):+ return {"name": name, "address": "192.0.2.40", "port": 24820, "reply_port": 24821, "pair_id": pair_id,+ "pairing": 3, "platform": "macos", "id": None, **extra}+++class Base(unittest.TestCase):+ def setUp(self):+ self.directory = tempfile.TemporaryDirectory()+ path = Path(self.directory.name) / "config.json"+ raw = settings_store.config_to_raw(settings_store.editable_default_config())+ raw.update(host="192.0.2.20", auth_token=PAIRED_TOKEN, pc_name="Studio")+ path.write_text(json.dumps(raw))+ self.store = settings_store.SettingsStore(path)+ logger = logging.getLogger("test-machines-panel")+ cfg = self.store.load()+ book, identity = bridge.links_from_store(self.store, "1.5.0")+ self.controller = WakingController(cfg, logger=logger, book=book, identity=identity, link_factory=FakeLink)+ with mock.patch.object(kvm_bridge_app, "accessibility_granted", return_value=True), \+ mock.patch.object(kvm_bridge_app, "input_monitoring_granted", return_value=True):+ self.window = kvm_bridge_app.ControlWindow.alloc().initWithController_settingsStore_logger_(+ self.controller, self.store, logger)+ self.panel = self.window.panel+ self.service = FakeService()+ self.panel.service = self.service+ self.directions = []+ self.window.direction_handler = lambda token, **change: self.directions.append((token, change))++ def tearDown(self):+ self.window.appearance_watch.stop()+ self.directory.cleanup()++ def pair(self, ident, token, name, **extra):+ self.store.add_peer(entry(ident, token, name, **extra))+ self.window.peers_changed()++ def rows(self):+ return [view for view in self.panel.list.arrangedSubviews()]++ def texts(self, view):+ found = []+ if isinstance(view, AppKit.NSTextField):+ found.append(view.stringValue())+ for sub in view.subviews():+ found.extend(self.texts(sub))+ return found+++class ListTests(Base):+ def test_the_migrated_machine_is_listed_by_its_name_and_where_it_is(self):+ self.panel.refresh()+ self.assertEqual(len(self.rows()), 1)+ self.assertIn("Studio", self.rows()[0].accessibilityLabel())+ self.assertTrue(self.panel.empty.view.isHidden())++ def test_every_paired_machine_is_a_row_and_two_of_one_name_show_the_end_of_their_ids(self):+ self.pair(FIRST, SECOND_TOKEN, "Studio")+ self.panel.refresh()+ labels = [row.accessibilityLabel() for row in self.rows()]+ self.assertEqual(len(labels), 2)+ self.assertIn("Studio", labels[0])+ self.assertIn(f"Studio ({FIRST[-4:]})", labels[1])++ def test_with_nothing_paired_the_list_says_so_and_the_sheet_is_open(self):+ self.store.remove_peer(PAIRED_TOKEN)+ self.window.peers_changed()+ self.panel.refresh()+ self.assertEqual(self.rows(), [])+ self.assertFalse(self.panel.empty.view.isHidden())+ self.assertEqual(self.panel.empty.text, "No machines paired yet.")+ self.assertFalse(self.panel.sheet.view.isHidden())++ def test_with_machines_paired_the_sheet_waits_for_the_button(self):+ self.panel.refresh()+ self.assertTrue(self.panel.sheet.view.isHidden() or self.panel.open is False)+ self.assertEqual(self.panel.pair_button.title, "Pair a machine")+ self.panel._toggle_sheet()+ self.assertTrue(self.panel.open)+ self.assertEqual(self.panel.pair_button.title, "Cancel")+ self.panel._toggle_sheet()+ self.assertFalse(self.panel.open)++ def test_the_machines_lead_the_page_with_and_without_existing_machines(self):+ body = self.window.overview_body+ self.panel.refresh()+ self.window._place_machines(False)+ order = list(body.arrangedSubviews())+ self.assertEqual(order.index(self.panel.machines_module.view), 1)+ self.window._place_machines(True)+ order = list(body.arrangedSubviews())+ self.assertEqual(order[1:3], [self.panel.machines_module.view, self.panel.sheet.view])+ self.assertNotIn(order[0], (self.panel.machines_module.view, self.panel.sheet.view))++ def test_addresses_are_dots_while_they_are_hidden(self):+ self.window.controller.cfg.hide_addresses = True+ self.panel._rows_key = None+ self.panel.refresh()+ text = " ".join(self.texts(self.rows()[0]))+ self.assertNotIn("192.0.2.20", text)+++ def texts(self, view):+ found = []+ if isinstance(view, AppKit.NSTextField):+ found.append(view.stringValue())+ for sub in view.subviews():+ found.extend(self.texts(sub))+ return found+++class DirectionAndRemovalTests(Base):+ def test_each_switch_hands_the_handler_its_machine_and_one_change(self):+ self.panel.refresh()+ row = self.rows()[0]+ self.assertEqual(len([view for view in self.descend(row)+ if view.accessibilityRole() == AppKit.NSAccessibilityCheckBoxRole]), 1)+ self.panel._toggle_directions(PAIRED_TOKEN)+ row = self.rows()[0]+ switches = [view for view in self.descend(row) if view.accessibilityRole() == AppKit.NSAccessibilityCheckBoxRole]+ self.assertEqual(len(switches), 3)+ switches[1].callback()+ switches[2].callback()+ token = PAIRED_TOKEN+ self.assertEqual([call[0] for call in self.directions], [token, token])+ self.assertEqual({tuple(call[1]) for call in self.directions}, {("send",), ("allow_drive",)})++ def descend(self, view):+ yield view+ for sub in view.subviews():+ yield from self.descend(sub)++ def test_remove_asks_first_and_keep_changes_nothing(self):+ self.panel.refresh()+ self.panel._ask_to_remove(PAIRED_TOKEN)+ self.assertEqual(self.panel.removing, PAIRED_TOKEN)+ text = " ".join(self.texts_of(self.rows()[0]))+ self.assertIn("Remove Studio?", text)+ self.panel._keep()+ self.assertIsNone(self.panel.removing)+ self.assertEqual(len(self.store.current()["peers"]), 1)++ def texts_of(self, view):+ return [v.stringValue() for v in self.descend(view) if isinstance(v, AppKit.NSTextField)]++ def test_removing_takes_the_machine_its_link_and_its_row(self):+ self.pair(FIRST, SECOND_TOKEN, "Laptop")+ self.assertEqual(len(self.controller.links), 2)+ self.panel._remove(SECOND_TOKEN)+ self.assertEqual([peer["token"] for peer in self.store.current()["peers"]], [PAIRED_TOKEN])+ self.assertEqual(list(self.controller.links), [PAIRED_TOKEN])+ self.panel.refresh()+ self.assertEqual(len(self.rows()), 1)++ def test_removing_the_first_machine_leaves_the_next_the_one_the_window_reads(self):+ self.pair(FIRST, SECOND_TOKEN, "Laptop")+ self.panel._remove(PAIRED_TOKEN)+ self.assertEqual(self.controller.cfg.auth_token, SECOND_TOKEN)+ self.assertEqual(self.window.connection_label if hasattr(self.window, "connection_label") else "Laptop", "Laptop")++ def test_a_removal_that_cannot_be_saved_says_so_and_keeps_the_machine(self):+ with mock.patch.object(self.store, "remove_peer", side_effect=settings_store.SettingsError("disk full")):+ self.panel._remove(PAIRED_TOKEN)+ self.assertEqual(len(self.store.current()["peers"]), 1)+++class FocusTests(Base):+ """A rebuild of the rows (a state changing, Remove asking) leaves focus on the control it was on."""++ def controls(self):+ found = {}++ def walk(view):+ ident = getattr(view, "focus_id", None)+ if ident is not None:+ found[ident] = view+ for sub in view.subviews():+ walk(sub)++ walk(self.panel.list)+ return found++ def focus(self, ident):+ view = self.controls()[ident]+ self.assertTrue(self.window.window.makeFirstResponder_(view))+ return view++ def focused(self):+ view = self.window.window.firstResponder()+ while view is not None and getattr(view, "focus_id", None) is None:+ view = view.superview() if hasattr(view, "superview") else None+ return getattr(view, "focus_id", None)++ def test_a_rebuild_keeps_focus_on_the_same_switch(self):+ self.panel.refresh()+ self.panel._toggle_directions(PAIRED_TOKEN)+ self.focus((PAIRED_TOKEN, "drives"))+ self.panel.invalidate()+ self.panel.refresh()+ self.assertEqual(self.focused(), (PAIRED_TOKEN, "drives"))++ def test_asking_to_remove_puts_focus_on_keep_and_keeping_puts_it_back_on_remove(self):+ self.panel.refresh()+ self.panel._toggle_directions(PAIRED_TOKEN)+ self.focus((PAIRED_TOKEN, "remove"))+ self.panel._ask_to_remove(PAIRED_TOKEN)+ self.assertEqual(self.focused(), (PAIRED_TOKEN, "keep"))+ self.panel._keep()+ self.assertEqual(self.focused(), (PAIRED_TOKEN, "remove"))++ def test_focus_outside_the_list_is_left_alone(self):+ self.panel.refresh()+ self.window.window.makeFirstResponder_(self.panel.pair_button.view)+ self.panel.invalidate()+ self.panel.refresh()+ self.assertIs(self.window.window.firstResponder(), self.panel.pair_button.view)++ def test_a_removed_machines_focus_is_not_chased(self):+ self.pair(FIRST, SECOND_TOKEN, "Laptop")+ self.panel.refresh()+ self.panel._toggle_directions(SECOND_TOKEN)+ self.focus((SECOND_TOKEN, "drives"))+ self.panel._remove(SECOND_TOKEN)+ self.panel.refresh()+ self.assertNotEqual(self.focused(), (SECOND_TOKEN, "drives"))+++class FollowTheFirstMachineTests(Base):+ def test_a_pairing_stored_from_the_service_thread_reaches_the_controller_on_the_next_tick(self):+ self.store.remove_peer(PAIRED_TOKEN)+ self.window.peers_changed()+ self.assertEqual(self.controller.cfg.auth_token, "")+ self.store.add_peer(entry(FIRST, SECOND_TOKEN, "Laptop"))+ self.assertEqual(self.controller.cfg.auth_token, "")+ self.window._follow_first_peer()+ self.assertEqual(self.controller.cfg.auth_token, SECOND_TOKEN)+ self.assertEqual([peer["token"] for peer in self.store.current()["peers"]], [SECOND_TOKEN])+++class ShowingACodeTests(Base):++ # The pairing QR is hidden until 1.6 (core.feature_flags); these tests prove both states.++ def test_while_the_qr_flag_is_off_the_code_shows_without_a_qr(self):++ with mock.patch.object(feature_flags, "PAIRING_QR_VISIBLE", False), \++ mock.patch.object(kvm_bridge_app.machines_panel.pairing, "pairing_address", return_value="192.0.2.9"):++ self.panel._toggle_sheet()++ self.panel._show_code()++ self.panel.refresh()++ self.assertEqual(self.panel.shown_code_boxes.value, "482913")++ self.assertIn("192.0.2.9", self.panel.code_address.text)++ self.assertTrue(self.panel.qr_view.isHidden())++ self.assertTrue(self.panel.qr_caption.view.isHidden())++++ @mock.patch.object(feature_flags, "PAIRING_QR_VISIBLE", True)+ def test_the_code_is_shown_in_two_groups_with_its_address_and_a_qr(self):+ with mock.patch.object(kvm_bridge_app.machines_panel.pairing, "pairing_address", return_value="192.0.2.9"):+ self.panel._toggle_sheet()+ self.panel._show_code()+ self.panel.refresh()+ self.assertEqual(self.service.begun, 1)+ self.assertEqual(self.panel.shown_code_boxes.value, "482913")+ self.assertEqual(self.panel.code_expiry.text, "Expires in 60 s")+ self.assertIn("192.0.2.9", self.panel.code_address.text)+ self.assertFalse(self.panel.qr_view.isHidden())+ self.assertIsNotNone(self.panel.qr_view.image())+ self.assertTrue(self.panel.show_button.view.isHidden())+++ @mock.patch.object(feature_flags, "PAIRING_QR_VISIBLE", True)+ def test_with_addresses_hidden_there_is_no_qr_and_no_address(self):+ self.controller.cfg.hide_addresses = True+ with mock.patch.object(kvm_bridge_app.machines_panel.pairing, "pairing_address", return_value="192.0.2.9"):+ self.panel._toggle_sheet()+ self.panel._show_code()+ self.panel.refresh()+ self.assertTrue(self.panel.qr_view.isHidden())+ self.assertNotIn("192.0.2.9", self.panel.code_address.text)+ self.assertIn("hidden", self.panel.qr_caption.text)++ def test_cancel_drops_the_code(self):+ self.panel._toggle_sheet()+ self.panel._show_code()+ self.panel.refresh()+ self.panel._cancel_code()+ self.assertEqual(self.service.cancelled, 1)+ self.assertFalse(self.panel.show_button.view.isHidden())++ def test_a_code_that_ends_says_how(self):+ self.panel._toggle_sheet()+ self.panel._show_code()+ self.panel.refresh()+ self.service.code = None+ self.service.outcome = "known_there"+ self.panel.refresh()+ self.assertIn("may already be paired here, or the code was wrong", self.panel.hosted_status.text)++ def test_a_host_with_32_machines_says_to_remove_one(self):+ self.service.begin_pairing = mock.Mock(side_effect=pairing.PairingError(pairing.ERROR_FULL))+ self.panel._show_code()+ self.assertIn("Remove one", self.panel.hosted_status.text)++ def test_closing_the_sheet_cancels_a_code_that_is_up(self):+ self.panel._toggle_sheet()+ self.panel._show_code()+ self.panel.refresh()+ self.panel._toggle_sheet()+ self.assertEqual(self.service.cancelled, 1)++ def test_a_machine_that_paired_with_the_shown_code_closes_the_sheet_and_is_named(self):+ said = []+ self.window._say = lambda message, ink="ink_2": said.append((message, ink))+ self.panel._toggle_sheet()+ self.store.add_peer(entry(FIRST, SECOND_TOKEN, "Laptop"))+ self.panel.hosted_pairing(entry(FIRST, SECOND_TOKEN, "Laptop"))+ self.assertFalse(self.panel.open)+ self.assertEqual(said, [("Paired with Laptop.", "signal")])+ self.assertEqual(self.controller.cfg.auth_token, PAIRED_TOKEN)+ self.assertEqual(len(self.store.current()["peers"]), 2)+++class EnteringACodeTests(Base):+ def setUp(self):+ super().setUp()+ self.panel._toggle_sheet()+ self.service.heard = [heard()]+ self.panel.refresh()+ self.said = []+ self.window._say = lambda message, ink="ink_2": self.said.append((message, ink))++ def run_pair(self):+ threads = []++ class Immediate:+ def __init__(self, target, name=None, daemon=None):+ self.target = target++ def start(self):+ self.target()++ with mock.patch.object(kvm_bridge_app.machines_panel.threading, "Thread", Immediate), \+ mock.patch.object(kvm_bridge_app.machines_panel.AppHelper, "callAfter", lambda fn, *args: fn(*args)):+ self.panel._pair()+ return threads++ def type_code(self, digits="123456"):+ for field, digit in zip(self.panel.code_boxes.fields, digits):+ field.setStringValue_(digit)++ def test_a_machine_heard_is_listed_and_choosing_it_says_what_to_type(self):+ self.assertEqual(len(self.panel.heard_list.arrangedSubviews()), 1)+ self.panel._choose(0)+ self.assertEqual(self.panel.chosen["name"], "Laptop")+ self.assertEqual(self.panel.pair_status.text, "Six digits, as shown on Laptop.")++ def test_long_discovery_name_keeps_room_and_full_name_tooltip_at_900_points(self):+ self.window.window.setContentSize_((900, 900))+ self.service.heard = [heard(name=f"Peer {index}", address=f"192.0.2.{index}") for index in range(4)]+ full_name = "localhost-live.example.lan"+ self.service.heard.append(heard(name=full_name, address=full_name, platform="linux"))+ self.panel._heard_key = None+ self.panel.refresh()+ self.window.window.contentView().layoutSubtreeIfNeeded()++ row = self.panel.heard_list.arrangedSubviews()[-1]+ line = row.subviews()[0]+ name, detail = line.arrangedSubviews()[1:]+ required_name_width = name.attributedStringValue().size().width+ self.assertGreaterEqual(name.frame().size.width, 100)+ self.assertLess(name.frame().size.width, required_name_width)+ self.assertGreater(detail.frame().size.width, 60)+ self.assertLess(detail.frame().size.width, detail.attributedStringValue().size().width)+ self.assertEqual(name.toolTip(), full_name)+ self.assertEqual(name.accessibilityLabel(), full_name)+ self.assertEqual(detail.toolTip(), "Linux · " + full_name)+ self.assertEqual(detail.accessibilityLabel(), "Linux · " + full_name)+ paragraph = name.attributedStringValue().attribute_atIndex_effectiveRange_(+ AppKit.NSParagraphStyleAttributeName, 0, None)[0]+ self.assertEqual(paragraph.lineBreakMode(), AppKit.NSLineBreakByTruncatingTail)++ def test_a_machine_not_showing_a_code_is_said_so(self):+ self.service.heard = [heard(pair_id=None)]+ self.panel._heard_key = None+ self.panel.refresh()+ self.panel._choose(0)+ self.assertIn("not showing a code yet", self.panel.pair_status.text)++ def test_a_version_2_machine_is_said_older_and_never_asked(self):+ self.service.heard = [heard(name="Old", pairing=2)]+ self.panel._heard_key = None+ self.panel.refresh()+ self.panel._choose(0)+ self.assertEqual(self.panel.pair_status.text, "Old runs an older Beamer. Update Beamer on it to 1.5.0, then pair again.")+ self.type_code()+ self.run_pair()+ self.assertEqual(self.service.paired, [])++ def test_same_named_older_machines_show_their_addresses(self):+ first = heard(name="Studio", address="192.168.50.22", pairing=2)+ second = heard(name="Studio", address="169.254.3.7", pairing=2)+ self.service.heard = [first, second]+ self.panel._heard_key = None+ self.panel.refresh()+ rows = self.panel.heard_list.arrangedSubviews()+ texts = [" ".join(self.texts(row)) for row in rows]+ self.assertEqual(len(texts), 2)+ self.assertNotEqual(*texts)+ self.assertIn("192.168.50.22", texts[0])+ self.assertIn("169.254.3.7", texts[1])++ def test_shared_older_machine_addresses_follow_the_hide_addresses_setting(self):+ self.controller.cfg.hide_addresses = True+ self.service.heard = [heard(name="Studio", address="192.168.50.22", pairing=2),+ heard(name="Studio", address="169.254.3.7", pairing=2)]+ self.panel._heard_key = None+ self.panel.refresh()+ texts = [" ".join(self.texts(row)) for row in self.panel.heard_list.arrangedSubviews()]+ self.assertTrue(all("192.168.50.22" not in text and "169.254.3.7" not in text for text in texts))++ def test_the_chosen_machine_is_paired_with_the_code_and_the_list_updates(self):+ self.service.result = entry(FIRST, SECOND_TOKEN, "Laptop")+ self.store.add_peer(self.service.result)+ self.panel._choose(0)+ self.type_code()+ self.run_pair()+ self.assertEqual(self.service.paired, [("machine", "Laptop", "123456")])+ self.assertFalse(self.panel.open)+ self.assertEqual(self.said[-1], ("Paired with Laptop. Connecting…", "signal"))+ self.assertEqual(len(self.controller.links), 2)++ def test_a_typed_address_pairs_by_address_and_beats_a_chosen_machine(self):+ self.service.result = entry(FIRST, SECOND_TOKEN, "Laptop")+ self.store.add_peer(self.service.result)+ self.panel._choose(0)+ self.panel.find_field.setStringValue_("192.0.2.55")+ self.type_code("654321")+ self.run_pair()+ self.assertEqual(self.service.paired, [("address", "192.0.2.55", "654321")])++ def test_choosing_a_machine_clears_a_typed_address(self):+ self.panel.find_field.setStringValue_("192.0.2.55")+ self.panel._choose(0)+ self.assertEqual(self.panel.find_field.stringValue(), "")++ def test_a_short_code_is_refused_before_anything_is_sent(self):+ self.panel._choose(0)+ self.type_code("123")+ self.run_pair()+ self.assertEqual(self.service.paired, [])+ self.assertEqual(self.panel.pair_status.text, "The code is 6 digits.")++ def test_every_failure_is_said_in_the_shared_words(self):+ self.panel._choose(0)+ for error, expected in (+ (pairing.PairingError(pairing.ERROR_REFUSED), "That code was not accepted, and Laptop has cancelled it."),+ (pairing.PairingError("no_answer"), "Laptop did not answer."),+ (pairing.AlreadyPaired(entry(FIRST, SECOND_TOKEN, "Laptop")), "Laptop is already paired with this machine, since"),+ (pairing.PairingError("not_saved"), "could not save it on this machine"),+ ):+ with self.subTest(error=str(error)):+ self.service.result = error+ self.type_code()+ self.run_pair()+ self.assertIn(expected, self.panel.pair_status.text)+ self.assertFalse(self.panel.pairing)++ def test_nothing_to_pair_with_disables_the_button(self):+ self.panel.chosen = None+ self.panel._refresh_sheet(False)+ self.assertFalse(self.panel.confirm_button.enabled)+ self.panel._choose(0)+ self.panel._refresh_sheet(False)+ self.assertTrue(self.panel.confirm_button.enabled)++ def refresh_heard(self, item):+ self.service.heard = [item] if item is not None else []+ self.panel.refresh()++ def test_a_chosen_machine_starting_its_code_updates_the_hint_and_keeps_a_partial_code(self):+ self.refresh_heard(heard(pair_id=None))+ self.panel._choose(0)+ self.assertIn("not showing a code yet", self.panel.pair_status.text)+ self.type_code("123")+ self.refresh_heard(heard(pair_id="first"))+ self.assertEqual(self.panel.chosen["pair_id"], "first")+ self.assertEqual(self.panel.pair_status.text, "Six digits, as shown on Laptop.")+ self.assertEqual(self.panel.code_boxes.value, "123")++ def test_a_chosen_machine_stopping_its_code_updates_the_hint(self):+ self.refresh_heard(heard(pair_id="first"))+ self.panel._choose(0)+ self.refresh_heard(heard(pair_id=None))+ self.assertIsNone(self.panel.chosen["pair_id"])+ self.assertIn("not showing a code yet", self.panel.pair_status.text)++ def test_a_new_code_or_reply_port_replaces_what_pairing_will_use(self):+ self.refresh_heard(heard(pair_id="first"))+ self.panel._choose(0)+ current = heard(pair_id="second", reply_port=24822)+ self.refresh_heard(current)+ self.assertEqual(self.panel.chosen, current)++ def test_progress_and_refusals_survive_the_beacon_changing(self):+ self.refresh_heard(heard(pair_id="first"))+ self.panel._choose(0)+ self.panel._say("That code was not accepted.", "fault")+ self.refresh_heard(heard(pair_id=None))+ self.assertEqual(self.panel.pair_status.text, "That code was not accepted.")+ self.refresh_heard(heard(pair_id="fresh"))+ self.assertEqual(self.panel.pair_status.text, "Six digits, as shown on Laptop.")+ self.panel.pairing = True+ self.panel._say("Pairing with Laptop…")+ self.refresh_heard(heard(pair_id=None))+ self.assertEqual(self.panel.pair_status.text, "Pairing with Laptop…")++ def test_a_machine_that_vanishes_clears_the_choice(self):+ self.refresh_heard(heard())+ self.panel._choose(0)+ self.refresh_heard(None)+ self.assertIsNone(self.panel.chosen)++ def test_a_listener_that_cannot_run_is_said_instead_of_an_empty_list(self):+ self.service.heard = []+ self.service.error = "address already in use"+ self.panel._heard_key = None+ self.panel.refresh()+ self.assertIn("cannot look for machines: address already in use", self.panel.heard_empty.text)+++class CodeBoxCentringTests(Base):+ """beta.4 on Toby's Mac: each typed digit sat left of the middle of its box. Measured on the real+ window's boxes, drawn offscreen at the 773-point width it had, never put on screen."""++ def ink_offsets(self):+ window = self.window.window+ window.setContentSize_((773, window.frame().size.height))+ boxes = self.panel.code_boxes+ boxes.focus(window)+ boxes.fields[0].selectText_(None)+ self.assertIsInstance(window.firstResponder(), AppKit.NSTextView)+ for digit in "408819":+ window.firstResponder().insertText_(digit)+ self.assertEqual(boxes.value, "408819")+ editor = boxes.fields[-1].currentEditor()+ self.assertIsNotNone(editor, "the last code box must still be in field-editor mode")+ self.assertEqual(editor.alignment(), AppKit.NSTextAlignmentCenter)+ self.assertEqual(+ editor.typingAttributes()[AppKit.NSParagraphStyleAttributeName].alignment(),+ AppKit.NSTextAlignmentCenter,+ )+ window.contentView().layoutSubtreeIfNeeded()+ view = boxes.view+ bounds = view.bounds()+ picture = view.bitmapImageRepForCachingDisplayInRect_(bounds)+ view.cacheDisplayInRect_toBitmapImageRep_(bounds, picture)+ scale = picture.pixelsWide() / bounds.size.width++ def level(x, y):+ colour = picture.colorAtX_y_(x, y).colorUsingColorSpace_(AppKit.NSColorSpace.sRGBColorSpace())+ return colour.redComponent() + colour.greenComponent() + colour.blueComponent()++ offsets = []+ for control in boxes.fields:+ box = control.superview()+ frame = box.convertRect_toView_(box.bounds(), view)+ # Measure rendered ink inside the box, clear of its border and corners.+ left = int((frame.origin.x + 4) * scale)+ right = int((frame.origin.x + frame.size.width - 4) * scale)+ top = int((frame.origin.y + 4) * scale)+ bottom = int((frame.origin.y + frame.size.height - 4) * scale)+ ground = level(left, top)+ inked = [(x, y) for x in range(left, right) for y in range(top, bottom)+ if abs(level(x, y) - ground) > 0.6]+ self.assertTrue(inked, "no digit drawn in a box")+ ink_left, ink_right = min(x for x, _ in inked), max(x for x, _ in inked)+ ink_top, ink_bottom = min(y for _, y in inked), max(y for _, y in inked)+ ink_x = (ink_left + ink_right + 1) / 2+ ink_y = (ink_top + ink_bottom + 1) / 2+ box_x = (frame.origin.x + frame.size.width / 2) * scale+ box_y = (frame.origin.y + frame.size.height / 2) * scale+ offsets.append((round(ink_x - box_x, 2), round(ink_y - box_y, 2)))+ return offsets++ def test_each_typed_digit_sits_in_the_middle_of_its_box(self):+ self.panel._toggle_sheet()+ self.panel.refresh()+ offsets = self.ink_offsets()+ self.assertEqual(len(offsets), pairing.CODE_DIGITS)+ for horizontal, vertical in offsets:+ self.assertLessEqual(abs(horizontal), 1, f"digits sit off the horizontal middle in pixels: {offsets}")+ self.assertLessEqual(abs(vertical), 1, f"digits sit off the vertical middle in pixels: {offsets}")+ editor = self.panel.code_boxes.fields[-1].currentEditor()+ self.assertEqual(editor.selectedRange().location, 1)+ self.assertEqual(editor.selectedRange().length, 0)++ def test_pasting_the_whole_code_fills_all_six_boxes(self):+ self.panel._toggle_sheet()+ boxes = self.panel.code_boxes+ boxes.focus(self.window.window)+ self.window.window.firstResponder().insertText_("408819")+ self.assertEqual(boxes.value, "408819")+++class TrayTests(Base):+ """The menu bar's side: one machine's switch, every machine's tick, a pairing this Mac hosted."""++ def tray(self):+ tray = mock.Mock()+ tray.controller = self.controller+ tray.settings_store = self.store+ tray.control_window = self.window+ tray.logger = logging.getLogger("test-machines-panel")+ tray.send_item = mock.Mock()+ tray.receive_item = mock.Mock()+ tray._switch = lambda tokens, **change: kvm_bridge_app.TrayApp._switch(tray, tokens, **change)+ return tray++ def test_one_machines_switch_changes_that_machine_only(self):+ self.pair(FIRST, SECOND_TOKEN, "Laptop")+ tray = self.tray()+ kvm_bridge_app.TrayApp._set_direction(tray, SECOND_TOKEN, send=False)+ peers = {peer["token"]: peer for peer in self.store.current()["peers"]}+ self.assertFalse(peers[SECOND_TOKEN]["send"])+ self.assertTrue(peers[PAIRED_TOKEN]["send"])+ self.assertEqual(list(self.controller.links), [PAIRED_TOKEN])++ def test_turning_off_the_machine_input_is_on_brings_input_home(self):+ self.pair(FIRST, SECOND_TOKEN, "Laptop")+ self.controller.owner.on = FIRST+ tray = self.tray()+ with mock.patch.object(self.controller, "set_redirecting") as home:+ kvm_bridge_app.TrayApp._set_direction(tray, SECOND_TOKEN, send=False)+ home.assert_called_once_with(False)++ def test_the_menu_tick_turns_every_machine_off_when_all_are_on_and_all_on_otherwise(self):+ self.pair(FIRST, SECOND_TOKEN, "Laptop")+ tray = self.tray()+ kvm_bridge_app.TrayApp.toggle_send_to_windows(tray, None)+ self.assertEqual([peer["send"] for peer in self.store.current()["peers"]], [False, False])+ kvm_bridge_app.TrayApp.toggle_send_to_windows(tray, None)+ self.assertEqual([peer["send"] for peer in self.store.current()["peers"]], [True, True])++ def test_the_menu_names_the_machine_when_there_is_one_and_every_machine_when_there_are_several(self):+ tray = self.tray()+ kvm_bridge_app.TrayApp._direction_items(tray)+ self.assertEqual(tray.send_item.title, "This Mac drives Studio")+ self.assertEqual(tray.receive_item.title, "Studio drives this Mac")+ self.pair(FIRST, SECOND_TOKEN, "Laptop")+ kvm_bridge_app.TrayApp._direction_items(tray)+ self.assertEqual(tray.send_item.title, "This Mac drives every machine")+ self.assertEqual(tray.receive_item.title, "Every machine drives this Mac")++ def test_the_menu_ticks_show_mixed_when_the_machines_differ(self):+ self.pair(FIRST, SECOND_TOKEN, "Laptop")+ self.store.set_peer(SECOND_TOKEN, send=False)+ tray = self.tray()+ kvm_bridge_app.TrayApp._direction_items(tray)+ self.assertEqual(tray.send_item.state, -1)++ def test_the_menu_hides_an_address_a_nameless_machine_is_called_by(self):+ settings = self.store.current()+ settings = {**settings, "peers": [{**settings["peers"][0], "name": ""}]}+ self.store.save_settings(settings)+ self.controller.cfg.hide_addresses = True+ tray = self.tray()+ kvm_bridge_app.TrayApp._direction_items(tray)+ self.assertNotIn("192.0.2", tray.send_item.title)++ def test_the_menu_bar_hides_an_address_a_nameless_machine_is_called_by(self):+ settings = self.store.current()+ self.store.save_settings({**settings, "peers": [{**settings["peers"][0], "name": ""}]})+ self.controller.cfg.hide_addresses = True+ self.controller.owner.on = None+ tray = mock.Mock()+ tray.controller = self.controller+ tray.control_window = self.window+ tray.windows_input = mock.Mock()+ tray.window = self.window+ tray._direction_items = lambda: None+ kvm_bridge_app.TrayApp.refresh_status(tray, None)+ self.assertNotIn("192.0.2", tray.toggle_item.title)+ self.assertNotIn("192.0.2", tray.status_item.title)++ def test_a_pairing_this_mac_hosted_reaches_the_window_on_the_main_thread(self):+ tray = self.tray()+ with mock.patch.object(kvm_bridge_app.AppHelper, "callAfter") as later:+ kvm_bridge_app.TrayApp._hosted_pairing(tray, {"name": "Laptop"})+ later.assert_called_once_with(self.window.panel.hosted_pairing, {"name": "Laptop"})+++if __name__ == "__main__":+ unittest.main()diff --cc mac_app/wake.pyindex 94dacee,770d693..0856fd1--- a/mac_app/wake.py+++ b/mac_app/wake.py@@@ -15,19 -14,8 +15,19 @@@ __all__ ="lookup_mac", "mac_from_arp_output", "magic_packet", "parse_mac", "send_magic_packet",]-WAKING_STATUS = "Waking Windows…"-NOT_WOKEN_STATUS = "Windows did not wake"+# What the link says when the machine answered and would not have it: a different Beamer, an older+# or newer one, a pairing it holds under another machine, or a first frame it could not read.- REFUSED_KINDS = ("older", "newer", "different", "unauthenticated", "wrong_id", "unreadable")++REFUSED_KINDS = ("older", "newer", "different", "unauthenticated", "wrong_id", "unreadable", "forgotten")++NOT_WOKEN_SUFFIX = " did not wake"+++def waking_status(name):+ return f"Waking {name}…"+++def not_woken_status(name):+ return f"{name}{NOT_WOKEN_SUFFIX}"class WakingController(KVMController):diff --cc win_app/app_config.pyindex a521301,fccda56..ab3b605--- a/win_app/app_config.py+++ b/win_app/app_config.py@@@ -628,323 -375,3 +628,341 @@@ def _write_json(path: Path, payload: difinally:if temporary_path is not None:temporary_path.unlink(missing_ok=True)+++def _read_object(path: Path):+ """The JSON object in a file, or None when it is missing or does not parse. A file that cannot be+ read for any other reason (locked, denied) raises, so it is never taken for a missing one."""+ try:+ raw = json.loads(path.read_text(encoding="utf-8"))+ except (FileNotFoundError, ValueError):+ return None+ return raw if isinstance(raw, dict) else None+++def load_settings(path: Path) -> dict:+ """settings.json at `path`, made from 1.4.x's config.json beside it (or defaults) when there is+ none, and brought up to date when 1.4.x paired again after the upgrade."""+ if legacy_config_path(path) == path:+ raise ConfigError("the settings file is settings.json; config.json is 1.4.x's and is never written")+ legacy = _read_object(legacy_config_path(path))+ if not path.exists():+ settings = migrate(legacy)+ _write_json(path, settings)+ return settings+ settings = _read_object(path)+ if (+ settings is None or settings.get("schema") != SCHEMA or not is_machine_id(settings.get("machine_id"))+ or not isinstance(settings.get("peers"), list) or not isinstance(settings.get("zones"), list)+ or not all(isinstance(entry, dict) for entry in settings["peers"] + settings["zones"])+ ):+ raise SettingsFileError(f"{path} is not a version {SCHEMA} Beamer settings file, and is left as it is")+ if any("way_back_by" in entry and not isinstance(entry["way_back_by"], str) for entry in settings["peers"]):+ raise SettingsFileError(f"{path} has a peer way_back_by that is not text, and is left as it is")+ if any("in_use" in entry and not isinstance(entry["in_use"], bool) for entry in settings["peers"]):+ raise SettingsFileError(f"{path} has a peer in_use that is not true or false, and is left as it is")+ phones_repaired = peerlist.normalise_phones(settings)+ if any("jump_key" in entry and (not isinstance(entry["jump_key"], str)+ or (entry["jump_key"] and not ways.valid_jump_key(entry["jump_key"])))+ for entry in settings["peers"]):+ raise SettingsFileError(f"{path} has a peer jump_key that is not a recorded modifier chord, and is left as it is")+ if _overlapping_zones(settings):+ raise SettingsFileError(f"{path} has two zones in use over the same stretch of the screen, and is left as it is")+ settings.setdefault("name", "")+ settings.setdefault("port", protocol.DEFAULT_PORT)+ settings.setdefault("shortcut", True)+ settings.setdefault("migrated_token_sha256", "")+ repaired = ways.ensure_zones(settings) or phones_repaired+ if (legacy is not None and remigrate(settings, legacy)) or repaired:+ _write_json(path, settings)+ return settings+++def _own_address(target: str) -> str:+ if not target:+ return ""+ try:+ return local_address_towards(target)+ except (OSError, ValueError):+ return ""+++def _overlapping_zones(settings: dict) -> bool:+ """Whether two zones in use cover one stretch (WIRE.md section 8): an edge zone covers its peer's side,+ a part zone the chosen thirds of it, a corner zone its corner. A corner inside an edge is fine, and+ a zone this reads as nothing (no such kind, no thirds) is left to the defaults as before."""+ sides = {peer.get("id", ""): peer.get("side", "") for peer in settings["peers"]}+ seen = set()+ for zone in settings["zones"]:+ if zone.get("off") is True:+ continue+ kind, side = zone.get("kind"), sides.get(zone.get("peer"), "")+ if kind == "corner" and zone.get("corner") in CORNERS:+ stretch = {("corner", zone["corner"])}+ elif kind == "edge" and side in return_edge.EDGES:+ stretch = {(side, part) for part in return_edge.PARTS}+ elif kind == "part" and side in return_edge.EDGES and isinstance(zone.get("parts"), list):+ stretch = {(side, part) for part in zone["parts"] if part in return_edge.PARTS}+ else:+ continue+ if stretch & seen:+ return True+ seen |= stretch+ return False+++def _zones_of(settings: dict, peer_id: str) -> dict:+ found = {}+ for zone in settings["zones"]:+ if zone.get("peer") == peer_id:+ found.setdefault(zone.get("kind"), zone)+ return found+++def _flat_from_settings(settings: dict) -> dict:+ """The dict `config_from_dict` reads: settings.json's kept fields, and the first desktop and its+ zones as the fields that used to be the Mac's."""+ flat = {key: settings[key] for key in KEPT_FIELDS if key in settings}+ flat.update(machine_id=settings["machine_id"], name=_text(settings["name"]), port=settings["port"],+ host="", mac_host="", auth_token="")+ peer = peerlist.first_desktop(settings["peers"])+ zones = _zones_of(settings, peer.get("id", "")) if peer else {}+ flat["crossing_methods"] = [kind for kind in KINDS if kind in zones and not zones[kind].get("off")]+ if settings["shortcut"]:+ flat["crossing_methods"].append("shortcut")+ _methods, corner, parts = _zone_fields({+ "crossing_corner": zones.get("corner", {}).get("corner"), "crossing_edge_parts": zones.get("part", {}).get("parts"),+ })+ flat["crossing_edge_parts"], flat["crossing_corner"] = parts, corner+ if peer:+ flat.update(+ auth_token=peer.get("token", ""), mac_host=peer.get("host", ""), paired_with=peer.get("name", ""),+ mac_hardware_address=peer.get("hw", ""), send_to_mac=peer.get("send", True),+ allow_mac_to_drive=peer.get("allow_drive", True), mac_return_edge=peer.get("side", ""),+ arrangement_set_at=peer.get("side_set_at", 0),+ )+ return flat+++def _apply_flat(settings: dict, flat: dict) -> None:+ """Write a Config's flat fields (from `config_to_dict`) into the settings: this PC's own, and the+ first desktop's address, name and switches, never a side or a zone. A token that is not that+ desktop's is a new pairing: it replaces that entry, and its zones point at the empty id until a link+ learns the new one."""+ own_id = settings["machine_id"]+ settings.update({key: flat[key] for key in KEPT_FIELDS})+ old_port, settings["port"] = settings["port"], flat["port"]+ settings["shortcut"] = "shortcut" in flat["crossing_methods"]+ settings["name"] = flat["name"]+ if not flat["auth_token"]:+ # Nothing paired: this machine's own settings are all there is to write, and no peer is made.+ return+ peers = settings["peers"]+ index = next((index for index, entry in enumerate(peers) if entry.get("port") != 0), None)+ peer = peers[index] if index is not None else None+ if peer is None or peer.get("token") != flat["auth_token"]:+ entry = _peer_entry(flat, flat["auth_token"], flat["port"], own_id)+ held = peer or {}+ # The side is the pair's, settled by `arrangement`, and is not the flat view's to set.+ entry.update(side=held.get("side", ""), side_set_at=held.get("side_set_at", 0), side_by=held.get("side_by", ""))+ if index is not None:+ for zone in settings["zones"]:+ if zone.get("peer") == peer.get("id"):+ zone["peer"] = ""+ peers[index] = entry+ else:+ peers.append(entry)+ peer = entry+ # Its name and hardware address are learnt on its link: written here only with a new address, which+ # clears what was learnt at the old one, or a save from a window read before one was learnt would+ # put the old one back.+ if flat["mac_host"] != peer.get("host"):+ peer.update(name=flat["paired_with"], hw=flat["mac_hardware_address"])+ peer.update(host=flat["mac_host"], send=flat["send_to_mac"], allow_drive=flat["allow_mac_to_drive"])+ if flat["port"] != old_port and peer.get("port") == old_port:+ peer["port"] = flat["port"]+++# Held around every read-change-write of settings.json, here and by the link's PeerBook (which takes+# this lock), so an id a link has just learnt and a change the window makes cannot cross.+SETTINGS_LOCK = threading.RLock()+++class ReadFallbackPeerBook(receiver.PeerBook):+ """The link's PeerBook over settings.json. `load` reads the file on every call. One read that+ fails (a lock held by a scanner, a save half written) must not raise into a link thread for the+ read-only calls, `peers` and `zones`, which then give the last good copy. `admit` and+ `store_paired` load, change and save, and a copy the window has since changed (it writes+ settings.json directly) would be written back over that change, so a failed read raises there+ and the handshake fails and retries. With no good copy yet, every call raises."""++ def __init__(self, load, save, lock=None) -> None:+ super().__init__(self._strict, save, lock if lock is not None else SETTINGS_LOCK)+ self._read_settings = load+ self._last_good = None++ def _strict(self) -> dict:+ settings = self._read_settings()+ self._last_good = copy.deepcopy(settings)+ return settings++ def _tolerant(self) -> dict:+ try:+ return self._strict()+ except Exception:+ if self._last_good is None:+ raise+ LOGGER.warning("Could not read the settings; using the last good copy", exc_info=True)+ return copy.deepcopy(self._last_good)++ def peers(self) -> list:+ with self.lock:+ return copy.deepcopy(list((self._tolerant() or {}).get("peers") or []))++ def zones(self) -> list:+ with self.lock:+ return copy.deepcopy(list((self._tolerant() or {}).get("zones") or []))+++def save_config(path: Path, config: Config) -> None:+ payload = config_to_dict(config)+ with SETTINGS_LOCK:+ settings = load_settings(path)+ if config.trigger_key != settings.get("trigger_key"):+ try:+ ways.check_trigger_key(settings, config.trigger_key)+ except ValueError as exc:+ raise ConfigError(str(exc)) from exc+ _apply_flat(settings, payload)+ write_settings(path, settings)+++def set_jump_key(path: Path, peer_id: str, value, trigger_key: str) -> dict:+ """Sets or clears one peer's local jump chord after the shared clash checks."""+ with SETTINGS_LOCK:+ settings = load_settings(path)+ entry = next((peer for peer in settings["peers"] if peer["id"] == peer_id), None)+ if entry is None:+ raise ConfigError("that machine is no longer paired with this PC")+ try:+ entry["jump_key"] = ways.check_jump_key(settings, peer_id, value, trigger_key) or ""+ except ValueError as exc:+ raise ConfigError(str(exc)) from exc+ write_settings(path, settings)+ return copy.deepcopy(entry)+++def write_settings(path: Path, settings: dict) -> None:+ """The settings as the link changed them (an id learnt, an address, `linked`), written atomically."""+ if any("in_use" in entry and not isinstance(entry["in_use"], bool) for entry in settings.get("peers", []) if isinstance(entry, dict)):+ raise SettingsFileError(f"{path} has a peer in_use that is not true or false")+ peerlist.normalise_phones(settings)+ if any("jump_key" in entry and (not isinstance(entry["jump_key"], str)+ or (entry["jump_key"] and not ways.valid_jump_key(entry["jump_key"])))+ for entry in settings.get("peers", []) if isinstance(entry, dict)):+ raise SettingsFileError(f"{path} has a peer jump_key that is not a recorded modifier chord")+ _write_json(path, settings)+++def set_own(path: Path, **fields) -> None:+ """Writes fields that belong to this PC rather than to a peer (`port`, `hide_addresses`) straight into the+ settings, which works with no machine paired and leaves every peer entry as it is."""+ with SETTINGS_LOCK:+ settings = load_settings(path)+ settings.update(fields)+ _write_json(path, settings)+++def learned_fields(path: Path) -> dict:+ """What links write into the first peer's entry, in the flat view's names: its token, address,+ hardware address and name, and the two direction switches."""+ with SETTINGS_LOCK:+ flat = _flat_from_settings(load_settings(path))+ # With no peer there is nothing for links to have written, and the flat view has no such fields.+ fallback = default_config()+ return {name: flat[name] if name in flat else getattr(fallback, name) for name in LEARNED}+++# What links and a fold write into the first peer, in the flat view's names.+LEARNED = ("auth_token", "mac_host", "mac_hardware_address", "paired_with", "send_to_mac", "allow_mac_to_drive")+# The ones a link writes while the window is not looking, which a save must never overwrite.+LINK_WRITTEN = ("mac_host", "mac_hardware_address", "paired_with")+++def set_peer_hardware_address(path: Path, peer: str, address: str) -> bool:+ """Writes a peer's hardware address, as learnt from the ARP table; True when it changed."""+ with SETTINGS_LOCK:+ settings = load_settings(path)+ entry = next((item for item in settings["peers"] if item.get("id") == peer), None)+ if entry is None or entry.get("port") == 0 or entry.get("hw") == address:+ return False+ entry["hw"] = address+ _write_json(path, settings)+ return True++- def set_ways(path: Path, peer: str, *, side=None, methods, parts, corner) -> bool:++def set_ways(path: Path, peer: str, *, side=None, methods, parts, corner, live=None) -> bool:+ """Writes one peer's ways across (WIRE.md section 8): its `side`, and its edge, part and corner+ zones, in use when named in `methods`. `side` None keeps the side held now, so a change to a way- never puts back a side that arrived since the window last read it. Raises ClashError, writing++ never puts back a side that arrived since the window last read it. A machine with no link now++ (`live(id)` false) gives way to them (core/ways.py give_way). Raises ClashError, writing+ nothing, when two machines' zones would then cover one stretch of this PC's screen; ConfigError+ when no entry has `peer`. Returns whether the side moved, which the caller sends as `arrangement`."""+ with SETTINGS_LOCK:+ settings = load_settings(path)+ entry = next((item for item in settings["peers"] if item.get("id") == peer), None)+ if entry is None:+ raise ConfigError("that machine is not paired with this PC")+ moved = ways.edit(+ settings, peer, side=entry.get("side", "") if side is None else side, methods=methods, parts=parts,+ corner=corner, kinds=KINDS, corner_edge=_corner_edge, now=time.time(),+ )+ if moved:+ # Moved onto a side another machine's edge holds: the side stands and this machine's way+ # there goes off, as when the side arrives from it; the page says which machine holds it.- ways.settle(settings, peer, "this PC")++ ways.settle(settings, peer, "this PC", live)++ for notice in ways.give_way(settings, peer, "this PC", live):++ LOGGER.info("%s", notice)+ sentence = ways.clash(settings, "this PC")+ if sentence is not None:+ raise ClashError(sentence)+ _write_json(path, settings)+ return moved+++def share_side(path: Path, side: str, thirds: dict) -> list:+ """Split one side's zones under the settings lock, returning every machine whose zones changed."""+ with SETTINGS_LOCK:+ settings = load_settings(path)+ changed = ways.share(settings, side, thirds, kinds=KINDS)+ _write_json(path, settings)+ return changed++- def apply_arrangement(path: Path, peer: str, edge: str, set_at: int, by: str, way_back=None, way_back_by=None):++def settle_presence(path: Path, live, gone):++ """What became of the zones set aside for a machine with no link (core/ways.py settle_presence).++ Returns (changed, notices): whether the file was written, and a sentence for each zone that stays++ off for good or could not be put back."""++ with SETTINGS_LOCK:++ settings = load_settings(path)++ before = copy.deepcopy(settings)++ notices = ways.settle_presence(settings, "this PC", live, gone)++ if settings == before:++ return False, notices++ _write_json(path, settings)++ return True, notices++++++def apply_arrangement(path: Path, peer: str, edge: str, set_at: int, by: str, way_back=None, way_back_by=None,++ live=None):+ """A peer's `arrangement` (WIRE.md section 8), as core.ways takes it: `edge` is the edge of the peer+ that faces this PC, so this PC's side for it is the opposite, and `way_back` is kept whatever the+ side. Returns (changed, notices): whether the file was written, and a sentence for each of that+ peer's zones turned off by a clash."""+ with SETTINGS_LOCK:+ settings = load_settings(path)+ changed, notices = ways.arrangement(settings, peer, edge, set_at, by, "this PC", way_back,- way_back_by=way_back_by, corner_edge=_corner_edge)++ way_back_by=way_back_by, corner_edge=_corner_edge, live=live)+ if changed:+ _write_json(path, settings)+ return changed, noticesdiff --cc win_app/kvm_bridge_win.pyindex b1e83cf,eccd33c..e2c4661--- a/win_app/kvm_bridge_win.py+++ b/win_app/kvm_bridge_win.py@@@ -52,7 -44,10 +52,8 @@@ from app_config importload_config,save_config,)-import autostart_win-import capture_win-import desktop_win-import effects++from core import crash_log+from core import effectsfrom diagram import ArrangementDiagram, PushStripfrom edge_glow import EdgeGlow, PreviewLoopfrom effect_overlay import EffectOverlay, logical_point@@@ -788,361 -570,32 +789,397 @@@ class WindowsApplication(QWidget)QApplication.beep()self.tray.showMessage(title, self._shown(message), QIcon(str(ICON_PATH)), 4000)- def _on_mac_learned(self, address: str) -> None:- if self._config is None or self._config.mac_hardware_address == address:+ def _same_module(self, current: Config) -> QWidget:+ module = widgets.Module("Settings")+ self.same_switch = widgets.Switch("Same on all machines")+ self.same_switch.setFont(theme.font(theme.TYPE["body"]))+ self.same_switch.setChecked(current.same_on_both)+ self.same_switch.toggled.connect(self._set_same)+ module.body.addWidget(self.same_switch)+ self.same_note = widgets.label("", "note", wrap=True)+ module.body.addWidget(self.same_note)+ if self._config is None or not self._paired:+ self.same_switch.setEnabled(False)+ return module++ def _own_note(self) -> QWidget:+ """A note on a row this PC keeps to itself, shown only while the pages are kept in step."""+ note = widgets.label(pages_win.OWN_ROW, "note", wrap=True)+ note.setVisible(False)+ self.own_notes.append(note)+ return note++ def _show_same(self) -> None:+ if self._config is None:return- self._config.mac_hardware_address = address- self._persist()+ old = any("settings" not in caps for caps in self._peer_caps().values())+ on = self._config.same_on_both and not old+ if self.same_switch.isChecked() != on:+ self.same_switch.blockSignals(True)+ self.same_switch.setChecked(on)+ self.same_switch.blockSignals(False)+ desktops = peerlist.desktops(self._peer_entries)+ self.same_switch.setEnabled(self._paired and bool(desktops) and not old)+ who = settings_sync.who([self._shown(label) for label in peerlist.labels(desktops).values()])+ self.same_note.setText(settings_sync.switch_note(who, self._config.same_on_both, old))+ self.same_note.setToolTip(settings_sync.switch_detail())+ widgets.set_role(self.same_note, "note-amber" if old else "note")+ for key, label in self.scope_labels.items():+ text = settings_sync.scope(key, who, on, pages_win.SCOPE.get(key))+ if label.text() != text:+ label.setText(text)+ for note in self.own_notes:+ if motion.target_shown(note) != on:+ motion.set_shown(note, on)+ self._refresh_design_follow()++ def _same_fields(self) -> tuple:+ return tuple(settings_sync.pc_values(self._config).values())++ def _design_fields(self) -> tuple:+ values = settings_sync.pc_values(self._config)+ return tuple(values.get(key) for key in settings_sync.DESIGN_KEYS)++ def _same_state(self) -> dict:+ config = self._config+ values = settings_sync.pc_values(config)+ design_state = {+ "set_at": config.design_set_at,+ "by": config.design_by or config.machine_id,+ "values": {key: values[key] for key in settings_sync.DESIGN_KEYS},+ "path": (self._design_path or [config.machine_id])+ if config.design_follow_peer and not config.same_on_both else [config.machine_id],+ }+ return settings_sync.message_data(+ config.same_on_both, config.same_set_at, values, by=config.same_by, design_state=design_state+ )- def _directions_module(self, current: Config) -> QWidget:- module = widgets.Module("Directions")- # The tray's words, so the two never disagree.- self.allow_switch = widgets.Switch("Your Mac drives this PC")- self.allow_switch.setFont(theme.font(theme.TYPE["body"]))- self.allow_switch.setChecked(current.allow_mac_to_drive)- self.allow_switch.toggled.connect(self._set_allow_drive)- module.body.addWidget(self.allow_switch)- self.send_switch = widgets.Switch("This PC drives your Mac")- self.send_switch.setFont(theme.font(theme.TYPE["body"]))- self.send_switch.setChecked(current.send_to_mac)- self.send_switch.toggled.connect(self._toggle_sending)- module.body.addWidget(self.send_switch)- self.send_hint = widgets.label("", "note", wrap=True)- self.send_hint.setVisible(False)- module.body.addWidget(self.send_hint)++ def _live(self, peer: str) -> bool:++ """Whether `peer` has a link up now, either way. One that has none gives way on the Crossing++ page and to an arrangement (core/ways.py give_way)."""++ ident = protocol.read_id(peer)++ return ident is not None and (self.sender.links.up(ident) or ident in self.server.links())++++ def _gone(self, peer: str) -> bool:++ """Whether `peer` has removed this pairing: the link this PC dials to it was closed unanswered++ for a minute (core/link.py). Its zones set aside by `give_way` then stay off for good."""++ entry = next((item for item in self._peer_entries if item.get("id") == peer), None)++ return entry is not None and self.sender.links.kind(entry.get("token")) == "forgotten"++++ def _settle_presence(self) -> None:++ """Puts back the zones set aside for a machine that has connected since, and keeps off for good,++ and says so, those of one that has removed this pairing (core/ways.py settle_presence)."""++ if self._config is None or not ways.presence_due(self._crossing_settings(), self._live, self._gone):++ return++ self._read_crossing()++ before = ways.way_back_state(self._crossing_settings())++ try:++ changed, notices = app_config.settle_presence(self.config_path, self._live, self._gone)++ except (ConfigError, OSError):++ LOGGER.exception("The zones set aside could not be settled")++ return++ if not changed:++ return++ for notice in notices:++ self._on_alert("Beamer", notice)++ self._pull_peer_fields()++ self.sender.refresh()++ self.server.peers_changed()++ self._read_crossing()++ for target, state in ways.way_back_state(self._crossing_settings()).items():++ if before.get(target) != state:++ self._tell(target)+++ def _design_peer_caps(self) -> dict:+ desktops = {entry.get("id") for entry in peerlist.desktops(self._peer_entries)}+ caps = {protocol.id_text(peer): self.sender.links.caps(peer) for peer in self.sender.peers_up()}+ for peer in self.server.links():+ known = self.server.caps_of(peer)+ if known is not None:+ caps[protocol.id_text(peer)] = known+ return {peer: known for peer, known in caps.items() if peer in desktops}++ def _refresh_design_follow(self) -> None:+ if not hasattr(self, "design_follow_choice") or self._config is None:+ return+ choice = self.design_follow_choice+ choice.blockSignals(True)+ model = QStandardItemModel(choice)+ none = QStandardItem("None")+ none.setData("", Qt.ItemDataRole.UserRole)+ model.appendRow(none)+ caps = self._design_peer_caps()+ desktops = [entry for entry in peerlist.desktops(self._peer_entries) if protocol.read_id(entry.get("id")) is not None]+ rows = settings_sync.follow_rows(desktops, caps, self._design_states, self._config.design_follow_peer)+ for entry, why_not in rows:+ name = self._shown(entry.get("name") or entry.get("platform") or "Paired machine")+ item = QStandardItem(f"{name} — {why_not}" if why_not == settings_sync.NEEDS_DESIGN_SYNC else name)+ item.setData(entry["id"], Qt.ItemDataRole.UserRole)+ if why_not is not None:+ item.setEnabled(False)+ item.setToolTip(why_not)+ model.appendRow(item)+ choice.setModel(model)+ selected = choice.findData(self._config.design_follow_peer, Qt.ItemDataRole.UserRole)+ choice.setCurrentIndex(max(0, selected))+ choice.blockSignals(False)+ desktops = peerlist.desktops(self._peer_entries)+ peer = next((item for item in desktops if item.get("id") == self._config.design_follow_peer), None)+ name = self._shown(peer.get('name') or 'that machine') if peer else ""+ if peer:+ if self._config.same_on_both:+ note = f"Following {name}, paused while Same on all machines is on."+ elif self._config.design_follow_peer not in caps:+ note = f"Keeping the last design received from {name} until it reconnects."+ else:+ note = ""+ else:+ note = settings_sync.follow_note(rows) or "None: this PC keeps its own Design."+ self.design_follow_note.setText(note)+ self.design_follow_note.setVisible(bool(note))+ self._lock_followed_design(+ settings_sync.follow_lock(self._config.design_follow_peer, self._config.same_on_both, desktops), name)++ def _lock_followed_design(self, entry, name: str) -> None:+ """Followed controls dimmed and deaf while `entry` is followed; the local ones stay live."""+ if not hasattr(self, "follow_banner"):+ return+ locked = entry is not None+ for control in (self.glow_style_choice, self.switch_style_choice, self.glow_colour_choice,+ self.length_choice, self.size_choice):+ control.set_enabled(not locked)+ self.landing_toggle.setEnabled(not locked)+ widgets.set_dimmed(self.landing_toggle, locked)+ self.follow_banner_label.setText(settings_sync.following_banner(name) if locked else "")+ self.follow_banner.setVisible(locked)++ def _follow_banner(self) -> QWidget:+ """Shown at the top of Style while this PC follows another machine's design, whose followed+ controls are locked until Stop following (settings_sync.follow_lock)."""+ self.follow_banner = QFrame()+ self.follow_banner.setProperty("vernier", "banner")+ row = QVBoxLayout(self.follow_banner)+ row.setContentsMargins(12, 10, 12, 10)+ row.setSpacing(8)+ self.follow_banner_label = widgets.label("", "heading", wrap=True)+ row.addWidget(self.follow_banner_label)+ self.stop_follow_button = widgets.ActionButton(settings_sync.STOP_FOLLOWING)+ self.stop_follow_button.setProperty("vernier", "small")+ self.stop_follow_button.clicked.connect(self._stop_following)+ row.addWidget(self.stop_follow_button, 0, Qt.AlignmentFlag.AlignLeft)+ self.follow_banner.setVisible(False)+ return self.follow_banner++ def _stop_following(self) -> None:+ self.design_follow_choice.setCurrentIndex(0)++ def _design_follow_chosen(self, _index: int) -> None:if self._config is None:- self.allow_switch.setEnabled(False)- self.send_switch.setEnabled(False)- return module+ return+ self._config.design_follow_peer = self.design_follow_choice.currentData(Qt.ItemDataRole.UserRole) or ""+ self._followed_version = None+ if not self._config.design_follow_peer:+ self._design_path = [self._config.machine_id]+ self._config.design_set_at = settings_sync.next_stamp(self._config.design_set_at, time.time())+ self._config.design_by = self._config.machine_id+ if not self._persist():+ return+ if not self._config.design_follow_peer:+ self._send_same()+ self._refresh_design_follow()+ self._apply_followed_design(force=True)++ def _apply_followed_design(self, force=False) -> None:+ config = self._config+ peer = config.design_follow_peer+ state = self._design_states.get(peer)+ if not peer or state is None or config.same_on_both:+ return+ current = settings_sync.pc_values(config)+ cursor = self._followed_version+ stamp, author = cursor[1:] if cursor and cursor[0] == peer else (-1, "")+ taken = settings_sync.followed_design(+ current, state, peer, peer, config.same_on_both, stamp,+ author, own_id=config.machine_id, force=force,+ )+ if taken is None:+ return+ cycle = taken.get("cycle", False)+ path = [config.machine_id] if cycle else taken["path"]+ announce = cycle or taken["changed"] or path != self._design_path or force+ if cycle:+ config.design_follow_peer = ""+ else:+ settings_sync.apply_pc(config, taken["values"])+ if announce:+ config.design_set_at = settings_sync.next_stamp(config.design_set_at, time.time())+ config.design_by = config.machine_id+ self._design_seen = tuple(getattr(config, key) for key in settings_sync.DESIGN_KEYS)+ self._reflect_config(config)+ if not self._persist():+ return+ self._design_path = path+ self._followed_version = None if cycle else (peer, taken["set_at"], taken["by"])+ if announce:+ self._send_same()+ self._refresh_design_follow()++ def _send_same(self, source: Optional[bytes] = None, data: Optional[dict] = None) -> None:+ """This PC's state, or `data` unchanged when a newer one arrived and goes on (section 10), to+ every peer that takes it but the one it came from: on the link this PC opened when that is+ up, else on the one the peer opened."""+ message = protocol.settings_msg(data if data is not None else self._same_state())+ for peer, caps in self._peer_caps().items():+ if peer != source and "settings" in caps:+ self._send_to(peer, message)++ def _peer_caps(self) -> dict:+ """{peer id: capabilities} for every peer with a link up, in either direction."""+ desktops = {protocol.read_id(entry.get("id")) for entry in peerlist.desktops(self._peer_entries)}+ caps = {peer: self.sender.links.caps(peer) for peer in self.sender.peers_up()}+ for peer in self.server.links():+ caps.setdefault(peer, self.server.caps_of(peer) or frozenset())+ return {peer: known for peer, known in caps.items() if peer in desktops}++ def _send_to(self, peer: bytes, message: dict) -> bool:+ return self.sender.send_to(peer, message) or self.server.send(peer, message)++ def _announce(self, peer: bytes) -> list:+ """What this PC tells a peer on every new link (section 3): the side it holds for the peer,+ once one has been set; the peers it may send to, when it may send to this one; and its+ Same on all machines state. On the link's thread."""+ config = self._config+ if config is None:+ return []+ try:+ peers = self.book.peers()+ except Exception:+ LOGGER.exception("The peers could not be read for an announcement")+ return []+ entry = next((item for item in peers if protocol.read_id(item.get("id")) == peer), None)+ if entry is None:+ return []+ messages = []+ author = protocol.read_id(entry.get("side_by")) or protocol.read_id(config.machine_id)+ if entry.get("port") != 0 and entry.get("side") in return_edge.EDGES and entry.get("side_set_at") and author is not None:+ settings = {"machine_id": protocol.id_text(self._identity()["id"]), "peers": peers,+ "zones": self.book.zones()}+ way_back = ways.has_way(settings, entry["id"])+ holder = protocol.read_id(ways.way_back_by(settings, entry["id"]))+ messages.append(protocol.arrangement_v6(entry["side"], entry["side_set_at"], author,+ way_back=way_back, way_back_by=holder))+ if entry.get("in_use", True) is True and entry.get("send"):+ others = [protocol.read_id(item.get("id")) for item in peers+ if item.get("in_use", True) is True+ and protocol.read_id(item.get("id")) not in (None, peer)]+ messages.append(protocol.paired_msg(others[: protocol.MAX_PEERS]))+ if entry.get("port") != 0 and "settings" in self._peer_caps().get(peer, ()):+ messages.append(protocol.settings_msg(self._same_state()))+ return messages++ def _driver_platform(self) -> str:+ """The platform of the machine driving this PC now, or "" when none is. From the peers the+ window last read, not settings.json: this runs on the responder's thread as input lands."""+ owner = self.server.owner+ if owner is None:+ return ""+ text = protocol.id_text(owner)+ return next((peer.get("platform") or "" for peer in self._peer_entries if peer.get("id") == text), "")++ def _identity(self) -> dict:+ """This machine as a `hello` and a `welcome` say it (section 2)."""+ config = self._config or default_config()+ name = (config.name or pairing.machine_name())[: protocol.MAX_NAME_CHARS]+ return {+ "id": protocol.read_id(config.machine_id) or b"",+ "name": name,+ "platform": OWN_PLATFORM,+ "app": VERSION[:32] if VERSION.isascii() and VERSION.isprintable() else "dev",+ # A swipe has no shortcut every Linux desktop shares, so Linux does not offer gestures.+ "caps": [cap for cap in ("clipboard", "clipboard_image", "gestures", "media_keys", "text", "settings", "design_sync")+ if not (cap == "gestures" and OWN_PLATFORM == "linux")],+ "port": self._settings_port,+ }++ def _zones(self) -> list:+ try:+ return self.book.zones()+ except (ConfigError, OSError):+ return []++ def _set_same(self, on: bool) -> None:+ """Turning it on carries this PC's Crossing and Design across; off, each end keeps what it+ has. Either way the Mac follows, now if a link is up, else when one next comes up."""+ if self._config is None:+ return+ self._config.same_on_both = bool(on)+ self._config.same_set_at = settings_sync.next_stamp(self._config.same_set_at, time.time())+ self._config.same_by = self._config.machine_id+ self._persist()+ self._send_same()+ if not on:+ self._apply_followed_design(force=True)+ self._show_same()++ def _on_settings(self, peer: str, data) -> None:+ """A peer's settings message, over either link. Its state stands only when it is newer than+ this PC's; then its values replace the shared ones here, and it goes on to every other peer+ that takes it, which stops the first time it meets a copy it already holds."""+ if self._config is None or any(entry.get("id") == peer and entry.get("port") == 0 for entry in self.book.peers()):+ return+ was_on = self._config.same_on_both+ state = settings_sync.read_design_state(data, TRIGGER_KEYS)+ if state is not None:+ held = self._design_states.get(peer)+ if held is None or settings_sync.design_arrived(state, held["set_at"], held["by"]):+ self._design_states[peer] = state+ source = protocol.read_id(peer)+ taken = settings_sync.arrived(+ data, self._config.same_set_at, TRIGGER_KEYS, by_here=self._config.same_by+ )+ if taken is not None:+ on, set_at, values = taken+ config = replace(self._config, crossing_methods=list(self._config.crossing_methods),+ crossing_edge_parts=list(self._config.crossing_edge_parts))+ config.same_on_both = on+ config.same_set_at = set_at+ config.same_by = data.get("by", "") if isinstance(data.get("by"), str) else ""+ if on:+ values, conflict = ways.shared_trigger_values({"peers": self.book.peers()}, values)+ if conflict is not None:+ self._show_trigger_conflict(conflict)+ design_stamp = settings_sync.design_change_stamp(+ settings_sync.pc_values(config), values, config.design_set_at,+ state, config.machine_id,+ )+ settings_sync.apply_pc(config, values)+ if design_stamp is not None:+ config.design_set_at = design_stamp["set_at"]+ config.design_by = design_stamp["by"]+ try:+ app_config.validate_config(config)+ except ConfigError:+ LOGGER.exception("Settings from a peer could not be applied")+ return+ self._config = config+ self._same_seen = self._same_fields()+ self._design_seen = self._design_fields()+ if not self._persist():+ return+ LOGGER.info("Settings from a peer applied (same on all machines %s)", "on" if on else "off")+ self.sender.update_config(config)+ self._configure_trigger(config)+ self._reflect_config(config)+ self._show_same()+ forwarded = dict(data)+ forwarded["design_sync"] = self._same_state()["design_sync"]+ self._send_same(source=source, data=forwarded)+ if taken is not None and was_on and not on:+ self._apply_followed_design(force=True)+ elif state is not None:+ self._apply_followed_design()+ if state is not None:+ self._refresh_design_follow()def _sign_in_module(self) -> QWidget:module = widgets.Module("At sign-in")@@@ -1322,151 -756,35 +1359,151 @@@self.crossing_rows["dragging"] = self._row(self.dragging_switch)for key in ("edge", "parts", "corner", "dragging"):module.body.addWidget(self.crossing_rows[key])+ if key == "edge":+ module.body.addWidget(self.share_module)++ self.jump_heading = widgets.Eyebrow("Jump to this machine")+ module.body.addWidget(self.jump_heading)+ jump_row = QVBoxLayout()+ jump_row.setSpacing(8)+ self.jump_recorder = widgets.JumpKeyRecorder(self._record_jump_key, self._jump_arming)+ jump_row.addWidget(self.jump_recorder, 1)+ self.jump_clear = widgets.ActionButton("Clear")+ self.jump_clear.setProperty("vernier", "plain")+ self.jump_clear.setAccessibleName("Clear jump key")+ self.jump_clear.clicked.connect(lambda: self._record_jump_key(""))+ jump_row.addWidget(self.jump_clear, 0, Qt.AlignmentFlag.AlignLeft)+ module.body.addLayout(jump_row)+ self.jump_note = widgets.label("", "note", wrap=True)+ module.body.addWidget(self.jump_note)- now_row = QHBoxLayout()- now_row.setSpacing(6)- # The Mac's half of the border -- the edge and push it asks for when it is the one- # sending. Hidden until the Mac has said, rather than reading "not set yet".- now_row.addWidget(widgets.label("Coming back from your Mac:", "note"))- self.return_readout = widgets.label("", "readout", wrap=True)- now_row.addWidget(self.return_readout, 1)- self.return_row = self._row(now_row)- self.return_row.setVisible(False)- module.body.addWidget(self.return_row)return module- def _ways_changed(self, way: str, on: bool) -> None:- if self._config is None:- return- self._config.crossing_methods = pages_win.toggle_way(self._config.crossing_methods, way, on)- self._persist()- self.sender.update_config(self._config)+ # -- the machine the Crossing page shows --++ def _crossing_settings(self) -> dict:+ """The peers and zones as last read, in the shape core.ways reads them."""+ own = self._config.machine_id if self._config is not None else ""+ desktops = peerlist.desktops(self._peer_entries)+ ids = {entry.get("id") for entry in desktops}+ return {"machine_id": own, "peers": desktops,+ "zones": [zone for zone in self._zone_entries if zone.get("peer") in ids]}++ def _read_crossing(self) -> None:+ try:+ self._peer_entries, self._zone_entries = self.book.peers(), self.book.zones()+ except (ConfigError, OSError):+ LOGGER.exception("The peers could not be read")++ def _crossing_machines(self) -> list:+ return [(ident, self._shown(label)) for ident, label in pages_win.crossing_machines(self._peer_entries)]++ def _chosen_machine(self) -> Optional[str]:+ ids = [ident for ident, _label in self._crossing_machines()]+ return self._chosen if self._chosen in ids else (ids[0] if ids else None)++ def _ways_in(self) -> set:+ """The kinds of zone in use towards any machine: what Pause holds and the Design page previews."""+ settings = self._crossing_settings()+ found = set()+ for ident, _label in self._crossing_machines():+ if ways.has_way(settings, ident):+ found.update(ways.ways(settings, ident)["methods"])+ return found++ def _share_part(self, part: str) -> None:+ """Move an offered third to the next machine without saving until Share is pressed."""+ recipients = self._share_recipients+ current = recipients.index(self._share_thirds[part])+ self._share_thirds[part] = recipients[(current + 1) % len(recipients)]+ self._reflect_ways()++ def _share_side(self) -> None:+ """Save the offered split, rebuild the live zones and tell every affected machine."""+ side, thirds = self._share_identity[0], dict(self._share_thirds)+ try:+ changed = app_config.share_side(self.config_path, side, thirds)+ except (ConfigError, OSError, ValueError):+ LOGGER.exception("The shared side could not be saved")+ return+ self._read_crossing()+ for peer in changed:+ self._tell(peer)+ self.server.peers_changed()+ self.sender.refresh()self._reflect_ways()- # The Design page's preview opens where the pointer crosses and says when a place is not a way in.self._reflect_look()- def _set_part(self, part: str, on: bool) -> None:- if self._config is None:- return- self._config.crossing_edge_parts = pages_win.toggle_part(self._config.crossing_edge_parts, part, on)- self._persist()- self.sender.update_config(self._config)+ def _choose_machine(self, peer: str) -> None:+ self._chosen = peer+ self._show_clash("")+ self._reflect_ways()+ self._reflect_look()++ def _show_clash(self, sentence: str) -> None:+ self.clash_note.setText(sentence)+ motion.set_shown(self.clash_note, bool(sentence))++ def _rebuild_machine_choice(self, machines: list) -> None:+ """The machine choice again when the paired machines or their names change."""+ items = tuple(machines)+ if items == self._machine_items:+ return+ self._machine_items = items+ old = self.machine_choice.view+ # Three names fit a row at the narrowest window; four or more go two to a row.+ columns = len(items) if len(items) <= 3 else 2+ self.machine_choice = widgets.Choice(items, max(1, columns), "", on_change=self._choose_machine)+ self.machine_choice.set_names("Machine")+ self._machine_slot.replaceWidget(old, self.machine_choice.view)+ old.hide()+ old.deleteLater()++ def _write_ways(self, **changes) -> bool:+ """One change to the chosen machine's ways. Every machine whose way back changed is told,+ along with the chosen machine when its side or way changed. An overlapping edge choice shows+ the share offer; other clashes are refused, said, and every control goes back."""+ peer = self._chosen_machine()+ if self._config is None or peer is None:+ self._reflect_ways()+ return False+ self._read_crossing()+ before = ways.way_back_state(self._crossing_settings())+ had_way = ways.has_way(self._crossing_settings(), peer)+ held = ways.ways(self._crossing_settings(), peer)+ held.update(changes)- offer = ways.share_offer(self._crossing_settings(), peer)++ offer = ways.share_offer(self._crossing_settings(), peer, self._live)+ occupied = {part for part, owner in offer["thirds"].items() if owner in offer["holders"]} if offer else set()+ if offer and ("edge" in held["methods"] or+ "part" in held["methods"] and occupied.intersection(held["parts"])):+ self._show_clash("")+ self._reflect_ways()+ self.share_button.setFocus(Qt.FocusReason.OtherFocusReason)+ return False+ try:+ moved = app_config.set_ways(self.config_path, peer, side=changes.get("side"), methods=held["methods"],- parts=held["parts"], corner=held["corner"])++ parts=held["parts"], corner=held["corner"], live=self._live)+ except app_config.ClashError as exc:+ self._show_clash(self._shown(str(exc)))+ self._reflect_ways()+ return False+ except (ConfigError, OSError):+ LOGGER.exception("A machine's ways could not be saved")+ self._reflect_ways()+ return False+ self._show_clash("")+ self._read_crossing()+ settings = self._crossing_settings()+ changed_peers = [target for target, state in ways.way_back_state(settings).items()+ if before.get(target) != state]+ if moved or ways.has_way(settings, peer) != had_way:+ # One border, walked both ways: the machine on the other side of it moves its own side to match.+ changed_peers.append(peer)+ for target in dict.fromkeys(changed_peers):+ self._tell(target)+ # A change on the Crossing page reaches a peer's pointer while it is here, not at its next crossing.+ self.server.peers_changed()+ self.sender.refresh()self._reflect_ways()# The Design page's preview opens where the pointer crosses and says when a place is not a way in.self._reflect_look()@@@ -1546,104 -819,26 +1583,105 @@@shot = motion.snapshot(self.ways_summary)self.ways_summary.setText(summary)motion.fade_from(self.ways_summary, shot)- motion.set_shown(self.edge_unlearned, not config.mac_return_edge)- self.arrangement_diagram.set_state(edge, config.crossing_methods, config.crossing_edge_parts,- config.crossing_corner, key_name, config.trigger_style)+ motion.set_shown(self.edge_unlearned, not side)- offer = ways.share_offer(settings, chosen) if chosen else None++ offer = ways.share_offer(settings, chosen, self._live) if chosen else None+ identity = (offer["side"], tuple(offer["holders"]), tuple(offer["thirds"].items())) if offer else None+ if identity != getattr(self, "_share_identity", None):+ self._share_identity = identity+ self._share_thirds = dict(offer["thirds"]) if offer else {}+ self.share_module.eyebrow.setText(f"Share the {offer['side']} edge" if offer else "Share the edge")+ self.share_button.setText(f"Share the {offer['side']} edge" if offer else "Share the edge")+ self._share_recipients = [chosen, *offer["holders"]] if offer else []+ labels = dict(machines)+ if offer:+ holder_names = [labels.get(peer, "another machine") for peer in offer["holders"]]+ self.share_sentence.setText(pages_win.share_sentence(holder_names, offer["side"],+ labels.get(chosen, "this machine")))+ names = pages_win.part_names(offer["side"])+ for part, tile in self.share_tiles.items():+ owner = self._share_thirds[part]+ tile.setText(f"{names[part]}\n{labels.get(owner, 'another machine')}")+ tile.setAccessibleName(f"{names[part]} third: {labels.get(owner, 'another machine')}")+ tile.setChecked(owner == chosen)+ self.share_button.setEnabled(chosen in self._share_thirds.values())+ motion.set_shown(self.share_module, offer is not None)+ for note, sentence in (- (self.blocked_note, ways.blocked_sentence(settings, chosen, "this PC") if chosen and not offer else ""),++ (self.blocked_note, (ways.blocked_sentence(settings, chosen, "this PC", self._live) if chosen and not offer else "")++ or (ways.gone_sentence(settings, chosen, "this PC", self._gone) if chosen else "")),+ (self.missing_note, ways.missing_sentence(settings, chosen, "this PC") if chosen else ""),+ (self.no_way_back_note, ways.no_way_back_sentence(settings, chosen) if chosen else "")):+ sentence = self._shown(sentence)+ if sentence != note.text():+ note.setText(sentence)+ motion.set_shown(note, bool(sentence))+ drawn = []+ for ident, label in machines or [("", "")]:+ found = ways.ways(settings, ident) if ident or machines else {"side": "", "methods": [], "parts": ["middle"],+ "corner": "top_left"}+ drawn.append(dict(found, key=ident, label=label, chosen=ident == chosen or not machines))+ self.arrangement_diagram.set_machines(drawn, key_name, config.trigger_style, shortcut)self.resistance_strip.set_edge(edge)+ self._reflect_jump_key()+ caption = f"Where {name} is"+ if self.edge_heading.fontMetrics().horizontalAdvance(caption) > 180:+ caption = "Where the other machine is"+ self.edge_heading.setText(caption)+ self.edge_heading.setAccessibleName(f"Where {name} is")+ self.edge_heading.setToolTip(f"Where {name} is")++ def _reflect_jump_key(self) -> None:+ chosen = self._chosen_machine()+ entry = next((peer for peer in self._peer_entries if peer.get("id") == chosen), None)+ self.jump_heading.setVisible(entry is not None)+ self.jump_recorder.setVisible(entry is not None)+ self.jump_clear.setVisible(entry is not None)+ self.jump_note.setVisible(entry is not None)+ if entry is None:+ self.jump_recorder.cancel()+ return+ name = self._shown(peerlist.label_for(self._peer_entries, peer_id=chosen) or "this machine")+ self.jump_recorder.set_value(entry.get("jump_key", ""))+ self.jump_heading.setText(f"Jump to {name}")+ self.jump_clear.setAccessibleName(f"Clear jump key for {name}")+ chord = self.jump_recorder.key.text()+ if entry.get("jump_key"):+ self.jump_note.setText(f"Press {chord} to send input to {name}; press again to bring it home.")+ else:+ self.jump_note.setText(f"Choose a key combination to jump to {name} and back.")+ self.jump_note.setToolTip(f"Works while edges are held. Needs In use, This PC drives it and permission from {name} to drive it.")++ def _jump_arming(self, armed: bool) -> None:+ self.sender.jump_recording = armed++ def _record_jump_key(self, value: str) -> None:+ chosen = self._chosen_machine()+ if chosen is None or self._config is None:+ return+ try:+ app_config.set_jump_key(self.config_path, chosen, value, self._config.trigger_key)+ except ConfigError as exc:+ self._read_crossing()+ self._reflect_jump_key()+ self.jump_note.setText(self._shown(str(exc)))+ return+ self._read_crossing()+ self.sender.refresh()+ self._reflect_jump_key()def _set_arrangement(self, pc_edge: str) -> None:- """The edge of THIS PC that leads to the Mac -- one border, walked either way. Not an- ordinary save: both machines have to agree on it, so this end's change is timestamped- and sent over whichever link is up."""- if self._config is None or pc_edge == self._config.mac_return_edge:+ """The edge of THIS PC that leads to the chosen machine -- one border, walked either way. Not+ an ordinary change: both machines have to agree on it, so this end's change is stamped and+ sent to that machine over whichever link is up."""+ if ways.ways(self._crossing_settings(), self._chosen_machine())["side"] == pc_edge:+ return+ self._write_ways(side=pc_edge)++ def _set_hold_full_screen(self, enabled: bool) -> None:+ if self._config is None:return- self._config.mac_return_edge = pc_edge- self._config.arrangement_set_at = int(time.time())+ self._config.hold_full_screen = bool(enabled)self._persist()- mac_edge = return_edge.OPPOSITE[pc_edge]- self.sender.send_arrangement(mac_edge, self._config.arrangement_set_at)- self.server.send_arrangement(mac_edge, self._config.arrangement_set_at)self.sender.update_config(self._config)- self._reflect_look()- self._reflect_ways()def _set_block_while_dragging(self, enabled: bool) -> None:if self._config is None:@@@ -1653,67 -848,30 +1691,67 @@@self.sender.update_config(self._config)def _set_corner(self, corner: str) -> None:- if self._config is None:- return- self._config.crossing_corner = corner- self._persist()- self.sender.update_config(self._config)- self._reflect_ways()+ self._write_ways(corner=corner)++ def _tell(self, peer: str) -> None:+ """This PC's side for `peer` as held, stamped as held, with whether a way leads there (WIRE.md+ section 8), over whichever link is up. Nothing while no side is set."""+ settings = self._crossing_settings()+ entry = next((item for item in settings["peers"] if item.get("id") == peer), None)+ if entry is None or entry.get("side") not in return_edge.EDGES or not entry.get("side_set_at"):+ return+ author = protocol.read_id(entry.get("side_by")) or protocol.read_id(self._config.machine_id)+ target = protocol.read_id(peer)+ if author is None or target is None:+ return+ self._send_to(target, protocol.arrangement_v6(+ entry["side"], entry["side_set_at"], author, way_back=ways.has_way(settings, peer),+ way_back_by=protocol.read_id(ways.way_back_by(settings, peer)),+ ))- def _on_arrangement(self, mac_edge: str, set_at: int) -> None:- """The Mac changed the arrangement, over either link. `mac_edge` is always the edge of- the MAC that leads here; an arrival older than what this end already holds is ignored."""+ def _on_arrangement(self, peer: str, edge: str, set_at: int, by: str, way_back=None, way_back_by=None) -> None:+ """A peer changed the arrangement, over either link. `edge` is the edge of the PEER that+ faces this PC; one older than what this end holds, by stamp and then by id, is ignored. A+ side that makes two zones cover one stretch turns the peer's clashing zones off. `way_back`+ is kept whatever the side; a message that changed anything here is answered with this PC's+ own, and one that changed nothing is not, so two machines never answer in turn."""if self._config is None:return- pc_edge = return_edge.OPPOSITE.get(mac_edge)- if pc_edge is None or pc_edge == self._config.mac_return_edge:- # One change on the Mac reaches this PC over both links, so the second copy finds it applied.+ self._read_crossing()+ before = ways.way_back_state(self._crossing_settings())+ try:+ changed, notices = app_config.apply_arrangement(self.config_path, peer, edge, set_at, by, way_back,- way_back_by)++ way_back_by, live=self._live)+ except (ConfigError, OSError):+ LOGGER.exception("An arrangement could not be saved")return- if self._config.arrangement_set_at and not protocol.arrangement_wins(set_at, self._config.arrangement_set_at):- LOGGER.info("Ignoring an arrangement from the Mac that is no newer than this PC's (%s vs %s)", set_at, self._config.arrangement_set_at)+ if not changed:return- self._config.mac_return_edge = pc_edge- self._config.arrangement_set_at = int(set_at)- self._persist()+ for notice in notices:+ self._on_alert("Beamer", notice)+ self._pull_peer_fields()+ self.sender.refresh()+ self.server.peers_changed()+ self._read_crossing()+ changed_peers = [target for target, state in ways.way_back_state(self._crossing_settings()).items()+ if before.get(target) != state]+ for target in dict.fromkeys([*changed_peers, peer]):+ self._tell(target)++ def _pull_peer_fields(self) -> None:+ """What links wrote into the first peer, into the window's flat view, and every machine's side+ and zones as links and arrangements left them, into the Crossing page."""+ if self._config is None:+ return+ try:+ learned = app_config.learned_fields(self.config_path)+ except (ConfigError, OSError):+ LOGGER.exception("The peers could not be read")+ return+ for name, value in learned.items():+ setattr(self._config, name, value)self.sender.update_config(self._config)- self.edge_choice.set_value(pc_edge)+ self._read_crossing()self._reflect_look()self._reflect_ways()@@@ -3463,7 -2320,6 +3501,8 @@@def _refresh_window(self) -> None:if self._closing:return+ self._show_same()++ self._settle_presence()with self._status_lock:state = self._statusdetail = self._status_detail@@@ -3597,6 -2428,6 +3636,8 @@@ def main() -> Nonereturnarguments = parse_args()log_path = configure_logging()++ if log_path is not None:++ crash_log.install(log_path.parent, LOGGER)LOGGER.info("Starting Beamer Windows receiver")if log_path is not None:LOGGER.info("Logging to %s", log_path)diff --cc win_app/peers_view.pyindex 9e7c2d9,0000000..9ee8970mode 100644,000000..100644--- a/win_app/peers_view.py+++ b/win_app/peers_view.py@@@ -1,72 -1,0 +1,72 @@@+"""What each paired machine's row on Overview says: a tone, a state word and one sentence.++Pure, so every state a link can be in is tested against a word. The booleans decide the broad+state; the link's own `kind` picks the flavour of a fault, and its status sentence (which already+names the machine, WIRE.md section 2) is the detail. The words are the Mac's, row for row.+"""++from __future__ import annotations++from dataclasses import dataclass++from core import protocol++PLATFORM_NAMES = {"macos": "Mac", "windows": "Windows", "linux": "Linux", "ios": "iPhone", "android": "Android"}+- REFUSED_KINDS = ("unauthenticated", "wrong_id", "different", "unreadable")++REFUSED_KINDS = ("unauthenticated", "wrong_id", "different", "unreadable", "forgotten")+VERSION_KINDS = ("older", "newer", "not_beamer")+UNREACHABLE_KINDS = ("unreachable", "timeout")+QUIET_KINDS = ("connected", "removed", "off")+++@dataclass(frozen=True)+class PeerState:+ tone: str+ word: str+ detail: str+++def platform_name(entry: dict) -> str:+ return PLATFORM_NAMES.get(entry.get("platform"), "Other")+++def address_line(entry: dict, hide: bool) -> str:+ host, port = entry.get("host") or "", entry.get("port")+ if not host or not isinstance(port, int) or isinstance(port, bool) or port <= 0:+ return "No address"+ return f"{'•••' if hide else host} · port {port}"+++def describe(entry: dict, label: str, *, up: bool, driving: bool, input_there: bool, kind: str, status: str,+ waking: bool) -> PeerState:+ """`up`: a link to this machine is live, either way round. `driving`: its input is on this PC.+ `input_there`: this PC's input is on it. `kind` and `status`: what the link this PC dials to it+ last reported."""+ if entry.get("in_use", True) is not True:+ return PeerState("amber", "NOT IN USE", f"{label} is not in use on this PC.")+ if driving:+ return PeerState("signal", "Driving this PC",+ f"{label}'s keyboard and pointer are on this PC. Push the pointer back through the edge it arrived by to send them home.")+ if input_there:+ return PeerState("signal", "Input here",+ f"This PC's keyboard and pointer are on {label}. Do the same again to bring them home.")+ if not protocol.linkable(entry):+ return PeerState("amber", "Pair again",+ f"{label} was paired on Beamer 1.4. Pair the two again to link them on 1.5.0.")+ if up:+ return PeerState("signal", "Linked", f"Connected to {label}.")+ if waking:+ return PeerState("amber", "Waiting", f"Waking {label}…")+ if not entry.get("send"):+ return PeerState("amber", "Waiting", f"Waiting for {label} to connect.")+ if not status or kind in QUIET_KINDS:+ return PeerState("amber", "Waiting", f"Looking for {label}. It connects on its own once Beamer is open there.")+ if kind in REFUSED_KINDS:+ return PeerState("fault", "Refused", status)+ if kind in VERSION_KINDS or (kind == "closed" and status.startswith("Update Beamer on")):+ return PeerState("fault", "Version", status)+ if kind in UNREACHABLE_KINDS:+ return PeerState("fault", "Unreachable", status)+ if kind == "refused":+ return PeerState("fault", "Not listening", status)+ return PeerState("fault", "Dropped", f"{status.rstrip('.')}. Beamer keeps trying to reconnect.")diff --cc win_app/sender.pyindex 003f049,db95afd..b02e742--- a/win_app/sender.py+++ b/win_app/sender.py@@@ -1314,183 -1143,11 +1314,183 @@@ class LinkSenderexcept Exception:LOGGER.exception("Pressure callback failed")- def _set_status(self, detail: str) -> None:- self._status = detail- if self._status_callback is None:++class LinkSet:+ """One core.link.OutboundLink for each peer entry this PC dials, keyed by the entry's token and+ found by peer id once up. What+ `LinkSender` asks of its links, and what each tells it back."""+- REFUSALS = ("older", "newer", "wrong_id", "unauthenticated", "different")++ REFUSALS = ("older", "newer", "wrong_id", "unauthenticated", "different", "forgotten")++ def __init__(self, sender: "LinkSender", is_local=is_this_machine, link_class=None) -> None:+ self._sender = sender+ self._is_local = is_local+ self._link_class = link_class or _outbound_link()+ self._links: dict = {} # token: OutboundLink+ self._by_peer: dict = {} # peer id: OutboundLink, while up+ self._lock = threading.RLock()+ self._started = False++ def start(self) -> None:+ with self._lock:+ self._started = True+ links = list(self._links.values())+ for link in links:+ link.start()++ def stop(self) -> None:+ with self._lock:+ self._started = False+ links = list(self._links.values())+ for link in links:+ link.stop()++ def key_of(self, entry: dict):+ return entry.get("token")++ def sync(self, entries: list) -> None:+ """Dials exactly the entries made by pairing whose address is not this PC's; an entry gone or+ turned local is stopped. The link itself ends and waits when `send` is off."""+ wanted = {+ entry["token"]: entry for entry in entries+ if entry.get("port") != 0 and protocol.linkable(entry) and not self._is_local(entry.get("host") or "")+ }+ with self._lock:+ gone = [token for token in self._links if token not in wanted]+ added = [token for token in wanted if token not in self._links]+ stale = [self._links.pop(token) for token in gone]+ downed = []+ for link in stale:+ # stop(wait=False) mutes the link's own down report, so the owner is told here.+ peer = protocol.read_id(link.peer_id)+ if peer is not None and self._by_peer.get(peer) is link:+ del self._by_peer[peer]+ downed.append(peer)+ fresh = []+ hooks = {"hardware": self._sender._hardware} if self._sender._hardware is not None else {}+ if hasattr(self._sender, "expects_clipboard"):+ hooks["large"] = self._sender.expects_clipboard+ for token in added:+ link = self._link_class(+ token, self._sender._book, self._sender._identity,+ state=self._state, up=self._up, message=self._message, **hooks,+ )+ self._links[token] = link+ fresh.append(link)+ started = self._started+ for link in stale:+ # Often the window's thread, which must not wait out a link that is in a 3 second connect.+ link.stop(wait=False)+ for peer in downed:+ self._sender.on_link(peer, False)+ if started:+ for link in fresh:+ link.start()++ def _link(self, peer):+ with self._lock:+ return self._by_peer.get(peer)++ def up(self, peer) -> bool:+ link = self._link(peer)+ return link is not None and link.live()++ live = up++ def refused(self, peer) -> bool:+ """The peer answered as a Beamer and refused this one: it is awake, and waking it would hide why."""+ link = self._link(peer)+ if link is None:+ entry = self._sender._peers.get(peer) or {}+ link = self._links.get(entry.get("token"))+ return link is not None and link.kind in self.REFUSALS++ def caps(self, peer) -> frozenset:+ link = self._link(peer)+ return link.caps if link is not None else frozenset()++ def post(self, peer, message) -> bool:+ link = self._link(peer)+ return link is not None and link.post(message)++ def send_input(self, peer, message) -> bool:+ link = self._link(peer)+ return link is not None and link.send_input(message)++ def close(self, peer, reason="The link went quiet") -> None:+ link = self._link(peer)+ if link is not None:+ link.drop(reason)++ def round_trip_ms(self, peer) -> Optional[int]:+ """The upper median of the last few trips, with the time the peer held each ACK taken off, or+ None when nothing fresh has been acknowledged."""+ link = self._link(peer)+ if link is None:+ return None+ trips = sorted(link.round_trips(ROUND_TRIP_MAX_AGE_SECONDS))+ return int(round(trips[len(trips) // 2] * 1000)) if trips else None++ def status(self, key) -> str:+ link = self._links.get(key)+ return link.status if link is not None else ""++ def kind(self, key) -> str:+ """What the link to the entry at `key` last reported (core.link's kinds), "" when none is dialled."""+ link = self._links.get(key)+ return link.kind if link is not None else ""++ def follow(self, machines: list) -> None:+ with self._lock:+ links = list(self._links.values())+ for link in links:+ link.follow(machines)++ def _state(self, link, up, text) -> None:+ if not up:+ peer = protocol.read_id(link.peer_id)+ with self._lock:+ held = peer is not None and self._by_peer.get(peer) is link+ if held:+ del self._by_peer[peer]+ if held:+ self._sender.on_link(peer, False)+ self._sender.on_status(link.token, up, text)++ def _up(self, link, fields) -> None:+ peer = fields["id"]+ with self._lock:+ if self._links.get(link.token) is not link:+ # Its machine was removed while the handshake finished: nothing would take it out again.+ return+ self._by_peer[peer] = link+ self._sender.on_link(peer, True, fields["accepts"])+ with self._lock:+ removed = self._links.get(link.token) is not link+ if removed:+ # sync took the machine out after the check above and told the owner it was down before+ # this told it up: that True landed last, so the owner is told down again.+ self._sender.on_link(peer, False)returntry:- self._status_callback(self.connected, detail)+ announcements = list(self._sender.announce(peer))except Exception:- LOGGER.exception("Status callback failed")+ LOGGER.exception("announce failed")+ announcements = []+ for message in announcements:+ link.post(message)++ def _message(self, link, message) -> None:+ peer = protocol.read_id(link.peer_id)+ if peer is not None:+ self._sender.on_message(peer, message, getattr(message, "began_at", None))+++def _outbound_link():+ from core import link++ return link.OutboundLink+++def _default_links(sender):+ return LinkSet(sender, sender._is_local)diff --cc win_app/tests/test_crossing_matrix.pyindex f28af94,5602ebd..560e825--- a/win_app/tests/test_crossing_matrix.py+++ b/win_app/tests/test_crossing_matrix.py@@@ -238,90 -199,88 +238,91 @@@ except ImportError: # PySide6 is onlykvm_bridge_win = None+def real_window(path):+ """The window over the settings at `path`, built offscreen, which starts no receiver, hooks or announcer."""+ from PySide6.QtWidgets import QApplication++ import theme++ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ QApplication.instance() or QApplication([])+ theme.init_fonts()+ # A free port, as cfad061 has every window test take: 24820 is the installed Beamer's.+ settings = app_config.load_settings(path)+ settings["port"] = harness.free_port()+ app_config.write_settings(path, settings)+ window = kvm_bridge_win.WindowsApplication(path)+ window._send_to = lambda peer, message: True+ return window++@unittest.skipIf(kvm_bridge_win is None, "needs PySide6")class ArrangementHeldByBothTests(unittest.TestCase):- """`_on_arrangement` and `_on_learned` are the two ways a Mac's idea of where the machines are- reaches this PC: a stamped message over either link, and the unstamped way home the hello- carries."""-- def page(self, edge="right", stamp=0):- config = default_config()- config.mac_return_edge = edge- config.arrangement_set_at = stamp- saved = []- page = types.SimpleNamespace(- _config=config,- _persist=lambda: saved.append((config.mac_return_edge, config.arrangement_set_at)) or True,- _start_sending=lambda config: None,- sender=types.SimpleNamespace(update_config=lambda config: None),- edge_choice=types.SimpleNamespace(set_value=lambda value: None),- mac_host_readout=types.SimpleNamespace(setText=lambda text: None),- _reflect_look=lambda: None,- _reflect_ways=lambda: None,+ """`_on_arrangement` is how a peer's idea of where the machines are reaches this PC: a stamped+ message over either link, settled by stamp and then by id (section 8)."""++ def setUp(self):+ import tempfile+ from pathlib import Path++ from core import protocol+ from core.tests import responder_harness as harness++ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.path = Path(directory.name) / "settings.json"+ self.peer = protocol.id_text(harness.B)+ self.own = protocol.id_text(harness.HERE)+ settings = app_config.migrate(None, machine_id=self.own)+ settings["peers"] = [harness.entry(harness.B, "Mac", side="right", side_set_at=100, side_by=self.own)]+ app_config.write_settings(self.path, settings)+ self.refreshed = []+ self.page = types.SimpleNamespace(+ _config=default_config(), config_path=self.path, _on_alert=lambda title, message: None,+ _pull_peer_fields=lambda: self.refreshed.append("pulled"),+ sender=types.SimpleNamespace(refresh=lambda: self.refreshed.append("sender")),+ server=types.SimpleNamespace(peers_changed=lambda: self.refreshed.append("server")),+ _tell=lambda peer: self.refreshed.append("answered"),++ _live=lambda peer: True,+ _read_crossing=lambda: None,+ _crossing_settings=lambda: app_config.load_settings(self.path),)- return page, saved-- def arrive(self, page, mac_edge, stamp):- kvm_bridge_win.WindowsApplication._on_arrangement(page, mac_edge, stamp)- def learn(self, page, edge, host="192.168.1.10"):- real = kvm_bridge_win.sender.is_this_machine- kvm_bridge_win.sender.is_this_machine = lambda h: False- try:- kvm_bridge_win.WindowsApplication._on_learned(page, host, edge, 40)- finally:- kvm_bridge_win.sender.is_this_machine = real+ def arrive(self, edge, stamp, by=None):+ kvm_bridge_win.WindowsApplication._on_arrangement(self.page, self.peer, edge, stamp, by or self.peer)- def test_a_newer_arrangement_from_the_mac_is_applied_as_this_pcs_opposite_edge_with_its_stamp(self):- page, saved = self.page("right", stamp=100)- self.arrive(page, "top", 200)- self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("bottom", 200))+ def side(self):+ return json.loads(self.path.read_text(encoding="utf-8"))["peers"][0]["side"]- def test_the_same_edge_with_a_newer_stamp_leaves_the_stored_stamp_as_the_mac_does(self):- page, saved = self.page("left", stamp=100)- self.arrive(page, "right", 200)- self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("left", 100))+ def test_a_newer_arrangement_is_applied_as_this_pcs_opposite_edge(self):+ self.arrive("top", 200)+ self.assertEqual(self.side(), "bottom")+ self.assertEqual(self.refreshed, ["pulled", "sender", "server", "answered"])def test_an_older_arrangement_is_ignored(self):- page, saved = self.page("right", stamp=200)- self.arrive(page, "top", 100)- self.assertEqual(page._config.mac_return_edge, "right")- self.assertEqual(saved, [])+ self.arrive("top", 50)+ self.assertEqual(self.side(), "right")+ self.assertEqual(self.refreshed, [])def test_the_same_arrangement_over_the_second_link_changes_nothing_and_logs_nothing(self):- # One change on the Mac reaches this PC over both links, so the second copy carries the- # stamp the first already stored.- page, saved = self.page("left", stamp=300)+ self.arrive("top", 200)+ self.refreshed.clear()with self.assertNoLogs(kvm_bridge_win.LOGGER, logging.INFO):- self.arrive(page, "right", 300)- self.assertEqual(saved, [])+ self.arrive("top", 200)+ self.assertEqual(self.refreshed, [])- def test_the_macs_hello_names_the_edge_of_a_pc_that_has_none(self):- page, saved = self.page("", stamp=0)- self.learn(page, "left")- self.assertEqual(page._config.mac_return_edge, "left")-- def test_a_change_made_here_with_no_link_is_stored_and_told_to_nobody(self):- page, saved = self.page("right", stamp=0)+ def test_a_change_made_here_is_stamped_and_sent_to_that_machine(self):+ window = real_window(self.path)+ self.addCleanup(window.server.stop)told = []- page.sender = types.SimpleNamespace(send_arrangement=lambda *a: told.append(("pc-to-mac", a)) or False, update_config=lambda c: None)- page.server = types.SimpleNamespace(send_arrangement=lambda *a: told.append(("mac-to-pc", a)) or False)- kvm_bridge_win.WindowsApplication._set_arrangement(page, "top")- self.assertEqual(page._config.mac_return_edge, "top")- self.assertGreater(page._config.arrangement_set_at, 0)- self.assertEqual([who for who, _ in told], ["pc-to-mac", "mac-to-pc"])- self.assertEqual(told[0][1][0], "bottom")-- def test_the_macs_hello_replaces_an_edge_set_here_and_leaves_its_stamp_claiming_otherwise(self):- # Pinned known gap (G1 in the report): the hello should not win over a newer stamp.- # What a PC set up before pairing goes through: the choice made here is stamped, the Mac's- # first hello names its own way home, and that is what the PC then holds, under the stamp- # of the choice it replaced.- page, saved = self.page("top", stamp=5000)- self.learn(page, "left")- self.assertEqual((page._config.mac_return_edge, page._config.arrangement_set_at), ("left", 5000))+ window._send_to = lambda peer, message: told.append((peer, message)) or False+ window._set_arrangement("top")+ entry = json.loads(self.path.read_text(encoding="utf-8"))["peers"][0]+ self.assertEqual((entry["side"], entry["side_by"]), ("top", self.own))+ self.assertGreater(entry["side_set_at"], 100)+ peer, message = told[0]+ self.assertEqual(peer, harness.B)+ self.assertEqual(message["data"], {"edge": "top", "set_at": entry["side_set_at"], "by": self.own, "way_back": True})def test_a_fresh_config_holds_no_edge_though_the_crossing_page_offers_right(self):# Pinned known gap (G3 in the report).diff --cc win_app/tests/test_ignored_page.pyindex 47948fa,15f77f7..ee93cb4--- a/win_app/tests/test_ignored_page.py+++ b/win_app/tests/test_ignored_page.py@@@ -91,6 -87,6 +91,48 @@@ class RecorderTests(unittest.TestCase)self.key(False, 0x11, 0x1D)self.assertEqual(self.recorded, [("key", 0xA2)])++ def test_laid_out_keycap_has_room_for_its_key_and_hint(self):++ # A widget that owns a layout is sized from that layout, not from its heightForWidth, so the++ # keycap's own padding has to live in the layout: without it the hint's last pixels sat++ # under the bottom border ("Click, then press the key" half cut off).++ from PySide6.QtWidgets import QVBoxLayout, QWidget++++ self.holder = holder = QWidget()++ column = QVBoxLayout(holder)++ column.addWidget(self.recorder)++ column.addStretch(1)++ holder.resize(280, 400)++ holder.show()++ self.app.processEvents()++ room = self.recorder.width() - 24++ need = self.recorder.key.heightForWidth(room) + self.recorder.hint.heightForWidth(room) + 10 + 16++ self.assertGreaterEqual(self.recorder.height(), need)++ holder.hide()++++ def test_hint_gets_the_whole_width_the_box_reserved_for_it(self):++ # Windows' fonts wrapped "Click, then press the key" inside a 110 px hint at 150% while the++ # box had reserved one line at its full width, so "key" sat under the bottom border. A++ # longer hint wraps at the size-hint width on any font, which is what the old layout used.++ from PySide6.QtWidgets import QVBoxLayout, QWidget++++ self.recorder.cancel()++ self.holder = holder = QWidget()++ column = QVBoxLayout(holder)++ column.addWidget(self.recorder)++ column.addStretch(1)++ for text in ("Click, then press the key", "Click here, then press the key you want to use as the shortcut"):++ self.recorder.hint.setText(text)++ for width in (240, 280, 420):++ with self.subTest(text=text, width=width):++ holder.resize(width, 400)++ holder.show()++ self.app.processEvents()++ hint = self.recorder.hint++ self.assertEqual(hint.width(), self.recorder.width() - 24)++ self.assertGreaterEqual(hint.height(), hint.heightForWidth(hint.width()))++ self.assertLessEqual(hint.geometry().bottom(), self.recorder.height() - 8)++ holder.hide()++if __name__ == "__main__":unittest.main()diff --cc win_app/tests/test_pc_three_machines.pyindex b3baf3e,0000000..a6d1d55mode 100644,000000..100644--- a/win_app/tests/test_pc_three_machines.py+++ b/win_app/tests/test_pc_three_machines.py@@@ -1,689 -1,0 +1,751 @@@+"""Three machines on the Windows app (1.5.0 milestone 5): the shortcut's machine, a tray item per+machine, each machine's ways written on its own, the Crossing page's choice of machine, the diagram+of this PC and its neighbours, and Pause counting every machine's zones (WIRE.md sections 5 and 8)."""++import json+import os+import sys+import tempfile+import unittest+from unittest import mock+from pathlib import Path++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from links_rig import B, C, Rig, edge_zone++import app_config+import pages_win+import sender as sender_module+from core import protocol+from core import ways+from core.tests import responder_harness as harness++try:+ from PySide6.QtWidgets import QApplication++ import diagram+ import kvm_bridge_win+ import theme+except ImportError: # PySide6 is only in the Windows venv+ kvm_bridge_win = None++D = harness.D+BT, CT, DT = protocol.id_text(B), protocol.id_text(C), protocol.id_text(D)+HIGH_ID = bytes([200]) * 16+HIGH = protocol.id_text(HIGH_ID)+++def target_of(message):+ return protocol.read_id(message["data"]["target"])+++class ShortcutMachineTests(unittest.TestCase):+ """The shortcut, the Send button and the tray send input where core.ways.shortcut_peer says."""++ def rig(self, up, **entries):+ peers = [harness.entry(B, "Bee", side="left", **entries.get("b", {})),+ harness.entry(C, "Sea", side="right", **entries.get("c", {}))]+ return Rig(entries=peers, zones=[edge_zone(B), edge_zone(C)], up=up)++ def test_with_the_first_machine_down_the_shortcut_takes_one_that_is_up(self):+ rig = self.rig(up=(C,))+ self.assertTrue(rig.sender.set_redirecting(True))+ self.assertEqual(rig.sender.owner, C)+ self.assertEqual(target_of(rig.sent(C, "focus")[0]), C)++ def test_the_shortcut_goes_back_to_the_machine_input_was_last_on(self):+ rig = self.rig(up=(B, C))+ rig.sender.go(C)+ rig.accept_take(C)+ rig.sender.set_redirecting(False)+ self.assertEqual(rig.sender.shortcut_target(), C)+ self.assertTrue(rig.sender.set_redirecting(True))+ self.assertEqual(rig.sender.owner, C)++ def test_a_machine_that_does_not_accept_input_is_passed_over(self):+ rig = self.rig(up=(C,))+ rig.bring_up(B, accepts=False)+ self.assertEqual(rig.sender.shortcut_target(), C)++ def test_a_machine_this_pc_does_not_send_to_is_never_picked(self):+ rig = self.rig(up=(B, C), b={"send": False})+ self.assertEqual(rig.sender.shortcut_target(), C)++ def test_with_every_machine_down_the_first_is_woken(self):+ rig = self.rig(up=(), b={"hw": "aa:bb:cc:dd:ee:ff"})+ woken = []+ rig.sender._wake_sender = lambda address, host: woken.append(address)+ self.addCleanup(rig.sender._stop_event.set)+ self.assertFalse(rig.sender.set_redirecting(True))+ self.assertTrue(rig.sender.is_waking(B))+ self.assertFalse(rig.sender.is_waking(C))++ def test_with_every_machine_down_and_none_to_wake_the_first_is_named(self):+ rig = self.rig(up=())+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][0]), False, "Bee is unreachable")+ self.assertFalse(rig.sender.set_redirecting(True))+ self.assertEqual(rig.alerts, ["Cannot switch — Bee is unreachable"])++ def test_the_status_is_the_shortcut_machines(self):+ rig = self.rig(up=(C,))+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][0]), False, "Bee is unreachable")+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][1]), True, "Connected to Sea")+ self.assertTrue(rig.sender.connected)+ self.assertEqual(rig.sender.status, "Connected to Sea")++ def test_the_status_does_not_name_a_machine_not_in_use(self):+ rig = self.rig(up=(), b={"in_use": False})+ rig.sender.on_status(rig.links.key_of(rig.settings.data["peers"][0]), False, "Bee is unreachable")+ self.assertEqual(rig.sender.status, sender_module.NOT_CONNECTED_STATUS)+++class SetWaysTests(unittest.TestCase):+ """Each machine's side and zones are written one machine at a time, under the settings lock, and+ never by a flat save."""++ def setUp(self):+ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.path = Path(directory.name) / "settings.json"+ settings = app_config.migrate(None, machine_id=protocol.id_text(harness.HERE))+ settings["peers"] = [+ harness.entry(B, "Bee", side="left", side_set_at=100, side_by=HIGH),+ harness.entry(C, "Sea", platform="windows"),+ ]+ settings["zones"] = [{"peer": BT, "kind": "edge"}]+ app_config.write_settings(self.path, settings)++ def saved(self):+ return json.loads(self.path.read_text(encoding="utf-8"))++ def peer(self, ident):+ return next(item for item in self.saved()["peers"] if item["id"] == ident)++ def zones(self, ident):+ return {zone["kind"]: zone for zone in self.saved()["zones"] if zone["peer"] == ident}++ def test_reading_the_settings_gives_a_machine_with_no_zone_its_edge_and_writes_it(self):+ # The rig's beta.3 file of 01-10-2026: the laptop paired second, its side set, no zone at all.+ settings = self.saved()+ settings["peers"][1]["side"] = "right"+ app_config.write_settings(self.path, settings)+ loaded = app_config.load_settings(self.path)+ self.assertIn({"peer": CT, "kind": "edge"}, loaded["zones"])+ self.assertIn({"peer": CT, "kind": "edge"}, self.saved()["zones"])++ def test_one_whose_side_is_taken_gets_its_edge_off_and_the_file_still_reads(self):+ settings = self.saved()+ settings["peers"][1]["side"] = "left"+ app_config.write_settings(self.path, settings)+ loaded = app_config.load_settings(self.path)+ self.assertIn({"peer": CT, "kind": "edge", "off": True}, loaded["zones"])+ self.assertIn("Sea has no way in", ways.blocked_sentence(loaded, CT, "this PC"))++ def test_one_machines_side_and_zones_are_written_and_the_others_left_alone(self):+ moved = app_config.set_ways(self.path, CT, side="right", methods=["part", "corner"], parts=["end"], corner="bottom_right")+ self.assertTrue(moved)+ entry = self.peer(CT)+ self.assertEqual((entry["side"], entry["side_by"]), ("right", self.saved()["machine_id"]))+ self.assertGreater(entry["side_set_at"], 0)+ zones = self.zones(CT)+ self.assertEqual(zones["part"]["parts"], ["end"])+ self.assertNotIn("off", zones["part"])+ self.assertTrue(zones["edge"]["off"])+ self.assertEqual((zones["corner"]["corner"], zones["corner"]["edge"]), ("bottom_right", "right"))+ self.assertEqual(self.peer(BT)["side"], "left")+ self.assertEqual(self.zones(BT), {"edge": {"peer": BT, "kind": "edge"}})++ def test_an_unchanged_side_is_not_a_move(self):+ self.assertFalse(app_config.set_ways(self.path, BT, side="left", methods=["edge"], parts=["middle"], corner="top_left"))+ self.assertEqual(self.peer(BT)["side_set_at"], 100)++ def test_no_side_given_keeps_the_side_held_whatever_the_window_last_read(self):+ settings = self.saved()+ settings["peers"][0]["side"] = "top"+ app_config.write_settings(self.path, settings)+ self.assertFalse(app_config.set_ways(self.path, BT, methods=["edge", "corner"], parts=["middle"], corner="top_left"))+ self.assertEqual(self.peer(BT)["side"], "top")+ self.assertEqual(self.zones(BT)["corner"]["edge"], "top")++ def test_a_clash_is_refused_with_a_sentence_naming_both_and_nothing_is_written(self):+ # On Bee's side with no way in yet: turning Sea's edge on would cover Bee's.+ app_config.set_ways(self.path, CT, side="left", methods=[], parts=["middle"], corner="top_left")+ before = self.path.read_bytes()+ with self.assertRaises(app_config.ConfigError) as raised:+ app_config.set_ways(self.path, CT, side="left", methods=["edge"], parts=["middle"], corner="top_left")+ self.assertIn("Bee", str(raised.exception))+ self.assertIn("Sea", str(raised.exception))+ self.assertIn("this PC", str(raised.exception))+ self.assertEqual(self.path.read_bytes(), before)++ def test_a_machine_that_is_not_paired_is_an_error(self):+ with self.assertRaises(app_config.ConfigError):+ app_config.set_ways(self.path, DT, side="left", methods=[], parts=["middle"], corner="top_left")++ def test_a_flat_save_never_writes_a_side_or_a_zone(self):+ stale = app_config.load_config(self.path)+ settings = self.saved()+ settings["peers"][0].update(side="top", side_set_at=300, side_by=HIGH)+ app_config.write_settings(self.path, settings)+ app_config.save_config(self.path, app_config.replace(+ stale, crossing_methods=["part"], crossing_edge_parts=["start"], mac_return_edge="bottom",+ arrangement_set_at=400, pointer_speed=2.0))+ saved = self.saved()+ self.assertEqual((saved["peers"][0]["side"], saved["peers"][0]["side_set_at"], saved["peers"][0]["side_by"]),+ ("top", 300, HIGH))+ # Sea's edge is the repair every read makes for a machine paired with no zone, not the save's.+ self.assertEqual(saved["zones"], [{"peer": BT, "kind": "edge"}, {"peer": CT, "kind": "edge"}])+ self.assertFalse(saved["shortcut"])+ self.assertEqual(saved["pointer_speed"], 2.0)++ def test_a_flat_save_keeps_a_name_and_hardware_address_learnt_since_the_window_read(self):+ stale = app_config.load_config(self.path)+ settings = self.saved()+ settings["peers"][0].update(name="Bee Studio", hw="aa:bb:cc:dd:ee:01")+ app_config.write_settings(self.path, settings)+ app_config.save_config(self.path, app_config.replace(stale, pointer_speed=2.0))+ self.assertEqual((self.peer(BT)["name"], self.peer(BT)["hw"]), ("Bee Studio", "aa:bb:cc:dd:ee:01"))+ app_config.save_config(self.path, app_config.replace(stale, mac_host="192.0.2.99", paired_with="",+ mac_hardware_address=""))+ self.assertEqual((self.peer(BT)["host"], self.peer(BT)["name"], self.peer(BT)["hw"]), ("192.0.2.99", "", ""))++ def test_an_arrangement_rewrites_the_edge_that_machines_corner_crosses(self):+ settings = self.saved()+ settings["zones"].append({"peer": BT, "kind": "corner", "corner": "top_right", "edge": "left"})+ app_config.write_settings(self.path, settings)+ self.assertEqual(app_config.apply_arrangement(self.path, BT, "left", 500, HIGH), (True, []))+ self.assertEqual((self.peer(BT)["side"], self.zones(BT)["corner"]["edge"]), ("right", "right"))++ def test_an_arrangement_is_core_ways_and_names_both_machines(self):+ settings = self.saved()+ settings["peers"][1]["side"] = "right"+ settings["zones"].append({"peer": CT, "kind": "edge"})+ app_config.write_settings(self.path, settings)+ changed, notices = app_config.apply_arrangement(self.path, CT, "right", 500, HIGH)+ self.assertTrue(changed)+ self.assertEqual(self.peer(CT)["side"], "left")+ self.assertEqual(notices, ["Bee and Sea now lead from the same part of this PC's screen, so Sea's edge is off."])+ self.assertTrue(self.zones(CT)["edge"]["off"])+++class DiagramGeometryTests(unittest.TestCase):+ SCREEN = (120.0, 75.0)++ def test_machines_sharing_a_side_are_ordered_by_their_thirds_then_the_list(self):+ slots = pages_win.side_slots([+ {"side": "right", "methods": ["part"], "parts": ["end"]},+ {"side": "right", "methods": ["part"], "parts": ["start"]},+ {"side": "top", "methods": [], "parts": ["middle"]},+ {"side": "", "methods": ["corner"], "parts": ["middle"]},+ ])+ self.assertEqual(slots, [("right", 0.5, 1.0), ("right", 0.0, 0.5), ("top", 0.0, 1.0), None])++ def test_one_machine_sits_where_the_pair_always_did(self):+ for side, offset in (("right", (134.0, 0.0)), ("left", (-134.0, 0.0)), ("top", (0.0, -89.0)), ("bottom", (0.0, 89.0))):+ pc, (other,), _height = pages_win.layout_rects(400.0, 0.0, [(pages_win.SIDE_ANGLE[side], 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual((other[0] - pc[0], other[1] - pc[1]), offset, side)+ self.assertEqual(other[2:], self.SCREEN)+ pc, (other,), height = pages_win.layout_rects(400.0, 10.0, [(0.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual(height, 75.0)+ self.assertEqual((pc[0] + other[0] + other[2]) / 2.0, 200.0)+ self.assertEqual(pc[1], 10.0)+ _pc, _rects, stacked = pages_win.layout_rects(400.0, 0.0, [(90.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual(stacked, 164.0)++ def test_a_row_puts_this_pc_in_the_middle(self):+ pc, (left, right), height = pages_win.layout_rects(+ 500.0, 0.0, [(180.0, 0.0, 1.0), (0.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual(pc[0] + pc[2] / 2.0, 250.0)+ self.assertEqual(left[0] + left[2] + 14.0, pc[0])+ self.assertEqual(right[0], pc[0] + pc[2] + 14.0)+ self.assertEqual(height, 75.0)++ def test_two_on_one_side_are_each_half_as_long_and_split_it(self):+ pc, (top, bottom), _height = pages_win.layout_rects(+ 500.0, 0.0, [(0.0, 0.0, 0.5), (0.0, 0.5, 1.0)], self.SCREEN, 14.0)+ self.assertEqual(top[2:], (60.0, 37.5))+ self.assertEqual(bottom[2:], (60.0, 37.5))+ self.assertEqual(top[0], pc[0] + pc[2] + 14.0)+ self.assertEqual((top[1], bottom[1] + bottom[3]), (pc[1], pc[1] + pc[3]))++ def test_an_l_has_one_beside_and_one_above(self):+ pc, (right, above), height = pages_win.layout_rects(+ 500.0, 0.0, [(0.0, 0.0, 1.0), (90.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertEqual((right[0], right[1]), (pc[0] + pc[2] + 14.0, pc[1]))+ self.assertEqual((above[0], above[1] + above[3] + 14.0), (pc[0], pc[1]))+ self.assertEqual(above[1], 0.0)+ self.assertEqual(height, 164.0)++ def test_with_several_machines_this_pc_stays_in_the_middle_whatever_the_sides(self):+ for placed in ([(0.0, 0.0, 1.0), (90.0, 0.0, 1.0)], [(0.0, 0.0, 0.5), (0.0, 0.5, 1.0)]):+ pc, _rects, _height = pages_win.layout_rects(500.0, 0.0, placed, self.SCREEN, 14.0, centre_pc=True)+ self.assertEqual(pc[0] + pc[2] / 2.0, 250.0, placed)+ pc, (_left, right), _height = pages_win.layout_rects(+ 300.0, 0.0, [(0.0, 0.0, 1.0), (90.0, 0.0, 1.0)], self.SCREEN, 14.0, centre_pc=True)+ self.assertEqual(pc[0] + pc[2] / 2.0, 150.0)+ self.assertLessEqual(right[0] + right[2], 300.001)++ def test_a_narrow_width_shrinks_the_drawing_to_fit(self):+ pc, (left, right), _height = pages_win.layout_rects(+ 300.0, 0.0, [(180.0, 0.0, 1.0), (0.0, 0.0, 1.0)], self.SCREEN, 14.0)+ self.assertGreaterEqual(left[0], -0.001)+ self.assertLessEqual(right[0] + right[2], 300.001)+ self.assertLess(pc[2], 120.0)++ def test_nobody_goes_through_this_pc_on_the_way_round(self):+ for start, end in ((0.0, 1.0), (0.0, 0.5), (0.5, 1.0)):+ for angle in range(0, 360, 5):+ pc, (other,), _height = pages_win.layout_rects(500.0, 0.0, [(float(angle), start, end)], self.SCREEN, 14.0)+ apart_x = other[0] >= pc[0] + pc[2] or other[0] + other[2] <= pc[0]+ apart_y = other[1] >= pc[1] + pc[3] or other[1] + other[3] <= pc[1]+ self.assertTrue(apart_x or apart_y, (angle, start, end))++ def test_the_description_names_every_machine_and_its_side(self):+ machines = [+ {"label": "Bee", "side": "right", "methods": ["edge"], "parts": ["middle"], "corner": "top_left", "chosen": True},+ {"label": "Sea", "side": "top", "methods": [], "parts": ["middle"], "corner": "top_left", "chosen": False},+ {"label": "Dee", "side": "", "methods": [], "parts": ["middle"], "corner": "top_left", "chosen": False},+ ]+ text = pages_win.diagram_description(machines, "Right Ctrl", "hold", True)+ self.assertIn("Bee is to the right of this PC", text)+ self.assertIn("Sea is above this PC", text)+ self.assertIn("Not placed yet: Dee", text)+ self.assertIn("Input moves to Bee when you push through the whole right edge", text)++ def test_the_unplaced_line_names_them_all(self):+ self.assertEqual(pages_win.unplaced_line(["Sea"]), "Not placed yet: Sea")+ self.assertEqual(pages_win.unplaced_line(["Sea", "Dee", "Eff"]), "Not placed yet: Sea, Dee and Eff")+ self.assertEqual(pages_win.unplaced_line([]), "")+++class WordingTests(unittest.TestCase):+ def test_the_summary_and_the_unlearned_side_name_the_machine(self):+ self.assertEqual(pages_win.ways_summary(["edge"], "right", [], "top_left", "F13", "hold", "Sea"),+ "Input moves to Sea when you push through the whole right edge.")+ self.assertIn("on Sea", pages_win.not_learned_edge("Sea"))+ self.assertIn("the other machine", pages_win.not_learned_edge())++ def test_no_page_purpose_pictures_exactly_one_other_machine(self):+ for _key, _name, purpose in pages_win.PAGES:+ self.assertNotIn("the other machine", purpose)+ for line in pages_win.SCOPE.values():+ self.assertNotIn("the other machine", line)++[email protected](kvm_bridge_win is None, "needs PySide6")+class WindowTests(unittest.TestCase):+ """The real window, built offscreen from a settings file, which starts no receiver, hooks or announcer."""++ PEERS = None++ def setUp(self):+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ self.app = QApplication.instance() or QApplication([])+ theme.init_fonts()+ directory = tempfile.TemporaryDirectory()+ self.addCleanup(directory.cleanup)+ self.path = Path(directory.name) / "settings.json"+ settings = app_config.migrate(None, machine_id=protocol.id_text(harness.HERE))+ settings["peers"] = self.PEERS if self.PEERS is not None else [+ harness.entry(B, "Bee", side="left", side_set_at=100, side_by=HIGH, paired_with=[]),+ harness.entry(C, "Sea", platform="windows", allow_drive=False),+ ]+ settings["zones"] = [{"peer": BT, "kind": "edge"}]+ settings["port"] = harness.free_port()+ app_config.write_settings(self.path, settings)+ self.window = kvm_bridge_win.WindowsApplication(self.path)++ # Both linked: a machine with no link gives way instead of being offered thirds (core/ways.py give_way).++ self.linked = {BT, CT}++ self.window._live = lambda peer: peer in self.linked+ self.sent = []+ self.window._send_to = lambda peer, message: self.sent.append((peer, message)) or True+ self.window._refresh_window()++ def tearDown(self):+ self.window.server.stop()+ self.window.deleteLater()++ def saved(self):+ return json.loads(self.path.read_text(encoding="utf-8"))++ def peer(self, ident):+ return next(item for item in self.saved()["peers"] if item["id"] == ident)+++class CrossingPageTests(WindowTests):+ def sharing_side(self):+ settings = app_config.load_settings(self.path)+ for peer in settings["peers"]:+ peer.update(side="right", side_set_at=100 if peer["id"] == BT else 200, side_by=HIGH)+ settings["zones"] = [{"peer": BT, "kind": "edge"}, {"peer": CT, "kind": "edge", "off": True}]+ app_config.write_settings(self.path, settings)+ self.window._pull_peer_fields()+ self.window._choose_machine(CT)+ return self.window+++ def test_edge_turns_on_over_a_machine_with_no_link_and_that_machines_edge_goes_off(self):++ # 06-10-2026: a machine gone for good held the side, and Edge would not turn on until it was moved.++ window = self.sharing_side()++ self.linked = {CT}++ window._choose_machine(CT)++ self.assertTrue(window.share_module.isHidden())++ window.way_boxes["edge"].setChecked(True)++ self.assertTrue(window.way_boxes["edge"].isChecked())++ zones = {(zone["peer"], zone["kind"]): zone for zone in app_config.load_settings(self.path)["zones"]}++ self.assertTrue(zones[(BT, "edge")].get("off"))++ self.assertTrue(zones[(BT, "edge")].get("aside"))++ self.assertIsNone(zones[(CT, "edge")].get("off"))++++ def lid_shut(self):++ """Sea given Bee's side while Bee, with its lid shut, has no link to this PC."""++ window = self.sharing_side()++ self.linked = {CT}++ window._choose_machine(CT)++ window.way_boxes["edge"].setChecked(True)++ self.alerts = []++ window._on_alert = lambda title, message: self.alerts.append(message)++ return window++++ def bee_zone(self):++ return next(zone for zone in app_config.load_settings(self.path)["zones"]++ if zone["peer"] == BT and zone["kind"] == "edge")++++ def test_a_machine_with_its_lid_shut_has_its_edge_set_aside_and_gets_it_back_when_it_connects(self):++ window = self.lid_shut()++ self.assertEqual(self.bee_zone(), {"peer": BT, "kind": "edge", "off": True, "aside": True})++ window.way_boxes["edge"].setChecked(False)++ window._settle_presence()++ self.assertTrue(self.bee_zone().get("aside"))++ self.linked = {BT, CT}++ window._settle_presence()++ self.assertEqual(self.bee_zone(), {"peer": BT, "kind": "edge"})++ self.assertIn(protocol.read_id(BT), {peer for peer, _message in self.sent})++ self.assertEqual(self.alerts, [])++++ def test_a_machine_back_over_a_side_another_holds_stays_off_and_the_page_offers_thirds(self):++ window = self.lid_shut()++ self.linked = {BT, CT}++ window._settle_presence()++ self.assertEqual(self.bee_zone(), {"peer": BT, "kind": "edge", "off": True})++ self.assertEqual(len(self.alerts), 1)++ window._choose_machine(BT)++ self.assertFalse(window.share_module.isHidden())++++ def test_a_machine_that_removed_this_pairing_stays_off_for_good_and_the_page_says_so(self):++ window = self.lid_shut()++ window._gone = lambda peer: peer == BT++ window._settle_presence()++ self.assertEqual(self.bee_zone(), {"peer": BT, "kind": "edge", "off": True})++ self.assertEqual(self.alerts, ["Bee no longer has this pairing, so its edge stays off. Remove Bee here and "++ "pair the two again."])++ window._choose_machine(BT)++ self.assertFalse(window.blocked_note.isHidden())++ self.assertIn("Bee no longer has this pairing", window.blocked_note.text())+++ def test_the_share_panel_offers_thirds_below_the_side_and_hides_the_blocked_sentence(self):+ window = self.sharing_side()+ self.assertFalse(window.share_module.isHidden())+ self.assertEqual([window.share_tiles[p].text() for p in ("start", "middle", "end")],+ ["Top\nBee", "Middle\nBee", "Bottom\nSea"])+ self.assertTrue(window.blocked_note.isHidden())++ def test_a_tile_cycles_its_machine_and_share_saves_and_tells_each_one(self):+ window = self.sharing_side()+ window.share_tiles["start"].click()+ self.assertEqual(window.share_tiles["start"].text(), "Top\nSea")+ window.share_button.click()+ zones = {(zone["peer"], zone["kind"]): zone for zone in self.saved()["zones"]}+ self.assertEqual(zones[(BT, "part")]["parts"], ["middle"])+ self.assertEqual(zones[(CT, "part")]["parts"], ["start", "end"])+ self.assertTrue(zones[(BT, "edge")].get("off"))+ self.assertTrue(zones[(CT, "edge")].get("off"))+ self.assertEqual({peer for peer, _data in self.arrangements()}, {B, C})++ def test_turning_on_edge_keeps_it_off_and_focuses_the_share_button(self):+ window = self.sharing_side()+ # An offscreen window is never active, so the focus asked for is what can be checked.+ with mock.patch.object(window.share_button, "setFocus") as focus:+ window.way_boxes["edge"].setChecked(True)+ self.assertFalse(window.way_boxes["edge"].isChecked())+ self.assertFalse(window.share_module.isHidden())+ self.assertTrue(window.blocked_note.isHidden())+ focus.assert_called()++ def test_turning_on_an_overlapping_part_keeps_it_off_and_focuses_the_share_button(self):+ window = self.sharing_side()+ # An offscreen window is never active, so the focus asked for is what can be checked.+ with mock.patch.object(window.share_button, "setFocus") as focus:+ window.way_boxes["part"].setChecked(True)+ self.assertFalse(window.way_boxes["part"].isChecked())+ self.assertFalse(window.share_module.isHidden())+ self.assertTrue(window.blocked_note.isHidden())+ focus.assert_called()++ def test_with_two_machines_paired_the_page_offers_a_choice_of_machine(self):+ window = self.window+ self.assertFalse(window.machine_row.isHidden())+ self.assertEqual(set(window.machine_choice._buttons), {BT, CT})+ self.assertEqual([button.text() for button in window.machine_choice._buttons.values()], ["Bee", "Sea"])+ self.assertEqual(window.machine_choice.value, BT)+ self.assertEqual(window.edge_choice.value, "left")+ self.assertTrue(window.way_boxes["edge"].isChecked())+ self.assertEqual(window.edge_heading.text(), "Where Bee is")++ def test_choosing_a_machine_shows_its_ways(self):+ window = self.window+ window._choose_machine(CT)+ self.assertEqual(window.edge_choice.value, None)+ # Every machine paired starts with its whole edge, which waits for a side.+ self.assertTrue(window.way_boxes["edge"].isChecked())+ self.assertTrue(window.way_boxes["shortcut"].isChecked())+ self.assertEqual(window.edge_heading.text(), "Where Sea is")+ self.assertEqual(window.edge_unlearned.text(), pages_win.not_learned_edge("Sea"))+ self.assertIn("Sea", window.ways_summary.text())++ def test_a_side_set_here_is_that_machines_alone_and_is_sent_to_it(self):+ window = self.window+ window._choose_machine(CT)+ window._set_arrangement("right")+ self.assertEqual(self.peer(CT)["side"], "right")+ self.assertEqual(self.peer(BT)["side"], "left")+ (peer, message), = self.sent+ self.assertEqual(peer, C)+ self.assertEqual(message["data"]["edge"], "right")+ self.assertEqual(message["data"]["set_at"], self.peer(CT)["side_set_at"])++ def arrangements(self):+ return [(peer, message["data"]) for peer, message in self.sent if message["type"] == protocol.MSG_ARRANGEMENT]++ def test_turning_off_every_way_to_a_machine_tells_it_so_with_its_side_as_it_was(self):+ self.window.way_boxes["edge"].setChecked(False)+ (peer, data), = self.arrangements()+ self.assertEqual((peer, data["edge"], data["set_at"], data["by"], data["way_back"]), (B, "left", 100, HIGH, False))+ self.window.way_boxes["corner"].setChecked(True)+ self.assertIs(self.arrangements()[-1][1]["way_back"], True)++ def test_moving_one_machine_tells_every_machine_whose_way_back_it_changed(self):+ settings = self.saved()+ settings["peers"][0].update(side="left", side_set_at=100, side_by=HIGH)+ settings["peers"][1].update(side="left", side_set_at=200, side_by=HIGH)+ settings["zones"] = [{"peer": BT, "kind": "edge"}, {"peer": CT, "kind": "edge", "off": True}]+ app_config.write_settings(self.path, settings)+ self.window._pull_peer_fields()+ self.assertEqual(ways.way_back_by(self.window._crossing_settings(), CT), BT)+ self.window._choose_machine(BT)+ self.window._set_arrangement("right")+ self.assertCountEqual([peer for peer, _data in self.arrangements()], [B, C])++ def test_removing_the_machine_in_the_way_tells_the_one_it_blocked(self):+ settings = self.saved()+ settings["peers"][0].update(side="left", side_set_at=100, side_by=HIGH)+ settings["peers"][1].update(side="left", side_set_at=200, side_by=HIGH)+ settings["zones"] = [{"peer": BT, "kind": "edge", "off": True}, {"peer": CT, "kind": "edge"}]+ app_config.write_settings(self.path, settings)+ self.window._pull_peer_fields()+ self.assertEqual(ways.way_back_by(self.window._crossing_settings(), BT), CT)++ self.window._remove_peer(harness.TOKENS[C])++ told = [(peer, data) for peer, data in self.arrangements() if peer == B]+ self.assertEqual(len(told), 1)+ self.assertFalse(told[0][1]["way_back"])+ self.assertNotIn("way_back_by", told[0][1])++ def test_an_arrangement_that_changed_something_is_answered_with_this_pcs_own(self):+ window = self.window+ window.bridge.arrangement.emit(CT, "left", 500, HIGH, True, None)+ (peer, data), = self.arrangements()+ self.assertEqual((peer, data["edge"], data["set_at"], data["by"], data["way_back"]), (C, "right", 500, HIGH, True))+ self.assertIs(self.peer(CT)["way_back"], True)+ window.bridge.arrangement.emit(CT, "left", 500, HIGH, True, None)+ self.assertEqual(len(self.arrangements()), 1)+ window.bridge.arrangement.emit(CT, "left", 500, HIGH, False, None)+ self.assertEqual(len(self.arrangements()), 2)+ self.assertIs(self.peer(CT)["way_back"], False)++ def test_every_link_up_says_whether_a_way_leads_to_that_machine(self):+ told = lambda: next(m["data"] for m in self.window._announce(B) if m["type"] == protocol.MSG_ARRANGEMENT)+ self.assertIs(told()["way_back"], True)+ self.window.way_boxes["edge"].setChecked(False)+ self.assertIs(told()["way_back"], False)++ def test_either_link_hands_on_way_back(self):+ heard = []+ self.window.bridge.arrangement.connect(lambda *args: heard.append(args))+ read = {"edge": "left", "set_at": 500, "by": HIGH_ID, "way_back": False}+ self.window.server._callbacks["arrangement"](C, read)+ self.window.sender.arrangement_callback(C, {**read, "set_at": 501, "way_back": True})+ self.assertEqual([args[4] for args in heard], [False, True])++ def test_a_way_with_a_share_offer_keeps_its_box_off_and_shows_the_panel(self):+ window = self.window+ window._choose_machine(CT)+ window._set_arrangement("left")+ before = self.path.read_bytes()+ window.way_boxes["edge"].setChecked(True)+ self.assertFalse(window.way_boxes["edge"].isChecked())+ self.assertEqual(self.path.read_bytes(), before)+ self.assertFalse(window.share_module.isHidden())+ self.assertIn("Bee already crosses from the left edge", window.share_sentence.text())+ self.assertTrue(window.blocked_note.isHidden())+ window._choose_machine(BT)+ self.assertTrue(window.share_module.isHidden())++ def test_ways_written_here_reach_that_machines_zones_only(self):+ window = self.window+ window._choose_machine(CT)+ window._set_arrangement("right")+ window.way_boxes["corner"].setChecked(True)+ window._set_corner("bottom_right")+ zones = {zone["kind"]: zone for zone in self.saved()["zones"] if zone["peer"] == CT}+ self.assertNotIn("off", zones["corner"])+ self.assertEqual(zones["corner"]["corner"], "bottom_right")+ self.assertEqual([zone for zone in self.saved()["zones"] if zone["peer"] == BT], [{"peer": BT, "kind": "edge"}])++ def test_the_shortcut_stays_this_pcs_own(self):+ window = self.window+ window._choose_machine(CT)+ window.way_boxes["shortcut"].setChecked(False)+ self.assertFalse(self.saved()["shortcut"])+ window._choose_machine(BT)+ self.assertFalse(window.way_boxes["shortcut"].isChecked())++ def test_a_machine_that_may_drive_this_pc_and_cannot_follow_the_way_is_named(self):+ window = self.window+ window._choose_machine(CT)+ self.assertFalse(window.missing_note.isHidden())+ self.assertIn("While Bee drives this PC, this way to Sea does nothing", window.missing_note.text())+ window._choose_machine(BT)+ self.assertTrue(window.missing_note.isHidden())++ def test_a_machine_whose_side_another_holds_is_named_in_the_share_panel(self):+ window = self.window+ window._on_arrangement(CT, "right", 500, HIGH)+ window._choose_machine(CT)+ self.assertFalse(window.share_module.isHidden())+ self.assertIn("Bee already crosses from the left edge", window.share_sentence.text())+ self.assertTrue(window.blocked_note.isHidden())+ window._choose_machine(BT)+ self.assertTrue(window.share_module.isHidden())++ def test_a_machine_that_said_no_way_leads_back_is_named_until_it_says_one_does(self):+ window = self.window+ self.assertTrue(window.no_way_back_note.isHidden())+ window._on_arrangement(BT, "right", 50, HIGH, False)+ self.assertFalse(window.no_way_back_note.isHidden())+ self.assertIn("Bee has no way back to this machine", window.no_way_back_note.text())+ window._on_arrangement(BT, "right", 50, HIGH, True)+ self.assertTrue(window.no_way_back_note.isHidden())++ def test_an_arrangement_names_the_machine_holding_the_way_back_side(self):+ window = self.window+ window._choose_machine(CT)+ window._on_arrangement(CT, "right", 500, HIGH, False, BT)+ sea = next(item for item in app_config.load_settings(self.path)["peers"] if item["id"] == CT)+ self.assertEqual(sea["way_back_by"], BT)+ self.assertIn("Bee on its right too", window.no_way_back_note.text())++ def test_an_arrangement_from_the_machine_not_shown_moves_only_its_side(self):+ window = self.window+ window._on_arrangement(CT, "left", 500, HIGH)+ self.assertEqual(window.edge_choice.value, "left")+ window._choose_machine(CT)+ self.assertEqual(window.edge_choice.value, "right")++ def test_the_diagram_draws_every_machine(self):+ window = self.window+ window._choose_machine(CT)+ window._set_arrangement("right")+ drawn = {machine["label"]: machine for machine in window.arrangement_diagram._machines}+ self.assertEqual((drawn["Bee"]["side"], drawn["Sea"]["side"]), ("left", "right"))+ self.assertTrue(drawn["Sea"]["chosen"])+ self.assertFalse(drawn["Bee"]["chosen"])+ self.assertIn("Bee is to the left of this PC", window.arrangement_diagram.accessibleDescription())++ def test_pause_counts_every_machines_zones(self):+ window = self.window+ window._choose_machine(BT)+ window.way_boxes["edge"].setChecked(False)+ self.assertFalse(window._crossing_state_args()[4])+ window._choose_machine(CT)+ window._set_arrangement("right")+ window.way_boxes["edge"].setChecked(True)+ self.assertTrue(window._crossing_state_args()[4])++ def test_the_same_switch_reaches_every_machine(self):+ self.assertEqual(self.window.same_switch.text(), "Same on all machines")+++class OneMachineTests(WindowTests):+ PEERS = [harness.entry(B, "Bee", side="left")]++ def test_one_machine_has_no_choice_and_the_page_reads_as_before(self):+ window = self.window+ self.assertTrue(window.machine_row.isHidden())+ self.assertEqual(window.edge_heading.text(), "Where the other machine is")+ self.assertEqual(window.edge_choice.value, "left")+ self.assertTrue(window.way_boxes["edge"].isChecked())++ def test_the_tray_has_no_item_per_machine_and_the_button_names_it(self):+ window = self.window+ self.assertEqual(window.machine_actions, {})+ self.assertEqual(window.redirect_action.text(), "Send input to Bee")+ self.assertTrue(window.redirect_action.isVisible())+++class TrayTests(WindowTests):+ def test_each_machine_this_pc_sends_to_has_its_own_tray_item(self):+ window = self.window+ self.assertEqual([action.text() for action in window.machine_actions.values()],+ ["Send input to Bee", "Send input to Sea"])+ went = []+ window.sender.go = lambda peer, *args: went.append(peer) or True+ window.machine_actions[CT].trigger()+ self.assertEqual(went, [C])+ self.assertFalse(window.redirect_action.isVisible())++ def test_the_send_button_names_the_machine_the_shortcut_would_pick(self):+ window = self.window+ window.sender.shortcut_target = lambda: C+ window._refresh_window()+ self.assertEqual(window.redirect_button.text(), "Send input to Sea")++[email protected](kvm_bridge_win is None, "needs PySide6")+class DiagramWidgetTests(unittest.TestCase):+ def setUp(self):+ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ self.app = QApplication.instance() or QApplication([])++ def machine(self, key, label, side, methods=(), chosen=False, parts=("middle",)):+ return {"key": key, "label": label, "side": side, "methods": list(methods), "parts": list(parts),+ "corner": "top_left", "chosen": chosen}++ def test_each_machines_marks_are_its_own_and_the_unplaced_are_named_underneath(self):+ picture = diagram.ArrangementDiagram()+ picture.resize(500, picture.height())+ picture.set_machines([self.machine("b", "Bee", "left", ["edge"], chosen=True),+ self.machine("c", "Sea", "right", ["part"], parts=["end"]),+ self.machine("d", "Dee", "")], "Right Ctrl", "hold", True)+ self.assertEqual(picture._marks[("edge", "b", "left")], 1.0)+ self.assertEqual(picture._marks[("part", "c", "right", "end")], 1.0)+ self.assertEqual(picture._marks[("part", "c", "right", "start")], 0.0)+ self.assertEqual(picture._unplaced, "Not placed yet: Dee")+ self.assertFalse(picture.grab().isNull())++ def test_one_machine_with_no_side_is_drawn_on_the_right_but_no_edge_lights_until_a_side_is_held(self):+ # This PC's engine crosses no edge for a machine with no side, as the page's Not learned yet says.+ picture = diagram.ArrangementDiagram()+ picture.set_machines([self.machine("b", "Bee", "", ["edge", "part"], chosen=True)], "Right Ctrl", "hold", False)+ self.assertEqual(picture._unplaced, "")+ self.assertEqual(diagram._drawn_side({"side": ""}, True), "right")+ self.assertEqual(picture._marks[("edge", "b", "right")], 0.0)+ self.assertEqual(picture._marks[("track", "b", "right")], 0.0)+ self.assertEqual(picture._marks[("part", "b", "right", "middle")], 0.0)+ picture.set_machines([self.machine("b", "Bee", "right", ["edge"], chosen=True)], "Right Ctrl", "hold", False)+ self.assertEqual(picture._marks[("edge", "b", "right")], 1.0)+++if __name__ == "__main__":+ unittest.main()diff --cc win_app/tests/test_settings_layout_acceptance.pyindex 0e08b3e,0000000..28a7c1amode 100644,000000..100644--- a/win_app/tests/test_settings_layout_acceptance.py+++ b/win_app/tests/test_settings_layout_acceptance.py@@@ -1,531 -1,0 +1,547 @@@+"""Settings layout acceptance checks, rendered offscreen with Beamer's actual font."""++from __future__ import annotations++import json+import os+import re+import subprocess+import sys+import tempfile+import unittest+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")+ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "win_app"))++from PySide6.QtCore import QCoreApplication, QEvent, QObject, QPoint, QRect, Qt+from PySide6.QtTest import QTest- from PySide6.QtWidgets import (QApplication, QAbstractButton, QComboBox, QFrame, QLabel, QPushButton, QStyle,++from PySide6.QtWidgets import (QApplication, QAbstractButton, QComboBox, QFrame, QLabel, QLayout, QPushButton, QStyle,+ QStyleOptionButton, QWidget)++import kvm_bridge_win as kvm+import pages_win+import theme+import widgets+import app_config+from core import protocol+from core.tests import responder_harness+++WIDTHS = (320, 426, 512, 640, 720, 900, 1100, 1440, 1920)+SCALES = ("1.0", "1.25", "1.5", "2.0")+RENDER_WIDTHS = (320, 640, 900, 1440, 1920)+PAGE_KEYS = tuple(key for key, _name, _purpose in pages_win.PAGES)+++class NullSignal:+ def connect(self, _callback):+ pass+++class NullAction:+ def __init__(self, text=""):+ self._text = text+ self.triggered = NullSignal()++ def text(self):+ return self._text++ def setText(self, text):+ self._text = text++ def setEnabled(self, _enabled):+ pass++ def setVisible(self, _visible):+ pass++ def setChecked(self, _checked):+ pass++ def isChecked(self):+ return False++ def setCheckable(self, _checkable):+ pass++ def deleteLater(self):+ pass+++class NullMenu(QObject):+ def removeAction(self, _action):+ pass++ def insertAction(self, _before, _action):+ pass+++class NullTray:+ def setToolTip(self, _text):+ pass++ def setIcon(self, _icon):+ pass++ def hide(self):+ pass++ def show(self):+ pass++ def showMessage(self, *_args):+ pass+++class SyntheticWindow(kvm.WindowsApplication):+ def _listen(self):+ pass++ def _start_sending(self, _config):+ pass++ def _start_receiver(self, _config):+ pass++ def _build_tray(self):+ self.tray = NullTray()+ for name in ("header_action", "open_action", "status_action", "redirect_action",+ "pause_action", "drive_action", "send_action"):+ setattr(self, name, NullAction())+ self.tray_menu = NullMenu(self)+++def write_synthetic_settings(folder):+ settings = app_config.migrate(None, machine_id=protocol.id_text(responder_harness.HERE))+ settings.update(port=responder_harness.free_port(), appearance="dark", shortcut_arrival=True,+ check_updates=False)+ first = protocol.id_text(responder_harness.B)+ settings["peers"] = [+ responder_harness.entry(responder_harness.B, "Synthetic workstation with a long machine name", side="right"),+ responder_harness.entry(responder_harness.C, "Synthetic laptop", side="left"),+ ]+ settings["zones"] = [+ {"peer": first, "kind": "part", "parts": ["start", "middle", "end"]},+ {"peer": first, "kind": "corner", "corner": "top_right", "edge": "right"},+ ]+ path = folder / "settings.json"+ app_config.write_settings(path, settings)+ return path+++class SettingsLayoutAcceptance(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.app = QApplication.instance() or QApplication([])+ theme.init_fonts()+ cls.app.setFont(theme.font(theme.TYPE["body"]))+ cls.effective_font = cls.app.font()++ def setUp(self):+ self.assertTrue(self.effective_font.family().lower().startswith("hanken"),+ f"tests must use the bundled Hanken Grotesk font, got {self.effective_font.family()!r}")+ scratch = ROOT / "renders" / "test-working"+ scratch.mkdir(parents=True, exist_ok=True)+ self.folder = tempfile.TemporaryDirectory(prefix="beamer-layout-acceptance-", dir=scratch)+ folder = Path(self.folder.name)+ self.window = SyntheticWindow(write_synthetic_settings(folder))+ self.window.full_screen_timer.stop()+ self.window.refresh_timer.stop()+ self.window.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen, True)+ self.window.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)+ self.window._select_page(PAGE_KEYS[0])+ self.window.show()+ self.settle()++ def tearDown(self):+ self.window.server.stop()+ self.window.close()+ self.window.deleteLater()+ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)+ self.app.processEvents()+ self.folder.cleanup()++ def settle(self):+ for _ in range(7):+ QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)+ QCoreApplication.sendPostedEvents(None, QEvent.Type.LayoutRequest)+ self.app.processEvents()++ def set_size(self, width, height=900):+ self.window.resize(width, height)+ self.settle()++ def page_scroll(self, key):+ self.window._select_page(key)+ self.settle()+ return self.window.stack.currentWidget()++ def test_window_accepts_320_dip_minimum_at_every_matrix_cell(self):+ width = int(os.environ.get("BEAMER_LAYOUT_WIDTH", "320"))+ self.set_size(width, 300)+ self.assertEqual(self.window.width(), width,+ f"requested {width} DIP but window settled at {self.window.width()} DIP")+ self.assertEqual(self.window.height(), 300,+ f"requested 300 DIP but window settled at {self.window.height()} DIP")+ self.assertLessEqual(self.window.minimumWidth(), 320)+ self.assertLessEqual(self.window.minimumHeight(), 300)+ expected_sidebar = 56 if width < 640 else 144 if width < 800 else 176+ self.assertEqual(self.window.sidebar.width(), expected_sidebar)+ if width < 640:+ for key, button in self.window.sidebar._buttons.items():+ with self.subTest(page=key):+ self.assertEqual((button.width(), button.height()), (44, 36))+ self.assertAlmostEqual(button.x() + button.width() / 2,+ self.window.sidebar.width() / 2, delta=1)+ self.assertTrue(button.toolTip(), f"{key} lost its accessible page-name tooltip")++ def test_follow_banner_keeps_whole_words_and_stop_following_its_natural_size(self):+ self.page_scroll("design")+ self.window._lock_followed_design({"id": "b" * 32}, "Windows workstation")+ label, button = self.window.follow_banner_label, self.window.stop_follow_button+ words = label.text().split()+ for width in WIDTHS:+ with self.subTest(width=width):+ self.set_size(width)+ self.assertTrue(self.window.follow_banner.isVisible())+ widest = max(label.fontMetrics().horizontalAdvance(word) for word in words)+ self.assertGreaterEqual(label.width(), widest, "a banner word is wider than its column")+ self.assertGreaterEqual(label.height(), label.heightForWidth(label.width()))+ natural = button.sizeHint()+ self.assertEqual(button.width(), natural.width(), "Stop following lost its natural width")+ self.assertGreaterEqual(button.height(), natural.height())+ self.assertTrue(self.paints_on_one_line(button), "Stop following wraps or truncates its label")++ @classmethod+ def paints_on_one_line(cls, button):+ """ActionButton paints its label word-wrapped into the content rectangle, so the label has+ to leave slack there; a plain QPushButton never wraps and only has to fit."""+ metrics = button.fontMetrics()+ room = cls.button_text_room(button)+ if not isinstance(button, widgets.ActionButton):+ return metrics.horizontalAdvance(button.text()) <= room+ drawn = metrics.boundingRect(QRect(0, 0, room, 10000), int(Qt.TextFlag.TextWordWrap), button.text())+ return drawn.height() <= metrics.height() + 1 and metrics.horizontalAdvance(button.text()) < room++ @staticmethod+ def button_text_room(button):+ option = QStyleOptionButton()+ button.initStyleOption(option)+ return button.style().subElementRect(QStyle.SubElement.SE_PushButtonContents, option, button).width()++ def test_no_button_label_wraps_or_clips_on_any_page(self):+ for width in WIDTHS:+ self.set_size(width)+ for key in PAGE_KEYS:+ scroll = self.page_scroll(key)+ for button in scroll.widget().findChildren(QPushButton):+ text = button.text()+ if (not text or not button.isVisibleTo(scroll.widget()) or isinstance(button, widgets._Swatch)+ or button.property("vernier") in ("page", "foot", "choice")):+ continue+ with self.subTest(width=width, page=key, button=text):+ self.assertTrue(self.paints_on_one_line(button), "the label wraps or clips inside its button")+ self.assertGreaterEqual(button.height(), 30)+++ def test_no_wrapping_label_is_a_horizontally_aligned_layout_item(self):++ # An aligned layout item gets its size hint's width, about 20 average characters for a++ # wrapping label, while its box reserved height for the full width: the text wraps where++ # the box has no room for the second line, on some fonts only (the Shortcut box on the rig).++ horizontal = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignHCenter++ for key in PAGE_KEYS:++ page = self.page_scroll(key).widget()++ for layout in page.findChildren(QLayout):++ for index in range(layout.count()):++ item = layout.itemAt(index)++ label = item.widget()++ if not isinstance(label, QLabel) or not label.wordWrap():++ continue++ with self.subTest(page=key, label=label.text()[:40]):++ self.assertFalse(item.alignment() & horizontal, "align the label's text, not its layout item")+++ def test_effective_dpr_matches_the_scale_of_this_process(self):+ expected = float(os.environ.get("QT_SCALE_FACTOR", "1.0"))+ self.assertAlmostEqual(self.window.devicePixelRatioF(), expected, delta=0.01,+ msg="Qt must apply the requested DPR once while geometry stays in DIP")++ def test_every_page_uses_the_same_centred_880_dip_section_column(self):+ width = int(os.environ.get("BEAMER_LAYOUT_WIDTH", "320"))+ self.set_size(width)+ measurements = {}+ for key in PAGE_KEYS:+ scroll = self.page_scroll(key)+ page = scroll.widget()+ modules = [module for module in page.findChildren(QFrame)+ if module.property("vernier") == "module" and module.isVisible()]+ column = page.findChild(QWidget, "page_column")+ self.assertIsNotNone(column, f"{key} has no page column")+ self.assertGreater(len(modules), 0, f"{key} has no settings sections")+ rects = [(module.mapTo(page, QPoint()).x(), module.width()) for module in modules]+ measurements[key] = rects+ expected = min(880, page.width() - 48)+ self.assertAlmostEqual(column.width(), expected, delta=1,+ msg=f"{key} column {column.width()} vs {expected} at {width} DIP")+ self.assertAlmostEqual(column.x(), (page.width() - expected) / 2, delta=1,+ msg=f"{key} column is not centred: {column.geometry().getRect()}")+ for x, module_width in rects:+ self.assertAlmostEqual(x, column.x(), delta=1,+ msg=f"{key} section leading edge {x}; column {column.x()}")+ self.assertAlmostEqual(module_width, column.width(), delta=1,+ msg=f"{key} section width {module_width}; column {column.width()}")+ self.assertLessEqual(page.width(), scroll.viewport().width() + 1,+ f"{key} document width {page.width()} exceeds viewport {scroll.viewport().width()}")++ def test_form_labels_keep_a_180_dip_track_without_wrapping_in_normal_windows(self):+ self.assertEqual(self.window.edge_heading.text(), "Where the other machine is")+ self.assertIn("Synthetic workstation", self.window.edge_heading.accessibleName())+ self.set_size(int(os.environ.get("BEAMER_LAYOUT_WIDTH", "900")))+ for key in PAGE_KEYS:+ scroll = self.page_scroll(key)+ column = scroll.widget().findChild(QWidget, "page_column")+ if column.width() <= 560:+ continue+ labels = [label for label in column.findChildren(QLabel)+ if label.property("form_label") or label.objectName() == "form_label"]+ for label in labels:+ if not label.isVisible():+ continue+ with self.subTest(page=key, label=label.text()):+ self.assertLessEqual(label.width(), 180)+ self.assertLessEqual(label.height(), label.fontMetrics().height() + 2,+ f"form label wraps: {label.text()!r}")+ self.assertLessEqual(label.fontMetrics().horizontalAdvance(label.text()), label.width(),+ f"form label is clipped: {label.text()!r}")++ def test_segmented_controls_and_menu_controls_obey_their_caps(self):+ self.set_size(int(os.environ.get("BEAMER_LAYOUT_WIDTH", "900")))+ for key in PAGE_KEYS:+ column = self.page_scroll(key).widget().findChild(QWidget, "page_column")+ for control in column.findChildren(QWidget):+ if control.property("segmented_choice") or control.objectName() == "segmented_choice":+ cap = int(control.property("segment_cap") or 360)+ with self.subTest(page=key, control=control.objectName()):+ self.assertLessEqual(control.width(), cap)+ for segment in control.findChildren(QAbstractButton):+ self.assertLessEqual(segment.width(), control.cell_width())+ self.assertGreaterEqual(segment.height(), segment.heightForWidth(segment.width()))+ for menu in column.findChildren(QComboBox):+ with self.subTest(page=key, menu=menu.objectName()):+ self.assertLessEqual(menu.width(), 320)++ def test_form_controls_never_overlap_their_labels_and_children_fit_the_column(self):+ self.set_size(int(os.environ.get("BEAMER_LAYOUT_WIDTH", "900")))+ for key in PAGE_KEYS:+ column = self.page_scroll(key).widget().findChild(QWidget, "page_column")+ for row in column.findChildren(widgets.FormRow):+ if not row.isVisible():+ continue+ point = row.holder.mapTo(row, QPoint())+ with self.subTest(page=key, label=row.heading.text()):+ if column.width() >= 560:+ self.assertEqual(row.heading.width(), 180)+ self.assertGreaterEqual(point.x(), row.heading.x() + row.heading.width() + 16)+ else:+ self.assertGreaterEqual(point.y(), row.heading.y() + row.heading.height() + 8)+ for child in column.findChildren(QWidget):+ if child.isVisible():+ x = child.mapTo(column, QPoint()).x()+ with self.subTest(page=key, child=type(child).__name__):+ self.assertGreaterEqual(x, 0)+ self.assertLessEqual(x + child.width(), column.width() + 1)++ def test_each_style_family_stays_horizontal_and_reflows_as_a_group(self):+ width = int(os.environ.get("BEAMER_LAYOUT_WIDTH", "320"))+ self.set_size(width)+ self.page_scroll("design")+ groups = self.window.glow_style_choice.groups+ column_width = self.page_scroll("design").widget().findChild(QWidget, "page_column").width()+ per_row = 3 if column_width >= 600 else 2 if column_width >= 400 else 1+ for family, choices in groups.items():+ tiles = list(choices._tiles.values())+ self.assertEqual(len(tiles), 3, f"{family} lost catalogue choices")+ positions = sorted((tile.y(), tile.x()) for tile in tiles)+ rows = {}+ for tile in tiles:+ rows.setdefault(tile.y(), []).append(tile)+ self.assertEqual(max(map(len, rows.values())), per_row,+ f"{family}: expected at most {per_row} choices per row, got {positions}")+ for row in rows.values():+ self.assertLessEqual(max(tile.width() for tile in row) - min(tile.width() for tile in row), 1)+ self.assertEqual(len({tile.height() for tile in row}), 1)+ self.assertLessEqual(max(tile.width() for tile in tiles) - min(tile.width() for tile in tiles), 1)++ def test_colour_families_are_five_three_or_two_cells_per_row(self):+ width = int(os.environ.get("BEAMER_LAYOUT_WIDTH", "320"))+ self.set_size(width)+ self.page_scroll("design")+ view = self.window.glow_colour_choice.view+ column_width = self.page_scroll("design").widget().findChild(QWidget, "page_column").width()+ per_row = 5 if column_width >= 600 else 3 if column_width >= 400 else 2+ swatches = list(self.window.glow_colour_choice._swatches.values())+ by_y = {}+ for swatch in swatches:+ by_y.setdefault(swatch.mapTo(view, QPoint()).y(), []).append(swatch)+ self.assertEqual(max(map(len, by_y.values())), per_row,+ f"expected {per_row} colour choices per row; rows={[len(r) for r in by_y.values()]}")+ for row in by_y.values():+ self.assertLessEqual(max(cell.width() for cell in row) - min(cell.width() for cell in row), 1)+ self.assertEqual(len({cell.height() for cell in row}), 1)+ mono_choices = [value for value in self.window.glow_colour_choice._swatches+ if value.startswith("mono")]+ self.assertEqual(len(mono_choices), 5, "Mono must be a full five-colour family")++ def test_design_controls_stay_inside_their_logical_width_caps(self):+ self.set_size(int(os.environ.get("BEAMER_LAYOUT_WIDTH", "900")))+ self.page_scroll("design")+ capped = {+ "Length": (self.window.length_choice.view, self.window.length_choice.view.cap),+ "Size": (self.window.size_choice.view, self.window.size_choice.view.cap),+ "Style for": (self.window.design_mode_choice.view, self.window.design_mode_choice.view.cap),+ "Show at": (self.window.effect_method_choice.view, self.window.effect_method_choice.view.cap),+ "Match design with": (self.window.design_follow_choice, 320),+ }+ for label, (control, maximum) in capped.items():+ with self.subTest(control=label):+ self.assertLessEqual(control.width(), maximum,+ f"{label} is {control.width()} DIP; cap is {maximum}")+ for control_name in ("length_choice", "size_choice", "design_mode_choice", "effect_method_choice"):+ choice = getattr(self.window, control_name)+ for value, button in choice._buttons.items():+ with self.subTest(choice=control_name, option=value):+ self.assertLessEqual(button.width(), choice.view.cell_width(),+ f"{control_name}.{value} segment exceeds its measured label width")+ self.assertLessEqual(self.window.design_follow_choice.width(), 320)++ def test_effect_preview_cache_uses_ceil_logical_size_at_effective_dpr(self):+ scale = float(os.environ.get("QT_SCALE_FACTOR", "1.0"))+ self.set_size(int(os.environ.get("BEAMER_LAYOUT_WIDTH", "900")))+ self.page_scroll("design")+ preview = self.window.effect_stills["glow"]+ preview.grab()+ self.assertIsNotNone(preview._image, "preview still was not rasterised")+ image = preview._image+ self.assertEqual(image.devicePixelRatio(), scale)+ self.assertGreaterEqual(image.width(), __import__("math").ceil(preview.width() * scale))+ self.assertGreaterEqual(image.height(), __import__("math").ceil(preview.height() * scale))++ def test_selected_style_detail_and_length_size_stay_with_style_group(self):+ self.set_size(int(os.environ.get("BEAMER_LAYOUT_WIDTH", "900")))+ self.page_scroll("design")+ style_module = self.window.look_module+ module_top = style_module.mapTo(self.window.stack.currentWidget().widget(), QPoint()).y()+ family_bottom = max(self.window.glow_style_choice.tile(value).mapTo(+ self.window.stack.currentWidget().widget(), QPoint()).y() ++ self.window.glow_style_choice.tile(value).height()+ for choices in self.window.glow_style_choice.groups.values()+ for value in choices._tiles)+ for widget in (self.window.effect_name, self.window.effect_note,+ self.window.length_choice.view, self.window.size_choice.view):+ y = widget.mapTo(self.window.stack.currentWidget().widget(), QPoint()).y()+ self.assertGreaterEqual(y, family_bottom,+ f"{widget.objectName() or type(widget).__name__} precedes style rows")+ self.assertGreaterEqual(y, module_top)++ def test_sidebar_selection_tracks_keyboard_focus_and_mouse_click(self):+ self.set_size(int(os.environ.get("BEAMER_LAYOUT_WIDTH", "900")))+ sidebar = self.window.sidebar+ selected = [key for key, button in sidebar._buttons.items() if button.isChecked()]+ self.assertEqual(selected, [self.window._page], "selected sidebar page must match displayed page")+ focused = [key for key, button in sidebar._buttons.items() if button.hasFocus()]+ self.assertTrue(not focused or focused == selected,+ f"focus must be absent or belong to selected page; got {focused}, selected {selected}")+ target = PAGE_KEYS[-1]+ QTest.mouseClick(sidebar._buttons[target], Qt.MouseButton.LeftButton)+ self.settle()+ selected = [key for key, button in sidebar._buttons.items() if button.isChecked()]+ self.assertEqual(selected, [target])+ focused = [key for key, button in sidebar._buttons.items() if button.hasFocus()]+ self.assertNotIn(target, focused, "pointer selection must not leave a keyboard focus ring")+ QApplication.setActiveWindow(self.window)+ QTest.keyClick(sidebar._buttons[target], Qt.Key.Key_Up)+ self.settle()+ current = PAGE_KEYS[PAGE_KEYS.index(target) - 1]+ selected = [key for key, button in sidebar._buttons.items() if button.isChecked()]+ focused = [key for key, button in sidebar._buttons.items() if button.hasFocus()]+ self.assertEqual(selected, [current], "arrow navigation must switch selected page immediately")+ self.assertEqual(focused, [current], "keyboard focus must follow the selected page")+ QCoreApplication.sendEvent(self.window, QEvent(QEvent.Type.WindowActivate))+ self.settle()+ selected = [key for key, button in sidebar._buttons.items() if button.isChecked()]+ self.assertEqual(selected, [current], "window activation must leave one selected page")++ def test_selected_tile_has_a_separate_keyboard_ring_that_pointer_input_clears(self):+ self.set_size(900)+ self.page_scroll("design")+ tile = self.window.glow_style_choice.tile("glow")+ QApplication.setActiveWindow(self.window)+ tile.setFocus(Qt.FocusReason.TabFocusReason)+ self.window.sidebar.keyboard_mode = False+ self.window.sidebar._update_rings()+ self.settle()++ def ink_at_focus_edge():+ image = tile.grab().toImage()+ dpr = image.devicePixelRatio()+ return image.pixelColor(image.width() // 2, round(5 * dpr)).lightness()++ pointer_ink = ink_at_focus_edge()+ QTest.keyClick(tile, Qt.Key.Key_Shift)+ self.settle()+ self.assertEqual(ink_at_focus_edge(), pointer_ink, "only Tab, Shift-Tab and the arrows show rings")+ QTest.keyClick(tile, Qt.Key.Key_Tab)+ QTest.keyClick(QApplication.focusWidget(), Qt.Key.Key_Backtab)+ self.settle()+ self.assertIs(QApplication.focusWidget(), tile)+ self.assertTrue(tile.isChecked())+ self.assertGreater(ink_at_focus_edge(), pointer_ink + 40)+ QTest.mouseClick(self.window.footer_note, Qt.MouseButton.LeftButton)+ self.settle()+ self.assertEqual(ink_at_focus_edge(), pointer_ink)+++if __name__ == "__main__":+ if len(sys.argv) == 2 and sys.argv[1] == "--matrix":+ log_root = ROOT / "renders" / "acceptance-matrix"+ log_root.mkdir(parents=True, exist_ok=True)++ def run_cell(cell):+ width, scale = cell+ env = os.environ.copy()+ env["QT_QPA_PLATFORM"] = "offscreen"+ env["QT_SCALE_FACTOR"] = scale+ env["BEAMER_LAYOUT_WIDTH"] = str(width)+ log_path = log_root / f"width-{width}-scale-{scale}.log"+ with log_path.open("w", encoding="utf-8") as log:+ result = subprocess.run(+ [sys.executable, str(Path(__file__).resolve()), "--case"],+ env=env, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, text=True,+ )+ output = log_path.read_text(encoding="utf-8", errors="replace")+ count = int(re.search(r"Ran (\d+) tests?", output).group(1)) if re.search(+ r"Ran (\d+) tests?", output) else 0+ failed = re.search(r"FAILED \(([^)]*)\)", output)+ failure_count = sum(int(value) for value in re.findall(+ r"(?:failures|errors)=(\d+)", failed.group(1))) if failed else 0+ return {"cell": cell, "returncode": result.returncode, "tests": count,+ "failures": failure_count, "log": log_path}++ cells = [(width, scale) for width in WIDTHS for scale in SCALES]+ with ThreadPoolExecutor(max_workers=4) as workers:+ results = list(workers.map(run_cell, cells))+ failures = [result for result in results if result["returncode"]]+ print(f"acceptance matrix: cells={len(results)} passed={len(results) - len(failures)} "+ f"failed={len(failures)} tests={sum(result['tests'] for result in results)} "+ f"assertion-failures={sum(result['failures'] for result in results)} "+ f"logs={log_root}")+ if failures:+ print("failed cells: " + ", ".join(+ f"{r['cell'][0]}@{r['cell'][1]}x" for r in failures), file=sys.stderr)+ raise SystemExit(1)+ elif len(sys.argv) == 2 and sys.argv[1] == "--case":+ unittest.main(argv=[sys.argv[0]])+ else:+ unittest.main()diff --cc win_app/widgets.pyindex b1491d3,b5fd4dc..99a2f6e--- a/win_app/widgets.py+++ b/win_app/widgets.py@@@ -325,173 -77,6 +325,176 @@@ class Module(QFrame)self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred)+class ActionButton(QPushButton):+ """An intrinsic action whose full label remains readable in a narrow column."""++ def __init__(self, text="", parent=None):+ super().__init__(text, parent)+ self.setMaximumWidth(240)+ self.setMinimumHeight(30)+ policy = QSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Preferred)+ policy.setHeightForWidth(True)+ self.setSizePolicy(policy)++ def _chrome(self):+ """Width the style adds round the label (border and the stylesheet's padding, which differs+ per `vernier` kind). A fixed 24 ignored the 2 px border, so the label was measured 2 px short+ of the room it painted in and wrapped inside a 30 px button."""+ option = QStyleOptionButton()+ self.initStyleOption(option)+ grown = self.style().sizeFromContents(QStyle.ContentsType.CT_PushButton, option, QSize(100, 20), self)+ return grown.width() - 100++ def heightForWidth(self, width):+ width = min(width, self.maximumWidth())+ room = max(1, width - self._chrome())+ metrics = self.fontMetrics()+ if metrics.horizontalAdvance(self.text()) < room:+ # boundingRect wraps a label that exactly fills its room, so a button at its own+ # sizeHint asked for two lines.+ return max(30, metrics.height() + 12)+ bounds = metrics.boundingRect(QRect(0, 0, room, 10000), int(Qt.TextFlag.TextWordWrap), self.text())+ return max(30, bounds.height() + 12)++ def sizeHint(self):+ width = min(240, max(64, self.fontMetrics().horizontalAdvance(self.text()) + self._chrome() + 2))+ return QSize(width, self.heightForWidth(width))++ def minimumSizeHint(self):+ return QSize(0, 30)++ def displayed_text(self):+ return self.text()++ def paintEvent(self, event):+ painter = QStylePainter(self)+ option = QStyleOptionButton()+ self.initStyleOption(option)+ option.text = ""+ painter.drawControl(QStyle.ControlElement.CE_PushButton, option)+ content = self.style().subElementRect(QStyle.SubElement.SE_PushButtonContents, option, self)+ if self.property("vernier") == "choice" and self.isChecked() and self.isEnabled():+ painter.setPen(QColor(tokens.PALETTE["ground"]))+ elif self.property("vernier") in ("primary", "live") and self.isEnabled():+ painter.setPen(QColor(theme.colour("ground")))+ else:+ painter.setPen(option.palette.color(QPalette.ColorRole.ButtonText))+ painter.drawText(content, Qt.AlignmentFlag.AlignCenter | Qt.TextFlag.TextWordWrap, self.text())+++class FormRow(QWidget):+ """The shared label track stacks before it would compress a setting's control."""++ def __init__(self, heading, control, notes=(), parent=None):+ super().__init__(parent)+ self.setProperty("vernier", "plain")+ self.heading = heading+ heading.setProperty("form_label", True)+ heading.setWordWrap(False)+ heading.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred)+ self._box = QBoxLayout(QBoxLayout.Direction.TopToBottom, self)+ self._box.setContentsMargins(0, 0, 0, 0)+ self._box.setSpacing(8)+ self._box.addWidget(heading, 0, Qt.AlignmentFlag.AlignTop)+ holder = QWidget()+ self.holder = holder+ holder.setProperty("vernier", "plain")+ column = QVBoxLayout(holder)+ column.setContentsMargins(0, 0, 0, 0)+ column.setSpacing(8)- column.addWidget(control, 0, Qt.AlignmentFlag.AlignLeft)++ # A wrapping label as an aligned item would get its size hint's width, narrower than the++ # height the row reserved for it (InputRecorder's hint); its text is left-aligned anyway.++ wraps = isinstance(control, QLabel) and control.wordWrap()++ column.addWidget(control, 0, Qt.AlignmentFlag(0) if wraps else Qt.AlignmentFlag.AlignLeft)+ for note in notes:+ column.addWidget(note)+ self._box.addWidget(holder, 1)+ self._inline = None++ def resizeEvent(self, event):+ super().resizeEvent(event)+ inline = self.width() + 32 >= 560+ if inline != self._inline:+ self._inline = inline+ self._box.setDirection(QBoxLayout.Direction.LeftToRight if inline else QBoxLayout.Direction.TopToBottom)+ self._box.setSpacing(16 if inline else 8)+ self.heading.setMinimumWidth(180 if inline else 0)+ self.heading.setMaximumWidth(180 if inline else 16777215)+++class _SegmentedView(QWidget):+ def __init__(self, parent=None):+ super().__init__(parent)+ self.setProperty("vernier", "plain")+ self.setProperty("segmented_choice", True)+ self.buttons = []+ self.cap = 360+ self.required = 0+ self.columns = 0+ self.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Preferred)+ policy = self.sizePolicy()+ policy.setHeightForWidth(True)+ self.setSizePolicy(policy)++ def set_cap(self, width):+ self.cap = width+ self.setProperty("segment_cap", width)+ self.setMaximumWidth(width)+ self.updateGeometry()++ def _horizontal(self, width):+ return width >= self.required++ def cell_width(self):+ widths = []+ for button in self.buttons:+ for weight in (400, 600):+ metrics = QFontMetrics(theme.font(theme.TYPE["small"], weight))+ widths.append(max(metrics.horizontalAdvance(button.text()),+ metrics.boundingRect(button.text()).width()) + 24)+ return max(widths, default=0)++ def refresh_metrics(self):+ self.required = self.cell_width() * len(self.buttons) + 4 * max(0, len(self.buttons) - 1)+ columns = self.columns or len(self.buttons)+ self.set_cap(self.cell_width() * columns + 4 * max(0, columns - 1))++ def row_columns(self, width):+ columns = self.columns or max(1, len(self.buttons))+ return columns if width >= self.cell_width() * columns + 4 * max(0, columns - 1) else 1++ def heightForWidth(self, width):+ if not self.buttons:+ return 0+ width = min(width, self.cap)+ columns = self.row_columns(width)+ segment_width = min(self.cell_width(), max(1, (width - 4 * (columns - 1)) // columns))+ height = max(button.heightForWidth(segment_width) for button in self.buttons)+ rows = (len(self.buttons) + columns - 1) // columns+ return rows * height + 4 * (rows - 1)++ def sizeHint(self):+ return QSize(self.cap, self.heightForWidth(self.cap))++ def minimumSizeHint(self):+ return QSize(0, 30 if self.buttons else 0)++ def resizeEvent(self, event):+ super().resizeEvent(event)+ # The machine choice is empty with fewer than two machines. An exception raised+ # here during a layout pass segfaults PySide6 6.11 at the next Python override.+ if not self.buttons:+ return+ columns = self.row_columns(self.width())+ segment_width = min(self.cell_width(), max(1, (self.width() - 4 * (columns - 1)) // columns))+ row_height = max((button.heightForWidth(segment_width) for button in self.buttons), default=30)+ for index, button in enumerate(self.buttons):+ col, row = index % columns, index // columns+ left = round(col * (self.width() + 4) / columns)+ right = round((col + 1) * (self.width() + 4) / columns) - 4+ button.setGeometry(left, row * (row_height + 4), min(self.cell_width(), right - left), row_height)++class Led(QWidget):def __init__(self, tone: str = "off", parent: QWidget | None = None) -> None:super().__init__(parent)@@@ -1104,28 -483,19 +1107,35 @@@ class InputRecorder(ActionButton)self.setProperty("vernier", "keycap")self.setCursor(Qt.CursorShape.PointingHandCursor)self.setAccessibleName(self._spoken(title))- self.setFixedHeight(42 if mono else 36)- row = QHBoxLayout(self)- row.setContentsMargins(12, 0, 12, 0)+ self.setMaximumWidth(16777215)+ self.setMinimumHeight(42 if mono else 36)+ row = QBoxLayout(QBoxLayout.Direction.TopToBottom, self)+ self._content = row- row.setContentsMargins(12, 0, 12, 0)++ # Vertical margins matter: a layout-owning widget is sized from its layout's own height for++ # width, not from heightForWidth below, so with none the key sat on the top border and the++ # hint's last pixels were cut by the bottom one.++ row.setContentsMargins(12, 8, 12, 8)row.setSpacing(10)- self.key = label(title, "keycap")+ self.key = label(title, "keycap", wrap=True)self.key.setFont(theme.mono_font(tokens.TYPE["field_mono"]) if mono else theme.font(tokens.TYPE["body"]))- self.hint = label(self.HINT, "small")+ self.hint = label(self.HINT, "small", wrap=True)for part in (self.key, self.hint):part.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)row.addWidget(self.key, 1)-- row.addWidget(self.hint, 0, Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)++ # Right-aligned as text, never as a layout item: an aligned item is given its size hint's++ # width, which for a wrapping label is about 20 average characters, so "Click, then press++ # the key" wrapped there on Windows' fonts while the box had reserved one line at full width.++ self.hint.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)++ row.addWidget(self.hint)self.clicked.connect(self._toggle)+ def heightForWidth(self, width):+ room = max(1, width - 24)- return max(self.minimumHeight(), sum(item.heightForWidth(room) for item in (self.key, self.hint)) + 20)++ return max(self.minimumHeight(), sum(item.heightForWidth(room) for item in (self.key, self.hint)) + 16 + 10)++ def sizeHint(self):+ return QSize(280, self.heightForWidth(280))+def set_title(self, title: str) -> None:"""What the keycap says while it is not recording: the trigger recorder shows its key."""self.title = title